hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
list | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
list | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
list | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
list | cell_types
list | cell_type_groups
list |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a8f1af7f6fb6f0f37e6c4ac0b831c49077780c6
| 933,161 |
ipynb
|
Jupyter Notebook
|
demo.ipynb
|
thomasjpfan/dabl
|
91a170f5013115dc07770c406b15e064dc4fff89
|
[
"BSD-3-Clause"
] | null | null | null |
demo.ipynb
|
thomasjpfan/dabl
|
91a170f5013115dc07770c406b15e064dc4fff89
|
[
"BSD-3-Clause"
] | null | null | null |
demo.ipynb
|
thomasjpfan/dabl
|
91a170f5013115dc07770c406b15e064dc4fff89
|
[
"BSD-3-Clause"
] | null | null | null | 1,028.84344 | 183,056 | 0.950957 |
[
[
[
"# A quick demo of dabl on some toy datasets and slightly more interesting datasets",
"_____no_output_____"
],
[
"# Scikit-learn build-in datasets:",
"_____no_output_____"
],
[
"## Wine classification",
"_____no_output_____"
]
],
[
[
"import dabl\nfrom sklearn.datasets import load_wine\nwine_df = dabl.utils.data_df_from_bunch(load_wine())\nwine_df.head()",
"_____no_output_____"
],
[
"dabl.plot(wine_df, 'target')",
"/home/amueller/public/dabl/dabl/plot/supervised.py:538: FutureWarning: The second positional argument of plot is a Series 'y'. If passing a column name, use a keyword.\n warnings.warn(\"The second positional argument of plot is a Series 'y'.\"\n"
],
[
"# obviously LDA solved the problem as we can see in the last plot. I might just want to use LDA or another linear model.\n# Or we see what the SimpleClassifier does:\nsc = dabl.SimpleClassifier()\nsc.fit(wine_df, target_col='target')",
"Running DummyClassifier(strategy='prior')\naccuracy: 0.399 recall_macro: 0.333 precision_macro: 0.133 f1_macro: 0.190\n=== new best DummyClassifier(strategy='prior') (using recall_macro):\naccuracy: 0.399 recall_macro: 0.333 precision_macro: 0.133 f1_macro: 0.190\n\nRunning GaussianNB()\naccuracy: 0.972 recall_macro: 0.975 precision_macro: 0.971 f1_macro: 0.972\n=== new best GaussianNB() (using recall_macro):\naccuracy: 0.972 recall_macro: 0.975 precision_macro: 0.971 f1_macro: 0.972\n\nRunning MultinomialNB()\naccuracy: 0.938 recall_macro: 0.941 precision_macro: 0.952 f1_macro: 0.941\nRunning DecisionTreeClassifier(class_weight='balanced', max_depth=1)\naccuracy: 0.528 recall_macro: 0.579 precision_macro: 0.400 f1_macro: 0.456\nRunning DecisionTreeClassifier(class_weight='balanced', max_depth=5)\naccuracy: 0.932 recall_macro: 0.934 precision_macro: 0.938 f1_macro: 0.932\nRunning DecisionTreeClassifier(class_weight='balanced', min_impurity_decrease=0.01)\naccuracy: 0.960 recall_macro: 0.958 precision_macro: 0.966 f1_macro: 0.961\nRunning LogisticRegression(C=0.1, class_weight='balanced', max_iter=1000)\naccuracy: 0.983 recall_macro: 0.986 precision_macro: 0.982 f1_macro: 0.983\n=== new best LogisticRegression(C=0.1, class_weight='balanced', max_iter=1000) (using recall_macro):\naccuracy: 0.983 recall_macro: 0.986 precision_macro: 0.982 f1_macro: 0.983\n\nRunning LogisticRegression(class_weight='balanced', max_iter=1000)\naccuracy: 0.983 recall_macro: 0.984 precision_macro: 0.983 f1_macro: 0.983\n\nBest model:\nLogisticRegression(C=0.1, class_weight='balanced', max_iter=1000)\nBest Scores:\naccuracy: 0.983 recall_macro: 0.986 precision_macro: 0.982 f1_macro: 0.983\n"
],
[
"# logistic regression has slightly higher accuracy and macro-average recall (which is the main metric we use)\n# than linear discriminant analysis. Not really a shocker.\ndabl.explain(sc)",
"_____no_output_____"
]
],
[
[
"Interestingly the large coefficients don't really correspond to what's shown in the univariate or pairplots. Possibly because the data is very correlated? Who knows!\nI assume we could create a simpler model with less features from the plots above. Maybe lasso next time?",
"_____no_output_____"
],
[
"## Ames housing dataset",
"_____no_output_____"
]
],
[
[
"ames_df = dabl.datasets.load_ames()\names_df.head()",
"_____no_output_____"
],
[
"dabl.plot(ames_df, 'SalePrice')",
"/home/amueller/public/dabl/dabl/plot/supervised.py:538: FutureWarning: The second positional argument of plot is a Series 'y'. If passing a column name, use a keyword.\n warnings.warn(\"The second positional argument of plot is a Series 'y'.\"\n/home/amueller/public/dabl/dabl/preprocessing.py:343: UserWarning: Discarding near-constant features: ['Street', 'Utilities', 'Land Slope', 'Condition 2', 'Roof Matl', 'Heating', 'Low Qual Fin SF', 'Kitchen AbvGr', 'Garage Cond', '3Ssn Porch', 'Pool Area', 'Misc Val']\n warn(\"Discarding near-constant features: {}\".format(\n"
]
],
[
[
"You can see that high-ordinality categorical variables were summarized with rare categories binned into \"dabl_other\".\nAlso, ``GarageCars`` should maybe be plotted as a categorical variable - and there's a garage that will be build in 2200 (it's the outlier that's dropped). Huh.\nWe were pretty aggressive with dropping \"near-constant\" features. Maybe being less agressive might be good in some situations?\n``Overall Qual`` might also arguably be better shown as a categorical feature, though it's a bit unclear.",
"_____no_output_____"
]
],
[
[
"dabl.plot(ames_df, 'SalePrice', type_hints={'Garage Cars': 'categorical'})",
"/home/amueller/public/dabl/dabl/plot/supervised.py:538: FutureWarning: The second positional argument of plot is a Series 'y'. If passing a column name, use a keyword.\n warnings.warn(\"The second positional argument of plot is a Series 'y'.\"\n/home/amueller/public/dabl/dabl/preprocessing.py:343: UserWarning: Discarding near-constant features: ['Street', 'Utilities', 'Land Slope', 'Condition 2', 'Roof Matl', 'Heating', 'Low Qual Fin SF', 'Kitchen AbvGr', 'Garage Cond', '3Ssn Porch', 'Pool Area', 'Misc Val']\n warn(\"Discarding near-constant features: {}\".format(\n"
],
[
"sr = dabl.SimpleRegressor()\nsr.fit(ames_df, target_col='SalePrice')",
"/home/amueller/public/dabl/dabl/preprocessing.py:343: UserWarning: Discarding near-constant features: ['Street', 'Utilities', 'Land Slope', 'Condition 2', 'Roof Matl', 'Heating', 'Low Qual Fin SF', 'Kitchen AbvGr', 'Garage Cond', '3Ssn Porch', 'Pool Area', 'Misc Val']\n warn(\"Discarding near-constant features: {}\".format(\n"
],
[
"dabl.explain(sr)",
"_____no_output_____"
],
[
"# The neighborhood seems to dominate, no continuous variable is in the top 10 highest coefficients.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a8f37fa0d1224efd2124ba79adad89fa498963f
| 39,796 |
ipynb
|
Jupyter Notebook
|
book/error-propagation/track-example.ipynb
|
willettk/stats-ds-book
|
06bc751a7e82f73f9d7419f32fe5882ec5742f2f
|
[
"MIT"
] | 41 |
2020-08-18T12:14:43.000Z
|
2022-03-31T16:37:17.000Z
|
book/error-propagation/track-example.ipynb
|
willettk/stats-ds-book
|
06bc751a7e82f73f9d7419f32fe5882ec5742f2f
|
[
"MIT"
] | 7 |
2020-08-19T04:22:24.000Z
|
2020-12-22T15:18:24.000Z
|
book/error-propagation/track-example.ipynb
|
willettk/stats-ds-book
|
06bc751a7e82f73f9d7419f32fe5882ec5742f2f
|
[
"MIT"
] | 13 |
2020-08-19T02:57:47.000Z
|
2022-03-03T15:24:07.000Z
| 82.22314 | 19,284 | 0.845713 |
[
[
[
"## A track example\n\nThe file `times.dat` has made up data for 100-m races between Florence Griffith-Joyner and Shelly-Ann Fraser-Pryce. \n\nWe want to understand how often Shelly-Ann beats Flo-Jo.",
"_____no_output_____"
]
],
[
[
"%pylab inline --no-import-all",
"Populating the interactive namespace from numpy and matplotlib\n"
]
],
[
[
"<!-- Secret comment:\nHow the data were generated\nw = np.random.normal(0,.07,10000)\nx = np.random.normal(10.65,.02,10000)+w\ny = np.random.normal(10.7,.02,10000)+w\nnp.savetxt('times.dat', (x,y), delimiter=',')\n-->",
"_____no_output_____"
]
],
[
[
"florence, shelly = np.loadtxt('times.dat', delimiter=',')",
"_____no_output_____"
],
[
"counts, bins, patches = plt.hist(florence,bins=50,alpha=0.2, label='Flo-Jo')\ncounts, bins, patches = plt.hist(shelly,bins=bins,alpha=0.2, label='Shelly-Ann')\nplt.legend()\nplt.xlabel('times (s)')",
"_____no_output_____"
],
[
"np.mean(florence), np.mean(shelly)",
"_____no_output_____"
],
[
"np.std(florence),np.std(shelly)",
"_____no_output_____"
]
],
[
[
"## let's make a prediction \n\nBased on the mean and std. of their times, let's make a little simulation to predict how often Shelly-Ann beats Flo-Jo.\n\nWe can use propagation of errors to predict mean and standard deviation for $q=T_{shelly}-T_{Florence}$",
"_____no_output_____"
]
],
[
[
"mean_q = np.mean(shelly)-np.mean(florence)",
"_____no_output_____"
],
[
"sigma_q = np.sqrt(np.std(florence)**2+np.std(shelly)**2)",
"_____no_output_____"
],
[
"f_guess = np.random.normal(np.mean(florence),np.std(florence),10000)\ns_guess = np.random.normal(np.mean(shelly),np.std(shelly),10000)\ntoy_difference = s_guess-f_guess",
"_____no_output_____"
]
],
[
[
"Make Toy data",
"_____no_output_____"
]
],
[
[
"#toy_difference = np.random.normal(mean_q, sigma_q, 10000)\ncounts, bins, patches = plt.hist(toy_difference,bins=50, alpha=0.2, label='toy data')\ncounts, bins, patches = plt.hist(toy_difference[toy_difference<0],bins=bins, alpha=0.2)\nnorm = (bins[1]-bins[0])*10000\nplt.plot(bins,norm*mlab.normpdf(bins,mean_q,sigma_q), label='prediction')\nplt.legend()\nplt.xlabel('Shelly - Florence')",
"_____no_output_____"
],
[
"# predict fraction of wins\nnp.sum(toy_difference<0)/10000.",
"_____no_output_____"
],
[
"#check toy data looks like real data\ncounts, bins, patches = plt.hist(f_guess,bins=50,alpha=0.2)\ncounts, bins, patches = plt.hist(s_guess,bins=bins,alpha=0.2)",
"_____no_output_____"
]
],
[
[
"## How often does she actually win?",
"_____no_output_____"
]
],
[
[
"counts, bins, patches = plt.hist(shelly-florence,bins=50,alpha=0.2)\ncounts, bins, patches = plt.hist((shelly-florence)[florence-shelly>0],bins=bins,alpha=0.2)\nplt.xlabel('Shelly - Florence')\n\n1.*np.sum(florence-shelly>0)/florence.size\n",
"_____no_output_____"
]
],
[
[
"## What's gonig on?",
"_____no_output_____"
]
],
[
[
"plt.scatter(f_guess,s_guess, alpha=0.01)",
"_____no_output_____"
],
[
"plt.scatter(florence,shelly, alpha=0.01)",
"_____no_output_____"
],
[
"plt.hexbin(shelly,florence, alpha=1)",
"_____no_output_____"
]
],
[
[
"Previously we learned propagation of errors formula neglecting correlation:\n\n$\\sigma_q^2 = \\left( \\frac{\\partial q}{ \\partial x} \\sigma_x \\right)^2 + \\left( \\frac{\\partial q}{ \\partial y}\\, \\sigma_y \\right)^2 = \\frac{\\partial q}{ \\partial x} \\frac{\\partial q}{ \\partial x} C_{xx} + \\frac{\\partial q}{ \\partial y} \\frac{\\partial q}{ \\partial y} C_{yy}$\n\nNow we need to extend the formula to take into account correlation\n\n$\\sigma_q^2 = \\frac{\\partial q}{ \\partial x} \\frac{\\partial q}{ \\partial x} C_{xx} + \\frac{\\partial q}{ \\partial y} \\frac{\\partial q}{ \\partial y} C_{yy} + 2 \\frac{\\partial q}{ \\partial x} \\frac{\\partial q}{ \\partial y} C_{xxy} $\n\n",
"_____no_output_____"
]
],
[
[
"# covariance matrix\ncov_matrix = np.cov(shelly,florence)\ncov_matrix",
"_____no_output_____"
],
[
"# normalized correlation matrix\nnp.corrcoef(shelly,florence)",
"_____no_output_____"
],
[
"# q = T_shelly - T_florence\n# x = T_shelly\n# y = T_florence\n# propagation of errors\ncov_matrix[0,0]+cov_matrix[1,1]-2*cov_matrix[0,1]",
"_____no_output_____"
],
[
"mean_q = np.mean(shelly)-np.mean(florence)\nsigma_q_with_corr = np.sqrt(cov_matrix[0,0]+cov_matrix[1,1]-2*cov_matrix[0,1])\nsigma_q_no_corr = np.sqrt(cov_matrix[0,0]+cov_matrix[1,1])",
"_____no_output_____"
],
[
"counts, bins, patches = plt.hist(shelly-florence,bins=50,alpha=0.2)\ncounts, bins, patches = plt.hist((shelly-florence)[florence-shelly>0],bins=bins,alpha=0.2)\nnorm = (bins[1]-bins[0])*10000\nplt.plot(bins,norm*mlab.normpdf(bins,mean_q,sigma_q_with_corr), label='prediction with correlation')\nplt.plot(bins,norm*mlab.normpdf(bins,mean_q, sigma_q_no_corr), label='prediction without correlation')\nplt.legend()\nplt.xlabel('Shelly - Florence')\n\n1.*np.sum(florence-shelly>0)/florence.size\n\n",
"_____no_output_____"
],
[
"np.std(florence-shelly)",
"_____no_output_____"
],
[
"np.sqrt(2.)*0.73",
"_____no_output_____"
],
[
"((np.sqrt(2.)*0.073)**2-0.028**2)/2.",
"_____no_output_____"
],
[
".073**2",
"_____no_output_____"
],
[
"np.std(florence+shelly)",
"_____no_output_____"
],
[
"np.sqrt(2*(np.sqrt(2.)*0.073)**2 -0.028**2)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a8f389c90128e0e46d04bdbe0455ac7cdf20271
| 108,966 |
ipynb
|
Jupyter Notebook
|
MaPeCode_Notebooks/15. Clustering - Distancias.ipynb
|
mapecode/python-ml-course
|
05054d17173f934ab09694b8f9eb406a98d69d6b
|
[
"MIT"
] | null | null | null |
MaPeCode_Notebooks/15. Clustering - Distancias.ipynb
|
mapecode/python-ml-course
|
05054d17173f934ab09694b8f9eb406a98d69d6b
|
[
"MIT"
] | null | null | null |
MaPeCode_Notebooks/15. Clustering - Distancias.ipynb
|
mapecode/python-ml-course
|
05054d17173f934ab09694b8f9eb406a98d69d6b
|
[
"MIT"
] | null | null | null | 52.742498 | 29,710 | 0.548281 |
[
[
[
"# Distancias",
"_____no_output_____"
]
],
[
[
"from scipy.spatial import distance_matrix\nimport pandas as pd",
"_____no_output_____"
],
[
"data = pd.read_csv(\"../datasets/movies/movies.csv\", sep=\";\")\ndata",
"_____no_output_____"
],
[
"movies = data.columns.values.tolist()[1:]\nmovies",
"_____no_output_____"
],
[
"def dm_to_df(dd, col_name):\n import pandas as pd\n return pd.DataFrame(dd, index=col_name, columns=col_name)",
"_____no_output_____"
]
],
[
[
"## Distancia de manhattan",
"_____no_output_____"
]
],
[
[
"dd1 = distance_matrix(data[movies], data[movies], p=1)\ndm_to_df(dd1, data['user_id'])",
"_____no_output_____"
]
],
[
[
"## Distancia euclidea",
"_____no_output_____"
]
],
[
[
"dd2 = distance_matrix(data[movies], data[movies], p=2)\ndm_to_df(dd2, data['user_id'])",
"_____no_output_____"
]
],
[
[
"------",
"_____no_output_____"
]
],
[
[
" import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D",
"_____no_output_____"
],
[
"fig = plt.figure()\nax = fig.add_subplot(111, projection=\"3d\")\nax.scatter(xs = data[\"star_wars\"], ys = data[\"lord_of_the_rings\"], zs=data[\"harry_potter\"])",
"_____no_output_____"
]
],
[
[
"## Enlaces",
"_____no_output_____"
]
],
[
[
"df = dm_to_df(dd1, data[\"user_id\"])\ndf\n",
"_____no_output_____"
],
[
"Z=[]",
"_____no_output_____"
],
[
"df[11]=df[1]+df[10]\ndf.loc[11]=df.loc[1]+df.loc[10]\nZ.append([1,10,0.7,2])#id1, id2, d, n_elementos_en_cluster -> 11.\ndf",
"_____no_output_____"
],
[
"for i in df.columns.values.tolist():\n df.loc[11][i] = min(df.loc[1][i], df.loc[10][i])\n df.loc[i][11] = min(df.loc[i][1], df.loc[i][10])\ndf",
"_____no_output_____"
],
[
"df = df.drop([1,10])\ndf = df.drop([1,10], axis=1)\ndf",
"_____no_output_____"
],
[
"x = 2\ny = 7\n\nn = 12\n\ndf[n]=df[x]+df[y]\ndf.loc[n]=df.loc[x]+df.loc[y]\nZ.append([x,y,df.loc[x][y],2])#id1, id2, d, n_elementos_en_cluster -> 11.\n\nfor i in df.columns.values.tolist():\n df.loc[n][i] = min(df.loc[x][i], df.loc[y][i])\n df.loc[i][n] = min(df.loc[i][x], df.loc[i][y])\n\ndf = df.drop([x,y])\ndf = df.drop([x,y], axis=1)\ndf",
"_____no_output_____"
],
[
"x = 11\ny = 13\n\nn = 14\n\ndf[n]=df[x]+df[y]\ndf.loc[n]=df.loc[x]+df.loc[y]\nZ.append([x,y,df.loc[x][y],2])#id1, id2, d, n_elementos_en_cluster -> 11.\n\nfor i in df.columns.values.tolist():\n df.loc[n][i] = min(df.loc[x][i], df.loc[y][i])\n df.loc[i][n] = min(df.loc[i][x], df.loc[i][y])\n\ndf = df.drop([x,y])\ndf = df.drop([x,y], axis=1)\ndf",
"_____no_output_____"
],
[
"x = 9\ny = 12\nz = 14\n\nn = 15\n\ndf[n]=df[x]+df[y]\ndf.loc[n]=df.loc[x]+df.loc[y]\nZ.append([x,y,df.loc[x][y],3])#id1, id2, d, n_elementos_en_cluster -> 11.\n\nfor i in df.columns.values.tolist():\n df.loc[n][i] = min(df.loc[x][i], df.loc[y][i], df.loc[z][i])\n df.loc[i][n] = min(df.loc[i][x], df.loc[i][y], df.loc[i][z])\n\ndf = df.drop([x,y,z])\ndf = df.drop([x,y,z], axis=1)\ndf",
"_____no_output_____"
],
[
"x = 4\ny = 6\nz = 15\n\nn = 16\n\ndf[n]=df[x]+df[y]\ndf.loc[n]=df.loc[x]+df.loc[y]\nZ.append([x,y,df.loc[x][y],3])#id1, id2, d, n_elementos_en_cluster -> 11.\n\nfor i in df.columns.values.tolist():\n df.loc[n][i] = min(df.loc[x][i], df.loc[y][i], df.loc[z][i])\n df.loc[i][n] = min(df.loc[i][x], df.loc[i][y], df.loc[i][z])\n\ndf = df.drop([x,y,z])\ndf = df.drop([x,y,z], axis=1)\ndf",
"_____no_output_____"
],
[
"x = 3\ny = 16\n\nn = 17\n\ndf[n]=df[x]+df[y]\ndf.loc[n]=df.loc[x]+df.loc[y]\nZ.append([x,y,df.loc[x][y],2])#id1, id2, d, n_elementos_en_cluster -> 11.\n\nfor i in df.columns.values.tolist():\n df.loc[n][i] = min(df.loc[x][i], df.loc[y][i])\n df.loc[i][n] = min(df.loc[i][x], df.loc[i][y])\n\ndf = df.drop([x,y])\ndf = df.drop([x,y], axis=1)\ndf",
"_____no_output_____"
],
[
"Z",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a8f55cbd34581e9ffb5ac23a4600c17df611712
| 295,751 |
ipynb
|
Jupyter Notebook
|
notebooks/knn.ipynb
|
ianscottknight/leaf-count
|
bfefadfdb6aaab141d526ad3bbdfc5f89138c60c
|
[
"FTL"
] | null | null | null |
notebooks/knn.ipynb
|
ianscottknight/leaf-count
|
bfefadfdb6aaab141d526ad3bbdfc5f89138c60c
|
[
"FTL"
] | null | null | null |
notebooks/knn.ipynb
|
ianscottknight/leaf-count
|
bfefadfdb6aaab141d526ad3bbdfc5f89138c60c
|
[
"FTL"
] | 3 |
2021-01-28T19:55:59.000Z
|
2022-03-19T06:12:57.000Z
| 477.788368 | 113,992 | 0.940406 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport os\nimport datetime\nimport pickle\nfrom PIL import Image\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sklearn\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import confusion_matrix",
"_____no_output_____"
]
],
[
[
"# Baseline: K Nearest Neighbors Classification ",
"_____no_output_____"
],
[
"### Load leaf count data",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame.from_csv('data.csv') ",
"/usr/local/lib/python3.7/site-packages/ipykernel_launcher.py:1: FutureWarning: from_csv is deprecated. Please use read_csv(...) instead. Note that some of the default arguments are different, so please refer to the documentation for from_csv when changing your function calls\n \"\"\"Entry point for launching an IPython kernel.\n"
]
],
[
[
"### Add new column of best guess at leaf count based by taking average of minimum and maximum",
"_____no_output_____"
]
],
[
[
"df['avg'] = df.apply(lambda x: (x['minimum']+x['maximum'])/2, axis=1)\n",
"_____no_output_____"
]
],
[
[
"### Examine sample of leaf data",
"_____no_output_____"
]
],
[
[
"df.sample(10)",
"_____no_output_____"
]
],
[
[
"### Examine distribution of leaf counts per plant",
"_____no_output_____"
]
],
[
[
"plt.hist(df.minimum, bins=[i for i in range(1, 18)], color='r', alpha=0.4, rwidth=0.3, label='minimum')\nplt.hist(df.maximum, bins=[i for i in range(1, 18)], color='b', alpha=0.4, rwidth=0.3, label='maximum')\nplt.hist(df.avg, bins=[i for i in range(1, 18)], color='g', alpha=0.5, rwidth=0.85, label='avg')\nplt.legend(loc='upper right')\nplt.title('Distribution of Plant Leaf Counts')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Examine sample image",
"_____no_output_____"
]
],
[
[
"Image.open('plants_augmented/plant_1.png')",
"_____no_output_____"
]
],
[
[
"### Convert sample image to grayscale",
"_____no_output_____"
]
],
[
[
"Image.open('plants_augmented/plant_1.png').convert('L')",
"_____no_output_____"
]
],
[
[
"### Load image data, convert to grayscale, and then convert to array",
"_____no_output_____"
]
],
[
[
"image_data = [np.array(Image.open('plants_augmented/plant_{}.png'.format(n)).convert('L')) for n in df.index]\n",
"_____no_output_____"
]
],
[
[
"### Examine distribution of grayscale pixel values",
"_____no_output_____"
]
],
[
[
"grayscale_pixels = []\nfor i in range(len(image_data)): \n grayscale_pixels += list(image_data[i].flatten())\n\nplt.hist(grayscale_pixels, bins=[i for i in range(0, 256, 10)], color='b', alpha=0.4, rwidth=0.85)\nplt.title('Distribution of Gray-Scale Pixel Counts')\nplt.show()\n",
"_____no_output_____"
]
],
[
[
"There is a clear bimodal distribution of grayscale pixel values, which is what we expect to see for images of dark foreground objects against a lighter background. ",
"_____no_output_____"
],
[
"### Separate training set (85%) and test set (15%)",
"_____no_output_____"
]
],
[
[
"mask = np.random.rand(len(df)) <= 0.85\ndf_train = df[mask]\ndf_test = df[~mask]",
"_____no_output_____"
]
],
[
[
"### Make x_train, y_train, x_test, and y_test\n\nFor the baseline only, we will use the minimum number of leaves per plant as a stand-in for the best guess of the true number of leaves. This is because KNN is an algorithm for classification tasks, and therefore we need our labels to be whole numbers so that they can be treated as robust classes. In contrast, the average can be a float, which would break our class requirement.",
"_____no_output_____"
]
],
[
[
"x_train = [image_data[i].flatten() for i, x in enumerate(list(mask)) if x == True]\nx_test = [image_data[i].flatten() for i, x in enumerate(list(mask)) if x == False]\n\ny_train = list(df_train['minimum'])\ny_test = list(df_test['minimum'])",
"_____no_output_____"
]
],
[
[
"### Pool of K values to test: 1, 2, 3, 5, 10, 15",
"_____no_output_____"
]
],
[
[
"model_1NN = KNeighborsClassifier(n_neighbors=1, n_jobs=-1)\nmodel_2NN = KNeighborsClassifier(n_neighbors=2, n_jobs=-1)\nmodel_3NN = KNeighborsClassifier(n_neighbors=3, n_jobs=-1)\nmodel_5NN = KNeighborsClassifier(n_neighbors=5, n_jobs=-1)\nmodel_10NN = KNeighborsClassifier(n_neighbors=10, n_jobs=-1)\nmodel_15NN = KNeighborsClassifier(n_neighbors=15, n_jobs=-1)\n\nmodel_pool = [(1, model_1NN),\n (2, model_2NN),\n (3, model_3NN),\n (5, model_5NN),\n (10, model_10NN),\n (15, model_15NN)]\n\nfor k, model in model_pool: \n model.fit(x_train, y_train)\n",
"_____no_output_____"
]
],
[
[
"### Class prediction accuracy: exact class predictions",
"_____no_output_____"
]
],
[
[
"for k, model in model_pool:\n print('K = {}: {}'.format(k, round(model.score(x_test, y_test), 3)))\n",
"K = 1: 0.154\nK = 2: 0.147\nK = 3: 0.14\nK = 5: 0.14\nK = 10: 0.13\nK = 15: 0.112\n"
]
],
[
[
"### Class prediction accuracy: within range of plus-or-minus 1",
"_____no_output_____"
]
],
[
[
"TOLERANCE = 1\n\nfor k, model in model_pool:\n pred = model.predict(x_test)\n acc = sum([1 for i, y_hat in enumerate(pred) if abs(y_hat - y_test[i]) <= df['maximum'].iloc[i]-df['minimum'].iloc[i]]) / len(y_test)\n\n print('K = {}: {}'.format(k, round(acc, 3)))\n",
"K = 1: 0.677\nK = 2: 0.642\nK = 3: 0.586\nK = 5: 0.589\nK = 10: 0.667\nK = 15: 0.691\n"
]
],
[
[
"### Class prediction accuracy: confusion matrix",
"_____no_output_____"
]
],
[
[
"for k, model in model_pool:\n pred = model.predict(x_test)\n arr = confusion_matrix(y_test, pred, labels=np.unique(y_test))\n df_cm = pd.DataFrame(arr, index=[i for i in np.unique(y_test)], columns=[i for i in np.unique(y_test)])\n sns.heatmap(df_cm, annot=True)\n plt.show()\n ",
"_____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"
] |
[
[
"code"
],
[
"markdown",
"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"
]
] |
4a8f63db05cc337b33d51adfaa3b95b6bb347c21
| 75,717 |
ipynb
|
Jupyter Notebook
|
notebooks/AD_EDA.ipynb
|
ghPRao/pneumonia_detectiion_from_chest_xray
|
645fa5ac94729ba4d073630688fa340275fd3b8c
|
[
"MIT"
] | null | null | null |
notebooks/AD_EDA.ipynb
|
ghPRao/pneumonia_detectiion_from_chest_xray
|
645fa5ac94729ba4d073630688fa340275fd3b8c
|
[
"MIT"
] | null | null | null |
notebooks/AD_EDA.ipynb
|
ghPRao/pneumonia_detectiion_from_chest_xray
|
645fa5ac94729ba4d073630688fa340275fd3b8c
|
[
"MIT"
] | null | null | null | 59.385882 | 2,771 | 0.607948 |
[
[
[
"## Angelica EDA",
"_____no_output_____"
],
[
"#### Library Imports\n",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom keras.preprocessing import image_dataset_from_directory\nfrom keras.models import Sequential, load_model\nfrom keras import layers, optimizers, models\nfrom keras import metrics\nfrom keras import optimizers",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report,confusion_matrix\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"# import opencv\n# FIX, NOT WORKING AT THE MOMENT.",
"_____no_output_____"
],
[
"import os",
"_____no_output_____"
]
],
[
[
"#### Data Imports",
"_____no_output_____"
]
],
[
[
"# train_dir_norm= '../data/chest_xray/train/NORMAL'\n# train_dir_pn = '../data/chest_xray/train/PNEUMONIA'\n\n# test_dir_norm= '../data/chest_xray/test/NORMAL'\n# test_dir_pn= '../data/chest_xray/test/PNEUMONIA'\n\n# val_dir_norm= '../data/chest_xray/val/NORMAL'\n# val_dir_pn= '../data/chest_xray/val/PNEUMONIA'\n\n#write a function for importing",
"_____no_output_____"
],
[
"os.getcwd()\nval2 = '/Users/angelicadegaetano/Documents/Flatiron/Lessons/pneumonia_detection/data'",
"_____no_output_____"
],
[
"# train_imgs_norm = [file for file in os.listdir(train_dir_norm) if file.endswith('.jpeg')]\n# train_imgs_pn = [file for file in os.listdir(train_dir_pn) if file.endswith('.jpeg')]\n \n# test_imgs_norm = [file for file in os.listdir(test_dir_norm) if file.endswith('.jpeg')]\n# test_imgs_pn = [file for file in os.listdir(test_dir_pn) if file.endswith('.jpeg')]\n \n \n# val_imgs_norm = [file for file in os.listdir(val_dir_norm) if file.endswith('.jpeg')]\n# val_imgs_pn = [file for file in os.listdir(val_dir_pn) if file.endswith('.jpeg')]\n \n \n#write a function ",
"_____no_output_____"
],
[
"print(len(train_imgs_norm))\nprint(len(train_imgs_pn))\n\nprint(len(test_imgs_norm))\nprint(len(test_imgs_pn))\n\nprint(len(val_imgs_norm))\nprint(len(val_imgs_pn))\n",
"1341\n3875\n234\n390\n8\n8\n"
],
[
"train_dir= '../data/chest_xray/train'\n\ntest_dir= '../data/chest_xray/test'\n\nval_dir= '../data/chest_xray/val'\n",
"_____no_output_____"
]
],
[
[
"#### Data Preprocessing",
"_____no_output_____"
]
],
[
[
"train_gen = ImageDataGenerator().flow_from_directory(train_dir)\n",
"Found 5216 images belonging to 2 classes.\n"
],
[
"#test_gen = ImageDataGenerator().flow_from_directory(test_dir, target_size= (64, 64), batch_size=80)\ntest_gen = ImageDataGenerator().flow_from_directory(test_dir)",
"Found 637 images belonging to 2 classes.\n"
],
[
"val_gen = ImageDataGenerator().flow_from_directory(val_dir)",
"Found 16 images belonging to 2 classes.\n"
],
[
"tf.keras.preprocessing.image_dataset_from_directory(train_dir)",
"Found 5216 files belonging to 2 classes.\n"
],
[
"tf.keras.preprocessing.image_dataset_from_directory(test_dir)",
"Found 637 files belonging to 2 classes.\n"
],
[
"tf.keras.preprocessing.image_dataset_from_directory(val_dir)",
"Found 16 files belonging to 2 classes.\n"
],
[
"train_dir= '../data/chest_xray/train'\n\ntest_dir= '../data/chest_xray/test'\n\nval_dir= '../data/chest_xray/val'",
"_____no_output_____"
],
[
"train_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n # This is the target directory\n train_dir,\n # All images will be resized to 150x150\n target_size=(150, 150),\n batch_size=20,\n # Since we use binary_crossentropy loss, we need binary labels\n class_mode='binary')\n",
"Found 5216 images belonging to 2 classes.\n"
],
[
"validation_generator = test_datagen.flow_from_directory(val_dir,\n target_size=(150, 150),\n batch_size=20,\n class_mode='binary')",
"Found 16 images belonging to 2 classes.\n"
],
[
"from keras import layers\nfrom keras import models\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu',\n input_shape=(150, 150, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))",
"_____no_output_____"
],
[
"from keras import optimizers\n\nmodel.compile(loss='binary_crossentropy',\n optimizer=optimizers.RMSprop(lr=1e-4),\n metrics=['acc'])",
"_____no_output_____"
],
[
"history = model.fit_generator(train_generator, \n steps_per_epoch=100, \n epochs=30, \n validation_data=validation_generator, \n validation_steps=50)",
"Epoch 1/30\n100/100 [==============================] - ETA: 0s - loss: 0.4683 - acc: 0.7875WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 50 batches). You may need to use the repeat() function when building your dataset.\n100/100 [==============================] - 38s 378ms/step - loss: 0.4683 - acc: 0.7875 - val_loss: 1.0015 - val_acc: 0.6250\nEpoch 2/30\n100/100 [==============================] - 37s 368ms/step - loss: 0.2287 - acc: 0.9083\nEpoch 3/30\n100/100 [==============================] - 38s 377ms/step - loss: 0.1573 - acc: 0.9385\nEpoch 4/30\n100/100 [==============================] - 37s 368ms/step - loss: 0.1460 - acc: 0.9444\nEpoch 5/30\n100/100 [==============================] - 42s 423ms/step - loss: 0.1260 - acc: 0.9509\nEpoch 6/30\n100/100 [==============================] - 40s 403ms/step - loss: 0.1150 - acc: 0.9535\nEpoch 7/30\n100/100 [==============================] - 40s 395ms/step - loss: 0.1154 - acc: 0.9569\nEpoch 8/30\n 23/100 [=====>........................] - ETA: 26s - loss: 0.0802 - acc: 0.9717"
],
[
"history = model.fit_generator(train_generator, \n steps_per_epoch=50, \n epochs=10, \n validation_data=validation_generator, \n validation_steps=25)",
"Epoch 1/10\n50/50 [==============================] - 18s 355ms/step - loss: 0.1070 - acc: 0.9659\nEpoch 2/10\n50/50 [==============================] - 20s 407ms/step - loss: 0.0960 - acc: 0.9620\nEpoch 3/10\n50/50 [==============================] - 21s 425ms/step - loss: 0.0979 - acc: 0.9590\nEpoch 4/10\n50/50 [==============================] - 18s 369ms/step - loss: 0.0922 - acc: 0.9650\nEpoch 5/10\n50/50 [==============================] - 18s 351ms/step - loss: 0.0718 - acc: 0.9690\nEpoch 6/10\n50/50 [==============================] - 18s 352ms/step - loss: 0.0925 - acc: 0.9640\nEpoch 7/10\n50/50 [==============================] - 21s 410ms/step - loss: 0.0849 - acc: 0.9690\nEpoch 8/10\n50/50 [==============================] - 18s 360ms/step - loss: 0.0854 - acc: 0.9610\nEpoch 9/10\n50/50 [==============================] - 18s 355ms/step - loss: 0.0663 - acc: 0.9790\nEpoch 10/10\n50/50 [==============================] - 18s 360ms/step - loss: 0.0663 - acc: 0.9800\n"
],
[
"model.compile(loss='binary_crossentropy',\n optimizer=optimizers.RMSprop(lr=1e-4),\n metrics=['mse'])",
"_____no_output_____"
],
[
"history = model.fit_generator(train_generator, \n steps_per_epoch=15, \n epochs=10, \n validation_data=validation_generator, \n validation_steps=210)",
"Epoch 1/10\n15/15 [==============================] - ETA: 0s - loss: 0.1382 - mse: 0.0414WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 210 batches). You may need to use the repeat() function when building your dataset.\n15/15 [==============================] - 6s 408ms/step - loss: 0.1382 - mse: 0.0414 - val_loss: 0.4032 - val_mse: 0.1218\nEpoch 2/10\n15/15 [==============================] - 6s 375ms/step - loss: 0.0647 - mse: 0.0174\nEpoch 3/10\n15/15 [==============================] - 6s 385ms/step - loss: 0.0884 - mse: 0.0240\nEpoch 4/10\n15/15 [==============================] - 5s 346ms/step - loss: 0.0387 - mse: 0.0102\nEpoch 5/10\n15/15 [==============================] - 5s 357ms/step - loss: 0.0909 - mse: 0.0260\nEpoch 6/10\n15/15 [==============================] - 5s 346ms/step - loss: 0.1251 - mse: 0.0368\nEpoch 7/10\n15/15 [==============================] - 5s 366ms/step - loss: 0.0555 - mse: 0.0164\nEpoch 8/10\n15/15 [==============================] - 5s 360ms/step - loss: 0.0987 - mse: 0.0264\nEpoch 9/10\n15/15 [==============================] - 5s 342ms/step - loss: 0.0790 - mse: 0.0221\nEpoch 10/10\n15/15 [==============================] - 5s 361ms/step - loss: 0.0792 - mse: 0.0214\n"
],
[
"from keras import metrics\nmodel.compile(loss='binary_crossentropy',\n optimizer=optimizers.RMSprop(lr=1e-4),\n metrics= [metrics.Recall()])",
"_____no_output_____"
],
[
"history = model.fit_generator(train_generator, \n steps_per_epoch=15, \n epochs=10, \n validation_data=validation_generator, \n validation_steps=10)",
"Epoch 1/10\n15/15 [==============================] - ETA: 0s - loss: 0.0814 - recall: 0.9779WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 10 batches). You may need to use the repeat() function when building your dataset.\n15/15 [==============================] - 6s 388ms/step - loss: 0.0814 - recall: 0.9779 - val_loss: 0.5726 - val_recall: 1.0000\nEpoch 2/10\n15/15 [==============================] - 5s 354ms/step - loss: 0.0883 - recall: 0.9816\nEpoch 3/10\n15/15 [==============================] - 5s 341ms/step - loss: 0.0283 - recall: 0.9956\nEpoch 4/10\n15/15 [==============================] - 6s 374ms/step - loss: 0.0407 - recall: 0.9867\nEpoch 5/10\n15/15 [==============================] - 7s 468ms/step - loss: 0.0991 - recall: 0.9865\nEpoch 6/10\n15/15 [==============================] - 6s 368ms/step - loss: 0.0533 - recall: 0.9822\nEpoch 7/10\n15/15 [==============================] - 7s 435ms/step - loss: 0.0826 - recall: 0.9732\nEpoch 8/10\n15/15 [==============================] - 7s 440ms/step - loss: 0.0306 - recall: 0.9954\nEpoch 9/10\n15/15 [==============================] - 7s 449ms/step - loss: 0.0176 - recall: 0.9956\nEpoch 10/10\n15/15 [==============================] - 6s 412ms/step - loss: 0.0772 - recall: 0.9821\n"
]
],
[
[
"#### Data",
"_____no_output_____"
]
],
[
[
"train_gen = ImageDataGenerator().flow_from_directory(train_dir, target_size = (200, 200), class_mode='binary')",
"Found 5216 images belonging to 2 classes.\n"
],
[
"test_gen = ImageDataGenerator().flow_from_directory(test_dir, target_size = (200, 200),class_mode='binary')",
"Found 637 images belonging to 2 classes.\n"
],
[
"val_gen = ImageDataGenerator().flow_from_directory(val_dir, target_size = (200, 200), class_mode='binary')",
"Found 16 images belonging to 2 classes.\n"
]
],
[
[
"### Model Building",
"_____no_output_____"
],
[
"##### FSM",
"_____no_output_____"
]
],
[
[
"model = Sequential()\n\nmodel.add(layers.Dense(15, activation= 'relu', input_shape= (200,200,3))) # input layer\nmodel.add(layers.Dense(20 , activation= 'relu')) # 1 hidden layer\nmodel.add(layers.Dense(1, activation= 'sigmoid')) # outpul layer",
"_____no_output_____"
],
[
"model.compile(optimizer='rmsprop', loss= 'binary_crossentropy', metrics =['Recall']) #thinking about RECALL?",
"_____no_output_____"
],
[
"fsm_model_fit = model.fit()",
"_____no_output_____"
],
[
"#FSM CNN\n\nmodel_1 = Sequential()\n\nmodel.add(layers.Conv2D(25, (3, 3), activation='relu',\n input_shape=(150, 150, 3)))\nmodel_1.add(layers.MaxPooling2D((2, 2)))\nmodel_1.add(layers.Conv2D(50, (3, 3), activation='relu'))\nmodel_1.add(layers.MaxPooling2D((2, 2)))\nmodel_1.add(layers.Dense(1, activation='sigmoid'))",
"_____no_output_____"
],
[
"model_1.compile(optimizer='rmsprop', loss= 'binary_crossentropy', metrics =['Recall'])",
"_____no_output_____"
],
[
"model_1_fit = model_1.fit_generator(train_gen, steps_per_epoch = 50, epochs=15, validation_data= val_gen, validation_steps= 25)",
"WARNING:tensorflow:From <ipython-input-20-9e7f5e68645e>:1: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use Model.fit, which supports generators.\nEpoch 1/15\n"
]
],
[
[
"## FSM- vanilla basic",
"_____no_output_____"
]
],
[
[
"train_dir= '../data/chest_xray/train'\n\ntest_dir= '../data/chest_xray/test'\n\nval_dir= '../data/chest_xray/val'",
"_____no_output_____"
],
[
"# train_datagen = ImageDataGenerator(rescale=1./255)\n# test_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_gen = ImageDataGenerator().flow_from_directory(\n train_dir,\n target_size=(200, 200),\n batch_size=15,\n class_mode='binary')",
"Found 5216 images belonging to 2 classes.\n"
],
[
"val_gen = ImageDataGenerator().flow_from_directory(val_dir,\n target_size=(200, 200),\n batch_size=15,\n class_mode='binary')",
"Found 16 images belonging to 2 classes.\n"
],
[
"model = models.Sequential()\nmodel.add(layers.Conv2D(20, (3, 3), activation='relu',\n input_shape=(200, 200, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(1, activation='sigmoid'))",
"_____no_output_____"
],
[
"model.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics= [metrics.Recall(), 'acc'])",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_2 (Conv2D) (None, 198, 198, 20) 560 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 99, 99, 20) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 196020) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 196021 \n=================================================================\nTotal params: 196,581\nTrainable params: 196,581\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"history = model.fit_generator(train_gen, \n steps_per_epoch=20, \n epochs=10, \n validation_data=val_gen, \n validation_steps=10)",
"Epoch 1/10\n20/20 [==============================] - ETA: 0s - loss: 3.3987 - recall_4: 0.9690 - acc: 0.9533WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 10 batches). You may need to use the repeat() function when building your dataset.\n20/20 [==============================] - 5s 233ms/step - loss: 3.3987 - recall_4: 0.9690 - acc: 0.9533 - val_loss: 1.0611 - val_recall_4: 1.0000 - val_acc: 0.8750\nEpoch 2/10\n20/20 [==============================] - 4s 209ms/step - loss: 0.5241 - recall_4: 0.9813 - acc: 0.9633\nEpoch 3/10\n20/20 [==============================] - 4s 218ms/step - loss: 0.2867 - recall_4: 0.9814 - acc: 0.9700\nEpoch 4/10\n20/20 [==============================] - 4s 207ms/step - loss: 0.4302 - recall_4: 0.9769 - acc: 0.9600\nEpoch 5/10\n20/20 [==============================] - 4s 196ms/step - loss: 0.3160 - recall_4: 0.9777 - acc: 0.9696\nEpoch 6/10\n20/20 [==============================] - 4s 221ms/step - loss: 0.7033 - recall_4: 0.9524 - acc: 0.9500\nEpoch 7/10\n20/20 [==============================] - 4s 214ms/step - loss: 1.1427 - recall_4: 0.9683 - acc: 0.9433\nEpoch 8/10\n20/20 [==============================] - 4s 187ms/step - loss: 0.0770 - recall_4: 0.9875 - acc: 0.9900\nEpoch 9/10\n20/20 [==============================] - 7s 369ms/step - loss: 0.1322 - recall_4: 0.9909 - acc: 0.9800\nEpoch 10/10\n20/20 [==============================] - 5s 235ms/step - loss: 0.2328 - recall_4: 0.9825 - acc: 0.9733\n"
],
[
"model2 = models.Sequential()\nmodel2.add(layers.Conv2D(20, (3, 3), activation='relu',\n input_shape=(200, 200, 3)))\nmodel2.add(layers.MaxPooling2D((2, 2)))\nmodel2.add(layers.Conv2D(50, (3, 3), activation='relu'))\nmodel2.add(layers.MaxPooling2D((2, 2)))\nmodel2.add(layers.Conv2D(100, (3, 3), activation='relu'))\nmodel2.add(layers.MaxPooling2D((2, 2)))\nmodel2.add(layers.Conv2D(146, (3, 3), activation='relu'))\nmodel2.add(layers.MaxPooling2D((2, 2)))\nmodel2.add(layers.Flatten())\nmodel2.add(layers.Dense(1, activation='sigmoid'))",
"_____no_output_____"
],
[
"model2.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics= [metrics.Recall(), 'acc'])",
"_____no_output_____"
],
[
"history2 = model2.fit_generator(train_gen, \n steps_per_epoch=20, \n epochs=20, \n validation_data=val_gen, \n validation_steps=20)",
"Epoch 1/20\n20/20 [==============================] - 6s 282ms/step - loss: 1.3401 - recall_3: 0.8766 - acc: 0.8233\nEpoch 2/20\n20/20 [==============================] - 6s 313ms/step - loss: 0.1134 - recall_3: 0.9685 - acc: 0.9533\nEpoch 3/20\n20/20 [==============================] - 6s 282ms/step - loss: 0.3387 - recall_3: 0.9447 - acc: 0.9167\nEpoch 4/20\n20/20 [==============================] - 6s 300ms/step - loss: 1.1982 - recall_3: 0.9693 - acc: 0.9300\nEpoch 5/20\n20/20 [==============================] - 6s 276ms/step - loss: 0.1734 - recall_3: 0.9571 - acc: 0.9367\nEpoch 6/20\n20/20 [==============================] - 6s 284ms/step - loss: 0.1703 - recall_3: 0.9628 - acc: 0.9300\nEpoch 7/20\n20/20 [==============================] - 7s 350ms/step - loss: 0.1615 - recall_3: 0.9518 - acc: 0.9400\nEpoch 8/20\n20/20 [==============================] - 8s 375ms/step - loss: 0.1893 - recall_3: 0.9716 - acc: 0.9433\nEpoch 9/20\n20/20 [==============================] - 6s 304ms/step - loss: 0.1498 - recall_3: 0.9735 - acc: 0.9533\nEpoch 10/20\n20/20 [==============================] - 6s 292ms/step - loss: 0.3460 - recall_3: 0.9214 - acc: 0.9000\nEpoch 11/20\n20/20 [==============================] - 6s 294ms/step - loss: 0.1597 - recall_3: 0.9457 - acc: 0.9400\nEpoch 12/20\n20/20 [==============================] - 7s 329ms/step - loss: 0.1496 - recall_3: 0.9696 - acc: 0.9467\nEpoch 13/20\n20/20 [==============================] - 6s 296ms/step - loss: 0.1981 - recall_3: 0.9573 - acc: 0.9467\nEpoch 14/20\n20/20 [==============================] - 6s 277ms/step - loss: 0.1445 - recall_3: 0.9782 - acc: 0.9667\nEpoch 15/20\n20/20 [==============================] - 6s 279ms/step - loss: 0.1450 - recall_3: 0.9740 - acc: 0.9533\nEpoch 16/20\n20/20 [==============================] - 6s 299ms/step - loss: 0.1989 - recall_3: 0.9417 - acc: 0.9167\nEpoch 17/20\n20/20 [==============================] - 6s 301ms/step - loss: 0.1316 - recall_3: 0.9732 - acc: 0.9500\nEpoch 18/20\n20/20 [==============================] - 6s 312ms/step - loss: 0.4147 - recall_3: 0.9868 - acc: 0.9500\nEpoch 19/20\n20/20 [==============================] - 8s 388ms/step - loss: 0.1477 - recall_3: 0.9682 - acc: 0.9500\nEpoch 20/20\n20/20 [==============================] - 6s 297ms/step - loss: 0.2180 - recall_3: 0.9640 - acc: 0.9400\n"
],
[
"\n from sklearn.metrics import classification_report\n Y_pred = model.predict(val_gen)\n y_pred = np.argmax(Y_pred, axis=1)\n print('Confusion Matrix')\n print(confusion_matrix(val_gen.classes, y_pred))\n print('Classification Report')\n target_names = ['Normal', 'Pneumonia']\n print(classification_report(val_gen.classes, y_pred, \n target_names=target_names))",
"Confusion Matrix\n[[8 0]\n [8 0]]\nClassification Report\n precision recall f1-score support\n\n Normal 0.50 1.00 0.67 8\n Pneumonia 0.00 0.00 0.00 8\n\n accuracy 0.50 16\n macro avg 0.25 0.50 0.33 16\nweighted avg 0.25 0.50 0.33 16\n\n"
],
[
" from sklearn.metrics import classification_report\n Y_pred = model2.predict(val_gen)\n y_pred = np.argmax(Y_pred, axis=1)\n print('Confusion Matrix')\n print(confusion_matrix(val_gen.classes, y_pred))\n print('Classification Report')\n target_names = ['Normal', 'Pneumonia']\n print(classification_report(val_gen.classes, y_pred, \n target_names=target_names))",
"Confusion Matrix\n[[8 0]\n [8 0]]\nClassification Report\n precision recall f1-score support\n\n Normal 0.50 1.00 0.67 8\n Pneumonia 0.00 0.00 0.00 8\n\n accuracy 0.50 16\n macro avg 0.25 0.50 0.33 16\nweighted avg 0.25 0.50 0.33 16\n\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a8f68e041c2821f437740711ae67cd38cc184b6
| 83,441 |
ipynb
|
Jupyter Notebook
|
Notebook/ResNet+TripletLoss+CASIAFACE (2).ipynb
|
mertz1999/Sima-Face-Recognition
|
444a35de1f4b48180feee6a3c245f6d76eeb4968
|
[
"MIT"
] | 3 |
2022-02-14T13:41:10.000Z
|
2022-02-15T17:14:11.000Z
|
Notebook/ResNet+TripletLoss+CASIAFACE (2).ipynb
|
mertz1999/Sima-Face-Recognition
|
444a35de1f4b48180feee6a3c245f6d76eeb4968
|
[
"MIT"
] | null | null | null |
Notebook/ResNet+TripletLoss+CASIAFACE (2).ipynb
|
mertz1999/Sima-Face-Recognition
|
444a35de1f4b48180feee6a3c245f6d76eeb4968
|
[
"MIT"
] | null | null | null | 57.625 | 18,494 | 0.647284 |
[
[
[
"## Load Python Packages\n",
"_____no_output_____"
]
],
[
[
"# --- load packages\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.nn.modules.distance import PairwiseDistance\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom torchsummary import summary\nfrom torch.cuda.amp import GradScaler, autocast\nfrom torch.nn import functional as F\n\n\nimport time\nfrom collections import OrderedDict\nimport numpy as np\nimport os\nfrom skimage import io\nfrom PIL import Image\nimport cv2\nimport matplotlib.pyplot as plt\n",
"_____no_output_____"
]
],
[
[
"## Set parameters",
"_____no_output_____"
]
],
[
[
"# --- Set all Parameters\nDatasetFolder = \"./CASIA-WebFace\" # path to Dataset folder\nResNet_sel = \"18\" # select ResNet type\nNumberID = 10575 # Number of ID in dataset \nbatch_size = 256 # size of batch size\nTriplet_size = 10000 * batch_size # size of total Triplets\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nloss_margin = 0.6 # Margin for Triplet loss\nlearning_rate = 0.075 # choose Learning Rate(note that this value will be change during training)\nepochs = 200 # number of iteration over total dataset\n",
"_____no_output_____"
]
],
[
[
"## Download Datasets\n#### In this section we download CASIA-WebFace and LFW-Dataset\n#### we use CAISA-WebFace for Training and LFW for Evaluation",
"_____no_output_____"
]
],
[
[
"# --- Download CASIA-WebFace Dataset\nprint(40*\"=\" + \" Download CASIA WebFace \" + 40*'=')\n! gdown --id 1Of_EVz-yHV7QVWQGihYfvtny9Ne8qXVz\n! unzip CASIA-WebFace.zip\n! rm CASIA-WebFace.zip\n\n# --- Download LFW Dataset\nprint(40*\"=\" + \" Download LFW \" + 40*'=')\n! wget http://vis-www.cs.umass.edu/lfw/lfw-deepfunneled.tgz\n! tar -xvzf lfw-deepfunneled.tgz\n! rm lfw-deepfunneled.tgz",
"_____no_output_____"
]
],
[
[
"# Define ResNet Parts\n#### 1. Residual block\n#### 2. Make ResNet by Prv. block",
"_____no_output_____"
]
],
[
[
"# --- Residual block\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, out_channels, downsample=1):\n super().__init__()\n # --- Variables\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.downsample = downsample\n\n # --- Residual parts\n # --- Conv part\n self.blocks = nn.Sequential(OrderedDict(\n {\n # --- First Conv\n 'conv1' : nn.Conv2d(self.in_channels, self.out_channels, kernel_size=3, stride=self.downsample, padding=1, bias=False),\n 'bn1' : nn.BatchNorm2d(self.out_channels),\n 'Relu1' : nn.ReLU(),\n \n # --- Secound Conv\n 'conv2' : nn.Conv2d(self.out_channels, self.out_channels, kernel_size=3, stride=1, padding=1, bias=False),\n 'bn2' : nn.BatchNorm2d(self.out_channels)\n }\n ))\n # --- shortcut part\n self.shortcut = nn.Sequential(OrderedDict(\n {\n 'conv' : nn.Conv2d(self.in_channels, self.out_channels, kernel_size=1, stride=self.downsample, bias=False),\n 'bn' : nn.BatchNorm2d(self.out_channels)\n }\n ))\n \n def forward(self, x):\n residual = x\n if (self.in_channels != self.out_channels) : residual = self.shortcut(x)\n x = self.blocks(x)\n x += residual\n return x\n\n\n\n",
"_____no_output_____"
],
[
"# # --- Test Residual block\n# dummy = torch.ones((1, 32, 140, 140))\n\n# block = ResidualBlock(32, 64)\n# block(dummy).shape\n# print(block)\n",
"_____no_output_____"
],
[
"# --- Make ResNet18\nclass ResNet18(nn.Module):\n def __init__(self):\n super().__init__()\n\n # --- Pre layers with 7*7 conv with stride2 and a max-pooling\n self.PreBlocks = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=7, padding=3, stride=2, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n )\n\n # --- Define all Residual Blocks here\n self.CoreBlocka = nn.Sequential(\n ResidualBlock(64,64 ,downsample=1),\n ResidualBlock(64,64 ,downsample=1),\n # ResidualBlock(64,64 ,downsample=1),\n\n ResidualBlock(64,128 ,downsample=2),\n ResidualBlock(128,128 ,downsample=1),\n # ResidualBlock(128,128 ,downsample=1),\n # ResidualBlock(128,128 ,downsample=1),\n\n ResidualBlock(128,256 ,downsample=2),\n ResidualBlock(256,256 ,downsample=1),\n # ResidualBlock(256,256 ,downsample=1),\n # ResidualBlock(256,256 ,downsample=1),\n # ResidualBlock(256,256 ,downsample=1),\n # ResidualBlock(256,256 ,downsample=1),\n\n ResidualBlock(256,512 ,downsample=2),\n ResidualBlock(512,512 ,downsample=1),\n # ResidualBlock(512,512 ,downsample=1)\n )\n\n # --- Make Average pooling\n self.avg = nn.AdaptiveAvgPool2d((1,1))\n\n # --- FC layer for output\n self.fc = nn.Linear(512, 512, bias=False)\n\n def forward(self, x):\n x = self.PreBlocks(x)\n x = self.CoreBlocka(x)\n x = self.avg(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n x = F.normalize(x, p=2, dim=1)\n return x",
"_____no_output_____"
],
[
"# dummy = torch.ones((1, 3, 114, 144))\nmodel = ResNet18()\n# model\n# res = model(dummy)\n\nmodel.to(device)\nsummary(model, (3, 114, 114))\ndel model",
"_____no_output_____"
]
],
[
[
"# Make TripletLoss Class ",
"_____no_output_____"
]
],
[
[
"# --- Triplet loss\n\"\"\"\n This code was imported from tbmoon's 'facenet' repository:\n https://github.com/tbmoon/facenet/blob/master/utils.py\n \n\"\"\"\n\nimport torch\nfrom torch.autograd import Function\nfrom torch.nn.modules.distance import PairwiseDistance\n\n\nclass TripletLoss(Function):\n def __init__(self, margin):\n super(TripletLoss, self).__init__()\n self.margin = margin\n self.pdist = PairwiseDistance(p=2)\n\n def forward(self, anchor, positive, negative):\n pos_dist = self.pdist.forward(anchor, positive)\n neg_dist = self.pdist.forward(anchor, negative)\n hinge_dist = torch.clamp(self.margin + pos_dist - neg_dist, min=0.0)\n loss = torch.mean(hinge_dist)\n # print(torch.mean(pos_dist).item(), torch.mean(neg_dist).item(), loss.item())\n # print(\"pos_dist\", pos_dist)\n # print(\"neg_dist\", neg_dist)\n # print(self.margin + pos_dist - neg_dist)\n return loss\n",
"_____no_output_____"
]
],
[
[
"# Make Triplet Dataset from CASIA-WebFace\n\n##### 1. Make Triplet pairs\n##### 2. Make them zip\n##### 3. Make Dataset Calss\n##### 4. Define Transform",
"_____no_output_____"
]
],
[
[
"# --- Create Triplet Datasets ---\n# --- make a list of ids and folders\nselected_ids = np.uint32(np.round((np.random.rand(int(Triplet_size))) * (NumberID-1)))\nfolders = os.listdir(\"./CASIA-WebFace/\")\n\n# --- Itrate on each id and make Triplets list\nTripletList = []\n\nfor index,id in enumerate(selected_ids):\n\n # --- find name of id faces folder\n id_str = str(folders[id])\n\n # --- find list of faces in this folder\n number_faces = os.listdir(\"./CASIA-WebFace/\"+id_str)\n\n # --- Get two Random number for Anchor and Positive\n while(True):\n two_random = np.uint32(np.round(np.random.rand(2) * (len(number_faces)-1))) \n if (two_random[0] != two_random[1]):\n break\n\n # --- Make Anchor and Positive image\n Anchor = str(number_faces[two_random[0]])\n Positive = str(number_faces[two_random[1]])\n\n # --- Make Negative image\n while(True):\n neg_id = np.uint32(np.round(np.random.rand(1) * (NumberID-1)))\n if (neg_id != id):\n break\n # --- number of images in negative Folder\n neg_id_str = str(folders[neg_id[0]])\n number_faces = os.listdir(\"./CASIA-WebFace/\"+neg_id_str)\n one_random = np.uint32(np.round(np.random.rand(1) * (len(number_faces)-1))) \n Negative = str(number_faces[one_random[0]])\n \n # --- insert Anchor, Positive and Negative image path to TripletList\n TempList = [\"\",\"\",\"\"]\n TempList[0] = id_str + \"/\" + Anchor\n TempList[1] = id_str + \"/\" + Positive\n TempList[2] = neg_id_str + \"/\" + Negative\n TripletList.append(TempList)\n\n \n\n\n\n\n\n",
"_____no_output_____"
],
[
"# # --- Make dataset Triplets File\n# f = open(\"CASIA-WebFace-Triplets.txt\", \"w\")\n# for index, triplet in enumerate(TripletList):\n# f.write(triplet[0] + \" \" + triplet[1] + \" \" + triplet[2])\n# if (index != len(TripletList)-1):\n# f.write(\"\\n\")\n# f.close()\n\n\n# # --- Make zipFile if you need\n# !zip -r CASIA-WebFace-Triplets.zip CASIA-WebFace-Triplets.txt",
"_____no_output_____"
],
[
"# # --- Read zip File and extract TripletList\n# TripletList = []\n# # !unzip CASIA-WebFace-Triplets.zip\n\n# # --- Read text file\n# with open('CASIA-WebFace-Triplets.txt') as f:\n# lines = f.readlines()\n# for line in lines:\n# TripletList.append(line.split(' '))\n# TripletList[-1][2] = TripletList[-1][2][0:-1]\n\n# # --- Print some data\n# print(TripletList[0:5])\n",
"_____no_output_____"
],
[
"# --- Make Pytorch Dataset Class for Triplets \nclass TripletFaceDatset(Dataset):\n def __init__(self, list_of_triplets, transform=None):\n # --- initializing values\n print(\"Start Creating Triplets Dataset from CASIA-WebFace\")\n self.list_of_triplets = list_of_triplets\n self.transform = transform\n\n # --- getitem function\n def __getitem__(self, index):\n # --- get images path and read faces\n anc_img_path, pos_img_path, neg_img_path = self.list_of_triplets[index]\n anc_img = cv2.imread('./CASIA-WebFace/'+anc_img_path)\n pos_img = cv2.imread('./CASIA-WebFace/'+pos_img_path)\n neg_img = cv2.imread('./CASIA-WebFace/'+neg_img_path)\n\n # anc_img = cv2.resize(anc_img, (114,114))\n # pos_img = cv2.resize(pos_img, (114,114))\n # neg_img = cv2.resize(neg_img, (114,114))\n\n\n # --- set transform\n if self.transform:\n anc_img = self.transform(anc_img)\n pos_img = self.transform(pos_img)\n neg_img = self.transform(neg_img)\n \n return {'anc_img' : anc_img,\n 'pos_img' : pos_img,\n 'neg_img' : neg_img}\n \n # --- return len of triplets\n def __len__(self):\n return len(self.list_of_triplets)\n \n\n\n\n",
"_____no_output_____"
],
[
"# --- Define Transforms\ntransform_list =transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize((140,140)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std =[0.229, 0.224, 0.225])\n ])\n\n",
"_____no_output_____"
],
[
"# --- Test Dataset\ntriplet_dataset = TripletFaceDatset(TripletList, transform_list)\ntriplet_dataset[0]['anc_img'].shape",
"Start Creating Triplets Dataset from CASIA-WebFace\n"
]
],
[
[
"# LFW Evaluation\n##### 1. Face detection function\n##### 2. Load LFW Pairs .npy file\n##### 3. Define Function for evaluation ",
"_____no_output_____"
]
],
[
[
"# -------------------------- UTILS CELL -------------------------------\n\ntrained_face_data = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')\n# --- define Functions\ndef face_detect(file_name):\n flag = True\n # Choose an image to detect faces in\n img = cv2.imread(file_name)\n\n # Must convert to greyscale\n # grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Detect Faces \n # face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)\n\n # img_crop = []\n # Draw rectangles around the faces\n # for (x, y, w, h) in face_coordinates:\n # img_crop.append(img[y-20:y+h+20, x-20:x+w+20])\n\n # --- select only Biggest\n # big_id = 0\n # if len(img_crop) > 1:\n # temp = 0\n # for idx, img in enumerate(img_crop):\n # if img.shape[0] > temp:\n # temp = img.shape[0]\n # big_id = idx\n # elif len(img_crop) == 0:\n # flag = False\n # img_crop = [0]\n\n # return image crop\n # return [img_crop[big_id]], flag\n return [img], flag",
"_____no_output_____"
],
[
"# --- LFW Dataset loading for test part\nl2_dist = PairwiseDistance(2)\ncos = nn.CosineSimilarity(dim=1, eps=1e-6)\n# --- 1. Load .npy pairs path\nlfw_pairs_path = np.load('lfw_pairs_path.npy', allow_pickle=True)\npairs_dist_list_mat = []\npairs_dist_list_unmat = []\nvalid_thresh = 0.96\n\ndef lfw_validation(model):\n global valid_thresh\n tot_len = len(lfw_pairs_path)\n\n model.eval() # use model in evaluation mode\n with torch.no_grad():\n true_match = 0\n for path in lfw_pairs_path:\n # --- extracting\n pair_one_path = path['pair_one']\n # print(pair_one_path)\n pair_two_path = path['pair_two']\n # print(pair_two_path)\n matched = int(path['matched'])\n\n # --- detect face and resize it\n pair_one_img, flag_one = face_detect(pair_one_path)\n pair_two_img, flag_two = face_detect(pair_two_path)\n\n if (flag_one==False) or (flag_two==False):\n tot_len = tot_len-1\n continue\n \n\n # --- Model Predict\n pair_one_img = transform_list(pair_one_img[0])\n pair_two_img = transform_list(pair_two_img[0])\n pair_one_embed = model(torch.unsqueeze(pair_one_img, 0).to(device))\n pair_two_embed = model(torch.unsqueeze(pair_two_img, 0).to(device))\n \n # print(pair_one_embed.shape)\n # break\n # print(pair_one_img)\n # break\n # --- find Distance\n pairs_dist = l2_dist.forward(pair_one_embed, pair_two_embed)\n if matched == 1: pairs_dist_list_mat.append(pairs_dist.item())\n if matched == 0: pairs_dist_list_unmat.append(pairs_dist.item())\n \n\n # --- thrsholding\n if (matched==1 and pairs_dist.item() <= valid_thresh) or (matched==0 and pairs_dist.item() > valid_thresh):\n true_match += 1\n\n valid_thresh = (np.percentile(pairs_dist_list_unmat,25) + np.percentile(pairs_dist_list_mat,75)) /2\n print(\"Thresh :\", valid_thresh)\n return (true_match/tot_len)*100\n\n",
"_____no_output_____"
],
[
"# img, _ = face_detect(\"./lfw-deepfunneled/Steve_Lavin/Steve_Lavin_0002.jpg\")\n# plt.imshow(img[0])\n# plt.show()",
"_____no_output_____"
],
[
"temp = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\nfor i in temp:\n valid_thresh = i\n print(lfw_validation(model))",
"_____no_output_____"
],
[
"(np.mean(pairs_dist_list_mat) + np.mean(pairs_dist_list_unmat) )/2",
"_____no_output_____"
],
[
"ppairs_dist_list_unmat",
"_____no_output_____"
],
[
"# --- find best thresh\nround_unmat = pairs_dist_list_unmat\nround_mat = pairs_dist_list_mat\n\nprint(\"----- Unmatched statistical information -----\")\nprint(\"len : \",len(round_unmat))\nprint(\"min : \", np.min(round_unmat))\nprint(\"Q1 : \", np.percentile(round_unmat, 15))\nprint(\"mean : \", np.mean(round_unmat))\nprint(\"Q3 : \", np.percentile(round_unmat, 75))\nprint(\"max : \", np.max(round_unmat))\n\nprint(\"\\n\")\nprint(\"----- matched statistical information -----\")\nprint(\"len : \",len(round_mat))\nprint(\"min : \", np.min(round_mat))\nprint(\"Q1 : \", np.percentile(round_mat, 25))\nprint(\"mean : \", np.mean(round_mat))\nprint(\"Q3 : \", np.percentile(round_mat, 85))\nprint(\"max : \", np.max(round_mat))",
"_____no_output_____"
]
],
[
[
"## How to make Training Faster",
"_____no_output_____"
]
],
[
[
"# Make Trianing Faster in Pytorch(Cuda):\n# 1. use number of worker\n# 2. set pin_memory\n# 3. Enable cuDNN for optimizing Conv\n# 4. using AMP\n# 5. set bias=False in conv layer if you set batch normalizing in model\n\n\n\n# source: https://betterprogramming.pub/how-to-make-your-pytorch-code-run-faster-93079f3c1f7b",
"_____no_output_____"
]
],
[
[
"# DataLoader",
"_____no_output_____"
]
],
[
[
"# --- DataLoader\nface_data = torch.utils.data.DataLoader(triplet_dataset, \n batch_size= batch_size,\n shuffle=True,\n num_workers=4,\n pin_memory= True)\n\n# --- Enable cuDNN\ntorch.backends.cudnn.benchmark = True\n",
"/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n cpuset_checked))\n"
]
],
[
[
"# Save Model (best acc. and last acc.)",
"_____no_output_____"
]
],
[
[
"# --- saving model for best and last model\n\n# --- Connect to google Drive for saving models\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n# --- some variable for saving models\nBEST_MODEL_PATH = \"./gdrive/MyDrive/best_trained.pth\"\nLAST_MODEL_PATH = \"./gdrive/MyDrive/last_trained.pth\"\n\n\ndef save_model(model_sv, loss_sv, epoch_sv, optimizer_state_sv, accuracy, accu_sv_list, loss_sv_list):\n # --- Inputs:\n # 1. model_sv : orginal model that trained\n # 2. loss_sv : current loss\n # 3. epoch_sv : current epoch\n # 4. optimizer_state_sv : current value of optimizer \n # 5. accuracy : current accuracy\n \n # --- save last epoch\n if accuracy >= max(accu_sv_list): \n torch.save(model.state_dict(), BEST_MODEL_PATH)\n \n # --- save this model for checkpoint\n torch.save({\n 'epoch': epoch_sv,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer_state_sv.state_dict(),\n 'loss': loss_sv,\n 'accu_sv_list': accu_sv_list,\n 'loss_sv_list' : loss_sv_list\n }, LAST_MODEL_PATH)\n",
"Mounted at /content/gdrive\n"
]
],
[
[
"# Load prev. model for continue training",
"_____no_output_____"
]
],
[
[
"torch.cuda.empty_cache()\n\n# --- training initialize and start\nmodel = ResNet18().to(device) # load model \ntiplet_loss = TripletLoss(loss_margin) # load Tripletloss\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), \n lr=learning_rate) # load optimizer\nl2_dist = PairwiseDistance(2) # L2 distance loading # save loss values\nepoch_check = 0\nvalid_arr = []\nloss_arr = []\n\n\nload_last_epoch = True\nif (load_last_epoch == True):\n # --- load last model\n # define model objects before this\n checkpoint = torch.load(LAST_MODEL_PATH, map_location=device) # load model path\n model.load_state_dict(checkpoint['model_state_dict']) # load state dict\n optimizer.load_state_dict(checkpoint['optimizer_state_dict']) # load optimizer\n epoch_check = checkpoint['epoch'] # load epoch\n loss = checkpoint['loss'] # load loss value\n valid_arr = checkpoint['accu_sv_list'] # load Acc. values\n loss_arr = checkpoint['loss_sv_list'] # load loss values\nmodel.train() \n",
"_____no_output_____"
],
[
"epoch_check",
"_____no_output_____"
],
[
"loss",
"_____no_output_____"
]
],
[
[
"# Training Loop",
"_____no_output_____"
]
],
[
[
"model.train()\n# --- Training loop based on number of epoch\ntemp = 0.075\nfor epoch in range(epoch_check,200):\n print(80*'=')\n \n # --- For saving imformation\n triplet_loss_sum = 0.0\n len_face_data = len(face_data)\n\n # -- set starting time\n time0 = time.time()\n\n # --- make learning rate update\n if 50 < len(loss_arr):\n for g in optimizer.param_groups:\n g['lr'] = 0.001\n temp = 0.001\n\n # --- loop on batches\n for batch_idx, batch_faces in enumerate(face_data):\n # --- Extract face triplets and send them to CPU or GPU\n anc_img = batch_faces['anc_img'].to(device)\n pos_img = batch_faces['pos_img'].to(device)\n neg_img = batch_faces['neg_img'].to(device)\n\n # --- Get embedded values for each triplet\n anc_embed = model(anc_img)\n pos_embed = model(pos_img)\n neg_embed = model(neg_img)\n \n\n # --- Find Distance\n pos_dist = l2_dist.forward(anc_embed, pos_embed)\n neg_dist = l2_dist.forward(anc_embed, neg_embed)\n\n # --- Select hard triplets\n all = (neg_dist - pos_dist < 0.8).cpu().numpy().flatten()\n hard_triplets = np.where(all == 1)\n\n if len(hard_triplets[0]) == 0: # --- Check number of hard triplets\n continue\n \n # --- select hard embeds\n anc_hard_embed = anc_embed[hard_triplets]\n pos_hard_embed = pos_embed[hard_triplets]\n neg_hard_embed = neg_embed[hard_triplets]\n\n # --- Loss\n loss_value = tiplet_loss.forward(anc_hard_embed, pos_hard_embed, neg_hard_embed)\n\n # --- backward path\n optimizer.zero_grad()\n loss_value.backward()\n optimizer.step()\n\n if (batch_idx % 200 == 0) : print(\"Epoch: [{}/{}] ,Batch index: [{}/{}], Loss Value:[{:.8f}]\".format(epoch+1, epochs, batch_idx+1, len_face_data,loss_value))\n # --- save information\n triplet_loss_sum += loss_value.item()\n \n print(\"Learning Rate: \", temp)\n\n\n # --- Find Avg. loss value\n avg_triplet_loss = triplet_loss_sum / len_face_data\n loss_arr.append(avg_triplet_loss)\n\n \n # --- Validation part besed on LFW Dataset\n validation_acc = lfw_validation(model)\n valid_arr.append(validation_acc)\n model.train()\n\n # --- Save model with checkpoints\n save_model(model, avg_triplet_loss, epoch+1, optimizer, validation_acc, valid_arr, loss_arr)\n\n # --- Print information for each epoch\n print(\" Train set - Triplet Loss = {:.8f}\".format(avg_triplet_loss))\n print(' Train set - Accuracy = {:.8f}'.format(validation_acc))\n print(f' Execution time = {time.time() - time0}')\n",
"================================================================================\n"
]
],
[
[
"# plot and print some information",
"_____no_output_____"
]
],
[
[
"plt.plotvalid_arr(, 'b-', \n label='Validation Accuracy',\n \n )\nplt.show()",
"_____no_output_____"
],
[
"plt.plot(loss_arr, 'b-', \n label='loss values',\n \n )\nplt.show()",
"_____no_output_____"
],
[
"for param_group in optimizer.param_groups:\n print(param_group['lr'])",
"0.01875\n"
],
[
"valid_arr",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"print(40*\"=\" + \" Download CASIA WebFace \" + 40*'=')\n! gdown --id 1Of_EVz-yHV7QVWQGihYfvtny9Ne8qXVz\n! unzip CASIA-WebFace.zip\n! rm CASIA-WebFace.zip",
"_____no_output_____"
],
[
"# --- LFW Dataset loading for test part\nl2_dist = PairwiseDistance(2)\ncos = nn.CosineSimilarity(dim=1, eps=1e-6)\n\nvalid_thresh = 0.96\n\n \n\nmodel.eval()\nwith torch.no_grad():\n # --- extracting\n pair_one_path = \"./3.jpg\"\n # print(pair_one_path)\n pair_two_path = \"./2.jpg\"\n\n # --- detect face and resize it\n pair_one_img, flag_one = face_detect(pair_one_path)\n pair_two_img, flag_two = face_detect(pair_two_path)\n\n # --- Model Predict\n pair_one_img = transform_list(pair_one_img[0])\n pair_two_img = transform_list(pair_two_img[0])\n pair_one_embed = model(torch.unsqueeze(pair_one_img, 0).to(device))\n pair_two_embed = model(torch.unsqueeze(pair_two_img, 0).to(device))\n\n # --- find Distance\n pairs_dist = l2_dist.forward(pair_one_embed, pair_two_embed)\n print(pairs_dist)\n ",
"tensor([0.9349], device='cuda:0')\n"
],
[
"# --- Create Triplet Datasets ---\n# --- make a list of ids and folders\nselected_ids = np.uint32(np.round((np.random.rand(int(Triplet_size))) * (NumberID-1)))\nfolders = os.listdir(\"./CASIA-WebFace/\")\n\n# --- Itrate on each id and make Triplets list\nTripletList = []\n\nfor index,id in enumerate(selected_ids):\n # --- print info\n # print(40*\"=\" + str(index) + 40*\"=\")\n # print(index)\n\n # --- find name of id faces folder\n id_str = str(folders[id])\n\n # --- find list of faces in this folder\n number_faces = os.listdir(\"./CASIA-WebFace/\"+id_str)\n\n # --- Get two Random number for Anchor and Positive\n while(True):\n two_random = np.uint32(np.round(np.random.rand(2) * (len(number_faces)-1))) \n if (two_random[0] != two_random[1]):\n break\n\n # --- Make Anchor and Positive image\n Anchor = str(number_faces[two_random[0]])\n Positive = str(number_faces[two_random[1]])\n\n # --- Make Negative image\n while(True):\n neg_id = np.uint32(np.round(np.random.rand(1) * (NumberID-1)))\n if (neg_id != id):\n break\n # --- number of images in negative Folder\n neg_id_str = str(folders[neg_id[0]])\n number_faces = os.listdir(\"./CASIA-WebFace/\"+neg_id_str)\n one_random = np.uint32(np.round(np.random.rand(1) * (len(number_faces)-1))) \n Negative = str(number_faces[one_random[0]])\n \n # --- insert Anchor, Positive and Negative image path to TripletList\n TempList = [\"\",\"\",\"\"]\n TempList[0] = id_str + \"/\" + Anchor\n TempList[1] = id_str + \"/\" + Positive\n TempList[2] = neg_id_str + \"/\" + Negative\n TripletList.append(TempList)\n # print(TripletList[-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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a8f6c64fc907e7b08cb73dc855c5a698638f9bf
| 26,845 |
ipynb
|
Jupyter Notebook
|
Publish.ipynb
|
sirmammingtonham/futureNEWS
|
b1f45cc4a9af03d14eba8f8c2e57a05af5fc9695
|
[
"Unlicense"
] | null | null | null |
Publish.ipynb
|
sirmammingtonham/futureNEWS
|
b1f45cc4a9af03d14eba8f8c2e57a05af5fc9695
|
[
"Unlicense"
] | 4 |
2020-07-21T12:45:00.000Z
|
2022-01-22T08:54:32.000Z
|
Publish.ipynb
|
sirmammingtonham/futureMAG
|
b1f45cc4a9af03d14eba8f8c2e57a05af5fc9695
|
[
"Unlicense"
] | null | null | null | 69.010283 | 7,063 | 0.661017 |
[
[
[
"import re\nimport os\nimport sys\nimport random\nimport gpt_2_simple as gpt2\nimport tensorflow as tf\n\nimport numpy as np",
"_____no_output_____"
],
[
"from random_word import RandomWords\nimport requests\nimport giphy_client\n\nfrom unsplash.api import Api\nfrom unsplash.auth import Auth\n\nfrom medium import Client",
"_____no_output_____"
],
[
"tags = {#'montag': ['Fake News', 'Opinion', 'Artificial Intelligence', 'NLP', 'Future'], \n 'onezero': ['Artificial Intelligence', 'Technology', 'NLP', 'Future'], \n #'futura': ['Sci Fi Fantasy', 'Artificial Intelligence', 'NLP', 'Future', 'Storytelling']\n }",
"_____no_output_____"
],
[
"def clean(story):\n story = story.replace('<|url|>', 'https://github.com/sirmammingtonham/futureMAG')\n story = story.replace('OneZero', 'FutureMAG')\n story = story.replace('onezero', 'FutureMAG')\n return story[16:]",
"_____no_output_____"
],
[
"def split_story(story, run_name):\n story = clean(story)\n split = re.split('(\\.)', story)[0:-1]\n metadata = split[0]\n title = metadata[metadata.find('# ')+2:metadata.find('## ')].strip('\\n')\n subtitle = metadata[metadata.find('## ')+3:metadata.find('\\n', metadata.find('## '))].strip('\\n')\n \n split[0] = split[0].replace(subtitle, f\"{subtitle} | AI generated article*\")\n# if len(title.split(' ')) <= 2:\n# split = story.split('\\n', 3)\n# title = split[1]\n# subtitle = split[2]\n# return [title, subtitle, split[3]]\n return [title, f\"{subtitle} | AI generated article*\", ''.join(split), None, run_name]",
"_____no_output_____"
],
[
"def retrieve_images(story):\n #story[1] = subtitle\n #story[2] = story\n matches = [(m.group(), m.start(0)) for m in re.finditer(r\"(<\\|image\\|>)\", story[2])]\n image_creds = []\n try:\n client_id = \"b9a6edaadf1b5ec49cf05f10aab79d5d2ea1fe66431605d12ec0f7ec22bc7289\"\n client_secret = \"f00e14688a25656c07f07d85e17b4ebd94e93fcf9bf0fd1859f7713ea1d94c16\"\n redirect_uri = \"urn:ietf:wg:oauth:2.0:oob\"\n auth = Auth(client_id, client_secret, redirect_uri)\n api = Api(auth)\n# q = max(re.sub(r'[^\\w\\s]', '', story[0]).split(), key=len) #take longest word from subtitle as search term\n q = story[0].split(' ')[:5]\n for match, idx in matches:\n pic = api.photo.random(query=q)[0]\n img = pic.urls.raw\n image_creds.append((f'https://unsplash.com/@{pic.user.username}', pic.user.name))\n cap_idx = story[2].find('*', idx+11)\n story[2] = story[2][:cap_idx] + '**' + story[2][cap_idx:]\n story[2] = story[2][:idx] + img + story[2][idx+9:]\n except:\n return story\n story[3] = image_creds\n return story",
"_____no_output_____"
],
[
"def publish(title, sub, article, creds, run_name):\n if title == sub:\n return\n #holy shit this is excessive\n tag = tags['onezero'] + [max(re.sub(r'[^\\w\\s]','',title).split(), key=len).capitalize()]\n \n access_token = '2aea40d684c5c501066c6f624d05c952256f0664585d9a36b394c0821ee646499'\n headers = {\n 'Authorization': \"Bearer \" + access_token,\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'\n }\n \n base_url = \"https://api.medium.com/v1/\"\n\n me_response = requests.request(\"GET\", base_url + 'me', headers=headers).text\n json_me_response = json.loads(me_response)\n user_id = json_me_response['data']['id']\n user_url = base_url + 'users/' + user_id + '/'\n posts_url = user_url + 'posts/'\n pub_url = base_url + 'publications/424c42caa624/posts/'\n \n if not creds:\n return\n else:\n img_creds = \"\"\n for auth_url, author in creds:\n img_creds += f\"[{author}]({auth_url})\"\n img_creds += ', ' if len(creds) > 1 else ' '\n img_creds += \"on [Unsplash](https://unsplash.com/)\"\n \n article += \"\\n\\n*This article was written by a [GPT-2 neural network](https://openai.com/blog/better-language-models). All information in this story is most likely false, and all opinions expressed are fake. Weird to think about…\\n\\n\"\n article += f\"**This caption was artificially generated. Image downloaded automatically from {img_creds}.\\n\\n\"\n article += \"All links in this article are placeholders generated by the neural network, signifying that an actual link should have been generated there. These placeholders were later replaced by a link to the github project page.\\n\\n\"\n article += \"**futureMAG** is an experiment in automated storytelling/journalism. This story was created and published without human intervention.\\n\\n\"\n article += \"Code for this project available on github: \"\n article += \"**[sirmammingtonham/futureMAG](https://github.com/sirmammingtonham/futureMAG)**\"\n payload = {\n 'title': title,\n 'contentFormat': 'markdown',\n 'tags': tag if run_name == 'onezero' else tags[run_name],\n 'publishStatus': 'draft',\n 'content': article\n }\n response = requests.request('POST', pub_url, data=payload, headers=headers)\n print(response.text)\n return payload",
"_____no_output_____"
]
],
[
[
"story = stories[0]\nsplit = re.split('(\\.)', story)[0:-1]\nmetadata = split[0]\ntitle = metadata[metadata.find('# ')+2:metadata.find('## ')].strip('\\n')\nsubtitle = metadata[metadata.find('## ')+3:metadata.find('\\n', metadata.find('## '))].strip('\\n')\nsplit[0] = split[0].replace(subtitle, f\"{subtitle} | AI generated article*\")",
"_____no_output_____"
],
[
"bruh = [(m.group(), m.start(0)) for m in re.finditer(r\"(<\\|image\\|>)\", story)]\nfor match, idx in bruh:\n cap_idx = story.find('*', idx+11)\n print(story[:cap_idx] + '**' + story[cap_idx:])\n print(story[:idx] + 'url' + story[idx+9:])",
"_____no_output_____"
],
[
"story = stories[0]\nsplit = re.split('(\\.)', story)[0:-1]\nmetadata = split[0]\ntitle = metadata[metadata.find('# ')+2:metadata.find('## ')].strip('\\n')\nsubtitle = metadata[metadata.find('## ')+3:metadata.find('\\n', metadata.find('## '))].strip('\\n')\nsplit[0] = split[0].replace(subtitle, f\"{subtitle} | AI generated article*\")",
"_____no_output_____"
],
[
"bruh = [(m.group(), m.start(0)) for m in re.finditer(r\"(<\\|image\\|>)\", story)]\nfor match, idx in bruh:\n cap_idx = story.find('*', idx+11)\n print(story[:cap_idx] + '**' + story[cap_idx:])\n print(story[:idx] + 'url' + story[idx+9:])",
"_____no_output_____"
]
],
[
[
"run_name = 'onezero_m'\nsess = gpt2.start_tf_sess()\ngpt2.load_gpt2(sess, run_name)",
"WARNING:tensorflow:From C:\\Users\\ethan\\Anaconda3\\envs\\futuremag\\lib\\site-packages\\tensorflow\\python\\framework\\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\nLoading checkpoint checkpoint\\onezero_m\\model-17000\nWARNING:tensorflow:From C:\\Users\\ethan\\Anaconda3\\envs\\futuremag\\lib\\site-packages\\tensorflow\\python\\training\\saver.py:1266: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to check for files with this prefix.\nINFO:tensorflow:Restoring parameters from checkpoint\\onezero_m\\model-17000\n"
],
[
"stories = gpt2.generate(\n sess, run_name, return_as_list=True,\n truncate=\"<|endoftext|>\", prefix=\"<|startoftext|>\",\n nsamples=1, batch_size=1, length=8000,\n temperature=1,\n top_p=0.9,\n split_context=0.5,\n)",
"WARNING:tensorflow:From C:\\Users\\ethan\\Anaconda3\\envs\\futuremag\\lib\\site-packages\\gpt_2_simple\\src\\sample.py:71: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nWARNING:tensorflow:From C:\\Users\\ethan\\Anaconda3\\envs\\futuremag\\lib\\site-packages\\gpt_2_simple\\src\\sample.py:77: multinomial (from tensorflow.python.ops.random_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.random.categorical instead.\n1016\n1528\n"
],
[
"articles = []\n\nfor story in stories:\n articles.append(split_story(story, run_name))\n\nfor article in articles:\n article = retrieve_images(article)",
"_____no_output_____"
],
[
"articles[0][-1] = 'onezero'",
"_____no_output_____"
],
[
"articles",
"_____no_output_____"
],
[
"publish(*articles[0])",
"{\"data\":{\"id\":\"72b08be038c4\",\"title\":\"Hint: The Constellation of Scorpio\",\"authorId\":\"113d0ce3c66e5af777e596aa4d9fbbc9bbe91a02c53080b3b5407c7bb8819a607\",\"url\":\"https://medium.com/@futureBOT/72b08be038c4\",\"canonicalUrl\":\"\",\"publishStatus\":\"draft\",\"license\":\"\",\"licenseUrl\":\"https://medium.com/policy/9db0094a1e0f\",\"tags\":[\"constellation\",\"nlp\",\"future\",\"technology\",\"artificial-intelligence\"],\"publicationId\":\"424c42caa624\"}}\n"
]
]
] |
[
"code",
"raw",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"raw",
"raw",
"raw",
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a8f7adaf43449bf3cd32f8f130af4f7be9255f0
| 3,641 |
ipynb
|
Jupyter Notebook
|
ipython_notebook/dtree_show.ipynb
|
laszo/ml_practice
|
8e154963cd44c4b91774dbb1f56e1f4745fc1528
|
[
"MIT"
] | null | null | null |
ipython_notebook/dtree_show.ipynb
|
laszo/ml_practice
|
8e154963cd44c4b91774dbb1f56e1f4745fc1528
|
[
"MIT"
] | null | null | null |
ipython_notebook/dtree_show.ipynb
|
laszo/ml_practice
|
8e154963cd44c4b91774dbb1f56e1f4745fc1528
|
[
"MIT"
] | null | null | null | 34.028037 | 1,496 | 0.660258 |
[
[
[
"from dtree2 import *\n%matplotlib inline \n",
"_____no_output_____"
],
[
"main()",
"('SMALL', 'F') 0.3\n('YELLOW', 'F') 0.3\n('STRETCH', 'T') 0.4\n('ADULT', 'T') 0.4\n('SMALL', 'F') 0.5\n('YELLOW', 'F') 0.5\n('ADULT', 'F') 0.5\n('YELLOW', 'F') 0.5\n('ADULT', 'F') 0.5\n('ADULT', 'F') 0.5\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
4a8f9fdbdbd3ddc716053b308a87f68a93c47bf7
| 15,156 |
ipynb
|
Jupyter Notebook
|
data_wrangling_json/sliderule_dsi_json_exercise.ipynb
|
llclave/Springboard-Mini-Projects
|
d59585c1297ed8088847763a6cbfc50db14b92c3
|
[
"MIT"
] | null | null | null |
data_wrangling_json/sliderule_dsi_json_exercise.ipynb
|
llclave/Springboard-Mini-Projects
|
d59585c1297ed8088847763a6cbfc50db14b92c3
|
[
"MIT"
] | null | null | null |
data_wrangling_json/sliderule_dsi_json_exercise.ipynb
|
llclave/Springboard-Mini-Projects
|
d59585c1297ed8088847763a6cbfc50db14b92c3
|
[
"MIT"
] | null | null | null | 31.057377 | 151 | 0.408815 |
[
[
[
"# JSON examples and exercise\n****\n+ get familiar with packages for dealing with JSON\n+ study examples with JSON strings and files \n+ work on exercise to be completed and submitted \n****\n+ reference: http://pandas.pydata.org/pandas-docs/stable/io.html#io-json-reader\n+ data source: http://jsonstudio.com/resources/\n****",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"## imports for Python, Pandas",
"_____no_output_____"
]
],
[
[
"import json\nfrom pandas.io.json import json_normalize",
"_____no_output_____"
]
],
[
[
"## JSON example, with string\n\n+ demonstrates creation of normalized dataframes (tables) from nested json string\n+ source: http://pandas.pydata.org/pandas-docs/stable/io.html#normalization",
"_____no_output_____"
]
],
[
[
"# define json string\ndata = [{'state': 'Florida', \n 'shortname': 'FL',\n 'info': {'governor': 'Rick Scott'},\n 'counties': [{'name': 'Dade', 'population': 12345},\n {'name': 'Broward', 'population': 40000},\n {'name': 'Palm Beach', 'population': 60000}]},\n {'state': 'Ohio',\n 'shortname': 'OH',\n 'info': {'governor': 'John Kasich'},\n 'counties': [{'name': 'Summit', 'population': 1234},\n {'name': 'Cuyahoga', 'population': 1337}]}]",
"_____no_output_____"
],
[
"# use normalization to create tables from nested element\njson_normalize(data, 'counties')",
"_____no_output_____"
],
[
"# further populate tables created from nested element\njson_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']])",
"_____no_output_____"
]
],
[
[
"****\n## JSON example, with file\n\n+ demonstrates reading in a json file as a string and as a table\n+ uses small sample file containing data about projects funded by the World Bank \n+ data source: http://jsonstudio.com/resources/",
"_____no_output_____"
]
],
[
[
"# load json as string\njson.load((open('data/world_bank_projects_less.json')))",
"_____no_output_____"
],
[
"# load as Pandas dataframe\nsample_json_df = pd.read_json('data/world_bank_projects_less.json')\nsample_json_df",
"_____no_output_____"
]
],
[
[
"****\n## JSON exercise\n\nUsing data in file 'data/world_bank_projects.json' and the techniques demonstrated above,\n1. Find the 10 countries with most projects\n2. Find the top 10 major project themes (using column 'mjtheme_namecode')\n3. In 2. above you will notice that some entries have only the code and the name is missing. Create a dataframe with the missing names filled in.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4a8faeab1f69abc5f23ddd6673767ee61b631ca7
| 88,272 |
ipynb
|
Jupyter Notebook
|
thermodynamic_addressability/.ipynb_checkpoints/Thermodynamic Addressability Bac-checkpoint.ipynb
|
j3ny/Analysis
|
16579af7d5763dc28055bafe484bd9cffd0505c5
|
[
"MIT"
] | null | null | null |
thermodynamic_addressability/.ipynb_checkpoints/Thermodynamic Addressability Bac-checkpoint.ipynb
|
j3ny/Analysis
|
16579af7d5763dc28055bafe484bd9cffd0505c5
|
[
"MIT"
] | null | null | null |
thermodynamic_addressability/.ipynb_checkpoints/Thermodynamic Addressability Bac-checkpoint.ipynb
|
j3ny/Analysis
|
16579af7d5763dc28055bafe484bd9cffd0505c5
|
[
"MIT"
] | null | null | null | 198.810811 | 33,724 | 0.873097 |
[
[
[
"import json\nimport math\nimport bigfloat\nimport numpy\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n\nimport seaborn as sns\nsns.set_style(\"whitegrid\", {\"font.family\": \"DejaVu Sans\"})\nsns.set_context(\"poster\")\n\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\n## for Palatino and other serif fonts use:\n#rc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)",
"_____no_output_____"
],
[
" def read_data(filename, short=False):\n json_data = open(filename, 'r').read()\n raw_data = json.loads(json_data)\n seq = []\n seq_id = []\n energy = []\n for k1, v1 in raw_data.iteritems():\n if k1 == \"name\":\n continue\n stp_i = int(k1)\n staple = v1\n #print str(stp_i) + ' ' + v1['staple_sequence']\n for k2, v2 in staple.iteritems():\n if not k2.isdigit():\n continue\n arm_i = k2\n arm = v2\n #if short and len(arm['sequence']) > 8:\n # continue\n dG = arm['dG']\n min_dG = float(arm['min_dG'])\n seq.append(arm['sequence'])\n seq_id.append('stp_' + str(stp_i) + '_' + str(arm_i))\n local_min = []\n for i in range(len(dG)-1):\n if dG[i] < dG[i-1] and dG[i] <= dG[i+1]:\n local_min.append(float(dG[i]))\n sorted_by_energy = sorted(local_min)\n energy.append(numpy.array(sorted_by_energy))\n return seq_id, seq, energy",
"_____no_output_____"
],
[
"def get_boltzmann_distribution(energy_by_arm):\n R = 8.3144621 # gas constant\n T = 293.15 # room temperature\n factor = 4184.0 # joules_per_kcal\n boltzmann_distribution = []\n for dG in energy_by_arm:\n ps = []\n total = bigfloat.BigFloat(0)\n for energy in dG:\n p = bigfloat.exp((-energy*factor)/(R*T), bigfloat.precision(1000))\n ps.append(p)\n total = bigfloat.add(total, p)\n normal_ps = []\n for p in ps:\n normal_ps.append(float(bigfloat.div(p,total)))\n boltzmann_distribution.append(numpy.array(normal_ps))\n return boltzmann_distribution\n\nprint get_boltzmann_distribution([-7.2, -4.6])",
"_____no_output_____"
],
[
"path = 'data/'\nfilename_DB = 'DeBruijn_alpha.json'\nfilename_pUC19 = 'pUC19_alpha.json'\nfilename_M13 = 'M13_square.json'\nfilename_DB7k = 'DB_7k_square.json'\n\n#ids, sequences, energies\n#_, _, energies_DB = read_data(path + filename_DB)\n#_, _, energies_pUC19 = read_data(path + filename_pUC19)\n#_, _, energies_M13 = read_data(path + filename_M13)\n\n_, _, energies_DB_short = read_data(path + filename_DB, short=True)\n_, _, energies_pUC19_short = read_data(path + filename_pUC19, short=True)\n_, _, energies_M13_short = read_data(path + filename_M13, short=True)\n_, _, energies_DB7k_short = read_data(path + filename_DB7k, short=True)\n\n#DB_dist_2 = get_boltzmann_distribution(d[:2] for d in energies_DB_short)\n#pUC19_dist_2 = get_boltzmann_distribution(d[:2] for d in energies_pUC19_short)\n#M13_dist_2 = get_boltzmann_distribution(d[:2] for d in energies_M13_short)\n\n#DB_dist_10 = get_boltzmann_distribution(d[:10] for d in energies_DB_short)\n#pUC19_dist_10 = get_boltzmann_distribution(d[:10] for d in energies_pUC19_short)\n#M13_dist_10 = get_boltzmann_distribution(d[:10] for d in energies_M13_short)\n\n#DB_dist_100 = get_boltzmann_distribution(d[:100] for d in energies_DB_short)\n#pUC19_dist_100 = get_boltzmann_distribution(d[:100] for d in energies_pUC19_short)\n#M13_dist_100 = get_boltzmann_distribution(d[:100] for d in energies_M13_short)\n\nDB_dist_all = get_boltzmann_distribution(d for d in energies_DB_short)\npUC19_dist_all = get_boltzmann_distribution(d for d in energies_pUC19_short)\nM13_dist_all = get_boltzmann_distribution(d for d in energies_M13_short)\nDB7k_dist_all = get_boltzmann_distribution(d for d in energies_DB7k_short)\n\n#DB_dist = get_boltzmann_distribution(d[:100] for d in energies_DB_short)\n#pUC19_dist = get_boltzmann_distribution(d[:100] for d in energies_pUC19_short)\n#M13_dist = get_boltzmann_distribution(d[:100] for d in energies_M13_short)\n\n#DB_dist = get_boltzmann_distribution(energies_DB_short)\n#pUC19_dist = get_boltzmann_distribution(energies_pUC19_short)\n\n#dist = [d[0] for d in DB_dist]",
"_____no_output_____"
],
[
"def example_plot(ax, fontsize=12):\n ax.plot([1, 2])\n ax.locator_params(nbins=3)\n ax.set_xlabel('x-label', fontsize=fontsize)\n ax.set_ylabel('y-label', fontsize=fontsize)\n ax.set_title('Title', fontsize=fontsize)",
"_____no_output_____"
],
[
"def distribution_plot(ax, data_label, data, xlabel, ylabel, fontsize=15):\n bins = 20\n x = numpy.zeros(bins)\n for dist in data:\n i = int(dist[0]*bins)\n i = 0 if i < 0 else i\n i = bins-1 if i > bins-1 else i\n x[i] += 1\n for i in range(len(x)):\n x[i] = 1.0 * x[i] / len(data)\n index = numpy.arange(0, bins)\n ax.bar(index, x, bar_width, linewidth=0)\n ax.set_xticks(numpy.arange(0, bins+1))\n ax.set_xticklabels([('$' + str(i*0.05) + '$') if i % 2 == 0 else \"\" for i in range(0, bins+1)])\n #ax.tick_params(axis='both', which='major')\n \n ylimit = 0.2 if ('6.9' in data_label or 'M13' in data_label) else 0.3\n ax.set_xlim(0, bins)\n ax.set_ylim(0, ylimit)\n \n ax.set_xlabel(xlabel, fontsize=20)\n ax.set_ylabel(ylabel, fontsize=20)\n ax.set_title(data_label, fontsize=20)\n ax.legend()\n ",
"_____no_output_____"
],
[
"plt.close('all')\n\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)\n\ndata_set = OrderedDict()\ndata_set['pUC19 (all)'] = pUC19_dist_all\ndata_set['DB (all)'] = DB_dist_all\ndata_set['M13 (all)'] = M13_dist_all\ndata_set['DB7k (all)'] = DB7k_dist_all\n\nxlabel = r'Specific binding probability'\nylabel = r'Fraction of staples'\n\ndistribution_plot(ax1, r'pUC19', pUC19_dist_all, '', ylabel)\ndistribution_plot(ax2, r'DB (2.4 knt)', DB_dist_all, '', '')\ndistribution_plot(ax3, r'M13', M13_dist_all, xlabel, ylabel)\ndistribution_plot(ax4, r'DBS (6.9 knt)', DB7k_dist_all, xlabel, '')\n\n#%matplotlib inline\n\nfig.set_size_inches(10, 10)\n\nplt.tight_layout()\nplt.savefig(\"/home/j3ny/repos/analysis/Analysis/thermodynamic_addressability/output/addressability_comparison.pdf\",format='pdf',dpi=600)\n#plt.savefig(\"/home/j3ny/repos/analysis/Analysis/thermodynamic_addressability/output/addressability_comparison_long.pdf\",format='pdf',dpi=600)\n",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(nrows=2, ncols=2)\n\nbar_width = 1.0\n\ndata_set = OrderedDict()\ndata_set['pUC19'] = pUC19_dist_all\ndata_set['DBS (2.4 knt)'] = DB_dist_all\ndata_set['M13'] = M13_dist_all\ndata_set['DBS (6.9 knt)'] = DB7k_dist_all\n\nplt.close('all')\nfig = plt.figure()\n\nfrom mpl_toolkits.axes_grid1 import Grid\ngrid = Grid(fig, rect=111, nrows_ncols=(2,2),\n axes_pad=0.4, label_mode='O',\n add_all = True,\n )\n\nfor ax, (data_label, data) in zip(grid, data_set.items()):\n xlabel = 'Specific binding probability' if ('6.9' in data_label or 'M13' in data_label) else ''\n ylabel = 'Fraction of staples'if ('pUC' in data_label or 'M13' in data_label) else ''\n distribution_plot(ax, data_label, data, xlabel, ylabel)\n\n#axes[0,0].set_title('pUC19')\n \n#grid[0].set_title('pUC19')\n#grid[0].set_ylabel('Fraction of staples', fontsize=15)\n#grid[1].set_title('DBS (2.4 knt)')\n\n#grid[2].set_title('M13')\n#grid[2].set_xlabel('Specific binding probability', fontsize=15)\n#grid[2].set_ylabel('Fraction of staples', fontsize=15)\n\n#grid[3].set_title('DBS (6.9 knt)')\n\n#axes[1].set_title('M13')\n#axes[2].set_title(r'$\\lambda$-phage')\n\n#fig.text(0.16, 0.92, 'pUC19', fontsize=15)\n#fig.text(0.6, 0.92, 'DBS (2.4 knt)', fontsize=15)\n\n#fig.text(0.16, 0.46, 'M13mp18', fontsize=15)\n#fig.text(0.6, 0.46, 'DBS (6.9 knt)', fontsize=15)\n\nfig.set_size_inches(6, 6)\n\nplt.tight_layout()\nplt.savefig(\"/home/j3ny/repos/analysis/Analysis/thermodynamic_addressability/output/addressability_comparison.pdf\",format='pdf',dpi=600)",
"_____no_output_____"
],
[
"#######################\n## OBSOLETE ##\n#######################\n\n#%matplotlib inline\n\nfig, axes = plt.subplots(nrows=2, ncols=2)\n\nbar_width = 1.0\n\ndata_set = OrderedDict()\ndata_set['pUC19 (all)'] = pUC19_dist_all\ndata_set['DB (all)'] = DB_dist_all\ndata_set['M13 (all)'] = M13_dist_all\ndata_set['DB7k (all)'] = DB7k_dist_all\n\nfor ax0, (data_label, data) in zip(axes.flat, data_set.items()):\n distribution_plot(ax0)\n\n#fig.text(0.19, 0.96, 'De Bruijn', ha='center')\nfig.text(0.3, 1, 'pUC19 (2.6 knt)', ha='center')\nfig.text(0.7, 1, 'DBS (2.4 knt)', ha='center')\n\nfig.text(0.5, 0.008, 'Specific binding probability', ha='center')\nfig.text(0.001, 0.5, 'Fraction of staples', va='center', rotation='vertical')\n\nfig.set_size_inches(7, 7)\n\nplt.tight_layout()\nplt.savefig(\"/home/j3ny/repos/analysis/Analysis/thermodynamic_addressability/output/addressability_comparison.pdf\",format='pdf',dpi=600)",
"_____no_output_____"
],
[
"## CONVERT DATA\n\npath = 'data/'\nfilename_DB = 'DeBruijn_alpha.json'\nfilename_pUC19 = 'pUC19_alpha.json'\nfilename_M13 = 'M13_square.json'\nfilename_DB7k = 'DB_7k_square.json'\n\nids, sequences, energies = read_data(path + filename_DB7k, short=True)\ndist_all = get_boltzmann_distribution(d for d in energies)\n\nwith open('data/DB_medium.csv', 'w') as out:\n for i in range(len(ids)):\n out.write(ids[i] + ',' + sequences[i] + ',')\n out.write('%.3f' % dist_all[i][0])\n out.write('\\n')\n #print idsi], sequences[i], energies_DB_short[i], DB_dist_all[i]",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a8faff3761689cb33a7720f03a0f834685d6a22
| 28,731 |
ipynb
|
Jupyter Notebook
|
Section 3 - Preparing Data using SparkSQL/hands-on/Hands-on-3.ipynb
|
Sinha-Ujjawal/Mastering-Big-Data-Analytics-with-PySpark
|
71bea36dc81e90a2a00454fda83799f132e32f40
|
[
"MIT"
] | null | null | null |
Section 3 - Preparing Data using SparkSQL/hands-on/Hands-on-3.ipynb
|
Sinha-Ujjawal/Mastering-Big-Data-Analytics-with-PySpark
|
71bea36dc81e90a2a00454fda83799f132e32f40
|
[
"MIT"
] | null | null | null |
Section 3 - Preparing Data using SparkSQL/hands-on/Hands-on-3.ipynb
|
Sinha-Ujjawal/Mastering-Big-Data-Analytics-with-PySpark
|
71bea36dc81e90a2a00454fda83799f132e32f40
|
[
"MIT"
] | null | null | null | 52.814338 | 3,143 | 0.464933 |
[
[
[
"from pyspark.sql import SparkSession, functions as f",
"_____no_output_____"
],
[
"spark = (\n SparkSession\n .builder\n .appName(\"Hands-on-3\")\n .master(\"local[*]\")\n .getOrCreate()\n)",
"_____no_output_____"
]
],
[
[
"### Setting up what we had done in the previous hands-on",
"_____no_output_____"
]
],
[
[
"df_ratings = (\n spark\n .read\n .csv(\n path=\"../../data-sets/ml-latest/ratings.csv\",\n sep=\",\",\n encoding=\"UTF-8\",\n header=True,\n quote='\"',\n schema=\"userId INT, movieId INT, rating DOUBLE, timestamp INT\",\n )\n .withColumnRenamed(\"timestamp\", \"timestamp_unix\")\n .withColumn(\"timestamp\", f.to_timestamp(f.from_unixtime(\"timestamp_unix\")))\n .drop(\"timestamp_unix\")\n)",
"_____no_output_____"
],
[
"df_ratings.show(n=5)\ndf_ratings.printSchema()",
"+------+-------+------+-------------------+\n|userId|movieId|rating| timestamp|\n+------+-------+------+-------------------+\n| 1| 307| 3.5|2009-10-28 02:30:21|\n| 1| 481| 3.5|2009-10-28 02:34:16|\n| 1| 1091| 1.5|2009-10-28 02:34:31|\n| 1| 1257| 4.5|2009-10-28 02:34:20|\n| 1| 1449| 4.5|2009-10-28 02:31:04|\n+------+-------+------+-------------------+\nonly showing top 5 rows\n\nroot\n |-- userId: integer (nullable = true)\n |-- movieId: integer (nullable = true)\n |-- rating: double (nullable = true)\n |-- timestamp: timestamp (nullable = true)\n\n"
],
[
"# As we anyway dropping timestamp_unix, we can directly apply the trasformations on timestamp column\n\ndf_ratings = (\n spark\n .read\n .csv(\n path=\"../../data-sets/ml-latest/ratings.csv\",\n sep=\",\",\n encoding=\"UTF-8\",\n header=True,\n quote='\"',\n schema=\"userId INT, movieId INT, rating DOUBLE, timestamp INT\",\n )\n .withColumn(\"timestamp\", f.to_timestamp(f.from_unixtime(\"timestamp\")))\n)",
"_____no_output_____"
],
[
"df_ratings.show(n=5)\ndf_ratings.printSchema()",
"+------+-------+------+-------------------+\n|userId|movieId|rating| timestamp|\n+------+-------+------+-------------------+\n| 1| 307| 3.5|2009-10-28 02:30:21|\n| 1| 481| 3.5|2009-10-28 02:34:16|\n| 1| 1091| 1.5|2009-10-28 02:34:31|\n| 1| 1257| 4.5|2009-10-28 02:34:20|\n| 1| 1449| 4.5|2009-10-28 02:31:04|\n+------+-------+------+-------------------+\nonly showing top 5 rows\n\nroot\n |-- userId: integer (nullable = true)\n |-- movieId: integer (nullable = true)\n |-- rating: double (nullable = true)\n |-- timestamp: timestamp (nullable = true)\n\n"
],
[
"# We are now going to load movies.csv for furthur analysis\n\ndf_movies = (\n spark\n .read\n .csv(\n path=\"../../data-sets/ml-latest/movies.csv\",\n sep=\",\",\n encoding=\"UTF-8\",\n header=True,\n quote='\"',\n schema=\"movieId INT, title STRING, genres STRING\",\n )\n)",
"_____no_output_____"
],
[
"df_movies.show(n=5)\ndf_movies.printSchema()",
"+-------+--------------------+--------------------+\n|movieId| title| genres|\n+-------+--------------------+--------------------+\n| 1| Toy Story (1995)|Adventure|Animati...|\n| 2| Jumanji (1995)|Adventure|Childre...|\n| 3|Grumpier Old Men ...| Comedy|Romance|\n| 4|Waiting to Exhale...|Comedy|Drama|Romance|\n| 5|Father of the Bri...| Comedy|\n+-------+--------------------+--------------------+\nonly showing top 5 rows\n\nroot\n |-- movieId: integer (nullable = true)\n |-- title: string (nullable = true)\n |-- genres: string (nullable = true)\n\n"
]
],
[
[
"### As we can see we have ellipsis (...) at some places in title and genre column. By default df.show method will truncate long strings with ellipsis (...). We can disable this with truncate=False argument, as follows-",
"_____no_output_____"
]
],
[
[
"df_movies.show(n=15, truncate=False)\ndf_movies.printSchema()",
"+-------+----------------------------------+-------------------------------------------+\n|movieId|title |genres |\n+-------+----------------------------------+-------------------------------------------+\n|1 |Toy Story (1995) |Adventure|Animation|Children|Comedy|Fantasy|\n|2 |Jumanji (1995) |Adventure|Children|Fantasy |\n|3 |Grumpier Old Men (1995) |Comedy|Romance |\n|4 |Waiting to Exhale (1995) |Comedy|Drama|Romance |\n|5 |Father of the Bride Part II (1995)|Comedy |\n|6 |Heat (1995) |Action|Crime|Thriller |\n|7 |Sabrina (1995) |Comedy|Romance |\n|8 |Tom and Huck (1995) |Adventure|Children |\n|9 |Sudden Death (1995) |Action |\n|10 |GoldenEye (1995) |Action|Adventure|Thriller |\n|11 |American President, The (1995) |Comedy|Drama|Romance |\n|12 |Dracula: Dead and Loving It (1995)|Comedy|Horror |\n|13 |Balto (1995) |Adventure|Animation|Children |\n|14 |Nixon (1995) |Drama |\n|15 |Cutthroat Island (1995) |Action|Adventure|Romance |\n+-------+----------------------------------+-------------------------------------------+\nonly showing top 15 rows\n\nroot\n |-- movieId: integer (nullable = true)\n |-- title: string (nullable = true)\n |-- genres: string (nullable = true)\n\n"
]
],
[
[
"### Now we are going to work with filterring the data aka: Dicing and Slicing",
"_____no_output_____"
]
],
[
[
"# Let's filter on genre with value \"Action\" in movies dataframe\ndf_movies.where(\"genres\" == \"Action\").show() # This is going to fail",
"_____no_output_____"
]
],
[
[
"### As you can see, we are unable to perform this action, as we require th condition to have Column object instead of string. We can fix this by using the SQL expression instead of the pythonic way of representing condition",
"_____no_output_____"
]
],
[
[
"df_movies.where('genres = \"Action\"').show() # Notice the quotes and single equals to \"=\"",
"+-------+--------------------+------+\n|movieId| title|genres|\n+-------+--------------------+------+\n| 9| Sudden Death (1995)|Action|\n| 71| Fair Game (1995)|Action|\n| 204|Under Siege 2: Da...|Action|\n| 251| Hunted, The (1995)|Action|\n| 667|Bloodsport 2 (a.k...|Action|\n| 980|Yes, Madam (a.k.a...|Action|\n| 1102|American Strays (...|Action|\n| 1110| Bird of Prey (1996)|Action|\n| 1170|Best of the Best ...|Action|\n| 1424| Inside (1996)|Action|\n| 1434|Stranger, The (1994)|Action|\n| 1497| Double Team (1997)|Action|\n| 1599| Steel (1997)|Action|\n| 2196| Knock Off (1998)|Action|\n| 2258| Master, The (1984)|Action|\n| 2534| Avalanche (1978)|Action|\n| 2756|Wanted: Dead or A...|Action|\n| 2817|Aces: Iron Eagle ...|Action|\n| 2965|Omega Code, The (...|Action|\n| 3283|Minnie and Moskow...|Action|\n+-------+--------------------+------+\nonly showing top 20 rows\n\n"
]
],
[
[
"### As you can see, we can use proper SQL expression for filterring, and it works",
"_____no_output_____"
],
[
"### Another way to do the same thing is to convert the string \"genre\" to spark column, as follows-",
"_____no_output_____"
]
],
[
[
"df_movies.where(f.col(\"genres\") == \"Action\").show(n=5, truncate=False)",
"+-------+-----------------------------------------------------------+------+\n|movieId|title |genres|\n+-------+-----------------------------------------------------------+------+\n|9 |Sudden Death (1995) |Action|\n|71 |Fair Game (1995) |Action|\n|204 |Under Siege 2: Dark Territory (1995) |Action|\n|251 |Hunted, The (1995) |Action|\n|667 |Bloodsport 2 (a.k.a. Bloodsport II: The Next Kumite) (1996)|Action|\n+-------+-----------------------------------------------------------+------+\nonly showing top 5 rows\n\n"
]
],
[
[
"### I prefer the later, as it's more pythonic",
"_____no_output_____"
],
[
"### As we can see the genre column has values seperated by pipe \"|\" symbol. I would like to have it as an array instead of a single string. For doing that I will create a new column called genre_array, and use f.split to apply transformation on genre column to split on the symbol \"|\"",
"_____no_output_____"
]
],
[
[
"df_movies_with_genre = (\n df_movies\n .withColumn(\"genres_array\", f.split(\"genres\", \"|\"))\n)\n\ndf_movies_with_genre.show(n=5)\ndf_movies_with_genre.printSchema()",
"+-------+--------------------+--------------------+--------------------+\n|movieId| title| genres| genres_array|\n+-------+--------------------+--------------------+--------------------+\n| 1| Toy Story (1995)|Adventure|Animati...|[A, d, v, e, n, t...|\n| 2| Jumanji (1995)|Adventure|Childre...|[A, d, v, e, n, t...|\n| 3|Grumpier Old Men ...| Comedy|Romance|[C, o, m, e, d, y...|\n| 4|Waiting to Exhale...|Comedy|Drama|Romance|[C, o, m, e, d, y...|\n| 5|Father of the Bri...| Comedy|[C, o, m, e, d, y, ]|\n+-------+--------------------+--------------------+--------------------+\nonly showing top 5 rows\n\nroot\n |-- movieId: integer (nullable = true)\n |-- title: string (nullable = true)\n |-- genres: string (nullable = true)\n |-- genres_array: array (nullable = true)\n | |-- element: string (containsNull = true)\n\n"
]
],
[
[
"### As we can see, it didn't work as expected. This happened because the second argument of f.split is actually a regex. And in the world of regex, \"|\" character is a special symbol, hence it needs to be excaped.",
"_____no_output_____"
]
],
[
[
"df_movies_with_genre = (\n df_movies\n .withColumn(\"genres_array\", f.split(\"genres\", \"\\|\")) # notice the escape symbol \"\\\"\n)\n\ndf_movies_with_genre.show(n=5, truncate=False)\ndf_movies_with_genre.printSchema()",
"+-------+----------------------------------+-------------------------------------------+-------------------------------------------------+\n|movieId|title |genres |genres_array |\n+-------+----------------------------------+-------------------------------------------+-------------------------------------------------+\n|1 |Toy Story (1995) |Adventure|Animation|Children|Comedy|Fantasy|[Adventure, Animation, Children, Comedy, Fantasy]|\n|2 |Jumanji (1995) |Adventure|Children|Fantasy |[Adventure, Children, Fantasy] |\n|3 |Grumpier Old Men (1995) |Comedy|Romance |[Comedy, Romance] |\n|4 |Waiting to Exhale (1995) |Comedy|Drama|Romance |[Comedy, Drama, Romance] |\n|5 |Father of the Bride Part II (1995)|Comedy |[Comedy] |\n+-------+----------------------------------+-------------------------------------------+-------------------------------------------------+\nonly showing top 5 rows\n\nroot\n |-- movieId: integer (nullable = true)\n |-- title: string (nullable = true)\n |-- genres: string (nullable = true)\n |-- genres_array: array (nullable = true)\n | |-- element: string (containsNull = true)\n\n"
]
],
[
[
"### Now for we want to create a single row for every movie, genre pair. In order to that, we will need to \"explode\" the genres_array column using f.explode",
"_____no_output_____"
]
],
[
[
"df_movies_with_genre = (\n df_movies\n .withColumn(\"genres_array\", f.split(\"genres\", \"\\|\")) # notice the escape symbol \"\\\"\n .withColumn(\"genre\", f.explode(\"genres_array\"))\n)\n\ndf_movies_with_genre.show(n=15, truncate=False)\ndf_movies_with_genre.printSchema()",
"+-------+----------------------------------+-------------------------------------------+-------------------------------------------------+---------+\n|movieId|title |genres |genres_array |genre |\n+-------+----------------------------------+-------------------------------------------+-------------------------------------------------+---------+\n|1 |Toy Story (1995) |Adventure|Animation|Children|Comedy|Fantasy|[Adventure, Animation, Children, Comedy, Fantasy]|Adventure|\n|1 |Toy Story (1995) |Adventure|Animation|Children|Comedy|Fantasy|[Adventure, Animation, Children, Comedy, Fantasy]|Animation|\n|1 |Toy Story (1995) |Adventure|Animation|Children|Comedy|Fantasy|[Adventure, Animation, Children, Comedy, Fantasy]|Children |\n|1 |Toy Story (1995) |Adventure|Animation|Children|Comedy|Fantasy|[Adventure, Animation, Children, Comedy, Fantasy]|Comedy |\n|1 |Toy Story (1995) |Adventure|Animation|Children|Comedy|Fantasy|[Adventure, Animation, Children, Comedy, Fantasy]|Fantasy |\n|2 |Jumanji (1995) |Adventure|Children|Fantasy |[Adventure, Children, Fantasy] |Adventure|\n|2 |Jumanji (1995) |Adventure|Children|Fantasy |[Adventure, Children, Fantasy] |Children |\n|2 |Jumanji (1995) |Adventure|Children|Fantasy |[Adventure, Children, Fantasy] |Fantasy |\n|3 |Grumpier Old Men (1995) |Comedy|Romance |[Comedy, Romance] |Comedy |\n|3 |Grumpier Old Men (1995) |Comedy|Romance |[Comedy, Romance] |Romance |\n|4 |Waiting to Exhale (1995) |Comedy|Drama|Romance |[Comedy, Drama, Romance] |Comedy |\n|4 |Waiting to Exhale (1995) |Comedy|Drama|Romance |[Comedy, Drama, Romance] |Drama |\n|4 |Waiting to Exhale (1995) |Comedy|Drama|Romance |[Comedy, Drama, Romance] |Romance |\n|5 |Father of the Bride Part II (1995)|Comedy |[Comedy] |Comedy |\n|6 |Heat (1995) |Action|Crime|Thriller |[Action, Crime, Thriller] |Action |\n+-------+----------------------------------+-------------------------------------------+-------------------------------------------------+---------+\nonly showing top 15 rows\n\nroot\n |-- movieId: integer (nullable = true)\n |-- title: string (nullable = true)\n |-- genres: string (nullable = true)\n |-- genres_array: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- genre: string (nullable = true)\n\n"
]
],
[
[
"### As we can see, each movie is \"exploded\" across every genre type. But it's hard to see, so we will select the rows we are interested in before showing",
"_____no_output_____"
]
],
[
[
"df_movies_with_genre = (\n df_movies\n .withColumn(\"genres_array\", f.split(\"genres\", \"\\|\")) # notice the escape symbol \"\\\"\n .withColumn(\"genre\", f.explode(\"genres_array\"))\n .select(\"movieId\", \"title\", \"genre\")\n)\n\ndf_movies_with_genre.show(n=15, truncate=False)\ndf_movies_with_genre.printSchema()",
"+-------+----------------------------------+---------+\n|movieId|title |genre |\n+-------+----------------------------------+---------+\n|1 |Toy Story (1995) |Adventure|\n|1 |Toy Story (1995) |Animation|\n|1 |Toy Story (1995) |Children |\n|1 |Toy Story (1995) |Comedy |\n|1 |Toy Story (1995) |Fantasy |\n|2 |Jumanji (1995) |Adventure|\n|2 |Jumanji (1995) |Children |\n|2 |Jumanji (1995) |Fantasy |\n|3 |Grumpier Old Men (1995) |Comedy |\n|3 |Grumpier Old Men (1995) |Romance |\n|4 |Waiting to Exhale (1995) |Comedy |\n|4 |Waiting to Exhale (1995) |Drama |\n|4 |Waiting to Exhale (1995) |Romance |\n|5 |Father of the Bride Part II (1995)|Comedy |\n|6 |Heat (1995) |Action |\n+-------+----------------------------------+---------+\nonly showing top 15 rows\n\nroot\n |-- movieId: integer (nullable = true)\n |-- title: string (nullable = true)\n |-- genre: string (nullable = true)\n\n"
]
],
[
[
"### Now it's much better to visualize",
"_____no_output_____"
],
[
"### Now let's list out all the distinct genre using .distinct",
"_____no_output_____"
]
],
[
[
"available_genres = df_movies_with_genre.select(\"genre\").distinct()\navailable_genres.show(truncate=False)",
"+------------------+\n|genre |\n+------------------+\n|Crime |\n|Romance |\n|Thriller |\n|Adventure |\n|Drama |\n|War |\n|Documentary |\n|Fantasy |\n|Mystery |\n|Musical |\n|Animation |\n|Film-Noir |\n|(no genres listed)|\n|IMAX |\n|Horror |\n|Western |\n|Comedy |\n|Children |\n|Action |\n|Sci-Fi |\n+------------------+\n\n"
]
],
[
[
"### We can see all the distinct genres, there is a value- (no genres listed). Let's figure out all the movies with (no genres listed)",
"_____no_output_____"
]
],
[
[
"df_movies_with_no_genres = (\n df_movies\n .filter(f.col(\"genres\") == \"(no genres listed)\")\n)\nprint(f\"Total: {df_movies_with_no_genres.count()} movie(s) does not have genres\")\ndf_movies_with_no_genres.show(truncate=False)",
"Total: 4266 movie(s) does not have genres\n+-------+-----------------------------------------------+------------------+\n|movieId|title |genres |\n+-------+-----------------------------------------------+------------------+\n|83773 |Away with Words (San tiao ren) (1999) |(no genres listed)|\n|83829 |Scorpio Rising (1964) |(no genres listed)|\n|84768 |Glitterbug (1994) |(no genres listed)|\n|86493 |Age of the Earth, The (A Idade da Terra) (1980)|(no genres listed)|\n|87061 |Trails (Veredas) (1978) |(no genres listed)|\n|91246 |Milky Way (Tejút) (2007) |(no genres listed)|\n|92435 |Dancing Hawk, The (Tanczacy jastrzab) (1978) |(no genres listed)|\n|92641 |Warsaw Bridge (Pont de Varsòvia) (1990) |(no genres listed)|\n|94431 |Ella Lola, a la Trilby (1898) |(no genres listed)|\n|94657 |Turkish Dance, Ella Lola (1898) |(no genres listed)|\n|95541 |Blacksmith Scene (1893) |(no genres listed)|\n|95750 |Promise of the Flesh (Yukcheui yaksok) (1975) |(no genres listed)|\n|96479 |Nocturno 29 (1968) |(no genres listed)|\n|96651 |Les hautes solitudes (1974) |(no genres listed)|\n|113472 |Direct from Brooklyn (1999) |(no genres listed)|\n|113545 |Primus Hallucino-Genetics Live 2004 (2004) |(no genres listed)|\n|114335 |La cravate (1957) |(no genres listed)|\n|114587 |Glumov's Diary (Dnevnik Glumova) (1923) |(no genres listed)|\n|114723 |At Land (1944) |(no genres listed)|\n|114725 |Study in Choreography for Camera, A (1945) |(no genres listed)|\n+-------+-----------------------------------------------+------------------+\nonly showing top 20 rows\n\n"
],
[
"spark.stop()",
"_____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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a8fb5138af5560af866c56828415566f3cdb1d8
| 24,416 |
ipynb
|
Jupyter Notebook
|
topics/3a_data.ipynb
|
misja/programmeren
|
9abf7fae0b810f1a09d97d7ea18936766913c5df
|
[
"MIT"
] | 4 |
2020-09-03T09:12:59.000Z
|
2021-12-15T23:15:45.000Z
|
topics/3a_data.ipynb
|
misja/programmeren
|
9abf7fae0b810f1a09d97d7ea18936766913c5df
|
[
"MIT"
] | 40 |
2020-09-07T06:15:16.000Z
|
2021-12-13T22:01:41.000Z
|
topics/3a_data.ipynb
|
misja/programmeren
|
9abf7fae0b810f1a09d97d7ea18936766913c5df
|
[
"MIT"
] | 4 |
2021-02-01T20:02:57.000Z
|
2021-08-10T09:08:39.000Z
| 23.750973 | 528 | 0.50299 |
[
[
[
"# Data\n\nData en handelingen op data",
"_____no_output_____"
],
[
"## Informatica\n\neen taal leren $\\sim$ **syntax** (noodzakelijk, maar niet het punt)\n\n... informatica studeren $\\sim$ **semantiek** (leren hoe machines denken!)\n",
"_____no_output_____"
],
[
"Een programmeertaal als Python leren heeft alles te maken met syntax waarmee je handelingen kan schrijven die een machine moet uitvoeren. Maar hiervoor heb je eerst andere kennis nodig, kennis die alles te maken heeft met wat de machine (bijvoorbeeld, jouw laptop) doet.",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"We gaan stap voor stap ontdekken wat er zich in de machine afspeelt en gaan we kijken naar data en handelingen op (of de verwerking van) data.",
"_____no_output_____"
],
[
"## Handelingen en data",
"_____no_output_____"
]
],
[
[
"x = 41\ny = x + 1",
"_____no_output_____"
]
],
[
[
"Laten we om te beginnen de volgende twee variabelen `x` en `y` ieder een waarde toekennen. Deze waarden (`41` en `42`) worden in het geheugen opgeslagen.",
"_____no_output_____"
],
[
"## Achter het doek\n\n",
"_____no_output_____"
],
[
"Stel je een variabele voor als een doos: de inhoud van de doos is de waarde (bijvoorbeeld `41` of `42` in ons geval) met extra informatie over het *type* van de waarde (een `int` wat staat voor *integer*, een geheel getal) en een geheugenlocatie (LOC).",
"_____no_output_____"
],
[
"### Geheugen\n\n",
"_____no_output_____"
],
[
"Geheugen is een hele lange lijst van dit soort dozen, elk met een naam, waarde, type en geheugenlocatie.",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"Random Access Memory ([RAM](https://nl.wikipedia.org/wiki/Dynamic_random-access_memory)) is waar variabelen worden opgeslagen, een kaart zoals je deze hier ziet zit ook in jouw computer! Als je het zwarte materiaal voorzichtig zou weghalen zal een (microscopisch klein) raster zichtbaar worden.",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"Horizontaal zie je de *bitlijnen*, of adresregels (de geheugenlokatie) en verticaal de *woordlijnen* (of dataregels). Elk kruispunt is een [condensator](https://nl.wikipedia.org/wiki/Condensator) die elektrisch geladen of ongeladen kan zijn.",
"_____no_output_____"
],
[
"### Bits\n\n",
"_____no_output_____"
],
[
"Zo'n punt (een condensator) dat geladen (1 of `True`) of ongeladen (0 of `False`) kan zijn wordt een *bit* genoemd. Dit is de kleinst mogelijk informatie-eenheid!",
"_____no_output_____"
],
[
"### Bytes\n\n",
"_____no_output_____"
],
[
"Je zal ook vaak horen over *bytes* en dit is een verzameling van 8 aaneengesloten *bits* op een adresregel. Waarom 8 en niet 5, 10, 12 of meer (of minder) zal je je misschien afvragen? Dit is historisch bepaald en heeft alles te maken met het minimaal aantal bits dat ooit nodig was om een bepaalde set van karakters (letters en andere tekens) te kunnen representeren ([ASCII](https://nl.wikipedia.org/wiki/ASCII_(tekenset)) om precies te zijn). Maak je geen zorgen om wat dit precies betekent, we komen hier nog op terug!",
"_____no_output_____"
],
[
"### Woord?\n\n",
"_____no_output_____"
],
[
"*Woord* in woordregel is niet een woord als in een zin (taal) maar een term die staat voor de [natuurlijke eenheid](https://en.wikipedia.org/wiki/Word_(computer_architecture)) van informatie voor een bepaalde computerarchitectuur. Tegenwoordig is deze voor de meeste systemen 64-bit, dit wordt ook wel de *adresruimte* van een architectuur genoemd.\n\nDeze eenheid is van belang want het bepaalt bijvoorbeeld het grootste gehele getal dat kan worden opgeslagen. Maar hoe komen we van bits naar bytes en vervolgens tot getallen en andere data zul je je afvragen? Dit zul je later zien, eerst gaan we kijken naar de verschillende typen data die we kunnen onderscheiden.",
"_____no_output_____"
],
[
"## Datatypes\n\n*Alle* talen hebben datatypes!\n\n| Type | Voorbeeld | Wat is het? |\n|---------|-------------------|----------------------------------------------------------------------------------|\n| `float` | `3.14` of `3.0` | decimale getallen |\n| `int` | `42` of `10**100` | gehele getallen |\n| `bool` | `True` of `False` | het resultaat van een test of vergelijking met: `==`, `!=`, `<`, `>`, `<=`, `>=` |\n",
"_____no_output_____"
]
],
[
[
"type(42.0)",
"_____no_output_____"
]
],
[
[
"Dit zijn de eerste datatypes waar we kennis mee gaan maken en ze komen aardig overeen met wat wij (mensen!) kunnen onderscheiden, bijvoorbeeld gehele- of decimale getallen. \n\nOok een `bool`(ean) is uiteindelijk een getal: als we `False` typen zal Python dit lezen als 0. `True` en `False`is *syntax* (!) om het voor ons makkelijker te maken, maar *semantisch* staat het voor 1 en 0 (in ieder geval voor Python!).\n\nMet de de *functie* `type(x)` kan je opvragen welk type Python denkt dat de waarde heeft.",
"_____no_output_____"
],
[
"## Operatoren\n\nSpeciale tekens die alles te maken hebben met handelingen op data.",
"_____no_output_____"
],
[
"### Python operatoren\n\n| Betekenis | |\n|-----------------------------------|---------------------------------|\n| groepering | `(` `)` |\n| machtsverheffing | `**` |\n| vermenigvuldiging, modulo, deling | `*` `%` `/` `//` |\n| optelling, aftrekking | `+` `-` |\n| vergelijking | `==` `!=`, `<`, `>`, `<=`, `>=` |\n| toekenning | `=` |\n",
"_____no_output_____"
],
[
"Net als bij rekenen moet je hier rekening houden met de bewerkingsvolgorde, hier zijn ze van meest naar minst belangrijk weergegeven. Het is *niet* nodig deze volgorde te onthouden, onze tip is waarden te groepereren in plaats van je zorgen te maken over de bewerkingsvolgorde.\n\nBij twee operatoren moeten we even stilstaan omdat niet direct duidelijk is wat ze doen, de modulo operator `%` en de *integer* deling `//` (in tegenstelling tot de gewone deling `/`).",
"_____no_output_____"
],
[
"### Modulo operator `%`\n\n- `7 % 3`\n- `9 % 3`\n\n`x % y` is het **restant** wanneer `x` door `y` wordt gedeeld",
"_____no_output_____"
]
],
[
[
"11 % 3",
"_____no_output_____"
]
],
[
[
"Syntax check! Het maakt niet uit of je `x%2` of `x % 2` schrijft (met spaties), Python weet wat je bedoelt :)",
"_____no_output_____"
],
[
"#### Voorbeelden\n\n| | Test | Mogelijke waarden van `x` | |\n|---|---------------|---------------------------|----------------------------------------------|\n| A | `x % 2 == 0` | | |\n| B | `x % 2 == 1` | | |\n| C | `x % 4 == 0` | | Wat gebeurt hier als `x` een jaartal is? |\n| D | `x % 24 == 0` | | Wat gebeurt hier als `x` een aantal uren is? |\n",
"_____no_output_____"
]
],
[
[
"3 % 2 == 0",
"_____no_output_____"
]
],
[
[
"A en B hebben alles te maken met even en oneven getallen, voorbeeld C met schrikkeljaren en voorbeeld D misschien met het digitaal display van jouw wekker?",
"_____no_output_____"
],
[
"### Integer deling\n\n- `7 // 3`\n- `9 // 3`\n- `30 // 7`\n\n`x // y` is als `x / y` maar dan **afgerond** tot een geheel getal",
"_____no_output_____"
]
],
[
[
"30 // 7",
"_____no_output_____"
]
],
[
[
"De `//` operator rondt af naar beneden, maar dan ook volledig naar beneden! In het Engels staat de `//` operator naast \"integer division\" ook bekend als \"floor division\": floor als in vloer (het laagste) in tegenstelling tot ceiling (plafond, hoogste). Maar er is meer aan de hand, want je zult zien dat `//` veel lijkt op de `%` operator!",
"_____no_output_____"
],
[
"De verdeling van 30 in veelheden van 7:\n\n```python\n30 == (4) * 7 + (2)\n```",
"_____no_output_____"
],
[
"Zouden we dit kunnen generaliseren tot een algemene regel met behulp van de operatoren `//` en `%` die we nu hebben leren kennen?",
"_____no_output_____"
],
[
"De verdeling van `x` in veelheden van `y`\n\n```python\nx == (x // y) * y + (x % y)\n```",
"_____no_output_____"
],
[
"en dit ingevuld voor ons voorbeeld:\n\n```python\n30 = (30 // 7) * 7 + (30 % 7)\n```",
"_____no_output_____"
],
[
"En daar is de `%` operator weer :) Je zult later zien dat het gebruik van `%` en `//` bijzonder handig is als we gaan rekenen met ... bits!\n\nKort samengevat: de `//` operator rondt volledig naar beneden af (door alles achter de komma weg te laten).",
"_____no_output_____"
],
[
"### Wat is gelijk?\n\n| Een waarde TOEKENNEN | IS NIET gelijk aan | een waarde TESTEN |\n|----------------------|--------------------|-------------------|\n| `=` | `!=` | `==` |\n",
"_____no_output_____"
],
[
"De enkele `=` ken je van wiskunde waar je $a = 1$ zal uitspreken als \"a is gelijk aan 1\". Bij programmeertalen is dit anders en wordt \"ken aan a de waarde 1 toe\" bedoeld. Om te testen of de waarde gelijk is aan een andere waarde wordt `==` gebruikt (en `!=` voor is *niet* gelijk aan).",
"_____no_output_____"
],
[
"### Identiteit\n\nIs `==` een test op *waarde* of *identiteit* (de geheugenlokatie waar de waarde *leeft*)?\n\nSommige talen hebben `===`!",
"_____no_output_____"
],
[
"Er is een verschil tussen testen op *waarde* en testen op *identiteit* (of het hetzelfde \"doos\" is, de geheugenlokatie). Python heeft geen `===` (zoals Javascript, een programeertal gebruikt in browsers) maar heeft speciaal voor dit geval `is`, bijvoorbeeld `a is b` om te vergelijken op basis van identiteit.\n\nVergelijken op waarde of identiteit met `==` kan erg verschillen per taal. Voor Java (een veel gebruikte programmeertaal) betekent `==` een test op *identiteit*. Python heeft gekozen om `==` een test op gelijkheid van *waarde* te laten zijn. Dit ligt misschien het dichtst bij hoe mensen denken, zeker als het gaat om vergelijken van bijvoorbeeld getallen of tekst.\n\nEen voorbeeld om het verschil duidelijk te maken.",
"_____no_output_____"
]
],
[
[
"a = 3141592\nb = 3141592",
"_____no_output_____"
]
],
[
[
"Gegeven twee variabelen `a` en `b` met dezelfde waarde",
"_____no_output_____"
]
],
[
[
"a == b",
"_____no_output_____"
]
],
[
[
"zal inderdaar blijken dat `a` en `b` een gelijke *waarde* hebben.",
"_____no_output_____"
]
],
[
[
"a is b",
"_____no_output_____"
]
],
[
[
"maar een vergelijking op basis van *identiteit* zal niet slagen...",
"_____no_output_____"
]
],
[
[
"print(id(a))\nprint(id(b))",
"139926283797584\n139926283797392\n"
]
],
[
[
"`id(x)` geeft de adreslokatie van een waarde terug. Je kan zien dat `a` en `b` anders zijn, hoewel ze tóch dezelfe waarde hebben! (let op, deze geheugenlokaties kunnen verschillen met jouw computer!) ",
"_____no_output_____"
],
[
"## Quiz\n\nVoer de volgende regels uit:\n\n```python\nx = 41\ny = x + 1\nz = x + y\n```\n\nWelke waarden hebben `x`, `y` en `z`?",
"_____no_output_____"
]
],
[
[
"x = 41\ny = x + 1\nz = x + y\n\nprint(x, y, z)",
"41 42 83\n"
]
],
[
[
"Voer vervolgens de volgende regel uit:\n\n```python\nx = x + y\n```\n\nWelke waarden hebben `x`, `y` en `z` nu?",
"_____no_output_____"
]
],
[
[
"x = x + y\n\nprint(x, y, z)",
"83 42 83\n"
]
],
[
[
"### Achter de schermen\n\n```python\nx = 41\ny = x + 1\nz = x + y\n```\n\nIn het geheugen:\n\n",
"_____no_output_____"
],
[
"De drie variabelen `x`, `y` en `z` zijn nu in het geheugen bewaard op drie verschillende lokaties.",
"_____no_output_____"
],
[
"Laatste stap:\n\n```python\nx = x + y\n```\n\nIn het geheugen:\n\n",
"_____no_output_____"
],
[
"Met de laatste stap wijzigen we de waarde van `x` en dit betekent dat de oorspronkelijke lokatie wordt gewist en de nieuwe waarde in het geheugen wordt gezet, op een nieuwe lokatie!\n\nJe kan de identiteit (de geheugenlokatie) in Python opvragen met `id(x)`. Probeer dit eens met `x` voor en na de laatste operatie en je zal zien dat ze verschillend zijn. Het wissen of verwijderen van een waarde kan je doen met `del x` (dus zonder de haakjes `()`).",
"_____no_output_____"
],
[
"### Extra\n\n```python\na = 11 // 2\nb = a % 3\nc = b ** a+b * a\n```\n\nWelke waarden hebben `a`, `b` en `c`?",
"_____no_output_____"
]
],
[
[
"a = 11 // 2\nb = a % 3\nc = b ** a+b * a",
"_____no_output_____"
],
[
"print(a, b, c)",
"5 2 42\n"
]
],
[
[
"## Cultuur\n\n",
"_____no_output_____"
],
[
"Het boek [The Hitchhiker's Guide to the Galaxy](https://en.wikipedia.org/wiki/The_Hitchhiker%27s_Guide_to_the_Galaxy) van [Douglas Adams](https://en.wikipedia.org/wiki/Douglas_Adams) heeft sporen nagelaten in onder andere informatica: de kans is groot dat je in voorbeelden of uitwerkingen het getal 42 tegenkomt. Maar ook in het gewone leven als je op [25 mei](https://en.wikipedia.org/wiki/Towel_Day) mensen met een handdoek ziet lopen ...",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4a8fecd79dfa3d5956e4a7351e517facc2c4016a
| 2,151 |
ipynb
|
Jupyter Notebook
|
code/week8_dataingestion/Kafka Sample Producer.ipynb
|
kaopanboonyuen/2110446_DataScience_2021s2
|
511611edf2c84a07e94cc9496858f805e85a71c3
|
[
"MIT"
] | 15 |
2022-01-11T06:07:28.000Z
|
2022-02-02T17:58:55.000Z
|
code/week8_dataingestion/Kafka Sample Producer.ipynb
|
kaopanboonyuen/2110446_DataScience_2021s2
|
511611edf2c84a07e94cc9496858f805e85a71c3
|
[
"MIT"
] | null | null | null |
code/week8_dataingestion/Kafka Sample Producer.ipynb
|
kaopanboonyuen/2110446_DataScience_2021s2
|
511611edf2c84a07e94cc9496858f805e85a71c3
|
[
"MIT"
] | 7 |
2022-02-18T18:35:48.000Z
|
2022-03-26T06:54:22.000Z
| 20.292453 | 114 | 0.534635 |
[
[
[
"# import required libraries\nfrom kafka import KafkaProducer\nimport time",
"_____no_output_____"
],
[
"# Connect to kafka broker running in your local host (docker). Change this to your kafka broker if needed\nkafka_broker = '34.87.22.17:9092'",
"_____no_output_____"
],
[
"producer = KafkaProducer(bootstrap_servers=[kafka_broker])",
"_____no_output_____"
],
[
"for i in range(100):\n s = 'message #{} from producer-0'.format(i)\n producer.send('sample', s.encode('utf-8'))\n time.sleep(2)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4a9019c9d3c6f7edf5ddcdf5ef94e5a9de99a333
| 7,025 |
ipynb
|
Jupyter Notebook
|
examples/pvi_example.ipynb
|
JeffRisberg/PLite.jl
|
223c00d58ba083528577985c94f6d7b4b0a84a7a
|
[
"MIT"
] | null | null | null |
examples/pvi_example.ipynb
|
JeffRisberg/PLite.jl
|
223c00d58ba083528577985c94f6d7b4b0a84a7a
|
[
"MIT"
] | 1 |
2015-12-04T04:12:16.000Z
|
2015-12-04T04:12:16.000Z
|
examples/pvi_example.ipynb
|
JeffRisberg/PLite.jl
|
223c00d58ba083528577985c94f6d7b4b0a84a7a
|
[
"MIT"
] | 3 |
2015-10-15T01:00:30.000Z
|
2021-07-04T09:07:41.000Z
| 25.827206 | 407 | 0.57694 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a9026e00fe3ae8b742a8c5b5a37900f9d0ee922
| 11,460 |
ipynb
|
Jupyter Notebook
|
docs/examples/streaks.ipynb
|
oarcher/xsarsea
|
f2bc1c3559a540b95c65675996e13cbc2c59e2cc
|
[
"MIT"
] | null | null | null |
docs/examples/streaks.ipynb
|
oarcher/xsarsea
|
f2bc1c3559a540b95c65675996e13cbc2c59e2cc
|
[
"MIT"
] | null | null | null |
docs/examples/streaks.ipynb
|
oarcher/xsarsea
|
f2bc1c3559a540b95c65675996e13cbc2c59e2cc
|
[
"MIT"
] | null | null | null | 32.836676 | 227 | 0.616318 |
[
[
[
"# Streaks analysis\n\n\nStreaks analysis is done by [Koch (20004)](https://www.climate-service-center.de/imperia/md/content/gkss/institut_fuer_kuestenforschung/ksd/paper/kochw_ieee_2004.pdf) algorithm implementation.\n",
"_____no_output_____"
]
],
[
[
"# import needed modules\nimport xsar\nimport xsarsea\nimport xsarsea.gradients\n\nimport xarray as xr\nimport numpy as np\nimport scipy\nimport os\nimport time\n\nimport logging\nlogging.basicConfig()\nlogging.getLogger('xsar.utils').setLevel(logging.DEBUG)\nlogging.getLogger('xsarsea.streaks').setLevel(logging.DEBUG)\n\nimport holoviews as hv\nhv.extension('bokeh')\nimport geoviews as gv\nfrom holoviews.operation.datashader import rasterize\n",
"_____no_output_____"
],
[
"# open a file a 100m \nfilename = xsar.get_test_file('S1A_IW_GRDH_1SDV_20170907T103020_20170907T103045_018268_01EB76_Z010.SAFE') # irma\n#filename = xsar.get_test_file('S1B_IW_GRDH_1SDV_20181013T062322_20181013T062347_013130_018428_Z000.SAFE') # bz\nfilename=xsar.get_test_file('S1B_IW_GRDH_1SDV_20211024T051203_20211024T051228_029273_037E47_Z010.SAFE')\n#filename=xsar.get_test_file('S1A_IW_GRDH_1SDV_20170720T112706_20170720T112735_017554_01D5C2_Z010.SAFE') # subswath\nsar_ds = xsar.open_dataset(filename,resolution='100m').isel(atrack=slice(20,None,None),xtrack=slice(20,None,None)) # isel to skip bad image edge\n\n# add detrended sigma0\nsar_ds['sigma0_detrend'] = xsarsea.sigma0_detrend(sar_ds.sigma0, sar_ds.incidence)\n# apply land mask\nland_mask = sar_ds['land_mask'].compute()\nsar_ds['sigma0_detrend'] = xr.where(land_mask, np.nan, sar_ds['sigma0_detrend']).transpose(*sar_ds['sigma0_detrend'].dims).compute()\n",
"_____no_output_____"
]
],
[
[
"## General overview\n\nGradients direction analysis is done by moving a window over the image. [xsarsea.gradients.Gradients](../basic_api.rst#xsarsea.gradients.Gradients) allow multiple windows sizes and resolutions.\n\n`sar_ds` is a IW_GRDH SAFE with a pixel size of 10m at full resolution. So to compute compute gradients with windows size of 16km and 32km, we need to use `windows_sizes=[1600,3200]`\n\n`sar_ds` resolution is 100m, so if we want to compute gradients at 100m an 200m, we need to use `downscales_factors=[1,2]`",
"_____no_output_____"
]
],
[
[
"gradients = xsarsea.gradients.Gradients(sar_ds['sigma0_detrend'].sel(pol='VV'), windows_sizes=[1600,3200], downscales_factors=[1,2])\n\n# get gradients histograms as an xarray dataset\nhist = gradients.histogram\n\n# get orthogonals gradients\nhist['angles'] = hist['angles'] + np.pi/2\n\n#mean\nhist_mean = hist.mean(['downscale_factor','window_size'])\n\n# mean, and smooth\nhist_mean_smooth = hist_mean.copy()\nhist_mean_smooth['weight'] = xsarsea.gradients.circ_smooth(hist_mean_smooth['weight'])\n\n# smooth only\nhist_smooth = hist.copy()\nhist_smooth['weight'] = xsarsea.gradients.circ_smooth(hist_smooth['weight'])\n\n# select histogram peak\niangle = hist_mean_smooth['weight'].fillna(0).argmax(dim='angles')\nstreaks_dir = hist_mean_smooth.angles.isel(angles=iangle)\nstreaks_weight = hist_mean_smooth['weight'].isel(angles=iangle)\nstreaks = xr.merge([dict(angle=streaks_dir,weight=streaks_weight)]).drop('angles')\n\n\n# convert from image convention (rad=0=atrack) to geographic convention (deg=0=north)\n# select needed variables in original dataset, and map them to streaks dataset\nstreaks_geo = sar_ds[['longitude','latitude','ground_heading']].interp(\n atrack=streaks.atrack,\n xtrack=streaks.xtrack, \n method='nearest')\n\nstreaks_geo['weight'] = streaks['weight']\n\n# convert directions from image convention to geographic convention\n# note that there is no clockwise swapping, because image axes are transposed\nstreaks_geo['streaks_dir'] = np.rad2deg(streaks['angle']) + streaks_geo['ground_heading']\n\nstreaks_geo = streaks_geo.compute()\n\n# plot. Note that hv.VectorField only accept radians, and 0 is West, so we need to reconvert degrees to radians when calling ...\ngv.tile_sources.Wikipedia * gv.VectorField(\n (\n streaks_geo['longitude'], \n streaks_geo['latitude'], \n np.pi/2 -np.deg2rad(streaks_geo['streaks_dir']), \n streaks_geo['weight']\n )\n).opts(pivot='mid', arrow_heads=False, tools=['hover'], magnitude='Magnitude')\n\n",
"_____no_output_____"
]
],
[
[
"> **_WARNING:_** `hv.VectorField` and `gv.VectorField` don't use degrees north convention, but radian convention, with 0 = East or right\n> So, to use them with degrees north, you have to convert them to gradients with \n> ```python\n> np.pi/2 -np.deg2rad(deg_north)\n> ```\n>",
"_____no_output_____"
],
[
"## Digging into intermediate computations \n\n### streaks_geo\n\n`streaks_geo` is a `xarray.Dataset`, with `latitude`, `longitude` and `streaks_dir` (0=deg north) variables.\n\nIt has dims `('atrack', 'xtrack')`, with a spacing corresponding to the first windows size, according to the window step.",
"_____no_output_____"
]
],
[
[
"streaks_geo",
"_____no_output_____"
]
],
[
[
"### streaks\n\n`streaks_geo` was computed from `streaks` (also a `xarray.Dataset`). The main difference is that the `angle` variable from `streaks` is in radians, in *image convention* (ie rad=0 is in atrack direction) \n\n",
"_____no_output_____"
]
],
[
[
"streaks",
"_____no_output_____"
]
],
[
[
"#### Convertion from image convention to geographic convention\n\n```python\nangle_geo = np.rad2deg(angle_img) + ground_heading\n```\n\n#### Conversion from geographic convention to image convention\n```python\nangle_img = np.deg2rad(angle_geo - ground_heading)\n```\n\n",
"_____no_output_____"
],
[
"### hist_mean\n\n`streaks` variable was computed from `hist_mean_smooth`.\n\nThe main difference with `streaks` variable is that we don't have a single angle, but a histogram of probability for binned angles",
"_____no_output_____"
]
],
[
[
"hist_mean_smooth",
"_____no_output_____"
]
],
[
[
"Let's exctract one histogram at an arbitrary position, and plot the histogram.\n\nWe can do this with the regular `hv.Histogram` function, or use [xsarsea.gradients.circ_hist](../basic_api.rst#xsarsea.gradients.circ_hist), that might be used with `hv.Path` to plot the histogram as a circular one.",
"_____no_output_____"
]
],
[
[
"hist_at = hist_mean_smooth['weight'].sel(atrack=5000,xtrack=12000,method='nearest')\nhv.Histogram( (hist_at.angles, hist_at )) + hv.Path(xsarsea.gradients.circ_hist(hist_at))",
"_____no_output_____"
]
],
[
[
"`xsarsea` also provide an interactive drawing class [xsarsea.gradients.PlotGradients](../basic_api.rst#xsarsea.gradients.PlotGradients) that can be used to draw the circular histogram at mouse tap. (needs a live notebook)",
"_____no_output_____"
]
],
[
[
"# background image for vectorfield\ns0 = sar_ds['sigma0_detrend'].sel(pol='VV')\nhv_img = rasterize(hv.Image(s0).opts(cmap='gray',clim=(0,np.nanpercentile(s0,95))))\n\n\nplot_mean_smooth = xsarsea.gradients.PlotGradients(hist_mean_smooth)\n\n# get vectorfield, with mouse tap activated\nhv_vf = plot_mean_smooth.vectorfield(tap=True)\n\n# connect mouse to histogram\nhv_hist = plot_mean_smooth.mouse_histogram()\n\n# notebook dynamic output\nhv_hist + hv_img * hv_vf",
"_____no_output_____"
]
],
[
[
"`hist_mean_smooth` was smoothed. Let's try `hist_smooth`",
"_____no_output_____"
]
],
[
[
"plot_smooth = xsarsea.gradients.PlotGradients(hist_smooth)\nhv_vf = plot_smooth.vectorfield()\nhv_hist = plot_smooth.mouse_histogram()\nhv_hist + (hv_img * hv_vf).opts(legend_position='right', frame_width=300)",
"_____no_output_____"
]
],
[
[
"Using `source` keyword for `mouse_histogram`, we can link several histrograms",
"_____no_output_____"
]
],
[
[
"plot_raw = xsarsea.gradients.PlotGradients(hist)\nplot_mean = xsarsea.gradients.PlotGradients(hist_mean)\nhv_vf = plot_smooth.vectorfield()\n\ngridspace = hv.GridSpace(kdims=['smooth','mean'])\ngridspace[(False,False)] = plot_smooth.mouse_histogram(source=plot_raw)\ngridspace[(True,False)] = plot_smooth.mouse_histogram()\ngridspace[(True,True)] = plot_smooth.mouse_histogram(source=plot_mean_smooth)\ngridspace[(False,True)] = plot_smooth.mouse_histogram(source=plot_mean)\n\n\ngridspace.opts(plot_size=(200,200)) + (hv_img * hv_vf).opts(legend_position='right', frame_height=500)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a902c6dbf06bfb120a4569513adbd73d42fbfa8
| 32,273 |
ipynb
|
Jupyter Notebook
|
S01 - Bootcamp and Binary Classification/SLU09 - Classification with Logistic Regression/Exercise notebook.ipynb
|
FarhadManiCodes/batch5-students
|
3a147145dc4f4ac65a851542987cf687b9915d5b
|
[
"MIT"
] | 2 |
2022-02-04T17:40:04.000Z
|
2022-03-26T18:03:12.000Z
|
S01 - Bootcamp and Binary Classification/SLU09 - Classification with Logistic Regression/Exercise notebook.ipynb
|
FarhadManiCodes/batch5-students
|
3a147145dc4f4ac65a851542987cf687b9915d5b
|
[
"MIT"
] | null | null | null |
S01 - Bootcamp and Binary Classification/SLU09 - Classification with Logistic Regression/Exercise notebook.ipynb
|
FarhadManiCodes/batch5-students
|
3a147145dc4f4ac65a851542987cf687b9915d5b
|
[
"MIT"
] | 2 |
2021-10-30T16:20:13.000Z
|
2021-11-25T12:09:31.000Z
| 31.578278 | 328 | 0.551885 |
[
[
[
"# SLU09 - Classification With Logistic Regression: Exercise notebook",
"_____no_output_____"
]
],
[
[
"import pandas as pd \nimport numpy as np \nimport hashlib",
"_____no_output_____"
]
],
[
[
"In this notebook you will practice the following: \n\n - What classification is for\n - Logistic regression\n - Cost function\n - Binary classification\n \nYou thought that you would get away without implementing your own little Logistic Regression? Hah!\n\n\n# Exercise 1. Implement the Exponential part of Sigmoid Function\n\n\nIn the first exercise, you will implement **only the piece** of the sigmoid function where you have to use an exponential. \n\nHere's a quick reminder of the formula:\n\n$$\\hat{p} = \\frac{1}{1 + e^{-z}}$$\n\nIn this exercise we only want you to complete the exponential part given the values of b0, b1, x1, b2 and x2:\n\n$$e^{-z}$$\n\nRecall that z has the following formula:\n\n$$z = \\beta_0 + \\beta_1 x_1 + \\beta_2 x_2$$\n\n**Hint: Divide your z into pieces by Betas, I've left the placeholders in there!**",
"_____no_output_____"
]
],
[
[
"def exponential_z_function(beta0, beta1, beta2, x1, x2):\n \"\"\" \n Implementation of the exponential part of \n the sigmoid function manually. In this exercise you \n have to compute the e raised to the power -z. Z is calculated\n according to the following formula: b0+b1x1+b2x2. \n \n You can use the inputs given to generate the z.\n \n Args:\n beta0 (np.float64): value of the intercept\n beta1 (np.float64): value of first coefficient\n beta2 (np.float64): value of second coefficient\n x1 (np.float64): value of first variable\n x2 (np.float64): value of second variable\n\n Returns:\n exp_z (np.float64): the exponential part of\n the sigmoid function\n\n \"\"\"\n \n # hint: obtain the exponential part\n # using np.exp()\n \n \n # Complete the following\n #beta0 = ...\n #b1_x1 = ...\n #b2_x2 = ...\n \n #exp_z = ...\n \n # YOUR CODE HERE\n raise NotImplementedError()\n return exp_z",
"_____no_output_____"
],
[
"value_arr = [1, 2, 1, 1, 0.5]\n\nexponential = exponential_z_function(\n value_arr[0], value_arr[1], value_arr[2], value_arr[3], value_arr[4])\n\nnp.testing.assert_almost_equal(np.round(exponential,3), 0.030)",
"_____no_output_____"
]
],
[
[
"Expected output:\n\n Exponential part: 0.03",
"_____no_output_____"
],
[
"# Exercise 2: Make a Prediction\n\nThe next step is to implement a function that receives an observation and returns the predicted probability with the sigmoid function.\n\nFor instance, we can make a prediction given a model with data and coefficients by using the sigmoid:\n\n$$\\hat{p} = \\frac{1}{1 + e^{-z}}$$\n\nWhere Z is the linear equation - you can't use the same function that you used above for the Z part as the input are now two arrays, one with the train data (x1, x2, ..., xn) and another with the coefficients (b0, b1, .., bn).\n\n**Complete here:**",
"_____no_output_____"
]
],
[
[
"def predict_proba(data, coefs):\n \"\"\" \n Implementation of a function that returns \n predicted probabilities for an observation.\n \n In the train array you will have \n the data values (corresponding to the x1, x2, .. , xn).\n \n In the coefficients array you will have\n the coefficients values (corresponding to the b0, b1, .., bn).\n \n In this exercise you should be able to return a float \n with the calculated probabilities given an array of size (1, n). \n The resulting value should be a float (the predicted probability)\n with a value between 0 and 1. \n \n Note: Be mindful that the input is completely different from \n the function above - you receive two arrays in this functions while \n in the function above you received 5 floats - each corresponding\n to the x's and b's.\n \n Args:\n data (np.array): a numpy array of shape (n)\n - n: number of variables\n coefs (np.array): a numpy array of shape (n + 1, 1)\n - coefs[0]: intercept\n - coefs[1:]: remaining coefficients\n\n Returns:\n proba (float): the predicted probability for a data example.\n\n \"\"\"\n\n # hint: you have to implement your z in a vectorized \n # way aka using vector multiplications - it's different from what you have done above\n \n # hint: don't forget about adding an intercept to the train data!\n \n # YOUR CODE HERE\n raise NotImplementedError()\n \n \n return proba",
"_____no_output_____"
],
[
"x = np.array([-1.2, -1.5])\ncoefficients = np.array([0 ,4, -1])\nnp.testing.assert_almost_equal(round(predict_proba(x, coefficients),3),0.036)\n\nx_1 = np.array([-1.5, -1, 3, 0])\ncoefficients_1 = np.array([0 ,2.1, -1, 0.5, 0])\n\nnp.testing.assert_almost_equal(round(predict_proba(x_1, coefficients_1),3),0.343)",
"_____no_output_____"
]
],
[
[
"Expected output:\n\n Predicted probabilities for example with 2 variables: 0.036\n \n Predicted probabilities for example with 3 variables: 0.343",
"_____no_output_____"
],
[
"# Exercise 3: Compute the Maximum Log-Likelihood Cost Function\n\nAs you will implement stochastic gradient descent, you need to calculate the cost function (the Maximum Log-Likelihood) for each prediction, checking how much you will penalize each example according to the difference between the calculated probability and its true value: \n\n$$H_{\\hat{p}}(y) = - (y \\log(\\hat{p}) + (1-y) \\log (1-\\hat{p}))$$\n\nIn the next exercise, you will loop through some examples stored in an array and calculate the cost function for the full dataset. Recall that the formula to generalize the cost function across several examples is: \n\n$$H_{\\hat{p}}(y) = - \\frac{1}{N}\\sum_{i=1}^{N} \\left [{ y_i \\ \\log(\\hat{p}_i) + (1-y_i) \\ \\log (1-\\hat{p}_i)} \\right ]$$\n\nYou will basically simulate what stochastic gradient descent does without updating the coefficients - computing the log for each example, sum each log-loss and then averaging the result across the number of observations in the x dataset/array.",
"_____no_output_____"
]
],
[
[
"import math\n\ndef max_log_likelihood_cost_function(var_x, coefs, var_y):\n \"\"\" \n Implementation of a function that returns the Maximum-Log-Likelihood loss\n \n Args:\n var_x (np.array): array with x training data of size (m, n) shape \n where m is the number of observations and n the number of columns\n coefs (float64): an array with the coefficients to apply of size (1, n+1)\n where n is the number of columns plus the intercept.\n var_y (float64): an array with integers with the real outcome per \n example.\n \n Returns:\n loss (np.float): a float with the resulting log loss for the \n entire data.\n\n \"\"\"\n \n # A list of hints that you can follow:\n \n # - you already computed a probability for an example so you might be able to reuse the function\n \n # - Store number of examples that you have to loop through\n \n #Steps to follow:\n # 1. Initialize loss\n # 2. Loop through every example \n # Hint: if you don't use the function from above to predict probas \n # don't forget to add the intercept to the X_array!\n # 2.1 Calculate probability for each example\n # 2.2 Compute log loss\n # Hint: maybe separating the log loss will help you avoiding get confused inside all the parenthesis\n # 2.3 Sum the computed loss for the example to the total log loss\n # 3. Divide log loss by the number of examples (don't forget that the log loss \n # has to return a positive number!)\n \n # YOUR CODE HERE\n raise NotImplementedError()\n return total_loss",
"_____no_output_____"
],
[
"x = np.array([[-2, -2], [3.5, 0], [6, 4]])\ncoefficients = np.array([[0 ,2, -1]])\ny = np.array([[1],[1],[0]])\nnp.testing.assert_almost_equal(round(max_log_likelihood_cost_function(x, coefficients, y),3),3.376)\n\ncoefficients_1 = np.array([[3 ,4, -0.6]])\nx_1 = np.array([[-4, -4], [6, 0], [3, 2], [4, 0]])\ny_1 = np.array([[4],[4],[2],[1.5]])\n\nnp.testing.assert_almost_equal(round(max_log_likelihood_cost_function(x_1, coefficients_1, y_1),3),-15.475)\n",
"_____no_output_____"
]
],
[
[
"Expected output:\n \n Computed log loss for first training set: 3.376\n \n Computed log loss for second training set: -15.475",
"_____no_output_____"
],
[
"# Exercise 4: Compute a first pass on Stochastic Gradient Descent\n\nNow that we know how to calculate probabilities and the cost function, let's do an interesting exercise - computing the derivatives and updating our coefficients. Here you will do a full pass on a bunch of examples, computing the gradient descent for each time you see one of them.\n\nIn this exercise, you should compute a single iteration of the gradient descent! \n\nYou will basically use stochastic gradient descent but you will have to update the coefficients after\nyou see a new example - so each time your algorithm knows that he saw something way off (for example, \nreturning a low probability for an example with outcome = 1) he will have a way (the gradient) to \nchange the coefficients so that he is able to minimize the cost function.\n\n## Quick reminders:\n\nRemember our formulas for the gradient:\n\n$$\\beta_{0(t+1)} = \\beta_{0(t)} - learning\\_rate \\frac{\\partial H_{\\hat{p}}(y)}{\\partial \\beta_{0(t)}}$$\n\n$$\\beta_{t+1} = \\beta_t - learning\\_rate \\frac{\\partial H_{\\hat{p}}(y)}{\\partial \\beta_t}$$\n\nwhich can be simplified to\n\n$$\\beta_{0(t+1)} = \\beta_{0(t)} + learning\\_rate \\left [(y - \\hat{p}) \\ \\hat{p} \\ (1 - \\hat{p})\\right]$$\n\n$$\\beta_{t+1} = \\beta_t + learning\\_rate \\left [(y - \\hat{p}) \\ \\hat{p} \\ (1 - \\hat{p}) \\ x \\right]$$\n\nYou will have to initialize the coefficients in some way. If you have a training set $X$, you can initialize them to zero, this way:\n```python\ncoefficients = np.zeros(X.shape[1]+1)\n```\n\nwhere the $+1$ is adding the intercept.\n\nNote: We are doing a stochastic gradient descent so don't forget to go observation by observation and updating the coefficients every time!\n\n**Complete here:**",
"_____no_output_____"
]
],
[
[
"def compute_coefs_sgd(x_train, y_train, learning_rate = 0.1, verbose = False):\n \"\"\" \n Implementation of a function that returns the a first iteration of \n stochastic gradient descent.\n\n Args:\n x_train (np.array): a numpy array of shape (m, n)\n m: number of training observations\n n: number of variables\n y_train (np.array): a numpy array of shape (m,) with \n the real value of the target.\n learning_rate (np.float64): a float\n\n Returns:\n coefficients (np.array): a numpy array of shape (n+1,)\n\n \"\"\"\n \n # A list of hints that might help you:\n \n # 1. Calculate the number of observations\n \n # 2. Initialize the coefficients array with zeros\n # hint: use np.zeros() \n \n # 3. Run the stochastic gradient descent and update the coefficients after each observation \n # 3.1 Compute the predicted probability - you can use a function we have done previously \n # 3.2 Update intercept\n # 3.3 Update the rest of the coefficients by looping through each variable\n \n # YOUR CODE HERE\n raise NotImplementedError()\n \n return coefficients",
"_____no_output_____"
],
[
"#Test 1\nx_train = np.array([[1,2,4], [2,4,9], [2,1,4], [9,2,10]])\ny_train = np.array([0,2.2,0,2.3])\nlearning_rate = 0.1\n\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train, y_train, learning_rate)[0],3),0.022)\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train, y_train, learning_rate)[1],3),0.081)\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train, y_train, learning_rate)[2],3),0.140)\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train, y_train, learning_rate)[3],3),0.320)\n\n#Test 2\nx_train_1 = np.array([[4,4,2,6], [1,5,7,2], [3,1,2,1], [8,2,9,5], [2,2,9,4]])\ny_train_1 = np.array([0,1.3,0,1.3,1.2])\n\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train_1, y_train_1, learning_rate).max(),3) ,0.277)\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train_1, y_train_1, learning_rate).min(),3) ,0.015)\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train_1, y_train_1, learning_rate).mean(),3),0.102)\nnp.testing.assert_almost_equal(round(compute_coefs_sgd(x_train_1, y_train_1, learning_rate).var(),3) ,0.008)\n",
"_____no_output_____"
]
],
[
[
"# Exercise 5: Normalize Data\n\nTo get this concept in your head, let's do a quick and easy function to normalize the data using a MaxMin approach. It is crucial that your variables are adjusted between $[0;1]$ (normalized) or standardized so that you can correctly analyze some logistic regression coefficients for your possible future employer.\n\nYou only have to implement this formula\n\n$$ x_{normalized} = \\frac{x - x_{min}}{x_{max} - x_{min}}$$\n\nDon't forget that the `axis` argument is critical when obtaining the maximum, minimum and mean values! As you want to obtain the maximum and minimum values of each individual feature, you have to specify `axis=0`. Thus, if you wanted to obtain the maximum values of each feature of data $X$, you would do the following:\n\n```python\nX_max = np.max(X, axis=0)\n```\n\nNot an assertable question but can you remember why it is important to normalize data for Logistic Regression?\n\n**Complete here:**",
"_____no_output_____"
]
],
[
[
"def normalize_data_function(data):\n \"\"\" \n Implementation of a function that normalizes your data variables\n \n Args:\n data (np.array): a numpy array of shape (m, n)\n m: number of observations\n n: number of variables\n\n Returns:\n normalized_data (np.array): a numpy array of shape (m, n)\n\n \"\"\"\n # Compute the numerator first \n # you can use np.min()\n # numerator = ...\n \n # Compute the denominator\n # you can use np.max() and np.min()\n # denominator = ...\n \n \n # YOUR CODE HERE\n raise NotImplementedError()\n return normalized_data",
"_____no_output_____"
],
[
"data = np.array([[7,7,3], [2,2,11], [9,5,2], [0,9,5], [10,1,3], [1,5,2]])\nnormalized_data = normalize_data_function(data)\nprint('Before normalization:')\nprint(data)\nprint('\\n-------------------\\n')\nprint('After normalization:')\nprint(normalized_data)",
"_____no_output_____"
]
],
[
[
"Expected output:\n \n Before normalization:\n [[ 7 7 3]\n [ 2 2 11]\n [ 9 5 2]\n [ 0 9 5]\n [10 1 3]\n [ 1 5 2]]\n\n -------------------\n\nAfter normalization:\n\n [[0.7 0.75 0.11111111]\n [0.2 0.125 1. ]\n [0.9 0.5 0. ]\n [0. 1. 0.33333333]\n [1. 0. 0.11111111]\n [0.1 0.5 0. ]]",
"_____no_output_____"
]
],
[
[
"data = np.array([[2,2,11,1], [7,5,1,3], [9,5,2,6]])\nnormalized_data = normalize_data_function(data)\nnp.testing.assert_almost_equal(round(normalized_data.max(),3),1.0)\nnp.testing.assert_almost_equal(round(normalized_data.mean(),3),0.518)\nnp.testing.assert_almost_equal(round(normalized_data.var(),3),0.205)\n\n\ndata = np.array([[1,3,1,3], [9,5,3,1], [2,2,4,6]])\nnormalized_data = normalize_data_function(data)\nnp.testing.assert_almost_equal(round(normalized_data.mean(),3),0.460)\nnp.testing.assert_almost_equal(round(normalized_data.std(),3),0.427)",
"_____no_output_____"
]
],
[
[
"# Exercise 6: Training a Logistic Regression with Sklearn\n\nIn this exercise, we will load a dataset related to direct marketing campaigns (phone calls) of a Portuguese banking institution. The goal is to predict whether the client will subscribe (1/0) to a term deposit (variable y) ([link to dataset](http://archive.ics.uci.edu/ml/datasets/Bank+Marketing))\n\nPrepare to use your sklearn skills!",
"_____no_output_____"
]
],
[
[
"# We will load the dataset for you\nbank = pd.read_csv('data/bank.csv', delimiter=\";\")\nbank.head()",
"_____no_output_____"
]
],
[
[
"In this exercise, you need to do the following: \n\n- Select an array/Series with the target variable (y) \n\n- Select an array/dataframe with the X numeric variables (age, balance, day, month, duration, campaign and pdays) \n\n- Scale all the X variables - normalize using Max / Min method. \n\n- Fit a logistic regression for a maximum of 100 epochs and random state = 100. \n\n- Return an array of the predicted probas and return the coefficients\n\nAfter this, feel free to explore your predictions! As a bonus why don't you construct a decision boundary using two variables eh? :-)",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LogisticRegression\n\ndef train_model_sklearn(dataset):\n '''\n Returns the predicted probas and coefficients \n of a trained logistic regression on the Titanic Dataset.\n \n Args:\n dataset(pd.DataFrame): dataset to train on.\n \n Returns:\n probas (np.array): Array of floats with the probability \n of surviving for each passenger\n coefficients (np.array): Returned coefficients of the \n trained logistic regression.\n '''\n \n # leave this np.random seed here\n \n np.random.seed(100)\n \n # List of hints:\n \n # 1. Use the Survived variable as y\n \n # 2. Select the Numerical variables for X \n # hint: use pandas .loc or indexing! \n \n # 3. Scale the X dataset - you can use a function we have already\n # constructed or resort to the sklearn implementation\n \n # 4. Define logistic regression from sklearn with max iter = 100 also add random_state = 100\n # Hint: for epochs look at the max_iter hyper param!\n \n # 5. Fit logistic\n \n # 6. Obtain probability of surviving\n \n # 7. Obtain Coefficients from logistic regression\n # Hint: see the sklearn logistic regression documentation if you do not know how to do this \n # No need to return the intercept, just the variable coefficients!\n \n # YOUR CODE HERE\n raise NotImplementedError()\n return probas, coef\n ",
"_____no_output_____"
],
[
"probas, coef = train_model_sklearn(bank)\n\n# Testing Probas\nmax_probas = probas.max()\nnp.testing.assert_almost_equal(max_probas, 0.997, 2)\nmin_probas = probas.min()\nnp.testing.assert_almost_equal(min_probas, 0.008, 2)\nmean_probas = probas.mean()\nnp.testing.assert_almost_equal(mean_probas, 0.115, 2)\nstd_probas = probas.std()\nnp.testing.assert_almost_equal(std_probas, 0.115, 2)\nsum_probas = probas.sum()\nnp.testing.assert_almost_equal(sum_probas*0.001, 0.521, 2)\n\n# Testing Coefs\nmax_coef = coef[0].max()\nnp.testing.assert_almost_equal(max_coef*0.1, 0.87, 1)\nmin_coef = coef[0].min()\nnp.testing.assert_almost_equal(min_coef*0.1, -0.18, 1)\nmean_coef = coef[0].mean()\nnp.testing.assert_almost_equal(mean_coef*0.1, 0.21, 1)\nstd_coef = coef[0].std()\nnp.testing.assert_almost_equal(std_coef*0.1, 0.35, 1)\nsum_probas = coef[0].sum()\nnp.testing.assert_almost_equal(sum_probas*0.1, 1.06, 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",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a9047f440293f507bf3b082cd773861436b1905
| 789,159 |
ipynb
|
Jupyter Notebook
|
notebooks/babies.ipynb
|
artoby/boyorgirl
|
f333e293798d894c1195ac559d211d31376d332c
|
[
"MIT"
] | 10 |
2019-10-10T00:55:07.000Z
|
2019-12-10T07:19:19.000Z
|
notebooks/babies.ipynb
|
artoby/boyorgirl
|
f333e293798d894c1195ac559d211d31376d332c
|
[
"MIT"
] | 6 |
2020-09-07T13:18:56.000Z
|
2022-02-26T18:42:53.000Z
|
notebooks/babies.ipynb
|
artoby/boyorgirl
|
f333e293798d894c1195ac559d211d31376d332c
|
[
"MIT"
] | null | null | null | 1,062.125168 | 392,212 | 0.940087 |
[
[
[
"# Baby boy/girl classifier model preparation\n\n*based on: Francisco Ingham and Jeremy Howard. Inspired by [Adrian Rosebrock](https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/)*\n\n*by: Artyom Vorobyov*\n\nNotebook execution and model training is made in Google Colab",
"_____no_output_____"
]
],
[
[
"from fastai.vision import *\nfrom pathlib import Path",
"_____no_output_____"
],
[
"# Check if running in Google Colab and save it to bool variable\ntry:\n import google.colab\n IS_COLAB = True\nexcept:\n IS_COLAB = False\nprint(\"Is Colab:\", IS_COLAB)",
"Is Colab: False\n"
]
],
[
[
"## Get a list of URLs",
"_____no_output_____"
],
[
"### How to get a dataset from Google Images",
"_____no_output_____"
],
[
"Go to [Google Images](http://images.google.com) and search for the images you are interested in. The more specific you are in your Google Search, the better the results and the less manual pruning you will have to do.\n\nScroll down until you've seen all the images you want to download, or until you see a button that says 'Show more results'. All the images you scrolled past are now available to download. To get more, click on the button, and continue scrolling. The maximum number of images Google Images shows is 700.\n\nIt is a good idea to put things you want to exclude into the search query, for instance if you are searching for the Eurasian wolf, \"canis lupus lupus\", it might be a good idea to exclude other variants:\n\n \"canis lupus lupus\" -dog -arctos -familiaris -baileyi -occidentalis\n\nYou can also limit your results to show only photos by clicking on Tools and selecting Photos from the Type dropdown.",
"_____no_output_____"
],
[
"### How to download image URLs",
"_____no_output_____"
],
[
"Now you must run some Javascript code in your browser which will save the URLs of all the images you want for you dataset.\n\nPress <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>J</kbd> in Windows/Linux and <kbd>Cmd</kbd><kbd>Opt</kbd><kbd>J</kbd> in Mac, and a small window the javascript 'Console' will appear. That is where you will paste the JavaScript commands.\n\nYou will need to get the urls of each of the images. Before running the following commands, you may want to disable ad blocking extensions (uBlock, AdBlockPlus etc.) in Chrome. Otherwise the window.open() command doesn't work. Then you can run the following commands:\n\n```javascript\nurls = Array.from(document.querySelectorAll('.rg_di .rg_meta')).map(el=>JSON.parse(el.textContent).ou);\nwindow.open('data:text/csv;charset=utf-8,' + escape(urls.join('\\n')));\n```",
"_____no_output_____"
],
[
"### What to do with babies",
"_____no_output_____"
],
[
"For this particular application (baby boy/girl classifier) you can just search for \"baby boys\" and \"baby girls\". Then run the script mentioned above and save the URLs in \"boys_urls.csv\" and \"girls_urls.csv\".",
"_____no_output_____"
],
[
"## Download images",
"_____no_output_____"
],
[
"fast.ai has a function that allows you to do just that. You just have to specify the urls filename as well as the destination folder and this function will download and save all images that can be opened. If they have some problem in being opened, they will not be saved.\n\nLet's download our images! Notice you can choose a maximum number of images to be downloaded. In this case we will not download all the urls.",
"_____no_output_____"
]
],
[
[
"class_boy = 'boys'\nclass_girl = 'girls'\nclasses = [class_boy, class_girl]\npath = Path('./data')\npath.mkdir(parents=True, exist_ok=True)\n\ndef download_dataset(is_colab):\n if is_colab:\n from google.colab import drive\n import shutil\n import zipfile\n\n # You'll be asked to sign in Google Account and copy-paste a code here. Do it.\n drive.mount('/content/gdrive')\n # Copy this model from Google Drive after export and manually put it in the \"ai_models\" folder in the repository\n # If there'll be an error during downloading the model - share it with some other Google account and download\n # from this 2nd account - it should work fine.\n zip_remote_path = Path('/content/gdrive/My Drive/Colab/boyorgirl/train.zip')\n shutil.copy(str(zip_remote_path), str(path))\n zip_local_path = path/'train.zip'\n with zipfile.ZipFile(zip_local_path, 'r') as zip_ref:\n zip_ref.extractall(path)\n print(\"train folder contents:\", (path/'train').ls())\n else:\n data_sources = [\n ('./boys_urls.csv', path/'train'/class_boy),\n ('./girls_urls.csv', path/'train'/class_girl)\n ]\n\n # Download the images listed in URL's files\n for urls_path, dest_path in data_sources:\n dest = Path(dest_path)\n dest.mkdir(parents=True, exist_ok=True)\n download_images(urls_path, dest, max_pics=800)\n # If you have problems download, try the code below with `max_workers=0` to see exceptions:\n # download_images(urls_path, dest, max_pics=20, max_workers=0)\n\n # Then we can remove any images that can't be opened:\n for _, dest_path in data_sources:\n verify_images(dest_path, delete=True, max_size=800)\n\n# If running from colab - zip your train set (train folder) and put it to \"Colab/boyorgirl/train.zip\" in your Google Drive\ndownload_dataset(IS_COLAB)",
"_____no_output_____"
]
],
[
[
"## Cleaning the data",
"_____no_output_____"
],
[
"Now it's a good moment to review the downloaded images and clean them. There will be some non-relevant images - photos of adults, photos of the baby clothes without the babies etc. Just review the images and remove non-relevant ones. For 2x400 images it'll take just 10-20 minutes in total.\n\nThere's also another way to clean the data - use the `fastiai.widgets.ImageCleaner`. It's used after you've trained your model. Even if you plan to use `ImageCleaner` later - it still makes sense to review the dataset briefly by yourself at the beginning.",
"_____no_output_____"
],
[
"## Load the data",
"_____no_output_____"
]
],
[
[
"np.random.seed(42)\ndata = ImageDataBunch.from_folder(path, train='train', valid_pct=0.2,\n ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats)",
"_____no_output_____"
]
],
[
[
"Good! Let's take a look at some of our pictures then.",
"_____no_output_____"
]
],
[
[
"# Check if all the classes were correctly read\nprint(data.classes)\nprint(data.classes == classes)",
"['boys', 'girls']\nTrue\n"
],
[
"data.show_batch(rows=3, figsize=(7,8), ds_type=DatasetType.Train)",
"_____no_output_____"
],
[
"data.show_batch(rows=3, figsize=(7,8), ds_type=DatasetType.Valid)",
"_____no_output_____"
],
[
"print('Train set size: {}. Validation set size: {}'.format(len(data.train_ds), len(data.valid_ds)))",
"Train set size: 592. Validation set size: 147\n"
]
],
[
[
"## Train model",
"_____no_output_____"
]
],
[
[
"learn = cnn_learner(data, models.resnet50, metrics=error_rate)",
"_____no_output_____"
],
[
"learn.fit_one_cycle(4)",
"_____no_output_____"
],
[
"learn.save('stage-1')",
"_____no_output_____"
],
[
"learn.unfreeze()",
"_____no_output_____"
],
[
"learn.lr_find()",
"_____no_output_____"
],
[
"# If the plot is not showing try to give a start and end learning rate\n# learn.lr_find(start_lr=1e-5, end_lr=1e-1)\nlearn.recorder.plot()",
"_____no_output_____"
],
[
"learn.fit_one_cycle(2, max_lr=slice(1e-5,1e-3))",
"_____no_output_____"
],
[
"learn.save('stage-2')",
"_____no_output_____"
]
],
[
[
"## Interpretation",
"_____no_output_____"
]
],
[
[
"learn.load('stage-2');",
"_____no_output_____"
],
[
"interp = ClassificationInterpretation.from_learner(learn)",
"_____no_output_____"
],
[
"interp.plot_confusion_matrix()",
"_____no_output_____"
]
],
[
[
"## Putting your model in production",
"_____no_output_____"
],
[
"First thing first, let's export the content of our `Learner` object for production. Below are 2 variants of export - for local environment and for colab environment:",
"_____no_output_____"
]
],
[
[
"# Use this cell to export model from local environment within the repository\ndef get_export_path(is_colab):\n if is_colab:\n from google.colab import drive\n \n # You'll be asked to sign in Google Account and copy-paste a code here. Do it.\n # force_remount=True is needed to write model if it was deleted from Google Drive, but remains in Colab local file system\n drive.mount('/content/gdrive', force_remount=True)\n # Copy this model from Google Drive after export and manually put it in the \"ai_models\" folder in the repository\n # If there'll be an error during downloading the model - share it with some other Google account and download\n # from this 2nd account - it should work fine.\n return Path('/content/gdrive/My Drive/Colab/boyorgirl/ai_models/export.pkl')\n else:\n # Used in case when notebook is run from the repository, but not in the Colab\n return Path('../backend/ai_models/export.pkl')\n\n# In case of Colab - model will be exported to 'Colab/boyorgirl/ai_models/export.pkl'. Download and save it in your repository manually\n# in the 'ai_models' folder\nexport_path = get_export_path(IS_COLAB)\n# ensure folder exists\nexport_path.parents[0].mkdir(parents=True, exist_ok=True)\n# absolute path is passed as learn object attaches relative path to it's data folder rather than to notebook folder\nlearn.export(export_path.absolute())\nprint(\"Export folder contents:\", export_path.parents[0].ls())",
"Export folder contents: [PosixPath('../backend/ai_models/.DS_Store'), PosixPath('../backend/ai_models/export.pkl')]\n"
]
],
[
[
"This will create a file named 'export.pkl' in the given directory. This exported model contains everything we need to deploy our model (the model, the weights but also some metadata like the classes or the transforms/normalization used).",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a904c307f9cac0911574d6faa337c912c01414c
| 39,583 |
ipynb
|
Jupyter Notebook
|
notebooks/Try Train Longformer SQuAD.ipynb
|
rizwandel/Master-Thesis-Multilingual-Longformer
|
31fd783cfbffb873da655635a0cd5726e82253a0
|
[
"MIT"
] | 14 |
2021-02-19T21:53:31.000Z
|
2022-03-30T10:34:59.000Z
|
notebooks/Try Train Longformer SQuAD.ipynb
|
rizwandel/Master-Thesis-Multilingual-Longformer
|
31fd783cfbffb873da655635a0cd5726e82253a0
|
[
"MIT"
] | 5 |
2021-04-29T15:59:16.000Z
|
2021-08-24T08:02:08.000Z
|
notebooks/Try Train Longformer SQuAD.ipynb
|
rizwandel/Master-Thesis-Multilingual-Longformer
|
31fd783cfbffb873da655635a0cd5726e82253a0
|
[
"MIT"
] | 3 |
2021-08-20T07:13:46.000Z
|
2021-10-13T14:11:57.000Z
| 37.09747 | 520 | 0.524038 |
[
[
[
"import torch\nimport datasets as nlp\nfrom transformers import LongformerTokenizerFast",
"\u001b[34m\u001b[1mwandb\u001b[0m: \u001b[33mWARNING\u001b[0m W&B installed but not logged in. Run `wandb login` or set the WANDB_API_KEY env variable.\n"
],
[
"tokenizer = LongformerTokenizerFast.from_pretrained('allenai/longformer-base-4096')",
"_____no_output_____"
],
[
"def get_correct_alignement(context, answer):\n \"\"\" Some original examples in SQuAD have indices wrong by 1 or 2 character. We test and fix this here. \"\"\"\n gold_text = answer['text'][0]\n start_idx = answer['answer_start'][0]\n end_idx = start_idx + len(gold_text)\n if context[start_idx:end_idx] == gold_text:\n return start_idx, end_idx # When the gold label position is good\n elif context[start_idx-1:end_idx-1] == gold_text:\n return start_idx-1, end_idx-1 # When the gold label is off by one character\n elif context[start_idx-2:end_idx-2] == gold_text:\n return start_idx-2, end_idx-2 # When the gold label is off by two character\n else:\n raise ValueError()\n\n# Tokenize our training dataset\ndef convert_to_features(example):\n # Tokenize contexts and questions (as pairs of inputs)\n encodings = tokenizer.encode_plus(example['question'], example['context'], pad_to_max_length=True, max_length=512, truncation=True)\n context_encodings = tokenizer.encode_plus(example['context'])\n \n\n # Compute start and end tokens for labels using Transformers's fast tokenizers alignement methodes.\n # this will give us the position of answer span in the context text\n start_idx, end_idx = get_correct_alignement(example['context'], example['answers'])\n start_positions_context = context_encodings.char_to_token(start_idx)\n end_positions_context = context_encodings.char_to_token(end_idx-1)\n\n # here we will compute the start and end position of the answer in the whole example\n # as the example is encoded like this <s> question</s></s> context</s>\n # and we know the postion of the answer in the context\n # we can just find out the index of the sep token and then add that to position + 1 (+1 because there are two sep tokens)\n # this will give us the position of the answer span in whole example \n sep_idx = encodings['input_ids'].index(tokenizer.sep_token_id)\n start_positions = start_positions_context + sep_idx + 1\n end_positions = end_positions_context + sep_idx + 1\n\n if end_positions > 512:\n start_positions, end_positions = 0, 0\n\n encodings.update({'start_positions': start_positions,\n 'end_positions': end_positions,\n 'attention_mask': encodings['attention_mask']})\n return encodings",
"_____no_output_____"
],
[
"# load train and validation split of squad\ntrain_dataset = nlp.load_dataset('squad', split='train')\nvalid_dataset = nlp.load_dataset('squad', split='validation')\n\n# Temp. Only for testing quickly\ntrain_dataset = nlp.Dataset.from_dict(train_dataset[:3])\nvalid_dataset = nlp.Dataset.from_dict(valid_dataset[:3])\n\ntrain_dataset = train_dataset.map(convert_to_features)\nvalid_dataset = valid_dataset.map(convert_to_features, load_from_cache_file=False)\n\n\n# set the tensor type and the columns which the dataset should return\ncolumns = ['input_ids', 'attention_mask', 'start_positions', 'end_positions']\ntrain_dataset.set_format(type='torch', columns=columns)\nvalid_dataset.set_format(type='torch', columns=columns)",
"_____no_output_____"
],
[
"len(train_dataset), len(valid_dataset)",
"_____no_output_____"
],
[
"t = torch.load('train_data.pt')",
"_____no_output_____"
],
[
"# Write training script",
"_____no_output_____"
],
[
"import json\n\nargs_dict = {\n \"n_gpu\": 1,\n \"model_name_or_path\": 'allenai/longformer-base-4096',\n \"max_len\": 512 ,\n \"output_dir\": './models',\n \"overwrite_output_dir\": True,\n \"per_gpu_train_batch_size\": 8,\n \"per_gpu_eval_batch_size\": 8,\n \"gradient_accumulation_steps\": 16,\n \"learning_rate\": 1e-4,\n \"num_train_epochs\": 3,\n \"do_train\": True\n}",
"_____no_output_____"
],
[
"## SQuAD evaluation script. Modifed slightly for this notebook\n\nfrom __future__ import print_function\nfrom collections import Counter\nimport string\nimport re\nimport argparse\nimport json\nimport sys\n\n\ndef normalize_answer(s):\n \"\"\"Lower text and remove punctuation, articles and extra whitespace.\"\"\"\n def remove_articles(text):\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\n\ndef f1_score(prediction, ground_truth):\n prediction_tokens = normalize_answer(prediction).split()\n ground_truth_tokens = normalize_answer(ground_truth).split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return 0\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1\n\n\ndef exact_match_score(prediction, ground_truth):\n return (normalize_answer(prediction) == normalize_answer(ground_truth))\n\n\ndef metric_max_over_ground_truths(metric_fn, prediction, ground_truths):\n scores_for_ground_truths = []\n for ground_truth in ground_truths:\n score = metric_fn(prediction, ground_truth)\n scores_for_ground_truths.append(score)\n return max(scores_for_ground_truths)\n\n\ndef evaluate(gold_answers, predictions):\n f1 = exact_match = total = 0\n\n for ground_truths, prediction in zip(gold_answers, predictions):\n total += 1\n exact_match += metric_max_over_ground_truths(\n exact_match_score, prediction, ground_truths)\n f1 += metric_max_over_ground_truths(f1_score, prediction, ground_truths)\n \n exact_match = 100.0 * exact_match / total\n f1 = 100.0 * f1 / total\n\n return {'exact_match': exact_match, 'f1': f1}",
"_____no_output_____"
],
[
"import torch\nfrom transformers import LongformerTokenizerFast, LongformerForQuestionAnswering\nfrom tqdm.auto import tqdm",
"_____no_output_____"
],
[
"tokenizer = LongformerTokenizerFast.from_pretrained('models')\nmodel = LongformerForQuestionAnswering.from_pretrained('models')\nmodel = model.cuda()\nmodel.eval()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a904d436ca2d33d82a1f39e85fd278dcd4968ca
| 2,457 |
ipynb
|
Jupyter Notebook
|
environments-bases/jupyter-notebooks/jupyter.ipynb
|
francomanca93/environments-for-ds
|
c280d62cdddf10de4903c0e2d9a316bce6fac663
|
[
"MIT"
] | null | null | null |
environments-bases/jupyter-notebooks/jupyter.ipynb
|
francomanca93/environments-for-ds
|
c280d62cdddf10de4903c0e2d9a316bce6fac663
|
[
"MIT"
] | null | null | null |
environments-bases/jupyter-notebooks/jupyter.ipynb
|
francomanca93/environments-for-ds
|
c280d62cdddf10de4903c0e2d9a316bce6fac663
|
[
"MIT"
] | null | null | null | 26.706522 | 154 | 0.491249 |
[
[
[
"print('Hello World')",
"Hello World\n"
],
[
"import math\nimport sys",
"_____no_output_____"
],
[
"def example1():\n ####This is a long comment. This should be wrapped to fit within 72 characters.\n some_tuple = (1, 2, 3, 'a')\n some_variable = {'long': 'Long code lines should be wrapped within 79 characters.',\n 'other': [math.pi, 100, 200, 300, 9876543210, 'This is a long string that goes on'],\n 'more': {'inner': 'This whole logical line should be wrapped.', some_tuple: [1,\n 20, 300, 40000, 500000000, 60000000000000000]}}\n return (some_tuple, some_variable)\n\n\ndef example2(): return {'has_key() is deprecated': True}.has_key(\n {'f': 2}.has_key(''))\n\n\nclass Example3(object):\n def __init__(self, bar):\n #Comments should have a space after the hash.\n if bar:\n bar += 1\n bar = bar * bar\n return bar\n else:\n some_string = \"\"\"\n Indentation in multiline strings should not be touched.\nOnly actual code should be reindented.\n\"\"\"\n return (sys.path, some_string)\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
4a90577128469e2efa1fa76a7e7a38197c8c420a
| 3,456 |
ipynb
|
Jupyter Notebook
|
notebooks/skdata_quick_intro.ipynb
|
Seanny123/hyperopt-sklearn
|
fa9d5e654a5cc681d6062caee1361706cac1334a
|
[
"BSD-3-Clause"
] | 1,322 |
2015-01-21T22:42:16.000Z
|
2022-03-25T03:43:32.000Z
|
notebooks/skdata_quick_intro.ipynb
|
Seanny123/hyperopt-sklearn
|
fa9d5e654a5cc681d6062caee1361706cac1334a
|
[
"BSD-3-Clause"
] | 118 |
2016-04-07T09:29:54.000Z
|
2022-03-20T14:54:30.000Z
|
notebooks/skdata_quick_intro.ipynb
|
Seanny123/hyperopt-sklearn
|
fa9d5e654a5cc681d6062caee1361706cac1334a
|
[
"BSD-3-Clause"
] | 273 |
2015-07-02T19:37:01.000Z
|
2022-02-24T12:25:39.000Z
| 32.299065 | 211 | 0.552662 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a9059884bf93a0ded38e5417a974f9daba74956
| 25,899 |
ipynb
|
Jupyter Notebook
|
09_deploying/09c_changesig.ipynb
|
isabella232/practical-ml-vision-book
|
94bf55698fe8d9d417fb926d99a446c1670a762b
|
[
"Apache-2.0"
] | 1 |
2021-02-17T08:26:02.000Z
|
2021-02-17T08:26:02.000Z
|
09_deploying/09c_changesig.ipynb
|
qwerlarlgus/practical-ml-vision-book
|
d42ee91b41d96a1e1d2396533eaf128a5f36ba53
|
[
"Apache-2.0"
] | 1 |
2021-03-17T19:06:16.000Z
|
2021-03-17T19:06:16.000Z
|
09_deploying/09c_changesig.ipynb
|
qwerlarlgus/practical-ml-vision-book
|
d42ee91b41d96a1e1d2396533eaf128a5f36ba53
|
[
"Apache-2.0"
] | null | null | null | 35.920943 | 968 | 0.573613 |
[
[
[
"from IPython.display import Markdown as md\n\n### change to reflect your notebook\n_nb_loc = \"09_deploying/09c_changesig.ipynb\"\n_nb_title = \"Changing signatures of exported model\"\n\n### no need to change any of this\n_nb_safeloc = _nb_loc.replace('/', '%2F')\nmd(\"\"\"\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://console.cloud.google.com/ai-platform/notebooks/deploy-notebook?name={1}&url=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2Fpractical-ml-vision-book%2Fblob%2Fmaster%2F{2}&download_url=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2Fpractical-ml-vision-book%2Fraw%2Fmaster%2F{2}\">\n <img src=\"https://raw.githubusercontent.com/GoogleCloudPlatform/practical-ml-vision-book/master/logo-cloud.png\"/> Run in AI Platform Notebook</a>\n </td>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/GoogleCloudPlatform/practical-ml-vision-book/blob/master/{0}\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/GoogleCloudPlatform/practical-ml-vision-book/blob/master/{0}\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://raw.githubusercontent.com/GoogleCloudPlatform/practical-ml-vision-book/master/{0}\">\n <img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>\n\"\"\".format(_nb_loc, _nb_title, _nb_safeloc))",
"_____no_output_____"
]
],
[
[
"# Changing signatures of exported model\n\nIn this notebook, we start from an already trained and saved model (as in Chapter 7).\nFor convenience, we have put this model in a public bucket in gs://practical-ml-vision-book/flowers_5_trained",
"_____no_output_____"
],
[
"## Enable GPU and set up helper functions\n\nThis notebook and pretty much every other notebook in this repository\nwill run faster if you are using a GPU.\nOn Colab:\n- Navigate to Edit→Notebook Settings\n- Select GPU from the Hardware Accelerator drop-down\n\nOn Cloud AI Platform Notebooks:\n- Navigate to https://console.cloud.google.com/ai-platform/notebooks\n- Create an instance with a GPU or select your instance and add a GPU\n\nNext, we'll confirm that we can connect to the GPU with tensorflow:",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nprint('TensorFlow version' + tf.version.VERSION)\nprint('Built with GPU support? ' + ('Yes!' if tf.test.is_built_with_cuda() else 'Noooo!'))\nprint('There are {} GPUs'.format(len(tf.config.experimental.list_physical_devices(\"GPU\"))))\ndevice_name = tf.test.gpu_device_name()\nif device_name != '/device:GPU:0':\n raise SystemError('GPU device not found')\nprint('Found GPU at: {}'.format(device_name))",
"_____no_output_____"
]
],
[
[
"## Exported model\n\nWe start from a trained and saved model from Chapter 7.\n<pre>\n model.save(...)\n</pre>",
"_____no_output_____"
]
],
[
[
"MODEL_LOCATION='gs://practical-ml-vision-book/flowers_5_trained'",
"_____no_output_____"
],
[
"!gsutil ls {MODEL_LOCATION}",
"gs://practical-ml-vision-book/flowers_5_trained/saved_model.pb\ngs://practical-ml-vision-book/flowers_5_trained/variables/\n"
],
[
"!saved_model_cli show --tag_set serve --signature_def serving_default --dir {MODEL_LOCATION}",
"The given SavedModel SignatureDef contains the following input(s):\n inputs['filenames'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: serving_default_filenames:0\nThe given SavedModel SignatureDef contains the following output(s):\n outputs['flower_type_int'] tensor_info:\n dtype: DT_INT64\n shape: (-1)\n name: StatefulPartitionedCall:0\n outputs['flower_type_str'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: StatefulPartitionedCall:1\n outputs['probability'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1)\n name: StatefulPartitionedCall:2\nMethod name is: tensorflow/serving/predict\n"
]
],
[
[
"## Passing through an input\n\nNote that the signature doesn't tell us the input filename.\nLet's add that.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nimport os, shutil\nmodel = tf.keras.models.load_model(MODEL_LOCATION)\n\[email protected](input_signature=[tf.TensorSpec([None,], dtype=tf.string)])\ndef predict_flower_type(filenames):\n old_fn = model.signatures['serving_default']\n result = old_fn(filenames) # has flower_type_int etc.\n result['filename'] = filenames\n return result\n\nshutil.rmtree('export', ignore_errors=True)\nos.mkdir('export')\nmodel.save('export/flowers_model',\n signatures={\n 'serving_default': predict_flower_type\n })",
"WARNING:tensorflow:From /opt/conda/lib/python3.7/site-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis property should not be used in TensorFlow 2.0, as updates are applied automatically.\nWARNING:tensorflow:From /opt/conda/lib/python3.7/site-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis property should not be used in TensorFlow 2.0, as updates are applied automatically.\nINFO:tensorflow:Assets written to: export/flowers_model/assets\n"
],
[
"!saved_model_cli show --tag_set serve --signature_def serving_default --dir export/flowers_model",
"The given SavedModel SignatureDef contains the following input(s):\n inputs['filenames'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: serving_default_filenames:0\nThe given SavedModel SignatureDef contains the following output(s):\n outputs['filename'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: StatefulPartitionedCall:0\n outputs['flower_type_int'] tensor_info:\n dtype: DT_INT64\n shape: (-1)\n name: StatefulPartitionedCall:1\n outputs['flower_type_str'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: StatefulPartitionedCall:2\n outputs['probability'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1)\n name: StatefulPartitionedCall:3\nMethod name is: tensorflow/serving/predict\n"
],
[
"import tensorflow as tf\nserving_fn = tf.keras.models.load_model('export/flowers_model').signatures['serving_default']\nfilenames = [\n 'gs://cloud-ml-data/img/flower_photos/dandelion/9818247_e2eac18894.jpg',\n 'gs://cloud-ml-data/img/flower_photos/dandelion/9853885425_4a82356f1d_m.jpg',\n 'gs://cloud-ml-data/img/flower_photos/daisy/9299302012_958c70564c_n.jpg',\n 'gs://cloud-ml-data/img/flower_photos/tulips/8733586143_3139db6e9e_n.jpg',\n 'gs://cloud-ml-data/img/flower_photos/tulips/8713397358_0505cc0176_n.jpg'\n]\npred = serving_fn(tf.convert_to_tensor(filenames))\nprint(pred)",
"{'filename': <tf.Tensor: shape=(5,), dtype=string, numpy=\narray([b'gs://cloud-ml-data/img/flower_photos/dandelion/9818247_e2eac18894.jpg',\n b'gs://cloud-ml-data/img/flower_photos/dandelion/9853885425_4a82356f1d_m.jpg',\n b'gs://cloud-ml-data/img/flower_photos/daisy/9299302012_958c70564c_n.jpg',\n b'gs://cloud-ml-data/img/flower_photos/tulips/8733586143_3139db6e9e_n.jpg',\n b'gs://cloud-ml-data/img/flower_photos/tulips/8713397358_0505cc0176_n.jpg'],\n dtype=object)>, 'probability': <tf.Tensor: shape=(5,), dtype=float32, numpy=\narray([0.61915255, 0.9999844 , 0.995083 , 0.97518593, 0.954918 ],\n dtype=float32)>, 'flower_type_int': <tf.Tensor: shape=(5,), dtype=int64, numpy=array([1, 1, 0, 4, 4])>, 'flower_type_str': <tf.Tensor: shape=(5,), dtype=string, numpy=\narray([b'dandelion', b'dandelion', b'daisy', b'tulips', b'tulips'],\n dtype=object)>}\n"
]
],
[
[
"## Multiple signatures\n",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nimport os, shutil\nmodel = tf.keras.models.load_model(MODEL_LOCATION)\nold_fn = model.signatures['serving_default']\n\[email protected](input_signature=[tf.TensorSpec([None,], dtype=tf.string)])\ndef pass_through_input(filenames):\n result = old_fn(filenames) # has flower_type_int etc.\n result['filename'] = filenames\n return result\n\nshutil.rmtree('export', ignore_errors=True)\nos.mkdir('export')\nmodel.save('export/flowers_model2',\n signatures={\n 'serving_default': old_fn,\n 'input_pass_through': pass_through_input\n })",
"INFO:tensorflow:Assets written to: export/flowers_model2/assets\n"
],
[
"!saved_model_cli show --tag_set serve --dir export/flowers_model2",
"The given SavedModel MetaGraphDef contains SignatureDefs with the following keys:\nSignatureDef key: \"__saved_model_init_op\"\nSignatureDef key: \"input_pass_through\"\nSignatureDef key: \"serving_default\"\n"
],
[
"!saved_model_cli show --tag_set serve --dir export/flowers_model2 --signature_def serving_default",
"The given SavedModel SignatureDef contains the following input(s):\n inputs['filenames'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: serving_default_filenames:0\nThe given SavedModel SignatureDef contains the following output(s):\n outputs['flower_type_int'] tensor_info:\n dtype: DT_INT64\n shape: (-1)\n name: StatefulPartitionedCall_1:0\n outputs['flower_type_str'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: StatefulPartitionedCall_1:1\n outputs['probability'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1)\n name: StatefulPartitionedCall_1:2\nMethod name is: tensorflow/serving/predict\n"
],
[
"!saved_model_cli show --tag_set serve --dir export/flowers_model2 --signature_def input_pass_through",
"The given SavedModel SignatureDef contains the following input(s):\n inputs['filenames'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: input_pass_through_filenames:0\nThe given SavedModel SignatureDef contains the following output(s):\n outputs['filename'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: StatefulPartitionedCall:0\n outputs['flower_type_int'] tensor_info:\n dtype: DT_INT64\n shape: (-1)\n name: StatefulPartitionedCall:1\n outputs['flower_type_str'] tensor_info:\n dtype: DT_STRING\n shape: (-1)\n name: StatefulPartitionedCall:2\n outputs['probability'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1)\n name: StatefulPartitionedCall:3\nMethod name is: tensorflow/serving/predict\n"
]
],
[
[
"## Deploying multi-signature model as REST API",
"_____no_output_____"
]
],
[
[
"!./caip_deploy.sh --version multi --model_location ./export/flowers_model2",
"Deploying flowers:multi from ./export/flowers_model2\nUsing endpoint [https://ml.googleapis.com/]\nThe model named flowers already exists.\nUsing endpoint [https://ml.googleapis.com/]\nCreating flowers:multi\nUsing endpoint [https://ml.googleapis.com/]\n"
],
[
"%%writefile request.json\n{\n \"instances\": [\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9818247_e2eac18894.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9853885425_4a82356f1d_m.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/daisy/9299302012_958c70564c_n.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/tulips/8733586143_3139db6e9e_n.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/tulips/8713397358_0505cc0176_n.jpg\"\n }\n ]\n}",
"Overwriting request.json\n"
],
[
"!gcloud ai-platform predict --model=flowers --version=multi --json-request=request.json",
"Using endpoint [https://ml.googleapis.com/]\nFLOWER_TYPE_INT FLOWER_TYPE_STR PROBABILITY\n1 dandelion 0.619152\n1 dandelion 0.999984\n0 daisy 0.995083\n4 tulips 0.975186\n4 tulips 0.954917\n"
],
[
"%%writefile request.json\n{\n \"signature_name\": \"input_pass_through\",\n \"instances\": [\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9818247_e2eac18894.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9853885425_4a82356f1d_m.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/daisy/9299302012_958c70564c_n.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/tulips/8733586143_3139db6e9e_n.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/tulips/8713397358_0505cc0176_n.jpg\"\n }\n ]\n}",
"Overwriting request.json\n"
],
[
"!gcloud ai-platform predict --model=flowers --version=multi --json-request=request.json",
"Using endpoint [https://ml.googleapis.com/]\nFLOWER_TYPE_INT FLOWER_TYPE_STR PROBABILITY\n1 dandelion 0.619152\n1 dandelion 0.999984\n0 daisy 0.995083\n4 tulips 0.975186\n4 tulips 0.954917\n"
]
],
[
[
"that's a bug ... filed a bug report; hope it's fixed by the time you are reading the book.",
"_____no_output_____"
]
],
[
[
"from oauth2client.client import GoogleCredentials\nimport requests\nimport json\n\nPROJECT = 'ai-analytics-solutions' # CHANGE\nMODEL_NAME = 'flowers'\nMODEL_VERSION = 'multi'\n\ntoken = GoogleCredentials.get_application_default().get_access_token().access_token\napi = 'https://ml.googleapis.com/v1/projects/{}/models/{}/versions/{}:predict' \\\n .format(PROJECT, MODEL_NAME, MODEL_VERSION)\nheaders = {'Authorization': 'Bearer ' + token }\ndata = {\n \"signature_name\": \"input_pass_through\",\n \"instances\": [\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9818247_e2eac18894.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9853885425_4a82356f1d_m.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/daisy/9299302012_958c70564c_n.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/tulips/8733586143_3139db6e9e_n.jpg\"\n },\n {\n \"filenames\": \"gs://cloud-ml-data/img/flower_photos/tulips/8713397358_0505cc0176_n.jpg\"\n }\n ]\n}\nresponse = requests.post(api, json=data, headers=headers)\nprint(response.content.decode('utf-8'))",
"{\"predictions\": [{\"filename\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9818247_e2eac18894.jpg\", \"flower_type_int\": 1, \"flower_type_str\": \"dandelion\", \"probability\": 0.6191519498825073}, {\"filename\": \"gs://cloud-ml-data/img/flower_photos/dandelion/9853885425_4a82356f1d_m.jpg\", \"flower_type_int\": 1, \"flower_type_str\": \"dandelion\", \"probability\": 0.9999843835830688}, {\"filename\": \"gs://cloud-ml-data/img/flower_photos/daisy/9299302012_958c70564c_n.jpg\", \"flower_type_int\": 0, \"flower_type_str\": \"daisy\", \"probability\": 0.9950828552246094}, {\"filename\": \"gs://cloud-ml-data/img/flower_photos/tulips/8733586143_3139db6e9e_n.jpg\", \"flower_type_int\": 4, \"flower_type_str\": \"tulips\", \"probability\": 0.9751859307289124}, {\"filename\": \"gs://cloud-ml-data/img/flower_photos/tulips/8713397358_0505cc0176_n.jpg\", \"flower_type_int\": 4, \"flower_type_str\": \"tulips\", \"probability\": 0.954916775226593}]}\n"
]
],
[
[
"## License\nCopyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.",
"_____no_output_____"
]
]
] |
[
"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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a907000c2b4ff9e2d14d0fdfe6632991e87dde1
| 61,927 |
ipynb
|
Jupyter Notebook
|
naive_imdb_model.ipynb
|
Miseq/naive_imdb_reviews_model
|
d185dab77a3aeb84c5bcd30fea77c9afac970830
|
[
"MIT"
] | 1 |
2020-06-13T08:04:18.000Z
|
2020-06-13T08:04:18.000Z
|
naive_imdb_model.ipynb
|
Miseq/naive_imdb_reviews_model
|
d185dab77a3aeb84c5bcd30fea77c9afac970830
|
[
"MIT"
] | null | null | null |
naive_imdb_model.ipynb
|
Miseq/naive_imdb_reviews_model
|
d185dab77a3aeb84c5bcd30fea77c9afac970830
|
[
"MIT"
] | null | null | null | 84.484311 | 17,838 | 0.735996 |
[
[
[
"<a href=\"https://colab.research.google.com/github/Miseq/naive_imdb_reviews_model/blob/master/naive_imdb_model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"from keras.datasets import imdb\nfrom keras import optimizers\nfrom keras import losses\nfrom keras import metrics\nfrom keras import models\nfrom keras import layers\nimport matplotlib.pyplot as plt\n\nimport numpy as np",
"_____no_output_____"
],
[
"def vectorize_data(data, dimension=10000):\n result = np.zeros((len(data), dimension))\n for i, seq in enumerate(data):\n result[i, seq] = 1.\n return result",
"_____no_output_____"
],
[
"(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)\n",
"_____no_output_____"
],
[
"x_train = vectorize_data(train_data)\nx_test = vectorize_data(test_data)\n\ny_train = np.asarray(train_labels).astype('float32')\ny_test = np.asarray(test_labels).astype('float32')",
"_____no_output_____"
],
[
"model = models.Sequential()\nmodel.add(layers.Dense(16, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=['accuracy'])",
"_____no_output_____"
],
[
"x_val = x_train[:20000]\npartial_x_train = x_train[20000:]\n\ny_val = y_train[:20000]\npartial_y_train = y_train[20000:]\n\nhistory = model.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))",
"Train on 5000 samples, validate on 20000 samples\nEpoch 1/20\n5000/5000 [==============================] - 2s 451us/step - loss: 0.6326 - acc: 0.6700 - val_loss: 0.5478 - val_acc: 0.8269\nEpoch 2/20\n5000/5000 [==============================] - 2s 400us/step - loss: 0.4662 - acc: 0.8814 - val_loss: 0.4704 - val_acc: 0.8316\nEpoch 3/20\n5000/5000 [==============================] - 2s 401us/step - loss: 0.3648 - acc: 0.9076 - val_loss: 0.4142 - val_acc: 0.8445\nEpoch 4/20\n5000/5000 [==============================] - 2s 407us/step - loss: 0.2858 - acc: 0.9364 - val_loss: 0.3652 - val_acc: 0.8655\nEpoch 5/20\n5000/5000 [==============================] - 2s 407us/step - loss: 0.2300 - acc: 0.9528 - val_loss: 0.3373 - val_acc: 0.8712\nEpoch 6/20\n5000/5000 [==============================] - 2s 402us/step - loss: 0.1875 - acc: 0.9638 - val_loss: 0.3312 - val_acc: 0.8663\nEpoch 7/20\n5000/5000 [==============================] - 2s 405us/step - loss: 0.1462 - acc: 0.9748 - val_loss: 0.3177 - val_acc: 0.8695\nEpoch 8/20\n5000/5000 [==============================] - 2s 400us/step - loss: 0.1219 - acc: 0.9802 - val_loss: 0.3105 - val_acc: 0.8735\nEpoch 9/20\n5000/5000 [==============================] - 2s 405us/step - loss: 0.0933 - acc: 0.9910 - val_loss: 0.3210 - val_acc: 0.8680\nEpoch 10/20\n5000/5000 [==============================] - 2s 405us/step - loss: 0.0779 - acc: 0.9938 - val_loss: 0.3201 - val_acc: 0.8701\nEpoch 11/20\n5000/5000 [==============================] - 2s 400us/step - loss: 0.0609 - acc: 0.9956 - val_loss: 0.3244 - val_acc: 0.8688\nEpoch 12/20\n5000/5000 [==============================] - 2s 397us/step - loss: 0.0460 - acc: 0.9976 - val_loss: 0.3414 - val_acc: 0.8666\nEpoch 13/20\n5000/5000 [==============================] - 2s 396us/step - loss: 0.0401 - acc: 0.9976 - val_loss: 0.3702 - val_acc: 0.8595\nEpoch 14/20\n5000/5000 [==============================] - 2s 397us/step - loss: 0.0284 - acc: 0.9988 - val_loss: 0.3639 - val_acc: 0.8639\nEpoch 15/20\n5000/5000 [==============================] - 2s 398us/step - loss: 0.0223 - acc: 0.9990 - val_loss: 0.3771 - val_acc: 0.8640\nEpoch 16/20\n5000/5000 [==============================] - 2s 392us/step - loss: 0.0184 - acc: 0.9990 - val_loss: 0.4321 - val_acc: 0.8571\nEpoch 17/20\n5000/5000 [==============================] - 2s 398us/step - loss: 0.0127 - acc: 0.9994 - val_loss: 0.4118 - val_acc: 0.8617\nEpoch 18/20\n5000/5000 [==============================] - 2s 398us/step - loss: 0.0095 - acc: 0.9996 - val_loss: 0.4326 - val_acc: 0.8603\nEpoch 19/20\n5000/5000 [==============================] - 2s 395us/step - loss: 0.0067 - acc: 1.0000 - val_loss: 0.4570 - val_acc: 0.8583\nEpoch 20/20\n5000/5000 [==============================] - 2s 396us/step - loss: 0.0048 - acc: 1.0000 - val_loss: 0.4997 - val_acc: 0.8546\n"
],
[
"history_dict = history.history\nhistory_dict.keys()",
"_____no_output_____"
],
[
"acc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc)+1)",
"_____no_output_____"
],
[
"# Tworzenie wykresu start tenowania i walidacji\nplt.plot(epochs, loss, 'bo', label='Strata trenowania')\nplt.plot(epochs, val_loss, 'b', label='Strata walidacji')\nplt.title('Strata renowania i walidacji')\nplt.xlabel('Epoki')\nplt.ylabel('Strata')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"# Tworzenie wykresu dokładności trenowania i walidacji\nplt.clf() # Czyszczenie rysunku(wazne)\nacc_values = history_dict['acc']\nval_acc_vales = history_dict['val_acc']\n\nplt.plot(epochs, acc, 'bo', label='Dokladnosc trenowania')\nplt.plot(epochs, val_acc, 'b', label='Dokladnosc walidacji')\nplt.title('Dokladnosc trenowania i walidacji')\nplt.xlabel('Epoki')\nplt.ylabel('Strata')\nplt.legend()\n\nplt.show()",
"_____no_output_____"
],
[
"min_loss_val = min(val_loss)\nmax_acc_val = max(val_acc)\n\nmin_loss_ix = val_loss.index(min_loss_val)\nmax_acc_ix = val_acc.index(max_acc_val)\nprint(f'{min_loss_ix} --- {max_acc_ix}')",
"7 --- 7\n"
]
],
[
[
"Po 7 epoce model zaczyna być przetrenowany",
"_____no_output_____"
]
],
[
[
"model.fit(x_train, y_train, epochs=7, batch_size=512, validation_data=(x_val, y_val))",
"Train on 25000 samples, validate on 20000 samples\nEpoch 1/7\n25000/25000 [==============================] - 5s 180us/step - loss: 0.3325 - acc: 0.8933 - val_loss: 0.2550 - val_acc: 0.9036\nEpoch 2/7\n25000/25000 [==============================] - 4s 174us/step - loss: 0.2126 - acc: 0.9207 - val_loss: 0.1963 - val_acc: 0.9266\nEpoch 3/7\n25000/25000 [==============================] - 4s 174us/step - loss: 0.1730 - acc: 0.9357 - val_loss: 0.1623 - val_acc: 0.9403\nEpoch 4/7\n25000/25000 [==============================] - 4s 176us/step - loss: 0.1441 - acc: 0.9458 - val_loss: 0.1304 - val_acc: 0.9542\nEpoch 5/7\n25000/25000 [==============================] - 4s 173us/step - loss: 0.1204 - acc: 0.9555 - val_loss: 0.1144 - val_acc: 0.9587\nEpoch 6/7\n25000/25000 [==============================] - 4s 172us/step - loss: 0.1027 - acc: 0.9640 - val_loss: 0.0872 - val_acc: 0.9725\nEpoch 7/7\n25000/25000 [==============================] - 4s 175us/step - loss: 0.0857 - acc: 0.9708 - val_loss: 0.0732 - val_acc: 0.9777\n"
],
[
"results = model.evaluate(x_test, y_test)",
"25000/25000 [==============================] - 2s 72us/step\n"
],
[
"results",
"_____no_output_____"
]
],
[
[
"## Wiecej warstw ukrytych",
"_____no_output_____"
]
],
[
[
"model = models.Sequential()\nmodel.add(layers.Dense(16, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(8, activation='relu'))\nmodel.add(layers.Dense(4, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=['accuracy'])",
"_____no_output_____"
],
[
"model.fit(x_train, y_train, epochs=10, batch_size=512, validation_data=(x_val, y_val))\nresults = model.evaluate(x_test, y_test)",
"Train on 25000 samples, validate on 20000 samples\nEpoch 1/10\n25000/25000 [==============================] - 5s 195us/step - loss: 0.4693 - acc: 0.8129 - val_loss: 0.2898 - val_acc: 0.9149\nEpoch 2/10\n25000/25000 [==============================] - 4s 173us/step - loss: 0.2685 - acc: 0.9068 - val_loss: 0.1943 - val_acc: 0.9414\nEpoch 3/10\n25000/25000 [==============================] - 4s 174us/step - loss: 0.2045 - acc: 0.9293 - val_loss: 0.1768 - val_acc: 0.9363\nEpoch 4/10\n25000/25000 [==============================] - 4s 173us/step - loss: 0.1681 - acc: 0.9418 - val_loss: 0.1281 - val_acc: 0.9627\nEpoch 5/10\n25000/25000 [==============================] - 4s 172us/step - loss: 0.1484 - acc: 0.9493 - val_loss: 0.1158 - val_acc: 0.9645\nEpoch 6/10\n25000/25000 [==============================] - 4s 173us/step - loss: 0.1293 - acc: 0.9563 - val_loss: 0.1697 - val_acc: 0.9266\nEpoch 7/10\n25000/25000 [==============================] - 4s 170us/step - loss: 0.1152 - acc: 0.9608 - val_loss: 0.1043 - val_acc: 0.9665\nEpoch 8/10\n25000/25000 [==============================] - 4s 173us/step - loss: 0.1059 - acc: 0.9652 - val_loss: 0.0746 - val_acc: 0.9804\nEpoch 9/10\n25000/25000 [==============================] - 4s 173us/step - loss: 0.0958 - acc: 0.9692 - val_loss: 0.0685 - val_acc: 0.9820\nEpoch 10/10\n25000/25000 [==============================] - 4s 170us/step - loss: 0.0849 - acc: 0.9727 - val_loss: 0.0665 - val_acc: 0.9824\n25000/25000 [==============================] - 2s 72us/step\n"
],
[
"results",
"_____no_output_____"
]
],
[
[
"## Wieksza ilosc jednostek ukrytych",
"_____no_output_____"
]
],
[
[
"model = models.Sequential()\nmodel.add(layers.Dense(64, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(32, activation='relu'))\nmodel.add(layers.Dense(16, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=10, batch_size=512, validation_data=(x_val, y_val))\nresults = model.evaluate(x_test, y_test)\n\nresults",
"Train on 25000 samples, validate on 20000 samples\nEpoch 1/10\n25000/25000 [==============================] - 6s 243us/step - loss: 0.4332 - acc: 0.8121 - val_loss: 0.2595 - val_acc: 0.9055\nEpoch 2/10\n25000/25000 [==============================] - 5s 217us/step - loss: 0.2454 - acc: 0.9061 - val_loss: 0.1678 - val_acc: 0.9447\nEpoch 3/10\n25000/25000 [==============================] - 5s 213us/step - loss: 0.1899 - acc: 0.9277 - val_loss: 0.1523 - val_acc: 0.9448\nEpoch 4/10\n25000/25000 [==============================] - 5s 212us/step - loss: 0.1546 - acc: 0.9405 - val_loss: 0.1261 - val_acc: 0.9543\nEpoch 5/10\n25000/25000 [==============================] - 5s 217us/step - loss: 0.1230 - acc: 0.9549 - val_loss: 0.0732 - val_acc: 0.9782\nEpoch 6/10\n25000/25000 [==============================] - 5s 216us/step - loss: 0.1051 - acc: 0.9616 - val_loss: 0.0589 - val_acc: 0.9832\nEpoch 7/10\n25000/25000 [==============================] - 5s 217us/step - loss: 0.0836 - acc: 0.9698 - val_loss: 0.0770 - val_acc: 0.9722\nEpoch 8/10\n25000/25000 [==============================] - 5s 219us/step - loss: 0.0613 - acc: 0.9788 - val_loss: 0.0314 - val_acc: 0.9929\nEpoch 9/10\n25000/25000 [==============================] - 5s 217us/step - loss: 0.0475 - acc: 0.9845 - val_loss: 0.0417 - val_acc: 0.9879\nEpoch 10/10\n25000/25000 [==============================] - 5s 216us/step - loss: 0.0377 - acc: 0.9902 - val_loss: 0.0143 - val_acc: 0.9979\n25000/25000 [==============================] - 2s 88us/step\n"
]
],
[
[
"## Funkcja straty mse",
"_____no_output_____"
]
],
[
[
"model = models.Sequential()\nmodel.add(layers.Dense(64, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(32, activation='relu'))\nmodel.add(layers.Dense(16, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.mse, metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=10, batch_size=512, validation_data=(x_val, y_val))\nresults = model.evaluate(x_test, y_test)\n\nresults",
"Train on 25000 samples, validate on 20000 samples\nEpoch 1/10\n25000/25000 [==============================] - 6s 240us/step - loss: 0.1502 - acc: 0.8012 - val_loss: 0.0788 - val_acc: 0.9103\nEpoch 2/10\n25000/25000 [==============================] - 5s 214us/step - loss: 0.0760 - acc: 0.9044 - val_loss: 0.0499 - val_acc: 0.9434\nEpoch 3/10\n25000/25000 [==============================] - 5s 214us/step - loss: 0.0576 - acc: 0.9267 - val_loss: 0.0397 - val_acc: 0.9535\nEpoch 4/10\n25000/25000 [==============================] - 5s 211us/step - loss: 0.0463 - acc: 0.9422 - val_loss: 0.0295 - val_acc: 0.9670\nEpoch 5/10\n25000/25000 [==============================] - 5s 212us/step - loss: 0.0392 - acc: 0.9509 - val_loss: 0.0253 - val_acc: 0.9718\nEpoch 6/10\n25000/25000 [==============================] - 5s 206us/step - loss: 0.0323 - acc: 0.9610 - val_loss: 0.0270 - val_acc: 0.9699\nEpoch 7/10\n25000/25000 [==============================] - 5s 205us/step - loss: 0.0255 - acc: 0.9704 - val_loss: 0.0164 - val_acc: 0.9837\nEpoch 8/10\n25000/25000 [==============================] - 5s 207us/step - loss: 0.0223 - acc: 0.9746 - val_loss: 0.0114 - val_acc: 0.9890\nEpoch 9/10\n25000/25000 [==============================] - 5s 207us/step - loss: 0.0181 - acc: 0.9794 - val_loss: 0.0144 - val_acc: 0.9864\nEpoch 10/10\n25000/25000 [==============================] - 5s 208us/step - loss: 0.0132 - acc: 0.9856 - val_loss: 0.0071 - val_acc: 0.9933\n25000/25000 [==============================] - 2s 87us/step\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a90774ffca92e60d92cca6c4a833df3aeb0177d
| 47,223 |
ipynb
|
Jupyter Notebook
|
test/Models/pheno_pkg/test/java/Updatephase.ipynb
|
cyrillemidingoyi/PyCropML
|
b866cc17374424379142d9162af985c1f87c74b6
|
[
"MIT"
] | 5 |
2020-06-21T18:58:04.000Z
|
2022-01-29T21:32:28.000Z
|
test/Models/pheno_pkg/test/java/Updatephase.ipynb
|
cyrillemidingoyi/PyCropML
|
b866cc17374424379142d9162af985c1f87c74b6
|
[
"MIT"
] | 27 |
2018-12-04T15:35:44.000Z
|
2022-03-11T08:25:03.000Z
|
test/Models/pheno_pkg/test/java/Updatephase.ipynb
|
cyrillemidingoyi/PyCropML
|
b866cc17374424379142d9162af985c1f87c74b6
|
[
"MIT"
] | 7 |
2019-04-20T02:25:22.000Z
|
2021-11-04T07:52:35.000Z
| 44.466102 | 143 | 0.420177 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a9080dbb7fc640030d8dcde6a05295a6f70a132
| 1,564 |
ipynb
|
Jupyter Notebook
|
dijkstra_algorithm.ipynb
|
lmsupc/wv71_tf_201617515_201816689
|
1a49794513c15556cbe02a36cd09312c29f2c7eb
|
[
"MIT"
] | null | null | null |
dijkstra_algorithm.ipynb
|
lmsupc/wv71_tf_201617515_201816689
|
1a49794513c15556cbe02a36cd09312c29f2c7eb
|
[
"MIT"
] | 14 |
2021-10-01T00:27:26.000Z
|
2021-11-12T18:02:20.000Z
|
dijkstra_algorithm.ipynb
|
lmsupc/wv71_tf_201617515_201816689
|
1a49794513c15556cbe02a36cd09312c29f2c7eb
|
[
"MIT"
] | null | null | null | 43.444444 | 229 | 0.654092 |
[
[
[
"#Algoritmo Dijkstra\nPara la solución del problema de enrutamiento de vehículos, se utilizará el algoritmo Dijkstra para encontrar el camino más corto desde un almacén hasta un punto de entrega. Los pasos a considerar son los siguientes:\n\n1. Se deberá considerar a todos los puntos de entrega como nodos. Solo se deberá considerar un almacén como nodo y al resto no. Las demás intersecciones en la ciudad también serán consideradas nodos.\n2. Establecer las aristas que unirán a los nodos. El peso de todas las aristas serán iguales.\n3. El almacén seleccionado en el punto anterior será el nodo inicial.\n4. Usando el algoritmo Dijkstra se encontrará el camino más corto partiendo desde el almacén hacia los demás puntos de entrega.\n5. Se repetirá el mismo proceso varias veces con los otros almacenes como nodo incial.\n6. Finalmente, comparando los caminos encontrados desde diferentes almacenes hacia un mismo punto de entrega, se escogerá solo al almacén que se ubique más cerca y se descartará a los demás almacenes.",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
4a9087bf698086bad1a104221036db626fc47bcf
| 8,274 |
ipynb
|
Jupyter Notebook
|
shortest-path/dijsktra.ipynb
|
jhultman/Robotics
|
7ffeb0ad943737827be69f05a30c8e8c1e7f40f1
|
[
"MIT"
] | null | null | null |
shortest-path/dijsktra.ipynb
|
jhultman/Robotics
|
7ffeb0ad943737827be69f05a30c8e8c1e7f40f1
|
[
"MIT"
] | null | null | null |
shortest-path/dijsktra.ipynb
|
jhultman/Robotics
|
7ffeb0ad943737827be69f05a30c8e8c1e7f40f1
|
[
"MIT"
] | 1 |
2018-12-15T00:09:50.000Z
|
2018-12-15T00:09:50.000Z
| 38.305556 | 2,580 | 0.602369 |
[
[
[
"import numpy as np\nimport heapq\nimport matplotlib.pyplot as plt\n\nfrom math import inf\nfrom itertools import product\n\n%matplotlib inline",
"_____no_output_____"
],
[
"class PQ(object):\n '''Wrapper object for heapq module'''\n def __init__(self, data, key):\n self.key = key\n self._data = [(key(elt), elt) for elt in data]\n heapq.heapify(self._data)\n \n def push(self, elt):\n heapq.heappush(self._data, (self.key(elt), elt))\n \n def pop(self):\n return heapq.heappop(self._data)[1]",
"_____no_output_____"
],
[
"class Dijkstra:\n '''0s in grid mark free space, 1s mark obstacles'''\n \n def __init__(self, grid, start, dest):\n self.grid = grid\n self.start = start\n self.dest = dest\n self.route = []\n self.came_from = {start: start}\n self.dist_to = np.array([[inf] * grid.shape[1]] * grid.shape[0])\n self.dist_to[start] = 0\n\n\n def dijsktra(self):\n seen = set()\n y0, y1 = self.start[0], self.start[1]\n manhattan = lambda x: abs(x[0] - y0) + abs(x[1] - y1)\n frontier = PQ(data=[self.start], key=manhattan)\n\n while frontier:\n curr = frontier.pop()\n seen.add(curr)\n for nbr in self.get_neighbors(*curr):\n if nbr not in seen: \n self.visit_neighbor(curr, nbr)\n frontier.push(nbr)\n if nbr == self.dest:\n frontier = []\n break\n\n self.build_route()\n return self.route\n\n\n def build_route(self):\n node = self.dest\n route = [self.dest]\n while node != self.came_from[node]:\n node = self.came_from[node]\n route += [node]\n self.route = list(reversed(route))\n \n \n def visit_neighbor(self, curr, nbr):\n tentative_dist = self.dist_to[curr] + 1\n if tentative_dist < self.dist_to[nbr]:\n self.dist_to[nbr] = tentative_dist\n self.came_from[nbr] = curr\n \n \n def get_neighbors(self, i, j):\n m, n = self.grid.shape\n in_bounds = lambda x: 0 <= x[0] < m and 0 <= x[1] < n\n available = lambda x: (x[0]==i) != (x[1]==j) and self.grid[x] != 1\n candidates = product(range(i-1, i+2), range(j-1, j+2))\n return filter(available, filter(in_bounds, candidates))\n \n \n def visualize(self):\n route = list(map(list, zip(*self.route)))\n self.grid[route] = 2\n self.grid[self.start] = 3\n self.grid[self.dest] = 4\n \n f, ax = plt.subplots()\n ax.imshow(self.grid)\n ax.set_axis_off()\n ax.set_title('Dijkstra')\n plt.show()",
"_____no_output_____"
],
[
"def add_obstacles(grid, obstacles):\n for obs in obstacles:\n grid[obs] = 1",
"_____no_output_____"
],
[
"def setup_grid():\n grid = np.zeros((10, 10), dtype=int)\n\n o1 = ([2] * 6, range(3, 9))\n o2 = ([6] * 2, range(6, 8))\n o3 = (range(5, 9), [5] * 4)\n\n add_obstacles(grid, [o1, o2, o3])\n return grid",
"_____no_output_____"
],
[
"def main():\n grid = setup_grid()\n start = (0, 1)\n dest = (8, 7)\n \n d = Dijkstra(grid, start, dest)\n route = d.dijsktra()\n d.visualize()",
"_____no_output_____"
],
[
"if __name__ == '__main__':\n main()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a908a747e6c5a95d4941f6699866b5ca7e24c3f
| 8,717 |
ipynb
|
Jupyter Notebook
|
extraerExcel-oneDrive.ipynb
|
Sud-Austral/Datos2
|
33f5d84f270bf3f55aa351fe8f3f1aeac4089b45
|
[
"MIT"
] | null | null | null |
extraerExcel-oneDrive.ipynb
|
Sud-Austral/Datos2
|
33f5d84f270bf3f55aa351fe8f3f1aeac4089b45
|
[
"MIT"
] | null | null | null |
extraerExcel-oneDrive.ipynb
|
Sud-Austral/Datos2
|
33f5d84f270bf3f55aa351fe8f3f1aeac4089b45
|
[
"MIT"
] | null | null | null | 47.375 | 181 | 0.622806 |
[
[
[
"import pandas as pd\nimport urllib3\n",
"_____no_output_____"
],
[
"def datacovidChile(): \n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62342&parId=9F999E057AD8C646!62390&authkey=!AgJICaWKd7tHakw&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/BASE CALCULO COMUNA.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62359&parId=9F999E057AD8C646!62390&authkey=!AgJICaWKd7tHakw&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/casos por comuna listos.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62361&parId=9F999E057AD8C646!62390&authkey=!AgJICaWKd7tHakw&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/Covid Chile V2.xlsx\")\n\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62377&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/00 DATACOVID Trabajo_HN.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62380&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/00 DATACOVID_HN_CUARENTENA.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62388&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/ALIMENTACION_HN.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62372&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/Covid HN.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62386&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/FARMACIAS_HN.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62378&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/LOCALIZA HN.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62384&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/SALUD_HN.xlsx\")\n\n url = \"https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62381&parId=9F999E057AD8C646!62371&authkey=!Au8PrBa4C6_6k_M&app=Excel\"\n urllib.request.urlretrieve(url, \"datacovidChile/Tabla_INSTALACIONES_Honduras_v1.xlsx\")\n return\n",
"_____no_output_____"
],
[
"def csvHoja_datacovidChile(): \n dato = pd.read_excel(\"datacovidChile/00 DATACOVID Trabajo_HN.xlsx\", sheet_name=\"trabajo\")\n dato.to_csv(\"datacovidChile/csv/00 DATACOVID Trabajo_HN-trabajo.csv\", index = False)\n\n dato = pd.read_excel(\"datacovidChile/00 DATACOVID_HN_CUARENTENA.xlsx\", sheet_name=\"Cuarentena_HN\")\n dato.to_csv(\"datacovidChile/csv/00 DATACOVID_HN_CUARENTENA-Cuarentena_HN.csv\", index = False)\n\n dato = pd.read_excel(\"datacovidChile/ALIMENTACION_HN.xlsx\", sheet_name=\"ALIMENTACION\")\n dato.to_csv(\"datacovidChile/csv/ALIMENTACION_HN-ALIMENTACION.csv\", index = False)\n\n dato = pd.read_excel(\"datacovidChile/BASE CALCULO COMUNA.xlsx\", sheet_name=None)\n sheets = dato.keys()\n\n for sheet_name in sheets:\n sheet = pd.read_excel(\"datacovidChile/BASE CALCULO COMUNA.xlsx\", sheet_name=sheet_name)\n #borra la fila si todos los valores son NaN\n sheet.dropna(axis = 0, how = 'all', inplace = True)\n #borra la fila de los Unnamed y pone la siguiente fila como encabezado\n if(sheet.columns[0] == 'Unnamed: 0'):\n sheet.columns = sheet.iloc[0]\n sheet = sheet.iloc[1:,].reindex()\n \n sheet.to_csv(\"datacovidChile/csv/BASE CALCULO COMUNA-%s.csv\" % sheet_name, index=False)\n \n\n\n dato = pd.read_excel(\"datacovidChile/casos por comuna listos.xlsx\", sheet_name=None)\n sheets = dato.keys()\n\n for sheet_name in sheets:\n sheet = pd.read_excel(\"datacovidChile/casos por comuna listos.xlsx\", sheet_name=sheet_name)\n sheet.dropna(axis = 0, how = 'all', inplace = True)\n if(sheet.columns[0] == 'Unnamed: 0'):\n sheet.columns = sheet.iloc[0]\n sheet = sheet.iloc[1:,].reindex()\n \n sheet.to_csv(\"datacovidChile/csv/casos por comuna listos-%s.csv\" % sheet_name, index=False)\n\n\n dato = pd.read_excel(\"datacovidChile/Covid Chile V2.xlsx\", sheet_name=None)\n sheets = dato.keys()\n\n for sheet_name in sheets:\n sheet = pd.read_excel(\"datacovidChile/Covid Chile V2.xlsx\", sheet_name=sheet_name)\n sheet.dropna(axis = 0, how = 'all', inplace = True)\n if(sheet.columns[0] == 'Unnamed: 0'):\n sheet.columns = sheet.iloc[0]\n sheet = sheet.iloc[1:,].reindex()\n sheet.to_csv(\"datacovidChile/csv/Covid Chile V2-%s.csv\" % sheet_name, index=False)\n\n\n dato = pd.read_excel(\"datacovidChile/Covid HN.xlsx\", sheet_name=None)\n sheets = dato.keys()\n\n for sheet_name in sheets:\n sheet = pd.read_excel(\"datacovidChile/Covid HN.xlsx\", sheet_name=sheet_name)\n sheet.dropna(axis = 0, how = 'all', inplace = True)\n if(sheet.columns[0] == 'Unnamed: 0'):\n sheet.columns = sheet.iloc[0]\n sheet = sheet.iloc[1:,].reindex()\n sheet.to_csv(\"datacovidChile/csv/Covid HN-%s.csv\" % sheet_name, index=False)\n\n\n dato = pd.read_excel(\"datacovidChile/FARMACIAS_HN.xlsx\", sheet_name=\"FARMACIAS\")\n dato.to_csv(\"datacovidChile/csv/FARMACIAS_HN-FARMACIAS.csv\", index = False)\n\n dato = pd.read_excel(\"datacovidChile/LOCALIZA HN.xlsx\", sheet_name=\"Hoja1\")\n dato.to_csv(\"datacovidChile/csv/LOCALIZA HN-Hoja1.csv\", index = False)\n\n dato = pd.read_excel(\"datacovidChile/SALUD_HN.xlsx\", sheet_name=\"HOSPITALES\")\n dato.to_csv(\"datacovidChile/csv/SALUD_HN-HOSPITALES.csv\", index = False)\n\n dato = pd.read_excel(\"datacovidChile/Tabla_INSTALACIONES_Honduras_v1.xlsx\", sheet_name=\"Instalaciones_Honduras\")\n dato.to_csv(\"datacovidChile/csv/Tabla_INSTALACIONES_Honduras_v1-Instalaciones_Honduras.csv\", index = False)\n \n return\n",
"_____no_output_____"
],
[
"csvHoja_datacovidChile()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4a908f1b844fd1fa5c698a94affd3601e8cf22f1
| 19,312 |
ipynb
|
Jupyter Notebook
|
hypothesis_17.ipynb
|
IuriSly/DnA-POC-olist
|
925a2392f84438a0d3906c9c8cd467cd461f5f8f
|
[
"MIT"
] | null | null | null |
hypothesis_17.ipynb
|
IuriSly/DnA-POC-olist
|
925a2392f84438a0d3906c9c8cd467cd461f5f8f
|
[
"MIT"
] | null | null | null |
hypothesis_17.ipynb
|
IuriSly/DnA-POC-olist
|
925a2392f84438a0d3906c9c8cd467cd461f5f8f
|
[
"MIT"
] | null | null | null | 138.935252 | 14,764 | 0.863867 |
[
[
[
"# Importing PySpark and opening files",
"_____no_output_____"
]
],
[
[
"from pyspark.sql import SparkSession, functions as F\nspark = SparkSession.builder.getOrCreate()\n\norders_df = spark.read \\\n .option('escape', '\\\"') \\\n .option('quote', '\\\"') \\\n .csv('./dataset/olist_orders_dataset.csv', header=True, multiLine=True, inferSchema=True)\n\nreviews_df = spark.read \\\n .option('escape', '\\\"') \\\n .option('quote', '\\\"') \\\n .csv('./dataset/olist_order_reviews_dataset.csv', header=True, multiLine=True, inferSchema=True)\n\ncustomers_df = spark.read \\\n .option('escape', '\\\"') \\\n .option('quote', '\\\"') \\\n .csv('./dataset/olist_customers_dataset.csv', header=True, multiLine=True, inferSchema=True)\n\norders_df.printSchema()\n\nreviews_df.printSchema()\n\ncustomers_df.printSchema()\n\norders_df = orders_df.select('order_id', 'customer_id')\n\norders_df = orders_df.join(reviews_df, orders_df.order_id == reviews_df.order_id) \\\n .join(customers_df, orders_df.customer_id == customers_df.customer_id) \\\n .select('customer_state', 'review_score')\n\norders_df = orders_df.groupBy('customer_state').agg(F.mean(\"review_score\"), F.stddev(\"review_score\")).orderBy(F.desc('avg(review_score)'))\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(16, 6))\nplt.ylim(3.5, 4.2)\nsns.set(style=\"whitegrid\")\nsns.set(font_scale=1.5)\nax_0 = sns.barplot(x='customer_state', y='avg(review_score)', data=orders_df.toPandas(), color='blue', linewidth=2.5)",
"root\n |-- order_id: string (nullable = true)\n |-- customer_id: string (nullable = true)\n |-- order_status: string (nullable = true)\n |-- order_purchase_timestamp: timestamp (nullable = true)\n |-- order_approved_at: timestamp (nullable = true)\n |-- order_delivered_carrier_date: timestamp (nullable = true)\n |-- order_delivered_customer_date: timestamp (nullable = true)\n |-- order_estimated_delivery_date: timestamp (nullable = true)\n\nroot\n |-- review_id: string (nullable = true)\n |-- order_id: string (nullable = true)\n |-- review_score: integer (nullable = true)\n |-- review_comment_title: string (nullable = true)\n |-- review_comment_message: string (nullable = true)\n |-- review_creation_date: timestamp (nullable = true)\n |-- review_answer_timestamp: timestamp (nullable = true)\n\nroot\n |-- customer_id: string (nullable = true)\n |-- customer_unique_id: string (nullable = true)\n |-- customer_zip_code_prefix: integer (nullable = true)\n |-- customer_city: string (nullable = true)\n |-- customer_state: string (nullable = true)\n\n"
]
],
[
[
"# Conclusion",
"_____no_output_____"
],
[
"### It's possible to conclude that there is some states where the review score average is higher or lower than other states",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4a909f1686aa3345d4d611432d43d472e3eb93c9
| 514,558 |
ipynb
|
Jupyter Notebook
|
class_materials/class_2/Class 2.ipynb
|
ashhadulislam/ML_Course_public
|
3532d755046e511739ae6e06f2c359a124681ad2
|
[
"MIT"
] | null | null | null |
class_materials/class_2/Class 2.ipynb
|
ashhadulislam/ML_Course_public
|
3532d755046e511739ae6e06f2c359a124681ad2
|
[
"MIT"
] | null | null | null |
class_materials/class_2/Class 2.ipynb
|
ashhadulislam/ML_Course_public
|
3532d755046e511739ae6e06f2c359a124681ad2
|
[
"MIT"
] | null | null | null | 13.224313 | 1,810 | 0.166246 |
[
[
[
"### Control Flow\n",
"_____no_output_____"
],
[
"#### Find the largest of three numbers",
"_____no_output_____"
]
],
[
[
"num1 = 100\nnum2 = 200\nnum3 = 1\n\nif (num1>=num2) and (num1 >= num3):\n largest=num1\nelif (num2>=num1) and (num2 >= num3):\n largest=num2\nelif (num3>=num1) and (num3 >= num2):\n largest=num3\nprint(\"Largest number is \", largest)",
"_____no_output_____"
]
],
[
[
"### while loop",
"_____no_output_____"
],
[
"#### Syntax:\nwhile test_expression:\n\n Body of while\n",
"_____no_output_____"
],
[
"#### Example",
"_____no_output_____"
]
],
[
[
"#find the sum of all numbers present in the list\n\nlst=[2,13,21,19,10]\n\nsum_list=0\nindx=0\n\nwhile indx < len(lst):\n sum_list=sum_list+lst[indx]\n indx+=1\n\nprint(\"Total sum is {}\".format(sum_list))\n",
"_____no_output_____"
]
],
[
[
"#### While loop with else ",
"_____no_output_____"
]
],
[
[
"lst=[2,13,21,19,10]\n\nindx=0\n\nwhile indx<len(lst):\n print(lst[indx])\n indx+=1\nelse:\n print(\"Items finished in the list. Index is {}\".format(indx))\n",
"_____no_output_____"
],
[
"# what happens if we forget to increase the index\nlst=[2,13,21,19,10]\n\nindx=0\n\nwhile indx<len(lst):\n print(lst[indx])\n# indx+=1\nelse:\n print(\"Items finished in the list. Index is {}\".format(indx))\n",
"2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n"
]
],
[
[
"#### Program to check if a number is prime",
"_____no_output_____"
]
],
[
[
"num=int(input(\"Enter a number\"))\n\ndiv=2\nisDivisibe=False\n\nwhile div<num:\n if num%div==0:\n isDivisibe=True\n div+=1\n \nif isDivisibe:\n print(\"{} is not a prime number\".format(num))\nelse:\n print(\"{} is a prime number\".format(num))",
"_____no_output_____"
]
],
[
[
"### Python For Loop\n\nUsed to iterate over sequence/lists\n\nfor element in sequence:\n \n body of For",
"_____no_output_____"
]
],
[
[
"#find the sum of numbers in a list\nlst=[21,12,13,14,90]\n\n\n\nfor element in lst:\n print(element)\n #whatebe you want \n #with element\n if element%2==1:\n print(\"{} is odd\".format(element))\n \n",
"21\n21 is odd\n12\n13\n13 is odd\n14\n90\n"
]
],
[
[
"#### range() function\n\nWe can generate a sequence of numbers using range() fuction.\n\nrange(10) will generate numbers from 0 to 9. Therefore 10 numbers",
"_____no_output_____"
]
],
[
[
"#print range of 10\nfor i in range(4):\n print(i)",
"0\n1\n2\n3\n"
],
[
"# print range of numbers from 1 to 20, eith increment of 2\nfor i in range(0,10,2):\n print(i)",
"0\n2\n4\n6\n8\n"
],
[
"#Apply the range function to iterate through list\nfruit_list=[\"mango\",\"apple\",\"banana\",\"grapes\",\"strawberry\"]\n",
"_____no_output_____"
],
[
"print(len(fruit_list))",
"5\n"
],
[
"#what are the two ways we can print this list",
"_____no_output_____"
],
[
"for i in range(len(fruit_list)):\n print(fruit_list[i])",
"mango\napple\nbanana\ngrapes\nstrawberry\n"
]
],
[
[
"#### for loop with else",
"_____no_output_____"
]
],
[
[
"vals=[12,21,13]\nfor val in vals:\n print(val)\nelse:\n print('no items are left')\n ",
"12\n21\n13\nno items are left\n"
]
],
[
[
"#### Code to display all prime numbers between an interval",
"_____no_output_____"
]
],
[
[
"#should contain a nested for loop",
"_____no_output_____"
]
],
[
[
"#### Example of continue",
"_____no_output_____"
]
],
[
[
"#print odd numbers present in a list",
"_____no_output_____"
],
[
"#use continue",
"_____no_output_____"
],
[
"list_num=[21,13,14,15,20,19,16]\n\nfor my_num in list_num:\n# print(my_num)\n if my_num%2==1:\n print(my_num)",
"21\n13\n15\n19\n"
],
[
"#print if a number is prime",
"_____no_output_____"
],
[
"#use break",
"_____no_output_____"
],
[
"#print numbers till 5\n\nnum=23\n\nfor i in range(2,num):\n if num%i==0:\n break\n print(i)\n ",
"2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a90a83d63797d3ef6cc0177e51938ed4f6eb807
| 94,181 |
ipynb
|
Jupyter Notebook
|
Convolutional Neural Networks/week1/Convolution_model_Application_v1a.ipynb
|
y33-j3T/Coursera
|
fbd5ec28ff95db8eef2de13ed96b839db08f2069
|
[
"MIT"
] | 125 |
2021-01-02T03:37:27.000Z
|
2022-03-23T21:58:13.000Z
|
Convolutional Neural Networks/week1/Convolution_model_Application_v1a.ipynb
|
y33-j3T/Coursera
|
fbd5ec28ff95db8eef2de13ed96b839db08f2069
|
[
"MIT"
] | 2 |
2021-02-08T04:26:14.000Z
|
2021-12-31T08:41:38.000Z
|
Convolutional Neural Networks/week1/Convolution_model_Application_v1a.ipynb
|
y33-j3T/Coursera
|
fbd5ec28ff95db8eef2de13ed96b839db08f2069
|
[
"MIT"
] | 150 |
2021-01-02T00:27:46.000Z
|
2022-03-30T03:42:27.000Z
| 96.103061 | 18,850 | 0.794003 |
[
[
[
"# Convolutional Neural Networks: Application\n\nWelcome to Course 4's second assignment! In this notebook, you will:\n\n- Implement helper functions that you will use when implementing a TensorFlow model\n- Implement a fully functioning ConvNet using TensorFlow \n\n**After this assignment you will be able to:**\n\n- Build and train a ConvNet in TensorFlow for a classification problem \n\nWe assume here that you are already familiar with TensorFlow. If you are not, please refer the *TensorFlow Tutorial* of the third week of Course 2 (\"*Improving deep neural networks*\").",
"_____no_output_____"
],
[
"### <font color='darkblue'> Updates to Assignment <font>\n\n#### If you were working on a previous version\n* The current notebook filename is version \"1a\". \n* You can find your work in the file directory as version \"1\".\n* To view the file directory, go to the menu \"File->Open\", and this will open a new tab that shows the file directory.\n\n#### List of Updates\n* `initialize_parameters`: added details about tf.get_variable, `eval`. Clarified test case.\n* Added explanations for the kernel (filter) stride values, max pooling, and flatten functions.\n* Added details about softmax cross entropy with logits.\n* Added instructions for creating the Adam Optimizer.\n* Added explanation of how to evaluate tensors (optimizer and cost).\n* `forward_propagation`: clarified instructions, use \"F\" to store \"flatten\" layer.\n* Updated print statements and 'expected output' for easier visual comparisons.\n* Many thanks to Kevin P. Brown (mentor for the deep learning specialization) for his suggestions on the assignments in this course!",
"_____no_output_____"
],
[
"## 1.0 - TensorFlow model\n\nIn the previous assignment, you built helper functions using numpy to understand the mechanics behind convolutional neural networks. Most practical applications of deep learning today are built using programming frameworks, which have many built-in functions you can simply call. \n\nAs usual, we will start by loading in the packages. ",
"_____no_output_____"
]
],
[
[
"import math\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nfrom cnn_utils import *\n\n%matplotlib inline\nnp.random.seed(1)",
"_____no_output_____"
]
],
[
[
"Run the next cell to load the \"SIGNS\" dataset you are going to use.",
"_____no_output_____"
]
],
[
[
"# Loading the data (signs)\nX_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()",
"_____no_output_____"
]
],
[
[
"As a reminder, the SIGNS dataset is a collection of 6 signs representing numbers from 0 to 5.\n\n<img src=\"images/SIGNS.png\" style=\"width:800px;height:300px;\">\n\nThe next cell will show you an example of a labelled image in the dataset. Feel free to change the value of `index` below and re-run to see different examples. ",
"_____no_output_____"
]
],
[
[
"# Example of a picture\nindex = 6\nplt.imshow(X_train_orig[index])\nprint (\"y = \" + str(np.squeeze(Y_train_orig[:, index])))",
"y = 2\n"
]
],
[
[
"In Course 2, you had built a fully-connected network for this dataset. But since this is an image dataset, it is more natural to apply a ConvNet to it.\n\nTo get started, let's examine the shapes of your data. ",
"_____no_output_____"
]
],
[
[
"X_train = X_train_orig/255.\nX_test = X_test_orig/255.\nY_train = convert_to_one_hot(Y_train_orig, 6).T\nY_test = convert_to_one_hot(Y_test_orig, 6).T\nprint (\"number of training examples = \" + str(X_train.shape[0]))\nprint (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape))\nprint (\"Y_train shape: \" + str(Y_train.shape))\nprint (\"X_test shape: \" + str(X_test.shape))\nprint (\"Y_test shape: \" + str(Y_test.shape))\nconv_layers = {}",
"number of training examples = 1080\nnumber of test examples = 120\nX_train shape: (1080, 64, 64, 3)\nY_train shape: (1080, 6)\nX_test shape: (120, 64, 64, 3)\nY_test shape: (120, 6)\n"
]
],
[
[
"### 1.1 - Create placeholders\n\nTensorFlow requires that you create placeholders for the input data that will be fed into the model when running the session.\n\n**Exercise**: Implement the function below to create placeholders for the input image X and the output Y. You should not define the number of training examples for the moment. To do so, you could use \"None\" as the batch size, it will give you the flexibility to choose it later. Hence X should be of dimension **[None, n_H0, n_W0, n_C0]** and Y should be of dimension **[None, n_y]**. [Hint: search for the tf.placeholder documentation\"](https://www.tensorflow.org/api_docs/python/tf/placeholder).",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: create_placeholders\n\ndef create_placeholders(n_H0, n_W0, n_C0, n_y):\n \"\"\"\n Creates the placeholders for the tensorflow session.\n \n Arguments:\n n_H0 -- scalar, height of an input image\n n_W0 -- scalar, width of an input image\n n_C0 -- scalar, number of channels of the input\n n_y -- scalar, number of classes\n \n Returns:\n X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype \"float\"\n Y -- placeholder for the input labels, of shape [None, n_y] and dtype \"float\"\n \"\"\"\n\n ### START CODE HERE ### (≈2 lines)\n X = tf.placeholder(tf.float32, [None, n_H0, n_W0, n_C0])\n Y = tf.placeholder(tf.float32, [None, n_y])\n ### END CODE HERE ###\n \n return X, Y",
"_____no_output_____"
],
[
"X, Y = create_placeholders(64, 64, 3, 6)\nprint (\"X = \" + str(X))\nprint (\"Y = \" + str(Y))",
"X = Tensor(\"Placeholder_9:0\", shape=(?, 64, 64, 3), dtype=float32)\nY = Tensor(\"Placeholder_10:0\", shape=(?, 6), dtype=float32)\n"
]
],
[
[
"**Expected Output**\n\n<table> \n<tr>\n<td>\n X = Tensor(\"Placeholder:0\", shape=(?, 64, 64, 3), dtype=float32)\n\n</td>\n</tr>\n<tr>\n<td>\n Y = Tensor(\"Placeholder_1:0\", shape=(?, 6), dtype=float32)\n\n</td>\n</tr>\n</table>",
"_____no_output_____"
],
[
"### 1.2 - Initialize parameters\n\nYou will initialize weights/filters $W1$ and $W2$ using `tf.contrib.layers.xavier_initializer(seed = 0)`. You don't need to worry about bias variables as you will soon see that TensorFlow functions take care of the bias. Note also that you will only initialize the weights/filters for the conv2d functions. TensorFlow initializes the layers for the fully connected part automatically. We will talk more about that later in this assignment.\n\n**Exercise:** Implement initialize_parameters(). The dimensions for each group of filters are provided below. Reminder - to initialize a parameter $W$ of shape [1,2,3,4] in Tensorflow, use:\n```python\nW = tf.get_variable(\"W\", [1,2,3,4], initializer = ...)\n```\n#### tf.get_variable()\n[Search for the tf.get_variable documentation](https://www.tensorflow.org/api_docs/python/tf/get_variable). Notice that the documentation says:\n```\nGets an existing variable with these parameters or create a new one.\n```\nSo we can use this function to create a tensorflow variable with the specified name, but if the variables already exist, it will get the existing variable with that same name.\n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters\n\ndef initialize_parameters():\n \"\"\"\n Initializes weight parameters to build a neural network with tensorflow. The shapes are:\n W1 : [4, 4, 3, 8]\n W2 : [2, 2, 8, 16]\n Note that we will hard code the shape values in the function to make the grading simpler.\n Normally, functions should take values as inputs rather than hard coding.\n Returns:\n parameters -- a dictionary of tensors containing W1, W2\n \"\"\"\n \n tf.set_random_seed(1) # so that your \"random\" numbers match ours\n \n ### START CODE HERE ### (approx. 2 lines of code)\n W1 = tf.get_variable(\"W1\", [4, 4, 3, 8], initializer=tf.contrib.layers.xavier_initializer(seed=0))\n W2 = tf.get_variable(\"W2\", [2, 2, 8, 16], initializer=tf.contrib.layers.xavier_initializer(seed=0))\n ### END CODE HERE ###\n\n parameters = {\"W1\": W1,\n \"W2\": W2}\n \n return parameters",
"_____no_output_____"
],
[
"tf.reset_default_graph()\nwith tf.Session() as sess_test:\n parameters = initialize_parameters()\n init = tf.global_variables_initializer()\n sess_test.run(init)\n print(\"W1[1,1,1] = \\n\" + str(parameters[\"W1\"].eval()[1,1,1]))\n print(\"W1.shape: \" + str(parameters[\"W1\"].shape))\n print(\"\\n\")\n print(\"W2[1,1,1] = \\n\" + str(parameters[\"W2\"].eval()[1,1,1]))\n print(\"W2.shape: \" + str(parameters[\"W2\"].shape))",
"W1[1,1,1] = \n[ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394\n -0.06847463 0.05245192]\nW1.shape: (4, 4, 3, 8)\n\n\nW2[1,1,1] = \n[-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058\n -0.00577033 -0.14643836 0.24162132 -0.05857408 -0.19055021 0.1345228\n -0.22779644 -0.1601823 -0.16117483 -0.10286498]\nW2.shape: (2, 2, 8, 16)\n"
]
],
[
[
"** Expected Output:**\n\n```\nW1[1,1,1] = \n[ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394\n -0.06847463 0.05245192]\nW1.shape: (4, 4, 3, 8)\n\n\nW2[1,1,1] = \n[-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058\n -0.00577033 -0.14643836 0.24162132 -0.05857408 -0.19055021 0.1345228\n -0.22779644 -0.1601823 -0.16117483 -0.10286498]\nW2.shape: (2, 2, 8, 16)\n```",
"_____no_output_____"
],
[
"### 1.3 - Forward propagation\n\nIn TensorFlow, there are built-in functions that implement the convolution steps for you.\n\n- **tf.nn.conv2d(X,W, strides = [1,s,s,1], padding = 'SAME'):** given an input $X$ and a group of filters $W$, this function convolves $W$'s filters on X. The third parameter ([1,s,s,1]) represents the strides for each dimension of the input (m, n_H_prev, n_W_prev, n_C_prev). Normally, you'll choose a stride of 1 for the number of examples (the first value) and for the channels (the fourth value), which is why we wrote the value as `[1,s,s,1]`. You can read the full documentation on [conv2d](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d).\n\n- **tf.nn.max_pool(A, ksize = [1,f,f,1], strides = [1,s,s,1], padding = 'SAME'):** given an input A, this function uses a window of size (f, f) and strides of size (s, s) to carry out max pooling over each window. For max pooling, we usually operate on a single example at a time and a single channel at a time. So the first and fourth value in `[1,f,f,1]` are both 1. You can read the full documentation on [max_pool](https://www.tensorflow.org/api_docs/python/tf/nn/max_pool).\n\n- **tf.nn.relu(Z):** computes the elementwise ReLU of Z (which can be any shape). You can read the full documentation on [relu](https://www.tensorflow.org/api_docs/python/tf/nn/relu).\n\n- **tf.contrib.layers.flatten(P)**: given a tensor \"P\", this function takes each training (or test) example in the batch and flattens it into a 1D vector. \n * If a tensor P has the shape (m,h,w,c), where m is the number of examples (the batch size), it returns a flattened tensor with shape (batch_size, k), where $k=h \\times w \\times c$. \"k\" equals the product of all the dimension sizes other than the first dimension.\n * For example, given a tensor with dimensions [100,2,3,4], it flattens the tensor to be of shape [100, 24], where 24 = 2 * 3 * 4. You can read the full documentation on [flatten](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/flatten).\n\n- **tf.contrib.layers.fully_connected(F, num_outputs):** given the flattened input F, it returns the output computed using a fully connected layer. You can read the full documentation on [full_connected](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/fully_connected).\n\nIn the last function above (`tf.contrib.layers.fully_connected`), the fully connected layer automatically initializes weights in the graph and keeps on training them as you train the model. Hence, you did not need to initialize those weights when initializing the parameters.\n\n\n#### Window, kernel, filter\nThe words \"window\", \"kernel\", and \"filter\" are used to refer to the same thing. This is why the parameter `ksize` refers to \"kernel size\", and we use `(f,f)` to refer to the filter size. Both \"kernel\" and \"filter\" refer to the \"window.\"",
"_____no_output_____"
],
[
"**Exercise**\n\nImplement the `forward_propagation` function below to build the following model: `CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED`. You should use the functions above. \n\nIn detail, we will use the following parameters for all the steps:\n - Conv2D: stride 1, padding is \"SAME\"\n - ReLU\n - Max pool: Use an 8 by 8 filter size and an 8 by 8 stride, padding is \"SAME\"\n - Conv2D: stride 1, padding is \"SAME\"\n - ReLU\n - Max pool: Use a 4 by 4 filter size and a 4 by 4 stride, padding is \"SAME\"\n - Flatten the previous output.\n - FULLYCONNECTED (FC) layer: Apply a fully connected layer without an non-linear activation function. Do not call the softmax here. This will result in 6 neurons in the output layer, which then get passed later to a softmax. In TensorFlow, the softmax and cost function are lumped together into a single function, which you'll call in a different function when computing the cost. ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: forward_propagation\n\ndef forward_propagation(X, parameters):\n \"\"\"\n Implements the forward propagation for the model:\n CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED\n \n Note that for simplicity and grading purposes, we'll hard-code some values\n such as the stride and kernel (filter) sizes. \n Normally, functions should take these values as function parameters.\n \n Arguments:\n X -- input dataset placeholder, of shape (input size, number of examples)\n parameters -- python dictionary containing your parameters \"W1\", \"W2\"\n the shapes are given in initialize_parameters\n\n Returns:\n Z3 -- the output of the last LINEAR unit\n \"\"\"\n \n # Retrieve the parameters from the dictionary \"parameters\" \n W1 = parameters['W1']\n W2 = parameters['W2']\n \n ### START CODE HERE ###\n # CONV2D: stride of 1, padding 'SAME'\n Z1 = tf.nn.conv2d(X, W1, strides=[1, 1, 1, 1], padding='SAME')\n # RELU\n A1 = tf.nn.relu(Z1)\n # MAXPOOL: window 8x8, stride 8, padding 'SAME'\n P1 = tf.nn.max_pool(A1, ksize=[1, 8, 8, 1], strides=[1, 8, 8, 1], padding='SAME')\n # CONV2D: filters W2, stride 1, padding 'SAME'\n Z2 = tf.nn.conv2d(P1, W2, strides=[1, 1, 1, 1], padding='SAME')\n # RELU\n A2 = tf.nn.relu(Z2)\n # MAXPOOL: window 4x4, stride 4, padding 'SAME'\n P2 = tf.nn.max_pool(A2, ksize=[1, 4, 4, 1], strides=[1, 4, 4, 1], padding='SAME')\n # FLATTEN\n F = tf.contrib.layers.flatten(P2)\n # FULLY-CONNECTED without non-linear activation function (not not call softmax).\n # 6 neurons in output layer. Hint: one of the arguments should be \"activation_fn=None\" \n Z3 = tf.contrib.layers.fully_connected(F, 6, activation_fn=None)\n ### END CODE HERE ###\n\n return Z3",
"_____no_output_____"
],
[
"tf.reset_default_graph()\n\nwith tf.Session() as sess:\n np.random.seed(1)\n X, Y = create_placeholders(64, 64, 3, 6)\n parameters = initialize_parameters()\n Z3 = forward_propagation(X, parameters)\n init = tf.global_variables_initializer()\n sess.run(init)\n a = sess.run(Z3, {X: np.random.randn(2,64,64,3), Y: np.random.randn(2,6)})\n print(\"Z3 = \\n\" + str(a))",
"Z3 = \n[[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064]\n [-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]]\n"
]
],
[
[
"**Expected Output**:\n\n```\nZ3 = \n[[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064]\n [-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]]\n```",
"_____no_output_____"
],
[
"### 1.4 - Compute cost\n\nImplement the compute cost function below. Remember that the cost function helps the neural network see how much the model's predictions differ from the correct labels. By adjusting the weights of the network to reduce the cost, the neural network can improve its predictions.\n\nYou might find these two functions helpful: \n\n- **tf.nn.softmax_cross_entropy_with_logits(logits = Z, labels = Y):** computes the softmax entropy loss. This function both computes the softmax activation function as well as the resulting loss. You can check the full documentation [softmax_cross_entropy_with_logits](https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits).\n- **tf.reduce_mean:** computes the mean of elements across dimensions of a tensor. Use this to calculate the sum of the losses over all the examples to get the overall cost. You can check the full documentation [reduce_mean](https://www.tensorflow.org/api_docs/python/tf/reduce_mean).\n\n#### Details on softmax_cross_entropy_with_logits (optional reading)\n* Softmax is used to format outputs so that they can be used for classification. It assigns a value between 0 and 1 for each category, where the sum of all prediction values (across all possible categories) equals 1.\n* Cross Entropy is compares the model's predicted classifications with the actual labels and results in a numerical value representing the \"loss\" of the model's predictions.\n* \"Logits\" are the result of multiplying the weights and adding the biases. Logits are passed through an activation function (such as a relu), and the result is called the \"activation.\"\n* The function is named `softmax_cross_entropy_with_logits` takes logits as input (and not activations); then uses the model to predict using softmax, and then compares the predictions with the true labels using cross entropy. These are done with a single function to optimize the calculations.\n\n** Exercise**: Compute the cost below using the function above.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: compute_cost \n\ndef compute_cost(Z3, Y):\n \"\"\"\n Computes the cost\n \n Arguments:\n Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (number of examples, 6)\n Y -- \"true\" labels vector placeholder, same shape as Z3\n \n Returns:\n cost - Tensor of the cost function\n \"\"\"\n \n ### START CODE HERE ### (1 line of code)\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z3, labels=Y))\n ### END CODE HERE ###\n \n return cost",
"_____no_output_____"
],
[
"tf.reset_default_graph()\n\nwith tf.Session() as sess:\n np.random.seed(1)\n X, Y = create_placeholders(64, 64, 3, 6)\n parameters = initialize_parameters()\n Z3 = forward_propagation(X, parameters)\n cost = compute_cost(Z3, Y)\n init = tf.global_variables_initializer()\n sess.run(init)\n a = sess.run(cost, {X: np.random.randn(4,64,64,3), Y: np.random.randn(4,6)})\n print(\"cost = \" + str(a))",
"cost = 2.91034\n"
]
],
[
[
"**Expected Output**: \n```\ncost = 2.91034\n```",
"_____no_output_____"
],
[
"## 1.5 Model \n\nFinally you will merge the helper functions you implemented above to build a model. You will train it on the SIGNS dataset. \n\n**Exercise**: Complete the function below. \n\nThe model below should:\n\n- create placeholders\n- initialize parameters\n- forward propagate\n- compute the cost\n- create an optimizer\n\nFinally you will create a session and run a for loop for num_epochs, get the mini-batches, and then for each mini-batch you will optimize the function. [Hint for initializing the variables](https://www.tensorflow.org/api_docs/python/tf/global_variables_initializer)",
"_____no_output_____"
],
[
"#### Adam Optimizer\nYou can use `tf.train.AdamOptimizer(learning_rate = ...)` to create the optimizer. The optimizer has a `minimize(loss=...)` function that you'll call to set the cost function that the optimizer will minimize.\n\nFor details, check out the documentation for [Adam Optimizer](https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer)",
"_____no_output_____"
],
[
"#### Random mini batches\nIf you took course 2 of the deep learning specialization, you implemented `random_mini_batches()` in the \"Optimization\" programming assignment. This function returns a list of mini-batches. It is already implemented in the `cnn_utils.py` file and imported here, so you can call it like this:\n```Python\nminibatches = random_mini_batches(X, Y, mini_batch_size = 64, seed = 0)\n```\n(You will want to choose the correct variable names when you use it in your code).",
"_____no_output_____"
],
[
"#### Evaluating the optimizer and cost\n\nWithin a loop, for each mini-batch, you'll use the `tf.Session` object (named `sess`) to feed a mini-batch of inputs and labels into the neural network and evaluate the tensors for the optimizer as well as the cost. Remember that we built a graph data structure and need to feed it inputs and labels and use `sess.run()` in order to get values for the optimizer and cost.\n\nYou'll use this kind of syntax:\n```\noutput_for_var1, output_for_var2 = sess.run(\n fetches=[var1, var2],\n feed_dict={var_inputs: the_batch_of_inputs,\n var_labels: the_batch_of_labels}\n )\n```\n* Notice that `sess.run` takes its first argument `fetches` as a list of objects that you want it to evaluate (in this case, we want to evaluate the optimizer and the cost). \n* It also takes a dictionary for the `feed_dict` parameter. \n* The keys are the `tf.placeholder` variables that we created in the `create_placeholders` function above. \n* The values are the variables holding the actual numpy arrays for each mini-batch. \n* The sess.run outputs a tuple of the evaluated tensors, in the same order as the list given to `fetches`. \n\nFor more information on how to use sess.run, see the documentation [tf.Sesssion#run](https://www.tensorflow.org/api_docs/python/tf/Session#run) documentation.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: model\n\ndef model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009,\n num_epochs = 100, minibatch_size = 64, print_cost = True):\n \"\"\"\n Implements a three-layer ConvNet in Tensorflow:\n CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED\n \n Arguments:\n X_train -- training set, of shape (None, 64, 64, 3)\n Y_train -- test set, of shape (None, n_y = 6)\n X_test -- training set, of shape (None, 64, 64, 3)\n Y_test -- test set, of shape (None, n_y = 6)\n learning_rate -- learning rate of the optimization\n num_epochs -- number of epochs of the optimization loop\n minibatch_size -- size of a minibatch\n print_cost -- True to print the cost every 100 epochs\n \n Returns:\n train_accuracy -- real number, accuracy on the train set (X_train)\n test_accuracy -- real number, testing accuracy on the test set (X_test)\n parameters -- parameters learnt by the model. They can then be used to predict.\n \"\"\"\n \n ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables\n tf.set_random_seed(1) # to keep results consistent (tensorflow seed)\n seed = 3 # to keep results consistent (numpy seed)\n (m, n_H0, n_W0, n_C0) = X_train.shape \n n_y = Y_train.shape[1] \n costs = [] # To keep track of the cost\n \n # Create Placeholders of the correct shape\n ### START CODE HERE ### (1 line)\n X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y)\n ### END CODE HERE ###\n\n # Initialize parameters\n ### START CODE HERE ### (1 line)\n parameters = initialize_parameters()\n ### END CODE HERE ###\n \n # Forward propagation: Build the forward propagation in the tensorflow graph\n ### START CODE HERE ### (1 line)\n Z3 = forward_propagation(X, parameters)\n ### END CODE HERE ###\n \n # Cost function: Add cost function to tensorflow graph\n ### START CODE HERE ### (1 line)\n cost = compute_cost(Z3, Y)\n ### END CODE HERE ###\n \n # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer that minimizes the cost.\n ### START CODE HERE ### (1 line)\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n ### END CODE HERE ###\n \n # Initialize all the variables globally\n init = tf.global_variables_initializer()\n \n # Start the session to compute the tensorflow graph\n with tf.Session() as sess:\n \n # Run the initialization\n sess.run(init)\n \n # Do the training loop\n for epoch in range(num_epochs):\n\n minibatch_cost = 0.\n num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set\n seed = seed + 1\n minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)\n\n for minibatch in minibatches:\n\n # Select a minibatch\n (minibatch_X, minibatch_Y) = minibatch\n \"\"\"\n # IMPORTANT: The line that runs the graph on a minibatch.\n # Run the session to execute the optimizer and the cost.\n # The feedict should contain a minibatch for (X,Y).\n \"\"\"\n ### START CODE HERE ### (1 line)\n _ , temp_cost = sess.run([optimizer, cost], feed_dict={X:minibatch_X, Y:minibatch_Y})\n ### END CODE HERE ###\n \n minibatch_cost += temp_cost / num_minibatches\n \n\n # Print the cost every epoch\n if print_cost == True and epoch % 5 == 0:\n print (\"Cost after epoch %i: %f\" % (epoch, minibatch_cost))\n if print_cost == True and epoch % 1 == 0:\n costs.append(minibatch_cost)\n \n \n # plot the cost\n plt.plot(np.squeeze(costs))\n plt.ylabel('cost')\n plt.xlabel('iterations (per tens)')\n plt.title(\"Learning rate =\" + str(learning_rate))\n plt.show()\n\n # Calculate the correct predictions\n predict_op = tf.argmax(Z3, 1)\n correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))\n \n # Calculate accuracy on the test set\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n print(accuracy)\n train_accuracy = accuracy.eval({X: X_train, Y: Y_train})\n test_accuracy = accuracy.eval({X: X_test, Y: Y_test})\n print(\"Train Accuracy:\", train_accuracy)\n print(\"Test Accuracy:\", test_accuracy)\n \n return train_accuracy, test_accuracy, parameters",
"_____no_output_____"
]
],
[
[
"Run the following cell to train your model for 100 epochs. Check if your cost after epoch 0 and 5 matches our output. If not, stop the cell and go back to your code!",
"_____no_output_____"
]
],
[
[
"_, _, parameters = model(X_train, Y_train, X_test, Y_test)",
"Cost after epoch 0: 1.917929\nCost after epoch 5: 1.506757\nCost after epoch 10: 0.955359\nCost after epoch 15: 0.845802\nCost after epoch 20: 0.701174\nCost after epoch 25: 0.571977\nCost after epoch 30: 0.518435\nCost after epoch 35: 0.495806\nCost after epoch 40: 0.429827\nCost after epoch 45: 0.407291\nCost after epoch 50: 0.366394\nCost after epoch 55: 0.376922\nCost after epoch 60: 0.299491\nCost after epoch 65: 0.338870\nCost after epoch 70: 0.316400\nCost after epoch 75: 0.310413\nCost after epoch 80: 0.249549\nCost after epoch 85: 0.243457\nCost after epoch 90: 0.200031\nCost after epoch 95: 0.175452\n"
]
],
[
[
"**Expected output**: although it may not match perfectly, your expected output should be close to ours and your cost value should decrease.\n\n<table> \n<tr>\n <td> \n **Cost after epoch 0 =**\n </td>\n\n <td> \n 1.917929\n </td> \n</tr>\n<tr>\n <td> \n **Cost after epoch 5 =**\n </td>\n\n <td> \n 1.506757\n </td> \n</tr>\n<tr>\n <td> \n **Train Accuracy =**\n </td>\n\n <td> \n 0.940741\n </td> \n</tr> \n\n<tr>\n <td> \n **Test Accuracy =**\n </td>\n\n <td> \n 0.783333\n </td> \n</tr> \n</table>",
"_____no_output_____"
],
[
"Congratulations! You have finished the assignment and built a model that recognizes SIGN language with almost 80% accuracy on the test set. If you wish, feel free to play around with this dataset further. You can actually improve its accuracy by spending more time tuning the hyperparameters, or using regularization (as this model clearly has a high variance). \n\nOnce again, here's a thumbs up for your work! ",
"_____no_output_____"
]
],
[
[
"fname = \"images/thumbs_up.jpg\"\nimage = np.array(ndimage.imread(fname, flatten=False))\nmy_image = scipy.misc.imresize(image, size=(64,64))\nplt.imshow(my_image)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
4a90b01df62d50aa8cb43f6dad0609d8c4bd27a2
| 993,180 |
ipynb
|
Jupyter Notebook
|
starter_code/WeatherPy.ipynb
|
sjgiauque/Python-API-Challenge
|
95add917e19b2747f683dc47f4a0fe6f074093d7
|
[
"ADSL"
] | null | null | null |
starter_code/WeatherPy.ipynb
|
sjgiauque/Python-API-Challenge
|
95add917e19b2747f683dc47f4a0fe6f074093d7
|
[
"ADSL"
] | null | null | null |
starter_code/WeatherPy.ipynb
|
sjgiauque/Python-API-Challenge
|
95add917e19b2747f683dc47f4a0fe6f074093d7
|
[
"ADSL"
] | null | null | null | 498.584337 | 175,632 | 0.936058 |
[
[
[
"# WeatherPy\n----\n\n#### Note\n* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.",
"_____no_output_____"
]
],
[
[
"# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport requests\nimport time\n\n# Import API key\nfrom api_keys import api_key\n\n# Incorporated citipy to determine city based on latitude and longitude\nfrom citipy import citipy\n\n# Output File (CSV)\noutput_data_file = \"output_data/cities.csv\"\n\n# Range of latitudes and longitudes\nlat_range = (-90, 90)\nlng_range = (-180, 180)\n",
"_____no_output_____"
]
],
[
[
"## Generate Cities List",
"_____no_output_____"
]
],
[
[
"# List for holding lat_lngs and cities\nlat_lngs = []\ncities = []\n\n# Create a set of random lat and lng combinations\nlats = np.random.uniform(low=-90.000, high=90.000, size=1500)\nlngs = np.random.uniform(low=-180.000, high=180.000, size=1500)\nlat_lngs = zip(lats, lngs)\n\n# Identify nearest city for each lat, lng combination\nfor lat_lng in lat_lngs:\n city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name\n \n # If the city is unique, then add it to a our cities list\n if city not in cities:\n cities.append(city)\n\n# Print the city count to confirm sufficient count\nlen(cities)\n",
"_____no_output_____"
]
],
[
[
"### Perform API Calls\n* Perform a weather check on each city using a series of successive API calls.\n* Include a print log of each city as it'sbeing processed (with the city number and city name).\n",
"_____no_output_____"
]
],
[
[
"new_cities = []\ncloudiness = []\ncountry = []\ndate = []\nhumidity = []\ntemp = []\nlat = []\nlng = []\nwind = []\n",
"_____no_output_____"
],
[
"record_counter = 0\nset_counter = 0\n# Starting URL for Weather Map API Call\nurl = \"http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=\" + api_key \nprint('------------------------')\nprint('Beginning Data Retrieval')\nprint('------------------------')\n\nfor city in cities:\n query_url = url + \"&q=\" + city\n # Get weather data\n response = requests.get(query_url).json()\n if record_counter < 50:\n record_counter += 1\n else:\n set_counter += 1\n record_counter = 0\n\n print('Processing record {} of set {} | {}'.format(record_counter, set_counter, city))\n print(url)\n try:\n cloudiness.append(response['clouds']['all'])\n country.append(response['sys']['country'])\n date.append(response['dt'])\n humidity.append(response['main']['humidity'])\n temp.append(response['main']['temp_max'])\n lat.append(response['coord']['lat'])\n lng.append(response['coord']['lon'])\n wind.append(response['wind']['speed'])\n new_cities.append(city)\n except:\n print(\"City not found!\")\n pass\n\nprint('-------------------------')\nprint('Data Retrieval Complete')\nprint('-------------------------')\n",
"------------------------\nBeginning Data Retrieval\n------------------------\nProcessing record 1 of set 0 | crotone\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 2 of set 0 | khatanga\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 3 of set 0 | ushuaia\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 4 of set 0 | shingu\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 5 of set 0 | atuona\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 6 of set 0 | rikitea\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 7 of set 0 | qaanaaq\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 8 of set 0 | jalingo\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 9 of set 0 | barrow\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 10 of set 0 | calamar\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 11 of set 0 | kruisfontein\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 12 of set 0 | nizhneyansk\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nCity not found!\nProcessing record 13 of set 0 | avera\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 14 of set 0 | general pico\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 15 of set 0 | makarov\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 16 of set 0 | esperance\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 17 of set 0 | kamenka\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 18 of set 0 | new norfolk\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 19 of set 0 | lima\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 20 of set 0 | chagda\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nCity not found!\nProcessing record 21 of set 0 | nago\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 22 of set 0 | georgetown\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 23 of set 0 | punta arenas\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 24 of set 0 | charters towers\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 25 of set 0 | vaini\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 26 of set 0 | narsaq\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 27 of set 0 | coihaique\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 28 of set 0 | arraial do cabo\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 29 of set 0 | gobabis\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 30 of set 0 | yokadouma\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 31 of set 0 | east london\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 32 of set 0 | umm lajj\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 33 of set 0 | attawapiskat\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nCity not found!\nProcessing record 34 of set 0 | kaitangata\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 35 of set 0 | dikson\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 36 of set 0 | almenara\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 37 of set 0 | albany\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 38 of set 0 | butaritari\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 39 of set 0 | bluff\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 40 of set 0 | comodoro rivadavia\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 41 of set 0 | faanui\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 42 of set 0 | mercedes\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 43 of set 0 | luanda\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 44 of set 0 | kulhudhuffushi\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 45 of set 0 | fairbanks\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 46 of set 0 | bambous virieux\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 47 of set 0 | thompson\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 48 of set 0 | port alfred\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 49 of set 0 | luderitz\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 50 of set 0 | jamestown\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 0 of set 1 | pevek\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 1 of set 1 | ritchie\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 2 of set 1 | gra liyia\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 3 of set 1 | vestmannaeyjar\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 4 of set 1 | chuy\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 5 of set 1 | cottbus\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 6 of set 1 | bredasdorp\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 7 of set 1 | san andres\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\nProcessing record 8 of set 1 | weinan\nhttp://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=3f04b67b6151bd1463ec9b6e463f1542\n"
]
],
[
[
"### Convert Raw Data to DataFrame\n* Export the city data into a .csv.\n* Display the DataFrame",
"_____no_output_____"
]
],
[
[
"# create a data frame from cities, temp, humidity, cloudiness and wind speed\nweather_dict = {\n \"City\": new_cities,\n \"Cloudiness\" : cloudiness,\n \"Country\" : country,\n \"Date\" : date,\n \"Humidity\" : humidity,\n \"Temp\": temp,\n \"Lat\" : lat,\n \"Lng\" : lng, \n \"Wind Speed\" : wind\n}\nweather_data = pd.DataFrame(weather_dict)\nweather_data.count()\n",
"_____no_output_____"
],
[
"weather_data.head()",
"_____no_output_____"
]
],
[
[
"### Plotting the Data\n* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.\n* Save the plotted figures as .pngs.",
"_____no_output_____"
],
[
"#### Latitude vs. Temperature Plot",
"_____no_output_____"
]
],
[
[
"# Latitude vs. Temperature Plot\nweather_data.plot(kind='scatter', x='Lat', y='Temp', c='DarkBlue')\nplt.title('City Latitude Vs Max Temperature ({})'.format(date) )\nplt.xlabel('Latitude')\nplt.ylabel('Max temperature (F)')\nplt.grid()\nplt.savefig(\"../Images/LatitudeVsTemperature.png\")\n",
"_____no_output_____"
]
],
[
[
"#### Latitude vs. Humidity Plot",
"_____no_output_____"
]
],
[
[
"# Latitude vs. Humidity Plot\nweather_data.plot(kind='scatter',x='Lat',y='Humidity', c='DarkBlue')\nplt.title('City Latitude Vs Max Humidity ({})'.format(date) )\nplt.xlabel('Latitude')\nplt.ylabel('Humidity (%)')\nplt.grid()\nplt.savefig(\"../Images/LatitudeVsHumidity.png\")\n",
"_____no_output_____"
]
],
[
[
"#### Latitude vs. Cloudiness Plot",
"_____no_output_____"
]
],
[
[
"# Latitude Vs Cloudiness Plot\n\nweather_data.plot(kind='scatter',x='Lat',y='Cloudiness', c='DarkBlue')\nplt.title('City Latitude Vs Cloudiness ({})'.format(date) )\nplt.xlabel('Latitude')\nplt.ylabel('Cloudiness (%)')\nplt.grid()\nplt.savefig(\"../Images/LatitudeVsCloudiness.png\")\n",
"_____no_output_____"
]
],
[
[
"#### Latitude vs. Wind Speed Plot",
"_____no_output_____"
]
],
[
[
"# Latitude Vs Wind Speed Plot\n\nweather_data.plot(kind='scatter',x='Lat',y='Wind Speed', c='DarkBlue')\nplt.title('City Latitude Vs Wind Speed ({})'.format(date) )\nplt.xlabel('Latitude')\nplt.ylabel('Wind Speed (mph)')\nplt.grid()\nplt.savefig(\"../Images/LatitudeVsWindSpeed.png\")\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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a90b7e800ad7ce1dc006d3393e8435e0c1dc242
| 18,412 |
ipynb
|
Jupyter Notebook
|
Python Absolute Beginner/Module_4_3_Absolute_Beginner.ipynb
|
svescuso/pythonteachingcode
|
718a5d5f04aa02ad38d0dfecd1658dbd4d7f7a54
|
[
"MIT"
] | null | null | null |
Python Absolute Beginner/Module_4_3_Absolute_Beginner.ipynb
|
svescuso/pythonteachingcode
|
718a5d5f04aa02ad38d0dfecd1658dbd4d7f7a54
|
[
"MIT"
] | null | null | null |
Python Absolute Beginner/Module_4_3_Absolute_Beginner.ipynb
|
svescuso/pythonteachingcode
|
718a5d5f04aa02ad38d0dfecd1658dbd4d7f7a54
|
[
"MIT"
] | null | null | null | 33.115108 | 652 | 0.539865 |
[
[
[
"# 1-7.1 Intro Python\n## `while()` loops & increments\n- **while `True` or forever loops**\n- **incrementing in loops**\n- Boolean operators in while loops\n\n\n----- \n\n><font size=\"5\" color=\"#00A0B2\" face=\"verdana\"> <B>Student will be able to</B></font>\n- **create forever loops using `while` and `break`**\n- **use incrementing variables in a while loop**\n- control while loops using Boolean operators",
"_____no_output_____"
],
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Concepts</B></font>\n## `while True:`\n### Using the 'while True:' loop\n[]( http://edxinteractivepage.blob.core.windows.net/edxpages/f7cff1a7-5601-48a1-95a6-fd1fdfabd20e.html?details=[{\"src\":\"http://jupyternootbookwams.streaming.mediaservices.windows.net/f43862cd-7cdc-45a3-adb1-a07dcbd9ae16/Unit1_Section7.1-while-forever.ism/manifest\",\"type\":\"application/vnd.ms-sstr+xml\"}],[{\"src\":\"http://jupyternootbookwams.streaming.mediaservices.windows.net/f43862cd-7cdc-45a3-adb1-a07dcbd9ae16/Unit1_Section7.1-while-forever.vtt\",\"srclang\":\"en\",\"kind\":\"subtitles\",\"label\":\"english\"}])\n\n**`while True:`** is known as the **forever loop** because it ...loops forever \n\nUsing the **`while True:`** statement results in a loop that continues to run forever \n...or, until the loop is interrupted, such as with a **`break`** statement \n\n## `break`\n### in a `while` loop, causes code flow to exit the loop \na **conditional** can implement **`break`** to exit a **`while True`** loop ",
"_____no_output_____"
],
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Examples</B></font>\n## `while True` loops forever unless a `break` statement is used ",
"_____no_output_____"
]
],
[
[
"# Review and run code\n# this example never loops because the break has no conditions\nwhile True:\n print('write forever, unless there is a \"break\"')\n break",
"write forever, unless there is a \"break\"\n"
],
[
"# [ ] review the NUMBER GUESS code then run - Q. what cause the break statement to run?\nnumber_guess = \"0\"\nsecret_number = \"5\"\n\nwhile True:\n number_guess = input(\"guess the number 1 to 5: \")\n if number_guess == secret_number:\n print(\"Yes\", number_guess,\"is correct!\\n\")\n break\n else:\n print(number_guess,\"is incorrect\\n\")",
"guess the number 1 to 5: 2\n2 is incorrect\n\nguess the number 1 to 5: 3\n3 is incorrect\n\nguess the number 1 to 5: 3\n3 is incorrect\n\nguess the number 1 to 5: 3\n3 is incorrect\n\nguess the number 1 to 5: 3\n3 is incorrect\n\nguess the number 1 to 5: 3\n3 is incorrect\n\nguess the number 1 to 5: 3\n3 is incorrect\n\nguess the number 1 to 5: 5\nYes 5 is correct!\n\n"
],
[
"# [ ] review WHAT TO WEAR code then run testing different inputs\nwhile True:\n weather = input(\"Enter weather (sunny, rainy, snowy, or quit): \") \n print()\n\n if weather.lower() == \"sunny\":\n print(\"Wear a t-shirt and sunscreen\")\n break\n elif weather.lower() == \"rainy\":\n print(\"Bring an umbrella and boots\")\n break\n elif weather.lower() == \"snowy\":\n print(\"Wear a warm coat and hat\")\n break\n elif weather.lower().startswith(\"q\"):\n print('\"quit\" detected, exiting')\n break\n else:\n print(\"Sorry, not sure what to suggest for\", weather +\"\\n\")",
"Enter weather (sunny, rainy, snowy, or quit): humid\n\nSorry, not sure what to suggest for humid\n\nEnter weather (sunny, rainy, snowy, or quit): rainy\n\nBring an umbrella and boots\n"
]
],
[
[
"# \n<font size=\"6\" color=\"#B24C00\" face=\"verdana\"> <B>Task 1</B></font>\n## `while True` \n### [ ] Program: Get a name forever ...or until done\n- create variable, familar_name, and assign it an empty string (**`\"\"`**)\n- use **`while True:`**\n- ask for user input for familar_name (common name friends/family use) \n- keep asking until given a non-blank/non-space alphabetical name is received (Hint: Boolean string test)\n- break loop and print a greeting using familar_name",
"_____no_output_____"
]
],
[
[
"# [ ] create Get Name program\nfamilar_name=\"\"\nwhile True:\n familar_name=input(\"Enter a familar, common, friend's, or family's name: \")\n if familar_name.isalpha():\n break\n else:\n print(\"That is not a name without spaces\")\nprint(familar_name,\"sounds like cool name to have\")\n",
"Enter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: \nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: George of the jungle\nThat is not a name without spaces\nEnter a familar, common, friend's, or family's name: Gerorome\nGerorome sounds like cool name to have\n"
]
],
[
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Concept</B></font>\n## Incrementing a variable\n[]( http://edxinteractivepage.blob.core.windows.net/edxpages/f7cff1a7-5601-48a1-95a6-fd1fdfabd20e.html?details=[{%22src%22:%22http://jupyternootbookwams.streaming.mediaservices.windows.net/cc7925d2-0652-4659-93fb-f4cc8d09ac51/Unit1_Section7.1-increment.ism/manifest%22,%22type%22:%22application/vnd.ms-sstr+xml%22}],[{%22src%22:%22http://jupyternootbookwams.streaming.mediaservices.windows.net/cc7925d2-0652-4659-93fb-f4cc8d09ac51/Unit1_Section7.1-increment.vtt%22,%22srclang%22:%22en%22,%22kind%22:%22subtitles%22,%22label%22:%22english%22}])\n## Incrementing\n### `votes = votes + 1` or `votes += 1`\n\n## Decrementing \n### `votes = votes - 1` or `votes -= 1`",
"_____no_output_____"
],
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Examples</B></font>\n \n",
"_____no_output_____"
]
],
[
[
"# [ ] review and run example\nvotes = 3\nprint(votes)\n\nvotes = votes + 1\nprint(votes)\n\nvotes += 2\nprint(votes)",
"3\n4\n6\n"
],
[
"print(votes)\n\nvotes -= 1\nprint(votes)",
"6\n5\n"
],
[
"# [ ] review the SEAT COUNT code then run \n\nseat_count = 0\nwhile True:\n print(\"seat count:\",seat_count)\n seat_count = seat_count + 1\n\n if seat_count > 4:\n break",
"seat count: 0\nseat count: 1\nseat count: 2\nseat count: 3\nseat count: 4\n"
],
[
"# [ ] review the SEAT TYPE COUNT code then run entering: hard, soft, medium and exit\n\n# initialize variables\nseat_count = 0\nsoft_seats = 0\nhard_seats = 0\nnum_seats = 4\n\n# loops tallying seats using soft pads vs hard, until seats full or user \"exits\"\nwhile True:\n seat_type = input('enter seat type of \"hard\",\"soft\" or \"exit\" (to finish): ')\n \n if seat_type.lower().startswith(\"e\"):\n print()\n break\n elif seat_type.lower() == \"hard\":\n hard_seats += 1\n elif seat_type.lower() == \"soft\":\n soft_seats += 1\n else:\n print(\"invalid entry: counted as hard\")\n hard_seats += 1 \n seat_count += 1\n if seat_count >= num_seats:\n print(\"\\nseats are full\")\n break\n \nprint(seat_count,\"Seats Total: \",hard_seats,\"hard and\",soft_seats,\"soft\" )",
"enter seat type of \"hard\",\"soft\" or \"exit\" (to finish): soft\nenter seat type of \"hard\",\"soft\" or \"exit\" (to finish): hard\nenter seat type of \"hard\",\"soft\" or \"exit\" (to finish): soft\nenter seat type of \"hard\",\"soft\" or \"exit\" (to finish): george\ninvalid entry: counted as hard\n\nseats are full\n4 Seats Total: 2 hard and 2 soft\n"
]
],
[
[
"# \n<font size=\"6\" color=\"#B24C00\" face=\"verdana\"> <B>Task 2</B></font>\n## incrementing in a `while()` loop\n### Program: Shirt Count\n- enter a sizes (S, M, L)\n- tally the count of each size\n- input \"exit\" when finished\n- report out the purchase of each shirt size \n",
"_____no_output_____"
]
],
[
[
"# [ ] Create the Shirt Count program, run tests\nsmall_shirts=0\nmedium_shirts=0\nlarge_shirts=0\nwhile True:\n order=input(\"Enter the shirt size you wish to order(S,M,L,done): \").upper()\n if order==\"S\":\n small_shirts+=1\n elif order==\"M\":\n medium_shirts+=1\n elif order==\"L\":\n large_shirts+=1\n elif order==\"DONE\":\n print(\"Thank you for your order :)\")\n break\n else:\n print(\"Enter a valid shirt size\")\nprint(\"You ordered:\\n\",small_shirts,\"Small Shirts\\n\",medium_shirts,\"Medium Shirts\\n\",large_shirts,\"Large shirts\")\n",
"Enter the shirt size you wish to order(S,M,L,done): f\nEnter a valid shirt size\nEnter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): D\nEnter a valid shirt size\nEnter the shirt size you wish to order(S,M,L,done): L\nEnter the shirt size you wish to order(S,M,L,done): E\nEnter a valid shirt size\nEnter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): M\nEnter the shirt size you wish to order(S,M,L,done): M\nEnter the shirt size you wish to order(S,M,L,done): L\nEnter the shirt size you wish to order(S,M,L,done): done\nThank you for your order :)\nYou ordered:\n 3 Small Shirts\n 2 Medium Shirts\n 2 Large shirts\n"
]
],
[
[
"### CHALLENGE: Shirt Register (optional) \nUpdate the **Shirt Count** program to calculate cost\n- use shirt cost (S = 6, M = 7, L = 8)\n- to calculate and report the subtotal cost for each size \n- to calculate and report the total cost of all shirts",
"_____no_output_____"
]
],
[
[
"# [ ] Create the Shirt Register program, run tests\nsmall_shirts=0\nmedium_shirts=0\nlarge_shirts=0\nsmall_cost=6\nmedium_cost=7\nlarge_cost=8\nwhile True:\n order=input(\"Enter the shirt size you wish to order(S,M,L,done): \").upper()\n if order==\"S\":\n small_shirts+=1\n elif order==\"M\":\n medium_shirts+=1\n elif order==\"L\":\n large_shirts+=1\n elif order==\"DONE\":\n print(\"Thank you for your order :)\")\n total_small=small_shirts*small_cost\n total_medium= medium_shirts*medium_cost\n total_large=large_shirts*large_cost\n total_cost=total_small+total_medium+total_large\n break\n else:\n print(\"Enter a valid shirt size\")\n\nprint(\"You ordered:\\n\",small_shirts,\"Small Shirts which costs\",total_small,\"\\n\",medium_shirts,\"Medium Shirts which cost\",total_medium,\"\\n\",large_shirts,\"Large shirts which cost\",total_large,\"\\n\")\nprint(\"Your total order price is\",total_cost)\n",
"Enter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): M\nEnter the shirt size you wish to order(S,M,L,done): D\nEnter a valid shirt size\nEnter the shirt size you wish to order(S,M,L,done): L\nEnter the shirt size you wish to order(S,M,L,done): L\nEnter the shirt size you wish to order(S,M,L,done): M\nEnter the shirt size you wish to order(S,M,L,done): M\nEnter the shirt size you wish to order(S,M,L,done): L\nEnter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): M\nEnter the shirt size you wish to order(S,M,L,done): M\nEnter the shirt size you wish to order(S,M,L,done): S\nEnter the shirt size you wish to order(S,M,L,done): L\nEnter the shirt size you wish to order(S,M,L,done): LK\nEnter a valid shirt size\nEnter the shirt size you wish to order(S,M,L,done): done\nThank you for your order :)\nYou ordered:\n 5 Small Shirts which costs 30 \n 5 Medium Shirts which cost 35 \n 4 Large shirts which cost 32 \n\nYour total order price is 97\n"
]
],
[
[
"[Terms of use](http://go.microsoft.com/fwlink/?LinkID=206977) [Privacy & cookies](https://go.microsoft.com/fwlink/?LinkId=521839) © 2017 Microsoft",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a90bfe434861eb3c8ad8acdf40d14e638c2bcb4
| 2,410 |
ipynb
|
Jupyter Notebook
|
matplotlib/gallery_jupyter/statistics/histogram_multihist.ipynb
|
kingreatwill/penter
|
2d027fd2ae639ac45149659a410042fe76b9dab0
|
[
"MIT"
] | 13 |
2020-01-04T07:37:38.000Z
|
2021-08-31T05:19:58.000Z
|
matplotlib/gallery_jupyter/statistics/histogram_multihist.ipynb
|
kingreatwill/penter
|
2d027fd2ae639ac45149659a410042fe76b9dab0
|
[
"MIT"
] | 3 |
2020-06-05T22:42:53.000Z
|
2020-08-24T07:18:54.000Z
|
matplotlib/gallery_jupyter/statistics/histogram_multihist.ipynb
|
kingreatwill/penter
|
2d027fd2ae639ac45149659a410042fe76b9dab0
|
[
"MIT"
] | 9 |
2020-10-19T04:53:06.000Z
|
2021-08-31T05:20:01.000Z
| 44.62963 | 829 | 0.582158 |
[
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\n=====================================================\nThe histogram (hist) function with multiple data sets\n=====================================================\n\nPlot histogram with multiple sample sets and demonstrate:\n\n * Use of legend with multiple sample sets\n * Stacked bars\n * Step curve with no fill\n * Data sets of different sample sizes\n\nSelecting different bin counts and sizes can significantly affect the\nshape of a histogram. The Astropy docs have a great section on how to\nselect these parameters:\nhttp://docs.astropy.org/en/stable/visualization/histogram.html\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(19680801)\n\nn_bins = 10\nx = np.random.randn(1000, 3)\n\nfig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(nrows=2, ncols=2)\n\ncolors = ['red', 'tan', 'lime']\nax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)\nax0.legend(prop={'size': 10})\nax0.set_title('bars with legend')\n\nax1.hist(x, n_bins, density=True, histtype='bar', stacked=True)\nax1.set_title('stacked bar')\n\nax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)\nax2.set_title('stack step (unfilled)')\n\n# Make a multiple-histogram of data-sets with different length.\nx_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]\nax3.hist(x_multi, n_bins, histtype='bar')\nax3.set_title('different sample sizes')\n\nfig.tight_layout()\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a90e432d2457a27ddfd646e2ec124ccfac795bc
| 32,449 |
ipynb
|
Jupyter Notebook
|
lessons/05-Functions/LAB-Functions.ipynb
|
IST256/spring2022
|
4fcfa7173c8c80677c186353b6547c23775f0b74
|
[
"Apache-2.0"
] | null | null | null |
lessons/05-Functions/LAB-Functions.ipynb
|
IST256/spring2022
|
4fcfa7173c8c80677c186353b6547c23775f0b74
|
[
"Apache-2.0"
] | null | null | null |
lessons/05-Functions/LAB-Functions.ipynb
|
IST256/spring2022
|
4fcfa7173c8c80677c186353b6547c23775f0b74
|
[
"Apache-2.0"
] | null | null | null | 29.962142 | 465 | 0.553484 |
[
[
[
"# Class Coding Lab: Functions\n\nThe goals of this lab are to help you to understand:\n\n- How to use Python's built-in functions in the standard library.\n- How to write user-defined functions\n- How to use other people's code.\n- The benefits of user-defined functions to code reuse and simplicity.\n- How to create a program to use functions to solve a complex idea\n\nWe will demonstrate these through the following example:\n\n\n## The Credit Card Problem\n\nIf you're going to do commerce on the web, you're going to support credit cards. But how do you know if a given number is valid? And how do you know which network issued the card?\n\n**Example:** Is `5300023581452982` a valid credit card number?Is it? Visa? MasterCard, Discover? or American Express?\n\nWhile eventually the card number is validated when you attempt to post a transaction, there's a lot of reasons why you might want to know its valid before the transaction takes place. The most common being just trying to catch an honest key-entry mistake made by your site visitor.\n\nSo there are two things we'd like to figure out, for any \"potential\" card number:\n\n- Who is the issuing network? Visa, MasterCard, Discover or American Express.\n- IS the number potentially valid (as opposed to a made up series of digits)?\n\n### What does this have to do with functions?\n\nIf we get this code to work, it seems like it might be useful to re-use it in several other programs we may write in the future. We can do this by writing the code as a **function**. Think of a function as an independent program its own inputs and output. The program is defined under a name so that we can use it simply by calling its name. \n\n**Example:** `n = int(\"50\")` the function `int()` takes the string `\"50\"` as input and converts it to an `int` value `50` which is then stored in the value `n`.\n\nWhen you create these credit card functions, we might want to re-use them by placing them in a **Module** which is a file with a collection of functions in it. Furthermore we can take a group of related modules and place them together in a Python **Package**. You install packages on your computer with the `pip` command. \n",
"_____no_output_____"
],
[
"## Built-In Functions\n\nLet's start by checking out the built-in functions in Python's math library. We use the `dir()` function to list the names of the math library:\n",
"_____no_output_____"
]
],
[
[
"import math\ndir(math)",
"_____no_output_____"
]
],
[
[
"If you look through the output, you'll see a `factorial` name. Let's see if it's a function we can use:",
"_____no_output_____"
]
],
[
[
"help(math.factorial)",
"Help on built-in function factorial in module math:\n\nfactorial(x, /)\n Find x!.\n \n Raise a ValueError if x is negative or non-integral.\n\n"
]
],
[
[
"It says it's a built-in function, and requies an integer value (which it referrs to as x, but that value is arbitrary) as an argument. Let's call the function and see if it works:",
"_____no_output_____"
]
],
[
[
"math.factorial(5) #this is an example of \"calling\" the function with input 5. The output should be 120",
"_____no_output_____"
],
[
"math.factorial(0) # here we call the same function with input 0. The output should be 1.",
"_____no_output_____"
]
],
[
[
"### 1.1 You Code \n\nCall the factorial function with an input argument of 4. What is the output?",
"_____no_output_____"
]
],
[
[
"#TODO write code here.\n",
"_____no_output_____"
],
[
"def mike():\n print(\"mike\")",
"_____no_output_____"
],
[
"mike()",
"mike\n"
]
],
[
[
"## Using functions to print things awesome in Juypter\n\nUntil this point we've used the boring `print()` function for our output. Let's do better. In the `IPython.display` module there are two functions `display()` and `HTML()`. The `display()` function outputs a Python object to the Jupyter notebook. The `HTML()` function creates a Python object from [HTML Markup](https://www.w3schools.com/html/html_intro.asp) as a string.\n\nFor example this prints Hello in Heading 1.\n",
"_____no_output_____"
]
],
[
[
"from IPython.display import display, HTML\nfrom ipywidgets import interact_manual\n\nprint(\"Exciting:\")\ndisplay(HTML(\"<h1>He<font color='red'>ll</font>o</h1>\"))\nprint(\"Boring:\")\nprint(\"Hello\")\n",
"Exciting:\n"
]
],
[
[
"Let's keep the example going by writing two of our own functions to print a title and print text as normal, respectively. \n\nExecute this code:",
"_____no_output_____"
]
],
[
[
"def print_title(text):\n '''\n This prints text to IPython.display as H1\n '''\n return display(HTML(\"<H1>\" + text + \"</H1>\"))\n\ndef print_normal(text):\n '''\n this prints text to IPython.display as normal text\n '''\n return display(HTML(text))\n\nprint_normal(\"Mike is cool!\")",
"_____no_output_____"
]
],
[
[
"Now let's use these two functions in a familiar program, along with `interact_manual()` to make the inputs as awesome as the outputs!",
"_____no_output_____"
]
],
[
[
"print_title(\"Area of a Rectangle\")\n@interact_manual(length=(0,25),width=(0,25))\ndef area(length, width):\n area = length * width\n print_normal(f\"The area is {area}.\")\n",
"_____no_output_____"
],
[
"from ipywidgets import interact_manual\n@interact_manual(name=\"\",age=(1,100,10),gpa=(0.0,4.0,0.05))\ndef doit(name, age, gpa):\n print(f\"{name} is {age} years old and has a {gpa} GPA.\")\n \n",
"_____no_output_____"
]
],
[
[
"## Get Down with OPC (Other People's Code)\n\nNow that we know a bit about **Packages**, **Modules**, and **Functions** let me expand your horizons a bit. There's a whole world of Python code out there that you can use, and it's what makes Python the powerful and popular programming language that it is today. All you need to do to use it is *read*!\n\nFor example. Let's say I want to print some emojis in Python. I might search the Python Package Index [https://pypi.org/](https://pypi.org/) for some modules to try. \n\nFor example this one: https://pypi.org/project/emoji/ \n\nLet's take it for a spin!\n",
"_____no_output_____"
],
[
"### Installing with pip\n\nFirst we need to install the package with the `pip` utility. This runs from the command line, so to execute pip within our notebook we use the bang `!` operator.\n\nThis downloads the package and installs it into your Python environment, so that you can `import` it. ",
"_____no_output_____"
]
],
[
[
"!pip install emoji",
"_____no_output_____"
]
],
[
[
"Once the package is installed we can use it. Learning how to use it is just a matter of reading the documentation and trying things out. There are no short-cuts here! For example:",
"_____no_output_____"
]
],
[
[
"# TODO: Run this\nimport emoji\nprint(emoji.emojize('Python is :thumbs_up:'))\nprint(emoji.emojize('But I thought this :lab_coat: was supposed to be about :credit_card: ??'))",
"_____no_output_____"
]
],
[
[
"### 1.2 You Code\n\nWrite a python program to print the bacon, ice cream, and thumbs-down emojis on a single line.",
"_____no_output_____"
]
],
[
[
"## TODO: Write your code here",
"_____no_output_____"
]
],
[
[
"## Let's get back to credit cards....\n\nNow that we know a bit about **Packages**, **Modules**, and **Functions** let's attempt to write our first function. Let's tackle the easier of our two credit card related problems:\n\n- Who is the issuing network? Visa, MasterCard, Discover or American Express.\n\nThis problem can be solved by looking at the first digit of the card number:\n\n - \"4\" ==> \"Visa\"\n - \"5\" ==> \"MasterCard\"\n - \"6\" ==> \"Discover\"\n - \"3\" ==> \"American Express\"\n \nSo for card number `5300023581452982` the issuer is \"MasterCard\".\n\nIt should be easy to write a program to solve this problem. Here's the algorithm:\n\n```\ninput credit card number into variable card\nget the first digit of the card number (eg. digit = card[0])\nif digit equals \"4\"\n the card issuer \"Visa\"\nelif digit equals \"5\"\n the card issuer \"MasterCard\"\nelif digit equals \"6\"\n the card issuer is \"Discover\"\nelif digit equals \"3\"\n the card issues is \"American Express\"\nelse\n the issuer is \"Invalid\" \nprint issuer\n```\n\n### 1.3 You Code\n\nDebug this code so that it prints the correct issuer based on the first card ",
"_____no_output_____"
]
],
[
[
"## TODO: Debug this code\ncard = input(\"Enter a credit card: \")\ndigit = card[0]\nif digit == '5':\n issuer = \"Visa\"\nelif digit == '5':\n issuer == \"Mastercard\"\nelif digit = '6':\n issuer == \"Discover\"\nelif digit == '3'\n issuer = \"American Express\"\nelse:\n issuer = \"Invalid\"\nprint(issuer)",
"_____no_output_____"
]
],
[
[
"**IMPORTANT** Make sure to test your code by running it 5 times. You should test issuer and also the \"Invalid Card\" case.\n\n## Introducing the Write - Refactor - Test - Rewrite approach\n\nIt would be nice to re-write this code to use a function. This can seem daunting / confusing for beginner programmers, which is why we teach the **Write - Refactor - Test - Rewrite** approach. In this approach you write the ENTIRE PROGRAM and then REWRITE IT to use functions. Yes, it's inefficient, but until you get comfotable thinking \"functions first\" its the best way to modularize your code with functions. Here's the approach:\n\n1. Write the code\n2. Refactor (change the code around) to use a function\n3. Test the function by calling it\n4. Rewrite the original code to use the new function.\n\n\nWe already did step 1: Write so let's move on to:\n\n### 1.4 You Code: refactor\n\nLet's strip the logic out of the above code to accomplish the task of the function:\n\n- Send into the function as input a credit card number as a `str`\n- Return back from the function as output the issuer of the card as a `str`\n\nTo help you out we've written the function stub for you all you need to do is write the function body code.",
"_____no_output_____"
]
],
[
[
"def CardIssuer(card):\n ## TODO write code here they should be the same as lines 3-13 from the code above\n #card = input(\"Enter a credit card: \")\n digit = card[0]\n if digit == '4':\n issuer = \"Visa\"\n elif digit == '5':\n issuer = \"Mastercard\"\n elif digit == '6':\n issuer = \"Discover\"\n elif digit == '3':\n issuer = \"American Express\"\n else:\n issuer = \"Invalid\"\n #print(issuer)\n # the last line in the function should return the output\n return issuer",
"_____no_output_____"
],
[
"x = CardIssuer(\"4873495768923465\")\nprint(x)",
"Visa\n"
]
],
[
[
"### Step 3: Test\n\nYou wrote the function, but how do you know it works? The short answer is unless you write code to *test your function* you're simply guessing!\n\nTesting our function is as simple as calling the function with input values where WE KNOW WHAT TO EXPECT from the output. We then compare that to the ACTUAL value from the called function. If they are the same, then we know the function is working as expected!\n\nHere are some examples:\n\n```\nWHEN card='40123456789' We EXPECT CardIssuer(card) to return Visa\nWHEN card='50123456789' We EXPECT CardIssuer(card) to return MasterCard\nWHEN card='60123456789' We EXPECT CardIssuer(card) to return Discover\nWHEN card='30123456789' We EXPECT CardIssuer(card) to return American Express\nWHEN card='90123456789' We EXPECT CardIssuer(card) to return Invalid Card\n```\n\n### 1.5 You Code: Tests \n\nWrite the tests based on the examples:",
"_____no_output_____"
]
],
[
[
"# Testing the CardIssuer() function\nprint(\"WHEN card='40123456789' We EXPECT CardIssuer(card) = Visa ACTUAL\", CardIssuer(\"40123456789\"))\nprint(\"WHEN card='50123456789' We EXPECT CardIssuer(card) = MasterCard ACTUAL\", CardIssuer(\"50123456789\"))\n\n## TODO: You write the remaining 3 tests, you can copy the lines and edit the values accordingly\n",
"WHEN card='40123456789' We EXPECT CardIssuer(card) = Visa ACTUAL Visa\nWHEN card='50123456789' We EXPECT CardIssuer(card) = MasterCard ACTUAL Mastercard\n"
]
],
[
[
"### Step 4: Rewrite\n\nThe final step is to re-write the original program, but use the function instead. The algorithm becomes\n\n```\ninput credit card number into variable card\ncall the CardIssuer function with card as input, issuer as output\nprint issuer\n```\n\n### 1.6 You Code\n\nRe-write the program. It should be 3 lines of code:\n\n- input card\n- call issuer function\n- print issuer\n",
"_____no_output_____"
]
],
[
[
"# TODO Re-write the program here, calling our function.\n",
"_____no_output_____"
]
],
[
[
"## Functions are abstractions. Abstractions are good.\n\n\nStep on the accellerator and the car goes. How does it work? Who cares, it's an abstraction! Functions are the same way. Don't believe me. Consider the Luhn Check Algorithm: https://en.wikipedia.org/wiki/Luhn_algorithm \n\nThis nifty little algorithm is used to verify that a sequence of digits is possibly a credit card number (as opposed to just a sequence of numbers). It uses a verfication approach called a **checksum** to as it uses a formula to figure out the validity. \n\nHere's the function which given a card will let you know if it passes the Luhn check:\n",
"_____no_output_____"
]
],
[
[
"# Todo: execute this code\n\ndef checkLuhn(card):\n ''' This Luhn algorithm was adopted from the pseudocode here: https://en.wikipedia.org/wiki/Luhn_algorithm'''\n total = 0\n length = len(card)\n parity = length % 2\n for i in range(length):\n digit = int(card[i])\n if i%2 == parity:\n digit = digit * 2\n if digit > 9:\n digit = digit -9\n total = total + digit\n return total % 10 == 0\n",
"_____no_output_____"
],
[
"checkLuhn('4916945264045429')",
"_____no_output_____"
]
],
[
[
"### Is that a credit card number or the ramblings of a madman?\n\nIn order to test the `checkLuhn()` function you need some credit card numbers. (Don't look at me... you ain't gettin' mine!!!!) Not to worry, the internet has you covered. The website: http://www.getcreditcardnumbers.com/ is not some mysterious site on the dark web. It's a site for generating \"test\" credit card numbers. You can't buy anything with these numbers, but they will pass the Luhn test.\n\nGrab a couple of numbers and test the Luhn function as we did with the `CardIssuer()` function. Write at least to tests like these ones:\n\n```\nWHEN card='5443713204330437' We EXPECT checkLuhn(card) to return True\nWHEN card='5111111111111111' We EXPECT checkLuhn(card) to return False \n```\n",
"_____no_output_____"
]
],
[
[
"#TODO Write your two tests here\nprint(\"when card = 5443713204330437, Expec checkLuhn(card) = True, Actual=\", checkLuhn('5443713204330437'))\nprint(\"when card = 5111111111111111, Expec checkLuhn(card) = False, Actual=\", checkLuhn('5111111111111111'))\n",
"_____no_output_____"
]
],
[
[
"## Putting it all together\n\nFinally let's use all the functions we wrote/used in this lab to make a really cool program to validate creditcard numbers. Tools we will use:\n\n- `interact_manual()` to transform the creditcard input into a textbox\n- `cardIssuer()` to see if the card is a Visa, MC, Discover, Amex.\n- `checkLuhn()` to see if the card number passes the Lhun check\n- `print_title()` to display the title\n- `print_normal()` to display the output\n- `emoji.emojize()` to draw a thumbs up (passed Lhun check) or thumbs down (did not pass Lhun check).\n\nHere's the Algorithm:\n```\nprint the title \"credit card validator\"\nwrite an interact function with card as input\n get the card issuer\n if the card passes lhun check\n use thumbs up emoji\n else\n use thumbs down emoji\n print in normal text the emoji icon and the card issuer\n \n```\n\n### 1.7 You Code",
"_____no_output_____"
]
],
[
[
"## TODO Write code here\nfrom IPython.display import display, HTML\nfrom ipywidgets import interact_manual\n\n\n",
"_____no_output_____"
]
],
[
[
"##### Metacognition\n\n",
"_____no_output_____"
],
[
"\n### Rate your comfort level with this week's material so far. \n\n**1** ==> I don't understand this at all yet and need extra help. If you choose this please try to articulate that which you do not understand to the best of your ability in the questions and comments section below. \n**2** ==> I can do this with help or guidance from other people or resources. If you choose this level, please indicate HOW this person helped you in the questions and comments section below. \n**3** ==> I can do this on my own without any help. \n**4** ==> I can do this on my own and can explain/teach how to do it to others.\n\n`--== Double-Click Here then Enter a Number 1 through 4 Below This Line ==--` \n\n",
"_____no_output_____"
],
[
"### Questions And Comments \n\nRecord any questions or comments you have about this lab that you would like to discuss in your recitation. It is expected you will have questions if you did not complete the code sections correctly. Learning how to articulate what you do not understand is an important skill of critical thinking. Write them down here so that you remember to ask them in your recitation. We expect you will take responsilbity for your learning and ask questions in class.\n\n`--== Double-click Here then Enter Your Questions Below this Line ==--` \n",
"_____no_output_____"
]
],
[
[
"# run this code to turn in your work!\nfrom coursetools.submission import Submission\nSubmission().submit()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
4a90e8044876f27a51b4602d03ca4a4ff4422f7b
| 42,363 |
ipynb
|
Jupyter Notebook
|
dev/20_metrics.ipynb
|
nareshr8/fastai_dev
|
c34bf4e0fe296cb4ff8410dea3895c0ad2f6fe93
|
[
"Apache-2.0"
] | null | null | null |
dev/20_metrics.ipynb
|
nareshr8/fastai_dev
|
c34bf4e0fe296cb4ff8410dea3895c0ad2f6fe93
|
[
"Apache-2.0"
] | null | null | null |
dev/20_metrics.ipynb
|
nareshr8/fastai_dev
|
c34bf4e0fe296cb4ff8410dea3895c0ad2f6fe93
|
[
"Apache-2.0"
] | null | null | null | 32.916084 | 339 | 0.598234 |
[
[
[
"#export\nfrom local.imports import *\nfrom local.test import *\nfrom local.core import *\nfrom local.layers import *\nfrom local.data.pipeline import *\nfrom local.data.source import *\nfrom local.data.core import *\nfrom local.data.external import *\nfrom local.notebook.showdoc import show_doc\nfrom local.optimizer import *\nfrom local.learner import *\nfrom local.callback.progress import *",
"_____no_output_____"
],
[
"#default_exp metrics\n# default_cls_lvl 3",
"_____no_output_____"
]
],
[
[
"# Metrics\n\n> Definition of the metrics that can be used in training models",
"_____no_output_____"
],
[
"## Core metric",
"_____no_output_____"
],
[
"This is where the function that converts scikit-learn metrics to fastai metrics is defined. You should skip this section unless you want to know all about the internals of fastai.",
"_____no_output_____"
]
],
[
[
"import sklearn.metrics as skm",
"_____no_output_____"
],
[
"#export core\ndef flatten_check(inp, targ, detach=True):\n \"Check that `out` and `targ` have the same number of elements and flatten them.\"\n inp,targ = to_detach(inp.contiguous().view(-1)),to_detach(targ.contiguous().view(-1))\n test_eq(len(inp), len(targ))\n return inp,targ",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(5,4),torch.randn(20)\nx1,x2 = flatten_check(x1,x2)\ntest_eq(x1.shape, [20])\ntest_eq(x2.shape, [20])\nx1,x2 = torch.randn(5,4),torch.randn(21)\ntest_fail(lambda: flatten_check(x1,x2))",
"_____no_output_____"
],
[
"#export\nclass AccumMetric(Metric):\n \"Stores predictions and targets on CPU in accumulate to perform final calculations with `func`.\"\n def __init__(self, func, dim_argmax=None, sigmoid=False, thresh=None, to_np=False, invert_arg=False, **kwargs): \n self.func,self.dim_argmax,self.sigmoid,self.thresh = func,dim_argmax,sigmoid,thresh\n self.to_np,self.invert_args,self.kwargs = to_np,invert_arg,kwargs\n \n def reset(self): self.targs,self.preds = [],[]\n\n def accumulate(self, learn):\n pred = learn.pred.argmax(dim=self.dim_argmax) if self.dim_argmax else learn.pred\n if self.sigmoid: pred = torch.sigmoid(pred)\n if self.thresh: pred = (pred >= self.thresh)\n pred,targ = flatten_check(pred, learn.yb)\n self.preds.append(pred)\n self.targs.append(targ)\n \n @property\n def value(self): \n preds,targs = torch.cat(self.preds),torch.cat(self.targs)\n if self.to_np: preds,targs = preds.numpy(),targs.numpy()\n return self.func(targs, preds, **self.kwargs) if self.invert_args else self.func(preds, targs, **self.kwargs)",
"_____no_output_____"
]
],
[
[
"`func` is only applied to the accumulated predictions/targets when the `value` attribute is asked for (so at the end of a validation/trianing phase, in use with `Learner` and its `Recorder`).The signature of `func` should be `inp,targ` (where `inp` are the predictions of the model and `targ` the corresponding labels).\n\nFor classification problems with single label, predictions need to be transformed with a sofmax then an argmax before being compared to the targets. Since a softmax doesn't change the order of the numbers, we can just apply the argmax. Pass along `dim_argmax` to have this done by `AccumMetric` (usually -1 will work pretty well).\n\nFor classification problems with multiple labels, or if your targets are onehot-encoded, predictions may need to pass through a sigmoid (if it wasn't included in your model) then be compared to a given threshold (to decide between 0 and 1), this is done by `AccumMetric` if you pass `sigmoid=True` and/or a value for `thresh`.\n\nIf you want to use a metric function sklearn.metrics, you will need to convert predictions and labels to numpy arrays with `to_np=True`. Also, scikit-learn metrics adopt the convention `y_true`, `y_preds` which is the opposite from us, so you will need to pass `invert_arg=True` to make `AccumMetric` do the inversion for you.",
"_____no_output_____"
]
],
[
[
"#For testing: a fake learner and a metric that isn't an average\nclass TstLearner():\n def __init__(self): self.pred,self.yb = None,None",
"_____no_output_____"
],
[
"def _l2_mean(x,y): return torch.sqrt((x-y).float().pow(2).mean())\n\n#Go through a fake cycle with various batch sizes and computes the value of met\ndef compute_val(met, x1, x2):\n met.reset()\n vals = [0,6,15,20]\n learn = TstLearner()\n for i in range(3): \n learn.pred,learn.yb = x1[vals[i]:vals[i+1]],x2[vals[i]:vals[i+1]]\n met.accumulate(learn)\n return met.value",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(20,5),torch.randn(20,5)\ntst = AccumMetric(_l2_mean)\ntest_close(compute_val(tst, x1, x2), _l2_mean(x1, x2))\ntest_eq(torch.cat(tst.preds), x1.view(-1))\ntest_eq(torch.cat(tst.targs), x2.view(-1))\n\n#test argmax\nx1,x2 = torch.randn(20,5),torch.randint(0, 5, (20,))\ntst = AccumMetric(_l2_mean, dim_argmax=-1)\ntest_close(compute_val(tst, x1, x2), _l2_mean(x1.argmax(dim=-1), x2))\n\n#test thresh\nx1,x2 = torch.randn(20,5),torch.randint(0, 2, (20,5)).byte()\ntst = AccumMetric(_l2_mean, thresh=0.5)\ntest_close(compute_val(tst, x1, x2), _l2_mean((x1 >= 0.5), x2))\n\n#test sigmoid\nx1,x2 = torch.randn(20,5),torch.randn(20,5)\ntst = AccumMetric(_l2_mean, sigmoid=True)\ntest_close(compute_val(tst, x1, x2), _l2_mean(torch.sigmoid(x1), x2))\n\n#test to_np\nx1,x2 = torch.randn(20,5),torch.randn(20,5)\ntst = AccumMetric(lambda x,y: isinstance(x, np.ndarray) and isinstance(y, np.ndarray), to_np=True)\nassert compute_val(tst, x1, x2)\n\n#test invert_arg\nx1,x2 = torch.randn(20,5),torch.randn(20,5)\ntst = AccumMetric(lambda x,y: torch.sqrt(x.pow(2).mean()))\ntest_close(compute_val(tst, x1, x2), torch.sqrt(x1.pow(2).mean()))\ntst = AccumMetric(lambda x,y: torch.sqrt(x.pow(2).mean()), invert_arg=True)\ntest_close(compute_val(tst, x1, x2), torch.sqrt(x2.pow(2).mean()))",
"_____no_output_____"
],
[
"#export\ndef skm_to_fastai(func, is_class=True, thresh=None, axis=-1, sigmoid=None, **kwargs):\n \"Convert `func` from sklearn.metrics to a fastai metric\"\n dim_argmax = axis if is_class and thresh is None else None\n sigmoid = sigmoid if sigmoid is not None else (is_class and thresh is not None)\n return AccumMetric(func, dim_argmax=dim_argmax, sigmoid=sigmoid, thresh=thresh, \n to_np=True, invert_arg=True, **kwargs)",
"_____no_output_____"
]
],
[
[
"This is the quickest way to use a sckit-learn metric in a fastai training loop. `is_class` indicates if you are in a classification problem or not. In this case:\n- leaving `thresh` to `None` indicates it's a single-label classification problem and predictions will pass through an argmax over `axis` before being compared to the targets\n- setting a value for `thresh` indicates it's a multi-label classification problem and predictions will pass through a sigmoid (can be deactivated with `sigmoid=False`) and be compared to `thresh` before being compared to the targets\n\nIf `is_class=False`, it indicates you are in a regression problem, and predictions are compared to the targets without being modified. In all cases, `kwargs` are extra keyword arguments passed to `func`.",
"_____no_output_____"
]
],
[
[
"tst_single = skm_to_fastai(skm.precision_score)\nx1,x2 = torch.randn(20,2),torch.randint(0, 2, (20,))\ntest_close(compute_val(tst_single, x1, x2), skm.precision_score(x2, x1.argmax(dim=-1)))",
"_____no_output_____"
],
[
"tst_multi = skm_to_fastai(skm.precision_score, thresh=0.2)\nx1,x2 = torch.randn(20),torch.randint(0, 2, (20,))\ntest_close(compute_val(tst_multi, x1, x2), skm.precision_score(x2, torch.sigmoid(x1) >= 0.2))\n\ntst_multi = skm_to_fastai(skm.precision_score, thresh=0.2, sigmoid=False)\nx1,x2 = torch.randn(20),torch.randint(0, 2, (20,))\ntest_close(compute_val(tst_multi, x1, x2), skm.precision_score(x2, x1 >= 0.2))",
"_____no_output_____"
],
[
"tst_reg = skm_to_fastai(skm.r2_score, is_class=False)\nx1,x2 = torch.randn(20,5),torch.randn(20,5)\ntest_close(compute_val(tst_reg, x1, x2), skm.r2_score(x2.view(-1), x1.view(-1)))",
"_____no_output_____"
]
],
[
[
"## Single-label classification",
"_____no_output_____"
],
[
"> Warning: All functions defined in this section are intended for single-label classification and targets that aren't one-hot encoded. For multi-label problems or one-hot encoded targets, use the `_multi` version of them.",
"_____no_output_____"
]
],
[
[
"#export\ndef accuracy(inp, targ, axis=-1):\n \"Compute accuracy with `targ` when `pred` is bs * n_classes\"\n pred,targ = flatten_check(inp.argmax(dim=axis), targ)\n return (pred == targ).float().mean()",
"_____no_output_____"
],
[
"#For testing\ndef change_targ(targ, n, c):\n idx = torch.randperm(len(targ))[:n]\n res = targ.clone()\n for i in idx: res[i] = (res[i]+random.randint(1,c-1))%c\n return res",
"_____no_output_____"
],
[
"x = torch.randn(4,5)\ny = x.argmax(dim=1)\ntest_eq(accuracy(x,y), 1)\ny1 = change_targ(y, 2, 5)\ntest_eq(accuracy(x,y1), 0.5)\ntest_eq(accuracy(x.unsqueeze(1).expand(4,2,5), torch.stack([y,y1], dim=1)), 0.75)",
"_____no_output_____"
],
[
"#export\ndef error_rate(inp, targ, axis=-1):\n \"1 - `accuracy`\"\n return 1 - accuracy(inp, targ, axis=axis)",
"_____no_output_____"
],
[
"x = torch.randn(4,5)\ny = x.argmax(dim=1)\ntest_eq(error_rate(x,y), 0)\ny1 = change_targ(y, 2, 5)\ntest_eq(error_rate(x,y1), 0.5)\ntest_eq(error_rate(x.unsqueeze(1).expand(4,2,5), torch.stack([y,y1], dim=1)), 0.25)",
"_____no_output_____"
],
[
"#export\ndef top_k_accuracy(inp, targ, k=5, axis=-1):\n \"Computes the Top-k accuracy (`targ` is in the top `k` predictions of `inp`)\"\n inp = inp.topk(k=k, dim=axis)[1]\n targ = targ.unsqueeze(dim=axis).expand_as(inp)\n return (inp == targ).sum(dim=-1).float().mean()",
"_____no_output_____"
],
[
"x = torch.randn(6,5)\ny = torch.arange(0,6)\ntest_eq(top_k_accuracy(x[:5],y[:5]), 1)\ntest_eq(top_k_accuracy(x, y), 5/6)",
"_____no_output_____"
],
[
"#export\ndef APScore(axis=-1, average='macro', pos_label=1, sample_weight=None):\n \"Average Precision for single-label classification problems\"\n return skm_to_fastai(skm.average_precision_score, axis=axis, \n average=average, pos_label=pos_label, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef BalancedAccuracy(axis=-1, sample_weight=None, adjusted=False):\n \"Balanced Accuracy for single-label binary classification problems\"\n return skm_to_fastai(skm.balanced_accuracy_score, axis=axis, \n sample_weight=sample_weight, adjusted=adjusted)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.balanced_accuracy_score.html#sklearn.metrics.balanced_accuracy_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef BrierScore(axis=-1, sample_weight=None, pos_label=None):\n \"Brier score for single-label classification problems\"\n return skm_to_fastai(skm.brier_score_loss, axis=axis, \n sample_weight=sample_weight, pos_label=pos_label)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.brier_score_loss.html#sklearn.metrics.brier_score_loss) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef CohenKappa(axis=-1, labels=None, weights=None, sample_weight=None):\n \"Cohen kappa for single-label classification problems\"\n return skm_to_fastai(skm.cohen_kappa_score, axis=axis, \n sample_weight=sample_weight, pos_label=pos_label)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.cohen_kappa_score.html#sklearn.metrics.cohen_kappa_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef F1Score(axis=-1, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"F1 score for single-label classification problems\"\n return skm_to_fastai(skm.f1_score, axis=axis, \n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html#sklearn.metrics.f1_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef FBeta(beta, axis=-1, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"FBeta score with `beta` for single-label classification problems\"\n return skm_to_fastai(skm.fbeta_score, axis=axis,\n beta=beta, labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.fbeta_score.html#sklearn.metrics.fbeta_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef HammingLoss(axis=-1, labels=None, sample_weight=None):\n \"Cohen kappa for single-label classification problems\"\n return skm_to_fastai(skm.hamming_loss, axis=axis,\n labels=labels, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.hamming_loss.html#sklearn.metrics.hamming_loss) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef Jaccard(axis=-1, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"Jaccard score for single-label classification problems\"\n return skm_to_fastai(skm.jaccard_similarity_score, axis=axis, \n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard_score.html#sklearn.metrics.jaccard_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef MatthewsCorrCoef(axis=-1, sample_weight=None):\n \"Matthews correlation coefficient for single-label binary classification problems\"\n return skm_to_fastai(skm.matthews_corrcoef, axis=axis, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html#sklearn.metrics.matthews_corrcoef) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef Precision(axis=-1, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"Precision for single-label classification problems\"\n return skm_to_fastai(skm.precision_score, axis=axis,\n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html#sklearn.metrics.precision_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef Recall(axis=-1, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"Recall for single-label classification problems\"\n return skm_to_fastai(skm.recall_score, axis=axis,\n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html#sklearn.metrics.recall_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef RocAuc(axis=-1, average='macro', sample_weight=None, max_fpr=None):\n \"Area Under the Receiver Operating Characteristic Curve for single-label binary classification problems\"\n return skm_to_fastai(skm.recall_score, axis=axis,\n laverage=average, sample_weight=sample_weight, max_fpr=max_fpr)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\nclass Perplexity(AvgLoss):\n \"Perplexity (exponential of cross-entropy loss) for Language Models\"\n @property\n def value(self): return torch.exp(self.total/self.count) if self.count != 0 else None\n @property\n def name(self): return \"perplexity\"\n \nperplexity = Perplexity()",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(20,5),torch.randint(0, 5, (20,))\ntst = perplexity\ntst.reset()\nvals = [0,6,15,20]\nlearn = TstLearner()\nfor i in range(3): \n learn.yb = x2[vals[i]:vals[i+1]]\n learn.loss = F.cross_entropy(x1[vals[i]:vals[i+1]],x2[vals[i]:vals[i+1]])\n tst.accumulate(learn)\ntest_close(tst.value, torch.exp(F.cross_entropy(x1,x2)))",
"_____no_output_____"
]
],
[
[
"## Multi-label classification",
"_____no_output_____"
]
],
[
[
"#export\ndef accuracy_multi(inp, targ, thresh=0.5, sigmoid=True):\n \"Compute accuracy when `inp` and `targ` are the same size.\"\n inp,targ = flatten_check(inp,targ)\n if sigmoid: inp = inp.sigmoid()\n return ((inp>thresh)==targ.byte()).float().mean()",
"_____no_output_____"
],
[
"#For testing\ndef change_1h_targ(targ, n):\n idx = torch.randperm(targ.numel())[:n]\n res = targ.clone().view(-1)\n for i in idx: res[i] = 1-res[i]\n return res.view(targ.shape)",
"_____no_output_____"
],
[
"x = torch.randn(4,5)\ny = torch.sigmoid(x) >= 0.5\ntest_eq(accuracy_multi(x,y), 1)\ntest_eq(accuracy_multi(x,1-y), 0)\ny1 = change_1h_targ(y, 5)\ntest_eq(accuracy_multi(x,y1), 0.75)\n\n#Different thresh\ny = torch.sigmoid(x) >= 0.2\ntest_eq(accuracy_multi(x,y, thresh=0.2), 1)\ntest_eq(accuracy_multi(x,1-y, thresh=0.2), 0)\ny1 = change_1h_targ(y, 5)\ntest_eq(accuracy_multi(x,y1, thresh=0.2), 0.75)\n\n#No sigmoid\ny = x >= 0.5\ntest_eq(accuracy_multi(x,y, sigmoid=False), 1)\ntest_eq(accuracy_multi(x,1-y, sigmoid=False), 0)\ny1 = change_1h_targ(y, 5)\ntest_eq(accuracy_multi(x,y1, sigmoid=False), 0.75)",
"_____no_output_____"
],
[
"#export\ndef APScoreMulti(thresh=0.5, sigmoid=True, average='macro', pos_label=1, sample_weight=None):\n \"Average Precision for multi-label classification problems\"\n return skm_to_fastai(skm.average_precision_score, thresh=thresh, sigmoid=sigmoid, \n average=average, pos_label=pos_label, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef BrierScoreMulti(thresh=0.5, sigmoid=True, sample_weight=None, pos_label=None):\n \"Brier score for multi-label classification problems\"\n return skm_to_fastai(skm.brier_score_loss, thresh=thresh, sigmoid=sigmoid, \n sample_weight=sample_weight, pos_label=pos_label)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.brier_score_loss.html#sklearn.metrics.brier_score_loss) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef F1ScoreMulti(thresh=0.5, sigmoid=True, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"F1 score for multi-label classification problems\"\n return skm_to_fastai(skm.f1_score, thresh=thresh, sigmoid=sigmoid,\n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html#sklearn.metrics.f1_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef FBetaMulti(beta, thresh=0.5, sigmoid=True, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"FBeta score with `beta` for multi-label classification problems\"\n return skm_to_fastai(skm.fbeta_score, thresh=thresh, sigmoid=sigmoid,\n beta=beta, labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.fbeta_score.html#sklearn.metrics.fbeta_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef HammingLossMulti(thresh=0.5, sigmoid=True, labels=None, sample_weight=None):\n \"Cohen kappa for multi-label classification problems\"\n return skm_to_fastai(skm.hamming_loss, thresh=thresh, sigmoid=sigmoid,\n labels=labels, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.hamming_loss.html#sklearn.metrics.hamming_loss) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef JaccardMulti(thresh=0.5, sigmoid=True, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"Jaccard score for multi-label classification problems\"\n return skm_to_fastai(skm.jaccard_similarity_score, thresh=thresh, sigmoid=sigmoid,\n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard_score.html#sklearn.metrics.jaccard_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef MatthewsCorrCoefMulti(thresh=0.5, sigmoid=True, sample_weight=None):\n \"Matthews correlation coefficient for multi-label classification problems\"\n return skm_to_fastai(skm.matthews_corrcoef, thresh=thresh, sigmoid=sigmoid, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html#sklearn.metrics.matthews_corrcoef) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef PrecisionMulti(thresh=0.5, sigmoid=True, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"Precision for multi-label classification problems\"\n return skm_to_fastai(skm.precision_score, thresh=thresh, sigmoid=sigmoid,\n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html#sklearn.metrics.precision_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef RecallMulti(thresh=0.5, sigmoid=True, labels=None, pos_label=1, average='binary', sample_weight=None):\n \"Recall for multi-label classification problems\"\n return skm_to_fastai(skm.recall_score, thresh=thresh, sigmoid=sigmoid,\n labels=labels, pos_label=pos_label, average=average, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html#sklearn.metrics.recall_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef RocAucMulti(thresh=0.5, sigmoid=True, average='macro', sample_weight=None, max_fpr=None):\n \"Area Under the Receiver Operating Characteristic Curve for multi-label binary classification problems\"\n return skm_to_fastai(skm.recall_score, thresh=thresh, sigmoid=sigmoid,\n laverage=average, sample_weight=sample_weight, max_fpr=max_fpr)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score) for more details.",
"_____no_output_____"
],
[
"## Regression",
"_____no_output_____"
]
],
[
[
"#export\ndef mse(inp,targ):\n \"Mean squared error between `inp` and `targ`.\"\n return F.mse_loss(*flatten_check(inp,targ))",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(4,5),torch.randn(4,5)\ntest_close(mse(x1,x2), (x1-x2).pow(2).mean())",
"_____no_output_____"
],
[
"#export\ndef _rmse(inp, targ): return torch.sqrt(F.mse_loss(inp, targ))\nrmse = AccumMetric(_rmse)\nrmse.__doc__ = \"Root mean squared error\"",
"_____no_output_____"
],
[
"show_doc(rmse, name=\"rmse\")",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(20,5),torch.randn(20,5)\ntest_eq(compute_val(rmse, x1, x2), torch.sqrt(F.mse_loss(x1,x2)))",
"_____no_output_____"
],
[
"#export\ndef mae(inp,targ):\n \"Mean absolute error between `inp` and `targ`.\"\n inp,targ = flatten_check(inp,targ)\n return torch.abs(inp - targ).mean()",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(4,5),torch.randn(4,5)\ntest_eq(mae(x1,x2), torch.abs(x1-x2).mean())",
"_____no_output_____"
],
[
"#export\ndef msle(inp, targ):\n \"Mean squared logarithmic error between `inp` and `targ`.\"\n inp,targ = flatten_check(inp,targ)\n return F.mse_loss(torch.log(1 + inp), torch.log(1 + targ))",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(4,5),torch.randn(4,5)\nx1,x2 = torch.relu(x1),torch.relu(x2)\ntest_close(msle(x1,x2), (torch.log(x1+1)-torch.log(x2+1)).pow(2).mean())",
"_____no_output_____"
],
[
"#export\ndef _exp_rmspe(inp,targ): \n inp,targ = torch.exp(inp),torch.exp(targ)\n return torch.sqrt(((targ - inp)/targ).pow(2).mean())\nexp_rmspe = AccumMetric(_exp_rmspe)\nexp_rmspe.__doc__ = \"Root mean square percentage error of the exponential of predictions and targets\"",
"_____no_output_____"
],
[
"show_doc(exp_rmspe, name=\"exp_rmspe\")",
"_____no_output_____"
],
[
"x1,x2 = torch.randn(20,5),torch.randn(20,5)\ntest_eq(compute_val(exp_rmspe, x1, x2), torch.sqrt((((torch.exp(x2) - torch.exp(x1))/torch.exp(x2))**2).mean()))",
"_____no_output_____"
],
[
"#export\ndef ExplainedVariance(sample_weight=None):\n \"Explained variance betzeen predictions and targets\"\n return skm_to_fastai(skm.explained_variance_score, is_class=False, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.explained_variance_score.html#sklearn.metrics.explained_variance_score) for more details.",
"_____no_output_____"
]
],
[
[
"#export\ndef R2Score(sample_weight=None):\n \"R2 score betzeen predictions and targets\"\n return skm_to_fastai(skm.r2_score, is_class=False, sample_weight=sample_weight)",
"_____no_output_____"
]
],
[
[
"See the [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html#sklearn.metrics.r2_score) for more details.",
"_____no_output_____"
],
[
"## Segmentation",
"_____no_output_____"
]
],
[
[
"#export\ndef foreground_acc(inp, targ, bkg_idx=0, axis=1):\n \"Computes non-background accuracy for multiclass segmentation\"\n targ = targ.squeeze(1)\n mask = targ != bkg_idx\n return (inp.argmax(dim=axis)[mask]==targ[mask]).float().mean()",
"_____no_output_____"
],
[
"x = torch.randn(4,5,3,3)\ny = x.argmax(dim=1)[:,None]\ntest_eq(foreground_acc(x,y), 1)\ny[0] = 0 #the 0s are ignored so we get the same value\ntest_eq(foreground_acc(x,y), 1)",
"_____no_output_____"
],
[
"#export\nclass Dice(Metric):\n \"Dice coefficient metric for binary target in segmentation\"\n def __init__(self, axis=1): self.axis = axis\n def reset(self): self.inter,self.union = 0,0\n def accumulate(self, learn):\n pred,targ = flatten_check(learn.pred.argmax(dim=self.axis), learn.yb)\n self.inter += (pred*targ).float().sum().item()\n self.union += (pred+targ).float().sum().item()\n \n @property\n def value(self): return 2. * self.inter/self.union if self.union > 0 else None",
"_____no_output_____"
],
[
"x1 = torch.randn(20,2,3,3)\nx2 = torch.randint(0, 2, (20, 3, 3))\npred = x1.argmax(1)\ninter = (pred*x2).float().sum().item()\nunion = (pred+x2).float().sum().item()\ntest_eq(compute_val(Dice(), x1, x2), 2*inter/union)",
"_____no_output_____"
],
[
"#export\nclass JaccardCoeff(Dice):\n \"Implemetation of the jaccard coefficient that is lighter in RAM\"\n @property\n def value(self): return self.inter/(self.union-self.inter) if self.union > 0 else None",
"_____no_output_____"
],
[
"x1 = torch.randn(20,2,3,3)\nx2 = torch.randint(0, 2, (20, 3, 3))\npred = x1.argmax(1)\ninter = (pred*x2).float().sum().item()\nunion = (pred+x2).float().sum().item()\ntest_eq(compute_val(JaccardCoeff(), x1, x2), inter/(union-inter))",
"_____no_output_____"
]
],
[
[
"## Export -",
"_____no_output_____"
]
],
[
[
"#hide\nfrom local.notebook.export import notebook2script\nnotebook2script(all_fs=True)",
"Converted 00_test.ipynb.\nConverted 01_core.ipynb.\nConverted 01a_script.ipynb.\nConverted 02_transforms.ipynb.\nConverted 03_pipeline.ipynb.\nConverted 04_data_external.ipynb.\nConverted 05_data_core.ipynb.\nConverted 06_data_source.ipynb.\nConverted 07_vision_core.ipynb.\nConverted 08_pets_tutorial.ipynb.\nConverted 09_vision_augment.ipynb.\nConverted 09a_rect_augment.ipynb.\nConverted 11_layers.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_learner.ipynb.\nConverted 14_callback_schedule.ipynb.\nConverted 15_callback_hook.ipynb.\nConverted 16_callback_progress.ipynb.\nConverted 17_callback_tracker.ipynb.\nConverted 18_callback_fp16.ipynb.\nConverted 20_metrics.ipynb.\nConverted 30_text_core.ipynb.\nConverted 90_notebook_core.ipynb.\nConverted 91_notebook_export.ipynb.\nConverted 92_notebook_showdoc.ipynb.\nConverted 93_notebook_export2html.ipynb.\nConverted 94_index.ipynb.\nConverted 95_synth_learner.ipynb.\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"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",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a90f8399d7d649c2984eaf80746dd1ca576d621
| 24,126 |
ipynb
|
Jupyter Notebook
|
week5_policy_based/practice_a3c.ipynb
|
ajmalrasi/Practical_Reinforcement-Learning
|
fcc42be697921046f529b1b8d9a264fcd93e4e9f
|
[
"MIT"
] | 2 |
2019-02-13T15:47:11.000Z
|
2019-02-26T19:50:11.000Z
|
week5_policy_based/practice_a3c.ipynb
|
ajmalrasi/Practical_Reinforcement-Learning
|
fcc42be697921046f529b1b8d9a264fcd93e4e9f
|
[
"MIT"
] | 2 |
2019-02-18T19:33:36.000Z
|
2019-02-19T15:03:35.000Z
|
week5_policy_based/practice_a3c.ipynb
|
ajmalrasi/Practical_Reinforcement-Learning
|
fcc42be697921046f529b1b8d9a264fcd93e4e9f
|
[
"MIT"
] | 1 |
2019-02-14T21:12:04.000Z
|
2019-02-14T21:12:04.000Z
| 33.461859 | 343 | 0.563583 |
[
[
[
"### Deep Kung-Fu with advantage actor-critic\n\nIn this notebook you'll build a deep reinforcement learning agent for atari [KungFuMaster](https://gym.openai.com/envs/KungFuMaster-v0/) and train it with advantage actor-critic.\n\n",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function, division\nfrom IPython.core import display\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\n\n#If you are running on a server, launch xvfb to record game videos\n#Please make sure you have xvfb installed\nimport os\nif os.environ.get(\"DISPLAY\") is str and len(os.environ.get(\"DISPLAY\"))!=0:\n !bash ../xvfb start\n %env DISPLAY=:1",
"_____no_output_____"
]
],
[
[
"For starters, let's take a look at the game itself:\n* Image resized to 42x42 and grayscale to run faster\n* Rewards divided by 100 'cuz they are all divisible by 100\n* Agent sees last 4 frames of game to account for object velocity",
"_____no_output_____"
]
],
[
[
"import gym\nfrom atari_util import PreprocessAtari\n\n# We scale rewards to avoid exploding gradients during optimization.\nreward_scale = 0.01\n\ndef make_env():\n env = gym.make(\"KungFuMasterDeterministic-v0\")\n env = PreprocessAtari(\n env, height=42, width=42,\n crop=lambda img: img[60:-30, 5:],\n dim_order='tensorflow',\n color=False, n_frames=4,\n reward_scale=reward_scale)\n return env\n\nenv = make_env()\n\nobs_shape = env.observation_space.shape\nn_actions = env.action_space.n\n\nprint(\"Observation shape:\", obs_shape)\nprint(\"Num actions:\", n_actions)\nprint(\"Action names:\", env.env.env.get_action_meanings())",
"_____no_output_____"
],
[
"s = env.reset()\nfor _ in range(100):\n s, _, _, _ = env.step(env.action_space.sample())\n\nplt.title('Game image')\nplt.imshow(env.render('rgb_array'))\nplt.show()\n\nplt.title('Agent observation (4-frame buffer)')\nplt.imshow(s.transpose([0,2,1]).reshape([42,-1]))\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Build an agent\n\nWe now have to build an agent for actor-critic training - a convolutional neural network that converts states into action probabilities $\\pi$ and state values $V$.\n\nYour assignment here is to build and apply a neural network - with any framework you want. \n\nFor starters, we want you to implement this architecture:\n\n\nAfter your agent gets mean reward above 50, we encourage you to experiment with model architecture to score even better.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\ntf.reset_default_graph()\nsess = tf.InteractiveSession()",
"_____no_output_____"
],
[
"from keras.layers import Conv2D, Dense, Flatten\n\nclass Agent:\n def __init__(self, name, state_shape, n_actions, reuse=False):\n \"\"\"A simple actor-critic agent\"\"\"\n \n with tf.variable_scope(name, reuse=reuse):\n \n # Prepare neural network architecture\n ### Your code here: prepare any necessary layers, variables, etc.\n \n # prepare a graph for agent step\n self.state_t = tf.placeholder('float32', [None,] + list(state_shape))\n self.agent_outputs = self.symbolic_step(self.state_t)\n \n def symbolic_step(self, state_t):\n \"\"\"Takes agent's previous step and observation, returns next state and whatever it needs to learn (tf tensors)\"\"\"\n \n # Apply neural network\n ### Your code here: apply agent's neural network to get policy logits and state values.\n \n logits = <logits go here>\n state_value = <state values go here>\n \n assert tf.is_numeric_tensor(state_value) and state_value.shape.ndims == 1, \\\n \"please return 1D tf tensor of state values [you got %s]\" % repr(state_value)\n assert tf.is_numeric_tensor(logits) and logits.shape.ndims == 2, \\\n \"please return 2d tf tensor of logits [you got %s]\" % repr(logits)\n # hint: if you triggered state_values assert with your shape being [None, 1], \n # just select [:, 0]-th element of state values as new state values\n \n return (logits, state_value)\n \n def step(self, state_t):\n \"\"\"Same as symbolic step except it operates on numpy arrays\"\"\"\n sess = tf.get_default_session()\n return sess.run(self.agent_outputs, {self.state_t: state_t})\n \n def sample_actions(self, agent_outputs):\n \"\"\"pick actions given numeric agent outputs (np arrays)\"\"\"\n logits, state_values = agent_outputs\n policy = np.exp(logits) / np.sum(np.exp(logits), axis=-1, keepdims=True)\n return np.array([np.random.choice(len(p), p=p) for p in policy])",
"_____no_output_____"
],
[
"agent = Agent(\"agent\", obs_shape, n_actions)\nsess.run(tf.global_variables_initializer())",
"_____no_output_____"
],
[
"state = [env.reset()]\nlogits, value = agent.step(state)\nprint(\"action logits:\\n\", logits)\nprint(\"state values:\\n\", value)",
"_____no_output_____"
]
],
[
[
"### Let's play!\nLet's build a function that measures agent's average reward.",
"_____no_output_____"
]
],
[
[
"def evaluate(agent, env, n_games=1):\n \"\"\"Plays an a game from start till done, returns per-game rewards \"\"\"\n\n game_rewards = []\n for _ in range(n_games):\n state = env.reset()\n\n total_reward = 0\n while True:\n action = agent.sample_actions(agent.step([state]))[0]\n state, reward, done, info = env.step(action)\n total_reward += reward\n if done: break\n\n # We rescale the reward back to ensure compatibility\n # with other evaluations.\n game_rewards.append(total_reward / reward_scale)\n return game_rewards",
"_____no_output_____"
],
[
"env_monitor = gym.wrappers.Monitor(env, directory=\"kungfu_videos\", force=True)\nrw = evaluate(agent, env_monitor, n_games=3,)\nenv_monitor.close()\nprint (rw)",
"_____no_output_____"
],
[
"#show video\nimport os\n\nfrom IPython.display import HTML\n\nvideo_names = [s for s in os.listdir(\"./kungfu_videos/\") if s.endswith(\".mp4\")]\n\nHTML(\"\"\"\n<video width=\"640\" height=\"480\" controls>\n <source src=\"{}\" type=\"video/mp4\">\n</video>\n\"\"\".format(\"./kungfu_videos/\" + video_names[-1])) #this may or may not be _last_ video. Try other indices",
"_____no_output_____"
]
],
[
[
"### Training on parallel games\n\n\nTo make actor-critic training more stable, we shall play several games in parallel. This means ya'll have to initialize several parallel gym envs, send agent's actions there and .reset() each env if it becomes terminated. To minimize learner brain damage, we've taken care of them for ya - just make sure you read it before you use it.\n",
"_____no_output_____"
]
],
[
[
"class EnvBatch:\n def __init__(self, n_envs = 10):\n \"\"\" Creates n_envs environments and babysits them for ya' \"\"\"\n self.envs = [make_env() for _ in range(n_envs)]\n \n def reset(self):\n \"\"\" Reset all games and return [n_envs, *obs_shape] observations \"\"\"\n return np.array([env.reset() for env in self.envs])\n \n def step(self, actions):\n \"\"\"\n Send a vector[batch_size] of actions into respective environments\n :returns: observations[n_envs, *obs_shape], rewards[n_envs], done[n_envs,], info[n_envs]\n \"\"\"\n results = [env.step(a) for env, a in zip(self.envs, actions)]\n new_obs, rewards, done, infos = map(np.array, zip(*results))\n \n # reset environments automatically\n for i in range(len(self.envs)):\n if done[i]:\n new_obs[i] = self.envs[i].reset()\n \n return new_obs, rewards, done, infos",
"_____no_output_____"
]
],
[
[
"__Let's try it out:__",
"_____no_output_____"
]
],
[
[
"env_batch = EnvBatch(10)\n\nbatch_states = env_batch.reset()\n\nbatch_actions = agent.sample_actions(agent.step(batch_states))\n\nbatch_next_states, batch_rewards, batch_done, _ = env_batch.step(batch_actions)\n\nprint(\"State shape:\", batch_states.shape)\nprint(\"Actions:\", batch_actions[:3])\nprint(\"Rewards:\", batch_rewards[:3])\nprint(\"Done:\", batch_done[:3])",
"_____no_output_____"
]
],
[
[
"# Actor-critic\n\nHere we define a loss functions and learning algorithms as usual.",
"_____no_output_____"
]
],
[
[
"# These placeholders mean exactly the same as in \"Let's try it out\" section above\nstates_ph = tf.placeholder('float32', [None,] + list(obs_shape)) \nnext_states_ph = tf.placeholder('float32', [None,] + list(obs_shape))\nactions_ph = tf.placeholder('int32', (None,))\nrewards_ph = tf.placeholder('float32', (None,))\nis_done_ph = tf.placeholder('float32', (None,))",
"_____no_output_____"
],
[
"# logits[n_envs, n_actions] and state_values[n_envs, n_actions]\nlogits, state_values = agent.symbolic_step(states_ph)\nnext_logits, next_state_values = agent.symbolic_step(next_states_ph)\nnext_state_values = next_state_values * (1 - is_done_ph)\n\n# probabilities and log-probabilities for all actions\nprobs = tf.nn.softmax(logits) # [n_envs, n_actions]\nlogprobs = tf.nn.log_softmax(logits) # [n_envs, n_actions]\n\n# log-probabilities only for agent's chosen actions\nlogp_actions = tf.reduce_sum(logprobs * tf.one_hot(actions_ph, n_actions), axis=-1) # [n_envs,]",
"_____no_output_____"
],
[
"\n\n# compute advantage using rewards_ph, state_values and next_state_values\ngamma = 0.99\nadvantage = <YOUR CODE>\n\nassert advantage.shape.ndims == 1, \"please compute advantage for each sample, vector of shape [n_envs,]\"\n\n# compute policy entropy given logits_seq. Mind the \"-\" sign!\nentropy = <YOUR CODE>\n\nassert entropy.shape.ndims == 1, \"please compute pointwise entropy vector of shape [n_envs,] \"\n\n\n\nactor_loss = - tf.reduce_mean(logp_actions * tf.stop_gradient(advantage)) - 0.001 * tf.reduce_mean(entropy)\n\n# compute target state values using temporal difference formula. Use rewards_ph and next_step_values\ntarget_state_values = <YOUR CODE>\n\ncritic_loss = tf.reduce_mean((state_values - tf.stop_gradient(target_state_values))**2 )\n\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(actor_loss + critic_loss)\nsess.run(tf.global_variables_initializer())",
"_____no_output_____"
],
[
"# Sanity checks to catch some errors. Specific to KungFuMaster in assignment's default setup.\nl_act, l_crit, adv, ent = sess.run([actor_loss, critic_loss, advantage, entropy], feed_dict = {\n states_ph: batch_states,\n actions_ph: batch_actions,\n next_states_ph: batch_states,\n rewards_ph: batch_rewards,\n is_done_ph: batch_done,\n })\n\nassert abs(l_act) < 100 and abs(l_crit) < 100, \"losses seem abnormally large\"\nassert 0 <= ent.mean() <= np.log(n_actions), \"impossible entropy value, double-check the formula pls\"\nif ent.mean() < np.log(n_actions) / 2: print(\"Entropy is too low for untrained agent\")\nprint(\"You just might be fine!\")",
"_____no_output_____"
]
],
[
[
"# Train \n\nJust the usual - play a bit, compute loss, follow the graidents, repeat a few million times.\n",
"_____no_output_____"
]
],
[
[
"from IPython.display import clear_output\nfrom tqdm import trange\nfrom pandas import DataFrame\newma = lambda x, span=100: DataFrame({'x':np.asarray(x)}).x.ewm(span=span).mean().values\n\nenv_batch = EnvBatch(10)\nbatch_states = env_batch.reset()\n\nrewards_history = []\nentropy_history = []",
"_____no_output_____"
],
[
"for i in trange(100000):\n batch_actions = agent.sample_actions(agent.step(batch_states))\n batch_next_states, batch_rewards, batch_done, _ = env_batch.step(batch_actions)\n\n feed_dict = {\n states_ph: batch_states,\n actions_ph: batch_actions,\n next_states_ph: batch_next_states,\n rewards_ph: batch_rewards,\n is_done_ph: batch_done,\n }\n batch_states = batch_next_states\n\n _, ent_t = sess.run([train_step, entropy], feed_dict)\n entropy_history.append(np.mean(ent_t))\n\n if i % 500 == 0:\n if i % 2500 == 0:\n rewards_history.append(np.mean(evaluate(agent, env, n_games=3)))\n if rewards_history[-1] >= 50:\n print(\"Your agent has earned the yellow belt\" % color)\n\n clear_output(True)\n plt.figure(figsize=[8, 4])\n plt.subplot(1, 2, 1)\n plt.plot(rewards_history, label='rewards')\n plt.plot(ewma(np.array(rewards_history), span=10), marker='.', label='rewards ewma@10')\n plt.title(\"Session rewards\")\n plt.grid()\n plt.legend()\n\n plt.subplot(1, 2, 2)\n plt.plot(entropy_history, label='entropy')\n plt.plot(ewma(np.array(entropy_history), span=1000), label='entropy ewma@1000')\n plt.title(\"Policy entropy\")\n plt.grid()\n plt.legend()\n plt.show()",
"_____no_output_____"
]
],
[
[
"Relax and grab some refreshments while your agent is locked in an infinite loop of violence and death.\n\n__How to interpret plots:__\n\nThe session reward is the easy thing: it should in general go up over time, but it's okay if it fluctuates ~~like crazy~~. It's also OK if it reward doesn't increase substantially before some 10k initial steps. However, if reward reaches zero and doesn't seem to get up over 2-3 evaluations, there's something wrong happening.\n\n\nSince we use a policy-based method, we also keep track of __policy entropy__ - the same one you used as a regularizer. The only important thing about it is that your entropy shouldn't drop too low (`< 0.1`) before your agent gets the yellow belt. Or at least it can drop there, but _it shouldn't stay there for long_.\n\nIf it does, the culprit is likely:\n* Some bug in entropy computation. Remember that it is $ - \\sum p(a_i) \\cdot log p(a_i) $\n* Your agent architecture converges too fast. Increase entropy coefficient in actor loss. \n* Gradient explosion - just [clip gradients](https://stackoverflow.com/a/43486487) and maybe use a smaller network\n* Us. Or TF developers. Or aliens. Or lizardfolk. Contact us on forums before it's too late!\n\nIf you're debugging, just run `logits, values = agent.step(batch_states)` and manually look into logits and values. This will reveal the problem 9 times out of 10: you'll likely see some NaNs or insanely large numbers or zeros. Try to catch the moment when this happens for the first time and investigate from there.",
"_____no_output_____"
],
[
"### \"Final\" evaluation",
"_____no_output_____"
]
],
[
[
"env_monitor = gym.wrappers.Monitor(env, directory=\"kungfu_videos\", force=True)\nfinal_rewards = evaluate(agent, env_monitor, n_games=20)\nenv_monitor.close()\nprint(\"Final mean reward:\", np.mean(final_rewards))\n\nvideo_names = list(filter(lambda s: s.endswith(\".mp4\"), os.listdir(\"./kungfu_videos/\")))",
"_____no_output_____"
],
[
"HTML(\"\"\"\n<video width=\"640\" height=\"480\" controls>\n <source src=\"{}\" type=\"video/mp4\">\n</video>\n\"\"\".format(\"./kungfu_videos/\"+video_names[-1])) ",
"_____no_output_____"
],
[
"HTML(\"\"\"\n<video width=\"640\" height=\"480\" controls>\n <source src=\"{}\" type=\"video/mp4\">\n</video>\n\"\"\".format(\"./kungfu_videos/\" + video_names[-2])) # try other indices",
"_____no_output_____"
],
[
"# if you don't see videos, just navigate to ./kungfu_videos and download .mp4 files from there.",
"_____no_output_____"
],
[
"from submit import submit_kungfu\nenv = make_env()\nsubmit_kungfu(agent, env, evaluate, <EMAIL>, <TOKEN>)",
"_____no_output_____"
]
],
[
[
"```\n\n```\n```\n\n```\n```\n\n```\n```\n\n```\n```\n\n```\n```\n\n```\n```\n\n```\n```\n\n```\n",
"_____no_output_____"
],
[
"### Now what?\nWell, 5k reward is [just the beginning](https://www.buzzfeed.com/mattjayyoung/what-the-color-of-your-karate-belt-actually-means-lg3g). Can you get past 200? With recurrent neural network memory, chances are you can even beat 400!\n\n* Try n-step advantage and \"lambda\"-advantage (aka GAE) - see [this article](https://arxiv.org/abs/1506.02438)\n * This change should improve early convergence a lot\n* Try recurrent neural network \n * RNN memory will slow things down initially, but in will reach better final reward at this game\n* Implement asynchronuous version\n * Remember [A3C](https://arxiv.org/abs/1602.01783)? The first \"A\" stands for asynchronuous. It means there are several parallel actor-learners out there.\n * You can write custom code for synchronization, but we recommend using [redis](https://redis.io/)\n * You can store full parameter set in redis, along with any other metadate\n * Here's a _quick_ way to (de)serialize parameters for redis\n ```\n import joblib\n from six import BytesIO\n```\n```\n def dumps(data):\n \"converts whatever to string\"\n s = BytesIO()\n joblib.dump(data,s)\n return s.getvalue()\n``` \n```\n def loads(string):\n \"converts string to whatever was dumps'ed in it\"\n return joblib.load(BytesIO(string))\n```",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4a90fbc645e959fba50b5094488ca15fd2ea994b
| 9,947 |
ipynb
|
Jupyter Notebook
|
notebooks/01_Notebooks.ipynb
|
leonistor/MadeWithML
|
8ee6de5b3bd98a4b882b5782732e574b70ded1e5
|
[
"MIT"
] | null | null | null |
notebooks/01_Notebooks.ipynb
|
leonistor/MadeWithML
|
8ee6de5b3bd98a4b882b5782732e574b70ded1e5
|
[
"MIT"
] | null | null | null |
notebooks/01_Notebooks.ipynb
|
leonistor/MadeWithML
|
8ee6de5b3bd98a4b882b5782732e574b70ded1e5
|
[
"MIT"
] | null | null | null | 32.087097 | 292 | 0.51895 |
[
[
[
"\n<div align=\"center\">\n<h1><img width=\"30\" src=\"https://madewithml.com/static/images/rounded_logo.png\"> <a href=\"https://madewithml.com/\">Made With ML</a></h1>\nApplied ML · MLOps · Production\n<br>\nJoin 30K+ developers in learning how to responsibly <a href=\"https://madewithml.com/about/\">deliver value</a> with ML.\n <br>\n</div>\n\n<br>\n\n<div align=\"center\">\n <a target=\"_blank\" href=\"https://newsletter.madewithml.com\"><img src=\"https://img.shields.io/badge/Subscribe-30K-brightgreen\"></a> \n <a target=\"_blank\" href=\"https://github.com/GokuMohandas/MadeWithML\"><img src=\"https://img.shields.io/github/stars/GokuMohandas/MadeWithML.svg?style=social&label=Star\"></a> \n <a target=\"_blank\" href=\"https://www.linkedin.com/in/goku\"><img src=\"https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social\"></a> \n <a target=\"_blank\" href=\"https://twitter.com/GokuMohandas\"><img src=\"https://img.shields.io/twitter/follow/GokuMohandas.svg?label=Follow&style=social\"></a>\n <br>\n 🔥 Among the <a href=\"https://github.com/topics/deep-learning\" target=\"_blank\">top ML</a> repositories on GitHub\n</div>\n\n<br>\n<hr>",
"_____no_output_____"
],
[
"# Notebooks\n\nIn this lesson, we'll learn about how to work with notebooks. ",
"_____no_output_____"
],
[
"<div align=\"left\">\n<a target=\"_blank\" href=\"https://madewithml.com/courses/foundations/notebooks/\"><img src=\"https://img.shields.io/badge/📖 Read-blog post-9cf\"></a> \n<a href=\"https://github.com/GokuMohandas/MadeWithML/blob/main/notebooks/01_Notebooks.ipynb\" role=\"button\"><img src=\"https://img.shields.io/static/v1?label=&message=View%20On%20GitHub&color=586069&logo=github&labelColor=2f363d\"></a> \n<a href=\"https://colab.research.google.com/github/GokuMohandas/MadeWithML/blob/main/notebooks/01_Notebooks.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n</div>",
"_____no_output_____"
],
[
"# Set Up",
"_____no_output_____"
],
[
"1. Click on this link to open the accompanying [notebook]() for this lesson or create a blank one on [Google Colab](https://colab.research.google.com/).\n2. Sign into your [Google account](https://accounts.google.com/signin) to start using the notebook. If you don't want to save your work, you can skip the steps below. If you do not have access to Google, you can follow along using [Jupyter Lab](https://jupyter.org/).\n3. If you do want to save your work, click the **COPY TO DRIVE** button on the toolbar. This will open a new notebook in a new tab. Rename this new notebook by removing the words Copy of from the title (change `Copy of 01_Notebooks` to `01_Notebooks`).\n\n<div align=\"center\">\n<img src=\"https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/images/foundations/notebooks/copy_to_drive.png\" width=\"400\">  <img src=\"https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/images/foundations/notebooks/rename.png\" width=\"320\">\n</div>",
"_____no_output_____"
],
[
"# Types of cells",
"_____no_output_____"
],
[
"Notebooks are made up of cells. Each cell can either be a `code cell` or a `text cell`. \n\n* `code cell`: used for writing and executing code.\n* `text cell`: used for writing text, HTML, Markdown, etc.\n\n\n",
"_____no_output_____"
],
[
"# Creating cells",
"_____no_output_____"
],
[
"First, let's create a text cell. Click on a desired location in the notebook and create the cell by clicking on the `➕ TEXT` (located in the top left corner). \n\n<div align=\"left\">\n<img src=\"https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/images/foundations/notebooks/text_cell.png\" width=\"320\">\n</div>\n\nOnce you create the cell, click on it and type the following text inside it:\n\n\n```\n### This is a header\nHello world!\n```",
"_____no_output_____"
],
[
"### This is a header\nHello world!",
"_____no_output_____"
],
[
"### Header\nHello, zuza!",
"_____no_output_____"
],
[
"# Running cells",
"_____no_output_____"
],
[
"Once you type inside the cell, press the `SHIFT` and `RETURN` (enter key) together to run the cell.",
"_____no_output_____"
],
[
"# Editing cells",
"_____no_output_____"
],
[
"To edit a cell, double click on it and make any changes.",
"_____no_output_____"
],
[
"# Moving cells",
"_____no_output_____"
],
[
"Once you create the cell, you can move it up and down by clicking on the cell and then pressing the ⬆ and ⬇ button on the top right of the cell. \n\n<div align=\"left\">\n<img src=\"https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/images/foundations/notebooks/move_cell.png\" width=\"500\">\n</div>",
"_____no_output_____"
],
[
"# Deleting cells",
"_____no_output_____"
],
[
"You can delete the cell by clicking on it and pressing the trash can button 🗑️ on the top right corner of the cell. Alternatively, you can also press ⌘/Ctrl + M + D.\n\n<div align=\"left\">\n<img src=\"https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/images/foundations/notebooks/delete_cell.png\" width=\"500\">\n</div>",
"_____no_output_____"
],
[
"# Creating a code cell\n",
"_____no_output_____"
],
[
"You can repeat the steps above to create and edit a *code* cell. You can create a code cell by clicking on the `➕ CODE` (located in the top left corner).\n\n<div align=\"left\">\n<img src=\"https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/images/foundations/notebooks/code_cell.png\" width=\"320\">\n</div>\n\nOnce you've created the code cell, double click on it, type the following inside it and then press `Shift + Enter` to execute the code.\n\n```\nprint (\"Hello world!\")\n```",
"_____no_output_____"
]
],
[
[
"print (\"Hello world!\")",
"Hello world!\n"
]
],
[
[
"These are the basic concepts you'll need to use these notebooks but we'll learn few more tricks in subsequent lessons.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a910456072c22d2ef39341e3796fb876d50b497
| 4,033 |
ipynb
|
Jupyter Notebook
|
notebooks/examples/twitcher-c3s-magic-demo.ipynb
|
bird-house/birdy
|
561ca91fbe8c64e36f4afd1ec6ee3a03bf1918eb
|
[
"Apache-2.0"
] | 7 |
2018-02-13T16:18:37.000Z
|
2022-03-31T13:42:50.000Z
|
notebooks/examples/twitcher-c3s-magic-demo.ipynb
|
bird-house/birdy
|
561ca91fbe8c64e36f4afd1ec6ee3a03bf1918eb
|
[
"Apache-2.0"
] | 163 |
2015-02-17T11:46:16.000Z
|
2022-03-31T21:54:28.000Z
|
notebooks/examples/twitcher-c3s-magic-demo.ipynb
|
bird-house/birdy
|
561ca91fbe8c64e36f4afd1ec6ee3a03bf1918eb
|
[
"Apache-2.0"
] | 4 |
2018-10-23T01:29:00.000Z
|
2021-08-16T11:41:41.000Z
| 17.309013 | 106 | 0.504587 |
[
[
[
"from birdy import WPSClient",
"_____no_output_____"
],
[
"magic = WPSClient('https://cp4cds-cn2.dkrz.de/ows/proxy/magic_demo') # verify=False # progress=True",
"_____no_output_____"
]
],
[
[
"### Rainfarm",
"_____no_output_____"
]
],
[
[
"help(magic.rainfarm)",
"_____no_output_____"
],
[
"result = magic.rainfarm()",
"_____no_output_____"
],
[
"print(result.getStatus())\nprint(result.statusMessage)\nprint(result.percentCompleted)",
"_____no_output_____"
],
[
"result.get()",
"_____no_output_____"
],
[
"result.get().success",
"_____no_output_____"
]
],
[
[
"### Run consecdrydays",
"_____no_output_____"
]
],
[
[
"result = magic.consecdrydays()",
"_____no_output_____"
],
[
"print(result.getStatus())\nprint(result.statusMessage)\nprint(result.percentCompleted)",
"_____no_output_____"
],
[
"result.get()",
"_____no_output_____"
],
[
"result.get().success",
"_____no_output_____"
]
],
[
[
"### Weather Regimes",
"_____no_output_____"
]
],
[
[
"result = magic.weather_regimes()",
"_____no_output_____"
],
[
"print(result.getStatus())\nprint(result.statusMessage)\nprint(result.percentCompleted)",
"_____no_output_____"
],
[
"result.get()",
"_____no_output_____"
],
[
"result.get().success",
"_____no_output_____"
]
],
[
[
"### Modes of Variability",
"_____no_output_____"
]
],
[
[
"result = magic.modes_of_variability()",
"_____no_output_____"
],
[
"print(result.getStatus())\nprint(result.statusMessage)\nprint(result.percentCompleted)",
"_____no_output_____"
],
[
"result.get()\n",
"_____no_output_____"
],
[
"result.get().success",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a912d68c1c995b5eda825542e29ab6f7ff2db56
| 660,137 |
ipynb
|
Jupyter Notebook
|
colab/kagle_multi_linear.ipynb
|
bhagath-ac07/machine-learning
|
2f790730d906932b0f402c8dfa6dc856dbcf79b7
|
[
"MIT"
] | null | null | null |
colab/kagle_multi_linear.ipynb
|
bhagath-ac07/machine-learning
|
2f790730d906932b0f402c8dfa6dc856dbcf79b7
|
[
"MIT"
] | null | null | null |
colab/kagle_multi_linear.ipynb
|
bhagath-ac07/machine-learning
|
2f790730d906932b0f402c8dfa6dc856dbcf79b7
|
[
"MIT"
] | null | null | null | 3,793.890805 | 653,238 | 0.962597 |
[
[
[
"<a href=\"https://colab.research.google.com/github/bhagath-ac07/machine-learning/blob/main/colab/kagle_multi_linear.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive')\n\n# from google.colab import auth\n# auth.authenticate_user()\n\n# import gspread\n# from oauth2client.client import GoogleCredentials\n\n# gc = gspread.authorize(GoogleCredentials.get_application_default())\n\n# worksheet = gc.open_by_url('data').sheet1\n\n# # get_all_values gives a list of rows.\n# rows = worksheet.get_all_values()\n\n# # Convert to a DataFrame and render.\n# import pandas as pd\ndataset = pd.read_csv('/content/drive/MyDrive/kc_house_data1.csv')\n\n\nimport sys #access to system parameters https://docs.python.org/3/library/sys.html\nprint(\"Python version: {}\". format(sys.version))\nimport numpy as np # linear algebra\nprint(\"NumPy version: {}\". format(np.__version__))\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nprint(\"pandas version: {}\". format(pd.__version__))\nimport matplotlib # collection of functions for scientific and publication-ready visualization\nprint(\"matplotlib version: {}\". format(matplotlib.__version__))\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport warnings # ignore warnings\nwarnings.filterwarnings('ignore')\n\ndataset.head()\nprint(dataset.dtypes)\n\ndataset = dataset.drop(['id','date'], axis = 1)\n\nwith sns.plotting_context(\"notebook\",font_scale=2.5):\n g = sns.pairplot(dataset[['sqft_lot','sqft_above','price','sqft_living','bedrooms']], \n hue='bedrooms', palette='tab20',size=6)\ng.set(xticklabels=[]);\n\nX = dataset.iloc[:,1:].values\ny = dataset.iloc[:,0].values\n\nprint(X)\nprint(y)\n#splitting dataset into training and testing dataset\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)\n \n# from sklearn.cross_validation import train_test_split\n#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0\n\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = regressor.predict(X_test)\nnp.set_printoptions(precision=2)\nprint(\"Predicted results\")\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)), 1))",
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\nPython version: 3.6.9 (default, Oct 8 2020, 12:12:24) \n[GCC 8.4.0]\nNumPy version: 1.19.5\npandas version: 1.1.5\nmatplotlib version: 3.2.2\nid int64\ndate object\nprice float64\nbedrooms int64\nbathrooms float64\nsqft_living int64\nsqft_lot int64\nfloors float64\nwaterfront int64\nview int64\ncondition int64\ngrade int64\nsqft_above int64\nsqft_basement int64\nyr_built int64\nyr_renovated int64\nzipcode int64\nlat float64\nlong float64\nsqft_living15 int64\nsqft_lot15 int64\ndtype: object\n[[ 3.00e+00 1.00e+00 1.18e+03 ... -1.22e+02 1.34e+03 5.65e+03]\n [ 3.00e+00 2.25e+00 2.57e+03 ... -1.22e+02 1.69e+03 7.64e+03]\n [ 2.00e+00 1.00e+00 7.70e+02 ... -1.22e+02 2.72e+03 8.06e+03]\n ...\n [ 2.00e+00 7.50e-01 1.02e+03 ... -1.22e+02 1.02e+03 2.01e+03]\n [ 3.00e+00 2.50e+00 1.60e+03 ... -1.22e+02 1.41e+03 1.29e+03]\n [ 2.00e+00 7.50e-01 1.02e+03 ... -1.22e+02 1.02e+03 1.36e+03]]\n[221900. 538000. 180000. ... 402101. 400000. 325000.]\nPredicted results\n[[ 640058.18 459000. ]\n [ 476677.53 445000. ]\n [ 707658.74 1057000. ]\n ...\n [ 360521.61 260000. ]\n [1387672.15 1795000. ]\n [ 367938.08 418000. ]]\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
]
] |
4a91301a076254e9516da4fa9861c30d4f25c0fa
| 672,015 |
ipynb
|
Jupyter Notebook
|
IRSA_COLAB.ipynb
|
Lennard94/IRSA
|
67dc6162f993de99289606740ed6b5d7402df0c2
|
[
"MIT"
] | null | null | null |
IRSA_COLAB.ipynb
|
Lennard94/IRSA
|
67dc6162f993de99289606740ed6b5d7402df0c2
|
[
"MIT"
] | null | null | null |
IRSA_COLAB.ipynb
|
Lennard94/IRSA
|
67dc6162f993de99289606740ed6b5d7402df0c2
|
[
"MIT"
] | null | null | null | 473.917489 | 244,828 | 0.829519 |
[
[
[
"<a href=\"https://colab.research.google.com/github/Lennard94/irsa/blob/master/IRSA_COLAB.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"**Install Miniconda, numpy and RDKit**",
"_____no_output_____"
]
],
[
[
"%%capture\n!pip install numpy\n!wget -c https://repo.continuum.io/miniconda/Miniconda3-py37_4.8.3-Linux-x86_64.sh\n!chmod +x Miniconda3-py37_4.8.3-Linux-x86_64.sh\n!time bash ./Miniconda3-py37_4.8.3-Linux-x86_64.sh -b -f -p /usr/local\n!time conda install -q -y -c conda-forge rdkit==2020.09.2 \n!pip install scipy\n!pip install lmfit",
"_____no_output_____"
]
],
[
[
"**Import Statements**",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('/usr/local/lib/python3.7/site-packages/')\nimport numpy as np\nimport matplotlib.pyplot as py\nimport rdkit\nfrom rdkit import *\nfrom rdkit.Chem import *\nfrom rdkit.Chem.rdDistGeom import EmbedMultipleConfs\nfrom rdkit.Chem.rdmolfiles import *\nfrom rdkit.Chem import Draw\nfrom rdkit.Chem.Draw import IPythonConsole\nimport os\nimport scipy\nfrom scipy import signal\nfrom lmfit.models import LorentzianModel, QuadraticModel, LinearModel, PolynomialModel\nimport lmfit\nfrom lmfit import Model",
"_____no_output_____"
]
],
[
[
"# **Algorithm**",
"_____no_output_____"
]
],
[
[
"class Algorithm: \n def __init__(self, theo_peaks, exp_peaks, cutoff = 0.01, u = 1100, h = 1800, sc = 1, algo = 1):\n \"\"\"SPECTRUM INFORMATION\"\"\"\n print(\"Initialization ND\")\n self.cutoff, self.theo_peaks, self.exp_peaks = cutoff, theo_peaks, exp_peaks\n self.algo, self.u, self.h, self.sc = algo, u, h, sc\n print(\"Initialization SUCCESSFUL\")\n\n def Diagonal_IR(self, freq_i, inten_i, exp_freq_j, exp_inten_j, bond_l, bond_h,\n n, m, exp_vcd = 0, inten_vcd = 0, width_j = 0, width_i = 0, eta_exp = 0, eta = 0):\n \"\"\"COMPUTE THE SCORES FOR EACH PEAK COMBINATION DYNAMICALLY\"\"\"\n value = 2\n def sign(a):\n return bool(a > 0) - bool(a < 0)\n if self.algo == 0:\n if inten_vcd == exp_vcd:\n if min(abs(1-exp_freq_j/freq_i), abs(1-freq_i/exp_freq_j)) < self.cutoff and exp_freq_j > self.u and exp_freq_j < self.h:\n x_dummy = min(abs(1-exp_freq_j/freq_i), abs(1-freq_i/exp_freq_j))\n width_dummy = min(abs(1-width_j/width_i), abs(1-width_i/width_j))\n freq_contrib = np.exp(-1/(1-abs(x_dummy/self.cutoff)**2))\n y_dummy = min(abs(1-inten_i/exp_inten_j), abs(1-exp_inten_j/inten_i))\n inten_contrib = np.exp(-1/(1-abs(y_dummy/1)**2))\n sigma_contrib = np.exp(-1/(1-abs(width_dummy/8)**2))\n if min(abs(1-width_i/width_j), abs(1-width_j/width_i)) < 8:\n if abs(1-inten_i/exp_inten_j) < 1 or abs(1-exp_inten_j/inten_i) < 1:\n value = -inten_contrib*freq_contrib*sigma_contrib#*eta_contrib #scoring function 1\n\n if self.algo == 1:\n if inten_vcd == exp_vcd:\n if min(abs(1-exp_freq_j/freq_i), abs(1-freq_i/exp_freq_j)) < self.cutoff and exp_freq_j > self.u and exp_freq_j < self.h:\n inten_contrib = inten_i*exp_inten_j\n if min(abs(1-width_i/width_j), abs(1-width_j/width_i)) < 8:\n #if abs(inten_i-exp_inten_j) < 0.2:\n value = -inten_contrib#*eta_contrib #scoring function 1\n\n return value\n\n def Backtrace_IR(self, p_mat, al_mat, n, m, freq_i, inten_i, exp_freq_j,\n exp_inten_i, sigma, bond_l, bond_h, exp_sigma, vcd, eta, eta_exp): #n theoretical, m experimental\n \"\"\"BACKTRACE THE NEEDLEMAN ALGORITHM\"\"\"\n new_freq, new_freq_VCD, old_freq, new_inten, new_sigma = [], [], [], [], []\n new_eta, non_matched_sigma, new_inten_vcd, non_matched_freq = [], [], [], []\n matched_freq, vcd_ir_array, non_matched_inten, non_matched_inten_vcd = [], [], [], []\n n = n-1\n m = m-1\n current_scaling_factor = 1\n factors = []\n while True :\n if p_mat[n, m] == \"D\":\n new_freq.append(exp_freq_j[m-1])\n old_freq.append(freq_i[n-1])\n new_inten.append(inten_i[n-1])\n new_sigma.append(sigma[n-1])\n new_eta.append(eta[n-1])\n vcd_ir_array.append(vcd[n-1])\n current_scaling_factor = exp_freq_j[m-1]/freq_i[n-1]\n matched_freq.append(n-1)\n factors.append(current_scaling_factor)\n n = n-1\n m = m-1\n elif p_mat[n, m] == \"V\":\n non_matched_inten.append(n-1)\n non_matched_sigma.append(n-1)\n non_matched_inten_vcd.append(n-1)\n non_matched_freq.append(n-1)\n n = n-1\n elif p_mat[n, m] == \"H\":\n m = m-1\n else:\n break\n\n for i in range(len(non_matched_freq)):\n closest_distance = 9999\n matched_to = 0\n sf = 1\n for j in range(len(matched_freq)):\n dis = abs(freq_i[non_matched_freq[i]]-freq_i[matched_freq[j]])\n if(dis < closest_distance):\n closest_distance = dis\n sf = factors[j]\n new_freq.append(freq_i[non_matched_freq[i]]*sf)\n new_sigma.append(sigma[non_matched_sigma[i]])\n new_eta.append(eta[non_matched_sigma[i]])\n vcd_ir_array.append(vcd[non_matched_freq[i]])\n old_freq.append(freq_i[non_matched_freq[i]])\n new_inten.append(inten_i[non_matched_freq[i]])\n new_inten_vcd.append(0)\n return np.asarray(new_freq), np.asarray(new_inten), np.asarray(old_freq), np.asarray(new_sigma), np.asarray(new_eta), np.asarray(vcd_ir_array)\n \n def Pointer(self, di, ho, ve):\n \"\"\"POINTER TO CELL IN THE TABLE\"\"\"\n pointer = min(di, min(ho, ve))\n if di == pointer:\n return \"D\"\n elif ho == pointer:\n return \"H\"\n else:\n return \"V\"\n\n def Needleman_IR(self):\n \"\"\"NEEDLEMAN ALGORITHM FOR IR\"\"\"\n freq = self.theo_peaks[:, 1]*self.sc\n inten = self.theo_peaks[:, 0]\n sigma = self.theo_peaks[:, 2]\n vcd = self.theo_peaks[:, 3]\n try:\n eta = self.theo_peaks[:, 4]\n except:\n eta = np.ones((len(sigma)))\n exp_freq = self.exp_peaks[:, 1]\n exp_inten = self.exp_peaks[:, 0]\n exp_sigma = self.exp_peaks[:, 2]\n exp_inten_vcd = self.exp_peaks[:, 3]\n\n try:\n eta_exp = self.exp_peaks[:, 4]\n except:\n eta_exp = np.ones((len(exp_sigma)))\n\n bond_l = self.u\n bond_h = self.h\n n = len(freq)+1\n m = len(exp_freq)+1\n norm = 1\n al_mat = np.zeros((n, m))\n p_mat = np.zeros((n, m), dtype='U25') #string\n for i in range(1, n):\n al_mat[i, 0] = al_mat[i-1, 0]#+0.01#self.dummy_0 # BOUND SOLUTION, VALUE MIGHT BE CHANGED\n p_mat[i, 0] = 'V'\n for i in range(1, m):\n al_mat[0, i] = al_mat[0, i-1]#+0.01##+self.dummy_1\n p_mat[0, i] = 'H'\n p_mat[0, 0] = \"S\"\n normalize = 0\n for i in range(1, n): #theoretical\n for j in range(1, m): #experimental\n di = self.Diagonal_IR(freq[i-1], inten[i-1], exp_freq[j-1], exp_inten[j-1],\n bond_l, bond_h, n, m, exp_vcd = exp_inten_vcd[j-1],\n inten_vcd = vcd[i-1], width_j = exp_sigma[j-1],\n width_i = sigma[i-1], eta_exp = eta_exp[j-1], eta = eta[i-1])\n di = al_mat[i-1, j-1]+di\n ho = al_mat[i, j-1]#+abs(exp_inten[j-1])#-np.sqrt((exp_inten[j-1]*self.cutoff*2)**2+exp_freq[j-1]**2)\n ve = al_mat[i-1, j]#+abs(inten[i-1])#-np.sqrt((exp_inten[j-1]*self.cutoff*2)**2+exp_freq[j-1]**2)\n al_mat[i, j] = min(di, min(ho, ve))\n p_mat[i, j] = self.Pointer(di, ho, ve)\n freq, inten, old_freq, new_sigma, eta_new, vcd = self.Backtrace_IR(p_mat, al_mat,\n n, m, freq, inten, exp_freq,\n exp_inten, sigma, bond_l, bond_h,\n exp_sigma, vcd=vcd, eta=eta, eta_exp = eta_exp)\n returnvalue = al_mat[n-1, m-1]#/(n+m) ##ORIGINALLY WE DIVIDED BY THE NUMBER OF THEORETICAL PEAKS\n ##HOWEVER, WE FOUND THIS TOO INCONVIENT, SINCE IT MAKES THE DEPENDENCE ON THE\n ##PURE NUMBERS TOO LARGE\n return returnvalue, old_freq, freq, inten, new_sigma, np.asarray(eta_new), np.asarray(vcd)",
"_____no_output_____"
]
],
[
[
"# **Function Declaration**",
"_____no_output_____"
]
],
[
[
"def L_(x, amp, cen, wid):\n t = ((x-cen)/(wid/2))**2\n L = amp/(1+t)\n return L\n\ndef V_(x, amp, cen, wid, eta):\n t = ((x-cen)/(wid/2))**2\n G = 1*np.exp(-np.log(2)*t)\n L = 1/(1+t)\n V = amp*(eta*L+(1-eta)*G)\n return V\n\ndef add_peak(prefix, center, amplitude=0.5, sigma=12,eta=0.5):\n peak = Model(V_, prefix=prefix)\n pars = peak.make_params()\n \n pars[prefix+'cen'].set(center, min=center-2, max=center+2, vary=True)\n pars[prefix+'amp'].set(amplitude, vary=True, min=0.03, max=1.5)\n pars[prefix+'wid'].set(sigma, vary=True, min=1, max=64)\n pars[prefix+'eta'].set(eta, vary=True, min=0, max=1)\n return peak, pars\n\n\ndef Lorentzian_broadening(peaks, w = 6):\n p = np.arange(500, 2000)\n x = (p[:, np.newaxis] - (peaks[:, 0])[np.newaxis, :])/(w/2)\n L = (peaks[:, 1])[np.newaxis, :]/(1+x*x)\n y = np.sum(L, axis=-1)[:, np.newaxis]\n p = p[:, np.newaxis]\n spectrum = np.concatenate([p, y], axis=-1)\n return spectrum\n\ndef Voigt(freq, inten, new_sigma, new_eta, u=1000, h=1500):\n x = np.arange(u, h)\n list_append = []\n for i in range(len(freq)):\n t = ((x-freq[i])/(new_sigma[i]/2))**2\n L = inten[i]/(1+t)\n G = inten[i]*np.exp(-np.log(2)*t)\n list_append.append(L*new_eta[i]+(1-new_eta[i])*G)\n list_append = np.asarray(list_append)\n y = np.sum(list_append,axis=0)\n return x, y\n\n\ndef deconvolute(spectrum, peaks, working_dir = '/content/', save_data = 'ir_exp_peaks.txt', u = 1000, h = 2000):\n params, model, write_state, name_state = None, None, [], []\n model = None\n for i in range(0, len(peaks)):\n peak, pars = add_peak('lz%d_' % (i+1), center = peaks[i, 0], \n amplitude = peaks[i, 1])\n if(i == 0):\n model = peak\n params = model.make_params()\n else:\n model = model + peak\n params.update(pars)\n\n init = model.eval(params, x = spectrum[:, 0])\n result = model.fit(spectrum[:, 1], params, x = spectrum[:, 0])\n comps = result.eval_components()\n \n for name, par in result.params.items():\n write_state.append(par.value)\n\n write_state=np.asarray(write_state)\n write_state=write_state.reshape(-1,4)\n dic = lmfit.fit_report(result.params)\n py.plot(spectrum[:, 0], spectrum[:, 1], label = 'data', color = \"black\")\n py.plot(spectrum[:, 0], result.best_fit, label = 'best fit', color = \"orange\")\n py.xlim(h, u)\n py.ylim(0,1.02)\n py.show()\n f = open(working_dir+save_data, 'w')\n for i in write_state:\n f.write(str(i[0])+\" \"+str(i[1])+\" \"+str(i[2])+\" 0 \" +str(i[3])+\"\\n\")\n f.close()\n",
"_____no_output_____"
]
],
[
[
"# **Global Settings**",
"_____no_output_____"
]
],
[
[
"working_dir = '/content/'\n##settings about the experimental spectrum\nabsorbance_ir = True ##Whether the absorbance of the exp spectrum is recorded\ntransmission_ir = False ##Whether the transmission of the exp spectrum is recorded\nabsorbance_raman = True ##Whether the absorbance of the exp spectrum is recorded\ntransmission_raman = False ##Whether the transmission of the exp spectrum is recorded\nabsorbance_vcd = True ##Whether the absorbance of the exp spectrum is recorded\ntransmission_vcd = False ##Whether the transmission of the exp spectrum is recorded\n\n##Sampling settings\nrmsd_cutoff = 0.5 ## choose either 0.5, 0.3 or 0.1\nmax_attempts = 10000 ## choose a large number\nexp_torsion_preference = False ## set torsion preference to false\nbasic_knowledge = True ## set basic knowledge to True\nir = True ##Whether to compute IR spectra\nraman = False ##Whether to compute Raman\nu = 1000 ##lower limit\nh = 1500 ##higher limit\nvcd = False ##Whether to compute VCD (only possible with g09)\n## Software to be used\norca_backend = True ## orca backend, use for IR and Raman\ng09_backend = False ## gaussian backend, use for VCD\nW = ' 4:00 ' ## Walltime\n## Calculation setup orca/5.0.1\nif(orca_backend):\n n_procs = ' 12 '\n mem = ' 1000 '\n basis_set = ' def2-TZVP def2/J '\n functional = ' RI BP86 D4 ' ## or use 'RIJCOSX B3LYP/G D4 '\n convergence = ' TightSCF TightOpt '\n if(raman):\n freq = \" NumFreq \"\n elif(ir):\n freq = \" freq \"\n else:\n freq = \" \"\nelif(g09_backend):\n## Calculation setup gaussian 09\n n_procs = ' 12 '\n mem = ' 12000 '\n basis_set = ' 6-31**G(d,p) '\n functional = ' B3LYP Dispersion=GD3 '\n convergence = ' TightSCF TightOpt '\n freq = ' freq('\n if(raman):\n freq+='Raman, ' \n if(VCD):\n freq+='VCD, '\n freq+=')'\nscaling_factor = 1.0 # change to 0.98 for B3LYP/G\n",
"_____no_output_____"
]
],
[
[
"# **WorkFlow, Step 1: Load experimental files**",
"_____no_output_____"
],
[
"**Load experimental files**",
"_____no_output_____"
]
],
[
[
"from google.colab import files\nuploaded = files.upload()\nprint(uploaded)\nfor fn in uploaded.keys():\n print('User uploaded file \"{name}\" with length {length} bytes'.format(\n name=fn, length=len(uploaded[fn])))\nif(raman):\n uploaded = files.upload()\n print(uploaded)\n for fn in uploaded.keys():\n print('User uploaded file \"{name}\" with length {length} bytes'.format(\n name=fn, length=len(uploaded[fn])))\nif(vcd):\n uploaded = files.upload()\n print(uploaded)\n for fn in uploaded.keys():\n print('User uploaded file \"{name}\" with length {length} bytes'.format(\n name=fn, length=len(uploaded[fn])))",
"_____no_output_____"
]
],
[
[
"**Set path to experimenal Spectra**",
"_____no_output_____"
]
],
[
[
"path_to_exp_IR = '/content/IR_30.txt' ##We expect that the file has two columns:\n ## First column: x-coordinates\n ## Second column: y-coordinates\npath_to_exp_raman = '/content/raman.txt'\npath_to_exp_vcd = '/content/vcd.txt'\nir_exp = np.loadtxt(path_to_exp_IR, usecols=(0, 1))\nif(not absorbance_ir):\n ir_exp[:, 1] = 2-np.log10(ir_exp[:, 1])\nidx_ir_exp = (ir_exp[:, 0]>u) & (ir_exp[:, 0]<h)\nir_exp = ir_exp[idx_ir_exp]\nir_exp[:, 1] = ir_exp[:, 1]/np.max(ir_exp[:, 1])\npy.plot(ir_exp[:, 0], ir_exp[:, 1], label='exp spectrum')\nind, _ = scipy.signal.find_peaks(ir_exp[:, 1])\nir_exp_peaks = ir_exp[ind]\npy.plot(ir_exp_peaks[:, 0], ir_exp_peaks[:, 1], 'o' ,label='Peaks')\npy.legend()\npy.xlim(h, u)\npy.ylim(0, 1.01)\npy.show()\nif(raman):\n raman_exp = np.loadtxt(path_to_exp_raman, usecols=(0, 1))\n if(not absorbance_raman):\n raman_exp[:, 1] = 2-np.log10(raman_exp[:, 1])\n idx_raman_exp = (raman_exp[:, 0] > u) & (raman_exp[:, 0] < h)\n py.plot(raman_exp[:, 0], raman_exp[:, 1]/np.max(raman_exp[idx_raman_exp, 1]))\n py.xlim(h, u)\n py.ylim(0, 1.01)\n py.show()\nif(vcd):\n vcd_exp = np.loadtxt(path_to_exp_vcd, usecols=(0, 1))\n if(not absorbance_vcd):\n vcd_exp[:, 1] = 2-np.log10(vcd_exp[:, 1])\n idx_vcd_exp = (vcd_exp[:, 0] > u) & (vcd_exp[:, 0] < h)\n py.plot(vcd_exp[:, 0], vcd_exp[:, 1]/np.max(np.abs(vcd_exp[idx_vcd_exp, 1])))\n py.xlim(h, u)\n py.ylim(-1.01, 1.01)\n py.show()",
"_____no_output_____"
]
],
[
[
"**Deconvolute Experimental Spectra**",
"_____no_output_____"
]
],
[
[
"deconvolute(ir_exp, ir_exp_peaks, working_dir=working_dir, save_data = 'ir_exp_peaks.txt', u = u, h = h)",
"_____no_output_____"
]
],
[
[
"# **WorkFlow, Step 2: Set Up Calculation Files**",
"_____no_output_____"
],
[
"**Set SMILE String**",
"_____no_output_____"
]
],
[
[
"#smile_string = 'C[C@H]([C@H]([C@H]([C@H](CO)Cl)O)Cl)Cl' ## Smile string of compound\nsmile_string = 'CC(C)(C)C(=O)[C@H](C)C[C@H](C)/C=C(\\C)/[C@H](OC)[C@H](C)[C@H]1OC(=O)c2c([C@@H]1O)nccc2O'\nmol = rdkit.Chem.MolFromSmiles(smile_string) ## Draw compound\nmol",
"_____no_output_____"
]
],
[
[
"**Create Conformational Ensemble, Write to xyz files**\n\n",
"_____no_output_____"
]
],
[
[
"solute_mol = AddHs(mol)\nEmbedMultipleConfs(solute_mol, numConfs = max_attempts, clearConfs = True, \n pruneRmsThresh = rmsd_cutoff, numThreads = 8, \n useExpTorsionAnglePrefs = exp_torsion_preference,\n useBasicKnowledge = basic_knowledge)\n## Create calculation file\npath = '/content/calculation_files/'\ntry:\n os.mkdir('/content/calculation_files')\nexcept:\n print('folder already exists')\n pass\ncounter = 0\n\nfor i in range(max_attempts):\n try:\n rdkit.Chem.rdmolfiles.MolToXYZFile(solute_mol, \n path+str(counter)+\".xyz\", confId = i)\n counter+=1\n except:\n pass\nprint(\"Number of conformations found\", str(counter))\nf = open(path+'out', 'w')\nf.write(str(counter))\nf.close()\n",
"Number of conformations found 10000\n"
]
],
[
[
"**Write Calculation files**",
"_____no_output_____"
]
],
[
[
"if(orca_backend):\n f_submit = open(path+'job.sh', 'w')\n for i in range(counter):\n f = open(path+str(i)+\".inp\",\"w+\")\n f.write(\"\"\"! \"\"\" + functional + basis_set + convergence + freq + \"\"\"\n%maxcore \"\"\"+ mem + \"\"\"\n%pal nprocs \"\"\" + n_procs + \"\"\"\nend\n* xyzfile 0 1 \"\"\" +str(i)+\"\"\".xyz \\n\"\"\")\n f.close()\n f_sh = open(path+str(i)+\".sh\", 'w')\n f_sh.write(\"\"\"a=$PWD\ncd $TMPDIR\ncp ${a}/\"\"\"+str(i)+\"\"\".inp .\ncp ${a}/\"\"\"+str(i)+\"\"\".xyz .\nmodule load orca openmpi/4.0.2\nsleep 20\n/cluster/apps/nss/orca/5.0.1/x86_64/bin/orca \"\"\"+str(i)+\"\"\".inp > \"\"\"+str(i)+\"\"\".out\ncp \"\"\"+str(i)+\"\"\".out ${a}\ncp \"\"\"+str(i)+\"\"\".engrad ${a}\ncp \"\"\"+str(i)+\"\"\".hess ${a}\ncp \"\"\"+str(i)+\"\"\".xyz ${a}\ncd ${a}\"\"\")\n f_sh.close()\n f_submit.write('chmod +wrx '+str(i)+'.sh\\n')\n f_submit.write('bsub -n ' +n_procs + '-W '+W+' ./'+str(i)+'.sh\\n')\n f_submit.close()\n\n#elif(g09_backend):\n# continue",
"_____no_output_____"
]
],
[
[
"**ZIP Files**",
"_____no_output_____"
]
],
[
[
"%%capture\nimport zipfile\nfrom google.colab import drive\nfrom google.colab import files\n!zip -rm /content/input.zip /content/calculation_files",
"_____no_output_____"
]
],
[
[
"**Download**",
"_____no_output_____"
]
],
[
[
"files.download(\"/content/input.zip\")",
"_____no_output_____"
]
],
[
[
"Next, you need to perform the calculations. The job.sh script automatically submits the jobs to the local cluster (i.e., bash job.sh), however, depending on your cluster architecture, you might need to update this file. You can then zip the calculation, i.e., zip -rm output.zip calculation_files, and upload it to the collab, and continue with the workflow",
"_____no_output_____"
],
[
"# **Workflow, Step 3: Align the Spectra**",
"_____no_output_____"
],
[
"**Upload finished computation**",
"_____no_output_____"
]
],
[
[
"uploaded = files.upload()\nprint(uploaded)\nfor fn in uploaded.keys():\n print('User uploaded file \"{name}\" with length {length} bytes'.format(\n name=fn, length=len(uploaded[fn])))",
"_____no_output_____"
]
],
[
[
"**Unzip file**",
"_____no_output_____"
]
],
[
[
"%%capture\n!unzip /content/30_calc_out_250.zip",
"_____no_output_____"
]
],
[
[
"**Set Path to Calculation Setup**",
"_____no_output_____"
]
],
[
[
"path_output = '/content/30_calc_out_250/'",
"_____no_output_____"
]
],
[
[
"**Read in free energies, IR spectra, and potentially other spectra**",
"_____no_output_____"
]
],
[
[
"free_energies, energies, ir_spectra, structure_files = [], [], [], []\n\nif(orca_backend):\n files = os.listdir(path_output) \n for fi in files:\n if(fi.endswith('.out')):\n name = fi.split('.')[0]\n freq = np.zeros((400, 2))\n f = open(path_output+name+\".out\", 'r')\n imaginary = False\n free_energies_tmp = 0\n energies_tmp = 0\n for line in f:\n if('Final Gibbs free energy' in line):\n free_energies_tmp = float(line.split()[-2])\n elif('FINAL SINGLE POINT ENERGY' in line):\n energies_tmp = float(line.split()[-1])\n elif('IR SPECTRUM' in line):\n f.readline()\n f.readline()\n f.readline()\n f.readline()\n f.readline()\n counter_tmp = 0\n while(True):\n try:\n tmp = f.readline().split()\n freq[counter_tmp, 0] = float(tmp[1])\n freq[counter_tmp, 1] = float(tmp[3])\n if(float(tmp[1]) < 0):\n imaginary = True\n except:\n break\n counter_tmp+=1\n if(imaginary==False and free_energies_tmp!=0 and energies_tmp!=0):\n structure_files.append(int(name))\n ir_spectra.append(freq)\n energies.append(energies_tmp)\n free_energies.append(free_energies_tmp)\n\nfree_energies = np.asarray(free_energies)\nenergies = np.asarray(energies)\nir_spectra = np.asarray(ir_spectra)\nstructure_files = np.asarray(structure_files)\nprint(len(energies))\nprint(len(free_energies))\nprint(len(structure_files))",
"238\n238\n238\n"
]
],
[
[
"**Filter structures which are equivalent**",
"_____no_output_____"
]
],
[
[
"threshold = 1e5 ## corresponds to 0.026 kJmol\nhartree_to_kJmol = 2625.4996394799\n_, index = np.unique(np.asarray(energies*threshold, dtype=int), return_index=True)\nfree_energies = free_energies[index]*hartree_to_kJmol\nenergies = energies[index]*hartree_to_kJmol\nir_spectra = ir_spectra[index]\nstructure_files = structure_files[index]\nfree_energies-=np.min(free_energies)\nenergies-=np.min(energies)\npy.plot(structure_files, free_energies)\npy.show()",
"_____no_output_____"
]
],
[
[
"**Generate Superimposed IR spectrum**",
"_____no_output_____"
]
],
[
[
"lorentzian_bandwidth = np.arange(6, 7, 1)\nZ = 1\nprint(scaling_factor)\nRT = 0.008314*298.15 # in kJmol\nir_theo_data = ir_spectra[0]\nif(len(free_energies) > 0):\n Z = np.sum(np.exp(-free_energies/RT))\n ir_theo_y = (ir_spectra[:, :, 1]*np.exp(-free_energies[:, np.newaxis]/RT)/Z).flatten()\n ir_theo_x = ir_spectra[:, :, 0].flatten()\n ir_theo_data = np.concatenate([ir_theo_x[:, np.newaxis], ir_theo_y[:, np.newaxis]], axis=-1)\nfor w in lorentzian_bandwidth:\n ir_theo = Lorentzian_broadening(ir_theo_data, w = w)\n idx_ir_theo = (ir_theo[:, 0] > u) & (ir_theo[:, 0] < h)\n ir_theo = ir_theo[idx_ir_theo]\n ir_theo[:, 1] /= np.max(ir_theo[:, 1])\n ind, _ = scipy.signal.find_peaks(ir_theo[:, 1])\n py.plot(ir_theo[:, 0]*scaling_factor, ir_theo[:, 1], label = \"theo\", color = 'orange')\n py.plot(ir_exp[:, 0], ir_exp[:, 1], label = \"exp\", color = 'black')\n py.legend()\n py.xlim(h, u)\n py.show()\n deconvolute(ir_theo, ir_theo[ind], working_dir = '/content/', save_data = str(w)+'_ir_theo_peaks.txt', u = u, h = h)",
"1.0\n"
]
],
[
[
"**Print out Parameters**",
"_____no_output_____"
]
],
[
[
"#for w in lorentzian_bandwidth:\n# print(np.loadtxt(working_dir+str(w)+\"_ir_theo_peaks.txt\"))",
"_____no_output_____"
],
[
"scaling_factor = np.arange(1.000, 1.02, 0.005)\nfor sc in scaling_factor:\n algorithm = Algorithm(theo_peaks = np.loadtxt(working_dir+str(w)+\"_ir_theo_peaks.txt\"), \n exp_peaks = np.loadtxt(working_dir+\"ir_exp_peaks.txt\"),\n cutoff = 0.04, u = u, h = h, sc = sc)\n s, _, freq_aligned, inten_aligned, sigma, eta, vcd_ir_array = algorithm.Needleman_IR()\n vcd_ir_array = np.asarray(vcd_ir_array, dtype=int)\n\n x, y = Voigt(freq_aligned[vcd_ir_array == 0], inten_aligned[vcd_ir_array == 0], \n sigma[vcd_ir_array == 0], \n eta[vcd_ir_array == 0], u = u, h = h)\n y /= np.max(y) \n py.plot(ir_theo[:, 0], ir_theo[:, 1], label = \"unaligned\", color = 'orange')\n py.plot(x, y, label = \"aligned\", color = 'red')\n py.plot(ir_exp[:, 0], ir_exp[:, 1], label = \"experimental\", color = 'black')\n print(sc, s)\n py.legend()\n py.show()",
"Initialization ND\nInitialization SUCCESSFUL\n1.0 -1.0713489501758149\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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a9130c690e18525b3fdebf02b8b60d49c677612
| 88,238 |
ipynb
|
Jupyter Notebook
|
src/models/1.1-bma-include_sentiment.ipynb
|
brandonmalexander/btc_prediction
|
f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79
|
[
"MIT"
] | null | null | null |
src/models/1.1-bma-include_sentiment.ipynb
|
brandonmalexander/btc_prediction
|
f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79
|
[
"MIT"
] | null | null | null |
src/models/1.1-bma-include_sentiment.ipynb
|
brandonmalexander/btc_prediction
|
f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79
|
[
"MIT"
] | null | null | null | 113.125641 | 25,068 | 0.847571 |
[
[
[
"%matplotlib inline\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"### Reading in & Formatting Price Data\nThe .csv read from contains the price of [bitcoin](https://bitcoin.org/en/) from 2015-02-01 to 2018-04-21.",
"_____no_output_____"
]
],
[
[
"prices_raw = pd.read_csv('data/price_data_final.csv', infer_datetime_format=True)\np = prices_raw['price']\nprint(p.head(2))\nprint(p.tail(2))",
"0 226.3959\n1 237.5409\nName: price, dtype: float64\n1174 8863.5025\n1175 8917.5963\nName: price, dtype: float64\n"
]
],
[
[
"### Reading in & Formatting Quantified Sentiment\nThe .csv we read from here contains daily sentiment scores from 2015-02-01 to 2018-04-21 for the title of every post in the [Bitcoin subreddit](https://www.reddit.com/r/Bitcoin/), an online Bitcoin community.\n\nThere seems to be *a lot* of noise in the form of 0's (neutral sentiment). **How can this effectively be handled?**\n\nFor now, I will take the daily average.",
"_____no_output_____"
]
],
[
[
"sentiment_raw = pd.read_csv('data/reddit_sentiment_data_final.csv', infer_datetime_format=True)\ns = sentiment_raw.mean(axis=1)\nprint(s.head(2))\nprint(s.tail(2))",
"0 0.068356\n1 0.068356\ndtype: float64\n1174 0.0\n1175 0.0\ndtype: float64\n"
],
[
"count = 0\nfor i in sentiment_raw.drop('Unnamed: 0', axis=1).values:\n for v in i:\n if v == 0:\n count += 1\nprint(count)",
"19572\n"
]
],
[
[
"### Final Data Formatting",
"_____no_output_____"
]
],
[
[
"# create the \"today's price\" feature\nprices = prices_raw.set_index('Unnamed: 0')\nprices = prices.reset_index(drop=True)\nprint(prices.head(3))\nprint(prices.tail(3))",
" price\n0 226.3959\n1 237.5409\n2 226.9566\n price\n1173 8273.7413\n1174 8863.5025\n1175 8917.5963\n"
],
[
"# create \"today's price - yesterday's price\" feature\ndiff = []\nfor n in range(0,len(prices)):\n diff.append(prices.iloc[n] - prices.iloc[n-1])\ndiff = pd.DataFrame(diff)\nprint(diff.head(3))\nprint(diff.tail(3))",
" price\n0 -8691.2004\n1 11.1450\n2 -10.5843\n price\n1173 110.0513\n1174 589.7612\n1175 54.0938\n"
],
[
"# create \"tomorrow's price\" label (for regression)\nlabel = pd.DataFrame(prices.drop(0)).reset_index(drop=True)\nprint(label.head(3))\nprint(label.tail(3))",
" price\n0 237.5409\n1 226.9566\n2 226.7291\n price\n1172 8273.7413\n1173 8863.5025\n1174 8917.5963\n"
],
[
"# create binary \"today minus yesterday up or down\" feature\nupOrDown = pd.DataFrame([1 if d > 0 else 0 for d in diff.values])\nprint(upOrDown.head(3))\nprint(upOrDown.tail(3))",
" 0\n0 0\n1 1\n2 0\n 0\n1173 1\n1174 1\n1175 1\n"
],
[
"# create \"tomorrow minus today up or down\" label for classification\nupdownLabel = upOrDown.drop(0).reset_index(drop=True)\nprint(updownLabel.head(3))\nprint(updownLabel.tail(3))",
" 0\n0 1\n1 0\n2 0\n 0\n1172 1\n1173 1\n1174 1\n"
],
[
"# create + or - sentiment feature\nposnegSent = pd.DataFrame([1 if d > 0 else 0 for d in s.values])\nprint(posnegSent.head(3))\nprint(posnegSent.tail(3))",
" 0\n0 1\n1 1\n2 1\n 0\n1173 1\n1174 0\n1175 0\n"
],
[
"# resizing\nprices = prices.drop(1175)\ndiff = diff.drop(1175)\nupOrDown = upOrDown.drop(1175)\ns = s.drop(1175)\nposnegSent = posnegSent.drop(1175)",
"_____no_output_____"
],
[
"# Bringing it all together\ndatas = pd.concat([prices, diff, s, posnegSent, label, upOrDown, updownLabel], axis=1)\ndatas.columns = ['price(t)', 'p(t) - p(t-1)','s(t)', 'sentPosNeg', 'p(t+1)',\n 'p(t) - p(t-1) > 0', 'p(t+1) - p(t) > 0']\ndatas = datas.drop(0)\ndatas.head(10)",
"_____no_output_____"
]
],
[
[
"### ...Let's try KNN\n#### This first section uses KNeighborsRegressor to predict price. ",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsRegressor",
"_____no_output_____"
],
[
"knnReg = KNeighborsRegressor(n_neighbors=2)\nX = datas[['price(t)', 's(t)']]\nY = datas['p(t+1)']\nknnReg.fit(X, Y)",
"_____no_output_____"
],
[
"x = list(range(1, 1175))\ny = []\nfor n in x:\n y.append(knnReg.predict(X[n-1:n]))",
"_____no_output_____"
],
[
"plt.plot(x,y)\nplt.xlabel('Days After 2-2-2015')\nplt.ylabel('Predicted Price (USD)')\nplt.title('KNN Regressor Predicting BTC Price')",
"_____no_output_____"
]
],
[
[
"so thats knnRegressor... not tweaked, but it followed the path so we know the model does its purpose. \n\nknnClassifier comin' up next.",
"_____no_output_____"
]
],
[
[
"plt.plot(x,p.drop(0).drop(1174), color='orange')\nplt.xlabel('Days After 2-2-2015')\nplt.ylabel('Acual Price (USD)')\nplt.title('Price of BTC, Feb 2015 - April 2018')",
"_____no_output_____"
],
[
"# Some evaluation?\nfrom sklearn.model_selection import cross_val_score",
"_____no_output_____"
],
[
"np.mean(cross_val_score(knnReg, X[1000:1175], Y[1000:1175]))\n# restricting the training to recent data ^^^",
"_____no_output_____"
]
],
[
[
"#### This second section uses KNeighborsClassifier to predict whether the price will go up or down.",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsClassifier",
"_____no_output_____"
],
[
"X = datas[['sentPosNeg', 'p(t) - p(t-1) > 0']]\nY = datas[['p(t+1) - p(t) > 0']]\nknnClass = KNeighborsClassifier(n_neighbors=3)\nknnClass.fit(X[1000:1175],Y[1000:1175])",
"/home/brandon/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:4: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n after removing the cwd from sys.path.\n"
],
[
"np.mean(cross_val_score(knnClass, X[1000:1175], Y[1000:1175]))",
"/home/brandon/anaconda3/lib/python3.6/site-packages/sklearn/model_selection/_validation.py:458: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n estimator.fit(X_train, y_train, **fit_params)\n/home/brandon/anaconda3/lib/python3.6/site-packages/sklearn/model_selection/_validation.py:458: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n estimator.fit(X_train, y_train, **fit_params)\n/home/brandon/anaconda3/lib/python3.6/site-packages/sklearn/model_selection/_validation.py:458: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n estimator.fit(X_train, y_train, **fit_params)\n"
],
[
"plt.plot(x,y,x,p.drop(0).drop(1174))\nplt.xlabel('Days After 2-2-2015')\nplt.ylabel('Price (USD)')\nplt.title('KNN Regressor Predicting BTC Price')\nplt.legend(('Predicted', 'Actual'))",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a9132561fea5b28a2b610ab819cf4a4e14662b7
| 3,022 |
ipynb
|
Jupyter Notebook
|
standford-cs231n/assignment1/Numpy Practice.ipynb
|
ArchibaldChain/python-workspace
|
71890f296c376155e374b2096ac3d8f1d286b7d2
|
[
"MIT"
] | null | null | null |
standford-cs231n/assignment1/Numpy Practice.ipynb
|
ArchibaldChain/python-workspace
|
71890f296c376155e374b2096ac3d8f1d286b7d2
|
[
"MIT"
] | 3 |
2020-06-17T16:01:27.000Z
|
2022-01-13T02:52:53.000Z
|
standford-cs231n/assignment1/Numpy Practice.ipynb
|
ArchibaldChain/python-workspace
|
71890f296c376155e374b2096ac3d8f1d286b7d2
|
[
"MIT"
] | null | null | null | 20.841379 | 76 | 0.429186 |
[
[
[
" import numpy as np",
"_____no_output_____"
],
[
"a = np.array([[1,2], [3, 4], [5, 6]])\n\nbool_idx = (a > 2) \nprint(bool_idx)",
"_____no_output_____"
],
[
"x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = np.empty_like(x)",
"_____no_output_____"
],
[
"print(y)",
"_____no_output_____"
],
[
"print(x+v)",
"[[ 2 2 4]\n [ 5 5 7]\n [ 8 8 10]\n [11 11 13]]\n"
],
[
"for i in range(4):\n y[i, :] = x[i, :] + v\n\n# Now y is the following\n# [[ 2 2 4]\n# [ 5 5 7]\n# [ 8 8 10]\n# [11 11 13]]\nprint(y)",
"_____no_output_____"
],
[
"import numpy as np\nfrom scipy.spatial.distance import pdist, squareform\n\n# Create the following array where each row is a point in 2D space:\n# [[0 1]\n# [1 0]\n# [2 0]]\nx = np.array([[0, 1], [1, 0], [2, 0]])\nprint(x)\n\n# Compute the Euclidean distance between all rows of x.\n# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],\n# and d is the following array:\n# [[ 0. 1.41421356 2.23606798]\n# [ 1.41421356 0. 1. ]\n# [ 2.23606798 1. 0. ]]\nd = squareform(pdist(x, 'euclidean'))\nprint(pdist(x,'euclidean'))\nprint(d)",
"[[0 1]\n [1 0]\n [2 0]]\n[1.41421356 2.23606798 1. ]\n[[0. 1.41421356 2.23606798]\n [1.41421356 0. 1. ]\n [2.23606798 1. 0. ]]\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a913a4f9a64583550b99d6f66fe5d9f450a8988
| 443,847 |
ipynb
|
Jupyter Notebook
|
scripts/ecg_demo.ipynb
|
vansjyo/NeuroKit
|
238cd3d89467f7922c68a3a4c1f44806a8466922
|
[
"MIT"
] | 1 |
2020-05-26T09:46:57.000Z
|
2020-05-26T09:46:57.000Z
|
scripts/ecg_demo.ipynb
|
vansjyo/NeuroKit
|
238cd3d89467f7922c68a3a4c1f44806a8466922
|
[
"MIT"
] | null | null | null |
scripts/ecg_demo.ipynb
|
vansjyo/NeuroKit
|
238cd3d89467f7922c68a3a4c1f44806a8466922
|
[
"MIT"
] | 1 |
2020-10-27T06:47:51.000Z
|
2020-10-27T06:47:51.000Z
| 263.0984 | 190,821 | 0.88617 |
[
[
[
"import neurokit2 as nk\nimport matplotlib.pyplot as plt\n\n%matplotlib notebook\n\n\necg = nk.ecg_simulate(duration=60, noise=0.05)\n\nsignals, info = nk.ecg_process(ecg)\n\nprint(signals.head)\nprint(info.keys(), info.values())",
"<bound method NDFrame.head of ECG_Raw ECG_Clean ECG_Peaks ECG_Rate\n0 0.426662 0.069743 0.0 71.081625\n1 0.423365 0.067463 0.0 71.079985\n2 0.415258 0.060371 0.0 71.078346\n3 0.402641 0.048770 0.0 71.076709\n4 0.385874 0.033019 0.0 71.075074\n... ... ... ... ...\n59995 -0.393764 0.009023 0.0 70.112868\n59996 -0.392628 0.012827 0.0 70.108022\n59997 -0.390360 0.017778 0.0 70.103172\n59998 -0.386951 0.023884 0.0 70.098317\n59999 -0.382398 0.031149 0.0 70.093458\n\n[60000 rows x 4 columns]>\ndict_keys(['ECG_Peaks']) dict_values([array([ 864, 1717, 2568, 3432, 4287, 5122, 5953, 6798, 7661,\n 8538, 9408, 10273, 11146, 12011, 12865, 13706, 14541, 15388,\n 16238, 17103, 17964, 18830, 19693, 20566, 21423, 22270, 23119,\n 23971, 24823, 25679, 26542, 27405, 28266, 29123, 29983, 30840,\n 31689, 32539, 33397, 34260, 35117, 35970, 36829, 37692, 38551,\n 39399, 40253, 41117, 41980, 42834, 43684, 44543, 45414, 46270,\n 47111, 47961, 48831, 49696, 50541, 51417, 52241, 53122, 53982,\n 54821, 55675, 56553, 57430, 58268, 59095, 59951])])\n"
]
],
[
[
"Plot data over seconds",
"_____no_output_____"
]
],
[
[
"fig1 = nk.ecg_plot(signals, sampling_rate=1000)",
"_____no_output_____"
]
],
[
[
"Plot data over samples",
"_____no_output_____"
]
],
[
[
"fig2 = nk.ecg_plot(signals)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a913fad90a21ada2a47b415f117dd538d52adca
| 36,497 |
ipynb
|
Jupyter Notebook
|
project3/.Trash-0/files/project_3_solution 8.ipynb
|
JingZhang918/AI-for-trading
|
85ab93928b9b0cfba4b97b432d492e100362b538
|
[
"MIT"
] | 12 |
2019-12-26T22:31:40.000Z
|
2021-07-07T10:20:25.000Z
|
project3/.Trash-0/files/project_3_solution 8.ipynb
|
JingZhang918/AI-for-trading
|
85ab93928b9b0cfba4b97b432d492e100362b538
|
[
"MIT"
] | 7 |
2019-12-20T12:40:10.000Z
|
2019-12-20T12:43:03.000Z
|
project3/.Trash-0/files/project_3_solution 8.ipynb
|
JingZhang918/AI-for-trading
|
85ab93928b9b0cfba4b97b432d492e100362b538
|
[
"MIT"
] | 5 |
2020-05-29T04:32:57.000Z
|
2021-11-30T16:40:22.000Z
| 40.283664 | 818 | 0.614215 |
[
[
[
"# Project 3: Smart Beta Portfolio and Portfolio Optimization\n\n## Overview\n\n\nSmart beta has a broad meaning, but we can say in practice that when we use the universe of stocks from an index, and then apply some weighting scheme other than market cap weighting, it can be considered a type of smart beta fund. By contrast, a purely alpha fund may create a portfolio of specific stocks, not related to an index, or may choose from the global universe of stocks. The other characteristic that makes a smart beta portfolio \"beta\" is that it gives its investors a diversified broad exposure to a particular market.\n\nImagine you're a portfolio manager, and wish to try out some different portfolio weighting methods.\n\nOne way to design portfolio is to look at certain accounting measures (fundamentals) that, based on past trends, indicate stocks that produce better results. \n\n\nFor instance, you may start with a hypothesis that dividend-issuing stocks tend to perform better than stocks that do not. This may not always be true of all companies; for instance, Apple does not issue dividends, but has had good historical performance. The hypothesis about dividend-paying stocks may go something like this: \n\nCompanies that regularly issue dividends may also be more prudent in allocating their available cash, and may indicate that they are more conscious of prioritizing shareholder interests. For example, a CEO may decide to reinvest cash into pet projects that produce low returns. Or, the CEO may do some analysis, identify that reinvesting within the company produces lower returns compared to a diversified portfolio, and so decide that shareholders would be better served if they were given the cash (in the form of dividends). So according to this hypothesis, dividends may be both a proxy for how the company is doing (in terms of earnings and cash flow), but also a signal that the company acts in the best interest of its shareholders. Of course, it's important to test whether this works in practice.\n\n\nYou may also have another hypothesis, with which you wish to design a portfolio that can then be made into an ETF. You may find that investors may wish to invest in passive beta funds, but wish to have less risk exposure (less volatility) in their investments. The goal of having a low volatility fund that still produces returns similar to an index may be appealing to investors who have a shorter investment time horizon, and so are more risk averse.\n\nSo the objective of your proposed portfolio is to design a portfolio that closely tracks an index, while also minimizing the portfolio variance. Also, if this portfolio can match the returns of the index with less volatility, then it has a higher risk-adjusted return (same return, lower volatility).\n\nSmart Beta ETFs can be designed with both of these two general methods (among others): alternative weighting and minimum volatility ETF.\n\n\n## Instructions\nEach problem consists of a function to implement and instructions on how to implement the function. The parts of the function that need to be implemented are marked with a `# TODO` comment. After implementing the function, run the cell to test it against the unit tests we've provided. For each problem, we provide one or more unit tests from our `project_tests` package. These unit tests won't tell you if your answer is correct, but will warn you of any major errors. Your code will be checked for the correct solution when you submit it to Udacity.\n\n## Packages\nWhen you implement the functions, you'll only need to you use the packages you've used in the classroom, like [Pandas](https://pandas.pydata.org/) and [Numpy](http://www.numpy.org/). These packages will be imported for you. We recommend you don't add any import statements, otherwise the grader might not be able to run your code.\n\nThe other packages that we're importing are `helper`, `project_helper`, and `project_tests`. These are custom packages built to help you solve the problems. The `helper` and `project_helper` module contains utility functions and graph functions. The `project_tests` contains the unit tests for all the problems.\n### Install Packages",
"_____no_output_____"
]
],
[
[
"import sys\n!{sys.executable} -m pip install -r requirements.txt",
"_____no_output_____"
]
],
[
[
"### Load Packages",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport helper\nimport project_helper\nimport project_tests",
"_____no_output_____"
]
],
[
[
"## Market Data\n### Load Data\nFor this universe of stocks, we'll be selecting large dollar volume stocks. We're using this universe, since it is highly liquid.",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('data/eod-quotemedia.csv')\n\npercent_top_dollar = 0.2\nhigh_volume_symbols = project_helper.large_dollar_volume_stocks(df, 'adj_close', 'adj_volume', percent_top_dollar)\ndf = df[df['ticker'].isin(high_volume_symbols)]\n\nclose = df.reset_index().pivot(index='date', columns='ticker', values='adj_close')\nvolume = df.reset_index().pivot(index='date', columns='ticker', values='adj_volume')\ndividends = df.reset_index().pivot(index='date', columns='ticker', values='dividends')",
"_____no_output_____"
]
],
[
[
"### View Data\nTo see what one of these 2-d matrices looks like, let's take a look at the closing prices matrix.",
"_____no_output_____"
]
],
[
[
"project_helper.print_dataframe(close)",
"_____no_output_____"
]
],
[
[
"# Part 1: Smart Beta Portfolio\nIn Part 1 of this project, you'll build a portfolio using dividend yield to choose the portfolio weights. A portfolio such as this could be incorporated into a smart beta ETF. You'll compare this portfolio to a market cap weighted index to see how well it performs. \n\nNote that in practice, you'll probably get the index weights from a data vendor (such as companies that create indices, like MSCI, FTSE, Standard and Poor's), but for this exercise we will simulate a market cap weighted index.\n\n## Index Weights\nThe index we'll be using is based on large dollar volume stocks. Implement `generate_dollar_volume_weights` to generate the weights for this index. For each date, generate the weights based on dollar volume traded for that date. For example, assume the following is close prices and volume data:\n```\n Prices\n A B ...\n2013-07-08 2 2 ...\n2013-07-09 5 6 ...\n2013-07-10 1 2 ...\n2013-07-11 6 5 ...\n... ... ... ...\n\n Volume\n A B ...\n2013-07-08 100 340 ...\n2013-07-09 240 220 ...\n2013-07-10 120 500 ...\n2013-07-11 10 100 ...\n... ... ... ...\n```\nThe weights created from the function `generate_dollar_volume_weights` should be the following:\n```\n A B ...\n2013-07-08 0.126.. 0.194.. ...\n2013-07-09 0.759.. 0.377.. ...\n2013-07-10 0.075.. 0.285.. ...\n2013-07-11 0.037.. 0.142.. ...\n... ... ... ...\n```",
"_____no_output_____"
]
],
[
[
"def generate_dollar_volume_weights(close, volume):\n \"\"\"\n Generate dollar volume weights.\n\n Parameters\n ----------\n close : DataFrame\n Close price for each ticker and date\n volume : str\n Volume for each ticker and date\n\n Returns\n -------\n dollar_volume_weights : DataFrame\n The dollar volume weights for each ticker and date\n \"\"\"\n assert close.index.equals(volume.index)\n assert close.columns.equals(volume.columns)\n \n #TODO: Implement function\n dollar_volume = close * volume\n\n return (dollar_volume.T / dollar_volume.T.sum()).T\n\nproject_tests.test_generate_dollar_volume_weights(generate_dollar_volume_weights)",
"_____no_output_____"
]
],
[
[
"### View Data\nLet's generate the index weights using `generate_dollar_volume_weights` and view them using a heatmap.",
"_____no_output_____"
]
],
[
[
"index_weights = generate_dollar_volume_weights(close, volume)\nproject_helper.plot_weights(index_weights, 'Index Weights')",
"_____no_output_____"
]
],
[
[
"## Portfolio Weights\nNow that we have the index weights, let's choose the portfolio weights based on dividends.\n\nImplement `calculate_dividend_weights` to returns the weights for each stock based on its total dividend yield over time. This is similar to generating the weight for the index, but it's using dividend data instead.\nFor example, assume the following is `dividends` data:\n```\n Prices\n A B\n2013-07-08 0 0\n2013-07-09 0 1\n2013-07-10 0.5 0\n2013-07-11 0 0\n2013-07-12 2 0\n... ... ...\n```\nThe weights created from the function `calculate_dividend_weights` should be the following:\n```\n A B\n2013-07-08 NaN NaN\n2013-07-09 0 1\n2013-07-10 0.333.. 0.666..\n2013-07-11 0.333.. 0.666..\n2013-07-12 0.714.. 0.285..\n... ... ...\n```",
"_____no_output_____"
]
],
[
[
"def calculate_dividend_weights(dividends):\n \"\"\"\n Calculate dividend weights.\n\n Parameters\n ----------\n ex_dividend : DataFrame\n Ex-dividend for each stock and date\n\n Returns\n -------\n dividend_weights : DataFrame\n Weights for each stock and date\n \"\"\"\n #TODO: Implement function\n dividend_cumsum_per_ticker = dividends.cumsum().T\n\n return (dividend_cumsum_per_ticker/dividend_cumsum_per_ticker.sum()).T\n\nproject_tests.test_calculate_dividend_weights(calculate_dividend_weights)",
"_____no_output_____"
]
],
[
[
"### View Data\nJust like the index weights, let's generate the ETF weights and view them using a heatmap.",
"_____no_output_____"
]
],
[
[
"etf_weights = calculate_dividend_weights(dividends)\nproject_helper.plot_weights(etf_weights, 'ETF Weights')",
"_____no_output_____"
]
],
[
[
"## Returns\nImplement `generate_returns` to generate returns data for all the stocks and dates from price data. You might notice we're implementing returns and not log returns. Since we're not dealing with volatility, we don't have to use log returns.",
"_____no_output_____"
]
],
[
[
"def generate_returns(prices):\n \"\"\"\n Generate returns for ticker and date.\n\n Parameters\n ----------\n prices : DataFrame\n Price for each ticker and date\n\n Returns\n -------\n returns : Dataframe\n The returns for each ticker and date\n \"\"\"\n #TODO: Implement function\n\n return prices / prices.shift(1) - 1\n\nproject_tests.test_generate_returns(generate_returns)",
"_____no_output_____"
]
],
[
[
"### View Data\nLet's generate the closing returns using `generate_returns` and view them using a heatmap.",
"_____no_output_____"
]
],
[
[
"returns = generate_returns(close)\nproject_helper.plot_returns(returns, 'Close Returns')",
"_____no_output_____"
]
],
[
[
"## Weighted Returns\nWith the returns of each stock computed, we can use it to compute the returns for an index or ETF. Implement `generate_weighted_returns` to create weighted returns using the returns and weights.",
"_____no_output_____"
]
],
[
[
"def generate_weighted_returns(returns, weights):\n \"\"\"\n Generate weighted returns.\n\n Parameters\n ----------\n returns : DataFrame\n Returns for each ticker and date\n weights : DataFrame\n Weights for each ticker and date\n\n Returns\n -------\n weighted_returns : DataFrame\n Weighted returns for each ticker and date\n \"\"\"\n assert returns.index.equals(weights.index)\n assert returns.columns.equals(weights.columns)\n \n #TODO: Implement function\n\n return returns * weights\n\nproject_tests.test_generate_weighted_returns(generate_weighted_returns)",
"_____no_output_____"
]
],
[
[
"### View Data\nLet's generate the ETF and index returns using `generate_weighted_returns` and view them using a heatmap.",
"_____no_output_____"
]
],
[
[
"index_weighted_returns = generate_weighted_returns(returns, index_weights)\netf_weighted_returns = generate_weighted_returns(returns, etf_weights)\nproject_helper.plot_returns(index_weighted_returns, 'Index Returns')\nproject_helper.plot_returns(etf_weighted_returns, 'ETF Returns')",
"_____no_output_____"
]
],
[
[
"## Cumulative Returns\nTo compare performance between the ETF and Index, we're going to calculate the tracking error. Before we do that, we first need to calculate the index and ETF comulative returns. Implement `calculate_cumulative_returns` to calculate the cumulative returns over time given the returns.",
"_____no_output_____"
]
],
[
[
"def calculate_cumulative_returns(returns):\n \"\"\"\n Calculate cumulative returns.\n\n Parameters\n ----------\n returns : DataFrame\n Returns for each ticker and date\n\n Returns\n -------\n cumulative_returns : Pandas Series\n Cumulative returns for each date\n \"\"\"\n #TODO: Implement function\n \n return (returns.T.sum() + 1).cumprod()\n\nproject_tests.test_calculate_cumulative_returns(calculate_cumulative_returns)",
"_____no_output_____"
]
],
[
[
"### View Data\nLet's generate the ETF and index cumulative returns using `calculate_cumulative_returns` and compare the two.",
"_____no_output_____"
]
],
[
[
"index_weighted_cumulative_returns = calculate_cumulative_returns(index_weighted_returns)\netf_weighted_cumulative_returns = calculate_cumulative_returns(etf_weighted_returns)\nproject_helper.plot_benchmark_returns(index_weighted_cumulative_returns, etf_weighted_cumulative_returns, 'Smart Beta ETF vs Index')",
"_____no_output_____"
]
],
[
[
"## Tracking Error\nIn order to check the performance of the smart beta portfolio, we can calculate the annualized tracking error against the index. Implement `tracking_error` to return the tracking error between the ETF and benchmark.\n\nFor reference, we'll be using the following annualized tracking error function:\n$$ TE = \\sqrt{252} * SampleStdev(r_p - r_b) $$\n\nWhere $ r_p $ is the portfolio/ETF returns and $ r_b $ is the benchmark returns.",
"_____no_output_____"
]
],
[
[
"def tracking_error(benchmark_returns_by_date, etf_returns_by_date):\n \"\"\"\n Calculate the tracking error.\n\n Parameters\n ----------\n benchmark_returns_by_date : Pandas Series\n The benchmark returns for each date\n etf_returns_by_date : Pandas Series\n The ETF returns for each date\n\n Returns\n -------\n tracking_error : float\n The tracking error\n \"\"\"\n assert benchmark_returns_by_date.index.equals(etf_returns_by_date.index)\n \n #TODO: Implement function\n \n return np.sqrt(252) * (etf_returns_by_date - benchmark_returns_by_date).std()\n\nproject_tests.test_tracking_error(tracking_error)",
"_____no_output_____"
]
],
[
[
"### View Data\nLet's generate the tracking error using `tracking_error`.",
"_____no_output_____"
]
],
[
[
"smart_beta_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(etf_weighted_returns, 1))\nprint('Smart Beta Tracking Error: {}'.format(smart_beta_tracking_error))",
"_____no_output_____"
]
],
[
[
"# Part 2: Portfolio Optimization\n\nNow, let's create a second portfolio. We'll still reuse the market cap weighted index, but this will be independent of the dividend-weighted portfolio that we created in part 1.\n\nWe want to both minimize the portfolio variance and also want to closely track a market cap weighted index. In other words, we're trying to minimize the distance between the weights of our portfolio and the weights of the index.\n\n$Minimize \\left [ \\sigma^2_p + \\lambda \\sqrt{\\sum_{1}^{m}(weight_i - indexWeight_i)^2} \\right ]$ where $m$ is the number of stocks in the portfolio, and $\\lambda$ is a scaling factor that you can choose.\n\nWhy are we doing this? One way that investors evaluate a fund is by how well it tracks its index. The fund is still expected to deviate from the index within a certain range in order to improve fund performance. A way for a fund to track the performance of its benchmark is by keeping its asset weights similar to the weights of the index. We’d expect that if the fund has the same stocks as the benchmark, and also the same weights for each stock as the benchmark, the fund would yield about the same returns as the benchmark. By minimizing a linear combination of both the portfolio risk and distance between portfolio and benchmark weights, we attempt to balance the desire to minimize portfolio variance with the goal of tracking the index.\n\n\n## Covariance\nImplement `get_covariance_returns` to calculate the covariance of the `returns`. We'll use this to calculate the portfolio variance.\n\nIf we have $m$ stock series, the covariance matrix is an $m \\times m$ matrix containing the covariance between each pair of stocks. We can use [numpy.cov](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html) to get the covariance. We give it a 2D array in which each row is a stock series, and each column is an observation at the same period of time.\n\nThe covariance matrix $\\mathbf{P} = \n\\begin{bmatrix}\n\\sigma^2_{1,1} & ... & \\sigma^2_{1,m} \\\\ \n... & ... & ...\\\\\n\\sigma_{m,1} & ... & \\sigma^2_{m,m} \\\\\n\\end{bmatrix}$",
"_____no_output_____"
]
],
[
[
"def get_covariance_returns(returns):\n \"\"\"\n Calculate covariance matrices.\n\n Parameters\n ----------\n returns : DataFrame\n Returns for each ticker and date\n\n Returns\n -------\n returns_covariance : 2 dimensional Ndarray\n The covariance of the returns\n \"\"\"\n #TODO: Implement function\n \n return np.cov(returns.T.fillna(0))\n\nproject_tests.test_get_covariance_returns(get_covariance_returns)",
"_____no_output_____"
]
],
[
[
"### View Data\nLet's look at the covariance generated from `get_covariance_returns`.",
"_____no_output_____"
]
],
[
[
"covariance_returns = get_covariance_returns(returns)\ncovariance_returns = pd.DataFrame(covariance_returns, returns.columns, returns.columns)\n\ncovariance_returns_correlation = np.linalg.inv(np.diag(np.sqrt(np.diag(covariance_returns))))\ncovariance_returns_correlation = pd.DataFrame(\n covariance_returns_correlation.dot(covariance_returns).dot(covariance_returns_correlation),\n covariance_returns.index,\n covariance_returns.columns)\n\nproject_helper.plot_covariance_returns_correlation(\n covariance_returns_correlation,\n 'Covariance Returns Correlation Matrix')",
"_____no_output_____"
]
],
[
[
"### portfolio variance\nWe can write the portfolio variance $\\sigma^2_p = \\mathbf{x^T} \\mathbf{P} \\mathbf{x}$\n\nRecall that the $\\mathbf{x^T} \\mathbf{P} \\mathbf{x}$ is called the quadratic form.\nWe can use the cvxpy function `quad_form(x,P)` to get the quadratic form.\n\n### Distance from index weights\nWe want portfolio weights that track the index closely. So we want to minimize the distance between them.\nRecall from the Pythagorean theorem that you can get the distance between two points in an x,y plane by adding the square of the x and y distances and taking the square root. Extending this to any number of dimensions is called the L2 norm. So: $\\sqrt{\\sum_{1}^{n}(weight_i - indexWeight_i)^2}$ Can also be written as $\\left \\| \\mathbf{x} - \\mathbf{index} \\right \\|_2$. There's a cvxpy function called [norm()](https://www.cvxpy.org/api_reference/cvxpy.atoms.other_atoms.html#norm)\n`norm(x, p=2, axis=None)`. The default is already set to find an L2 norm, so you would pass in one argument, which is the difference between your portfolio weights and the index weights.\n\n### objective function\nWe want to minimize both the portfolio variance and the distance of the portfolio weights from the index weights.\nWe also want to choose a `scale` constant, which is $\\lambda$ in the expression. \n\n$\\mathbf{x^T} \\mathbf{P} \\mathbf{x} + \\lambda \\left \\| \\mathbf{x} - \\mathbf{index} \\right \\|_2$\n\n\nThis lets us choose how much priority we give to minimizing the difference from the index, relative to minimizing the variance of the portfolio. If you choose a higher value for `scale` ($\\lambda$).\n\nWe can find the objective function using cvxpy `objective = cvx.Minimize()`. Can you guess what to pass into this function?\n\n",
"_____no_output_____"
],
[
"### constraints\nWe can also define our constraints in a list. For example, you'd want the weights to sum to one. So $\\sum_{1}^{n}x = 1$. You may also need to go long only, which means no shorting, so no negative weights. So $x_i >0 $ for all $i$. you could save a variable as `[x >= 0, sum(x) == 1]`, where x was created using `cvx.Variable()`.\n\n### optimization\nSo now that we have our objective function and constraints, we can solve for the values of $\\mathbf{x}$.\ncvxpy has the constructor `Problem(objective, constraints)`, which returns a `Problem` object.\n\nThe `Problem` object has a function solve(), which returns the minimum of the solution. In this case, this is the minimum variance of the portfolio.\n\nIt also updates the vector $\\mathbf{x}$.\n\nWe can check out the values of $x_A$ and $x_B$ that gave the minimum portfolio variance by using `x.value`",
"_____no_output_____"
]
],
[
[
"import cvxpy as cvx\n\ndef get_optimal_weights(covariance_returns, index_weights, scale=2.0):\n \"\"\"\n Find the optimal weights.\n\n Parameters\n ----------\n covariance_returns : 2 dimensional Ndarray\n The covariance of the returns\n index_weights : Pandas Series\n Index weights for all tickers at a period in time\n scale : int\n The penalty factor for weights the deviate from the index \n Returns\n -------\n x : 1 dimensional Ndarray\n The solution for x\n \"\"\"\n assert len(covariance_returns.shape) == 2\n assert len(index_weights.shape) == 1\n assert covariance_returns.shape[0] == covariance_returns.shape[1] == index_weights.shape[0]\n\n #TODO: Implement function\n x = cvx.Variable(len(index_weights))\n\n objective = cvx.Minimize(cvx.quad_form(x, covariance_returns) + scale*cvx.norm(x - index_weights, 2))\n constraints = [\n x >= 0,\n sum(x) == 1]\n\n cvx.Problem(objective, constraints).solve()\n\n return x.value\n\nproject_tests.test_get_optimal_weights(get_optimal_weights)",
"_____no_output_____"
]
],
[
[
"## Optimized Portfolio\nUsing the `get_optimal_weights` function, let's generate the optimal ETF weights without rebalanceing. We can do this by feeding in the covariance of the entire history of data. We also need to feed in a set of index weights. We'll go with the average weights of the index over time.",
"_____no_output_____"
]
],
[
[
"raw_optimal_single_rebalance_etf_weights = get_optimal_weights(covariance_returns.values, index_weights.iloc[-1])\noptimal_single_rebalance_etf_weights = pd.DataFrame(\n np.tile(raw_optimal_single_rebalance_etf_weights, (len(returns.index), 1)),\n returns.index,\n returns.columns)",
"_____no_output_____"
]
],
[
[
"With our ETF weights built, let's compare it to the index. Run the next cell to calculate the ETF returns and compare it to the index returns.",
"_____no_output_____"
]
],
[
[
"optim_etf_returns = generate_weighted_returns(returns, optimal_single_rebalance_etf_weights)\noptim_etf_cumulative_returns = calculate_cumulative_returns(optim_etf_returns)\nproject_helper.plot_benchmark_returns(index_weighted_cumulative_returns, optim_etf_cumulative_returns, 'Optimized ETF vs Index')\n\noptim_etf_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(optim_etf_returns, 1))\nprint('Optimized ETF Tracking Error: {}'.format(optim_etf_tracking_error))",
"_____no_output_____"
]
],
[
[
"## Rebalance Portfolio Over Time\nThe single optimized ETF portfolio used the same weights for the entire history. This might not be the optimal weights for the entire period. Let's rebalance the portfolio over the same period instead of using the same weights. Implement `rebalance_portfolio` to rebalance a portfolio.\n\nReblance the portfolio every n number of days, which is given as `shift_size`. When rebalancing, you should look back a certain number of days of data in the past, denoted as `chunk_size`. Using this data, compute the optoimal weights using `get_optimal_weights` and `get_covariance_returns`.",
"_____no_output_____"
]
],
[
[
"def rebalance_portfolio(returns, index_weights, shift_size, chunk_size):\n \"\"\"\n Get weights for each rebalancing of the portfolio.\n\n Parameters\n ----------\n returns : DataFrame\n Returns for each ticker and date\n index_weights : DataFrame\n Index weight for each ticker and date\n shift_size : int\n The number of days between each rebalance\n chunk_size : int\n The number of days to look in the past for rebalancing\n\n Returns\n -------\n all_rebalance_weights : list of Ndarrays\n The ETF weights for each point they are rebalanced\n \"\"\"\n assert returns.index.equals(index_weights.index)\n assert returns.columns.equals(index_weights.columns)\n assert shift_size > 0\n assert chunk_size >= 0\n \n #TODO: Implement function\n all_rebalance_weights = []\n\n for shift in range(chunk_size, len(returns), shift_size):\n start_idx = shift - chunk_size\n covariance_returns = get_covariance_returns(returns.iloc[start_idx:shift])\n\n all_rebalance_weights.append(get_optimal_weights(covariance_returns, index_weights.iloc[shift-1]))\n\n return all_rebalance_weights\n\nproject_tests.test_rebalance_portfolio(rebalance_portfolio)",
"_____no_output_____"
]
],
[
[
"Run the following cell to rebalance the portfolio using `rebalance_portfolio`.",
"_____no_output_____"
]
],
[
[
"chunk_size = 250\nshift_size = 5\nall_rebalance_weights = rebalance_portfolio(returns, index_weights, shift_size, chunk_size)",
"_____no_output_____"
]
],
[
[
"## Portfolio Turnover\nWith the portfolio rebalanced, we need to use a metric to measure the cost of rebalancing the portfolio. Implement `get_portfolio_turnover` to calculate the annual portfolio turnover. We'll be using the formulas used in the classroom:\n\n$ AnnualizedTurnover =\\frac{SumTotalTurnover}{NumberOfRebalanceEvents} * NumberofRebalanceEventsPerYear $\n\n$ SumTotalTurnover =\\sum_{t,n}{\\left | x_{t,n} - x_{t+1,n} \\right |} $ Where $ x_{t,n} $ are the weights at time $ t $ for equity $ n $.\n\n$ SumTotalTurnover $ is just a different way of writing $ \\sum \\left | x_{t_1,n} - x_{t_2,n} \\right | $",
"_____no_output_____"
]
],
[
[
"def get_portfolio_turnover(all_rebalance_weights, shift_size, rebalance_count, n_trading_days_in_year=252):\n \"\"\"\n Calculage portfolio turnover.\n\n Parameters\n ----------\n all_rebalance_weights : list of Ndarrays\n The ETF weights for each point they are rebalanced\n shift_size : int\n The number of days between each rebalance\n rebalance_count : int\n Number of times the portfolio was rebalanced\n n_trading_days_in_year: int\n Number of trading days in a year\n\n Returns\n -------\n portfolio_turnover : float\n The portfolio turnover\n \"\"\"\n assert shift_size > 0\n assert rebalance_count > 0\n \n #TODO: Implement function\n all_rebalance_weights_df = pd.DataFrame(np.array(all_rebalance_weights))\n rebalance_total = (all_rebalance_weights_df - all_rebalance_weights_df.shift(-1)).abs().sum().sum()\n rebalance_avg = rebalance_total / rebalance_count\n rebanaces_per_year = n_trading_days_in_year / shift_size\n \n return rebalance_avg * rebanaces_per_year\n\nproject_tests.test_get_portfolio_turnover(get_portfolio_turnover)",
"_____no_output_____"
]
],
[
[
"Run the following cell to get the portfolio turnover from `get_portfolio turnover`.",
"_____no_output_____"
]
],
[
[
"print(get_portfolio_turnover(all_rebalance_weights, shift_size, returns.shape[1]))",
"_____no_output_____"
]
],
[
[
"That's it! You've built a smart beta portfolio in part 1 and did portfolio optimization in part 2. You can now submit your project.",
"_____no_output_____"
],
[
"## Submission\nNow that you're done with the project, it's time to submit it. Click the submit button in the bottom right. One of our reviewers will give you feedback on your project with a pass or not passed grade. You can continue to the next section while you wait for feedback.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4a914a99f850c50b999e6f0a07562bf56860ab20
| 38,509 |
ipynb
|
Jupyter Notebook
|
regression_metrics.ipynb
|
ugtern/lesson_2_regression
|
1f8351f11daf271383909a3c82a2676e938078c7
|
[
"MIT"
] | null | null | null |
regression_metrics.ipynb
|
ugtern/lesson_2_regression
|
1f8351f11daf271383909a3c82a2676e938078c7
|
[
"MIT"
] | null | null | null |
regression_metrics.ipynb
|
ugtern/lesson_2_regression
|
1f8351f11daf271383909a3c82a2676e938078c7
|
[
"MIT"
] | null | null | null | 71.979439 | 24,340 | 0.74419 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_boston\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\nfrom numpy.linalg import inv\n\nboston_dataset = load_boston()",
"_____no_output_____"
],
[
"feauters = boston_dataset.data\nfeauters.shape",
"_____no_output_____"
],
[
"y = boston_dataset.target\ny.shape",
"_____no_output_____"
],
[
"w = inv(\n (feauters.T).dot(feauters)\n).dot(\n feauters.T\n).dot(y)",
"_____no_output_____"
],
[
"def custome_print(w, format_string = '{0:.2f}'):\n return [format_string.format(a) for i,a in enumerate(w)]",
"_____no_output_____"
],
[
"print(custome_print(w))",
"['-0.09', '0.05', '-0.00', '2.85', '-2.87', '5.93', '-0.01', '-0.97', '0.17', '-0.01', '-0.39', '0.01', '-0.42']\n"
],
[
"regression = LinearRegression().fit(feauters, y)",
"_____no_output_____"
],
[
"print(custome_print(regression.coef_))",
"['-0.11', '0.05', '0.02', '2.69', '-17.77', '3.81', '0.00', '-1.48', '0.31', '-0.01', '-0.95', '0.01', '-0.52']\n"
],
[
"df = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\ndf['target'] = pd.Series(boston_dataset.target)\ndf",
"_____no_output_____"
],
[
"regression.predict(boston_dataset.data[0:10])",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(10, 10))\nax = plt.axes()\n\nax.scatter(df['CRIM'], df['target'], s=100)\n\nplt.show()",
"_____no_output_____"
],
[
"print(mean_absolute_error(regression.predict(feauters), y))",
"3.2708628109003177\n"
],
[
"print(mean_squared_error(regression.predict(feauters), y))",
"21.894831181729202\n"
],
[
"print(r2_score(regression.predict(feauters), y))",
"0.6498212316698573\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a915aca4ac6dbf976ff67a92eb895dfe0a938d4
| 24,707 |
ipynb
|
Jupyter Notebook
|
2nd-ML100Days/homework/D-028/Day_028_HW.ipynb
|
qwerzxcv98/100Day-ML-Marathon
|
3c86cd083b086a1e4b7a55a41b127909c7860f79
|
[
"MIT"
] | 3 |
2019-08-22T15:19:11.000Z
|
2019-08-24T00:54:54.000Z
|
2nd-ML100Days/homework/D-028/Day_028_HW.ipynb
|
magikerwin1993/100Day-ML-Marathon
|
3c86cd083b086a1e4b7a55a41b127909c7860f79
|
[
"MIT"
] | null | null | null |
2nd-ML100Days/homework/D-028/Day_028_HW.ipynb
|
magikerwin1993/100Day-ML-Marathon
|
3c86cd083b086a1e4b7a55a41b127909c7860f79
|
[
"MIT"
] | 1 |
2019-07-18T01:52:04.000Z
|
2019-07-18T01:52:04.000Z
| 44.277778 | 10,452 | 0.643947 |
[
[
[
"# 作業 : (Kaggle)鐵達尼生存預測\nhttps://www.kaggle.com/c/titanic",
"_____no_output_____"
],
[
"# [作業目標]\n- 試著調整特徵篩選的門檻值, 觀察會有什麼影響效果",
"_____no_output_____"
],
[
"# [作業重點]\n- 調整相關係數過濾法的篩選門檻, 看看篩選結果的影響 (In[5]~In[8], Out[5]~Out[8])\n- 調整L1 嵌入法篩選門檻, 看看篩選結果的影響 (In[9]~In[11], Out[9]~Out[11])",
"_____no_output_____"
]
],
[
[
"# 做完特徵工程前的所有準備 (與前範例相同)\nimport pandas as pd\nimport numpy as np\nimport copy\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\n\ndata_path = '../../data/'\ndf = pd.read_csv(data_path + 'titanic_train.csv')\n\ntrain_Y = df['Survived']\ndf = df.drop(['PassengerId'] , axis=1)\ndf.head()",
"_____no_output_____"
],
[
"%matplotlib inline\n# 計算df整體相關係數, 並繪製成熱圖\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ncorr = df.corr()\nsns.heatmap(corr)\nplt.show()",
"_____no_output_____"
],
[
"# 記得刪除 Survived\ndf = df.drop(['Survived'] , axis=1)\n\n#只取 int64, float64 兩種數值型欄位, 存於 num_features 中\nnum_features = []\nfor dtype, feature in zip(df.dtypes, df.columns):\n if dtype == 'float64' or dtype == 'int64':\n num_features.append(feature)\nprint(f'{len(num_features)} Numeric Features : {num_features}\\n')\n\n# 削減文字型欄位, 只剩數值型欄位\ndf = df[num_features]\ndf = df.fillna(-1)\nMMEncoder = MinMaxScaler()\ndf.head()",
"5 Numeric Features : ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare']\n\n"
]
],
[
[
"# 作業1\n* 鐵達尼生存率預測中,試著變更兩種以上的相關係數門檻值,觀察預測能力是否提升?",
"_____no_output_____"
]
],
[
[
"# 原始特徵 + 邏輯斯迴歸\ntrain_X = MMEncoder.fit_transform(df.astype(np.float64))\nestimator = LogisticRegression(solver='lbfgs')\ncross_val_score(estimator, train_X, train_Y, cv=5).mean()",
"_____no_output_____"
],
[
"# 篩選相關係數1\nhigh_list = list(corr[(corr['Survived']>0.1) | (corr['Survived']<-0.1)].index)\nhigh_list.remove('Survived')\nprint(high_list)",
"['Pclass', 'Fare']\n"
],
[
"# 特徵1 + 邏輯斯迴歸\ntrain_X = MMEncoder.fit_transform(df[high_list].astype(np.float64))\ncross_val_score(estimator, train_X, train_Y, cv=5).mean()",
"_____no_output_____"
],
[
"# 篩選相關係數2\n\"\"\"\nYour Code Here\n\"\"\"\nhigh_list = list(corr[(corr['Survived']<0.1) | (corr['Survived']>-0.1)].index)\nhigh_list.remove('Survived')\nprint(high_list)",
"['Pclass', 'Age', 'SibSp', 'Parch', 'Fare']\n"
],
[
"# 特徵2 + 邏輯斯迴歸\ntrain_X = MMEncoder.fit_transform(df[high_list].astype(np.float64))\ncross_val_score(estimator, train_X, train_Y, cv=5).mean()",
"_____no_output_____"
]
],
[
[
"# 作業2\n* 續上題,使用 L1 Embedding 做特徵選擇(自訂門檻),觀察預測能力是否提升?",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import Lasso\n\"\"\"\nYour Code Here, select parameter alpha \n\"\"\"\nL1_Reg = Lasso(alpha=0.003)\ntrain_X = MMEncoder.fit_transform(df.astype(np.float64))\nL1_Reg.fit(train_X, train_Y)\nL1_Reg.coef_",
"_____no_output_____"
],
[
"from itertools import compress\nL1_mask = list((L1_Reg.coef_>0) | (L1_Reg.coef_<0))\nL1_list = list(compress(list(df), list(L1_mask)))\nL1_list",
"_____no_output_____"
],
[
"# L1_Embedding 特徵 + 線性迴歸\ntrain_X = MMEncoder.fit_transform(df[L1_list].astype(np.float64))\ncross_val_score(estimator, train_X, train_Y, cv=5).mean()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a9161d1ec83c735f5b97ca16119b9a079c505c9
| 228,105 |
ipynb
|
Jupyter Notebook
|
sandbox/ooi_pioneer/notebooks/MITgcm_profilespkg_TUTORIAL.ipynb
|
IvanaEscobar/sandbox
|
71d62af2c112686c5ce26def35593247cf6a0ccc
|
[
"MIT"
] | null | null | null |
sandbox/ooi_pioneer/notebooks/MITgcm_profilespkg_TUTORIAL.ipynb
|
IvanaEscobar/sandbox
|
71d62af2c112686c5ce26def35593247cf6a0ccc
|
[
"MIT"
] | 3 |
2022-02-15T23:32:52.000Z
|
2022-03-28T21:35:12.000Z
|
sandbox/ooi_pioneer/notebooks/MITgcm_profilespkg_TUTORIAL.ipynb
|
IvanaEscobar/sandbox
|
71d62af2c112686c5ce26def35593247cf6a0ccc
|
[
"MIT"
] | null | null | null | 186.512674 | 87,880 | 0.80256 |
[
[
[
"# Example of iPROF nc file content",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm, colors\nimport ecco_v4_py as ecco\nimport xmitgcm\n\nimport os\nimport warnings\nwarnings.simplefilter('ignore')\nos.environ['PYTHONWARNOINGS'] = 'ignore'",
"_____no_output_____"
],
[
"path=f'/scratch/fhabbal/aste_270x450x180/run_template/input_insitu/+aste/+18x18'",
"_____no_output_____"
],
[
"ds = xr.open_dataset(f'{path}/argo_feb2016_2013_llc270_18x18_ASTE.nc')\nds",
"_____no_output_____"
],
[
"(unique, counts) = np.unique(ds.prof_date, return_counts=True)\n\ndates = unique[np.where(counts == max(counts))[0]]\ndates",
"_____no_output_____"
],
[
"np.isnan(ds.prof_date.where( ds.prof_date == dates[-1] )).plot()\nplt.show()\n\nplt.figure()\nplt.plot(counts)\nplt.show()",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,10))\nds.prof_T.plot()\nplt.show()",
"_____no_output_____"
],
[
"ds = xr.open_dataset(f'{path}/ctd_santa_anna_llc270_18x18_july2017_ASTE.nc')\nds.isel(prof_depth=10)",
"_____no_output_____"
],
[
"ds.prof_depth.plot(marker='o', linewidth=0., markersize=0.5)",
"_____no_output_____"
],
[
"ds = xr.open_dataset('/home/fhabbal/curr_scratch/run_FW_runoff_aste_iceplume_pickup7_Exp1_osnap_PISMv3_10mRadConeARL/ARL_profile7_2017_30x30.nc')\nds",
"_____no_output_____"
],
[
"ds.prof_depth.plot(marker='o', linewidth=0., markersize=0.5)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a91634c88b5e1bc70c97d7af7807cbbc03db3a0
| 26,649 |
ipynb
|
Jupyter Notebook
|
examples/vectorization/total_vector.ipynb
|
nnnyt/EduNLP
|
a40e7de1d73cb177bc36f5d75d933904c18040ef
|
[
"Apache-2.0"
] | null | null | null |
examples/vectorization/total_vector.ipynb
|
nnnyt/EduNLP
|
a40e7de1d73cb177bc36f5d75d933904c18040ef
|
[
"Apache-2.0"
] | null | null | null |
examples/vectorization/total_vector.ipynb
|
nnnyt/EduNLP
|
a40e7de1d73cb177bc36f5d75d933904c18040ef
|
[
"Apache-2.0"
] | null | null | null | 47.843806 | 369 | 0.595257 |
[
[
[
"# 向量化\r\n\r\n## 简述\r\n\r\n向量化过程是将item转换为向量的过程,其前置步骤为语法解析、成分分解、令牌化,本部分将先后介绍如何获得数据集、如何使用本地的预训练模型、如何直接调用远程提供的预训练模型。",
"_____no_output_____"
],
[
"## 获得数据集\r\n\r\n### 概述\r\n\r\n此部分通过调用 [OpenLUNA.json](http://base.ustc.edu.cn/data/OpenLUNA/OpenLUNA.json) 获得。",
"_____no_output_____"
],
[
"## I2V\r\n\r\n### 概述\r\n\r\n使用自己提供的任一预训练模型(给出模型存放路径即可)将给定的题目文本转成向量。\r\n\r\n- 优点:可以使用自己的模型,另可调整训练参数,灵活性强。",
"_____no_output_____"
],
[
"### D2V",
"_____no_output_____"
],
[
"#### 导入类",
"_____no_output_____"
]
],
[
[
"from EduNLP.I2V import D2V",
"D:\\MySoftwares\\Anaconda\\envs\\data\\lib\\site-packages\\gensim\\similarities\\__init__.py:15: UserWarning: The gensim.similarities.levenshtein submodule is disabled, because the optional Levenshtein package <https://pypi.org/project/python-Levenshtein/> is unavailable. Install Levenhstein (e.g. `pip install python-Levenshtein`) to suppress this warning.\n warnings.warn(msg)\n"
]
],
[
[
"#### 输入\r\n\r\n类型:str \r\n内容:题目文本 (text)",
"_____no_output_____"
]
],
[
[
"items = [\r\nr\"1如图几何图形.此图由三个半圆构成,三个半圆的直径分别为直角三角形$ABC$的斜边$BC$, 直角边$AB$, $AC$.$\\bigtriangleup ABC$的三边所围成的区域记为$I$,黑色部分记为$II$, 其余部分记为$III$.在整个图形中随机取一点,此点取自$I,II,III$的概率分别记为$p_1,p_2,p_3$,则$\\SIFChoice$$\\FigureID{1}$\",\r\nr\"2如图来自古希腊数学家希波克拉底所研究的几何图形.此图由三个半圆构成,三个半圆的直径分别为直角三角形$ABC$的斜边$BC$, 直角边$AB$, $AC$.$\\bigtriangleup ABC$的三边所围成的区域记为$I$,黑色部分记为$II$, 其余部分记为$III$.在整个图形中随机取一点,此点取自$I,II,III$的概率分别记为$p_1,p_2,p_3$,则$\\SIFChoice$$\\FigureID{1}$\"\r\n]",
"_____no_output_____"
]
],
[
[
"#### 输出",
"_____no_output_____"
]
],
[
[
"model_path = \"./d2v/test_d2v_256.bin\"\r\ni2v = D2V(\"pure_text\",\"d2v\",filepath=model_path, pretrained_t2v = False)\r\n\r\nitem_vectors, token_vectors = i2v(items)\r\nprint(item_vectors[0])\r\nprint(token_vectors) # For d2v, token_vector is None\r\nprint(\"shape of item_vector: \",len(item_vectors), item_vectors[0].shape) ",
"[ 0.10603202 -0.10537548 -0.04773913 0.15573525 0.25898772 -0.06423073\n -0.02817309 0.0068187 -0.07323898 0.06517941 0.07943465 0.14800762\n -0.06772996 -0.23892336 0.04638071 0.1539897 0.17565852 0.02895202\n -0.18859927 0.2180874 0.00909669 0.06621908 -0.02090263 -0.13006955\n -0.21020882 0.00618349 0.00531093 -0.04877732 -0.06709669 -0.04705636\n 0.09211092 0.13896106 -0.07455818 0.06019318 -0.09071473 0.12701215\n 0.13018885 -0.02784999 0.10064025 -0.07757548 -0.05522636 -0.02657779\n -0.04159601 -0.03008493 0.10995369 -0.00587291 0.05902484 0.06532726\n 0.04887666 0.01902074 0.03713945 0.03691795 0.12516327 0.07410683\n -0.14467879 0.05678609 0.02574336 -0.1320522 0.07502684 0.07929367\n -0.06655917 -0.0144536 0.02595847 0.04403471 0.21743318 -0.02525017\n -0.0416184 0.21441495 -0.09308876 -0.09418222 0.08030997 0.00492512\n -0.04921608 -0.07808654 -0.03323801 0.0879296 -0.04668022 -0.0696011\n 0.06708417 0.06555629 -0.07418457 -0.13050951 -0.01802611 0.11730465\n -0.0479078 0.06389603 0.12324224 -0.17746696 -0.09874132 -0.07683054\n 0.06596514 -0.04210603 0.03182372 -0.1455575 0.03900012 0.13290605\n -0.07672353 -0.02826704 -0.00803517 -0.09681892 -0.15212329 -0.10524812\n 0.03367848 0.10413344 -0.0089777 0.0583192 -0.01553376 0.02675472\n 0.12278829 0.01667286 0.01958599 -0.06468913 0.08307286 0.07304061\n -0.10451686 -0.04367925 0.0143903 0.11394493 0.00759796 -0.03158598\n -0.01733392 -0.12918264 0.1761386 -0.02913121 -0.01364522 0.01497996\n 0.09318532 -0.03958051 0.00465893 -0.01766865 -0.03531685 0.01445563\n 0.05919004 -0.10480376 -0.08359206 -0.08283877 -0.04920156 0.0486405\n 0.0059151 -0.03783213 -0.01815955 -0.0157437 0.2334638 0.15233137\n -0.2698607 -0.04492244 0.03728078 0.06730984 0.09165722 0.07212968\n -0.1418279 -0.10517611 -0.0469548 -0.01878718 -0.08850995 0.07481015\n 0.15206474 0.0923347 -0.08849481 0.01736124 0.12647657 -0.03515046\n 0.07980374 -0.06639698 0.00411603 0.0479564 0.04197159 0.0854824\n 0.103918 -0.01195896 0.05059687 -0.03206704 0.0277859 0.05210226\n -0.15160614 -0.01996467 -0.00720571 -0.01154042 0.10944121 -0.00173247\n 0.11439639 -0.04765575 0.05989955 -0.05265343 0.11914644 0.0085329\n -0.13220952 -0.1538407 -0.07261448 0.04143476 0.15447438 0.02005473\n 0.14354227 0.10015973 0.12290012 0.05011315 0.0425972 -0.13731483\n 0.02323116 -0.1031343 -0.17960383 -0.04875064 0.14352156 0.04516263\n -0.04433561 0.11548021 -0.2057457 -0.02778868 -0.06643672 0.05604808\n 0.04864014 -0.03015646 0.07734285 0.00573904 0.01155302 0.02486293\n 0.16259493 0.05099423 -0.15283771 -0.01909443 -0.12749314 0.06718695\n 0.08334705 -0.05442797 0.03448674 -0.00542413 0.00832719 0.02702984\n -0.02359959 -0.00855793 -0.19381124 -0.13036375 -0.0351354 -0.03983364\n 0.0133928 0.07395492 0.04119737 0.05661048 0.08151852 -0.1529391\n 0.00742581 0.05521343 0.02089992 -0.00824985 -0.00211842 -0.05555268\n 0.05448649 -0.02032894 -0.0760811 -0.01713146 -0.16146915 0.10822926\n -0.1240218 -0.03639562 -0.20028785 -0.02452293]\nNone\nshape of item_vector: 2 (256,)\n"
]
],
[
[
"### W2V",
"_____no_output_____"
]
],
[
[
"from EduNLP.I2V import W2V",
"_____no_output_____"
],
[
"model_path = \"./w2v/general_literal_300/general_literal_300.kv\"\r\ni2v = W2V(\"pure_text\",\"w2v\",filepath=model_path, pretrained_t2v = False)\r\n\r\nitem_vectors, token_vectors = i2v(items)\r\n\r\nprint(item_vectors[0])\r\nprint(token_vectors[0][0])\r\nprint(\"shape of item_vectors: \", len(item_vectors), item_vectors[0].shape)\r\nprint(\"shape of token_vectors: \", len(token_vectors), len(token_vectors[0]), len(token_vectors[0][0]))",
"[-1.34266680e-03 5.19845746e-02 -1.98070258e-02 -4.17470075e-02\n 4.92814295e-02 -1.70883536e-01 -2.16597781e-01 -3.12069029e-01\n 8.96430463e-02 -1.31331667e-01 9.16494895e-03 -3.22572999e-02\n 3.07940125e-01 1.92060292e-01 1.31043345e-02 6.10962026e-02\n 2.21019030e-01 -3.53541046e-01 1.34150490e-01 1.14867561e-01\n 1.17448963e-01 2.27990672e-01 -1.65213019e-01 2.78246611e-01\n -4.36594114e-02 -1.37816787e-01 -1.07707813e-01 -1.80805102e-01\n 1.20028563e-01 -1.14409983e-01 6.19181581e-02 -1.79836392e-01\n 7.68677965e-02 2.41688967e-01 6.20721914e-02 -7.59824514e-02\n 1.79465964e-01 1.69306010e-01 -1.99512452e-01 -9.75036696e-02\n 1.02485821e-01 -1.59723386e-01 -1.67252243e-01 1.52240042e-02\n -5.98842278e-03 6.47612512e-02 8.48228261e-02 2.67874986e-01\n -1.73656959e-02 -4.40101810e-02 9.11948457e-02 1.40905827e-01\n 6.33735815e-03 2.03221604e-01 -1.97303146e-01 1.32987842e-01\n -1.80283263e-01 3.64040211e-02 2.49624569e-02 7.49479085e-02\n -2.05568615e-02 -4.02397066e-02 -1.08619891e-01 -1.04757406e-01\n -8.36341307e-02 6.61163032e-02 -1.11632387e-03 3.96131463e-02\n -3.51454802e-02 9.09155831e-02 1.87938929e-01 -2.40521863e-01\n -5.97307160e-02 1.74426511e-01 1.56350788e-02 -4.20243442e-02\n -1.90285146e-02 -3.85696471e-01 -1.01543151e-01 -1.42145246e-01\n 2.33298853e-01 1.85939763e-02 -2.68633634e-01 -3.60178575e-02\n 3.64447385e-02 -1.70443758e-01 1.03326524e-02 -1.47003353e-01\n -9.38110873e-02 1.63190335e-01 1.20674491e-01 -2.36976147e-02\n -6.52602538e-02 1.29773334e-01 -4.23593611e-01 2.43276700e-01\n -8.00978579e-03 -9.39133018e-03 1.17623486e-01 1.16482794e-01\n -9.27330479e-02 6.17316999e-02 1.51295820e-02 2.25901395e-01\n 7.31975585e-02 2.29724105e-02 9.95925292e-02 -1.10697523e-01\n 2.28960160e-02 8.65939483e-02 1.16645083e-01 -7.00058565e-02\n 1.13389529e-01 -5.30471019e-02 1.43660516e-01 1.61379650e-02\n 6.77419230e-02 8.09707418e-02 2.09957212e-01 -6.64654151e-02\n -1.81450248e-01 2.21659631e-01 -4.53737518e-03 4.69567403e-02\n 8.59350115e-02 1.17934339e-01 -1.98988736e-01 -4.13361974e-02\n 1.26167178e-01 3.84825058e-02 1.64396539e-01 -1.63344927e-02\n 9.12889242e-02 -1.13650873e-01 -1.37156844e-02 2.06742659e-02\n -9.15742964e-02 7.41296187e-02 2.50813574e-01 -1.35987863e-01\n -1.11708120e-01 -1.52451068e-01 1.08608082e-01 4.99855466e-02\n 1.68440521e-01 -2.47063249e-01 -2.21773341e-01 4.81536575e-02\n -7.66365305e-02 2.55189091e-01 -5.60788438e-03 -2.69066542e-02\n 2.07698755e-02 1.36008840e-02 1.33086294e-01 -3.80828045e-02\n -7.03251585e-02 -6.18199483e-02 9.03518647e-02 -1.89310908e-01\n -5.30523732e-02 -2.04426926e-02 -2.27697566e-01 7.68405125e-02\n 1.28568143e-01 1.07449636e-01 -1.98028013e-01 -2.67155319e-01\n -5.17064631e-02 -1.62200809e-01 1.87425911e-01 4.74511087e-02\n -4.24213745e-02 -2.71449953e-01 -2.83543557e-01 -2.36278087e-01\n -4.38764729e-02 1.67618364e-01 -2.51966029e-01 -2.73265123e-01\n -1.68406263e-01 -3.58684808e-01 2.44145632e-01 -2.55741596e-01\n -2.28520826e-01 2.39279866e-01 -1.68833986e-01 1.66422993e-01\n -3.53969544e-01 -1.10907286e-01 -6.29489049e-02 -4.55605611e-02\n 1.46765754e-01 1.95176788e-02 -3.80197394e-04 3.36615089e-03\n -1.42359287e-01 -1.06109239e-01 -3.36164385e-02 3.16832401e-02\n 1.09924652e-01 2.10711379e-02 1.58359021e-01 1.71957895e-01\n 4.08717275e-01 -4.28679548e-02 -6.48310632e-02 1.27063962e-02\n 5.73479272e-02 1.40002951e-01 -3.66613895e-01 8.07148069e-02\n 2.11823225e-01 -1.10516161e-01 -2.01001287e-01 3.22122797e-02\n 5.47345541e-02 2.30176803e-02 -9.94866490e-02 -4.44128877e-03\n 6.64432272e-02 1.28168091e-01 -2.34743133e-01 3.17057431e-01\n -8.75139013e-02 2.66474396e-01 -3.12204093e-01 7.78969377e-03\n 6.21694922e-02 7.64596611e-02 -8.79013091e-02 1.01901866e-01\n 3.23867425e-02 -2.27650225e-01 9.44062844e-02 -5.54776154e-02\n -7.03687780e-03 5.66167049e-02 -1.87480077e-01 9.11692008e-02\n 1.51293352e-01 -1.92774653e-01 2.23165095e-01 2.26982050e-02\n -2.70489484e-01 1.25889871e-02 -2.30410039e-01 1.40989587e-01\n 2.20341813e-02 2.70313285e-02 6.07572980e-02 8.79322216e-02\n 7.42911696e-02 -2.76499927e-01 2.05189809e-01 -1.84953049e-01\n -1.68468937e-01 1.85525760e-01 -3.32091609e-03 2.29632735e-01\n 7.13749304e-02 -2.75445748e-02 2.74335817e-02 1.65132031e-01\n -1.64373592e-01 -1.14925921e-01 4.98081557e-02 2.10796613e-02\n -2.07561441e-02 5.90056814e-02 -1.25214513e-02 3.78197022e-02\n 3.62618983e-01 1.72744930e-01 -8.75385627e-02 1.52320743e-01\n 1.29331559e-01 -1.34815618e-01 6.12287596e-02 7.30569959e-02\n 5.37401363e-02 -1.46815628e-01 -2.61263877e-01 2.18300954e-01\n 8.95068944e-02 -6.59529120e-02 -8.52308050e-02 2.63195664e-01\n 2.09921718e-01 -1.73417434e-01 2.11869497e-02 7.06950724e-02\n -7.89924189e-02 1.11086138e-01 -1.29149273e-01 1.16233543e-01\n 2.16104537e-01 -3.05427730e-01 -2.46336535e-01 7.59556964e-02]\n[-9.74057533e-04 1.39671087e-03 -2.67836265e-04 3.15364590e-03\n 2.96666636e-04 2.81736051e-04 -2.63743475e-03 1.52303779e-03\n 1.01379235e-03 1.57282199e-03 -1.71113803e-04 8.02559836e-04\n 2.57097790e-03 1.81893981e-03 2.63088616e-03 3.40178027e-04\n -2.11292668e-03 -2.50976160e-03 -1.20709895e-03 1.67239667e-03\n -2.58512655e-03 -1.26207829e-03 1.39700493e-03 1.95603608e-03\n 2.89038429e-03 -2.39552581e-03 -3.91247275e-04 -3.21114226e-03\n 9.58531688e-04 8.29325523e-04 -1.59795280e-03 1.25081465e-03\n 3.81096208e-04 1.59411912e-03 -8.54889571e-04 -3.06331483e-03\n 1.97919217e-04 -9.37395904e-04 2.09570490e-03 1.22304517e-03\n -2.73981970e-03 1.85640890e-03 -8.50516954e-04 2.05107126e-03\n 3.25771095e-03 -2.02651741e-03 -2.99406121e-03 -2.29128683e-03\n 7.10814027e-04 -2.45556026e-03 3.29233892e-03 -1.30950764e-03\n -1.89368729e-03 1.27877074e-03 2.70718103e-03 -2.21936312e-03\n 1.69272022e-03 7.79648602e-04 2.15323060e-03 -1.90569717e-03\n -2.24422058e-03 -7.12279463e-04 1.38582790e-03 2.27209576e-03\n -2.48074066e-03 -1.57340372e-03 -2.78435787e-03 2.53080134e-03\n 9.29941365e-04 9.57158394e-04 -4.04856197e-04 7.77039502e-04\n 2.93451315e-03 1.50868180e-03 -2.39667180e-03 1.94984837e-03\n -1.30266906e-03 -3.10783624e-03 2.75730062e-03 6.42884581e-04\n -5.66801231e-04 7.95386615e-04 -2.41047610e-03 1.00338063e-03\n 2.82178726e-03 -2.43772753e-03 5.73688361e-04 1.23452744e-03\n -3.01872566e-03 -1.07384368e-03 3.28231254e-03 -5.47548116e-04\n 2.18831864e-03 -3.27980524e-04 1.68147963e-03 2.44990899e-03\n -2.45229807e-03 1.02455064e-03 -2.29938584e-03 2.91304989e-03\n 1.60753564e-03 1.12590473e-03 3.00752558e-03 1.44218525e-03\n 3.16225761e-03 -1.64008932e-04 -5.27421653e-04 1.06547831e-03\n 1.11937604e-03 4.77150286e-04 -2.42268969e-03 -3.12998053e-03\n 4.55578178e-04 2.90129334e-03 -3.05265025e-03 -1.28805637e-03\n -2.08641519e-03 3.26466886e-03 -2.95106089e-03 -2.08173040e-03\n -1.99576933e-03 4.53641405e-04 -2.70907651e-03 -2.34400504e-03\n 1.16086320e-03 -2.44718627e-03 9.25636268e-05 9.73496411e-04\n -1.01899146e-03 -3.02827288e-03 9.58363991e-04 -3.27257067e-03\n 2.40717572e-03 1.20117664e-04 1.10580446e-03 -4.41495577e-05\n -2.85318610e-03 1.54357916e-03 3.11869616e-03 6.44255488e-04\n -1.31027703e-03 -1.52749463e-03 8.79097788e-04 7.01892364e-04\n 1.34046946e-03 -8.91715696e-04 -1.93791394e-03 -4.34041809e-04\n 1.12010317e-03 -2.24535773e-03 -1.76302914e-03 -1.11521804e-03\n -2.68377946e-03 -2.55486579e-03 2.67607206e-03 -2.09635729e-03\n 4.45536774e-04 4.23340796e-04 -2.36946181e-03 1.01201690e-03\n 2.53369007e-03 -8.69231240e-04 -2.23573043e-05 4.58726077e-04\n 9.46683111e-04 -1.58690137e-03 1.31600059e-03 2.19468423e-03\n -1.69886113e-03 1.71214901e-03 -1.43307843e-04 -1.10225752e-03\n 3.13180522e-03 1.78616366e-03 -4.65679186e-05 -1.40959187e-03\n -6.96717121e-04 -5.70511795e-04 -1.54102559e-03 -2.30318774e-03\n 2.54784338e-03 -1.62216101e-03 3.14650533e-04 -2.94532534e-03\n -1.02099183e-03 2.99499906e-03 -6.38728146e-04 -2.72372481e-03\n 3.22340080e-03 -1.49127806e-03 2.27723271e-03 2.73366761e-03\n 2.62600114e-03 2.68271845e-03 3.20440996e-03 -4.97240224e-04\n -1.02938886e-03 3.26999027e-04 9.46711691e-04 1.76053529e-03\n 1.74157624e-03 1.49760721e-03 -3.09546776e-05 2.48821010e-03\n 2.15774146e-03 2.42709951e-03 -2.46135960e-03 1.82637456e-03\n -3.11999000e-03 -2.49591586e-03 -3.27967643e-03 -1.17016002e-03\n 6.43555308e-04 3.32132494e-03 -2.58475146e-03 -7.75608991e-04\n 3.30572366e-03 6.71840506e-04 -2.23828160e-04 2.99876463e-03\n 3.10293835e-05 -1.25048554e-03 2.48837401e-03 -4.16146126e-04\n -8.01149989e-04 -2.19148802e-04 -2.70171487e-03 1.73141161e-04\n -2.53586681e-03 3.11773620e-03 1.13646187e-04 2.82005151e-03\n -3.23787535e-04 1.52152695e-03 3.21076158e-03 -2.29426223e-04\n -2.22376501e-03 -3.26833175e-03 5.72812569e-04 3.06089874e-03\n 8.33402446e-04 1.29480439e-03 1.32911524e-03 2.61883345e-03\n -2.53178203e-03 6.48000219e-04 2.66361074e-03 -3.05172289e-03\n -9.23413434e-04 -2.13261833e-03 8.54914193e-04 -1.48963137e-03\n -1.95632223e-03 -7.69955339e-04 -3.29735363e-03 1.98830920e-03\n 1.31162966e-03 1.10320176e-03 -3.22533771e-03 2.04978790e-03\n -5.25970478e-04 -1.89223525e-03 2.42309878e-03 8.27315671e-04\n 9.63741913e-04 8.84156208e-04 1.02529768e-03 -1.41616585e-03\n 6.75518531e-04 -6.47147477e-04 2.71809031e-03 2.17319001e-03\n 9.71910951e-04 -2.93364283e-03 2.43404706e-04 1.14709849e-03\n -1.99730392e-04 3.82491737e-04 -3.08531453e-03 -2.20424891e-03\n 2.87708524e-03 1.51069486e-03 9.24036489e-04 -1.09619542e-03\n 1.36686012e-03 -2.61674239e-03 -1.52974128e-04 -2.72300956e-03\n 1.70241436e-03 -6.61658472e-04 -2.15324806e-03 -2.46914220e-03\n 1.41488796e-03 -3.25874239e-03 -2.29610526e-03 -2.22696620e-03\n -2.09132349e-03 -2.79461709e-03 -3.24834906e-03 -1.12362858e-03]\nshape of item_vectors: 2 (300,)\nshape of token_vectors: 2 55 300\n"
]
],
[
[
"## get_pretrained_i2v\r\n\r\n### 概述\r\n\r\n使用 EduNLP 项目组给定的预训练模型将给定的题目文本转成向量。\r\n\r\n- 优点:简单方便。\r\n- 缺点:只能使用项目中给定的模型,局限性较大。\r\n",
"_____no_output_____"
],
[
"### 导入功能块",
"_____no_output_____"
]
],
[
[
"from EduNLP import get_pretrained_i2v",
"_____no_output_____"
]
],
[
[
"### 输入\r\n\r\n类型:str \r\n内容:题目文本 (text)",
"_____no_output_____"
]
],
[
[
"items = [\r\n\"如图来自古希腊数学家希波克拉底所研究的几何图形.此图由三个半圆构成,三个半圆的直径分别为直角三角形$ABC$的斜边$BC$, 直角边$AB$, $AC$.$\\bigtriangleup ABC$的三边所围成的区域记为$I$,黑色部分记为$II$, 其余部分记为$III$.在整个图形中随机取一点,此点取自$I,II,III$的概率分别记为$p_1,p_2,p_3$,则$\\SIFChoice$$\\FigureID{1}$\"\r\n]\r\n",
"_____no_output_____"
]
],
[
[
"### 模型选择与使用",
"_____no_output_____"
],
[
"根据题目所属学科选择预训练模型: \r\n\r\n 预训练模型名称 | 模型训练数据的所属学科 \r\n -------------- | ---------------------- \r\n d2v_all_256 | 全学科 \r\n d2v_sci_256 | 理科 \r\n d2v_eng_256 | 英语 \r\n d2v_lit_256 | 文科 \r\n w2v_eng_300 | 英语 \r\n w2v_lit_300 | 文科 ",
"_____no_output_____"
]
],
[
[
"i2v = get_pretrained_i2v(\"d2v_sci_256\", model_dir=\"./d2v\")",
"EduNLP, INFO Use pretrained t2v model d2v_sci_256\ndownloader, INFO http://base.ustc.edu.cn/data/model_zoo/EduNLP/d2v/general_science_256.zip is saved as d2v\\general_science_256.zip\ndownloader, INFO file existed, skipped\n"
]
],
[
[
"- 注意:\n 默认的 EduNLP 项目存储地址为根目录(`~/.EduNLP`),模型存储地址为项目存储地址下的 `model` 文件夹。您可以通过修改下面的环境变量来修改模型存储地址:\n - EduNLP 项目存储地址:`EDUNLPPATH = xx/xx/xx`\n - 模型存储地址:`EDUNLPMODELPATH = xx/xx/xx`",
"_____no_output_____"
]
],
[
[
"item_vectors, token_vectors = i2v(items)\r\nprint(item_vectors)\r\nprint(token_vectors)",
"[array([-0.23861311, 0.06892798, -0.27065727, 0.16547263, 0.02818857,\n -0.18185084, 0.09226187, 0.01612627, 0.0921795 , 0.3134312 ,\n 0.09265023, -0.22529641, -0.25788078, 0.06702194, 0.09765045,\n -0.19932257, 0.08527228, -0.22684543, -0.1776405 , -0.03682012,\n 0.6210964 , -0.26637274, 0.08060682, -0.15860714, -0.17825642,\n -0.13271384, 0.27331072, 0.18202724, 0.08430962, 0.23299456,\n 0.179898 , 0.1571772 , -0.1406754 , -0.19508898, -0.11265783,\n 0.11396482, 0.0223774 , 0.07824919, -0.2421433 , 0.06195279,\n -0.04763965, -0.02037446, 0.07481094, -0.1908799 , 0.09688905,\n 0.3995564 , 0.28225863, 0.30547026, -0.46538818, -0.02891348,\n -0.19343005, 0.01966276, -0.21590087, 0.09774096, -0.26137134,\n -0.23963049, 0.34259936, 0.14825426, -0.2987728 , -0.38039675,\n -0.12087625, 0.05897354, 0.06351897, 0.10188989, 0.12092843,\n 0.13229063, 0.12786968, -0.15378596, 0.00724137, -0.13644631,\n -0.15164569, 0.11535735, -0.24394232, -0.08835315, 0.05014084,\n -0.05980775, 0.03040357, -0.05804552, -0.04122322, 0.31905708,\n -0.02468318, 0.06953011, -0.1299219 , 0.01482821, -0.00126122,\n -0.20185567, -0.00784766, -0.28023243, -0.16416278, -0.04939609,\n -0.22619021, -0.17099814, 0.1434735 , -0.13193442, -0.18329675,\n -0.06873035, -0.21638975, -0.0767743 , 0.17778671, 0.0459166 ,\n 0.0719557 , 0.0797654 , -0.15445784, -0.20094277, 0.11860424,\n 0.09521067, -0.10993416, -0.01273298, -0.0857757 , -0.05475522,\n -0.09463413, 0.00845256, 0.06638184, -0.22701578, 0.06599791,\n 0.1323833 , 0.2227748 , 0.13431212, -0.08537175, 0.14300612,\n 0.24459998, 0.00735889, -0.07123663, 0.24863936, 0.10320719,\n -0.06399037, 0.0537433 , 0.00862593, -0.10747737, -0.01009098,\n 0.01707896, 0.07951383, -0.2245529 , 0.03152119, 0.19090259,\n 0.27611575, -0.16507478, 0.05977706, 0.09740735, 0.32154247,\n -0.02540598, -0.20875612, 0.11484967, 0.12112009, -0.00937327,\n -0.03855037, -0.03728763, 0.13645649, 0.42706412, 0.14456204,\n -0.1542145 , 0.07858715, 0.14076898, 0.01195827, 0.16896723,\n -0.0516856 , 0.05795754, 0.09602529, 0.02058077, 0.14346235,\n 0.3984762 , 0.06770886, -0.5524451 , -0.18779868, 0.11151859,\n -0.06967582, 0.09465033, 0.2242416 , -0.17179447, 0.20837718,\n 0.43269685, -0.33945957, 0.00746959, -0.14856125, -0.04883511,\n 0.0790235 , 0.18130969, -0.06500382, -0.05761597, 0.15247819,\n 0.22402437, 0.33508143, -0.02544755, 0.10404763, -0.0392291 ,\n 0.14048643, -0.39408255, -0.04759403, -0.09290893, -0.10062248,\n 0.3836949 , -0.04212417, 0.04195033, -0.34143335, 0.02139966,\n 0.00748172, 0.09670173, 0.11287135, 0.07313446, -0.06884305,\n -0.27654266, -0.02745902, 0.11782443, -0.05509072, -0.02731109,\n 0.02932139, 0.20647307, -0.09912065, 0.08175386, 0.04051739,\n -0.13783188, 0.2178767 , 0.01360986, -0.11862064, 0.02632025,\n 0.01305837, -0.07418288, -0.11537156, 0.07784148, -0.02828423,\n 0.0152778 , -0.27535534, -0.26457086, -0.2426946 , 0.17839569,\n 0.41153124, -0.06237097, 0.28373018, 0.09847705, -0.2693095 ,\n 0.15109962, 0.02665104, 0.12224031, 0.0053689 , 0.08057593,\n 0.0029663 , -0.01309686, 0.04294159, -0.26014623, -0.09540065,\n -0.19017759, -0.02596658, -0.21918078, -0.04269371, 0.09444954,\n -0.05112423, 0.21732539, 0.2555126 , 0.06598321, -0.00912136,\n 0.01300732, -0.02216252, 0.16752972, 0.00181198, 0.02385568,\n -0.0017939 ], dtype=float32)]\nNone\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a9188d9f5c62cfc248e48a76455903af1d27e2a
| 21,652 |
ipynb
|
Jupyter Notebook
|
Tutorial-LaTeX_SymPy_Conversion.ipynb
|
goncalo-andrade/nrpytutorial
|
4fbcb51c936864b442daefd176bd6a5277c00116
|
[
"BSD-2-Clause"
] | 1 |
2020-06-09T16:16:21.000Z
|
2020-06-09T16:16:21.000Z
|
Tutorial-LaTeX_SymPy_Conversion.ipynb
|
goncalo-andrade/nrpytutorial
|
4fbcb51c936864b442daefd176bd6a5277c00116
|
[
"BSD-2-Clause"
] | null | null | null |
Tutorial-LaTeX_SymPy_Conversion.ipynb
|
goncalo-andrade/nrpytutorial
|
4fbcb51c936864b442daefd176bd6a5277c00116
|
[
"BSD-2-Clause"
] | null | null | null | 35.495082 | 1,494 | 0.524986 |
[
[
[
"<script async src=\"https://www.googletagmanager.com/gtag/js?id=UA-59152712-8\"></script>\n<script>\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n\n gtag('config', 'UA-59152712-8');\n</script>\n\n# Convert LaTeX Sentence to SymPy Expression\n\n## Author: Ken Sible\n\n## The following module will demonstrate a recursive descent parser for LaTeX.\n\n### NRPy+ Source Code for this module:\n1. [latex_parser.py](../edit/latex_parser.py); [\\[**tutorial**\\]](Tutorial-LaTeX_SymPy_Conversion.ipynb) The latex_parser.py script will convert a LaTeX sentence to a SymPy expression using the following function: parse(sentence).",
"_____no_output_____"
],
[
"<a id='toc'></a>\n\n# Table of Contents\n$$\\label{toc}$$\n\n1. [Step 1](#intro): Introduction: Lexical Analysis and Syntax Analysis\n1. [Step 2](#sandbox): Demonstration and Sandbox (LaTeX Parser)\n1. [Step 3](#tensor): Tensor Support with Einstein Notation (WIP)\n1. [Step 4](#latex_pdf_output): $\\LaTeX$ PDF Output",
"_____no_output_____"
],
[
"<a id='intro'></a>\n\n# Step 1: Lexical Analysis and Syntax Analysis \\[Back to [top](#toc)\\]\n$$\\label{intro}$$\n\nIn the following section, we discuss [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (lexing) and [syntax analysis](https://en.wikipedia.org/wiki/Parsing) (parsing). In the process of lexical analysis, a lexer will tokenize a character string, called a sentence, using substring pattern matching (or tokenizing). We implemented a regex-based lexer for NRPy+, which does pattern matching using a [regular expression](https://en.wikipedia.org/wiki/Regular_expression) for each token pattern. In the process of syntax analysis, a parser will receive a token iterator from the lexer and build a parse tree containing all syntactic information of the language, as specified by a [formal grammar](https://en.wikipedia.org/wiki/Formal_grammar). We implemented a [recursive descent parser](https://en.wikipedia.org/wiki/Recursive_descent_parser) for NRPy+, which will build a parse tree in [preorder](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)), starting from the root [nonterminal](https://en.wikipedia.org/wiki/Terminal_and_nonterminal_symbols), using a [right recursive](https://en.wikipedia.org/wiki/Left_recursion) grammar. The following right recursive, [context-free grammar](https://en.wikipedia.org/wiki/Context-free_grammar) was written for parsing [LaTeX](https://en.wikipedia.org/wiki/LaTeX), adhering to the canonical (extended) [BNF](https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form) notation used for describing a context-free grammar:\n```\n<ROOT> -> <EXPRESSION> | <STRUCTURE> { <LINE_BREAK> <STRUCTURE> }*\n<STRUCTURE> -> <CONFIG> | <ENVIROMENT> | <ASSIGNMENT>\n<ENVIROMENT> -> <BEGIN_ALIGN> <ASSIGNMENT> { <LINE_BREAK> <ASSIGNMENT> }* <END_ALIGN>\n<ASSIGNMENT> -> <VARIABLE> = <EXPRESSION>\n<EXPRESSION> -> <TERM> { ( '+' | '-' ) <TERM> }*\n<TERM> -> <FACTOR> { [ '/' ] <FACTOR> }*\n<FACTOR> -> <BASE> { '^' <EXPONENT> }*\n<BASE> -> [ '-' ] ( <ATOM> | '(' <EXPRESSION> ')' | '[' <EXPRESSION> ']' )\n<EXPONENT> -> <BASE> | '{' <BASE> '}'\n<ATOM> -> <VARIABLE> | <NUMBER> | <COMMAND>\n<VARIABLE> -> <ARRAY> | <SYMBOL> [ '_' ( <SYMBOL> | <INTEGER> ) ]\n<NUMBER> -> <RATIONAL> | <DECIMAL> | <INTEGER>\n<COMMAND> -> <SQRT> | <FRAC>\n<SQRT> -> '\\\\sqrt' [ '[' <INTEGER> ']' ] '{' <EXPRESSION> '}'\n<FRAC> -> '\\\\frac' '{' <EXPRESSION> '}' '{' <EXPRESSION> '}'\n<CONFIG> -> '%' <ARRAY> '[' <INTEGER> ']' [ ':' <SYMMETRY> ] { ',' <ARRAY> '[' <INTEGER> ']' [ ':' <SYMMETRY> ] }*\n<ARRAY> -> ( <SYMBOL | <TENSOR> ) \n [ '_' ( <SYMBOL> | '{' { <SYMBOL> }+ '}' ) [ '^' ( <SYMBOL> | '{' { <SYMBOL> }+ '}' ) ]\n | '^' ( <SYMBOL> | '{' { <SYMBOL> }+ '}' ) [ '_' ( <SYMBOL> | '{' { <SYMBOL> }+ '}' ) ] ]\n```\n\n<small>**Source**: Robert W. Sebesta. Concepts of Programming Languages. Pearson Education Limited, 2016.</small>",
"_____no_output_____"
]
],
[
[
"from latex_parser import * # Import NRPy+ module for lexing and parsing LaTeX\nfrom sympy import srepr # Import SymPy function for expression tree representation",
"_____no_output_____"
],
[
"lexer = Lexer(); lexer.initialize(r'\\sqrt{5}(x + 2/3)^2')\nprint(', '.join(token for token in lexer.tokenize()))",
"SQRT_CMD, LEFT_BRACE, INTEGER, RIGHT_BRACE, LEFT_PAREN, SYMBOL, PLUS, RATIONAL, RIGHT_PAREN, CARET, INTEGER\n"
],
[
"expr = parse(r'\\sqrt{5}(x + 2/3)^2', expression=True)\nprint(expr, ':', srepr(expr))",
"sqrt(5)*(x + 2/3)**2 : Mul(Pow(Integer(5), Rational(1, 2)), Pow(Add(Symbol('x'), Rational(2, 3)), Integer(2)))\n"
]
],
[
[
"#### `Grammar Derivation: (x + 2/3)^2`\n```\n<EXPRESSION> -> <TERM>\n -> <FACTOR>\n -> <BASE>^<EXPONENT>\n -> (<EXPRESSION>)^<EXPONENT>\n -> (<TERM> + <TERM>)^<EXPONENT>\n -> (<FACTOR> + <TERM>)^<EXPONENT>\n -> (<BASE> + <TERM>)^<EXPONENT>\n -> (<ATOM> + <TERM>)^<EXPONENT>\n -> (<VARIABLE> + <TERM>)^<EXPONENT>\n -> (<SYMBOL> + <TERM>)^<EXPONENT>\n -> (x + <TERM>)^<EXPONENT>\n -> (x + <FACTOR>)^<EXPONENT>\n -> (x + <BASE>)^<EXPONENT>\n -> (x + <ATOM>)^<EXPONENT>\n -> (x + <NUMBER>)^<EXPONENT>\n -> (x + <RATIONAL>)^<EXPONENT>\n -> (x + 2/3)^<EXPONENT>\n -> (x + 2/3)^<BASE>\n -> (x + 2/3)^<ATOM>\n -> (x + 2/3)^<NUMBER>\n -> (x + 2/3)^<INTEGER>\n -> (x + 2/3)^2\n```",
"_____no_output_____"
],
[
"<a id='sandbox'></a>\n\n# Step 2: Demonstration and Sandbox (LaTeX Parser) \\[Back to [top](#toc)\\]\n$$\\label{sandbox}$$\n\nWe implemented a wrapper function for the `parse()` method that will accept a LaTeX sentence and return a SymPy expression. Furthermore, the entire parsing module was designed for extendibility. We apply the following procedure for extending parser functionality to include an unsupported LaTeX command: append that command to the grammar dictionary in the Lexer class with the mapping regex:token, write a grammar abstraction (similar to a regular expression) for that command, add the associated nonterminal (the command name) to the command abstraction in the Parser class, and finally implement the straightforward (private) method for parsing the grammar abstraction. We shall demonstrate the extension procedure using the `\\sqrt` LaTeX command.\n\n```<SQRT> -> '\\\\sqrt' [ '[' <INTEGER> ']' ] '{' <EXPRESSION> '}'```\n```\ndef _sqrt(self):\n if self.accept('LEFT_BRACKET'):\n integer = self.lexer.lexeme\n self.expect('INTEGER')\n root = Rational(1, integer)\n self.expect('RIGHT_BRACKET')\n else: root = Rational(1, 2)\n self.expect('LEFT_BRACE')\n expr = self.__expr()\n self.expect('RIGHT_BRACE')\n return Pow(expr, root)\n```",
"_____no_output_____"
]
],
[
[
"print(parse(r'\\sqrt[3]{\\alpha_0}', expression=True))",
"alpha_0**(1/3)\n"
]
],
[
[
"In addition to expression parsing, we included support for equation parsing, which will produce a dictionary mapping LHS $\\mapsto$ RHS, where LHS must be a symbol, and insert that mapping into the global namespace of the previous stack frame, as demonstrated below.",
"_____no_output_____"
]
],
[
[
"parse(r'x = n\\sqrt{2}^n'); print(x)",
"2**(n/2)*n\n"
]
],
[
[
"We implemented robust error messaging using the custom `ParseError` exception, which should handle every conceivable case to identify, as detailed as possible, invalid syntax inside of a LaTeX sentence. The following are runnable examples of possible error messages (simply uncomment and run the cell):",
"_____no_output_____"
]
],
[
[
"# parse(r'\\sqrt[*]{2}')\n # ParseError: \\sqrt[*]{2}\n # ^\n # unexpected '*' at position 6\n\n# parse(r'\\sqrt[0.5]{2}')\n # ParseError: \\sqrt[0.5]{2}\n # ^\n # expected token INTEGER at position 6\n\n# parse(r'\\command{}')\n # ParseError: \\command{}\n # ^\n # unsupported command '\\command' at position 0",
"_____no_output_____"
],
[
"from warnings import filterwarnings # Import Python function for warning suppression\nfilterwarnings('ignore', category=OverrideWarning); del Parser.namespace['x']",
"_____no_output_____"
]
],
[
[
"In the sandbox code cell below, you can experiment with the LaTeX parser using the wrapper function `parse(sentence)`, where sentence must be a [raw string](https://docs.python.org/3/reference/lexical_analysis.html) to interpret a backslash as a literal character rather than an [escape sequence](https://en.wikipedia.org/wiki/Escape_sequence).",
"_____no_output_____"
]
],
[
[
"# Write Sandbox Code Here",
"_____no_output_____"
]
],
[
[
"<a id='tensor'></a>\n\n# Step 3: Tensor Support with Einstein Notation (WIP) \\[Back to [top](#toc)\\]\n$$\\label{tensor}$$\n\nIn the following section, we demonstrate the current parser support for tensor notation using the Einstein summation convention. The first example will parse an equation for a tensor contraction, the second will parse an equation for raising an index using the metric tensor, and the third will parse an align enviroment with an equation dependency. In each example, every tensor should appear either on the LHS of an equation or inside of a configuration before appearing on the RHS of an equation. Moreover, the parser will raise an exception upon violation of the Einstein summation convention, i.e. an invalid free or bound index.\n\n**Configuration Syntax** `% <TENSOR> [<DIMENSION>]: <SYMMETRY>, <TENSOR> [<DIMENSION>]: <SYMMETRY>, ... ;`",
"_____no_output_____"
],
[
"#### Example 1\nLaTeX Source | Rendered LaTeX\n:----------- | :-------------\n<pre lang=\"latex\"> h = h^\\\\mu{}_\\\\mu </pre> | $$ h = h^\\mu{}_\\mu $$",
"_____no_output_____"
]
],
[
[
"parse(r\"\"\"\n % h^\\mu_\\mu [4]: nosym;\n h = h^\\mu{}_\\mu\n\"\"\")",
"_____no_output_____"
],
[
"print('h =', h)",
"h = hUD00 + hUD11 + hUD22 + hUD33\n"
]
],
[
[
"#### Example 2\nLaTeX Source | Rendered LaTeX\n:----------- | :-------------\n<pre lang=\"latex\"> v^\\\\mu = g^{\\\\mu\\\\nu}v_\\\\nu </pre> | $$ v^\\mu = g^{\\mu\\nu}v_\\nu $$",
"_____no_output_____"
]
],
[
[
"parse(r\"\"\"\n % g^{\\mu\\nu} [3]: metric, v_\\nu [3];\n v^\\mu = g^{\\mu\\nu}v_\\nu\n\"\"\")",
"_____no_output_____"
],
[
"print('vU =', vU)",
"vU = [gUU00*vD0 + gUU01*vD1 + gUU02*vD2, gUU01*vD0 + gUU11*vD1 + gUU12*vD2, gUU02*vD0 + gUU12*vD1 + gUU22*vD2]\n"
]
],
[
[
"#### Example 3\nLaTeX Source | Rendered LaTeX\n:----------- | :-------------\n<pre lang=\"latex\"> \\\\begin{align\\*}<br>    R &= g_{ab}R^{ab} \\\\\\\\ <br>    G^{ab} &= R^{ab} - \\\\frac{1}{2}g^{ab}R <br> \\\\end{align\\*} </pre> | $$ \\begin{align*} R &= g_{ab}R^{ab} \\\\ G^{ab} &= R^{ab} - \\frac{1}{2}g^{ab}R \\end{align*} $$",
"_____no_output_____"
]
],
[
[
"parse(r\"\"\"\n % g_{ab} [2]: metric, R^{ab} [2]: sym01;\n \\begin{align*}\n R &= g_{ab}R^{ab} \\\\\n G^{ab} &= R^{ab} - \\frac{1}{2}g^{ab}R\n \\end{align*}\n\"\"\")",
"_____no_output_____"
],
[
"print('R =', R)",
"R = RUU00*gDD00 + 2*RUU01*gDD01 + RUU11*gDD11\n"
],
[
"display(GUU)",
"_____no_output_____"
]
],
[
[
"The static variable `namespace` for the `Parser` class will provide access to the global namespace of the parser across each instance of the class.",
"_____no_output_____"
]
],
[
[
"Parser.namespace",
"_____no_output_____"
]
],
[
[
"We extended our robust error messaging using the custom `TensorError` exception, which should handle any inconsistent tensor dimension and any violation of the Einstein summation convention, specifically that a bound index must appear exactly once as a superscript and exactly once as a subscript in any single term and that a free index must appear in every term with the same position and cannot be summed over in any term. The following are runnable examples of possible error messages (simply uncomment and run the cell):",
"_____no_output_____"
]
],
[
[
"# parse(r\"\"\"\n# % h^{\\mu\\mu}_{\\mu\\mu} [4]: nosym;\n# h = h^{\\mu\\mu}_{\\mu\\mu}\n# \"\"\")\n # TensorError: illegal bound index\n\n# parse(r\"\"\"\n# % g^\\mu_\\nu [3]: sym01, v_\\nu [3];\n# v^\\mu = g^\\mu_\\nu v_\\nu\n# \"\"\")\n # TensorError: illegal bound index\n\n# parse(r\"\"\"\n# % g^{\\mu\\nu} [3]: sym01, v_\\mu [3], w_\\nu [3];\n# u^\\mu = g^{\\mu\\nu}(v_\\mu + w_\\nu)\n# \"\"\")\n # TensorError: unbalanced free index",
"_____no_output_____"
]
],
[
[
"<a id='latex_pdf_output'></a>\n\n# Step 4: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-LaTeX_SymPy_Conversion.pdf](Tutorial-LaTeX_SymPy_Conversion.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)",
"_____no_output_____"
]
],
[
[
"import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface\ncmd.output_Jupyter_notebook_to_LaTeXed_PDF(\"Tutorial-LaTeX_SymPy_Conversion\")",
"Created Tutorial-LaTeX_SymPy_Conversion.tex, and compiled LaTeX file to PDF\n file Tutorial-LaTeX_SymPy_Conversion.pdf\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"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a9190bd3bf120447aa3d3e4d7c6d84b1b087927
| 204,905 |
ipynb
|
Jupyter Notebook
|
completed/analyzing_data_with_pandas_notebook_complete.ipynb
|
thejqs/pycar
|
756c7fdc7b261a4e0cc50c6934a8da3a6dcdb614
|
[
"MIT"
] | 105 |
2015-02-03T22:28:09.000Z
|
2021-06-13T02:54:54.000Z
|
completed/analyzing_data_with_pandas_notebook_complete.ipynb
|
thejqs/pycar
|
756c7fdc7b261a4e0cc50c6934a8da3a6dcdb614
|
[
"MIT"
] | 62 |
2015-01-12T21:23:31.000Z
|
2019-03-28T16:57:22.000Z
|
completed/analyzing_data_with_pandas_notebook_complete.ipynb
|
thejqs/pycar
|
756c7fdc7b261a4e0cc50c6934a8da3a6dcdb614
|
[
"MIT"
] | 38 |
2015-02-06T21:33:24.000Z
|
2021-02-13T01:11:58.000Z
| 42.300784 | 11,404 | 0.433352 |
[
[
[
"# Analyzing data with Pandas",
"_____no_output_____"
],
[
"First a little setup. Importing the pandas library as ```pd```",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"Set some helpful display options. Uncomment the boilerplate in this cell.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\npd.set_option(\"max_columns\", 150)\npd.set_option('max_colwidth',40)\npd.options.display.float_format = '{:,.2f}'.format",
"_____no_output_____"
]
],
[
[
"open and read in the Master.csv and Salaries.csv tables in the ```data/2017/``` directory",
"_____no_output_____"
]
],
[
[
"master = pd.read_csv('../project3/data/2017/Master.csv') # File with player details\nsalary = pd.read_csv('../project3/data/2017/Salaries.csv') #File with baseball players' salaries",
"_____no_output_____"
]
],
[
[
"check to see what type each object is with `print(table_name)`. You can also use the ```.info()``` method to explore the data's structure.",
"_____no_output_____"
]
],
[
[
"master.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 18846 entries, 0 to 18845\nData columns (total 24 columns):\nplayerID 18846 non-null object\nbirthYear 18703 non-null float64\nbirthMonth 18531 non-null float64\nbirthDay 18382 non-null float64\nbirthCountry 18773 non-null object\nbirthState 18220 non-null object\nbirthCity 18647 non-null object\ndeathYear 9336 non-null float64\ndeathMonth 9335 non-null float64\ndeathDay 9334 non-null float64\ndeathCountry 9329 non-null object\ndeathState 9277 non-null object\ndeathCity 9325 non-null object\nnameFirst 18807 non-null object\nnameLast 18846 non-null object\nnameGiven 18807 non-null object\nweight 17975 non-null float64\nheight 18041 non-null float64\nbats 17655 non-null object\nthrows 17868 non-null object\ndebut 18653 non-null object\nfinalGame 18653 non-null object\nretroID 18792 non-null object\nbbrefID 18845 non-null object\ndtypes: float64(8), object(16)\nmemory usage: 3.5+ MB\n"
],
[
"salary.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 25575 entries, 0 to 25574\nData columns (total 5 columns):\nyearID 25575 non-null int64\nteamID 25575 non-null object\nlgID 25575 non-null object\nplayerID 25575 non-null object\nsalary 25575 non-null int64\ndtypes: int64(2), object(3)\nmemory usage: 999.1+ KB\n"
]
],
[
[
"print out sample data for each table with `table.head()`<br>\nsee additional options by pressing `tab` after you type the `head()` method",
"_____no_output_____"
]
],
[
[
"master.head()",
"_____no_output_____"
],
[
"salary.head()",
"_____no_output_____"
]
],
[
[
"Now we join the two csv's using `pd.merge`.<br>\nWe want to keep all the players names in the `master` data set<br>\neven if their salary is missing from the `salary` data set.<br>\nWe can always filter the NaN values out later",
"_____no_output_____"
]
],
[
[
"joined = pd.merge(left=master, right=salary, how=\"left\")",
"_____no_output_____"
]
],
[
[
"see what columns the `joined` table contains",
"_____no_output_____"
]
],
[
[
"joined.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 39455 entries, 0 to 39454\nData columns (total 28 columns):\nplayerID 39455 non-null object\nbirthYear 39312 non-null float64\nbirthMonth 39140 non-null float64\nbirthDay 38991 non-null float64\nbirthCountry 39382 non-null object\nbirthState 37738 non-null object\nbirthCity 39228 non-null object\ndeathYear 9669 non-null float64\ndeathMonth 9668 non-null float64\ndeathDay 9667 non-null float64\ndeathCountry 9662 non-null object\ndeathState 9603 non-null object\ndeathCity 9658 non-null object\nnameFirst 39416 non-null object\nnameLast 39455 non-null object\nnameGiven 39416 non-null object\nweight 38584 non-null float64\nheight 38650 non-null float64\nbats 38264 non-null object\nthrows 38477 non-null object\ndebut 39262 non-null object\nfinalGame 39262 non-null object\nretroID 39401 non-null object\nbbrefID 39454 non-null object\nyearID 25567 non-null float64\nteamID 25567 non-null object\nlgID 25567 non-null object\nsalary 25567 non-null float64\ndtypes: float64(10), object(18)\nmemory usage: 8.7+ MB\n"
]
],
[
[
"check if all the players have a salary assigned. The easiest way is to deduct the length of the `joined` table from the `master` table",
"_____no_output_____"
]
],
[
[
"len(master) - len(joined)",
"_____no_output_____"
]
],
[
[
"Something went wrong. There are now more players in the `joined` data set than in the `master` data set.<br>\nSome entries probably got duplicated<br>\nLet's check if we have duplicate `playerIDs` by using `.value_counts()`",
"_____no_output_____"
]
],
[
[
"joined[\"playerID\"].value_counts()",
"_____no_output_____"
]
],
[
[
"Yep, we do.<br>\nLet's filter out an arbitrary player to see why there is duplication",
"_____no_output_____"
]
],
[
[
"joined[joined[\"playerID\"] == \"moyerja01\"]",
"_____no_output_____"
]
],
[
[
"As we can see, there are now salaries in the dataset for each year of the players carreer.<br>\nWe only want to have the most recent salary though.<br>\nWe therefore need to 'deduplicate' the data set.",
"_____no_output_____"
],
[
"But first, let's make sure we get the newest year. We can do this by sorting the data on the newest entry",
"_____no_output_____"
]
],
[
[
"joined = joined.sort_values([\"playerID\",\"yearID\"])",
"_____no_output_____"
]
],
[
[
"Now we deduplicate",
"_____no_output_____"
]
],
[
[
"deduplicated = joined.drop_duplicates(\"playerID\", keep=\"last\")",
"_____no_output_____"
]
],
[
[
"And let's do the check again",
"_____no_output_____"
]
],
[
[
"len(master) - len(deduplicated)",
"_____no_output_____"
]
],
[
[
"Now we van get into the interesting part: analysis!",
"_____no_output_____"
],
[
"## What is the average (mean, median, max, min) salary?",
"_____no_output_____"
]
],
[
[
"deduplicated[\"salary\"].describe()",
"_____no_output_____"
]
],
[
[
"## Who makes the most money?",
"_____no_output_____"
]
],
[
[
"max_salary = deduplicated[\"salary\"].max()",
"_____no_output_____"
],
[
"deduplicated[deduplicated[\"salary\"] == max_salary]",
"_____no_output_____"
]
],
[
[
"## What are the most common baseball players salaries?",
"_____no_output_____"
],
[
"Draw a histogram. <br>",
"_____no_output_____"
]
],
[
[
"deduplicated.hist(\"salary\")",
"_____no_output_____"
]
],
[
[
"We can do the same with the column `yearID` to see how recent our data is.<br>\nWe have 30 years in our data set, so we need to do some minor tweaking",
"_____no_output_____"
]
],
[
[
"deduplicated.hist(\"yearID\", bins=30)",
"_____no_output_____"
]
],
[
[
"## Who are the top 10% highest-paid players?",
"_____no_output_____"
],
[
"calculate the 90 percentile cutoff",
"_____no_output_____"
]
],
[
[
"top_10_p = deduplicated[\"salary\"].quantile(q=0.9)\ntop_10_p",
"_____no_output_____"
]
],
[
[
"filter out players that make more money than the cutoff",
"_____no_output_____"
]
],
[
[
"best_paid = deduplicated[deduplicated[\"salary\"] >= top_10_p]\nbest_paid",
"_____no_output_____"
]
],
[
[
"use the `nlargest` to see the top 10 best paid players",
"_____no_output_____"
]
],
[
[
"best_paid_top_10 = best_paid.nlargest(10, \"salary\")\nbest_paid_top_10",
"_____no_output_____"
]
],
[
[
"draw a chart",
"_____no_output_____"
]
],
[
[
"best_paid_top_10.plot(kind=\"barh\", x=\"nameLast\", y=\"salary\")",
"_____no_output_____"
]
],
[
[
"save the data",
"_____no_output_____"
]
],
[
[
"best_paid.to_csv('highest-paid.csv', index=False)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a91966466b8a2802b5321619ec62584a5d80391
| 49,356 |
ipynb
|
Jupyter Notebook
|
notebook/Visualization.ipynb
|
JuliaTagBot/LaserTag.jl
|
fed9afad9184311fb464dfff28e12a5a52faa24c
|
[
"MIT"
] | 5 |
2020-07-14T09:22:06.000Z
|
2022-03-27T17:21:38.000Z
|
notebook/Visualization.ipynb
|
JuliaTagBot/LaserTag.jl
|
fed9afad9184311fb464dfff28e12a5a52faa24c
|
[
"MIT"
] | 3 |
2018-09-25T19:44:14.000Z
|
2021-05-12T14:38:52.000Z
|
notebook/Visualization.ipynb
|
JuliaTagBot/LaserTag.jl
|
fed9afad9184311fb464dfff28e12a5a52faa24c
|
[
"MIT"
] | 6 |
2020-02-08T11:41:31.000Z
|
2022-02-26T14:05:14.000Z
| 89.251356 | 13,146 | 0.695133 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a91a6838a7351ff934a7597973341113c5431c4
| 13,310 |
ipynb
|
Jupyter Notebook
|
Weeks_1-2/Etivities/CS6462_Etivity_1a.ipynb
|
goksuturann/CS6462_SEM2_2021-2
|
78e6b01d49b32b8ff334ad22535cec0f86496dbc
|
[
"BSD-3-Clause"
] | null | null | null |
Weeks_1-2/Etivities/CS6462_Etivity_1a.ipynb
|
goksuturann/CS6462_SEM2_2021-2
|
78e6b01d49b32b8ff334ad22535cec0f86496dbc
|
[
"BSD-3-Clause"
] | null | null | null |
Weeks_1-2/Etivities/CS6462_Etivity_1a.ipynb
|
goksuturann/CS6462_SEM2_2021-2
|
78e6b01d49b32b8ff334ad22535cec0f86496dbc
|
[
"BSD-3-Clause"
] | null | null | null | 20.829421 | 137 | 0.398873 |
[
[
[
"<div>\n<img src=\"https://drive.google.com/uc?export=view&id=1vK33e_EqaHgBHcbRV_m38hx6IkG0blK_\" width=\"350\"/>\n</div> \n\n#**Artificial Intelligence - MSc**\n\n##CS6462 - PROBABILISTIC AND EXPLAINABLE AI \n\n###CS6462_Etivity_1a\n\n###Author: Enrique Naredo",
"_____no_output_____"
],
[
"##Rolling a Die",
"_____no_output_____"
],
[
"Code in the cells are only hints and you must verify its correct implementation.\n\nLab_1.1",
"_____no_output_____"
],
[
"###Imports",
"_____no_output_____"
],
[
"Add any library you require.",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nimport \n\n\n\n",
"_____no_output_____"
]
],
[
[
"###Random generator",
"_____no_output_____"
],
[
"Write a code to get one integer from 1 to 6, randomly chosen to simulate a die.",
"_____no_output_____"
]
],
[
[
"# Here your code\n\ndef DieRoller():\n\n\n\n return number",
"_____no_output_____"
]
],
[
[
"### Roll a die N times",
"_____no_output_____"
],
[
"Write a code to roll a six-sided die N times",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nN = 10000000\n\nfor i in range(N): \n\n # use your previous function\n face[i] = DieRoller()\n\n # increment counter\n frequency[face] += 1\n\n",
"_____no_output_____"
]
],
[
[
"###Print frequency",
"_____no_output_____"
],
[
"Display frequency for each face.",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nprint('Face', \"Frequency\")\n\nfor :\n print()\n\n",
"_____no_output_____"
]
],
[
[
"### Plot a histogram",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nsns.displot(frequency, kde = False)\nplt.title(\"Histogram of simulated dice rolls\")\nplt.xlim([0,7])",
"_____no_output_____"
]
],
[
[
"### Dice rolling simulator",
"_____no_output_____"
],
[
"Use the nicer Dice rolling simulator from the Lab_1.1.\n\n* Do not use the while loop (code line 63), because you already have a random generator.\n",
"_____no_output_____"
]
],
[
[
"# Here your code\n\n\n# string var\nx = \"y\"\n\n# dictionary\nface = {\n# case 1\n1: (\n\t\t\"┌─────────┐\\n\"\n\t\t\"│ │\\n\"\n\t\t\"│ ● │\\n\"\n\t\t\"│ │\\n\"\n\t\t\"└─────────┘\\n\"\n\t),\n\n\n\n\n\n ",
"_____no_output_____"
]
],
[
[
"###Show first events",
"_____no_output_____"
],
[
"Show the first 10 events using the nicer Dice rolling simulator from the Lab_1.1",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nfor :\n\n print(face[number])\n\n\n ",
"_____no_output_____"
]
],
[
[
"###Expected value",
"_____no_output_____"
],
[
"\n**Expected value of a dice roll.**\n\nThe expected value of a dice roll is\n$$ \\sum_{i=1}^6 i \\times \\frac{1}{6} = 3.5 $$\n\nThat means that if we toss a dice a large number of times, the mean value should converge to 3.5.",
"_____no_output_____"
]
],
[
[
"# Here your code\n\n# N could be same from the previous cells\nN = \nroll = np.zeros(N, dtype=int)\nexpectation = np.zeros(N)\n\n# you could use your previous results \n# face[i]\n\nfor i in range(1, N):\n expectation[i] = np.mean(face[0:i])\n\nplt.plot(expectation)\nplt.title(\"Expectation of a dice roll\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"##Card Probabilities",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nimport\n\n\n",
"_____no_output_____"
],
[
"# Here your code\n\n# define the number of events\nM =\n",
"_____no_output_____"
]
],
[
[
"###Deck of Cards",
"_____no_output_____"
],
[
"Use the code from the Lab_2.2 to run 4 experiments related to the questions.\n\n* Address the questions using the code from the Lab_2.2\n* Add code line to save the frequency of the event for each question.\n* In the last cells add a code to print the frequency of the events for each question.\n* Finally, plot a histogram with the results.",
"_____no_output_____"
],
[
"Generate a Deck of Cards uaing the code from the Lab_2.2",
"_____no_output_____"
]
],
[
[
"# Here your code\n\n# make a deck of cards\ndeck = \n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"##Question 1",
"_____no_output_____"
],
[
"What is the probability that when two cards are drawn from a deck of cards without a replacement that both of them will be Ace?",
"_____no_output_____"
]
],
[
[
"# Here your code\n\n\n\n",
"_____no_output_____"
]
],
[
[
"###Question 2",
"_____no_output_____"
],
[
"What is the probability of two Aces in 5 card hand without replacement",
"_____no_output_____"
]
],
[
[
"# Here your code\n\n\n\n",
"_____no_output_____"
]
],
[
[
"###Question 3\n",
"_____no_output_____"
],
[
"What is the probability of being dealt a flush (5 cards of all the same suit) from the first 5 cards in a deck?",
"_____no_output_____"
]
],
[
[
"# Here your code\n\n\n\n",
"_____no_output_____"
]
],
[
[
"###Question 4",
"_____no_output_____"
],
[
"What is the probability of being dealt a royal flush from the first 5 cards in a deck?",
"_____no_output_____"
]
],
[
[
"# Here your code\n\n\n\n",
"_____no_output_____"
]
],
[
[
"###Print frequency",
"_____no_output_____"
],
[
"Display frequency for each face.",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nprint('Questions', \"Frequency\")\n\nfor :\n print()\n\n",
"_____no_output_____"
]
],
[
[
"### Plot a histogram",
"_____no_output_____"
]
],
[
[
"# Here your code\n\nsns.displot(frequency, kde = False)\nplt.title(\"Histogram of Questions\")\nplt.xlim([0,7])",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a91b6b3bf36e092929c74b9d1a15bb2ea47dbdc
| 30,215 |
ipynb
|
Jupyter Notebook
|
src/project_alt.ipynb
|
lechemrc/CS-Build-Week
|
81412c5fe572ac12f4860e9f7acb8641d8553929
|
[
"MIT"
] | null | null | null |
src/project_alt.ipynb
|
lechemrc/CS-Build-Week
|
81412c5fe572ac12f4860e9f7acb8641d8553929
|
[
"MIT"
] | null | null | null |
src/project_alt.ipynb
|
lechemrc/CS-Build-Week
|
81412c5fe572ac12f4860e9f7acb8641d8553929
|
[
"MIT"
] | null | null | null | 256.059322 | 21,030 | 0.815257 |
[
[
[
"# College Score Card data analysis using *K Means Clustering*\n\nSource:<br> \nhttps://collegescorecard.ed.gov/data/ <br><br>\nData Dictionary and Technical Docs: <br>\nhttps://collegescorecard.ed.gov/data/documentation/ <br><br>",
"_____no_output_____"
]
],
[
[
"# Base libraries\nimport numpy as np\nimport scipy as sp\n\n# Visualization libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n# Algorithm testing libraries\nfrom sklearn.cluster import KMeans",
"_____no_output_____"
],
[
"url = 'https://ed-public-download.app.cloud.gov/downloads/Most-Recent-Cohorts-All-Data-Elements.csv'\n\ndf = pd.read_csv(url)",
"_____no_output_____"
],
[
"print(f'Rows: {len(df)}')\nprint(f'Columns: {len(df.columns)}')\ndf.head()",
"Rows: 6806\nColumns: 1986\n"
],
[
"column_list = df.columns\nfor item in column_list:\n print(item)",
"IG_YR4_RT\nFIRSTGEN_UNKN_4YR_TRANS_YR4_RT\nFIRSTGEN_UNKN_2YR_TRANS_YR4_RT\nNOT1STGEN_DEATH_YR4_RT\nNOT1STGEN_COMP_ORIG_YR4_RT\nNOT1STGEN_COMP_4YR_TRANS_YR4_RT\nNOT1STGEN_COMP_2YR_TRANS_YR4_RT\nNOT1STGEN_WDRAW_ORIG_YR4_RT\nNOT1STGEN_WDRAW_4YR_TRANS_YR4_RT\nNOT1STGEN_WDRAW_2YR_TRANS_YR4_RT\nNOT1STGEN_ENRL_ORIG_YR4_RT\nNOT1STGEN_ENRL_4YR_TRANS_YR4_RT\nNOT1STGEN_ENRL_2YR_TRANS_YR4_RT\nNOT1STGEN_UNKN_ORIG_YR4_RT\nNOT1STGEN_UNKN_4YR_TRANS_YR4_RT\nNOT1STGEN_UNKN_2YR_TRANS_YR4_RT\nDEATH_YR6_RT\nCOMP_ORIG_YR6_RT\nCOMP_4YR_TRANS_YR6_RT\nCOMP_2YR_TRANS_YR6_RT\nWDRAW_ORIG_YR6_RT\nWDRAW_4YR_TRANS_YR6_RT\nWDRAW_2YR_TRANS_YR6_RT\nENRL_ORIG_YR6_RT\nENRL_4YR_TRANS_YR6_RT\nENRL_2YR_TRANS_YR6_RT\nUNKN_ORIG_YR6_RT\nUNKN_4YR_TRANS_YR6_RT\nUNKN_2YR_TRANS_YR6_RT\nLO_INC_DEATH_YR6_RT\nLO_INC_COMP_ORIG_YR6_RT\nLO_INC_COMP_4YR_TRANS_YR6_RT\nLO_INC_COMP_2YR_TRANS_YR6_RT\nLO_INC_WDRAW_ORIG_YR6_RT\nLO_INC_WDRAW_4YR_TRANS_YR6_RT\nLO_INC_WDRAW_2YR_TRANS_YR6_RT\nLO_INC_ENRL_ORIG_YR6_RT\nLO_INC_ENRL_4YR_TRANS_YR6_RT\nLO_INC_ENRL_2YR_TRANS_YR6_RT\nLO_INC_UNKN_ORIG_YR6_RT\nLO_INC_UNKN_4YR_TRANS_YR6_RT\nLO_INC_UNKN_2YR_TRANS_YR6_RT\nMD_INC_DEATH_YR6_RT\nMD_INC_COMP_ORIG_YR6_RT\nMD_INC_COMP_4YR_TRANS_YR6_RT\nMD_INC_COMP_2YR_TRANS_YR6_RT\nMD_INC_WDRAW_ORIG_YR6_RT\nMD_INC_WDRAW_4YR_TRANS_YR6_RT\nMD_INC_WDRAW_2YR_TRANS_YR6_RT\nMD_INC_ENRL_ORIG_YR6_RT\nMD_INC_ENRL_4YR_TRANS_YR6_RT\nMD_INC_ENRL_2YR_TRANS_YR6_RT\nMD_INC_UNKN_ORIG_YR6_RT\nMD_INC_UNKN_4YR_TRANS_YR6_RT\nMD_INC_UNKN_2YR_TRANS_YR6_RT\nHI_INC_DEATH_YR6_RT\nHI_INC_COMP_ORIG_YR6_RT\nHI_INC_COMP_4YR_TRANS_YR6_RT\nHI_INC_COMP_2YR_TRANS_YR6_RT\nHI_INC_WDRAW_ORIG_YR6_RT\nHI_INC_WDRAW_4YR_TRANS_YR6_RT\nHI_INC_WDRAW_2YR_TRANS_YR6_RT\nHI_INC_ENRL_ORIG_YR6_RT\nHI_INC_ENRL_4YR_TRANS_YR6_RT\nHI_INC_ENRL_2YR_TRANS_YR6_RT\nHI_INC_UNKN_ORIG_YR6_RT\nHI_INC_UNKN_4YR_TRANS_YR6_RT\nHI_INC_UNKN_2YR_TRANS_YR6_RT\nDEP_DEATH_YR6_RT\nDEP_COMP_ORIG_YR6_RT\nDEP_COMP_4YR_TRANS_YR6_RT\nDEP_COMP_2YR_TRANS_YR6_RT\nDEP_WDRAW_ORIG_YR6_RT\nDEP_WDRAW_4YR_TRANS_YR6_RT\nDEP_WDRAW_2YR_TRANS_YR6_RT\nDEP_ENRL_ORIG_YR6_RT\nDEP_ENRL_4YR_TRANS_YR6_RT\nDEP_ENRL_2YR_TRANS_YR6_RT\nDEP_UNKN_ORIG_YR6_RT\nDEP_UNKN_4YR_TRANS_YR6_RT\nDEP_UNKN_2YR_TRANS_YR6_RT\nIND_DEATH_YR6_RT\nIND_COMP_ORIG_YR6_RT\nIND_COMP_4YR_TRANS_YR6_RT\nIND_COMP_2YR_TRANS_YR6_RT\nIND_WDRAW_ORIG_YR6_RT\nIND_WDRAW_4YR_TRANS_YR6_RT\nIND_WDRAW_2YR_TRANS_YR6_RT\nIND_ENRL_ORIG_YR6_RT\nIND_ENRL_4YR_TRANS_YR6_RT\nIND_ENRL_2YR_TRANS_YR6_RT\nIND_UNKN_ORIG_YR6_RT\nIND_UNKN_4YR_TRANS_YR6_RT\nIND_UNKN_2YR_TRANS_YR6_RT\nFEMALE_DEATH_YR6_RT\nFEMALE_COMP_ORIG_YR6_RT\nFEMALE_COMP_4YR_TRANS_YR6_RT\nFEMALE_COMP_2YR_TRANS_YR6_RT\nFEMALE_WDRAW_ORIG_YR6_RT\nFEMALE_WDRAW_4YR_TRANS_YR6_RT\nFEMALE_WDRAW_2YR_TRANS_YR6_RT\nFEMALE_ENRL_ORIG_YR6_RT\nFEMALE_ENRL_4YR_TRANS_YR6_RT\nFEMALE_ENRL_2YR_TRANS_YR6_RT\nFEMALE_UNKN_ORIG_YR6_RT\nFEMALE_UNKN_4YR_TRANS_YR6_RT\nFEMALE_UNKN_2YR_TRANS_YR6_RT\nMALE_DEATH_YR6_RT\nMALE_COMP_ORIG_YR6_RT\nMALE_COMP_4YR_TRANS_YR6_RT\nMALE_COMP_2YR_TRANS_YR6_RT\nMALE_WDRAW_ORIG_YR6_RT\nMALE_WDRAW_4YR_TRANS_YR6_RT\nMALE_WDRAW_2YR_TRANS_YR6_RT\nMALE_ENRL_ORIG_YR6_RT\nMALE_ENRL_4YR_TRANS_YR6_RT\nMALE_ENRL_2YR_TRANS_YR6_RT\nMALE_UNKN_ORIG_YR6_RT\nMALE_UNKN_4YR_TRANS_YR6_RT\nMALE_UNKN_2YR_TRANS_YR6_RT\nPELL_DEATH_YR6_RT\nPELL_COMP_ORIG_YR6_RT\nPELL_COMP_4YR_TRANS_YR6_RT\nPELL_COMP_2YR_TRANS_YR6_RT\nPELL_WDRAW_ORIG_YR6_RT\nPELL_WDRAW_4YR_TRANS_YR6_RT\nPELL_WDRAW_2YR_TRANS_YR6_RT\nPELL_ENRL_ORIG_YR6_RT\nPELL_ENRL_4YR_TRANS_YR6_RT\nPELL_ENRL_2YR_TRANS_YR6_RT\nPELL_UNKN_ORIG_YR6_RT\nPELL_UNKN_4YR_TRANS_YR6_RT\nPELL_UNKN_2YR_TRANS_YR6_RT\nNOPELL_DEATH_YR6_RT\nNOPELL_COMP_ORIG_YR6_RT\nNOPELL_COMP_4YR_TRANS_YR6_RT\nNOPELL_COMP_2YR_TRANS_YR6_RT\nNOPELL_WDRAW_ORIG_YR6_RT\nNOPELL_WDRAW_4YR_TRANS_YR6_RT\nNOPELL_WDRAW_2YR_TRANS_YR6_RT\nNOPELL_ENRL_ORIG_YR6_RT\nNOPELL_ENRL_4YR_TRANS_YR6_RT\nNOPELL_ENRL_2YR_TRANS_YR6_RT\nNOPELL_UNKN_ORIG_YR6_RT\nNOPELL_UNKN_4YR_TRANS_YR6_RT\nNOPELL_UNKN_2YR_TRANS_YR6_RT\nLOAN_DEATH_YR6_RT\nLOAN_COMP_ORIG_YR6_RT\nLOAN_COMP_4YR_TRANS_YR6_RT\nLOAN_COMP_2YR_TRANS_YR6_RT\nLOAN_WDRAW_ORIG_YR6_RT\nLOAN_WDRAW_4YR_TRANS_YR6_RT\nLOAN_WDRAW_2YR_TRANS_YR6_RT\nLOAN_ENRL_ORIG_YR6_RT\nLOAN_ENRL_4YR_TRANS_YR6_RT\nLOAN_ENRL_2YR_TRANS_YR6_RT\nLOAN_UNKN_ORIG_YR6_RT\nLOAN_UNKN_4YR_TRANS_YR6_RT\nLOAN_UNKN_2YR_TRANS_YR6_RT\nNOLOAN_DEATH_YR6_RT\nNOLOAN_COMP_ORIG_YR6_RT\nNOLOAN_COMP_4YR_TRANS_YR6_RT\nNOLOAN_COMP_2YR_TRANS_YR6_RT\nNOLOAN_WDRAW_ORIG_YR6_RT\nNOLOAN_WDRAW_4YR_TRANS_YR6_RT\nNOLOAN_WDRAW_2YR_TRANS_YR6_RT\nNOLOAN_ENRL_ORIG_YR6_RT\nNOLOAN_ENRL_4YR_TRANS_YR6_RT\nNOLOAN_ENRL_2YR_TRANS_YR6_RT\nNOLOAN_UNKN_ORIG_YR6_RT\nNOLOAN_UNKN_4YR_TRANS_YR6_RT\nNOLOAN_UNKN_2YR_TRANS_YR6_RT\nFIRSTGEN_DEATH_YR6_RT\nFIRSTGEN_COMP_ORIG_YR6_RT\nFIRSTGEN_COMP_4YR_TRANS_YR6_RT\nFIRSTGEN_COMP_2YR_TRANS_YR6_RT\nFIRSTGEN_WDRAW_ORIG_YR6_RT\nFIRSTGEN_WDRAW_4YR_TRANS_YR6_RT\nFIRSTGEN_WDRAW_2YR_TRANS_YR6_RT\nFIRSTGEN_ENRL_ORIG_YR6_RT\nFIRSTGEN_ENRL_4YR_TRANS_YR6_RT\nFIRSTGEN_ENRL_2YR_TRANS_YR6_RT\nFIRSTGEN_UNKN_ORIG_YR6_RT\nFIRSTGEN_UNKN_4YR_TRANS_YR6_RT\nFIRSTGEN_UNKN_2YR_TRANS_YR6_RT\nNOT1STGEN_DEATH_YR6_RT\nNOT1STGEN_COMP_ORIG_YR6_RT\nNOT1STGEN_COMP_4YR_TRANS_YR6_RT\nNOT1STGEN_COMP_2YR_TRANS_YR6_RT\nNOT1STGEN_WDRAW_ORIG_YR6_RT\nNOT1STGEN_WDRAW_4YR_TRANS_YR6_RT\nNOT1STGEN_WDRAW_2YR_TRANS_YR6_RT\nNOT1STGEN_ENRL_ORIG_YR6_RT\nNOT1STGEN_ENRL_4YR_TRANS_YR6_RT\nNOT1STGEN_ENRL_2YR_TRANS_YR6_RT\nNOT1STGEN_UNKN_ORIG_YR6_RT\nNOT1STGEN_UNKN_4YR_TRANS_YR6_RT\nNOT1STGEN_UNKN_2YR_TRANS_YR6_RT\nDEATH_YR8_RT\nCOMP_ORIG_YR8_RT\nCOMP_4YR_TRANS_YR8_RT\nCOMP_2YR_TRANS_YR8_RT\nWDRAW_ORIG_YR8_RT\nWDRAW_4YR_TRANS_YR8_RT\nWDRAW_2YR_TRANS_YR8_RT\nENRL_ORIG_YR8_RT\nENRL_4YR_TRANS_YR8_RT\nENRL_2YR_TRANS_YR8_RT\nUNKN_ORIG_YR8_RT\nUNKN_4YR_TRANS_YR8_RT\nUNKN_2YR_TRANS_YR8_RT\nLO_INC_DEATH_YR8_RT\nLO_INC_COMP_ORIG_YR8_RT\nLO_INC_COMP_4YR_TRANS_YR8_RT\nLO_INC_COMP_2YR_TRANS_YR8_RT\nLO_INC_WDRAW_ORIG_YR8_RT\nLO_INC_WDRAW_4YR_TRANS_YR8_RT\nLO_INC_WDRAW_2YR_TRANS_YR8_RT\nLO_INC_ENRL_ORIG_YR8_RT\nLO_INC_ENRL_4YR_TRANS_YR8_RT\nLO_INC_ENRL_2YR_TRANS_YR8_RT\nLO_INC_UNKN_ORIG_YR8_RT\nLO_INC_UNKN_4YR_TRANS_YR8_RT\nLO_INC_UNKN_2YR_TRANS_YR8_RT\nMD_INC_DEATH_YR8_RT\nMD_INC_COMP_ORIG_YR8_RT\nMD_INC_COMP_4YR_TRANS_YR8_RT\nMD_INC_COMP_2YR_TRANS_YR8_RT\nMD_INC_WDRAW_ORIG_YR8_RT\nMD_INC_WDRAW_4YR_TRANS_YR8_RT\nMD_INC_WDRAW_2YR_TRANS_YR8_RT\nMD_INC_ENRL_ORIG_YR8_RT\nMD_INC_ENRL_4YR_TRANS_YR8_RT\nMD_INC_ENRL_2YR_TRANS_YR8_RT\nMD_INC_UNKN_ORIG_YR8_RT\nMD_INC_UNKN_4YR_TRANS_YR8_RT\nMD_INC_UNKN_2YR_TRANS_YR8_RT\nHI_INC_DEATH_YR8_RT\nHI_INC_COMP_ORIG_YR8_RT\nHI_INC_COMP_4YR_TRANS_YR8_RT\nHI_INC_COMP_2YR_TRANS_YR8_RT\nHI_INC_WDRAW_ORIG_YR8_RT\nHI_INC_WDRAW_4YR_TRANS_YR8_RT\nHI_INC_WDRAW_2YR_TRANS_YR8_RT\nHI_INC_ENRL_ORIG_YR8_RT\nHI_INC_ENRL_4YR_TRANS_YR8_RT\nHI_INC_ENRL_2YR_TRANS_YR8_RT\nHI_INC_UNKN_ORIG_YR8_RT\nHI_INC_UNKN_4YR_TRANS_YR8_RT\nHI_INC_UNKN_2YR_TRANS_YR8_RT\nDEP_DEATH_YR8_RT\nDEP_COMP_ORIG_YR8_RT\nDEP_COMP_4YR_TRANS_YR8_RT\nDEP_COMP_2YR_TRANS_YR8_RT\nDEP_WDRAW_ORIG_YR8_RT\nDEP_WDRAW_4YR_TRANS_YR8_RT\nDEP_WDRAW_2YR_TRANS_YR8_RT\nDEP_ENRL_ORIG_YR8_RT\nDEP_ENRL_4YR_TRANS_YR8_RT\nDEP_ENRL_2YR_TRANS_YR8_RT\nDEP_UNKN_ORIG_YR8_RT\nDEP_UNKN_4YR_TRANS_YR8_RT\nDEP_UNKN_2YR_TRANS_YR8_RT\nIND_DEATH_YR8_RT\nIND_COMP_ORIG_YR8_RT\nIND_COMP_4YR_TRANS_YR8_RT\nIND_COMP_2YR_TRANS_YR8_RT\nIND_WDRAW_ORIG_YR8_RT\nIND_WDRAW_4YR_TRANS_YR8_RT\nIND_WDRAW_2YR_TRANS_YR8_RT\nIND_ENRL_ORIG_YR8_RT\nIND_ENRL_4YR_TRANS_YR8_RT\nIND_ENRL_2YR_TRANS_YR8_RT\nIND_UNKN_ORIG_YR8_RT\nIND_UNKN_4YR_TRANS_YR8_RT\nIND_UNKN_2YR_TRANS_YR8_RT\nFEMALE_DEATH_YR8_RT\nFEMALE_COMP_ORIG_YR8_RT\nFEMALE_COMP_4YR_TRANS_YR8_RT\nFEMALE_COMP_2YR_TRANS_YR8_RT\nFEMALE_WDRAW_ORIG_YR8_RT\nFEMALE_WDRAW_4YR_TRANS_YR8_RT\nFEMALE_WDRAW_2YR_TRANS_YR8_RT\nFEMALE_ENRL_ORIG_YR8_RT\nFEMALE_ENRL_4YR_TRANS_YR8_RT\nFEMALE_ENRL_2YR_TRANS_YR8_RT\nFEMALE_UNKN_ORIG_YR8_RT\nFEMALE_UNKN_4YR_TRANS_YR8_RT\nFEMALE_UNKN_2YR_TRANS_YR8_RT\nMALE_DEATH_YR8_RT\nMALE_COMP_ORIG_YR8_RT\nMALE_COMP_4YR_TRANS_YR8_RT\nMALE_COMP_2YR_TRANS_YR8_RT\nMALE_WDRAW_ORIG_YR8_RT\nMALE_WDRAW_4YR_TRANS_YR8_RT\nMALE_WDRAW_2YR_TRANS_YR8_RT\nMALE_ENRL_ORIG_YR8_RT\nMALE_ENRL_4YR_TRANS_YR8_RT\nMALE_ENRL_2YR_TRANS_YR8_RT\nMALE_UNKN_ORIG_YR8_RT\nMALE_UNKN_4YR_TRANS_YR8_RT\nMALE_UNKN_2YR_TRANS_YR8_RT\nPELL_DEATH_YR8_RT\nPELL_COMP_ORIG_YR8_RT\nPELL_COMP_4YR_TRANS_YR8_RT\nPELL_COMP_2YR_TRANS_YR8_RT\nPELL_WDRAW_ORIG_YR8_RT\nPELL_WDRAW_4YR_TRANS_YR8_RT\nPELL_WDRAW_2YR_TRANS_YR8_RT\nPELL_ENRL_ORIG_YR8_RT\nPELL_ENRL_4YR_TRANS_YR8_RT\nPELL_ENRL_2YR_TRANS_YR8_RT\nPELL_UNKN_ORIG_YR8_RT\nPELL_UNKN_4YR_TRANS_YR8_RT\nPELL_UNKN_2YR_TRANS_YR8_RT\nNOPELL_DEATH_YR8_RT\nNOPELL_COMP_ORIG_YR8_RT\nNOPELL_COMP_4YR_TRANS_YR8_RT\nNOPELL_COMP_2YR_TRANS_YR8_RT\nNOPELL_WDRAW_ORIG_YR8_RT\nNOPELL_WDRAW_4YR_TRANS_YR8_RT\nNOPELL_WDRAW_2YR_TRANS_YR8_RT\nNOPELL_ENRL_ORIG_YR8_RT\nNOPELL_ENRL_4YR_TRANS_YR8_RT\nNOPELL_ENRL_2YR_TRANS_YR8_RT\nNOPELL_UNKN_ORIG_YR8_RT\nNOPELL_UNKN_4YR_TRANS_YR8_RT\nNOPELL_UNKN_2YR_TRANS_YR8_RT\nLOAN_DEATH_YR8_RT\nLOAN_COMP_ORIG_YR8_RT\nLOAN_COMP_4YR_TRANS_YR8_RT\nLOAN_COMP_2YR_TRANS_YR8_RT\nLOAN_WDRAW_ORIG_YR8_RT\nLOAN_WDRAW_4YR_TRANS_YR8_RT\nLOAN_WDRAW_2YR_TRANS_YR8_RT\nLOAN_ENRL_ORIG_YR8_RT\nLOAN_ENRL_4YR_TRANS_YR8_RT\nLOAN_ENRL_2YR_TRANS_YR8_RT\nLOAN_UNKN_ORIG_YR8_RT\nLOAN_UNKN_4YR_TRANS_YR8_RT\nLOAN_UNKN_2YR_TRANS_YR8_RT\nNOLOAN_DEATH_YR8_RT\nNOLOAN_COMP_ORIG_YR8_RT\nNOLOAN_COMP_4YR_TRANS_YR8_RT\nNOLOAN_COMP_2YR_TRANS_YR8_RT\nNOLOAN_WDRAW_ORIG_YR8_RT\nNOLOAN_WDRAW_4YR_TRANS_YR8_RT\nNOLOAN_WDRAW_2YR_TRANS_YR8_RT\nNOLOAN_ENRL_ORIG_YR8_RT\nNOLOAN_ENRL_4YR_TRANS_YR8_RT\nNOLOAN_ENRL_2YR_TRANS_YR8_RT\nNOLOAN_UNKN_ORIG_YR8_RT\nNOLOAN_UNKN_4YR_TRANS_YR8_RT\nNOLOAN_UNKN_2YR_TRANS_YR8_RT\nFIRSTGEN_DEATH_YR8_RT\nFIRSTGEN_COMP_ORIG_YR8_RT\nFIRSTGEN_COMP_4YR_TRANS_YR8_RT\nFIRSTGEN_COMP_2YR_TRANS_YR8_RT\nFIRSTGEN_WDRAW_ORIG_YR8_RT\nFIRSTGEN_WDRAW_4YR_TRANS_YR8_RT\nFIRSTGEN_WDRAW_2YR_TRANS_YR8_RT\nFIRSTGEN_ENRL_ORIG_YR8_RT\nFIRSTGEN_ENRL_4YR_TRANS_YR8_RT\nFIRSTGEN_ENRL_2YR_TRANS_YR8_RT\nFIRSTGEN_UNKN_ORIG_YR8_RT\nFIRSTGEN_UNKN_4YR_TRANS_YR8_RT\nFIRSTGEN_UNKN_2YR_TRANS_YR8_RT\nNOT1STGEN_DEATH_YR8_RT\nNOT1STGEN_COMP_ORIG_YR8_RT\nNOT1STGEN_COMP_4YR_TRANS_YR8_RT\nNOT1STGEN_COMP_2YR_TRANS_YR8_RT\nNOT1STGEN_WDRAW_ORIG_YR8_RT\nNOT1STGEN_WDRAW_4YR_TRANS_YR8_RT\nNOT1STGEN_WDRAW_2YR_TRANS_YR8_RT\nNOT1STGEN_ENRL_ORIG_YR8_RT\nNOT1STGEN_ENRL_4YR_TRANS_YR8_RT\nNOT1STGEN_ENRL_2YR_TRANS_YR8_RT\nNOT1STGEN_UNKN_ORIG_YR8_RT\nNOT1STGEN_UNKN_4YR_TRANS_YR8_RT\nNOT1STGEN_UNKN_2YR_TRANS_YR8_RT\nRPY_1YR_RT\nCOMPL_RPY_1YR_RT\nNONCOM_RPY_1YR_RT\nLO_INC_RPY_1YR_RT\nMD_INC_RPY_1YR_RT\nHI_INC_RPY_1YR_RT\nDEP_RPY_1YR_RT\nIND_RPY_1YR_RT\nPELL_RPY_1YR_RT\nNOPELL_RPY_1YR_RT\nFEMALE_RPY_1YR_RT\nMALE_RPY_1YR_RT\nFIRSTGEN_RPY_1YR_RT\nNOTFIRSTGEN_RPY_1YR_RT\nRPY_3YR_RT\nCOMPL_RPY_3YR_RT\nNONCOM_RPY_3YR_RT\nLO_INC_RPY_3YR_RT\nMD_INC_RPY_3YR_RT\nHI_INC_RPY_3YR_RT\nDEP_RPY_3YR_RT\nIND_RPY_3YR_RT\nPELL_RPY_3YR_RT\nNOPELL_RPY_3YR_RT\nFEMALE_RPY_3YR_RT\nMALE_RPY_3YR_RT\nFIRSTGEN_RPY_3YR_RT\nNOTFIRSTGEN_RPY_3YR_RT\nRPY_5YR_RT\nCOMPL_RPY_5YR_RT\nNONCOM_RPY_5YR_RT\nLO_INC_RPY_5YR_RT\nMD_INC_RPY_5YR_RT\nHI_INC_RPY_5YR_RT\nDEP_RPY_5YR_RT\nIND_RPY_5YR_RT\nPELL_RPY_5YR_RT\nNOPELL_RPY_5YR_RT\nFEMALE_RPY_5YR_RT\nMALE_RPY_5YR_RT\nFIRSTGEN_RPY_5YR_RT\nNOTFIRSTGEN_RPY_5YR_RT\nRPY_7YR_RT\nCOMPL_RPY_7YR_RT\nNONCOM_RPY_7YR_RT\nLO_INC_RPY_7YR_RT\nMD_INC_RPY_7YR_RT\nHI_INC_RPY_7YR_RT\nDEP_RPY_7YR_RT\nIND_RPY_7YR_RT\nPELL_RPY_7YR_RT\nNOPELL_RPY_7YR_RT\nFEMALE_RPY_7YR_RT\nMALE_RPY_7YR_RT\nFIRSTGEN_RPY_7YR_RT\nNOTFIRSTGEN_RPY_7YR_RT\nINC_PCT_LO\nDEP_STAT_PCT_IND\nDEP_INC_PCT_LO\nIND_INC_PCT_LO\nPAR_ED_PCT_1STGEN\nINC_PCT_M1\nINC_PCT_M2\nINC_PCT_H1\nINC_PCT_H2\nDEP_INC_PCT_M1\nDEP_INC_PCT_M2\nDEP_INC_PCT_H1\nDEP_INC_PCT_H2\nIND_INC_PCT_M1\nIND_INC_PCT_M2\nIND_INC_PCT_H1\nIND_INC_PCT_H2\nPAR_ED_PCT_MS\nPAR_ED_PCT_HS\nPAR_ED_PCT_PS\nAPPL_SCH_PCT_GE2\nAPPL_SCH_PCT_GE3\nAPPL_SCH_PCT_GE4\nAPPL_SCH_PCT_GE5\nDEP_INC_AVG\nIND_INC_AVG\nOVERALL_YR2_N\nLO_INC_YR2_N\nMD_INC_YR2_N\nHI_INC_YR2_N\nDEP_YR2_N\nIND_YR2_N\nFEMALE_YR2_N\nMALE_YR2_N\nPELL_YR2_N\nNOPELL_YR2_N\nLOAN_YR2_N\nNOLOAN_YR2_N\nFIRSTGEN_YR2_N\nNOT1STGEN_YR2_N\nOVERALL_YR3_N\nLO_INC_YR3_N\nMD_INC_YR3_N\nHI_INC_YR3_N\nDEP_YR3_N\nIND_YR3_N\nFEMALE_YR3_N\nMALE_YR3_N\nPELL_YR3_N\nNOPELL_YR3_N\nLOAN_YR3_N\nNOLOAN_YR3_N\nFIRSTGEN_YR3_N\nNOT1STGEN_YR3_N\nOVERALL_YR4_N\nLO_INC_YR4_N\nMD_INC_YR4_N\nHI_INC_YR4_N\nDEP_YR4_N\nIND_YR4_N\nFEMALE_YR4_N\nMALE_YR4_N\nPELL_YR4_N\nNOPELL_YR4_N\nLOAN_YR4_N\nNOLOAN_YR4_N\nFIRSTGEN_YR4_N\nNOT1STGEN_YR4_N\nOVERALL_YR6_N\nLO_INC_YR6_N\nMD_INC_YR6_N\nHI_INC_YR6_N\nDEP_YR6_N\nIND_YR6_N\nFEMALE_YR6_N\nMALE_YR6_N\nPELL_YR6_N\nNOPELL_YR6_N\nLOAN_YR6_N\nNOLOAN_YR6_N\nFIRSTGEN_YR6_N\nNOT1STGEN_YR6_N\nOVERALL_YR8_N\nLO_INC_YR8_N\nMD_INC_YR8_N\nHI_INC_YR8_N\nDEP_YR8_N\nIND_YR8_N\nFEMALE_YR8_N\nMALE_YR8_N\nPELL_YR8_N\nNOPELL_YR8_N\nLOAN_YR8_N\nNOLOAN_YR8_N\nFIRSTGEN_YR8_N\nNOT1STGEN_YR8_N\nDEBT_MDN\nGRAD_DEBT_MDN\nWDRAW_DEBT_MDN\nLO_INC_DEBT_MDN\nMD_INC_DEBT_MDN\nHI_INC_DEBT_MDN\nDEP_DEBT_MDN\nIND_DEBT_MDN\nPELL_DEBT_MDN\nNOPELL_DEBT_MDN\nFEMALE_DEBT_MDN\nMALE_DEBT_MDN\nFIRSTGEN_DEBT_MDN\nNOTFIRSTGEN_DEBT_MDN\nDEBT_N\nGRAD_DEBT_N\nWDRAW_DEBT_N\nLO_INC_DEBT_N\nMD_INC_DEBT_N\nHI_INC_DEBT_N\nDEP_DEBT_N\nIND_DEBT_N\nPELL_DEBT_N\nNOPELL_DEBT_N\nFEMALE_DEBT_N\nMALE_DEBT_N\nFIRSTGEN_DEBT_N\nNOTFIRSTGEN_DEBT_N\nGRAD_DEBT_MDN10YR\nCUML_DEBT_N\nCUML_DEBT_P90\nCUML_DEBT_P75\nCUML_DEBT_P25\nCUML_DEBT_P10\nINC_N\nDEP_INC_N\nIND_INC_N\nDEP_STAT_N\nPAR_ED_N\nAPPL_SCH_N\nREPAY_DT_MDN\nSEPAR_DT_MDN\nREPAY_DT_N\nSEPAR_DT_N\nRPY_1YR_N\nCOMPL_RPY_1YR_N\nNONCOM_RPY_1YR_N\nLO_INC_RPY_1YR_N\nMD_INC_RPY_1YR_N\nHI_INC_RPY_1YR_N\nDEP_RPY_1YR_N\nIND_RPY_1YR_N\nPELL_RPY_1YR_N\nNOPELL_RPY_1YR_N\nFEMALE_RPY_1YR_N\nMALE_RPY_1YR_N\nFIRSTGEN_RPY_1YR_N\nNOTFIRSTGEN_RPY_1YR_N\nRPY_3YR_N\nCOMPL_RPY_3YR_N\nNONCOM_RPY_3YR_N\nLO_INC_RPY_3YR_N\nMD_INC_RPY_3YR_N\nHI_INC_RPY_3YR_N\nDEP_RPY_3YR_N\nIND_RPY_3YR_N\nPELL_RPY_3YR_N\nNOPELL_RPY_3YR_N\nFEMALE_RPY_3YR_N\nMALE_RPY_3YR_N\nFIRSTGEN_RPY_3YR_N\nNOTFIRSTGEN_RPY_3YR_N\nRPY_5YR_N\nCOMPL_RPY_5YR_N\nNONCOM_RPY_5YR_N\nLO_INC_RPY_5YR_N\nMD_INC_RPY_5YR_N\nHI_INC_RPY_5YR_N\nDEP_RPY_5YR_N\nIND_RPY_5YR_N\nPELL_RPY_5YR_N\nNOPELL_RPY_5YR_N\nFEMALE_RPY_5YR_N\nMALE_RPY_5YR_N\nFIRSTGEN_RPY_5YR_N\nNOTFIRSTGEN_RPY_5YR_N\nRPY_7YR_N\nCOMPL_RPY_7YR_N\nNONCOM_RPY_7YR_N\nLO_INC_RPY_7YR_N\nMD_INC_RPY_7YR_N\nHI_INC_RPY_7YR_N\nDEP_RPY_7YR_N\nIND_RPY_7YR_N\nPELL_RPY_7YR_N\nNOPELL_RPY_7YR_N\nFEMALE_RPY_7YR_N\nMALE_RPY_7YR_N\nFIRSTGEN_RPY_7YR_N\nNOTFIRSTGEN_RPY_7YR_N\nCOUNT_ED\nLOAN_EVER\nPELL_EVER\nAGE_ENTRY\nAGE_ENTRY_SQ\nAGEGE24\nFEMALE\nMARRIED\nDEPENDENT\nVETERAN\nFIRST_GEN\nFAMINC\nMD_FAMINC\nFAMINC_IND\nLNFAMINC\nLNFAMINC_IND\nPCT_WHITE\nPCT_BLACK\nPCT_ASIAN\nPCT_HISPANIC\nPCT_BA\nPCT_GRAD_PROF\nPCT_BORN_US\nMEDIAN_HH_INC\nPOVERTY_RATE\nUNEMP_RATE\nLN_MEDIAN_HH_INC\nFSEND_COUNT\nFSEND_1\nFSEND_2\nFSEND_3\nFSEND_4\nFSEND_5\nCOUNT_NWNE_P10\nCOUNT_WNE_P10\nMN_EARN_WNE_P10\nMD_EARN_WNE_P10\nPCT10_EARN_WNE_P10\nPCT25_EARN_WNE_P10\nPCT75_EARN_WNE_P10\nPCT90_EARN_WNE_P10\nSD_EARN_WNE_P10\nCOUNT_WNE_INC1_P10\nCOUNT_WNE_INC2_P10\nCOUNT_WNE_INC3_P10\nCOUNT_WNE_INDEP0_INC1_P10\nCOUNT_WNE_INDEP0_P10\nCOUNT_WNE_INDEP1_P10\nCOUNT_WNE_MALE0_P10\nCOUNT_WNE_MALE1_P10\nGT_25K_P10\nMN_EARN_WNE_INC1_P10\nMN_EARN_WNE_INC2_P10\nMN_EARN_WNE_INC3_P10\nMN_EARN_WNE_INDEP0_INC1_P10\nMN_EARN_WNE_INDEP0_P10\nMN_EARN_WNE_INDEP1_P10\nMN_EARN_WNE_MALE0_P10\nMN_EARN_WNE_MALE1_P10\nCOUNT_NWNE_P6\nCOUNT_WNE_P6\nMN_EARN_WNE_P6\nMD_EARN_WNE_P6\nPCT10_EARN_WNE_P6\nPCT25_EARN_WNE_P6\nPCT75_EARN_WNE_P6\nPCT90_EARN_WNE_P6\nSD_EARN_WNE_P6\nCOUNT_WNE_INC1_P6\nCOUNT_WNE_INC2_P6\nCOUNT_WNE_INC3_P6\nCOUNT_WNE_INDEP0_INC1_P6\nCOUNT_WNE_INDEP0_P6\nCOUNT_WNE_INDEP1_P6\nCOUNT_WNE_MALE0_P6\nCOUNT_WNE_MALE1_P6\nGT_25K_P6\nMN_EARN_WNE_INC1_P6\nMN_EARN_WNE_INC2_P6\nMN_EARN_WNE_INC3_P6\nMN_EARN_WNE_INDEP0_INC1_P6\nMN_EARN_WNE_INDEP0_P6\nMN_EARN_WNE_INDEP1_P6\nMN_EARN_WNE_MALE0_P6\nMN_EARN_WNE_MALE1_P6\nCOUNT_NWNE_P7\nCOUNT_WNE_P7\nMN_EARN_WNE_P7\nSD_EARN_WNE_P7\nGT_25K_P7\nCOUNT_NWNE_P8\nCOUNT_WNE_P8\nMN_EARN_WNE_P8\nMD_EARN_WNE_P8\nPCT10_EARN_WNE_P8\nPCT25_EARN_WNE_P8\nPCT75_EARN_WNE_P8\nPCT90_EARN_WNE_P8\nSD_EARN_WNE_P8\nGT_25K_P8\nCOUNT_NWNE_P9\nCOUNT_WNE_P9\nMN_EARN_WNE_P9\nSD_EARN_WNE_P9\nGT_25K_P9\nDEBT_MDN_SUPP\nGRAD_DEBT_MDN_SUPP\nGRAD_DEBT_MDN10YR_SUPP\nRPY_3YR_RT_SUPP\nLO_INC_RPY_3YR_RT_SUPP\nMD_INC_RPY_3YR_RT_SUPP\nHI_INC_RPY_3YR_RT_SUPP\nCOMPL_RPY_3YR_RT_SUPP\nNONCOM_RPY_3YR_RT_SUPP\nDEP_RPY_3YR_RT_SUPP\nIND_RPY_3YR_RT_SUPP\nPELL_RPY_3YR_RT_SUPP\nNOPELL_RPY_3YR_RT_SUPP\nFEMALE_RPY_3YR_RT_SUPP\nMALE_RPY_3YR_RT_SUPP\nFIRSTGEN_RPY_3YR_RT_SUPP\nNOTFIRSTGEN_RPY_3YR_RT_SUPP\nC150_L4_POOLED_SUPP\nC150_4_POOLED_SUPP\nC200_L4_POOLED_SUPP\nC200_4_POOLED_SUPP\nALIAS\nC100_4\nD100_4\nC100_L4\nD100_L4\nTRANS_4\nDTRANS_4\nTRANS_L4\nDTRANS_L4\nICLEVEL\nUGDS_MEN\nUGDS_WOMEN\nCDR3_DENOM\nCDR2_DENOM\nT4APPROVALDATE\nD150_4_WHITE\nD150_4_BLACK\nD150_4_HISP\nD150_4_ASIAN\nD150_4_AIAN\nD150_4_NHPI\nD150_4_2MOR\nD150_4_NRA\nD150_4_UNKN\nD150_4_WHITENH\nD150_4_BLACKNH\nD150_4_API\nD150_4_AIANOLD\nD150_4_HISPOLD\nD150_L4_WHITE\nD150_L4_BLACK\nD150_L4_HISP\nD150_L4_ASIAN\nD150_L4_AIAN\nD150_L4_NHPI\nD150_L4_2MOR\nD150_L4_NRA\nD150_L4_UNKN\nD150_L4_WHITENH\nD150_L4_BLACKNH\nD150_L4_API\nD150_L4_AIANOLD\nD150_L4_HISPOLD\nD_PCTPELL_PCTFLOAN\nOPENADMP\nUGNONDS\nGRADS\nACCREDCODE\nOMACHT6_FTFT\nOMAWDP6_FTFT\nOMACHT8_FTFT\nOMAWDP8_FTFT\nOMENRYP8_FTFT\nOMENRAP8_FTFT\nOMENRUP8_FTFT\nOMACHT6_PTFT\nOMAWDP6_PTFT\nOMACHT8_PTFT\nOMAWDP8_PTFT\nOMENRYP8_PTFT\nOMENRAP8_PTFT\nOMENRUP8_PTFT\nOMACHT6_FTNFT\nOMAWDP6_FTNFT\nOMACHT8_FTNFT\nOMAWDP8_FTNFT\nOMENRYP8_FTNFT\nOMENRAP8_FTNFT\nOMENRUP8_FTNFT\nOMACHT6_PTNFT\nOMAWDP6_PTNFT\nOMACHT8_PTNFT\nOMAWDP8_PTNFT\nOMENRYP8_PTNFT\nOMENRAP8_PTNFT\nOMENRUP8_PTNFT\nRET_FT4_POOLED\nRET_FTL4_POOLED\nRET_PT4_POOLED\nRET_PTL4_POOLED\nRET_FT_DEN4_POOLED\nRET_FT_DENL4_POOLED\nRET_PT_DEN4_POOLED\nRET_PT_DENL4_POOLED\nPOOLYRSRET_FT\nPOOLYRSRET_PT\nRET_FT4_POOLED_SUPP\nRET_FTL4_POOLED_SUPP\nRET_PT4_POOLED_SUPP\nRET_PTL4_POOLED_SUPP\nTRANS_4_POOLED\nTRANS_L4_POOLED\nDTRANS_4_POOLED\nDTRANS_L4_POOLED\nTRANS_4_POOLED_SUPP\nTRANS_L4_POOLED_SUPP\nC100_4_POOLED\nC100_L4_POOLED\nD100_4_POOLED\nD100_L4_POOLED\nPOOLYRS100\nC100_4_POOLED_SUPP\nC100_L4_POOLED_SUPP\nC150_4_PELL\nD150_4_PELL\nC150_L4_PELL\nD150_L4_PELL\nC150_4_LOANNOPELL\nD150_4_LOANNOPELL\nC150_L4_LOANNOPELL\nD150_L4_LOANNOPELL\nC150_4_NOLOANNOPELL\nD150_4_NOLOANNOPELL\nC150_L4_NOLOANNOPELL\nD150_L4_NOLOANNOPELL\nGT_28K_P10\nGT_28K_P8\nGT_28K_P6\nOMACHT6_FTFT_POOLED\nOMAWDP6_FTFT_POOLED\nOMACHT8_FTFT_POOLED\nOMAWDP8_FTFT_POOLED\nOMENRYP8_FTFT_POOLED\nOMENRAP8_FTFT_POOLED\nOMENRUP8_FTFT_POOLED\nOMACHT6_PTFT_POOLED\nOMAWDP6_PTFT_POOLED\nOMACHT8_PTFT_POOLED\nOMAWDP8_PTFT_POOLED\nOMENRYP8_PTFT_POOLED\nOMENRAP8_PTFT_POOLED\nOMENRUP8_PTFT_POOLED\nOMACHT6_FTNFT_POOLED\nOMAWDP6_FTNFT_POOLED\nOMACHT8_FTNFT_POOLED\nOMAWDP8_FTNFT_POOLED\nOMENRYP8_FTNFT_POOLED\nOMENRAP8_FTNFT_POOLED\nOMENRUP8_FTNFT_POOLED\nOMACHT6_PTNFT_POOLED\nOMAWDP6_PTNFT_POOLED\nOMACHT8_PTNFT_POOLED\nOMAWDP8_PTNFT_POOLED\nOMENRYP8_PTNFT_POOLED\nOMENRAP8_PTNFT_POOLED\nOMENRUP8_PTNFT_POOLED\nPOOLYRSOM_FTFT\nPOOLYRSOM_PTFT\nPOOLYRSOM_FTNFT\nPOOLYRSOM_PTNFT\nOMAWDP6_FTFT_POOLED_SUPP\nOMAWDP8_FTFT_POOLED_SUPP\nOMENRYP8_FTFT_POOLED_SUPP\nOMENRAP8_FTFT_POOLED_SUPP\nOMENRUP8_FTFT_POOLED_SUPP\nOMAWDP6_PTFT_POOLED_SUPP\nOMAWDP8_PTFT_POOLED_SUPP\nOMENRYP8_PTFT_POOLED_SUPP\nOMENRAP8_PTFT_POOLED_SUPP\nOMENRUP8_PTFT_POOLED_SUPP\nOMAWDP6_FTNFT_POOLED_SUPP\nOMAWDP8_FTNFT_POOLED_SUPP\nOMENRYP8_FTNFT_POOLED_SUPP\nOMENRAP8_FTNFT_POOLED_SUPP\nOMENRUP8_FTNFT_POOLED_SUPP\nOMAWDP6_PTNFT_POOLED_SUPP\nOMAWDP8_PTNFT_POOLED_SUPP\nOMENRYP8_PTNFT_POOLED_SUPP\nOMENRAP8_PTNFT_POOLED_SUPP\nOMENRUP8_PTNFT_POOLED_SUPP\nSCHTYPE\nOPEFLAG\nPRGMOFR\nCIPCODE1\nCIPCODE2\nCIPCODE3\nCIPCODE4\nCIPCODE5\nCIPCODE6\nCIPTITLE1\nCIPTITLE2\nCIPTITLE3\nCIPTITLE4\nCIPTITLE5\nCIPTITLE6\nCIPTFBS1\nCIPTFBS2\nCIPTFBS3\nCIPTFBS4\nCIPTFBS5\nCIPTFBS6\nCIPTFBSANNUAL1\nCIPTFBSANNUAL2\nCIPTFBSANNUAL3\nCIPTFBSANNUAL4\nCIPTFBSANNUAL5\nCIPTFBSANNUAL6\nMTHCMP1\nMTHCMP2\nMTHCMP3\nMTHCMP4\nMTHCMP5\nMTHCMP6\nPOOLYRSOM_ALL\nPOOLYRSOM_FIRSTTIME\nPOOLYRSOM_NOTFIRSTTIME\nPOOLYRSOM_FULLTIME\nPOOLYRSOM_PARTTIME\nOMENRYP_ALL\nOMENRAP_ALL\nOMAWDP8_ALL\nOMENRUP_ALL\nOMENRYP_FIRSTTIME\nOMENRAP_FIRSTTIME\nOMAWDP8_FIRSTTIME\nOMENRUP_FIRSTTIME\nOMENRYP_NOTFIRSTTIME\nOMENRAP_NOTFIRSTTIME\nOMAWDP8_NOTFIRSTTIME\nOMENRUP_NOTFIRSTTIME\nOMENRYP_FULLTIME\nOMENRAP_FULLTIME\nOMAWDP8_FULLTIME\nOMENRUP_FULLTIME\nOMENRYP_PARTTIME\nOMENRAP_PARTTIME\nOMAWDP8_PARTTIME\nOMENRUP_PARTTIME\nOMENRYP_ALL_POOLED_SUPP\nOMENRAP_ALL_POOLED_SUPP\nOMAWDP8_ALL_POOLED_SUPP\nOMENRUP_ALL_POOLED_SUPP\nOMENRYP_FIRSTTIME_POOLED_SUPP\nOMENRAP_FIRSTTIME_POOLED_SUPP\nOMAWDP8_FIRSTTIME_POOLED_SUPP\nOMENRUP_FIRSTTIME_POOLED_SUPP\nOMENRYP_NOTFIRSTTIME_POOLED_SUPP\nOMENRAP_NOTFIRSTTIME_POOLED_SUPP\nOMAWDP8_NOTFIRSTTIME_POOLED_SUPP\nOMENRUP_NOTFIRSTTIME_POOLED_SUPP\nOMENRYP_FULLTIME_POOLED_SUPP\nOMENRAP_FULLTIME_POOLED_SUPP\nOMAWDP8_FULLTIME_POOLED_SUPP\nOMENRUP_FULLTIME_POOLED_SUPP\nOMENRYP_PARTTIME_POOLED_SUPP\nOMENRAP_PARTTIME_POOLED_SUPP\nOMAWDP8_PARTTIME_POOLED_SUPP\nOMENRUP_PARTTIME_POOLED_SUPP\nFTFTPCTPELL\nFTFTPCTFLOAN\nUG12MN\nG12MN\nSCUGFFN\nPOOLYRS_FTFTAIDPCT\nFTFTPCTPELL_POOLED_SUPP\nFTFTPCTFLOAN_POOLED_SUPP\nSCUGFFN_POOLED\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a91b7dd4ed36513ee0962d307ab789dcc972723
| 3,278 |
ipynb
|
Jupyter Notebook
|
Practico_parte_2.ipynb
|
msoledadfernandez/DataScience_AnalisisyVisualizacion
|
63b7814df366ec4fff49128f861e99debae581f4
|
[
"MIT"
] | null | null | null |
Practico_parte_2.ipynb
|
msoledadfernandez/DataScience_AnalisisyVisualizacion
|
63b7814df366ec4fff49128f861e99debae581f4
|
[
"MIT"
] | null | null | null |
Practico_parte_2.ipynb
|
msoledadfernandez/DataScience_AnalisisyVisualizacion
|
63b7814df366ec4fff49128f861e99debae581f4
|
[
"MIT"
] | null | null | null | 42.571429 | 538 | 0.680903 |
[
[
[
"# **Parte 2**\n\nLuego del segundo fin de semana de clase, podemos revisitar nuestro trabajo anterior y completarlo respondiendo a las siguientes preguntas:",
"_____no_output_____"
],
[
"## **3. Distribuciones**\n### **3.1** Realizar una prueba de Kolmogorov-Smirnof para comprobar analíticamente si estas variables responden la distribución propuesta en el ejercicio anterior. Hint: podés usar https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.kstest.html, pero hay que tener en cuenta que si la distribución es \"norm\", entonces va a comparar los datos con una distribución normal con media 0 y desviación estándar 1. Se puede utilizar la distribución sobre todos los datos o sólo sobre Latinoamérica.",
"_____no_output_____"
],
[
"## **4. Correlaciones**\n\n### **4.1** Calcular algún coeficiente de correlación adecuado entre los dos pares de variables, dependiendo de la cantidad de datos, el tipo de datos y la distribución de los mismo. Algunas opciones son: coeficiente de pearson, coeficiente de spearman, coeficientes de tau y de kendall. Interpretar los resultados y justificar si las variables están correlacionadas o no. ",
"_____no_output_____"
],
[
"### **4.2** [Opcional] Analizar la correlación entre la region y el pf_score (y/o el ef_score); y entre la region y el pf_identity. Considerar que como la variable *region* es ordinal, debe utilizarse algún tipo de test. Explicar cuáles son los requisitos necesarios para la aplicación de ese test. (Si no se cumplieran, se pueden agregar algunos datos para generar más registros). Genere nuevas variables categóricas ordinales para calcular la correlación Tau de Kendal y genere una tabla de contingencia con esas nuevas variables.",
"_____no_output_____"
],
[
"Además de completar estos puntos faltantes, luego de haber visitado los conceptos de percepción visual y comunicación efectiva, están en condiciones de reveer los gráficos realizados y evaluar si pueden ser mejorados. Para ello, puede hacerse las siguientes preguntas:\n\n* ¿Están utilizando el tipo de gráfico adecuado para cada tipo de variable?\n* Los gráficos, ¿son legibles?\n* Los gráficos generados, ¿responden a las preguntas mostrando un patrón claro? En caso de que no, ¿podemos filtrar los datos para que el patrón sea más evidente? ¿o agruparlos de manera distinta? ¿o cambiar el tipo de gráfico?",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4a91bf5e91ddaeb7bbd131d2610b160aa4cdbe94
| 1,424 |
ipynb
|
Jupyter Notebook
|
test/py/Canopytemperature.ipynb
|
Crop2ML-Catalog/SQ_Energy_Balance
|
db6a8ba30940b6527e3ae82c325319454ff8a224
|
[
"BSD-3-Clause"
] | null | null | null |
test/py/Canopytemperature.ipynb
|
Crop2ML-Catalog/SQ_Energy_Balance
|
db6a8ba30940b6527e3ae82c325319454ff8a224
|
[
"BSD-3-Clause"
] | null | null | null |
test/py/Canopytemperature.ipynb
|
Crop2ML-Catalog/SQ_Energy_Balance
|
db6a8ba30940b6527e3ae82c325319454ff8a224
|
[
"BSD-3-Clause"
] | null | null | null | 24.135593 | 81 | 0.585674 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4a91e0a034110e52b9092978a9c025a7e75577b9
| 19,206 |
ipynb
|
Jupyter Notebook
|
notebook.ipynb
|
benharmonics/drive-or-bike
|
2e8a0947b7cc2dd97447cad702dd6852bdb112cc
|
[
"MIT"
] | null | null | null |
notebook.ipynb
|
benharmonics/drive-or-bike
|
2e8a0947b7cc2dd97447cad702dd6852bdb112cc
|
[
"MIT"
] | null | null | null |
notebook.ipynb
|
benharmonics/drive-or-bike
|
2e8a0947b7cc2dd97447cad702dd6852bdb112cc
|
[
"MIT"
] | null | null | null | 95.552239 | 13,104 | 0.831094 |
[
[
[
"import requests\nfrom matplotlib import pyplot as plt\nfrom bs4 import BeautifulSoup",
"_____no_output_____"
],
[
"def gasoline_price():\n \"\"\"Gets current gasoline price in Swedish Krona\"\"\"\n try:\n page = requests.get('https://www.globalpetrolprices.com/Sweden/gasoline_prices/')\n soup = BeautifulSoup(page.content, 'html.parser')\n body = soup.body\n table = body.find('div', {'id': 'contentHolder'}).table\n entries = table.tbody.find_all('tr')\n # Scraped cost in liters\n cost_liters = [float(entry.find_all('td')[0].text) for entry in entries]\n\n return cost_liters[0]\n except:\n return None",
"_____no_output_____"
],
[
"def electricity_price():\n \"\"\"Gets current electricity price in Swedish Krona\"\"\"\n try:\n page = requests.get('https://www.vattenfall.se/elavtal/elmarknaden/elmarknaden-just-nu/')\n soup = BeautifulSoup(page.content, 'html.parser')\n body = soup.body\n tbody = body.find('table').tbody\n entries = tbody.find_all('tr')\n data = entries[1:]\n # Scraped Values\n prices_2022 = [datum.find_all('td')[1].text for datum in data]\n prices_as_float = [float(price.split()[0].replace(',', '.')) for price in prices_2022]\n max_price_sek = max(prices_as_float) / 100\n\n return max_price_sek\n except:\n return None",
"_____no_output_____"
],
[
"def gasoline_cost_sek(dist, sekpl=20.0, kmpl=9.4):\n \"\"\"Gets cost of commute via car in Swedish Krona.\n Inputs:\n dist: distance in kilometers (numeric)\n sekpl: Swedish Krona (SEK) per liter (L). Obtained from gasoline_price() function.\n kmpl: Kilometers (km) per liter (L). (Fuel efficiency)\n \n kmpl estimation from: \n https://www.bts.gov/content/average-fuel-efficiency-us-passenger-cars-and-light-trucks\n \"\"\"\n return sekpl * dist / kmpl",
"_____no_output_____"
],
[
"def electricity_cost_sek(dist, sekpkwh=.85, kmpkwh=100):\n \"\"\"Gets cost of commute via ebike in Swedish Krona.\n Inputs:\n dist: distance in kilometers (numeric)\n sekpkwh: Swedish Krona (SEK) per kilowatt-hour (kWh). Obtained from electricity_price() function.\n kmpkwh: Kilometers (km) per kilowatt-hour (kWh).\n \n ebikes: 80-100 kilometers per kWh?\n https://www.ebikejourney.com/ebike/\n \"\"\"\n return sekpkwh * dist / kmpkwh",
"_____no_output_____"
],
[
"def circle_plot(dist, gas_price, elec_price, kmpl=9.4, kmpkwh=100):\n \"\"\"Generates a plot where the area of each circle is proportional to the cost of the commute.\"\"\"\n gas_cost = gasoline_cost_sek(dist, gas_price, kmpl)\n elec_cost = electricity_cost_sek(dist, elec_price, kmpkwh)\n\n radius_g = gas_cost**.5\n radius_e = elec_cost**.5\n circle_g = plt.Circle((radius_g, radius_g), radius_g, color='r', label='gasoline cost', alpha=0.8)\n circle_e = plt.Circle((0.7*radius_g, 0.7*radius_g), radius_e, color='g', label='electricity cost', alpha=0.8)\n\n fig, ax = plt.subplots()\n ax.set_xlim([0, 2.02*radius_g])\n ax.set_ylim([0, 2.05*radius_g])\n ax.add_patch(circle_g)\n ax.add_patch(circle_e)\n ax.axis('off')\n ax.legend()\n plt.savefig('circleplot.png', transparent=True)",
"_____no_output_____"
],
[
"elec_price = electricity_price() or 0.85\ngas_price = gasoline_price() or 20.0",
"_____no_output_____"
],
[
"circle_plot(50, gas_price, elec_price)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a91ec5bacd4fee3bebbe1b48b89a843c69664da
| 854,103 |
ipynb
|
Jupyter Notebook
|
3. Facial Keypoint Detection, Complete Pipeline.ipynb
|
Shyam876/CNN_Facial_Key_points_detector
|
5a6d383777cfef89c1b41ee6642f9df6768b484c
|
[
"MIT"
] | null | null | null |
3. Facial Keypoint Detection, Complete Pipeline.ipynb
|
Shyam876/CNN_Facial_Key_points_detector
|
5a6d383777cfef89c1b41ee6642f9df6768b484c
|
[
"MIT"
] | null | null | null |
3. Facial Keypoint Detection, Complete Pipeline.ipynb
|
Shyam876/CNN_Facial_Key_points_detector
|
5a6d383777cfef89c1b41ee6642f9df6768b484c
|
[
"MIT"
] | null | null | null | 1,801.905063 | 315,868 | 0.957888 |
[
[
[
"## Face and Facial Keypoint detection\n\nAfter you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.\n\n1. Detect all the faces in an image using a face detector (we'll be using a Haar Cascade detector in this notebook).\n2. Pre-process those face images so that they are grayscale, and transformed to a Tensor of the input size that your net expects. This step will be similar to the `data_transform` you created and applied in Notebook 2, whose job was tp rescale, normalize, and turn any image into a Tensor to be accepted as input to your CNN.\n3. Use your trained model to detect facial keypoints on the image.\n\n---",
"_____no_output_____"
],
[
"In the next python cell we load in required libraries for this section of the project.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n%matplotlib inline\n",
"_____no_output_____"
]
],
[
[
"#### Select an image \n\nSelect an image to perform facial keypoint detection on; you can select any image of faces in the `images/` directory.",
"_____no_output_____"
]
],
[
[
"import cv2\n# load in color image for face detection\nimage = cv2.imread('images/obamas.jpg')\n\n# switch red and blue color channels \n# --> by default OpenCV assumes BLUE comes first, not RED as in many images\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n# plot the image\nfig = plt.figure(figsize=(9,9))\nplt.imshow(image)",
"_____no_output_____"
]
],
[
[
"## Detect all faces in an image\n\nNext, you'll use one of OpenCV's pre-trained Haar Cascade classifiers, all of which can be found in the `detector_architectures/` directory, to find any faces in your selected image.\n\nIn the code below, we loop over each face in the original image and draw a red square on each face (in a copy of the original image, so as not to modify the original). You can even [add eye detections](https://docs.opencv.org/3.4.1/d7/d8b/tutorial_py_face_detection.html) as an *optional* exercise in using Haar detectors.\n\nAn example of face detection on a variety of images is shown below.\n\n<img src='images/haar_cascade_ex.png' width=80% height=80%/>\n",
"_____no_output_____"
]
],
[
[
"# load in a haar cascade classifier for detecting frontal faces\nface_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')\n\n# run the detector\n# the output here is an array of detections; the corners of each detection box\n# if necessary, modify these parameters until you successfully identify every face in a given image\nfaces = face_cascade.detectMultiScale(image, 1.2, 2)\n\n# make a copy of the original image to plot detections on\nimage_with_detections = image.copy()\n\n# loop over the detected faces, mark the image where each face is found\nfor (x,y,w,h) in faces:\n # draw a rectangle around each detected face\n # you may also need to change the width of the rectangle drawn depending on image resolution\n cv2.rectangle(image_with_detections,(x,y),(x+w,y+h),(255,0,0),3) \n\nfig = plt.figure(figsize=(9,9))\n\nplt.imshow(image_with_detections)",
"_____no_output_____"
]
],
[
[
"## Loading in a trained model\n\nOnce you have an image to work with (and, again, you can select any image of faces in the `images/` directory), the next step is to pre-process that image and feed it into your CNN facial keypoint detector.\n\nFirst, load your best model by its filename.",
"_____no_output_____"
]
],
[
[
"import torch\nfrom models import Net\n\nnet = Net().double()\n\n## TODO: load the best saved model parameters (by your path name)\n## You'll need to un-comment the line below and add the correct name for *your* saved model\nnet.load_state_dict(torch.load('keypoints_model_drop.pt'))\n\n## print out your net and prepare it for testing (uncomment the line below)\nnet.eval()",
"_____no_output_____"
]
],
[
[
"## Keypoint detection\n\nNow, we'll loop over each detected face in an image (again!) only this time, you'll transform those faces in Tensors that your CNN can accept as input images.\n\n### TODO: Transform each detected face into an input Tensor\n\nYou'll need to perform the following steps for each detected face:\n1. Convert the face from RGB to grayscale\n2. Normalize the grayscale image so that its color range falls in [0,1] instead of [0,255]\n3. Rescale the detected face to be the expected square size for your CNN (224x224, suggested)\n4. Reshape the numpy image into a torch image.\n\nYou may find it useful to consult to transformation code in `data_load.py` to help you perform these processing steps.\n\n\n### TODO: Detect and display the predicted keypoints\n\nAfter each face has been appropriately converted into an input Tensor for your network to see as input, you'll wrap that Tensor in a Variable() and can apply your `net` to each face. The ouput should be the predicted the facial keypoints. These keypoints will need to be \"un-normalized\" for display, and you may find it helpful to write a helper function like `show_keypoints`. You should end up with an image like the following with facial keypoints that closely match the facial features on each individual face:\n\n<img src='images/michelle_detected.png' width=30% height=30%/>\n\n\n",
"_____no_output_____"
]
],
[
[
"from torchvision import transforms, utils\nfrom data_load import FacialKeypointsDataset\nfrom data_load import Rescale, RandomCrop, Normalize, ToTensor\n\nimage_copy = np.copy(image)\n# loop over the detected faces from your haar cascade\nfor (x,y,w,h) in faces:\n \n # Select the region of interest that is the face in the image \n roi = image_copy[y:y+h, x:x+w]\n plt.imshow(roi)\n roi = cv2.cvtColor(roi, cv2.COLOR_RGB2GRAY)\n roi = roi/255.0\n \n roi = cv2.resize(roi, (244,244))\n \n if(len(roi.shape) == 2):\n roi = roi.reshape(roi.shape[0], roi.shape[1], 1)\n roi = roi.transpose((2, 0, 1))\n roi = torch.from_numpy(roi)\n print(roi.shape)\n output_pts = net(roi[None, ...])\n print(output_pts)\n ## TODO: Convert the face region from RGB to grayscale\n\n ## TODO: Normalize the grayscale image so that its color range falls in [0,1] instead of [0,255]\n \n ## TODO: Rescale the detected face to be the expected square size for your CNN (224x224, suggested)\n \n ## TODO: Reshape the numpy image shape (H x W x C) into a torch image shape (C x H x W)\n \n ## TODO: Make facial keypoint predictions using your loaded, trained network \n ## perform a forward pass to get the predicted facial keypoints\n\n ## TODO: Display each detected face and the corresponding keypoints \n\n",
"torch.Size([1, 244, 244])\ntensor([[-4.9025, -4.8973, -4.9113, -4.9051, -4.9138, -4.9087, -4.9118, -4.9268,\n -4.8941, -4.9127, -4.9178, -4.9043, -4.9131, -4.9150, -4.9227, -4.9203,\n -4.9063, -4.9094, -4.9136, -4.9192, -4.9276, -4.8951, -4.9089, -4.9180,\n -4.9104, -4.9054, -4.9148, -4.9028, -4.9055, -4.9152, -4.9046, -4.8994,\n -4.9109, -4.9062, -4.9113, -4.9241, -4.9178, -4.9153, -4.9085, -4.9262,\n -4.9017, -4.9169, -4.9097, -4.9161, -4.9096, -4.9040, -4.9139, -4.9241,\n -4.9090, -4.9258, -4.9132, -4.9166, -4.9240, -4.9126, -4.9133, -4.9210,\n -4.9085, -4.9050, -4.9173, -4.9102, -4.9118, -4.9117, -4.9049, -4.9291,\n -4.9028, -4.9218, -4.9091, -4.9234, -4.9225, -4.8990, -4.9299, -4.9246,\n -4.9108, -4.9246, -4.8975, -4.9132, -4.9261, -4.9051, -4.9198, -4.9192,\n -4.9199, -4.9055, -4.9105, -4.9014, -4.9113, -4.9088, -4.9138, -4.9204,\n -4.9149, -4.9194, -4.9162, -4.9198, -4.8916, -4.9224, -4.9177, -4.9125,\n -4.9080, -4.9138, -4.9123, -4.9236, -4.9286, -4.9121, -4.9154, -4.9276,\n -4.9157, -4.9089, -4.9146, -4.9048, -4.9117, -4.9152, -4.9160, -4.9075,\n -4.9177, -4.9064, -4.9116, -4.9087, -4.9072, -4.9063, -4.9093, -4.9116,\n -4.9299, -4.8837, -4.9103, -4.9070, -4.9027, -4.9071, -4.9207, -4.9172,\n -4.9042, -4.8992, -4.9083, -4.9128, -4.9141, -4.9238, -4.9071, -4.9243]],\n dtype=torch.float64, grad_fn=<LogSoftmaxBackward0>)\ntorch.Size([1, 244, 244])\ntensor([[-4.8991, -4.8951, -4.9123, -4.9065, -4.9141, -4.9102, -4.9184, -4.9272,\n -4.8931, -4.9075, -4.9199, -4.9078, -4.9119, -4.9148, -4.9225, -4.9229,\n -4.9042, -4.9042, -4.9163, -4.9215, -4.9249, -4.8907, -4.9098, -4.9228,\n -4.9091, -4.9104, -4.9148, -4.9022, -4.9062, -4.9129, -4.9098, -4.8952,\n -4.9097, -4.9089, -4.9089, -4.9258, -4.9236, -4.9178, -4.9117, -4.9258,\n -4.9058, -4.9190, -4.9075, -4.9194, -4.9100, -4.9078, -4.9133, -4.9239,\n -4.9046, -4.9216, -4.9101, -4.9164, -4.9282, -4.9133, -4.9055, -4.9225,\n -4.9090, -4.9059, -4.9174, -4.9127, -4.9092, -4.9091, -4.9057, -4.9313,\n -4.8958, -4.9229, -4.9094, -4.9231, -4.9241, -4.8983, -4.9304, -4.9296,\n -4.9147, -4.9246, -4.8955, -4.9141, -4.9240, -4.9053, -4.9212, -4.9229,\n -4.9188, -4.9082, -4.9106, -4.9000, -4.9105, -4.9068, -4.9144, -4.9169,\n -4.9146, -4.9199, -4.9164, -4.9207, -4.8941, -4.9205, -4.9173, -4.9132,\n -4.9025, -4.9160, -4.9057, -4.9246, -4.9310, -4.9147, -4.9170, -4.9221,\n -4.9140, -4.9119, -4.9209, -4.9055, -4.9116, -4.9152, -4.9156, -4.9053,\n -4.9163, -4.9055, -4.9102, -4.9113, -4.9046, -4.9012, -4.9088, -4.9137,\n -4.9272, -4.8853, -4.9092, -4.8997, -4.9021, -4.9089, -4.9176, -4.9173,\n -4.9027, -4.9013, -4.9053, -4.9121, -4.9138, -4.9221, -4.9089, -4.9291]],\n dtype=torch.float64, grad_fn=<LogSoftmaxBackward0>)\n"
],
[
"predicted_key_pts = output_pts.data\n\npredicted_key_pts = predicted_key_pts.numpy()\n\n# undo normalization of keypoints \npredicted_key_pts = (predicted_key_pts*50.0)+100\n\n# plot ground truth points for comparison, if they exist\n\npredicted_key_pts = predicted_key_pts.astype('float').reshape(-1, 2)\nprint(predicted_key_pts)\nplt.imshow(image, cmap='gray')\nplt.scatter(predicted_key_pts[:, 0], predicted_key_pts[:, 1], s=20, marker='.', c='m')",
"[[-144.95256303 -144.75297922]\n [-145.6132114 -145.32435387]\n [-145.7054258 -145.51127675]\n [-145.91858938 -146.36176583]\n [-144.65585111 -145.37538433]\n [-145.99608975 -145.38930251]\n [-145.59694927 -145.73970127]\n [-146.12640636 -146.14502523]\n [-145.21110333 -145.21084909]\n [-145.8173149 -146.0767879 ]\n [-146.24254116 -144.53643347]\n [-145.48873923 -146.14181242]\n [-145.45408492 -145.52146151]\n [-145.74008193 -145.10986805]\n [-145.31172517 -145.64269834]\n [-145.49213808 -144.75896944]\n [-145.48474057 -145.447088 ]\n [-145.44466651 -146.2888962 ]\n [-146.1815818 -145.89099634]\n [-145.58407679 -146.29087995]\n [-145.29150256 -145.94924314]\n [-145.37449153 -145.97082329]\n [-145.49797402 -145.38870377]\n [-145.66378595 -146.19595938]\n [-145.22761556 -146.07763454]\n [-145.5073052 -145.81827565]\n [-146.41242015 -145.66687896]\n [-145.27290431 -146.12737152]\n [-145.45065014 -145.29450003]\n [-145.86850285 -145.6353269 ]\n [-145.45793058 -145.45441928]\n [-145.28734457 -146.56437444]\n [-144.78817183 -146.14655857]\n [-145.47187299 -146.1556842 ]\n [-146.20417903 -144.91381247]\n [-146.51751224 -146.48138949]\n [-145.73459719 -146.22996997]\n [-144.77588312 -145.70532407]\n [-146.19981736 -145.26591309]\n [-146.05856044 -146.14727043]\n [-145.94205505 -145.409409 ]\n [-145.5311472 -145.00085987]\n [-145.52633749 -145.33865358]\n [-145.71841691 -145.84749714]\n [-145.72820338 -145.99559283]\n [-145.82049332 -146.03482328]\n [-144.70556293 -146.0247144 ]\n [-145.86713543 -145.65809061]\n [-145.12346071 -145.7979543 ]\n [-145.28558652 -146.2296995 ]\n [-146.54998662 -145.73587709]\n [-145.85051937 -146.10438702]\n [-145.69822409 -145.59306775]\n [-146.04464037 -145.27586896]\n [-145.58024239 -145.75993498]\n [-145.77751392 -145.26685995]\n [-145.81309401 -145.27726179]\n [-145.51247746 -145.56528995]\n [-145.23122616 -145.06235342]\n [-145.43988826 -145.68651576]\n [-146.36094395 -144.26252101]\n [-145.45964517 -144.98451344]\n [-145.10689448 -145.44340265]\n [-145.88142263 -145.86626548]\n [-145.13531828 -145.06459619]\n [-145.26686375 -145.60717881]\n [-145.69050468 -146.10254759]\n [-145.44673945 -146.4548361 ]]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a91edd243ab766725b38f46261dddeccdd91ec4
| 3,091 |
ipynb
|
Jupyter Notebook
|
notebooks/xy-yz-jupyter-notebook-template.ipynb
|
martinabuck/gecm
|
6d6dc7a9e5fa46d73dc16b5f77cda09ff02399ce
|
[
"MIT"
] | 1 |
2020-11-21T17:07:29.000Z
|
2020-11-21T17:07:29.000Z
|
notebooks/xy-yz-jupyter-notebook-template.ipynb
|
martinabuck/gecm
|
6d6dc7a9e5fa46d73dc16b5f77cda09ff02399ce
|
[
"MIT"
] | 3 |
2020-11-17T14:18:42.000Z
|
2020-12-01T13:11:41.000Z
|
notebooks/xy-yz-jupyter-notebook-template.ipynb
|
martinabuck/gecm
|
6d6dc7a9e5fa46d73dc16b5f77cda09ff02399ce
|
[
"MIT"
] | 1 |
2020-11-05T12:22:08.000Z
|
2020-11-05T12:22:08.000Z
| 20.335526 | 76 | 0.505985 |
[
[
[
"# Descriptive-Title\nForename Lastname | XX.YY.ZZZZ\n\n## Core Analysis Goal(s)\n1.\n2.\n3.\n\n## Key Insight(s)\n1.\n2.\n3.",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport logging\nfrom pathlib import Path\n\nimport numpy as np\nimport scipy as sp\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\n\n%load_ext autoreload\n%autoreload 2\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport seaborn as sns\nsns.set_context(\"poster\")\nsns.set(rc={'figure.figsize': (16, 9.)})\nsns.set_style(\"ticks\")\n\nimport pandas as pd\npd.set_option(\"display.max_rows\", 120)\npd.set_option(\"display.max_columns\", 120)\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout)",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
]
],
[
[
"Define directory structure",
"_____no_output_____"
]
],
[
[
"# project directory\nabspath = os.path.abspath('')\nproject_dir = str(Path(abspath).parents[0])\n\n# sub-directories\ndata_raw = os.path.join(project_dir, \"data\", \"raw\")\ndata_processed = os.path.join(project_dir, \"data\", \"processed\")\nfigure_dir = os.path.join(project_dir, \"plots\")",
"_____no_output_____"
]
],
[
[
"Code ...",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a91f76f8564e3a45875bdf4b79921cd3d90b5b5
| 187,076 |
ipynb
|
Jupyter Notebook
|
notebooks/0.2.read.nyt.article.search.ipynb
|
vibya/Economic-Downturn
|
03df854f4c314d5a944cd99474b980a95f088f39
|
[
"MIT"
] | 1 |
2018-09-18T01:07:53.000Z
|
2018-09-18T01:07:53.000Z
|
notebooks/0.2.read.nyt.article.search.ipynb
|
aidinhass/reb
|
33fc9d9781e2c0fce8faa6240ec2d56899ee2c07
|
[
"MIT"
] | null | null | null |
notebooks/0.2.read.nyt.article.search.ipynb
|
aidinhass/reb
|
33fc9d9781e2c0fce8faa6240ec2d56899ee2c07
|
[
"MIT"
] | 3 |
2018-09-18T01:08:01.000Z
|
2019-03-10T10:06:41.000Z
| 103.81576 | 1,267 | 0.755575 |
[
[
[
"import os, inspect, sys\nimport json\nimport datetime as dt\n\nCURRENT_DIR = os.path.dirname(inspect.getabsfile(inspect.currentframe()))\nROOT_DIR = os.path.dirname(CURRENT_DIR)\nsys.path.insert(0, ROOT_DIR)\n\nfrom reb.src import pynyt\nfrom reb.conf import APIKEY_NYT_ARTICLE",
"_____no_output_____"
],
[
"def daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)):\n yield start_date + dt.timedelta(n), start_date + dt.timedelta(n+1)",
"_____no_output_____"
],
[
"nytArticle = pynyt.ArticleSearch(APIKEY_NYT_ARTICLE)\nnytArchive = pynyt.ArchiveApi(APIKEY_NYT_ARTICLE)\n\n# get 1000 news articles from the Foreign newsdesk from 1987 \n\nfor year in range(1990, 1996):\n for month in range(1, 13):\n start_date = dt.date(year, month, 1)\n end_date = dt.date(year + month//12,\n (month+1)%12, 1)\n news_monthly = {}\n for d1, d2 in daterange(start_date, end_date):\n d1_str = d1.strftime(\"%Y%m%d\")\n d2_str = d2.strftime(\"%Y%m%d\")\n print(f\"--> Reading NYT Business news from {d1_str}\")\n\n news = nytArticle.query(\n # q=\"obama\",\n fq={\"type_of_material\": [\"news\"],\n \"section_name.contains\": [\"business\", \"Business Day\", \"Real Estate\"]},\n begin_date=d1_str,\n end_date=d1_str,\n # facet_field=['source', 'day_of_week'],\n # facet_filter = True,\n verbose=True)\n \n news_daily = {\"status\": [],\n \"copyright\": None,\n \"response\": {\"meta\": [], \"docs\": []}}\n for x in news:\n news_daily[\"status\"].append(x[\"status\"])\n news_daily[\"copyright\"] = x[\"copyright\"]\n news_daily[\"response\"][\"meta\"].append(x[\"response\"][\"meta\"])\n news_daily[\"response\"][\"docs\"].extend(x[\"response\"][\"docs\"])\n news_monthly[d1_str] = news_daily\n \n fname = f\"nyt-business-{year}-{month}.json\"\n path = os.path.join(ROOT_DIR, \"reb\", \"data\", \"raw\")\n ffname = os.path.join(path, fname)\n with open(ffname, \"w\") as fp:\n json.dump(news_monthly, fp)\n print(f\"--> Writing to '{fname}' at {path}\")\n",
"--> Reading NYT Business news from 19900101\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900101&end_date=19900101&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900101&end_date=19900101&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900101&end_date=19900101&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900101&end_date=19900101&page=3\n--> Reading NYT Business news from 19900102\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900102&end_date=19900102&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900102&end_date=19900102&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900102&end_date=19900102&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900102&end_date=19900102&page=3\n--> Reading NYT Business news from 19900103\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900103&end_date=19900103&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900103&end_date=19900103&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900103&end_date=19900103&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900103&end_date=19900103&page=3\nProcessing page 4\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900103&end_date=19900103&page=4\nProcessing page 5\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900103&end_date=19900103&page=5\n--> Reading NYT Business news from 19900104\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900104&end_date=19900104&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900104&end_date=19900104&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900104&end_date=19900104&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900104&end_date=19900104&page=3\n--> Reading NYT Business news from 19900105\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900105&end_date=19900105&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900105&end_date=19900105&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900105&end_date=19900105&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900105&end_date=19900105&page=3\nProcessing page 4\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900105&end_date=19900105&page=4\n--> Reading NYT Business news from 19900106\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900106&end_date=19900106&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900106&end_date=19900106&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900106&end_date=19900106&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900106&end_date=19900106&page=3\n--> Reading NYT Business news from 19900107\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900107&end_date=19900107&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900107&end_date=19900107&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900107&end_date=19900107&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900107&end_date=19900107&page=3\n--> Reading NYT Business news from 19900108\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900108&end_date=19900108&page=0\nProcessing page 1\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900108&end_date=19900108&page=1\nProcessing page 2\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900108&end_date=19900108&page=2\nProcessing page 3\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900108&end_date=19900108&page=3\n--> Reading NYT Business news from 19900109\nProcessing page 0\nhttp://api.nytimes.com/svc/search/v2/articlesearch.json?fq=type_of_material%3A%28news%29+AND+section_name.contains%3A%28business+Business+Day+Real+Estate%29&begin_date=19900109&end_date=19900109&page=0\nProcessing page 1\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
4a92160cad212a83fb2fbe5fa18baf779aa1277f
| 230,750 |
ipynb
|
Jupyter Notebook
|
(07) Naive_Bayes.ipynb
|
Goagekido/480
|
34f5537bf3d10e4053451fc8b00e27d5b6157a91
|
[
"MIT"
] | null | null | null |
(07) Naive_Bayes.ipynb
|
Goagekido/480
|
34f5537bf3d10e4053451fc8b00e27d5b6157a91
|
[
"MIT"
] | null | null | null |
(07) Naive_Bayes.ipynb
|
Goagekido/480
|
34f5537bf3d10e4053451fc8b00e27d5b6157a91
|
[
"MIT"
] | null | null | null | 621.967655 | 84,372 | 0.947055 |
[
[
[
"# K-Naive Bayes\n\ncode by xbwei, adapted for use by daviscj & mathi2ma.\n",
"_____no_output_____"
],
[
"## Import and Prepare the Data",
"_____no_output_____"
],
[
"[pandas](https://pandas.pydata.org/) provides excellent data reading and querying module,[dataframe](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html), which allows you to import structured data and perform SQL-like queries. We also use the [mglearn](https://github.com/amueller/mglearn) package to help us visualize the data and models.\n\nHere we imported some house price records from [Trulia](https://www.trulia.com/?cid=sem|google|tbw_br_nat_x_x_nat!53f9be4f|Trulia-Exact_352364665_22475209465_aud-278383240986:kwd-1967776155_260498918114_). For more about extracting data from Trulia, please check [my previous tutorial](https://www.youtube.com/watch?v=qB418v3k2vk).\n\nWe use the house type as the [dependent variable](https://en.wikipedia.org/wiki/Dependent_and_independent_variables) and the house ages and house prices as the [independent variables](https://en.wikipedia.org/wiki/Dependent_and_independent_variables).",
"_____no_output_____"
]
],
[
[
"import sklearn\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nimport pandas\nimport numpy as np\nimport mglearn\nfrom collections import Counter\n\ndf = pandas.read_excel('house_price_label.xlsx')\n# combine multipl columns into a 2D array\n# also convert the integer data to float data\nX = np.column_stack((df.built_in.astype(float),df.price.astype(float))) \ny = df.house_type\nX_train, X_test, y_train, y_test = train_test_split(X, y,test_size =0.3,stratify = y, random_state=0) \n\n# for classification, make sure a stratify splitting method is selected\nmglearn.discrete_scatter(X[:,0],X[:,1],y) # use mglearn to visualize data\n\nplt.legend(y,loc='best')\nplt.xlabel('house age')\nplt.ylabel('house price')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Classification",
"_____no_output_____"
],
[
"The [Naive Bayes](http://scikit-learn.org/stable/modules/naive_bayes.html) model is used to classify the house types based on the house ages and prices. Specifically, the [Gaussian Naive Bayes](http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB) is selected in this classification. We also calculate the [Accuracy](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.score) and the [Kappa](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.cohen_kappa_score.html) score of our classification on the training and test data.",
"_____no_output_____"
]
],
[
[
"from sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import cohen_kappa_score\n\ngnb = GaussianNB()\ngnb.fit(X_train,y_train)\n\nprint(\"Training set accuracy: {:.2f}\".format(gnb.score(X_train, y_train)))\nprint (\"Training Kappa: {:.3f}\".format(cohen_kappa_score(y_train,gnb.predict(X_train))))\nprint(\"Test set accuracy: {:.2f}\".format(gnb.score(X_test, y_test)))\nprint (\"Test Kappa: {:.3f}\".format(cohen_kappa_score(y_test,gnb.predict(X_test))))",
"Training set accuracy: 0.74\nTraining Kappa: 0.419\nTest set accuracy: 0.75\nTest Kappa: 0.426\n"
]
],
[
[
"## Visualize the Result",
"_____no_output_____"
],
[
"We plot the predicted results of the training data and the test data.",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(1, 2, figsize=(20, 6))\nfor ax,data in zip(axes,[X_train,X_test]):\n mglearn.discrete_scatter(data[:,0],data[:,1],gnb.predict(data),ax=ax) # use mglearn to visualize data\n\n ax.set_title(\"{}\".format('Predicted House Type'))\n ax.set_xlabel(\"house age\")\n ax.set_ylabel(\"house price\")\n ax.legend(loc='best')",
"_____no_output_____"
]
],
[
[
"We check the distribution of the independent variables for each house type.",
"_____no_output_____"
]
],
[
[
"df.groupby('house_type').hist(figsize=(14,2),column=['price','built_in'])",
"_____no_output_____"
]
],
[
[
"The [Gaussian Naive Bayes](http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB) assumes that each feature follows a normal distribution. Here we plot the [pdf](https://en.wikipedia.org/wiki/Probability_density_function) of each feature in the training data for each house type.\n",
"_____no_output_____"
]
],
[
[
"import scipy.stats\n\nhouse_type = ['condo','land and lot','single-family','townhouse']\nhouse_feature =['huilt_in','price']\nfig, axes = plt.subplots(4, 2, figsize=(12, 10))\nfor j in range(4):\n for i in range(2):\n mu = gnb.theta_[j,i] # get mean value of each feature for each class\n sigma=np.sqrt(gnb.sigma_ [j,i])# get std value of each feature for each class\n x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)\n axes[j][i].plot(x,scipy.stats.norm.pdf(x, mu, sigma) )\n axes[j][i].set_title(\"{}\".format(house_type[j]))\n axes[j][i].set_xlabel(house_feature[i])\nplt.subplots_adjust(hspace=0.5)\n",
"_____no_output_____"
]
],
[
[
"# Bernoulli Model",
"_____no_output_____"
]
],
[
[
"from sklearn.naive_bayes import BernoulliNB\nfrom sklearn.metrics import cohen_kappa_score\n\ngnb = BernoulliNB()\ngnb.fit(X_train,y_train)\n\nprint(\"Training set accuracy: {:.2f}\".format(gnb.score(X_train, y_train)))\nprint (\"Training Kappa: {:.3f}\".format(cohen_kappa_score(y_train,gnb.predict(X_train))))\nprint(\"Test set accuracy: {:.2f}\".format(gnb.score(X_test, y_test)))\nprint (\"Test Kappa: {:.3f}\".format(cohen_kappa_score(y_test,gnb.predict(X_test))))",
"Training set accuracy: 0.77\nTraining Kappa: 0.000\nTest set accuracy: 0.77\nTest Kappa: 0.000\n"
]
],
[
[
"# Multinomial Model",
"_____no_output_____"
]
],
[
[
"from sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import cohen_kappa_score\n\ngnb = MultinomialNB()\ngnb.fit(X_train,y_train)\n\nprint(\"Training set accuracy: {:.2f}\".format(gnb.score(X_train, y_train)))\nprint (\"Training Kappa: {:.3f}\".format(cohen_kappa_score(y_train,gnb.predict(X_train))))\nprint(\"Test set accuracy: {:.2f}\".format(gnb.score(X_test, y_test)))\nprint (\"Test Kappa: {:.3f}\".format(cohen_kappa_score(y_test,gnb.predict(X_test))))",
"Training set accuracy: 0.51\nTraining Kappa: 0.172\nTest set accuracy: 0.54\nTest Kappa: 0.171\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a9248e766500103353a815cebd2a2c52d84bd02
| 258,781 |
ipynb
|
Jupyter Notebook
|
notebooks/Clustering by Classification.ipynb
|
jattenberg/clustering_by_classification
|
fb4aed751bcb81033d1a2179fe2ae55dd00a4240
|
[
"MIT"
] | null | null | null |
notebooks/Clustering by Classification.ipynb
|
jattenberg/clustering_by_classification
|
fb4aed751bcb81033d1a2179fe2ae55dd00a4240
|
[
"MIT"
] | null | null | null |
notebooks/Clustering by Classification.ipynb
|
jattenberg/clustering_by_classification
|
fb4aed751bcb81033d1a2179fe2ae55dd00a4240
|
[
"MIT"
] | 1 |
2019-07-10T13:37:38.000Z
|
2019-07-10T13:37:38.000Z
| 1,421.873626 | 252,684 | 0.95507 |
[
[
[
"import numpy as np\nimport functools\nfrom sklearn.base import BaseEstimator, ClusterMixin, TransformerMixin\n\nfrom sklearn.linear_model import LogisticRegression \nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\n\nfrom clustering_by_classification import ClusterByClassifier",
"_____no_output_____"
],
[
"from sklearn import cluster, datasets, mixture\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom itertools import cycle, islice\n%matplotlib inline\n\nnp.random.seed(0)\n\n# ============\n# Generate datasets. We choose the size big enough to see the scalability\n# of the algorithms, but not too big to avoid too long running times\n# ============\nn_samples = 5000\nnoisy_circles = datasets.make_circles(n_samples=n_samples, factor=.5,\n noise=.05)\nnoisy_moons = datasets.make_moons(n_samples=n_samples, noise=.05)\nblobs = datasets.make_blobs(n_samples=n_samples, random_state=8)\nno_structure = np.random.rand(n_samples, 2), None\n\n# Anisotropicly distributed data\nrandom_state = 170\nX, y = datasets.make_blobs(n_samples=n_samples, random_state=random_state)\ntransformation = [[0.6, -0.6], [-0.4, 0.8]]\nX_aniso = np.dot(X, transformation)\naniso = (X_aniso, y)\n\n# blobs with varied variances\nvaried = datasets.make_blobs(n_samples=n_samples,\n cluster_std=[1.0, 2.5, 0.5],\n random_state=random_state)\n\n\ndataset_types = [\n noisy_circles,\n noisy_moons,\n blobs,\n no_structure,\n varied\n]\n\nplt.figure(figsize=(9 * 2 + 3, 12.5))\nplt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05,\n hspace=.01)\n\nlr = LogisticRegression()\ndt = DecisionTreeClassifier()\nsvm = SVC()\nrf = RandomForestClassifier()\n\nfor i, dataset in enumerate(dataset_types):\n X = dataset[0]\n cl = ClusterByClassifier(rf,\n n_clusters=5,\n max_iters=50,\n soft_clustering=True)\n y_pred = cl.fit_predict(X)\n \n \n plt.subplot(len(dataset_types), 1, i+1)\n\n colors = np.array(list(islice(cycle(['#377eb8', '#ff7f00', '#4daf4a',\n '#f781bf', '#a65628', '#984ea3',\n '#999999', '#e41a1c', '#dede00']),\n int(max(y_pred) + 1))))\n # add black color for outliers (if any)\n colors = np.append(colors, [\"#000000\"])\n plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[y_pred])\n\n plt.xlim(-2.5, 2.5)\n plt.ylim(-2.5, 2.5)\n plt.xticks(())\n plt.yticks(())\nplt.show()",
"WARNING:root:try: 0, score 0.986\nWARNING:root:try: 1, score 0.988\nWARNING:root:try: 2, score 0.976\nWARNING:root:try: 3, score 0.982\nWARNING:root:try: 4, score 0.981\nWARNING:root:best score: 0.988\nWARNING:root:try: 0, score 0.986\nWARNING:root:try: 1, score 0.994\nWARNING:root:try: 2, score 0.994\nWARNING:root:try: 3, score 0.979\nWARNING:root:try: 4, score 0.994\nWARNING:root:best score: 0.994\nWARNING:root:reduction in number of clusers,from 5 to 4\nWARNING:root:try: 0, score 0.976\nWARNING:root:try: 1, score 0.976\nWARNING:root:try: 2, score 0.981\nWARNING:root:try: 3, score 0.984\nWARNING:root:try: 4, score 0.985\nWARNING:root:best score: 0.985\nWARNING:root:try: 0, score 0.985\nWARNING:root:try: 1, score 0.979\nWARNING:root:try: 2, score 0.980\nWARNING:root:try: 3, score 0.982\nWARNING:root:try: 4, score 0.980\nWARNING:root:best score: 0.985\n/Users/jattenberg/development/clustering_by_classification/virt/lib/python3.7/site-packages/sklearn/model_selection/_split.py:672: UserWarning: The least populated class in y has only 4 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nWARNING:root:try: 0, score 0.987\nWARNING:root:try: 1, score 0.987\nWARNING:root:try: 2, score 0.982\nWARNING:root:try: 3, score 0.981\nWARNING:root:try: 4, score 0.981\nWARNING:root:best score: 0.987\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
4a925fa665843a95107e8133182b0ecaa8baea7b
| 45,089 |
ipynb
|
Jupyter Notebook
|
doc/caret2sql-ctree2-iris.ipynb
|
antoinecarme/caret2sql
|
521e0690cf35b63010d25290d4b29e762b98d906
|
[
"BSD-3-Clause"
] | 3 |
2019-04-23T10:25:14.000Z
|
2021-03-23T06:40:57.000Z
|
doc/caret2sql-ctree2-iris.ipynb
|
antoinecarme/caret2sql
|
521e0690cf35b63010d25290d4b29e762b98d906
|
[
"BSD-3-Clause"
] | 24 |
2018-07-25T17:08:26.000Z
|
2019-04-03T12:07:39.000Z
|
doc/caret2sql-ctree2-iris.ipynb
|
antoinecarme/caret2sql
|
521e0690cf35b63010d25290d4b29e762b98d906
|
[
"BSD-3-Clause"
] | 1 |
2019-04-23T10:25:13.000Z
|
2019-04-23T10:25:13.000Z
| 60.603495 | 973 | 0.393533 |
[
[
[
"library(caret, quiet=TRUE);\nlibrary(base64enc)\nlibrary(httr, quiet=TRUE)\n",
"\nAttaching package: ‘httr’\n\nThe following object is masked from ‘package:caret’:\n\n progress\n\n"
]
],
[
[
"# Build a Model",
"_____no_output_____"
]
],
[
[
"set.seed(1960)\n\ncreate_model = function() {\n\n model <- train(Species ~ ., data = iris, method = \"ctree2\")\n \n return(model)\n}",
"_____no_output_____"
],
[
"# dataset\nmodel = create_model()",
"_____no_output_____"
],
[
"# pred <- predict(model, as.matrix(iris[, -5]) , type=\"prob\")\npred_labels <- predict(model, as.matrix(iris[, -5]) , type=\"raw\")\nsum(pred_labels != iris$Species)/length(pred_labels)\n",
"_____no_output_____"
]
],
[
[
"# SQL Code Generation",
"_____no_output_____"
]
],
[
[
"\ntest_ws_sql_gen = function(mod) {\n WS_URL = \"https://sklearn2sql.herokuapp.com/model\"\n WS_URL = \"http://localhost:1888/model\"\n model_serialized <- serialize(mod, NULL)\n b64_data = base64encode(model_serialized)\n data = list(Name = \"caret_rpart_test_model\", SerializedModel = b64_data , SQLDialect = \"postgresql\" , Mode=\"caret\")\n r = POST(WS_URL, body = data, encode = \"json\")\n # print(r)\n content = content(r)\n # print(content)\n lSQL = content$model$SQLGenrationResult[[1]]$SQL # content[\"model\"][\"SQLGenrationResult\"][0][\"SQL\"]\n return(lSQL);\n}",
"_____no_output_____"
],
[
"lModelSQL = test_ws_sql_gen(model)",
"_____no_output_____"
],
[
"cat(lModelSQL)\n",
"WITH \"DT_node_lookup\" AS \n(SELECT \"ADS\".\"KEY\" AS \"KEY\", CASE WHEN (\"ADS\".\"Feature_2\" <= 1.9) THEN 2 ELSE CASE WHEN (\"ADS\".\"Feature_3\" <= 1.7) THEN CASE WHEN (\"ADS\".\"Feature_2\" <= 4.8) THEN 5 ELSE 6 END ELSE CASE WHEN (\"ADS\".\"Feature_2\" <= 5.0) THEN 8 ELSE 9 END END END AS node_id_2 \nFROM \"INPUT_DATA\" AS \"ADS\"), \n\"DT_node_data\" AS \n(SELECT \"Values\".nid AS nid, \"Values\".\"P_setosa\" AS \"P_setosa\", \"Values\".\"P_versicolor\" AS \"P_versicolor\", \"Values\".\"P_virginica\" AS \"P_virginica\", \"Values\".\"D\" AS \"D\", \"Values\".\"DP\" AS \"DP\" \nFROM (SELECT 2 AS nid, 1.0 AS \"P_setosa\", 0.0 AS \"P_versicolor\", 0.0 AS \"P_virginica\", 'setosa' AS \"D\", 1.0 AS \"DP\" UNION ALL SELECT 5 AS nid, 0.0 AS \"P_setosa\", 0.9782608695652174 AS \"P_versicolor\", 0.02173913043478261 AS \"P_virginica\", 'versicolor' AS \"D\", 0.9782608695652174 AS \"DP\" UNION ALL SELECT 6 AS nid, 0.0 AS \"P_setosa\", 0.5 AS \"P_versicolor\", 0.5 AS \"P_virginica\", 'versicolor' AS \"D\", 0.5 AS \"DP\" UNION ALL SELECT 8 AS nid, 0.0 AS \"P_setosa\", 0.125 AS \"P_versicolor\", 0.875 AS \"P_virginica\", 'virginica' AS \"D\", 0.875 AS \"DP\" UNION ALL SELECT 9 AS nid, 0.0 AS \"P_setosa\", 0.0 AS \"P_versicolor\", 1.0 AS \"P_virginica\", 'virginica' AS \"D\", 1.0 AS \"DP\") AS \"Values\"), \n\"DT_Output\" AS \n(SELECT \"DT_node_lookup\".\"KEY\" AS \"KEY\", \"DT_node_lookup\".node_id_2 AS node_id_2, \"DT_node_data\".nid AS nid, \"DT_node_data\".\"P_setosa\" AS \"P_setosa\", \"DT_node_data\".\"P_versicolor\" AS \"P_versicolor\", \"DT_node_data\".\"P_virginica\" AS \"P_virginica\", \"DT_node_data\".\"D\" AS \"D\", \"DT_node_data\".\"DP\" AS \"DP\" \nFROM \"DT_node_lookup\" LEFT OUTER JOIN \"DT_node_data\" ON \"DT_node_lookup\".node_id_2 = \"DT_node_data\".nid)\n SELECT \"DT_Output\".\"KEY\" AS \"KEY\", CAST(NULL AS FLOAT) AS \"Score_setosa\", CAST(NULL AS FLOAT) AS \"Score_versicolor\", CAST(NULL AS FLOAT) AS \"Score_virginica\", \"DT_Output\".\"P_setosa\" AS \"Proba_setosa\", \"DT_Output\".\"P_versicolor\" AS \"Proba_versicolor\", \"DT_Output\".\"P_virginica\" AS \"Proba_virginica\", CASE WHEN (\"DT_Output\".\"P_setosa\" IS NULL OR \"DT_Output\".\"P_setosa\" > 0.0) THEN ln(\"DT_Output\".\"P_setosa\") ELSE -1.79769313486231e+308 END AS \"LogProba_setosa\", CASE WHEN (\"DT_Output\".\"P_versicolor\" IS NULL OR \"DT_Output\".\"P_versicolor\" > 0.0) THEN ln(\"DT_Output\".\"P_versicolor\") ELSE -1.79769313486231e+308 END AS \"LogProba_versicolor\", CASE WHEN (\"DT_Output\".\"P_virginica\" IS NULL OR \"DT_Output\".\"P_virginica\" > 0.0) THEN ln(\"DT_Output\".\"P_virginica\") ELSE -1.79769313486231e+308 END AS \"LogProba_virginica\", \"DT_Output\".\"D\" AS \"Decision\", \"DT_Output\".\"DP\" AS \"DecisionProba\" \nFROM \"DT_Output\""
]
],
[
[
"# Execute the SQL Code",
"_____no_output_____"
]
],
[
[
"library(RODBC)\nconn = odbcConnect(\"pgsql\", uid=\"db\", pwd=\"db\", case=\"nochange\")\nodbcSetAutoCommit(conn , autoCommit = TRUE)",
"_____no_output_____"
],
[
"dataset = iris[,-5]\n\ndf_sql = as.data.frame(dataset)\nnames(df_sql) = sprintf(\"Feature_%d\",0:(ncol(df_sql)-1))\ndf_sql$KEY = seq.int(nrow(dataset))\n\nsqlDrop(conn , \"INPUT_DATA\" , errors = FALSE)\nsqlSave(conn, df_sql, tablename = \"INPUT_DATA\", verbose = FALSE)\n\nhead(df_sql)",
"_____no_output_____"
],
[
"# colnames(df_sql)\n# odbcGetInfo(conn)\n# sqlTables(conn)",
"_____no_output_____"
],
[
"df_sql_out = sqlQuery(conn, lModelSQL)\nhead(df_sql_out)",
"_____no_output_____"
]
],
[
[
"# R Caret Rpart Output",
"_____no_output_____"
]
],
[
[
"# pred_proba = predict(model, as.matrix(iris[,-5]), type = \"prob\")\ndf_r_out = data.frame(seq.int(nrow(dataset))) # (pred_proba)\nnames(df_r_out) = c(\"KEY\") # sprintf(\"Proba_%s\",model$levels)\n\ndf_r_out$KEY = seq.int(nrow(dataset))\ndf_r_out$Score_setosa = NA\ndf_r_out$Score_versicolor = NA\ndf_r_out$Score_virginica = NA\ndf_r_out$Proba_setosa = NA\ndf_r_out$Proba_versicolor = NA\ndf_r_out$Proba_virginica = NA\ndf_r_out$LogProba_setosa = log(df_r_out$Proba_setosa)\ndf_r_out$LogProba_versicolor = log(df_r_out$Proba_versicolor)\ndf_r_out$LogProba_virginica = log(df_r_out$Proba_virginica)\ndf_r_out$Decision = predict(model, as.matrix(iris[,-5]), type = \"raw\")\ndf_r_out$DecisionProba = NA\nhead(df_r_out)\n\n",
"_____no_output_____"
]
],
[
[
"# Compare R and SQL output",
"_____no_output_____"
]
],
[
[
"df_merge = merge(x = df_r_out, y = df_sql_out, by = \"KEY\", all = TRUE, , suffixes = c(\"_1\",\"_2\"))\nhead(df_merge)",
"_____no_output_____"
],
[
"diffs_df = df_merge[df_merge$Decision_1 != df_merge$Decision_2,]\nhead(diffs_df)",
"Warning message in cbind(parts$left, ellip_h, parts$right, deparse.level = 0L):\n“number of rows of result is not a multiple of vector length (arg 2)”Warning message in cbind(parts$left, ellip_h, parts$right, deparse.level = 0L):\n“number of rows of result is not a multiple of vector length (arg 2)”Warning message in cbind(parts$left, ellip_h, parts$right, deparse.level = 0L):\n“number of rows of result is not a multiple of vector length (arg 2)”Warning message in cbind(parts$left, ellip_h, parts$right, deparse.level = 0L):\n“number of rows of result is not a multiple of vector length (arg 2)”"
],
[
"stopifnot(nrow(diffs_df) == 0)",
"_____no_output_____"
],
[
"summary(df_r_out)",
"_____no_output_____"
],
[
"summary(df_sql_out)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4a9264db282ed2b6392967147cc750e86301feae
| 19,273 |
ipynb
|
Jupyter Notebook
|
cnn_cifar10.ipynb
|
ferdouszislam/pytorch-practice
|
e14129c3a520f9610a431e70e4da14e7ae50d2e1
|
[
"MIT"
] | null | null | null |
cnn_cifar10.ipynb
|
ferdouszislam/pytorch-practice
|
e14129c3a520f9610a431e70e4da14e7ae50d2e1
|
[
"MIT"
] | null | null | null |
cnn_cifar10.ipynb
|
ferdouszislam/pytorch-practice
|
e14129c3a520f9610a431e70e4da14e7ae50d2e1
|
[
"MIT"
] | null | null | null | 33.286701 | 238 | 0.469984 |
[
[
[
"<a href=\"https://colab.research.google.com/github/ferdouszislam/pytorch-practice/blob/main/cnn_cifar10.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import torch \nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndevice",
"_____no_output_____"
],
[
"# hyper parameters\nnum_epochs = 20\nbatch_size = 64\nlearning_rate = 0.001",
"_____no_output_____"
],
[
"# load dataset\ntransform = transforms.Compose(\n [\n transforms.ToTensor(), \n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]\n)\n\ntrain_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntest_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n\ntrain_loader = torch.utils.data.DataLoader(train_dataset, \n batch_size=batch_size, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(test_dataset, \n batch_size=batch_size, shuffle=False)\n\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') ",
"Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz\n"
],
[
"# convolutional neural network\nclass ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n\n # 5x5 conv kernel/filter\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=5) \n \n # 2x2 maxpooling\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2) \n \n # 5x5 conv kernel/filter\n self.conv2 = nn.Conv2d(6, 16, 5)\n \n # 3x32x32 --conv1--> 6x28x28 --maxpool--> 6x14x14\n # 6x14x14 --conv2--> 16x10x10 --maxpool--> 16x5x5\n self.fc1 = nn.Linear(16*5*5, 120) \n self.fc2 = nn.Linear(120, 84) \n self.fc3 = nn.Linear(84, 10)\n self.relu = nn.ReLU()\n\n def forward(self, input):\n # conv1 -> relu -> maxpool\n output = self.pool(self.relu(self.conv1(input))) \n # conv2 -> relu -> maxpool\n output = self.pool(self.relu(self.conv2(output)))\n\n # flatten\n output = output.reshape(-1, 16*5*5)\n # -> fc1 -> relu\n output = self.relu(self.fc1(output))\n # -> fc2 -> relu\n output = self.relu(self.fc2(output))\n # fc3 (no activation at end)\n output = self.fc3(output)\n\n return output",
"_____no_output_____"
],
[
"model = ConvNet().to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)",
"_____no_output_____"
],
[
"for epoch in range(num_epochs):\n avg_batch_loss = 0\n for step, (images, labels) in enumerate(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n\n # forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n\n # backward pass\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # accumulate batch loss\n avg_batch_loss+=loss\n\n avg_batch_loss /= len(train_loader)\n\n print(f'epoch {epoch+1}/{num_epochs}, loss = {avg_batch_loss:.4f}')",
"epoch 1/20, loss = 1.2382\nepoch 2/20, loss = 1.2164\nepoch 3/20, loss = 1.1937\nepoch 4/20, loss = 1.1727\nepoch 5/20, loss = 1.1545\nepoch 6/20, loss = 1.1355\nepoch 7/20, loss = 1.1186\nepoch 8/20, loss = 1.1008\nepoch 9/20, loss = 1.0837\nepoch 10/20, loss = 1.0700\nepoch 11/20, loss = 1.0550\nepoch 12/20, loss = 1.0403\nepoch 13/20, loss = 1.0263\nepoch 14/20, loss = 1.0144\nepoch 15/20, loss = 1.0011\nepoch 16/20, loss = 0.9878\nepoch 17/20, loss = 0.9759\nepoch 18/20, loss = 0.9642\nepoch 19/20, loss = 0.9514\nepoch 20/20, loss = 0.9402\n"
],
[
"PATH = './cnn.pth'\ntorch.save(model.state_dict(), PATH)\n\nwith torch.no_grad():\n n_correct = 0\n n_samples = 0\n for images, labels in test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n # max returns (value ,index)\n _, predicted = torch.max(outputs, 1)\n n_samples += labels.size(0)\n n_correct += (predicted == labels).sum().item()\n\n acc = 100.0 * n_correct / n_samples\n print(f'Accuracy of the network: {acc}%')",
"Accuracy of the network: 62.47%\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a92883434e74e8d4f14c56d72dfe5c9b9d8eb17
| 78,452 |
ipynb
|
Jupyter Notebook
|
ChartHomework/ChartsHomework.ipynb
|
lexieheinle/jour407homework
|
16dce4e30671499bea711216e2aba65f3a787d1c
|
[
"MIT"
] | 2 |
2017-03-25T23:05:02.000Z
|
2021-03-05T03:49:14.000Z
|
ChartHomework/ChartsHomework.ipynb
|
lexieheinle/jour407homework
|
16dce4e30671499bea711216e2aba65f3a787d1c
|
[
"MIT"
] | 1 |
2016-03-06T17:36:26.000Z
|
2016-03-06T17:36:26.000Z
|
ChartHomework/ChartsHomework.ipynb
|
lexieheinle/jour407homework
|
16dce4e30671499bea711216e2aba65f3a787d1c
|
[
"MIT"
] | 2 |
2016-03-06T17:30:06.000Z
|
2017-03-25T23:05:05.000Z
| 469.772455 | 25,624 | 0.933921 |
[
[
[
"Seaborn provides a easy framework to edit matplotlib charts. \nPandas pulls in the data. sns.set allows a one set default for the program.",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nsns.set(style=\"ticks\", context='talk', font_scale=1.1)\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"Read the csv file into a panda",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('top10mountain-lions.csv')",
"_____no_output_____"
]
],
[
[
"Chart 1 features a whitegrid style to help assign a number to each bar. Despine removes Tufte's chart junk.",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"whitegrid\")\nsns.barplot(x=\"count\", y=\"COUNTY\", data=df, color=\"#2ecc71\")\nsns.despine(bottom=True, left=True)",
"_____no_output_____"
]
],
[
[
"Chart 2 features a white chart style. Y label is removed because county label is redudant. Also, X label is more useful. Despine removes Tufte's chart junk.\n\nI think this chart is the most effective although I would decrease the scale to every 10. Another weakness is probably a locational aspect to the sightings and that relationship isn't shown in the bar chart.",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"white\")\nsns.barplot(x=\"count\", y=\"COUNTY\", data=df, color=\"#f6a14e\")\nplt.ylabel('')\nplt.xlabel('Mountain Lion Sightings')\nsns.despine(bottom=True, left=True)",
"_____no_output_____"
]
],
[
[
"Chart 3 features a dark grid style. Although the grid helps assign values to the bars, the color is distracting and tends to chart junk",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"darkgrid\")\nsns.barplot(x=\"count\", y=\"COUNTY\", data=df, color=\"#7fe5ba\")\nplt.ylabel('')\nplt.xlabel('Mountain Lion Sightings')\nsns.despine(bottom=True, left=True)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a9290d202e7c134cfe03c50ddb68d99095052af
| 16,073 |
ipynb
|
Jupyter Notebook
|
01_DataTypes-Markdown.ipynb
|
billquinn/Teaching-Python
|
fa2a0bab19d80baa291a91fae54b50bc97eaa31d
|
[
"MIT"
] | null | null | null |
01_DataTypes-Markdown.ipynb
|
billquinn/Teaching-Python
|
fa2a0bab19d80baa291a91fae54b50bc97eaa31d
|
[
"MIT"
] | null | null | null |
01_DataTypes-Markdown.ipynb
|
billquinn/Teaching-Python
|
fa2a0bab19d80baa291a91fae54b50bc97eaa31d
|
[
"MIT"
] | null | null | null | 30.969171 | 554 | 0.578672 |
[
[
[
"# Python Data Types and Markdown\n\nThis tutorial covers the very basics of Python and Markdown.\n\n> Because this file is saved on GitHub, you should feel free to change whatever you want in this file and even try to break it. Breaking code and then trying to fix it again is a fantastic way to learn how code works—AS LONG AS you have a saved checkpoint or backup. It's always good practice to save works in progress frequently and, if you achieve a significant milestone, perhaps copy the file before going forward in case you need to reset. If you break anything in this repository, simply re-download the files that you need and start over.\n\n",
"_____no_output_____"
],
[
"## Markdown\n\nJupyter Notebook allows writers to declare cells as \"code\" or \"markdown.\" Markdown is very useful for commenting on code and is a common syntax for blogging. Cells default to \"code.\" To change a cell to markdown, simply click the dropdown menu at the top center that reads, \"Code,\" and change it to \"Markdown.\"\n\nWith the cell now set to markdown, you can now write like most text editors. There are some codes that can change formatting, such as headers, italics, underline, etc. You can also provide hyperlinks and add images. You can browse and become familiar with markdown codes here: https://guides.github.com/pdfs/markdown-cheatsheet-online.pdf.\n\n## Python\n\n",
"_____no_output_____"
],
[
"## Data Types\n\nPython recognizes different simple and complex data types. \n\nStarting with simple data types, we will see how Python can do math and work with \"strings,\" or text values.\n\n1. Integers\n2. Strings\n3. Floats\n\n#### Integers\n\nTo run a cell, you can press Shift + Enter or press the Run button in the top menu.",
"_____no_output_____"
]
],
[
[
"1 + 1",
"_____no_output_____"
]
],
[
[
"Python can perform mathematical functions using basic notation (+, -, /, \\*, ^) as well as follows order of operations.\n\n#### Strings\n\nA string is a value between single or double quotation marks (\" \" or ' '). Python recognizes strings with these quotation marks. To include quotations marks within the string, you can either escape the quotation mark with a slash (\\\") or use single quotation marks within double and vice-versa (\"...' '...\").",
"_____no_output_____"
]
],
[
[
"\"Concatenating\" + \" \" + \"Strings\" ",
"_____no_output_____"
]
],
[
[
"Python can also use + to concatenate string types. \"Concatenate\" is the term common in coding that refers to joining data (often strings) together. Concatenating can take two or more string types and join them together to create a longer string.\n\n#### Floats",
"_____no_output_____"
]
],
[
[
"0.2 + 2",
"_____no_output_____"
]
],
[
[
"\"Floats\" refer to numerical values with decimal values. Some texts include numerical reports within them. This can cause problems when you're trying to parse \"text,\" data you think is a string, but contains numerical or float values, leading to a TypeError. \n\nWe won't need to deal with floats for the most part with the libraries we will eventually be using. But, it's important to know what a \"float\" is.\n\n### Brief Note on Errors",
"_____no_output_____"
]
],
[
[
"# Integers and Strings >>> Notice, too, this comment, which is ignored when running code.\n# Put a '#' in front of text on a line to create a comment.\n1 + \"1\"",
"_____no_output_____"
]
],
[
[
"The error here, TypeError, occurs when a function fails to work with different data types. Here, \"1\" is not a numerical value. Error reports in Python can be quite confusing. For many errors, you can debug them by first looking at the very bottom of the report for the error type. \n\n\"TypeError: unsupported operand type(s) for +: 'int' and 'str'\" means that an error occurred around the plus sign operand, \"+.\" More specifically, the error occurred because \"+\" cannot join or add and integer ('int') with a string ('str').\n\nSometimes, the report will also tell you where within the cell the error happened. The '----> 2' symbol in the left margin indicates that the error happened on the second line of the cell.\n\nDecoding error reports can be maddening. One common experience for debugging is examining each line for missing punctuation or typo. Learning how to read error reports can be very frustrating at first, but gradually gets better. Copying and pasting the error line (\"TypeError: unsupported operand type(s) for +: 'int' and 'str'\") can be a productive starting point. But, ultimately, reading errors only gets better with time and practice.\n\n## Defining Variables\n\nPython allows coders to create their own variables, which stores different value types. To create a variable, create a name, in this case \"x\", and use the equal sign (=) to assign a value to the name.",
"_____no_output_____"
]
],
[
[
"x = 1\n\n1 + x",
"_____no_output_____"
],
[
"x = \"words\"\n\n\"concatenating\" + \" \" + x",
"_____no_output_____"
],
[
"x + 1",
"_____no_output_____"
]
],
[
[
"We get another TypeError because we overwrote \"x,\" making the integer value into a string type, and we cannot to join strings and integers.\n\nPython offers a way to change value types.",
"_____no_output_____"
]
],
[
[
"x = \"1\"\n\n# 1 + x : This will also fail because x is still a string value. But,\n\n1 + int(x)",
"_____no_output_____"
]
],
[
[
"Here, we use a Python function to change \"x\" temporally to an integer data type, which allows us to add 1 + 1. \n\nPython functions follow certain grammatical rules. That is, functions typically have a name, in the case above \"int,\" followed by parenthesis. The function int() acts on the variable \"x.\"\n\nA later notebook will cover functions in more detail, but, here, we can see how data types can be changed.\n\n## Complex Data Types\n\nThere are more data types that are more complex. Although the following data types are more complex, they build off simpler types. The following types gather simpler value types into recognizable structures. There are more data types than these, but we will be focusing on the two most common types.\n\n1. Lists\n2. Dictionaries\n\n#### Lists\n\nA list is a collection of values that occur between square brackets ([ ]). As a data structure, lists provide diff erent functionlity than other data types.",
"_____no_output_____"
]
],
[
[
"my_list = [1, 2, 3, 4] # Each value in a list is separated by a comma.\n\nmy_list",
"_____no_output_____"
]
],
[
[
"Lists are also indexed, so I can access a single value.",
"_____no_output_____"
]
],
[
[
"my_list[0]",
"_____no_output_____"
]
],
[
[
"Notice that Python starts counting at zero. The value in the zero position of my_list is 1.\n\n#### Dictionaries\n\nA list provides a range of values (integers, strings, even lists within a list) that do not necessarily have any relation other than being in a list. A dictionary, on the other hand, is similar to a list except that it has keys and values. That is, it conveys a relationship between a \"key\" and that key's \"value.\" A dictionary is a collection of information between curly brackets { }.",
"_____no_output_____"
]
],
[
[
"my_dictionary = {\n 'name': 'Bill',\n 'grade': 'B'\n}\n\nmy_dictionary",
"_____no_output_____"
]
],
[
[
"While we will be using dataframes, a data structure we'll discuss later, dictionaries can be very good at structuring data.\n\nIt's worth noting as well, that lists and dictionaries can work within each other and become nested. For example, I can put my_list into my_dictionary as a value.",
"_____no_output_____"
]
],
[
[
"my_dictionary['list'] = my_list\n\nmy_dictionary",
"_____no_output_____"
]
],
[
[
"The first line in the cell above does two things:\n1. Create a new key named 'list'\n2. Append a value, my_list to the key\n\nI can also change the value of 'list' using the same syntax.",
"_____no_output_____"
]
],
[
[
"my_dictionary['list'] = [5, 6, 7, 8]\n\nmy_dictionary",
"_____no_output_____"
]
],
[
[
"I can retrieve keys and values as well using default functions.",
"_____no_output_____"
]
],
[
[
"my_dictionary.keys()",
"_____no_output_____"
]
],
[
[
"The data types and structures here are not exhaustive. There are other types that you will likely encounter. And, the data types you do encounter will likely be much larger and complex than the ones here. But, this template covers the very basics of data types in Python.\n\nKnowing how to access and change the fundamental data structures and types of Python will become essential for adapting code from the internet. Often, functions require specific data types and structures as input that will likely differ from how your dataset is constructed. ",
"_____no_output_____"
],
[
"____\n\n# Sandbox\n\nTo gain familiarity with data types, try the following exercises:\n\n1. Create a variable that stores a string value.\n2. Concatenate that variable with another string.\n3. Create a short list of variables.\n4. Make a dictionary with a key and set its value to the short list you just created.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4a92a517fe78e5b4ad77854a02698749ac9b4de8
| 54,394 |
ipynb
|
Jupyter Notebook
|
module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
|
cocoisland/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments
|
a15fb98ad38b66698752bfccf8158fe5601cc1b0
|
[
"MIT"
] | null | null | null |
module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
|
cocoisland/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments
|
a15fb98ad38b66698752bfccf8158fe5601cc1b0
|
[
"MIT"
] | null | null | null |
module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb
|
cocoisland/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments
|
a15fb98ad38b66698752bfccf8158fe5601cc1b0
|
[
"MIT"
] | null | null | null | 49.136405 | 14,464 | 0.561202 |
[
[
[
"<a href=\"https://colab.research.google.com/github/cocoisland/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments/blob/master/module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Lambda School Data Science Module 142\n## Sampling, Confidence Intervals, and Hypothesis Testing",
"_____no_output_____"
],
[
"## Prepare - examine other available hypothesis tests\n\nIf you had to pick a single hypothesis test in your toolbox, t-test would probably be the best choice - but the good news is you don't have to pick just one! Here's some of the others to be aware of:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom scipy.stats import chisquare # One-way chi square test\n\n# Chi square can take any crosstab/table and test the independence of rows/cols\n# The null hypothesis is that the rows/cols are independent -> low chi square\n# rows/cols independent -> statistic closer to mean or 0 null distribution\n# - pvalue larger than 0.01 or 0.05\n# - null hypothesis true, random chance/probability, no relationship\n# - eg good rating rave does not apply to drug reviews.\n#\n# rows/cols dependent -> statistic far out into x-axis infinity on null distribution.\n# - pvalue less than 0.05 or 0.01\n# - null hypothesis rejected, no random chance, dependent relationship.\n# - drug review ratings are true, trusted and accepted.\n#\n# The alternative is that there is a dependence -> high chi square\n# Be aware! Chi square does *not* tell you direction/causation\n\nind_obs = np.array([[1, 1], [2, 2]]).T\nprint(ind_obs)\nprint(chisquare(ind_obs, axis=None))\n\ndep_obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T\nprint(dep_obs)\nprint(chisquare(dep_obs, axis=None))",
"[[1 2]\n [1 2]]\nPower_divergenceResult(statistic=0.6666666666666666, pvalue=0.8810148425137847)\n[[16 32]\n [18 24]\n [16 16]\n [14 28]\n [12 20]\n [12 24]]\nPower_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565)\n"
],
[
"# Distribution tests:\n# We often assume that something is normal, but it can be important to *check*\n\n# For example, later on with predictive modeling, a typical assumption is that\n# residuals (prediction errors) are normal - checking is a good diagnostic\n\nfrom scipy.stats import normaltest\n# Poisson models arrival times and is related to the binomial (coinflip)\nsample = np.random.poisson(5, 1000)\nprint(normaltest(sample)) # Pretty clearly not normal",
"NormaltestResult(statistic=38.69323106073592, pvalue=3.961609200867749e-09)\n"
],
[
"# Kruskal-Wallis H-test - compare the median rank between 2+ groups\n# Can be applied to ranking decisions/outcomes/recommendations\n# The underlying math comes from chi-square distribution, and is best for n>5\nfrom scipy.stats import kruskal\n\nx1 = [1, 3, 5, 7, 9]\ny1 = [2, 4, 6, 8, 10]\nprint(kruskal(x1, y1)) # x1 is a little better, but not \"significantly\" so\n\nx2 = [1, 1, 1]\ny2 = [2, 2, 2]\nz = [2, 2] # Hey, a third group, and of different size!\nprint(kruskal(x2, y2, z)) # x clearly dominates",
"KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)\nKruskalResult(statistic=7.0, pvalue=0.0301973834223185)\n"
]
],
[
[
"And there's many more! `scipy.stats` is fairly comprehensive, though there are even more available if you delve into the extended world of statistics packages. As tests get increasingly obscure and specialized, the importance of knowing them by heart becomes small - but being able to look them up and figure them out when they *are* relevant is still important.",
"_____no_output_____"
],
[
"## Live Lecture - let's explore some more of scipy.stats",
"_____no_output_____"
]
],
[
[
"# Taking requests! Come to lecture with a topic or problem and we'll try it.\n",
"_____no_output_____"
]
],
[
[
"### Confidence interval\n* Similar to hypothesis testing, but centered at sample mean\n\n* Reporting the 95% confidence interval, is better than reporting the point estimate at sample mean.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom scipy import stats\n\ndef confidence_interval(data, confidence=0.95):\n '''\n Calculate confidence_interval around a sample mean for a given data size.\n Using t-distribution and two-tailed test, default 95% confidence\n Arguments:\n data - iterable(list or np.array) of sample observations\n confidence - level of confidence for the interval\n Return:\n tuples of (mean, lower bound, upper bound)\n '''\n data = np.array(data)\n mean = data.mean()\n degree_of_freedom = len(data) - 1\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf( (1+confidence)/2., degree_of_freedom )\n return(mean, mean-interval, mean+interval)\n\ndef report_confidence_interval(confidence_interval):\n '''\n Arguments:\n tuples of (mean, lower bound, upper bound)\n Return:\n print report of confidence interval\n '''\n s='\"Sample mean in interval {} - {} - {}\".format(\n confidence_interval[1], \n confidence_interval[0]\n confidence_interval[2]'\n print(s)\n ",
"_____no_output_____"
]
],
[
[
"## Assignment - Build a confidence interval\n\nA confidence interval refers to a neighborhood around some point estimate, the size of which is determined by the desired p-value. For instance, we might say that 52% of Americans prefer tacos to burritos, with a 95% confidence interval of +/- 5%.\n\n52% (0.52) is the point estimate, and +/- 5% (the interval $[0.47, 0.57]$) is the confidence interval. \"95% confidence\" means a p-value $\\leq 1 - 0.95 = 0.05$.\n\nIn this case, the confidence interval includes $0.5$ - which is the natural null hypothesis (that half of Americans prefer tacos and half burritos, thus there is no clear favorite). So in this case, we could use the confidence interval to report that we've failed to reject the null hypothesis.\n\nBut providing the full analysis with a confidence interval, including a graphical representation of it, can be a helpful and powerful way to tell your story. Done well, it is also more intuitive to a layperson than simply saying \"fail to reject the null hypothesis\" - it shows that in fact the data does *not* give a single clear result (the point estimate) but a whole range of possibilities.\n\nHow is a confidence interval built, and how should it be interpreted? It does *not* mean that 95% of the data lies in that interval - instead, the frequentist interpretation is \"if we were to repeat this experiment 100 times, we would expect the average result to lie in this interval ~95 times.\"\n\nFor a 95% confidence interval and a normal(-ish) distribution, you can simply remember that +/-2 standard deviations contains 95% of the probability mass, and so the 95% confidence interval based on a given sample is centered at the mean (point estimate) and has a range of +/- 2 (or technically 1.96) standard deviations.\n\nDifferent distributions/assumptions (90% confidence, 99% confidence) will require different math, but the overall process and interpretation (with a frequentist approach) will be the same.\n\nYour assignment - using the data from the prior module ([congressional voting records](https://archive.ics.uci.edu/ml/datasets/Congressional+Voting+Records)):\n\n1. Generate and numerically represent a confidence interval\n2. Graphically (with a plot) represent the confidence interval\n3. Interpret the confidence interval - what does it tell you about the data and its distribution?\n\nStretch goals:\n\n1. Write a summary of your findings, mixing prose and math/code/results. *Note* - yes, this is by definition a political topic. It is challenging but important to keep your writing voice *neutral* and stick to the facts of the data. Data science often involves considering controversial issues, so it's important to be sensitive about them (especially if you want to publish).\n2. Apply the techniques you learned today to your project data or other data of your choice, and write/discuss your findings here.",
"_____no_output_____"
]
],
[
[
"# TODO - your code!\n'''\nDrug company testing\n'''\nurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00462/drugsCom_raw.zip'\n!wget $url",
"--2018-12-05 19:36:58-- http://archive.ics.uci.edu/ml/machine-learning-databases/00462/drugsCom_raw.zip\nResolving archive.ics.uci.edu (archive.ics.uci.edu)... 128.195.10.249\nConnecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.249|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 42989872 (41M) [application/zip]\nSaving to: ‘drugsCom_raw.zip’\n\ndrugsCom_raw.zip 100%[===================>] 41.00M 22.1MB/s in 1.9s \n\n2018-12-05 19:37:00 (22.1 MB/s) - ‘drugsCom_raw.zip’ saved [42989872/42989872]\n\n"
],
[
"!unzip drugsCom_raw.zip\n",
"Archive: drugsCom_raw.zip\n inflating: drugsComTest_raw.tsv \n inflating: drugsComTrain_raw.tsv \n"
],
[
"import pandas as pd\nfrom scipy.stats import chisquare\n\ndf = pd.read_table('drugsComTrain_raw.tsv')\ndf.head()",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"'''\nGiven 161297 observation,\n pvalue=0.7, this sample distribution greater than 0.05\n statistic=733, fat tailed sample data point.\n \nNull hypothesis not rejected, this drug rating can not be trusted with confidence\n'''\nrating_liraglutide = df[ df['drugName']=='Liraglutide' ]['rating']\nchisquare(rating_liraglutide, axis=None)",
"_____no_output_____"
],
[
"drugs=df['drugName'].unique()\nlen(drugs)",
"_____no_output_____"
],
[
"drug_rating = pd.DataFrame(columns=['drugName','statistic','pvalue'])\ni=0\nfor drug in drugs:\n rating = df[ df['drugName']== drug ]['rating']\n s,p = chisquare(rating, axis=None)\n drug_rating.loc[i] = [drug,s,p]\n i = i + 1\n \n \n ",
"_____no_output_____"
],
[
"drug_rating.dropna(inplace=True)",
"_____no_output_____"
],
[
"#data_plot = drug_rating[ drug_rating['pvalue'] < 0.001 ][['drugName','pvalue']].sort_values('pvalue')\n\n",
"_____no_output_____"
],
[
"'''\nDrugs with lot of review ratings, \n - chisquare able to establish dependent relationship\n - gives high confidence pvalue with infinity small value\n - drug review rating can be trusted because the rating applied to the drugs.\n'''\ndrug_rating.sort_values('pvalue').head()",
"_____no_output_____"
],
[
"'''\ndrug rating with little reviews has high pvalue\n - pvalue of 1.0 = blant no relationship between drug and review rating.\n - Rating for these drugs can not be trusted.\n'''\ndrug_rating.sort_values('pvalue').tail()",
"_____no_output_____"
],
[
"'''\nDrugName with the most number of rating entry\n'''\ndf.groupby('drugName').sum().sort_values('rating', ascending=False).head()",
"_____no_output_____"
],
[
"'''\ndrugName with least rating entry\n'''\ndf.groupby('drugName').sum().sort_values('rating').head()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\n\n'''\norder does not display right\n'''\ndata_plot['order']= [10,8,6,4,2]\ny_pos = np.arange(len(data_plot))\n\nplt.barh(data_plot.drugName, data_plot.order)\nplt.yticks(y_pos, data_plot.drugName)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a92a51a39346c302a68b8a3d19cff6c6221595d
| 102,530 |
ipynb
|
Jupyter Notebook
|
Notebooks/cpu_and_gpu_end_to_end_example/gpu_End_to_End.ipynb
|
quasiben/rapids-dask-tutorial-2021
|
493ce39d057292f49ba61106d94d41e2dbc49ed9
|
[
"BSD-3-Clause"
] | 7 |
2021-05-20T18:55:27.000Z
|
2022-02-08T16:39:24.000Z
|
Notebooks/cpu_and_gpu_end_to_end_example/gpu_End_to_End.ipynb
|
quasiben/rapids-dask-tutorial-2021
|
493ce39d057292f49ba61106d94d41e2dbc49ed9
|
[
"BSD-3-Clause"
] | 2 |
2021-05-05T19:53:04.000Z
|
2021-05-20T13:34:19.000Z
|
Notebooks/cpu_and_gpu_end_to_end_example/gpu_End_to_End.ipynb
|
quasiben/rapids-dask-tutorial-2021
|
493ce39d057292f49ba61106d94d41e2dbc49ed9
|
[
"BSD-3-Clause"
] | 2 |
2021-05-04T15:59:39.000Z
|
2021-05-13T04:17:47.000Z
| 56.709071 | 42,524 | 0.651965 |
[
[
[
"# Predicting NYC Taxi Fares with RAPIDS\nProcess 380 million rides in NYC from 2015-2017. ",
"_____no_output_____"
],
[
"RAPIDS is a suite of GPU accelerated data science libraries with APIs that should be familiar to users of Pandas, Dask, and Scikitlearn.\n\nThis notebook focuses on showing how to use cuDF with Dask & XGBoost to scale GPU DataFrame ETL-style operations & model training out to multiple GPUs. \n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cupy\nimport cudf\nimport dask\nimport dask_cudf\nimport xgboost as xgb\nfrom dask.distributed import Client, wait\nfrom dask.utils import parse_bytes",
"_____no_output_____"
],
[
"from dask_cuda import LocalCUDACluster\ncluster = LocalCUDACluster(rmm_pool_size=parse_bytes(\"25 GB\"),\n scheduler_port=9888,\n dashboard_address=9787, \n )\n\nclient = Client(cluster)\nclient",
"_____no_output_____"
]
],
[
[
"# Inspecting the Data\n\nNow that we have a cluster of GPU workers, we'll use [dask-cudf](https://github.com/rapidsai/dask-cudf/) to load and parse a bunch of CSV files into a distributed DataFrame. ",
"_____no_output_____"
]
],
[
[
"base_path = \"/raid/vjawa/nyc_taxi/data/\"\n\nimport dask_cudf\ndf_2014 = dask_cudf.read_csv(base_path+'2014/yellow_*.csv', chunksize='256 MiB')\n\ndf_2014.head()",
"_____no_output_____"
]
],
[
[
"# Data Cleanup\n\nAs usual, the data needs to be massaged a bit before we can start adding features that are useful to an ML model.\n\nFor example, in the 2014 taxi CSV files, there are `pickup_datetime` and `dropoff_datetime` columns. The 2015 CSVs have `tpep_pickup_datetime` and `tpep_dropoff_datetime`, which are the same columns. One year has `rate_code`, and another `RateCodeID`.\n\nAlso, some CSV files have column names with extraneous spaces in them.\n\nWorst of all, starting in the July 2016 CSVs, pickup & dropoff latitude and longitude data were replaced by location IDs, making the second half of the year useless to us.\n\nWe'll do a little string manipulation, column renaming, and concatenating of DataFrames to sidestep the problems.",
"_____no_output_____"
]
],
[
[
"#Dictionary of required columns and their datatypes\nmust_haves = {\n 'pickup_datetime': 'datetime64[s]',\n 'dropoff_datetime': 'datetime64[s]',\n 'passenger_count': 'int32',\n 'trip_distance': 'float32',\n 'pickup_longitude': 'float32',\n 'pickup_latitude': 'float32',\n 'rate_code': 'int32',\n 'dropoff_longitude': 'float32',\n 'dropoff_latitude': 'float32',\n 'fare_amount': 'float32'\n }",
"_____no_output_____"
],
[
"def clean(ddf, must_haves):\n # replace the extraneous spaces in column names and lower the font type\n tmp = {col:col.strip().lower() for col in list(ddf.columns)}\n ddf = ddf.rename(columns=tmp)\n\n ddf = ddf.rename(columns={\n 'tpep_pickup_datetime': 'pickup_datetime',\n 'tpep_dropoff_datetime': 'dropoff_datetime',\n 'ratecodeid': 'rate_code'\n })\n \n ddf['pickup_datetime'] = ddf['pickup_datetime'].astype('datetime64[ms]')\n ddf['dropoff_datetime'] = ddf['dropoff_datetime'].astype('datetime64[ms]')\n\n for col in ddf.columns:\n if col not in must_haves:\n ddf = ddf.drop(columns=col)\n continue\n # if column was read as a string, recast as float\n if ddf[col].dtype == 'object':\n ddf[col] = ddf[col].str.fillna('-1')\n ddf[col] = ddf[col].astype('float32')\n else:\n # downcast from 64bit to 32bit types\n # Tesla T4 are faster on 32bit ops\n if 'int' in str(ddf[col].dtype):\n ddf[col] = ddf[col].astype('int32')\n if 'float' in str(ddf[col].dtype):\n ddf[col] = ddf[col].astype('float32')\n ddf[col] = ddf[col].fillna(-1)\n \n return ddf",
"_____no_output_____"
]
],
[
[
"<b> NOTE: </b>We will realize that some of 2015 data has column name as `RateCodeID` and others have `RatecodeID`. When we rename the columns in the clean function, it internally doesn't pass meta while calling map_partitions(). This leads to the error of column name mismatch in the returned data. For this reason, we will call the clean function with map_partition and pass the meta to it. Here is the link to the bug created for that: https://github.com/rapidsai/cudf/issues/5413 ",
"_____no_output_____"
]
],
[
[
"df_2014 = df_2014.map_partitions(clean, must_haves, meta=must_haves)",
"_____no_output_____"
]
],
[
[
"We still have 2015 and the first half of 2016's data to read and clean. Let's increase our dataset.",
"_____no_output_____"
]
],
[
[
"df_2015 = dask_cudf.read_csv(base_path+'2015/yellow_*.csv', chunksize='1024 MiB')",
"_____no_output_____"
],
[
"df_2015 = df_2015.map_partitions(clean, must_haves, meta=must_haves)",
"_____no_output_____"
]
],
[
[
"# Handling 2016's Mid-Year Schema Change",
"_____no_output_____"
],
[
"In 2016, only January - June CSVs have the columns we need. If we try to read base_path+2016/yellow_*.csv, Dask will not appreciate having differing schemas in the same DataFrame.\n\nInstead, we'll need to create a list of the valid months and read them independently.",
"_____no_output_____"
]
],
[
[
"months = [str(x).rjust(2, '0') for x in range(1, 7)]\nvalid_files = [base_path+'2016/yellow_tripdata_2016-'+month+'.csv' for month in months]",
"_____no_output_____"
],
[
"#read & clean 2016 data and concat all DFs\ndf_2016 = dask_cudf.read_csv(valid_files, chunksize='512 MiB').map_partitions(clean, must_haves, meta=must_haves)\n\n#concatenate multiple DataFrames into one bigger one\ntaxi_df = dask.dataframe.multi.concat([df_2014, df_2015, df_2016])",
"_____no_output_____"
]
],
[
[
"## Exploratory Data Analysis (EDA)",
"_____no_output_____"
],
[
"Here, we are checking out if there are any non-sensical records and outliers, and in such case, we need to remove them from the dataset.",
"_____no_output_____"
]
],
[
[
"# check out if there is any negative total trip time\ntaxi_df[taxi_df.dropoff_datetime <= taxi_df.pickup_datetime].head()",
"_____no_output_____"
],
[
"# check out if there is any abnormal data where trip distance is short, but the fare is very high.\ntaxi_df[(taxi_df.trip_distance < 10) & (taxi_df.fare_amount > 300)].head()",
"_____no_output_____"
],
[
"# check out if there is any abnormal data where trip distance is long, but the fare is very low.\ntaxi_df[(taxi_df.trip_distance > 50) & (taxi_df.fare_amount < 50)].head()",
"_____no_output_____"
]
],
[
[
"EDA visuals and additional analysis yield the filter logic below.",
"_____no_output_____"
]
],
[
[
"# apply a list of filter conditions to throw out records with missing or outlier values\nquery_frags = [\n 'fare_amount > 1 and fare_amount < 500',\n 'passenger_count > 0 and passenger_count < 6',\n 'pickup_longitude > -75 and pickup_longitude < -73',\n 'dropoff_longitude > -75 and dropoff_longitude < -73',\n 'pickup_latitude > 40 and pickup_latitude < 42',\n 'dropoff_latitude > 40 and dropoff_latitude < 42',\n 'trip_distance > 0 and trip_distance < 500',\n 'not (trip_distance > 50 and fare_amount < 50)',\n 'not (trip_distance < 10 and fare_amount > 300)',\n 'not dropoff_datetime <= pickup_datetime'\n]\ntaxi_df = taxi_df.query(' and '.join(query_frags))",
"_____no_output_____"
],
[
"# reset_index and drop index column\ntaxi_df = taxi_df.reset_index(drop=True)\ntaxi_df.head()",
"_____no_output_____"
]
],
[
[
"# Adding Interesting Features\n\nDask & cuDF provide standard DataFrame operations, but also let you run \"user defined functions\" on the underlying data. Here we use [dask.dataframe's map_partitions](https://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.map_partitions) to apply user defined python function on each DataFrame partition.\n\nWe'll use a Haversine Distance calculation to find total trip distance, and extract additional useful variables from the datetime fields.",
"_____no_output_____"
]
],
[
[
"## add features\n\ntaxi_df['hour'] = taxi_df['pickup_datetime'].dt.hour\ntaxi_df['year'] = taxi_df['pickup_datetime'].dt.year\ntaxi_df['month'] = taxi_df['pickup_datetime'].dt.month\ntaxi_df['day'] = taxi_df['pickup_datetime'].dt.day\ntaxi_df['day_of_week'] = taxi_df['pickup_datetime'].dt.weekday\ntaxi_df['is_weekend'] = (taxi_df['day_of_week']>=5).astype('int32')\n\n#calculate the time difference between dropoff and pickup.\ntaxi_df['diff'] = taxi_df['dropoff_datetime'].astype('int64') - taxi_df['pickup_datetime'].astype('int64')\ntaxi_df['diff']=(taxi_df['diff']/1000).astype('int64')\n\ntaxi_df['pickup_latitude_r'] = taxi_df['pickup_latitude']//.01*.01\ntaxi_df['pickup_longitude_r'] = taxi_df['pickup_longitude']//.01*.01\ntaxi_df['dropoff_latitude_r'] = taxi_df['dropoff_latitude']//.01*.01\ntaxi_df['dropoff_longitude_r'] = taxi_df['dropoff_longitude']//.01*.01\n\ntaxi_df = taxi_df.drop('pickup_datetime', axis=1)\ntaxi_df = taxi_df.drop('dropoff_datetime', axis=1)",
"_____no_output_____"
],
[
"import cupy as cp\n\ndef cudf_haversine_distance(lon1, lat1, lon2, lat2):\n\n lon1, lat1, lon2, lat2 = map(cp.radians, [lon1, lat1, lon2, lat2])\n\n newlon = lon2 - lon1\n newlat = lat2 - lat1\n\n haver_formula = cp.sin(newlat/2.0)**2 + cp.cos(lat1) * cp.cos(lat2) * cp.sin(newlon/2.0)**2\n\n dist = 2 * cp.arcsin(cp.sqrt(haver_formula ))\n km = 6367 * dist #6367 for distance in KM for miles use 3958\n return km\n\n\ndef haversine_dist(df):\n df['h_distance']= cudf_haversine_distance(\n df['pickup_longitude'],\n df['pickup_latitude'],\n df['dropoff_longitude'],\n df['dropoff_latitude']\n )\n df['h_distance']= df['h_distance'].astype('float32')\n return df\n\ntaxi_df = taxi_df.map_partitions(haversine_dist)\ntaxi_df.head()",
"_____no_output_____"
],
[
"len(taxi_df)",
"_____no_output_____"
],
[
"%%time \n\ntaxi_df = taxi_df.persist()\nx = wait(taxi_df);",
"CPU times: user 3.75 s, sys: 297 ms, total: 4.04 s\nWall time: 5.39 s\n"
]
],
[
[
"# Pick a Training Set\n\nLet's imagine you're making a trip to New York on the 25th and want to build a model to predict what fare prices will be like the last few days of the month based on the first part of the month. We'll use a query expression to identify the `day` of the month to use to divide the data into train and test sets.\n\nThe wall-time below represents how long it takes your GPU cluster to load data from the Google Cloud Storage bucket and the ETL portion of the workflow.",
"_____no_output_____"
]
],
[
[
"#since we calculated the h_distance let's drop the trip_distance column, and then do model training with XGB.\ntaxi_df = taxi_df.drop('trip_distance', axis=1)",
"_____no_output_____"
],
[
"# this is the original data partition for train and test sets.\nX_train = taxi_df.query('day < 25')\n\n# create a Y_train ddf with just the target variable\nY_train = X_train[['fare_amount']].persist()\n# drop the target variable from the training ddf\nX_train = X_train[X_train.columns.difference(['fare_amount'])].persist()\n\n# # this wont return until all data is in GPU memory\na = wait([X_train, Y_train]);",
"_____no_output_____"
]
],
[
[
"# Train the XGBoost Regression Model\n\nThe wall time output below indicates how long it took your GPU cluster to train an XGBoost model over the training set.",
"_____no_output_____"
]
],
[
[
"dtrain = xgb.dask.DaskDMatrix(client, X_train, Y_train)",
"_____no_output_____"
],
[
"%%time\n\nparams = {\n 'learning_rate': 0.3,\n 'max_depth': 8,\n 'objective': 'reg:squarederror',\n 'subsample': 0.6,\n 'gamma': 1,\n 'silent': False,\n 'verbose_eval': True,\n 'tree_method':'gpu_hist'\n}\n\ntrained_model = xgb.dask.train(\n client,\n params,\n dtrain,\n num_boost_round=12,\n evals=[(dtrain, 'train')]\n)",
"[0]\ttrain-rmse:11.35932\n[1]\ttrain-rmse:8.09728\n[2]\ttrain-rmse:5.85966\n[3]\ttrain-rmse:4.35156\n[4]\ttrain-rmse:3.36561\n[5]\ttrain-rmse:2.74858\n[6]\ttrain-rmse:2.37931\n[7]\ttrain-rmse:2.16902\n[8]\ttrain-rmse:2.04409\n[9]\ttrain-rmse:1.97927\n[10]\ttrain-rmse:1.93947\n[11]\ttrain-rmse:1.91399\nCPU times: user 2.91 s, sys: 339 ms, total: 3.24 s\nWall time: 22.7 s\n"
],
[
"ax = xgb.plot_importance(trained_model['booster'], height=0.8, max_num_features=10, importance_type=\"gain\")\nax.grid(False, axis=\"y\")\nax.set_title('Estimated feature importance')\nax.set_xlabel('importance')\nplt.show()",
"_____no_output_____"
]
],
[
[
"# How Good is Our Model?\n\nNow that we have a trained model, we need to test it with the 25% of records we held out.\n\nBased on the filtering conditions applied to this dataset, many of the DataFrame partitions will wind up having 0 rows. This is a problem for XGBoost which doesn't know what to do with 0 length arrays. We'll repartition the data. ",
"_____no_output_____"
]
],
[
[
"def drop_empty_partitions(df):\n lengths = df.map_partitions(len).compute()\n nonempty = [length > 0 for length in lengths]\n return df.partitions[nonempty]",
"_____no_output_____"
],
[
"X_test = taxi_df.query('day >= 25').persist()\nX_test = drop_empty_partitions(X_test)\n\n# Create Y_test with just the fare amount\nY_test = X_test[['fare_amount']].persist()\n\n# Drop the fare amount from X_test\nX_test = X_test[X_test.columns.difference(['fare_amount'])]\n\n# this wont return until all data is in GPU memory\ndone = wait([X_test, Y_test])\n\n# display test set size\nlen(X_test)",
"_____no_output_____"
]
],
[
[
"## Calculate Prediction",
"_____no_output_____"
]
],
[
[
"# generate predictions on the test set\nbooster = trained_model[\"booster\"] # \"Booster\" is the trained model\nbooster.set_param({'predictor': 'gpu_predictor'})",
"_____no_output_____"
],
[
"prediction = xgb.dask.inplace_predict(client, booster, X_test).persist()\nwait(prediction);",
"_____no_output_____"
],
[
"y = Y_test['fare_amount'].reset_index(drop=True)",
"_____no_output_____"
],
[
"# Calculate RMSE\nsquared_error = ((prediction-y)**2)\ncupy.sqrt(squared_error.mean().compute())",
"_____no_output_____"
]
],
[
[
"## Save Trained Model for Later Use¶",
"_____no_output_____"
],
[
"We often need to store our models on a persistent filesystem for future deployment. Let's save our model.",
"_____no_output_____"
]
],
[
[
"trained_model",
"_____no_output_____"
],
[
"import joblib\n\n# Save the booster to file\njoblib.dump(trained_model, \"xgboost-model\")",
"_____no_output_____"
],
[
"len(taxi_df)",
"_____no_output_____"
]
],
[
[
"## Reload a Saved Model from Disk",
"_____no_output_____"
],
[
"You can also read the saved model back into a normal XGBoost model object.",
"_____no_output_____"
]
],
[
[
"with open(\"xgboost-model\", 'rb') as fh: \n loaded_model = joblib.load(fh)",
"_____no_output_____"
],
[
"# Generate predictions on the test set again, but this time using the reloaded model\nloaded_booster = loaded_model[\"booster\"]\nloaded_booster.set_param({'predictor': 'gpu_predictor'})\n\nnew_preds = xgb.dask.inplace_predict(client, loaded_booster, X_test).persist()\n\n# Verify that the predictions result in the same RMSE error\nsquared_error = ((new_preds - y)**2)\n\ncp.sqrt(squared_error.mean().compute())",
"_____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"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4a92b36e69fae406742b1995b6b7e2da200f4f63
| 26,563 |
ipynb
|
Jupyter Notebook
|
module1-rnn-and-lstm/LS_DS_431_RNN_and_LSTM_Assignment.ipynb
|
JeanFraga/DS-Unit-4-Sprint-3-Deep-Learning
|
63ee3ccca39876299f35a73bb1fba16af8e5937e
|
[
"MIT"
] | null | null | null |
module1-rnn-and-lstm/LS_DS_431_RNN_and_LSTM_Assignment.ipynb
|
JeanFraga/DS-Unit-4-Sprint-3-Deep-Learning
|
63ee3ccca39876299f35a73bb1fba16af8e5937e
|
[
"MIT"
] | null | null | null |
module1-rnn-and-lstm/LS_DS_431_RNN_and_LSTM_Assignment.ipynb
|
JeanFraga/DS-Unit-4-Sprint-3-Deep-Learning
|
63ee3ccca39876299f35a73bb1fba16af8e5937e
|
[
"MIT"
] | null | null | null | 41.700157 | 1,203 | 0.516734 |
[
[
[
"<img align=\"left\" src=\"https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png\" width=200>\n<br></br>\n<br></br>\n\n## *Data Science Unit 4 Sprint 3 Assignment 1*\n\n# Recurrent Neural Networks and Long Short Term Memory (LSTM)\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_____"
]
],
[
[
"import requests\nfrom tensorflow.keras.callbacks import LambdaCallback\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM\nfrom tensorflow.keras.optimizers import RMSprop\n\nimport numpy as np\nimport random\nimport sys\nimport os",
"_____no_output_____"
],
[
"r = requests.get(url = 'https://www.gutenberg.org/files/100/100-0.txt')\n\nr.text[0:1000]",
"_____no_output_____"
],
[
"giant_string = (str(r.text).split(\"Contents\\r\\n\\r\\n\\r\\n\\r\\n\", 1)[1]).split(\"FINIS\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\", 1)[0]\n\nchars = list(set(giant_string))\nchar_int = {c:i for i,c in enumerate(chars)}\nint_char = {i:c for i,c in enumerate(chars)}\n\nindices_char = int_char\nchar_indices = char_int\n\nmaxlen = 40\nstep = 5\n\nencoded = [char_int[c] for c in giant_string]\n\nsequences = [] # 40 characters\nnext_chars = [] # 1 character\n\nfor i in range(0, len(encoded) - maxlen, step):\n sequences.append(encoded[i: i + maxlen])\n next_chars.append(encoded[i + maxlen])\n\nprint('sequences: ', len(sequences))",
"sequences: 1150962\n"
],
[
"# Specify x & y\n\nX = np.zeros((len(sequences), maxlen, len(chars)), dtype=np.bool)\ny = np.zeros((len(sequences), len(chars)), dtype=np.bool)\n\nfor i, sequence in enumerate(sequences):\n for t, char in enumerate(sequence):\n X[i, t, char] = 1\n \n y[i, next_chars[i]] = 1",
"_____no_output_____"
],
[
"X.shape",
"_____no_output_____"
],
[
"# build the model: a single LSTM\nmodel = Sequential()\nmodel.add(LSTM(128, input_shape=(maxlen, len(chars))))\nmodel.add(Dense(len(chars), activation='softmax'))\n\noptimizer = RMSprop(learning_rate=0.01)\nmodel.compile(loss='categorical_crossentropy', optimizer = optimizer)",
"_____no_output_____"
],
[
"def sample(preds, temperature=1.0):\n # helper function to sample an index from a probability array\n preds = np.asarray(preds).astype('float64')\n preds = np.log(preds) / temperature\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n probas = np.random.multinomial(1, preds, 1)\n return np.argmax(probas)",
"_____no_output_____"
],
[
"text = giant_string",
"_____no_output_____"
],
[
"def on_epoch_end(epoch, _):\n # Function invoked at end of each epoch. Prints generated text.\n print()\n print('----- Generating text after Epoch: %d' % epoch)\n\n start_index = random.randint(0, len(text) - maxlen - 1)\n for diversity in [0.2, 0.5, 1.0, 1.2]:\n print('----- diversity:', diversity)\n\n generated = ''\n sentence = text[start_index: start_index + maxlen]\n generated += sentence\n print('----- Generating with seed: \"' + sentence + '\"')\n sys.stdout.write(generated)\n\n for i in range(400):\n x_pred = np.zeros((1, maxlen, len(chars)))\n for t, char in enumerate(sentence):\n x_pred[0, t, char_indices[char]] = 1.\n\n preds = model.predict(x_pred, verbose=0)[0]\n next_index = sample(preds, diversity)\n next_char = indices_char[next_index]\n\n sentence = sentence[1:] + next_char\n\n sys.stdout.write(next_char)\n sys.stdout.flush()\n print()\n\nprint_callback = LambdaCallback(on_epoch_end=on_epoch_end)",
"_____no_output_____"
],
[
"model.fit(X, y,\n batch_size=64,\n epochs=5,\n callbacks=[print_callback])",
"Train on 1150962 samples\nEpoch 1/5\n1150400/1150962 [============================>.] - ETA: 0s - loss: 1.7390\n----- Generating text after Epoch: 0\n----- diversity: 0.2\n----- Generating with seed: \" sorrow,\n Remember Margaret was a pr\"\n sorrow,\n Remember Margaret was a proud me for the more the more the money,\n And the man be the man and here a best the mind the man be the man the man be speak,\n And a bough and the best thou shall be the more the man but the good his speak of the more the dead,\n And the stren with his perpose and the worse and I will be the father be part\n And the most be that with his sure him to the bost be the bount the more the\n----- diversity: 0.5\n----- Generating with seed: \" sorrow,\n Remember Margaret was a pr\"\n sorrow,\n Remember Margaret was a present shears\nWho comes the never be think the bous which I will be the fies here a mornt in the\n \n----- diversity: 1.0\n----- Generating with seed: \" sorrow,\n Remember Margaret was a pr\"\n sorrow,\n Remember Margaret was a prince?\n\n [_Elets Is down willing my grave,\n And micking of Ubcef\nthat of I wisdim, I wan thy byet yous thank that come bought be\nEntervorcanion:\n LRWARSHOSS. Thou hant remember amenboy men think we behold;\nNot nounk mine rather out soon partimanaing weâll knows avee,\nLet me\n Ad i knot rason yet. A beut, womans.\nCould mat diumit antimitus nopse.\n\n [_Exeut Bovely,\nSo , which ill\n----- diversity: 1.2\n----- Generating with seed: \" sorrow,\n Remember Margaret was a pr\"\n sorrow,\n Remember Margaret was a prince,\nAy, I wear they the suwpaie wisding, sir; Isword of ,\n Choose this letres. How, presentru! Gowâd visto'-, and Amander\nTo strong ; he! I theirselfows, abonminer your gen,\nDone give gurop, straiss; Do his facia with Pesthhafs._\n\nCOester. Go be give not that leavy, bowned hifâ toeting morrus ped meaf,\nNonishfond nofing, gow of a loesmo,\nand for till by whats. Butpo is they foRd that\n1150962/1150962 [==============================] - 158s 137us/sample - loss: 1.7389\nEpoch 2/5\n1150848/1150962 [============================>.] - ETA: 0s - loss: 1.6643\n----- Generating text after Epoch: 1\n----- diversity: 0.2\n----- Generating with seed: \"s of a king; are we not high?\n High \"\ns of a king; are we not high?\n High the lies the stand of all the such a sight and the company.\n E ENTESS.\n T WARDINE.\n A IA.\n The patient stand and the perfort,\n The live the fortune the sone the forth.\n AMBELLE.\n\n----- diversity: 0.5\n----- Generating with seed: \"s of a king; are we not high?\n High \"\ns of a king; are we not high?\n High have the grace, my lord, and all the for the fair of brow one heart\n Shall be deared a master.\n The lost; from my lord, which give the worn\n For the pries to the bust seems and whither all some may not may the such forth,\n The demons his headst the daints the forth.\n Whither and the gods\n \n----- diversity: 1.0\n----- Generating with seed: \"s of a king; are we not high?\n High \"\ns of a king; are we not high?\n High to mlositing day will in her say.Ane Come\n Do and how my may hard you the cornony,\n To shate you bot may an orâs.\n LOANTE. He wife one apposs to remembance, he to co, you doof\nAs I me piage for his dress theck he into. Cousin siste .\n\nME.\nThy heavhes of I would speakd by him in allon\n That ments fill never to betright us epter\n I chalve so to usteing them sloncth, oge;\n \n----- diversity: 1.2\n----- Generating with seed: \"s of a king; are we not high?\n High \"\ns of a king; are we not high?\n High leave still, your yhe hound of Anvilianaing._]\n\nTI GLLHAOGUS.\nPatist, sir; not is you after and then my friend\n Receive Comoom by thee for my holy pause\nBid I must unsey worded! But honouth ansCad\ntermeâs had ink hadras;\nAnd I give know in Aneants, if he glead ? By forish?\n\nWe give the sovergcing Ears, doth, dustobse, and his,\nThree he list speaks pover stle;\nWith that down dpla s\n1150962/1150962 [==============================] - 158s 137us/sample - loss: 1.6643\nEpoch 3/5\n1150528/1150962 [============================>.] - ETA: 0s - loss: 1.6100\n----- Generating text after Epoch: 2\n----- diversity: 0.2\n----- Generating with seed: \"ou\n took them for.\n\n\n SECO\"\nou\n took them for.\n\n\n SECOND OF SERANE.\n \n----- diversity: 0.5\n----- Generating with seed: \"ou\n took them for.\n\n\n SECO\"\nou\n took them for.\n\n\n SECOND.\nCome to this the more to the cannoted in the smally and me, doth have that have it is she better.\n The shower of your love might me, the landers of the ying\n To land the common to a with the princes which she words,\n That this find me not the two part in the day,\n Deint the tomptied to the sparrice of the place.\n\nTITIT.\nThe at when you think the world the done me, and put c\n----- diversity: 1.0\n----- Generating with seed: \"ou\n took them for.\n\n\n SECO\"\nou\n took them for.\n\n\n SECONDY.\nThou shalt not be grost and flails with the worth\n In tage so face lady? If I doâs he spe\n Bald was itsion\nSo torun in thy never dost peaces.\n\nACT IImelb"
]
],
[
[
"# 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"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4a92cbefdebda0a9fbc18bbed003787916b96d18
| 24,088 |
ipynb
|
Jupyter Notebook
|
01_the_machine_learning_landscape.ipynb
|
nantoiuimi/handson-ml2-perso
|
27ba6827c938af5311faa497beaa46e5331f0be9
|
[
"Apache-2.0"
] | null | null | null |
01_the_machine_learning_landscape.ipynb
|
nantoiuimi/handson-ml2-perso
|
27ba6827c938af5311faa497beaa46e5331f0be9
|
[
"Apache-2.0"
] | null | null | null |
01_the_machine_learning_landscape.ipynb
|
nantoiuimi/handson-ml2-perso
|
27ba6827c938af5311faa497beaa46e5331f0be9
|
[
"Apache-2.0"
] | null | null | null | 29.701603 | 247 | 0.558618 |
[
[
[
"**Chapter 1 – The Machine Learning landscape**\n\n_This is the code used to generate some of the figures in chapter 1._",
"_____no_output_____"
],
[
"<table align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/ageron/handson-ml2/blob/master/01_the_machine_learning_landscape.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"# Code example 1-1",
"_____no_output_____"
],
[
"Although Python 2.x may work, it is deprecated so we strongly recommend you use Python 3 instead.",
"_____no_output_____"
]
],
[
[
"# Python ≥3.5 is required\nimport sys\nassert sys.version_info >= (3, 5)",
"_____no_output_____"
],
[
"# Scikit-Learn ≥0.20 is required\nimport sklearn\nassert sklearn.__version__ >= \"0.20\"",
"_____no_output_____"
]
],
[
[
"This function just merges the OECD's life satisfaction data and the IMF's GDP per capita data. It's a bit too long and boring and it's not specific to Machine Learning, which is why I left it out of the book.",
"_____no_output_____"
]
],
[
[
"def prepare_country_stats(oecd_bli, gdp_per_capita):\n oecd_bli = oecd_bli[oecd_bli[\"INEQUALITY\"]==\"TOT\"]\n oecd_bli = oecd_bli.pivot(index=\"Country\", columns=\"Indicator\", values=\"Value\")\n gdp_per_capita.rename(columns={\"2015\": \"GDP per capita\"}, inplace=True)\n gdp_per_capita.set_index(\"Country\", inplace=True)\n full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita,\n left_index=True, right_index=True)\n full_country_stats.sort_values(by=\"GDP per capita\", inplace=True)\n remove_indices = [0, 1, 6, 8, 33, 34, 35]\n keep_indices = list(set(range(36)) - set(remove_indices))\n return full_country_stats[[\"GDP per capita\", 'Life satisfaction']].iloc[keep_indices]",
"_____no_output_____"
]
],
[
[
"The code in the book expects the data files to be located in the current directory. I just tweaked it here to fetch the files in datasets/lifesat.",
"_____no_output_____"
]
],
[
[
"import os\ndatapath = os.path.join(\"datasets\", \"lifesat\", \"\")",
"_____no_output_____"
],
[
"# To plot pretty figures directly within Jupyter\n%matplotlib inline\nimport matplotlib as mpl\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)",
"_____no_output_____"
],
[
"# Download the data\nimport urllib\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml2/master/\"\nos.makedirs(datapath, exist_ok=True)\nfor filename in (\"oecd_bli_2015.csv\", \"gdp_per_capita.csv\"):\n print(\"Downloading\", filename)\n url = DOWNLOAD_ROOT + \"datasets/lifesat/\" + filename\n urllib.request.urlretrieve(url, datapath + filename)",
"_____no_output_____"
],
[
"# Code example\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport sklearn.linear_model\n\n# Load the data\noecd_bli = pd.read_csv(datapath + \"oecd_bli_2015.csv\", thousands=',')\ngdp_per_capita = pd.read_csv(datapath + \"gdp_per_capita.csv\",thousands=',',delimiter='\\t',\n encoding='latin1', na_values=\"n/a\")\n\n# Prepare the data\ncountry_stats = prepare_country_stats(oecd_bli, gdp_per_capita)\nX = np.c_[country_stats[\"GDP per capita\"]]\ny = np.c_[country_stats[\"Life satisfaction\"]]\n\n# Visualize the data\ncountry_stats.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction')\nplt.show()\n\n# Select a linear model\nmodel = sklearn.linear_model.LinearRegression()\n\n# Train the model\nmodel.fit(X, y)\n\n# Make a prediction for Cyprus\nX_new = [[22587]] # Cyprus' GDP per capita\nprint(model.predict(X_new)) # outputs [[ 5.96242338]]",
"_____no_output_____"
]
],
[
[
"# Note: you can ignore the rest of this notebook, it just generates many of the figures in chapter 1.",
"_____no_output_____"
],
[
"Create a function to save the figures.",
"_____no_output_____"
]
],
[
[
"# Where to save the figures\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"fundamentals\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\nos.makedirs(IMAGES_PATH, exist_ok=True)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)",
"_____no_output_____"
]
],
[
[
"Make this notebook's output stable across runs:",
"_____no_output_____"
]
],
[
[
"np.random.seed(42)",
"_____no_output_____"
]
],
[
[
"# Load and prepare Life satisfaction data",
"_____no_output_____"
],
[
"If you want, you can get fresh data from the OECD's website.\nDownload the CSV from http://stats.oecd.org/index.aspx?DataSetCode=BLI\nand save it to `datasets/lifesat/`.",
"_____no_output_____"
]
],
[
[
"oecd_bli = pd.read_csv(datapath + \"oecd_bli_2015.csv\", thousands=',')\noecd_bli = oecd_bli[oecd_bli[\"INEQUALITY\"]==\"TOT\"]\noecd_bli = oecd_bli.pivot(index=\"Country\", columns=\"Indicator\", values=\"Value\")\noecd_bli.head(2)",
"_____no_output_____"
],
[
"oecd_bli[\"Life satisfaction\"].head()",
"_____no_output_____"
]
],
[
[
"# Load and prepare GDP per capita data",
"_____no_output_____"
],
[
"Just like above, you can update the GDP per capita data if you want. Just download data from http://goo.gl/j1MSKe (=> imf.org) and save it to `datasets/lifesat/`.",
"_____no_output_____"
]
],
[
[
"gdp_per_capita = pd.read_csv(datapath+\"gdp_per_capita.csv\", thousands=',', delimiter='\\t',\n encoding='latin1', na_values=\"n/a\")\ngdp_per_capita.rename(columns={\"2015\": \"GDP per capita\"}, inplace=True)\ngdp_per_capita.set_index(\"Country\", inplace=True)\ngdp_per_capita.head(2)",
"_____no_output_____"
],
[
"full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita, left_index=True, right_index=True)\nfull_country_stats.sort_values(by=\"GDP per capita\", inplace=True)\nfull_country_stats",
"_____no_output_____"
],
[
"full_country_stats[[\"GDP per capita\", 'Life satisfaction']].loc[\"United States\"]",
"_____no_output_____"
],
[
"remove_indices = [0, 1, 6, 8, 33, 34, 35]\nkeep_indices = list(set(range(36)) - set(remove_indices))\n\nsample_data = full_country_stats[[\"GDP per capita\", 'Life satisfaction']].iloc[keep_indices]\nmissing_data = full_country_stats[[\"GDP per capita\", 'Life satisfaction']].iloc[remove_indices]",
"_____no_output_____"
],
[
"sample_data.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(5,3))\nplt.axis([0, 60000, 0, 10])\nposition_text = {\n \"Hungary\": (5000, 1),\n \"Korea\": (18000, 1.7),\n \"France\": (29000, 2.4),\n \"Australia\": (40000, 3.0),\n \"United States\": (52000, 3.8),\n}\nfor country, pos_text in position_text.items():\n pos_data_x, pos_data_y = sample_data.loc[country]\n country = \"U.S.\" if country == \"United States\" else country\n plt.annotate(country, xy=(pos_data_x, pos_data_y), xytext=pos_text,\n arrowprops=dict(facecolor='black', width=0.5, shrink=0.1, headwidth=5))\n plt.plot(pos_data_x, pos_data_y, \"ro\")\nplt.xlabel(\"GDP per capita (USD)\")\nsave_fig('money_happy_scatterplot')\nplt.show()",
"_____no_output_____"
],
[
"sample_data.to_csv(os.path.join(\"datasets\", \"lifesat\", \"lifesat.csv\"))",
"_____no_output_____"
],
[
"sample_data.loc[list(position_text.keys())]",
"_____no_output_____"
],
[
"import numpy as np\n\nsample_data.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(5,3))\nplt.xlabel(\"GDP per capita (USD)\")\nplt.axis([0, 60000, 0, 10])\nX=np.linspace(0, 60000, 1000)\nplt.plot(X, 2*X/100000, \"r\")\nplt.text(40000, 2.7, r\"$\\theta_0 = 0$\", fontsize=14, color=\"r\")\nplt.text(40000, 1.8, r\"$\\theta_1 = 2 \\times 10^{-5}$\", fontsize=14, color=\"r\")\nplt.plot(X, 8 - 5*X/100000, \"g\")\nplt.text(5000, 9.1, r\"$\\theta_0 = 8$\", fontsize=14, color=\"g\")\nplt.text(5000, 8.2, r\"$\\theta_1 = -5 \\times 10^{-5}$\", fontsize=14, color=\"g\")\nplt.plot(X, 4 + 5*X/100000, \"b\")\nplt.text(5000, 3.5, r\"$\\theta_0 = 4$\", fontsize=14, color=\"b\")\nplt.text(5000, 2.6, r\"$\\theta_1 = 5 \\times 10^{-5}$\", fontsize=14, color=\"b\")\nsave_fig('tweaking_model_params_plot')\nplt.show()",
"_____no_output_____"
],
[
"from sklearn import linear_model\nlin1 = linear_model.LinearRegression()\nXsample = np.c_[sample_data[\"GDP per capita\"]]\nysample = np.c_[sample_data[\"Life satisfaction\"]]\nlin1.fit(Xsample, ysample)\nt0, t1 = lin1.intercept_[0], lin1.coef_[0][0]\nt0, t1",
"_____no_output_____"
],
[
"sample_data.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(5,3))\nplt.xlabel(\"GDP per capita (USD)\")\nplt.axis([0, 60000, 0, 10])\nX=np.linspace(0, 60000, 1000)\nplt.plot(X, t0 + t1*X, \"b\")\nplt.text(5000, 3.1, r\"$\\theta_0 = 4.85$\", fontsize=14, color=\"b\")\nplt.text(5000, 2.2, r\"$\\theta_1 = 4.91 \\times 10^{-5}$\", fontsize=14, color=\"b\")\nsave_fig('best_fit_model_plot')\nplt.show()\n",
"_____no_output_____"
],
[
"cyprus_gdp_per_capita = gdp_per_capita.loc[\"Cyprus\"][\"GDP per capita\"]\nprint(cyprus_gdp_per_capita)\ncyprus_predicted_life_satisfaction = lin1.predict([[cyprus_gdp_per_capita]])[0][0]\ncyprus_predicted_life_satisfaction",
"_____no_output_____"
],
[
"sample_data.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(5,3), s=1)\nplt.xlabel(\"GDP per capita (USD)\")\nX=np.linspace(0, 60000, 1000)\nplt.plot(X, t0 + t1*X, \"b\")\nplt.axis([0, 60000, 0, 10])\nplt.text(5000, 7.5, r\"$\\theta_0 = 4.85$\", fontsize=14, color=\"b\")\nplt.text(5000, 6.6, r\"$\\theta_1 = 4.91 \\times 10^{-5}$\", fontsize=14, color=\"b\")\nplt.plot([cyprus_gdp_per_capita, cyprus_gdp_per_capita], [0, cyprus_predicted_life_satisfaction], \"r--\")\nplt.text(25000, 5.0, r\"Prediction = 5.96\", fontsize=14, color=\"b\")\nplt.plot(cyprus_gdp_per_capita, cyprus_predicted_life_satisfaction, \"ro\")\nsave_fig('cyprus_prediction_plot')\nplt.show()",
"_____no_output_____"
],
[
"sample_data[7:10]",
"_____no_output_____"
],
[
"(5.1+5.7+6.5)/3",
"_____no_output_____"
],
[
"backup = oecd_bli, gdp_per_capita\n\ndef prepare_country_stats(oecd_bli, gdp_per_capita):\n oecd_bli = oecd_bli[oecd_bli[\"INEQUALITY\"]==\"TOT\"]\n oecd_bli = oecd_bli.pivot(index=\"Country\", columns=\"Indicator\", values=\"Value\")\n gdp_per_capita.rename(columns={\"2015\": \"GDP per capita\"}, inplace=True)\n gdp_per_capita.set_index(\"Country\", inplace=True)\n full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita,\n left_index=True, right_index=True)\n full_country_stats.sort_values(by=\"GDP per capita\", inplace=True)\n remove_indices = [0, 1, 6, 8, 33, 34, 35]\n keep_indices = list(set(range(36)) - set(remove_indices))\n return full_country_stats[[\"GDP per capita\", 'Life satisfaction']].iloc[keep_indices]",
"_____no_output_____"
],
[
"# Code example\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport sklearn.linear_model\n\n# Load the data\noecd_bli = pd.read_csv(datapath + \"oecd_bli_2015.csv\", thousands=',')\ngdp_per_capita = pd.read_csv(datapath + \"gdp_per_capita.csv\",thousands=',',delimiter='\\t',\n encoding='latin1', na_values=\"n/a\")\n\n# Prepare the data\ncountry_stats = prepare_country_stats(oecd_bli, gdp_per_capita)\nX = np.c_[country_stats[\"GDP per capita\"]]\ny = np.c_[country_stats[\"Life satisfaction\"]]\n\n# Visualize the data\ncountry_stats.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction')\nplt.show()\n\n# Select a linear model\nmodel = sklearn.linear_model.LinearRegression()\n\n# Train the model\nmodel.fit(X, y)\n\n# Make a prediction for Cyprus\nX_new = [[22587]] # Cyprus' GDP per capita\nprint(model.predict(X_new)) # outputs [[ 5.96242338]]",
"_____no_output_____"
],
[
"oecd_bli, gdp_per_capita = backup",
"_____no_output_____"
],
[
"missing_data",
"_____no_output_____"
],
[
"position_text2 = {\n \"Brazil\": (1000, 9.0),\n \"Mexico\": (11000, 9.0),\n \"Chile\": (25000, 9.0),\n \"Czech Republic\": (35000, 9.0),\n \"Norway\": (60000, 3),\n \"Switzerland\": (72000, 3.0),\n \"Luxembourg\": (90000, 3.0),\n}",
"_____no_output_____"
],
[
"sample_data.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(8,3))\nplt.axis([0, 110000, 0, 10])\n\nfor country, pos_text in position_text2.items():\n pos_data_x, pos_data_y = missing_data.loc[country]\n plt.annotate(country, xy=(pos_data_x, pos_data_y), xytext=pos_text,\n arrowprops=dict(facecolor='black', width=0.5, shrink=0.1, headwidth=5))\n plt.plot(pos_data_x, pos_data_y, \"rs\")\n\nX=np.linspace(0, 110000, 1000)\nplt.plot(X, t0 + t1*X, \"b:\")\n\nlin_reg_full = linear_model.LinearRegression()\nXfull = np.c_[full_country_stats[\"GDP per capita\"]]\nyfull = np.c_[full_country_stats[\"Life satisfaction\"]]\nlin_reg_full.fit(Xfull, yfull)\n\nt0full, t1full = lin_reg_full.intercept_[0], lin_reg_full.coef_[0][0]\nX = np.linspace(0, 110000, 1000)\nplt.plot(X, t0full + t1full * X, \"k\")\nplt.xlabel(\"GDP per capita (USD)\")\n\nsave_fig('representative_training_data_scatterplot')\nplt.show()",
"_____no_output_____"
],
[
"full_country_stats.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(8,3))\nplt.axis([0, 110000, 0, 10])\n\nfrom sklearn import preprocessing\nfrom sklearn import pipeline\n\npoly = preprocessing.PolynomialFeatures(degree=60, include_bias=False)\nscaler = preprocessing.StandardScaler()\nlin_reg2 = linear_model.LinearRegression()\n\npipeline_reg = pipeline.Pipeline([('poly', poly), ('scal', scaler), ('lin', lin_reg2)])\npipeline_reg.fit(Xfull, yfull)\ncurve = pipeline_reg.predict(X[:, np.newaxis])\nplt.plot(X, curve)\nplt.xlabel(\"GDP per capita (USD)\")\nsave_fig('overfitting_model_plot')\nplt.show()",
"_____no_output_____"
],
[
"full_country_stats.loc[[c for c in full_country_stats.index if \"W\" in c.upper()]][\"Life satisfaction\"]",
"_____no_output_____"
],
[
"gdp_per_capita.loc[[c for c in gdp_per_capita.index if \"W\" in c.upper()]].head()",
"_____no_output_____"
],
[
"plt.figure(figsize=(8,3))\n\nplt.xlabel(\"GDP per capita\")\nplt.ylabel('Life satisfaction')\n\nplt.plot(list(sample_data[\"GDP per capita\"]), list(sample_data[\"Life satisfaction\"]), \"bo\")\nplt.plot(list(missing_data[\"GDP per capita\"]), list(missing_data[\"Life satisfaction\"]), \"rs\")\n\nX = np.linspace(0, 110000, 1000)\nplt.plot(X, t0full + t1full * X, \"r--\", label=\"Linear model on all data\")\nplt.plot(X, t0 + t1*X, \"b:\", label=\"Linear model on partial data\")\n\nridge = linear_model.Ridge(alpha=10**9.5)\nXsample = np.c_[sample_data[\"GDP per capita\"]]\nysample = np.c_[sample_data[\"Life satisfaction\"]]\nridge.fit(Xsample, ysample)\nt0ridge, t1ridge = ridge.intercept_[0], ridge.coef_[0][0]\nplt.plot(X, t0ridge + t1ridge * X, \"b\", label=\"Regularized linear model on partial data\")\n\nplt.legend(loc=\"lower right\")\nplt.axis([0, 110000, 0, 10])\nplt.xlabel(\"GDP per capita (USD)\")\nsave_fig('ridge_model_plot')\nplt.show()",
"_____no_output_____"
],
[
"backup = oecd_bli, gdp_per_capita\n\ndef prepare_country_stats(oecd_bli, gdp_per_capita):\n return sample_data",
"_____no_output_____"
],
[
"# Replace this linear model:\nimport sklearn.linear_model\nmodel = sklearn.linear_model.LinearRegression()",
"_____no_output_____"
],
[
"# with this k-neighbors regression model:\nimport sklearn.neighbors\nmodel = sklearn.neighbors.KNeighborsRegressor(n_neighbors=3)",
"_____no_output_____"
],
[
"X = np.c_[country_stats[\"GDP per capita\"]]\ny = np.c_[country_stats[\"Life satisfaction\"]]\n\n# Train the model\nmodel.fit(X, y)\n\n# Make a prediction for Cyprus\nX_new = np.array([[22587.0]]) # Cyprus' GDP per capita\nprint(model.predict(X_new)) # outputs [[ 5.76666667]]",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a92cdf8136f9c96c22d98f5194b5b219d3039d5
| 124,583 |
ipynb
|
Jupyter Notebook
|
8-Labs/Lab24/Lab24WS.ipynb
|
dustykat/engr-1330-psuedo-course
|
3e7e31a32a1896fcb1fd82b573daa5248e465a36
|
[
"CC0-1.0"
] | null | null | null |
8-Labs/Lab24/Lab24WS.ipynb
|
dustykat/engr-1330-psuedo-course
|
3e7e31a32a1896fcb1fd82b573daa5248e465a36
|
[
"CC0-1.0"
] | null | null | null |
8-Labs/Lab24/Lab24WS.ipynb
|
dustykat/engr-1330-psuedo-course
|
3e7e31a32a1896fcb1fd82b573daa5248e465a36
|
[
"CC0-1.0"
] | null | null | null | 242.851852 | 30,340 | 0.910277 |
[
[
[
"%%html\n<!--Script block to left align Markdown Tables-->\n<style>\n table {margin-left: 0 !important;}\n</style>",
"_____no_output_____"
]
],
[
[
"**Download** (right-click, save target as ...) this page as a jupyterlab notebook from: [Lab24](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab24/Lab24.ipynb)\n\n___",
"_____no_output_____"
],
[
"# <font color=green>Laboratory 24: \"Predictor-Response Data Models\"</font>\n\nLAST NAME, FIRST NAME\n\nR00000000\n\nENGR 1330 Laboratory 24 ",
"_____no_output_____"
],
[
"## Exercise: Watershed Response Metrics \n\n### Background \nRainfall-Runoff response prediction is a vital step in engineering design for mitigating flood-induced infrastructure failure. One easy to measure characteristic of a watershed is its drainage area. Harder to quantify are its characteristic response time, and its conversion (of precipitation into runoff) factor.\n\n### Study Database\n\nThe [watersheds.csv](http://54.243.252.9/engr-1330-webroot/4-Databases/watersheds.csv) dataset contains (measured) drainage area for 92 study watersheds in Texas from [Cleveland, et. al., 2006](https://192.168.1.75/documents/about-me/MyWebPapers/journal_papers/ASCE_Irrigation_Drainage_IR-022737/2006_0602_IUHEvalTexas.pdf), and the associated data:\n\n|Columns|Info.|\n|:---|:---|\n|STATION_ID |USGS HUC-8 Station ID code|\n|TDA |Total drainage area (sq. miles) |\n|RCOEF|Runoff Ratio (Runoff Depth/Precipitation Depth)|\n|TPEAK|Characteristic Time (minutes)|\n|FPEAK|Peaking factor (same as NRCS factor)|\n|QP_OBS|Observed peak discharge (measured)|\n|QP_MOD|Modeled peak discharge (modeled)| \n\n### :\n\nUsing the following steps, build a predictor-response type data model. \n",
"_____no_output_____"
],
[
"<hr/><hr/> \n\n**Step 1:** \n\n<hr/>\n\nRead the \"watersheds.csv\" file as a dataframe. Explore the dataframe and in a markdown cell briefly describe the summarize the dataframe. <br>",
"_____no_output_____"
]
],
[
[
"# import packages\nimport pandas, numpy\n# read data file\nmydata = pandas.read_csv(\"watersheds.csv\")\n# summarize contents + markdown cell as needed\nmydata.head()",
"_____no_output_____"
]
],
[
[
"<hr/><hr/> \n\n**Step 2:** <hr/>\n\nMake a data model using **TDA** as a predictor of **TPEAK** ($T_{peak} = \\beta_{0}+\\beta_{1}*TDA$) <br> Plot your model and the data on the same plot. Report your values of the parameters.",
"_____no_output_____"
]
],
[
[
"predictor = mydata['TDA'].tolist()\nresponse = mydata['TPEAK'].tolist()",
"_____no_output_____"
],
[
"# Our data model\ndef poly1(b0,b1,x):\n # return y = b0 + b1*x\n poly1=b0+b1*x\n return(poly1)",
"_____no_output_____"
],
[
"intercept = 200\nslope = 6.0\nsortedpred = sorted(predictor)\nmodelresponse = [] # empty list\nfor i in range(len(sortedpred)):\n modelresponse.append(poly1(intercept,slope,sortedpred[i]))",
"_____no_output_____"
],
[
"# Our plotting function\nimport matplotlib.pyplot as plt\ndef make2plot(listx1,listy1,listx2,listy2,strlablx,strlably,strtitle):\n mydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class\n plt.plot(listx1,listy1, c='red', marker='p',linewidth=0) # basic data plot\n plt.plot(listx2,listy2, c='blue',linewidth=1) # basic model plot\n plt.xlabel(strlablx)\n plt.ylabel(strlably)\n plt.legend(['Data','Model'])# modify for argument insertion\n plt.title(strtitle)\n plt.show()",
"_____no_output_____"
],
[
"# Plotting results\ncharttitle=\"Plot of y=b0+b1*x model and observations \\n\" + \" Model equation: y = \" + str(intercept) + \" + \" + str(slope) + \"x\"\nmake2plot(predictor,response,sortedpred,modelresponse,'TDA','TPEAK',charttitle)",
"_____no_output_____"
],
[
"# solving the linear system to make a model\n##############################\nimport numpy\nX = [numpy.ones(len(predictor)),numpy.array(predictor)] # build the design X matrix #\nX = numpy.transpose(X) # get into correct shape for linear solver\nY = numpy.array(response) # build the response Y vector\nA = numpy.transpose(X)@X # build the XtX matrix\nb = numpy.transpose(X)@Y # build the XtY vector\nx = numpy.linalg.solve(A,b) # avoid inversion and just solve the linear system \nsortedpred = sorted(predictor)\nmodelresponse = [] # empty list\nfor i in range(len(sortedpred)):\n modelresponse.append(poly1(x[0],x[1],sortedpred[i]))\n# Plotting results\ncharttitle=\"Plot of y=b0+b1*x model and observations \\n\" + \" Model equation: y = \" + str(x[0]) + \" + \" + str(x[1]) + \"x\"\nmake2plot(predictor,response,sortedpred,modelresponse,'TDA','TPEAK',charttitle)",
"_____no_output_____"
]
],
[
[
"<hr/><hr/> \n\n**Step 3:**\n\n<hr/>\n\nMake a data model using **log(TDA)** as a predictor of **TPEAK** ($T_{peak} = \\beta_{0}+\\beta_{1}*log(TDA)$)\n\nIn your opinion which mapping of **TDA** (arithmetic or logarithmic) produces a more useful graph? ",
"_____no_output_____"
]
],
[
[
"#",
"_____no_output_____"
],
[
"import math\npredictor = mydata['TDA'].apply(math.log).tolist()\nresponse = mydata['TPEAK'].tolist()",
"_____no_output_____"
],
[
"# Our data model\ndef poly1(b0,b1,x):\n # return y = b0 + b1*x\n poly1=b0+b1*x\n return(poly1)",
"_____no_output_____"
],
[
"intercept = 1\nslope = 120.0\nsortedpred = sorted(predictor)\nmodelresponse = [] # empty list\nfor i in range(len(sortedpred)):\n modelresponse.append(poly1(intercept,slope,sortedpred[i]))",
"_____no_output_____"
],
[
"# Our plotting function\nimport matplotlib.pyplot as plt\ndef make2plot(listx1,listy1,listx2,listy2,strlablx,strlably,strtitle):\n mydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class\n plt.plot(listx1,listy1, c='red', marker='p',linewidth=0) # basic data plot\n plt.plot(listx2,listy2, c='blue',linewidth=1) # basic model plot\n plt.xlabel(strlablx)\n plt.ylabel(strlably)\n plt.legend(['Data','Model'])# modify for argument insertion\n plt.title(strtitle)\n plt.show()",
"_____no_output_____"
],
[
"# Plotting results\ncharttitle=\"Plot of y=b0+b1*x model and observations \\n\" + \" Model equation: y = \" + str(intercept) + \" + \" + str(slope) + \"x\"\nmake2plot(predictor,response,sortedpred,modelresponse,'logTDA','TPEAK',charttitle)",
"_____no_output_____"
],
[
"# lets try a quadratic\ndef poly2(b0,b1,b2,x):\n # return y = b0 + b1*x\n poly2=b0+b1*x+b2*x**2\n return(poly2)\n# solving the linear system to make a model\n##############################\nimport numpy\nX = [numpy.ones(len(predictor)),numpy.array(predictor),numpy.array(predictor)**2] # build the design X matrix #\nX = numpy.transpose(X) # get into correct shape for linear solver\nY = numpy.array(response) # build the response Y vector\nA = numpy.transpose(X)@X # build the XtX matrix\nb = numpy.transpose(X)@Y # build the XtY vector\nx = numpy.linalg.solve(A,b) # avoid inversion and just solve the linear system \npredictor.sort()",
"_____no_output_____"
],
[
"sortedpred = sorted(predictor)\nmodelresponse = [] # empty list\nfor i in range(len(sortedpred)):\n modelresponse.append(poly2(x[0],x[1],x[2],sortedpred[i]))\n# Plotting results\ncharttitle=\"Plot of y=b0+b1*x model and observations \\n\" + \" Model equation: y = \" + str(x[0]) + \" + \" + str(x[1]) + \"x +\" + str(x[2]) + \"x^2\"\nmake2plot(predictor,response,sortedpred,modelresponse,'logTDA','TPEAK',charttitle)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a92cef4b3a1362dc313e23fdf9dab48d3ba5b5a
| 7,333 |
ipynb
|
Jupyter Notebook
|
tutorial/4_3_Higher_Order_Markov.ipynb
|
Lewiky/mai
|
8fe6f1056444bc0d8c2eba6ad73e86beeae3f895
|
[
"Apache-2.0"
] | null | null | null |
tutorial/4_3_Higher_Order_Markov.ipynb
|
Lewiky/mai
|
8fe6f1056444bc0d8c2eba6ad73e86beeae3f895
|
[
"Apache-2.0"
] | null | null | null |
tutorial/4_3_Higher_Order_Markov.ipynb
|
Lewiky/mai
|
8fe6f1056444bc0d8c2eba6ad73e86beeae3f895
|
[
"Apache-2.0"
] | null | null | null | 25.199313 | 366 | 0.457657 |
[
[
[
"[View in Colaboratory](https://colab.research.google.com/github/davidkant/mai/blob/master/tutorial/4_3_Higher_Order_Markov.ipynb)",
"_____no_output_____"
],
[
"#4.3 Higher Order Markov Chains\nIn this notebook we'll learn how extend the previous code to work with Markov chains of *higher order*.",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"# install external libraries\n!pip install -q git+https://github.com/davidkant/mai#egg=mai;\n!pip install -q pretty_midi\n!pip install -q pyfluidsynth\n!apt-get -qq update\n!apt-get -qq install -y libfluidsynth1\n",
"_____no_output_____"
],
[
"# imports\nimport mai\nimport random\nimport matplotlib.pyplot as plt",
"Using TensorFlow backend.\n"
]
],
[
[
"## Learn a higher order transition table from data\nThis time we are going to learn a third order transition table. Conceptually, *order* specifies how far back the Markov chain looks when considering what to do next. In terms of numerical formalization, when order is greater than 1, the previous state is represented not as a single value but as a list of values. Order is the number of items in that list.",
"_____no_output_____"
],
[
"Example sequence to train on",
"_____no_output_____"
]
],
[
[
"# make some dummy music\nmusic = [60, 62, 64, 65, 67, 60]",
"_____no_output_____"
]
],
[
[
"Learn a third order Markov chain by passing the argument `order=3` when you call the function `train`",
"_____no_output_____"
]
],
[
[
"# create a new markov chain \nmark = mai.markov.Markov()\n\n# clear the table\nmark.clear()\n\n# learn a table\nmark.train(music, order=3) # <-- increase the value of order here!!!",
"_____no_output_____"
]
],
[
[
"View the transition table. Note that the previous state is represented as a list of numbers. For instance, the transition table entry `((60, 62, 64), 65): 1` means we that the sequence ``(60, 62, 64)`` is followed by the number `65` once.",
"_____no_output_____"
]
],
[
[
"# view the transition table\nmark.transitions",
"_____no_output_____"
]
],
[
[
"## Generate a new musical sequence from the trained Markov model\nThis works pretty much the same as order 1 EXCEPT our initial state must now be a list of three values",
"_____no_output_____"
]
],
[
[
"# set initial state\nmark.state = (60, 62, 64)\n\n# next choice\nmark.choose()",
"_____no_output_____"
]
],
[
[
"Keep choosing",
"_____no_output_____"
]
],
[
[
"# next choice\nmark.choose()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a92d29aaeb2b7b4fe40061122e11aabf21dff4e
| 258,389 |
ipynb
|
Jupyter Notebook
|
Activities Week 7 (social analytics)/Social_Analytics_Part3/Day1/Day1.ipynb
|
lraynes/ClassActivities
|
920df2331f39c8a89477ab73e4393675a299d02d
|
[
"MIT"
] | null | null | null |
Activities Week 7 (social analytics)/Social_Analytics_Part3/Day1/Day1.ipynb
|
lraynes/ClassActivities
|
920df2331f39c8a89477ab73e4393675a299d02d
|
[
"MIT"
] | null | null | null |
Activities Week 7 (social analytics)/Social_Analytics_Part3/Day1/Day1.ipynb
|
lraynes/ClassActivities
|
920df2331f39c8a89477ab73e4393675a299d02d
|
[
"MIT"
] | null | null | null | 62.097813 | 75,380 | 0.505103 |
[
[
[
"# Instructor Turn Get Home Tweets",
"_____no_output_____"
]
],
[
[
"!pip install tweepy",
"Requirement already satisfied: tweepy in c:\\users\\drew\\anaconda3\\lib\\site-packages\nRequirement already satisfied: requests>=2.11.1 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from tweepy)\nRequirement already satisfied: six>=1.10.0 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from tweepy)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from tweepy)\nRequirement already satisfied: PySocks>=1.5.7 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from tweepy)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from requests>=2.11.1->tweepy)\nRequirement already satisfied: idna<2.7,>=2.5 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from requests>=2.11.1->tweepy)\nRequirement already satisfied: urllib3<1.23,>=1.21.1 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from requests>=2.11.1->tweepy)\nRequirement already satisfied: certifi>=2017.4.17 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from requests>=2.11.1->tweepy)\nRequirement already satisfied: oauthlib>=0.6.2 in c:\\users\\drew\\anaconda3\\lib\\site-packages (from requests-oauthlib>=0.7.0->tweepy)\n"
],
[
"# Dependencies\nimport json\nimport tweepy",
"_____no_output_____"
],
[
"# Import Twitter API Keys\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret",
"_____no_output_____"
],
[
"# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Get all tweets from home feed\npublic_tweets = api.home_timeline()\nprint(public_tweets)",
"[{'created_at': 'Sat Jun 02 17:10:55 +0000 2018', 'id': 1002960768004952065, 'id_str': '1002960768004952065', 'text': 'RT @nycHealthy: ICYMI: We are alerting New Yorkers about the dangers of smoking #hookah: https://t.co/4v1ApjyCRO https://t.co/43aWNGsj3C', 'truncated': False, 'entities': {'hashtags': [{'text': 'hookah', 'indices': [80, 87]}], 'symbols': [], 'user_mentions': [{'screen_name': 'nycHealthy', 'name': 'nycHealthy', 'id': 17997467, 'id_str': '17997467', 'indices': [3, 14]}], 'urls': [{'url': 'https://t.co/4v1ApjyCRO', 'expanded_url': 'http://on.nyc.gov/2kfajku', 'display_url': 'on.nyc.gov/2kfajku', 'indices': [89, 112]}], 'media': [{'id': 1002920375070658560, 'id_str': '1002920375070658560', 'indices': [113, 136], 'media_url': 'http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'media_url_https': 'https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'url': 'https://t.co/43aWNGsj3C', 'display_url': 'pic.twitter.com/43aWNGsj3C', 'expanded_url': 'https://twitter.com/nycHealthy/status/1002920377327243264/photo/1', 'type': 'photo', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'medium': {'w': 1200, 'h': 675, 'resize': 'fit'}, 'small': {'w': 680, 'h': 383, 'resize': 'fit'}, 'large': {'w': 1200, 'h': 675, 'resize': 'fit'}}, 'source_status_id': 1002920377327243264, 'source_status_id_str': '1002920377327243264', 'source_user_id': 17997467, 'source_user_id_str': '17997467'}]}, 'extended_entities': {'media': [{'id': 1002920375070658560, 'id_str': '1002920375070658560', 'indices': [113, 136], 'media_url': 'http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'media_url_https': 'https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'url': 'https://t.co/43aWNGsj3C', 'display_url': 'pic.twitter.com/43aWNGsj3C', 'expanded_url': 'https://twitter.com/nycHealthy/status/1002920377327243264/photo/1', 'type': 'photo', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'medium': {'w': 1200, 'h': 675, 'resize': 'fit'}, 'small': {'w': 680, 'h': 383, 'resize': 'fit'}, 'large': {'w': 1200, 'h': 675, 'resize': 'fit'}}, 'source_status_id': 1002920377327243264, 'source_status_id_str': '1002920377327243264', 'source_user_id': 17997467, 'source_user_id_str': '17997467'}]}, 'source': '<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 55338739, 'id_str': '55338739', 'name': \"NYC Mayor's Office\", 'screen_name': 'NYCMayorsOffice', 'location': 'New York, NY', 'description': 'Live from City Hall, in the greatest city on earth. @NYCMayor Bill de Blasio.', 'url': 'https://t.co/gbCFBEvClg', 'entities': {'url': {'urls': [{'url': 'https://t.co/gbCFBEvClg', 'expanded_url': 'http://www.NYC.gov', 'display_url': 'NYC.gov', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 945050, 'friends_count': 738, 'listed_count': 5713, 'created_at': 'Thu Jul 09 19:42:27 +0000 2009', 'favourites_count': 1240, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 25912, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '9AE4E8', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/55338739/1527875021', 'profile_link_color': '0084B4', 'profile_sidebar_border_color': 'BDDCAD', 'profile_sidebar_fill_color': 'DDFFCC', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'retweeted_status': {'created_at': 'Sat Jun 02 14:30:25 +0000 2018', 'id': 1002920377327243264, 'id_str': '1002920377327243264', 'text': 'ICYMI: We are alerting New Yorkers about the dangers of smoking #hookah: https://t.co/4v1ApjyCRO https://t.co/43aWNGsj3C', 'truncated': False, 'entities': {'hashtags': [{'text': 'hookah', 'indices': [64, 71]}], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/4v1ApjyCRO', 'expanded_url': 'http://on.nyc.gov/2kfajku', 'display_url': 'on.nyc.gov/2kfajku', 'indices': [73, 96]}], 'media': [{'id': 1002920375070658560, 'id_str': '1002920375070658560', 'indices': [97, 120], 'media_url': 'http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'media_url_https': 'https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'url': 'https://t.co/43aWNGsj3C', 'display_url': 'pic.twitter.com/43aWNGsj3C', 'expanded_url': 'https://twitter.com/nycHealthy/status/1002920377327243264/photo/1', 'type': 'photo', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'medium': {'w': 1200, 'h': 675, 'resize': 'fit'}, 'small': {'w': 680, 'h': 383, 'resize': 'fit'}, 'large': {'w': 1200, 'h': 675, 'resize': 'fit'}}}]}, 'extended_entities': {'media': [{'id': 1002920375070658560, 'id_str': '1002920375070658560', 'indices': [97, 120], 'media_url': 'http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'media_url_https': 'https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg', 'url': 'https://t.co/43aWNGsj3C', 'display_url': 'pic.twitter.com/43aWNGsj3C', 'expanded_url': 'https://twitter.com/nycHealthy/status/1002920377327243264/photo/1', 'type': 'photo', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'medium': {'w': 1200, 'h': 675, 'resize': 'fit'}, 'small': {'w': 680, 'h': 383, 'resize': 'fit'}, 'large': {'w': 1200, 'h': 675, 'resize': 'fit'}}}]}, 'source': '<a href=\"https://www.hootsuite.com\" rel=\"nofollow\">Hootsuite Inc.</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 17997467, 'id_str': '17997467', 'name': 'nycHealthy', 'screen_name': 'nycHealthy', 'location': 'New York, NY', 'description': 'nycHealthy is the official account of the NYC Dept. of Health & Mental Hygiene. \\r\\n\\r\\nUser Policy: http://t.co/y2O6BKEOkN', 'url': 'http://t.co/6bcwqWmZLV', 'entities': {'url': {'urls': [{'url': 'http://t.co/6bcwqWmZLV', 'expanded_url': 'http://nyc.gov/health', 'display_url': 'nyc.gov/health', 'indices': [0, 22]}]}, 'description': {'urls': [{'url': 'http://t.co/y2O6BKEOkN', 'expanded_url': 'http://on.nyc.gov/1j279u3', 'display_url': 'on.nyc.gov/1j279u3', 'indices': [97, 119]}]}}, 'protected': False, 'followers_count': 43101, 'friends_count': 503, 'listed_count': 1172, 'created_at': 'Tue Dec 09 18:13:28 +0000 2008', 'favourites_count': 5113, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 18555, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'EFEFEF', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme15/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme15/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/880811566979002368/f5cNu1dp_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/880811566979002368/f5cNu1dp_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/17997467/1400530219', 'profile_link_color': '5C85A3', 'profile_sidebar_border_color': 'A8C7F7', 'profile_sidebar_fill_color': 'C0DFEC', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': False, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 1, 'favorite_count': 3, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, 'is_quote_status': False, 'retweet_count': 1, 'favorite_count': 0, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 17:07:26 +0000 2018', 'id': 1002959888367177728, 'id_str': '1002959888367177728', 'text': 'Experts on workplace abuse on how to recognize it, the toll it takes on workers, and why it so often flies under th… https://t.co/SlgbHhQ02V', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/SlgbHhQ02V', 'expanded_url': 'https://twitter.com/i/web/status/1002959888367177728', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [117, 140]}]}, 'source': '<a href=\"http://www.socialflow.com\" rel=\"nofollow\">SocialFlow</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 45564482, 'id_str': '45564482', 'name': 'New York Magazine', 'screen_name': 'NYMag', 'location': 'New York, NY', 'description': 'The ideas, people, and cultural currents that are forever reshaping the world.', 'url': 'http://t.co/uvSpg4t2HC', 'entities': {'url': {'urls': [{'url': 'http://t.co/uvSpg4t2HC', 'expanded_url': 'http://nymag.com', 'display_url': 'nymag.com', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 1781637, 'friends_count': 871, 'listed_count': 13777, 'created_at': 'Mon Jun 08 13:30:34 +0000 2009', 'favourites_count': 1767, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 128566, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/45564482/1443719391', 'profile_link_color': '1F638A', 'profile_sidebar_border_color': '000000', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 6, 'favorite_count': 14, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 17:07:21 +0000 2018', 'id': 1002959867856998404, 'id_str': '1002959867856998404', 'text': '4 train service has resumed. https://t.co/q6pdumcC4l', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/q6pdumcC4l', 'expanded_url': 'https://twitter.com/NYCTSubway/status/1002958408105037824', 'display_url': 'twitter.com/NYCTSubway/sta…', 'indices': [29, 52]}]}, 'source': '<a href=\"http://www.conversocial.com\" rel=\"nofollow\">Conversocial</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 66379182, 'id_str': '66379182', 'name': 'NYCT Subway', 'screen_name': 'NYCTSubway', 'location': 'New York City', 'description': 'Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.', 'url': 'https://t.co/A32pJWLkKU', 'entities': {'url': {'urls': [{'url': 'https://t.co/A32pJWLkKU', 'expanded_url': 'http://www.mta.info', 'display_url': 'mta.info', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 949461, 'friends_count': 296, 'listed_count': 4007, 'created_at': 'Mon Aug 17 15:28:03 +0000 2009', 'favourites_count': 1490, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 269223, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/66379182/1525279294', 'profile_link_color': '000003', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'F0D108', 'profile_text_color': '0A070F', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': True, 'quoted_status_id': 1002958408105037824, 'quoted_status_id_str': '1002958408105037824', 'quoted_status': {'created_at': 'Sat Jun 02 17:01:33 +0000 2018', 'id': 1002958408105037824, 'id_str': '1002958408105037824', 'text': 'Southbound 4 trains are running express from Bedford Park Blvd to Burnside Av because of NYPD activity at 183 St.', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': []}, 'source': '<a href=\"http://gms.mtanyct.info/GMSTwitter/Default.aspx\" rel=\"nofollow\">GMS Web Pro App</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 66379182, 'id_str': '66379182', 'name': 'NYCT Subway', 'screen_name': 'NYCTSubway', 'location': 'New York City', 'description': 'Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.', 'url': 'https://t.co/A32pJWLkKU', 'entities': {'url': {'urls': [{'url': 'https://t.co/A32pJWLkKU', 'expanded_url': 'http://www.mta.info', 'display_url': 'mta.info', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 949461, 'friends_count': 296, 'listed_count': 4007, 'created_at': 'Mon Aug 17 15:28:03 +0000 2009', 'favourites_count': 1490, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 269223, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/66379182/1525279294', 'profile_link_color': '000003', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'F0D108', 'profile_text_color': '0A070F', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 1, 'favorite_count': 3, 'favorited': False, 'retweeted': False, 'lang': 'en'}, 'retweet_count': 0, 'favorite_count': 1, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 17:05:00 +0000 2018', 'id': 1002959278225969152, 'id_str': '1002959278225969152', 'text': 'Calvin Moreland said he was ordered to get out of his car during a stop, but an officer tased him when he reached t… https://t.co/stRGDkmryO', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/stRGDkmryO', 'expanded_url': 'https://twitter.com/i/web/status/1002959278225969152', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [117, 140]}]}, 'source': '<a href=\"http://www.socialnewsdesk.com\" rel=\"nofollow\">SocialNewsDesk</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 43425975, 'id_str': '43425975', 'name': 'Spectrum News NY1', 'screen_name': 'NY1', 'location': 'New York City', 'description': 'Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).', 'url': 'https://t.co/xPLV2Nm1aQ', 'entities': {'url': {'urls': [{'url': 'https://t.co/xPLV2Nm1aQ', 'expanded_url': 'http://www.ny1.com', 'display_url': 'ny1.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 455646, 'friends_count': 88, 'listed_count': 4150, 'created_at': 'Fri May 29 22:37:45 +0000 2009', 'favourites_count': 992, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 91284, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '19334C', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/43425975/1526580308', 'profile_link_color': '17324D', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'DAE4EE', 'profile_text_color': '000000', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 2, 'favorite_count': 1, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 17:01:33 +0000 2018', 'id': 1002958408105037824, 'id_str': '1002958408105037824', 'text': 'Southbound 4 trains are running express from Bedford Park Blvd to Burnside Av because of NYPD activity at 183 St.', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': []}, 'source': '<a href=\"http://gms.mtanyct.info/GMSTwitter/Default.aspx\" rel=\"nofollow\">GMS Web Pro App</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 66379182, 'id_str': '66379182', 'name': 'NYCT Subway', 'screen_name': 'NYCTSubway', 'location': 'New York City', 'description': 'Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.', 'url': 'https://t.co/A32pJWLkKU', 'entities': {'url': {'urls': [{'url': 'https://t.co/A32pJWLkKU', 'expanded_url': 'http://www.mta.info', 'display_url': 'mta.info', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 949461, 'friends_count': 296, 'listed_count': 4007, 'created_at': 'Mon Aug 17 15:28:03 +0000 2009', 'favourites_count': 1490, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 269223, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/66379182/1525279294', 'profile_link_color': '000003', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'F0D108', 'profile_text_color': '0A070F', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 1, 'favorite_count': 3, 'favorited': False, 'retweeted': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 17:01:19 +0000 2018', 'id': 1002958350282383360, 'id_str': '1002958350282383360', 'text': 'Rivka Galchen on parenting: \"At three, my daughter became aware that at age four she would get another round of vac… https://t.co/K3tJs2pVP9', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/K3tJs2pVP9', 'expanded_url': 'https://twitter.com/i/web/status/1002958350282383360', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [117, 140]}]}, 'source': '<a href=\"http://www.socialflow.com\" rel=\"nofollow\">SocialFlow</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 14677919, 'id_str': '14677919', 'name': 'The New Yorker', 'screen_name': 'NewYorker', 'location': 'New York, NY', 'description': 'The New Yorker is a weekly magazine with a mix of reporting on politics and culture, humor and cartoons, fiction and poetry, and reviews and criticism.', 'url': 'https://t.co/RLTwD4Ft0i', 'entities': {'url': {'urls': [{'url': 'https://t.co/RLTwD4Ft0i', 'expanded_url': 'http://www.newyorker.com', 'display_url': 'newyorker.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 8619393, 'friends_count': 422, 'listed_count': 63156, 'created_at': 'Tue May 06 19:36:33 +0000 2008', 'favourites_count': 1793, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': True, 'statuses_count': 75774, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': True, 'profile_background_color': '9AE4E8', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme16/bg.gif', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme16/bg.gif', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/14677919/1478111474', 'profile_link_color': '0084B4', 'profile_sidebar_border_color': 'BDDCAD', 'profile_sidebar_fill_color': 'DDFFCC', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 6, 'favorite_count': 20, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 17:01:16 +0000 2018', 'id': 1002958336738947073, 'id_str': '1002958336738947073', 'text': 'RT @amyyensi: Somber Symbol at the Youth Against Gun Violence Rally and March. They’ll be walking across the #BrooklynBridge & want #gunref…', 'truncated': False, 'entities': {'hashtags': [{'text': 'BrooklynBridge', 'indices': [109, 124]}], 'symbols': [], 'user_mentions': [{'screen_name': 'amyyensi', 'name': 'Amy Yensi', 'id': 72613712, 'id_str': '72613712', 'indices': [3, 12]}], 'urls': []}, 'source': '<a href=\"http://www.socialnewsdesk.com\" rel=\"nofollow\">SocialNewsDesk</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 43425975, 'id_str': '43425975', 'name': 'Spectrum News NY1', 'screen_name': 'NY1', 'location': 'New York City', 'description': 'Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).', 'url': 'https://t.co/xPLV2Nm1aQ', 'entities': {'url': {'urls': [{'url': 'https://t.co/xPLV2Nm1aQ', 'expanded_url': 'http://www.ny1.com', 'display_url': 'ny1.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 455646, 'friends_count': 88, 'listed_count': 4150, 'created_at': 'Fri May 29 22:37:45 +0000 2009', 'favourites_count': 992, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 91284, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '19334C', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/43425975/1526580308', 'profile_link_color': '17324D', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'DAE4EE', 'profile_text_color': '000000', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'retweeted_status': {'created_at': 'Sat Jun 02 16:51:45 +0000 2018', 'id': 1002955940956647425, 'id_str': '1002955940956647425', 'text': 'Somber Symbol at the Youth Against Gun Violence Rally and March. They’ll be walking across the #BrooklynBridge & wa… https://t.co/ZERLDnQOTV', 'truncated': True, 'entities': {'hashtags': [{'text': 'BrooklynBridge', 'indices': [95, 110]}], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/ZERLDnQOTV', 'expanded_url': 'https://twitter.com/i/web/status/1002955940956647425', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [121, 144]}]}, 'source': '<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 72613712, 'id_str': '72613712', 'name': 'Amy Yensi', 'screen_name': 'amyyensi', 'location': 'New York, NY', 'description': 'Reporter @NY1 Native New Yorker #BronxGirl Brunch&Broadway lover. Proud Dominican-American. Links & Retweet’s are not endorsements.', 'url': 'https://t.co/deN7bl1sRW', 'entities': {'url': {'urls': [{'url': 'https://t.co/deN7bl1sRW', 'expanded_url': 'http://facebook.com/AmyYensi', 'display_url': 'facebook.com/AmyYensi', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 1415, 'friends_count': 2605, 'listed_count': 30, 'created_at': 'Tue Sep 08 17:40:49 +0000 2009', 'favourites_count': 221, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': False, 'statuses_count': 1315, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '642D8B', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme10/bg.gif', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme10/bg.gif', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/907582283749699585/qLvKmKsr_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/907582283749699585/qLvKmKsr_normal.jpg', 'profile_link_color': 'FF0000', 'profile_sidebar_border_color': '65B0DA', 'profile_sidebar_fill_color': '7AC3EE', 'profile_text_color': '3D1957', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': False, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 5, 'favorite_count': 4, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, 'is_quote_status': False, 'retweet_count': 5, 'favorite_count': 0, 'favorited': False, 'retweeted': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:59:27 +0000 2018', 'id': 1002957879761145857, 'id_str': '1002957879761145857', 'text': 'Last chance to catch “Zoe Leonard: Survey” at the Whitney Museum of American Art https://t.co/wSme1kPUyu', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/wSme1kPUyu', 'expanded_url': 'https://nyti.ms/2LdLS2n', 'display_url': 'nyti.ms/2LdLS2n', 'indices': [81, 104]}]}, 'source': '<a href=\"http://www.socialflow.com\" rel=\"nofollow\">SocialFlow</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 1440641, 'id_str': '1440641', 'name': 'New York Times Arts', 'screen_name': 'nytimesarts', 'location': 'New York, NY', 'description': 'Arts and entertainment news from The New York Times.', 'url': 'http://t.co/0H74AaBX8Y', 'entities': {'url': {'urls': [{'url': 'http://t.co/0H74AaBX8Y', 'expanded_url': 'http://www.nytimes.com/arts', 'display_url': 'nytimes.com/arts', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 2652074, 'friends_count': 230, 'listed_count': 19383, 'created_at': 'Sun Mar 18 20:30:33 +0000 2007', 'favourites_count': 319, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': True, 'statuses_count': 144228, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'FFFFFF', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/964180969702895616/wJcdJ1MU_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/964180969702895616/wJcdJ1MU_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/1440641/1510847448', 'profile_link_color': 'FF691F', 'profile_sidebar_border_color': '323232', 'profile_sidebar_fill_color': 'E7EFF8', 'profile_text_color': '000000', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 2, 'favorite_count': 7, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:45:04 +0000 2018', 'id': 1002954262693937153, 'id_str': '1002954262693937153', 'text': \"Moisturizer with SPF is essential year-round, but it's especially necessary in summer https://t.co/G9vsnJKed9\", 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/G9vsnJKed9', 'expanded_url': 'https://nym.ag/2J4fEtL', 'display_url': 'nym.ag/2J4fEtL', 'indices': [86, 109]}]}, 'source': '<a href=\"http://www.socialflow.com\" rel=\"nofollow\">SocialFlow</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 45564482, 'id_str': '45564482', 'name': 'New York Magazine', 'screen_name': 'NYMag', 'location': 'New York, NY', 'description': 'The ideas, people, and cultural currents that are forever reshaping the world.', 'url': 'http://t.co/uvSpg4t2HC', 'entities': {'url': {'urls': [{'url': 'http://t.co/uvSpg4t2HC', 'expanded_url': 'http://nymag.com', 'display_url': 'nymag.com', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 1781637, 'friends_count': 871, 'listed_count': 13777, 'created_at': 'Mon Jun 08 13:30:34 +0000 2009', 'favourites_count': 1767, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 128566, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/45564482/1443719391', 'profile_link_color': '1F638A', 'profile_sidebar_border_color': '000000', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 3, 'favorite_count': 15, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:27:29 +0000 2018', 'id': 1002949835794894849, 'id_str': '1002949835794894849', 'text': 'RT @NY1onstage: Tune in alert! 7pm tonight! https://t.co/6vipDlMyw3', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [{'screen_name': 'NY1onstage', 'name': 'NY1 - ON STAGE', 'id': 100043275, 'id_str': '100043275', 'indices': [3, 14]}], 'urls': [{'url': 'https://t.co/6vipDlMyw3', 'expanded_url': 'https://twitter.com/ny1/status/1002943072165036034', 'display_url': 'twitter.com/ny1/status/100…', 'indices': [44, 67]}]}, 'source': '<a href=\"http://www.socialnewsdesk.com\" rel=\"nofollow\">SocialNewsDesk</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 43425975, 'id_str': '43425975', 'name': 'Spectrum News NY1', 'screen_name': 'NY1', 'location': 'New York City', 'description': 'Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).', 'url': 'https://t.co/xPLV2Nm1aQ', 'entities': {'url': {'urls': [{'url': 'https://t.co/xPLV2Nm1aQ', 'expanded_url': 'http://www.ny1.com', 'display_url': 'ny1.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 455646, 'friends_count': 88, 'listed_count': 4150, 'created_at': 'Fri May 29 22:37:45 +0000 2009', 'favourites_count': 992, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 91284, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '19334C', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/43425975/1526580308', 'profile_link_color': '17324D', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'DAE4EE', 'profile_text_color': '000000', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'retweeted_status': {'created_at': 'Sat Jun 02 16:22:38 +0000 2018', 'id': 1002948615772491781, 'id_str': '1002948615772491781', 'text': 'Tune in alert! 7pm tonight! https://t.co/6vipDlMyw3', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/6vipDlMyw3', 'expanded_url': 'https://twitter.com/ny1/status/1002943072165036034', 'display_url': 'twitter.com/ny1/status/100…', 'indices': [28, 51]}]}, 'source': '<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 100043275, 'id_str': '100043275', 'name': 'NY1 - ON STAGE', 'screen_name': 'NY1onstage', 'location': 'New York City', 'description': 'ON STAGE on Spectrum News @NY1 is a weekly theater program hosted by @fdilella and dedicated to the NYC theater scene and beyond.', 'url': 'https://t.co/xPLV2N4pMg', 'entities': {'url': {'urls': [{'url': 'https://t.co/xPLV2N4pMg', 'expanded_url': 'http://www.ny1.com', 'display_url': 'ny1.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 8850, 'friends_count': 227, 'listed_count': 266, 'created_at': 'Mon Dec 28 20:46:16 +0000 2009', 'favourites_count': 655, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': False, 'statuses_count': 2052, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '42160B', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/953802883174141952/9h86QUTB_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/953802883174141952/9h86QUTB_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/100043275/1516239248', 'profile_link_color': '94000C', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'EBB484', 'profile_text_color': '030303', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': False, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': True, 'quoted_status_id': 1002943072165036034, 'quoted_status_id_str': '1002943072165036034', 'quoted_status': {'created_at': 'Sat Jun 02 16:00:36 +0000 2018', 'id': 1002943072165036034, 'id_str': '1002943072165036034', 'text': 'Don’t forget to tune in a half hour earlier tonight at 7pm for our “Road to the Tonys” special on @NY1onstage! https://t.co/6q46uEFIjP', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [{'screen_name': 'NY1onstage', 'name': 'NY1 - ON STAGE', 'id': 100043275, 'id_str': '100043275', 'indices': [99, 110]}], 'urls': [], 'media': [{'id': 1002942923078492165, 'id_str': '1002942923078492165', 'indices': [112, 135], 'media_url': 'http://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg', 'media_url_https': 'https://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg', 'url': 'https://t.co/6q46uEFIjP', 'display_url': 'pic.twitter.com/6q46uEFIjP', 'expanded_url': 'https://twitter.com/NY1/status/1002943072165036034/video/1', 'type': 'photo', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'medium': {'w': 1200, 'h': 675, 'resize': 'fit'}, 'small': {'w': 680, 'h': 383, 'resize': 'fit'}, 'large': {'w': 1280, 'h': 720, 'resize': 'fit'}}}]}, 'extended_entities': {'media': [{'id': 1002942923078492165, 'id_str': '1002942923078492165', 'indices': [112, 135], 'media_url': 'http://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg', 'media_url_https': 'https://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg', 'url': 'https://t.co/6q46uEFIjP', 'display_url': 'pic.twitter.com/6q46uEFIjP', 'expanded_url': 'https://twitter.com/NY1/status/1002943072165036034/video/1', 'type': 'video', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'medium': {'w': 1200, 'h': 675, 'resize': 'fit'}, 'small': {'w': 680, 'h': 383, 'resize': 'fit'}, 'large': {'w': 1280, 'h': 720, 'resize': 'fit'}}, 'video_info': {'aspect_ratio': [16, 9], 'duration_millis': 42843, 'variants': [{'content_type': 'application/x-mpegURL', 'url': 'https://video.twimg.com/ext_tw_video/1002942923078492165/pu/pl/iyGNzXX6Vc1HF6_q.m3u8?tag=3'}, {'bitrate': 2176000, 'content_type': 'video/mp4', 'url': 'https://video.twimg.com/ext_tw_video/1002942923078492165/pu/vid/1280x720/LZ5bsAnqhJbQzkNJ.mp4?tag=3'}, {'bitrate': 832000, 'content_type': 'video/mp4', 'url': 'https://video.twimg.com/ext_tw_video/1002942923078492165/pu/vid/640x360/xoKd4ghCMGtI0k4G.mp4?tag=3'}, {'bitrate': 256000, 'content_type': 'video/mp4', 'url': 'https://video.twimg.com/ext_tw_video/1002942923078492165/pu/vid/320x180/edaunxpdgPpqUlXY.mp4?tag=3'}]}, 'additional_media_info': {'monetizable': False}}]}, 'source': '<a href=\"http://www.socialnewsdesk.com\" rel=\"nofollow\">SocialNewsDesk</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 43425975, 'id_str': '43425975', 'name': 'Spectrum News NY1', 'screen_name': 'NY1', 'location': 'New York City', 'description': 'Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).', 'url': 'https://t.co/xPLV2Nm1aQ', 'entities': {'url': {'urls': [{'url': 'https://t.co/xPLV2Nm1aQ', 'expanded_url': 'http://www.ny1.com', 'display_url': 'ny1.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 455646, 'friends_count': 88, 'listed_count': 4150, 'created_at': 'Fri May 29 22:37:45 +0000 2009', 'favourites_count': 992, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 91284, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '19334C', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/43425975/1526580308', 'profile_link_color': '17324D', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'DAE4EE', 'profile_text_color': '000000', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 1, 'favorite_count': 3, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, 'retweet_count': 1, 'favorite_count': 1, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, 'is_quote_status': True, 'quoted_status_id': 1002943072165036034, 'quoted_status_id_str': '1002943072165036034', 'retweet_count': 1, 'favorite_count': 0, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:25:10 +0000 2018', 'id': 1002949254594392065, 'id_str': '1002949254594392065', 'text': 'A few showers have popped-up around the area, but, the five boroughs remain mostly dry at the moment. https://t.co/mBl5GqlKs9', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [], 'media': [{'id': 1002948655584772098, 'id_str': '1002948655584772098', 'indices': [102, 125], 'media_url': 'http://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg', 'media_url_https': 'https://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg', 'url': 'https://t.co/mBl5GqlKs9', 'display_url': 'pic.twitter.com/mBl5GqlKs9', 'expanded_url': 'https://twitter.com/NY1weather/status/1002949254594392065/photo/1', 'type': 'photo', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'large': {'w': 746, 'h': 419, 'resize': 'fit'}, 'medium': {'w': 746, 'h': 419, 'resize': 'fit'}, 'small': {'w': 680, 'h': 382, 'resize': 'fit'}}}]}, 'extended_entities': {'media': [{'id': 1002948655584772098, 'id_str': '1002948655584772098', 'indices': [102, 125], 'media_url': 'http://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg', 'media_url_https': 'https://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg', 'url': 'https://t.co/mBl5GqlKs9', 'display_url': 'pic.twitter.com/mBl5GqlKs9', 'expanded_url': 'https://twitter.com/NY1weather/status/1002949254594392065/photo/1', 'type': 'photo', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'large': {'w': 746, 'h': 419, 'resize': 'fit'}, 'medium': {'w': 746, 'h': 419, 'resize': 'fit'}, 'small': {'w': 680, 'h': 382, 'resize': 'fit'}}}]}, 'source': '<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 43435902, 'id_str': '43435902', 'name': 'NY1 Weather', 'screen_name': 'NY1weather', 'location': 'New York City', 'description': \"Weather info from New York City's 24-hour newschannel\", 'url': 'http://t.co/ora6dbI5aQ', 'entities': {'url': {'urls': [{'url': 'http://t.co/ora6dbI5aQ', 'expanded_url': 'http://ny1.com/weather', 'display_url': 'ny1.com/weather', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 376088, 'friends_count': 37, 'listed_count': 1919, 'created_at': 'Fri May 29 23:37:52 +0000 2009', 'favourites_count': 16376, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 28294, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '2A6398', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg', 'profile_link_color': 'C72126', 'profile_sidebar_border_color': '184D98', 'profile_sidebar_fill_color': 'CCE3F5', 'profile_text_color': '181D33', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 2, 'favorite_count': 10, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:23:23 +0000 2018', 'id': 1002948802549108737, 'id_str': '1002948802549108737', 'text': 'The White House is working to set up a summit between President Trump and Vladimir Putin https://t.co/LHDAVWnk5y', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/LHDAVWnk5y', 'expanded_url': 'https://nym.ag/2HeTuz1', 'display_url': 'nym.ag/2HeTuz1', 'indices': [89, 112]}]}, 'source': '<a href=\"http://www.socialflow.com\" rel=\"nofollow\">SocialFlow</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 45564482, 'id_str': '45564482', 'name': 'New York Magazine', 'screen_name': 'NYMag', 'location': 'New York, NY', 'description': 'The ideas, people, and cultural currents that are forever reshaping the world.', 'url': 'http://t.co/uvSpg4t2HC', 'entities': {'url': {'urls': [{'url': 'http://t.co/uvSpg4t2HC', 'expanded_url': 'http://nymag.com', 'display_url': 'nymag.com', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 1781637, 'friends_count': 871, 'listed_count': 13777, 'created_at': 'Mon Jun 08 13:30:34 +0000 2009', 'favourites_count': 1767, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 128566, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/45564482/1443719391', 'profile_link_color': '1F638A', 'profile_sidebar_border_color': '000000', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 3, 'favorite_count': 7, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:23:16 +0000 2018', 'id': 1002948776175329281, 'id_str': '1002948776175329281', 'text': '\"My looks definitely opened doors for me. I never interviewed for a job I didn’t get\" https://t.co/Y4kMs05sWN', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/Y4kMs05sWN', 'expanded_url': 'https://nym.ag/2J7NBK0', 'display_url': 'nym.ag/2J7NBK0', 'indices': [86, 109]}]}, 'source': '<a href=\"http://www.socialflow.com\" rel=\"nofollow\">SocialFlow</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 45564482, 'id_str': '45564482', 'name': 'New York Magazine', 'screen_name': 'NYMag', 'location': 'New York, NY', 'description': 'The ideas, people, and cultural currents that are forever reshaping the world.', 'url': 'http://t.co/uvSpg4t2HC', 'entities': {'url': {'urls': [{'url': 'http://t.co/uvSpg4t2HC', 'expanded_url': 'http://nymag.com', 'display_url': 'nymag.com', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 1781637, 'friends_count': 871, 'listed_count': 13777, 'created_at': 'Mon Jun 08 13:30:34 +0000 2009', 'favourites_count': 1767, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 128566, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/45564482/1443719391', 'profile_link_color': '1F638A', 'profile_sidebar_border_color': '000000', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 8, 'favorite_count': 24, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:23:00 +0000 2018', 'id': 1002948708189851649, 'id_str': '1002948708189851649', 'text': 'Dumplings are one of those cross-cultural culinary wonders that tend to be both very comforting and affordably fill… https://t.co/aeymVPrEST', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/aeymVPrEST', 'expanded_url': 'https://twitter.com/i/web/status/1002948708189851649', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [117, 140]}]}, 'source': '<a href=\"https://about.twitter.com/products/tweetdeck\" rel=\"nofollow\">TweetDeck</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 9917652, 'id_str': '9917652', 'name': 'Eater NY', 'screen_name': 'EaterNY', 'location': 'New York, NY', 'description': 'Food news and dining guides for New York City.', 'url': 'http://t.co/zePlLx1Yt5', 'entities': {'url': {'urls': [{'url': 'http://t.co/zePlLx1Yt5', 'expanded_url': 'http://ny.eater.com', 'display_url': 'ny.eater.com', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 442264, 'friends_count': 197, 'listed_count': 3760, 'created_at': 'Sat Nov 03 16:15:19 +0000 2007', 'favourites_count': 508, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': True, 'statuses_count': 38530, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'FDF7F7', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/513844477476081665/tgVPjKD1_normal.png', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/513844477476081665/tgVPjKD1_normal.png', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/9917652/1418407817', 'profile_link_color': 'B40041', 'profile_sidebar_border_color': 'FDF7F7', 'profile_sidebar_fill_color': 'FFFFFF', 'profile_text_color': '333333', 'profile_use_background_image': False, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 0, 'favorite_count': 7, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:22:45 +0000 2018', 'id': 1002948645124177927, 'id_str': '1002948645124177927', 'text': 'Northbound A and Rockaway S trains are running with delays because of a train with mechanical problems at Broad Channel.', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': []}, 'source': '<a href=\"http://gms.mtanyct.info/GMSTwitter/Default.aspx\" rel=\"nofollow\">GMS Web Pro App</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 66379182, 'id_str': '66379182', 'name': 'NYCT Subway', 'screen_name': 'NYCTSubway', 'location': 'New York City', 'description': 'Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.', 'url': 'https://t.co/A32pJWLkKU', 'entities': {'url': {'urls': [{'url': 'https://t.co/A32pJWLkKU', 'expanded_url': 'http://www.mta.info', 'display_url': 'mta.info', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 949461, 'friends_count': 296, 'listed_count': 4007, 'created_at': 'Mon Aug 17 15:28:03 +0000 2009', 'favourites_count': 1490, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 269223, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '000000', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/66379182/1525279294', 'profile_link_color': '000003', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'F0D108', 'profile_text_color': '0A070F', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 0, 'favorite_count': 1, 'favorited': False, 'retweeted': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:17:22 +0000 2018', 'id': 1002947291534319616, 'id_str': '1002947291534319616', 'text': 'RT @FDNY: #CPRSavesLives and National CPR and AED Awareness Week is a great time to sign up for a FREE hands-only CPR class with the #FDNY…', 'truncated': False, 'entities': {'hashtags': [{'text': 'CPRSavesLives', 'indices': [10, 24]}, {'text': 'FDNY', 'indices': [133, 138]}], 'symbols': [], 'user_mentions': [{'screen_name': 'FDNY', 'name': 'FDNY', 'id': 134846593, 'id_str': '134846593', 'indices': [3, 8]}], 'urls': []}, 'source': '<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 55338739, 'id_str': '55338739', 'name': \"NYC Mayor's Office\", 'screen_name': 'NYCMayorsOffice', 'location': 'New York, NY', 'description': 'Live from City Hall, in the greatest city on earth. @NYCMayor Bill de Blasio.', 'url': 'https://t.co/gbCFBEvClg', 'entities': {'url': {'urls': [{'url': 'https://t.co/gbCFBEvClg', 'expanded_url': 'http://www.NYC.gov', 'display_url': 'NYC.gov', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 945050, 'friends_count': 738, 'listed_count': 5713, 'created_at': 'Thu Jul 09 19:42:27 +0000 2009', 'favourites_count': 1240, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 25912, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '9AE4E8', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/55338739/1527875021', 'profile_link_color': '0084B4', 'profile_sidebar_border_color': 'BDDCAD', 'profile_sidebar_fill_color': 'DDFFCC', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'retweeted_status': {'created_at': 'Sat Jun 02 15:10:05 +0000 2018', 'id': 1002930357400952832, 'id_str': '1002930357400952832', 'text': '#CPRSavesLives and National CPR and AED Awareness Week is a great time to sign up for a FREE hands-only CPR class w… https://t.co/6LDwHATZtd', 'truncated': True, 'entities': {'hashtags': [{'text': 'CPRSavesLives', 'indices': [0, 14]}], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/6LDwHATZtd', 'expanded_url': 'https://twitter.com/i/web/status/1002930357400952832', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [117, 140]}]}, 'source': '<a href=\"https://www.hootsuite.com\" rel=\"nofollow\">Hootsuite Inc.</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 134846593, 'id_str': '134846593', 'name': 'FDNY', 'screen_name': 'FDNY', 'location': 'New York, NY', 'description': 'The official New York City Fire Department feed. Call 911 for all emergencies, 311 for non-emergencies. Account is not monitored 24/7', 'url': 'https://t.co/baW8ITvn7T', 'entities': {'url': {'urls': [{'url': 'https://t.co/baW8ITvn7T', 'expanded_url': 'http://www.nyc.gov/fdny', 'display_url': 'nyc.gov/fdny', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 233195, 'friends_count': 269, 'listed_count': 2789, 'created_at': 'Mon Apr 19 16:26:00 +0000 2010', 'favourites_count': 341, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 32023, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '131516', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme14/bg.gif', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme14/bg.gif', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/884856237552275456/ulMRDdJd_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/884856237552275456/ulMRDdJd_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/134846593/1452639153', 'profile_link_color': '89C9FA', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': '102459', 'profile_text_color': 'F0E8F0', 'profile_use_background_image': False, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': False, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 13, 'favorite_count': 25, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, 'is_quote_status': False, 'retweet_count': 13, 'favorite_count': 0, 'favorited': False, 'retweeted': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:15:45 +0000 2018', 'id': 1002946882216185856, 'id_str': '1002946882216185856', 'text': 'In an ancient valley in the Honduran jungle, a scientific expedition used motion-sensing cameras to capture images… https://t.co/iK3yhDSoKU', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/iK3yhDSoKU', 'expanded_url': 'https://twitter.com/i/web/status/1002946882216185856', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [116, 139]}]}, 'source': '<a href=\"http://snappytv.com\" rel=\"nofollow\">SnappyTV.com</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 14677919, 'id_str': '14677919', 'name': 'The New Yorker', 'screen_name': 'NewYorker', 'location': 'New York, NY', 'description': 'The New Yorker is a weekly magazine with a mix of reporting on politics and culture, humor and cartoons, fiction and poetry, and reviews and criticism.', 'url': 'https://t.co/RLTwD4Ft0i', 'entities': {'url': {'urls': [{'url': 'https://t.co/RLTwD4Ft0i', 'expanded_url': 'http://www.newyorker.com', 'display_url': 'newyorker.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 8619393, 'friends_count': 422, 'listed_count': 63156, 'created_at': 'Tue May 06 19:36:33 +0000 2008', 'favourites_count': 1793, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': True, 'statuses_count': 75774, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': True, 'profile_background_color': '9AE4E8', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme16/bg.gif', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme16/bg.gif', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/14677919/1478111474', 'profile_link_color': '0084B4', 'profile_sidebar_border_color': 'BDDCAD', 'profile_sidebar_fill_color': 'DDFFCC', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 115, 'favorite_count': 223, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:15:44 +0000 2018', 'id': 1002946878491807744, 'id_str': '1002946878491807744', 'text': 'Summer-like warmth and moderate levels of humidity are in store for the afternoon hours. We could also see a shower… https://t.co/henixBbnSV', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/henixBbnSV', 'expanded_url': 'https://twitter.com/i/web/status/1002946878491807744', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [117, 140]}]}, 'source': '<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 43435902, 'id_str': '43435902', 'name': 'NY1 Weather', 'screen_name': 'NY1weather', 'location': 'New York City', 'description': \"Weather info from New York City's 24-hour newschannel\", 'url': 'http://t.co/ora6dbI5aQ', 'entities': {'url': {'urls': [{'url': 'http://t.co/ora6dbI5aQ', 'expanded_url': 'http://ny1.com/weather', 'display_url': 'ny1.com/weather', 'indices': [0, 22]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 376088, 'friends_count': 37, 'listed_count': 1919, 'created_at': 'Fri May 29 23:37:52 +0000 2009', 'favourites_count': 16376, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 28294, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '2A6398', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg', 'profile_link_color': 'C72126', 'profile_sidebar_border_color': '184D98', 'profile_sidebar_fill_color': 'CCE3F5', 'profile_text_color': '181D33', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 4, 'favorite_count': 6, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}, {'created_at': 'Sat Jun 02 16:14:00 +0000 2018', 'id': 1002946443190177793, 'id_str': '1002946443190177793', 'text': 'The Brooklyn Army Terminal’s 100th year: Unveiling new space for over 1,000 new jobs, launching strategies for the… https://t.co/Yh5kpvmZEr', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/Yh5kpvmZEr', 'expanded_url': 'https://twitter.com/i/web/status/1002946443190177793', 'display_url': 'twitter.com/i/web/status/1…', 'indices': [116, 139]}]}, 'source': '<a href=\"https://about.twitter.com/products/tweetdeck\" rel=\"nofollow\">TweetDeck</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 250884927, 'id_str': '250884927', 'name': 'City of New York', 'screen_name': 'nycgov', 'location': 'New York City', 'description': 'Official New York City government Twitter. Keep up with NYC news, services, programs, free events and emergency notifications. https://t.co/N0igPl3T7S', 'url': 'https://t.co/HSvs3qcfig', 'entities': {'url': {'urls': [{'url': 'https://t.co/HSvs3qcfig', 'expanded_url': 'http://nyc.gov', 'display_url': 'nyc.gov', 'indices': [0, 23]}]}, 'description': {'urls': [{'url': 'https://t.co/N0igPl3T7S', 'expanded_url': 'http://nyc.gov/socialmediapolicy', 'display_url': 'nyc.gov/socialmediapol…', 'indices': [127, 150]}]}}, 'protected': False, 'followers_count': 1171727, 'friends_count': 243, 'listed_count': 4414, 'created_at': 'Sat Feb 12 00:43:55 +0000 2011', 'favourites_count': 2644, 'utc_offset': None, 'time_zone': None, 'geo_enabled': True, 'verified': True, 'statuses_count': 27885, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': '7DC7FF', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme13/bg.gif', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme13/bg.gif', 'profile_background_tile': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/879455346179354624/uWMfEYZH_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/879455346179354624/uWMfEYZH_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/250884927/1525899407', 'profile_link_color': '0099B9', 'profile_sidebar_border_color': 'FFFFFF', 'profile_sidebar_fill_color': 'E5E8E8', 'profile_text_color': '3C3940', 'profile_use_background_image': True, 'has_extended_profile': False, 'default_profile': False, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 2, 'favorite_count': 7, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'possibly_sensitive_appealable': False, 'lang': 'en'}]\n"
],
[
"# Loop through all tweets\nfor tweet in public_tweets:\n # Utilize JSON dumps to generate a pretty-printed json\n print(json.dumps(tweet, sort_keys=True, indent=4))",
"{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:10:55 +0000 2018\",\n \"entities\": {\n \"hashtags\": [\n {\n \"indices\": [\n 80,\n 87\n ],\n \"text\": \"hookah\"\n }\n ],\n \"media\": [\n {\n \"display_url\": \"pic.twitter.com/43aWNGsj3C\",\n \"expanded_url\": \"https://twitter.com/nycHealthy/status/1002920377327243264/photo/1\",\n \"id\": 1002920375070658560,\n \"id_str\": \"1002920375070658560\",\n \"indices\": [\n 113,\n 136\n ],\n \"media_url\": \"http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"medium\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"small\": {\n \"h\": 383,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"source_status_id\": 1002920377327243264,\n \"source_status_id_str\": \"1002920377327243264\",\n \"source_user_id\": 17997467,\n \"source_user_id_str\": \"17997467\",\n \"type\": \"photo\",\n \"url\": \"https://t.co/43aWNGsj3C\"\n }\n ],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"on.nyc.gov/2kfajku\",\n \"expanded_url\": \"http://on.nyc.gov/2kfajku\",\n \"indices\": [\n 89,\n 112\n ],\n \"url\": \"https://t.co/4v1ApjyCRO\"\n }\n ],\n \"user_mentions\": [\n {\n \"id\": 17997467,\n \"id_str\": \"17997467\",\n \"indices\": [\n 3,\n 14\n ],\n \"name\": \"nycHealthy\",\n \"screen_name\": \"nycHealthy\"\n }\n ]\n },\n \"extended_entities\": {\n \"media\": [\n {\n \"display_url\": \"pic.twitter.com/43aWNGsj3C\",\n \"expanded_url\": \"https://twitter.com/nycHealthy/status/1002920377327243264/photo/1\",\n \"id\": 1002920375070658560,\n \"id_str\": \"1002920375070658560\",\n \"indices\": [\n 113,\n 136\n ],\n \"media_url\": \"http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"medium\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"small\": {\n \"h\": 383,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"source_status_id\": 1002920377327243264,\n \"source_status_id_str\": \"1002920377327243264\",\n \"source_user_id\": 17997467,\n \"source_user_id_str\": \"17997467\",\n \"type\": \"photo\",\n \"url\": \"https://t.co/43aWNGsj3C\"\n }\n ]\n },\n \"favorite_count\": 0,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002960768004952065,\n \"id_str\": \"1002960768004952065\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 1,\n \"retweeted\": false,\n \"retweeted_status\": {\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 14:30:25 +0000 2018\",\n \"entities\": {\n \"hashtags\": [\n {\n \"indices\": [\n 64,\n 71\n ],\n \"text\": \"hookah\"\n }\n ],\n \"media\": [\n {\n \"display_url\": \"pic.twitter.com/43aWNGsj3C\",\n \"expanded_url\": \"https://twitter.com/nycHealthy/status/1002920377327243264/photo/1\",\n \"id\": 1002920375070658560,\n \"id_str\": \"1002920375070658560\",\n \"indices\": [\n 97,\n 120\n ],\n \"media_url\": \"http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"medium\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"small\": {\n \"h\": 383,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"type\": \"photo\",\n \"url\": \"https://t.co/43aWNGsj3C\"\n }\n ],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"on.nyc.gov/2kfajku\",\n \"expanded_url\": \"http://on.nyc.gov/2kfajku\",\n \"indices\": [\n 73,\n 96\n ],\n \"url\": \"https://t.co/4v1ApjyCRO\"\n }\n ],\n \"user_mentions\": []\n },\n \"extended_entities\": {\n \"media\": [\n {\n \"display_url\": \"pic.twitter.com/43aWNGsj3C\",\n \"expanded_url\": \"https://twitter.com/nycHealthy/status/1002920377327243264/photo/1\",\n \"id\": 1002920375070658560,\n \"id_str\": \"1002920375070658560\",\n \"indices\": [\n 97,\n 120\n ],\n \"media_url\": \"http://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/media/DesWxHYWkAAOt0E.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"medium\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"small\": {\n \"h\": 383,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"type\": \"photo\",\n \"url\": \"https://t.co/43aWNGsj3C\"\n }\n ]\n },\n \"favorite_count\": 3,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002920377327243264,\n \"id_str\": \"1002920377327243264\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 1,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"https://www.hootsuite.com\\\" rel=\\\"nofollow\\\">Hootsuite Inc.</a>\",\n \"text\": \"ICYMI: We are alerting New Yorkers about the dangers of smoking #hookah: https://t.co/4v1ApjyCRO https://t.co/43aWNGsj3C\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Tue Dec 09 18:13:28 +0000 2008\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"nycHealthy is the official account of the NYC Dept. of Health & Mental Hygiene. \\r\\n\\r\\nUser Policy: http://t.co/y2O6BKEOkN\",\n \"entities\": {\n \"description\": {\n \"urls\": [\n {\n \"display_url\": \"on.nyc.gov/1j279u3\",\n \"expanded_url\": \"http://on.nyc.gov/1j279u3\",\n \"indices\": [\n 97,\n 119\n ],\n \"url\": \"http://t.co/y2O6BKEOkN\"\n }\n ]\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nyc.gov/health\",\n \"expanded_url\": \"http://nyc.gov/health\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/6bcwqWmZLV\"\n }\n ]\n }\n },\n \"favourites_count\": 5113,\n \"follow_request_sent\": false,\n \"followers_count\": 43101,\n \"following\": false,\n \"friends_count\": 503,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 17997467,\n \"id_str\": \"17997467\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 1172,\n \"location\": \"New York, NY\",\n \"name\": \"nycHealthy\",\n \"notifications\": false,\n \"profile_background_color\": \"EFEFEF\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme15/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme15/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/17997467/1400530219\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/880811566979002368/f5cNu1dp_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/880811566979002368/f5cNu1dp_normal.jpg\",\n \"profile_link_color\": \"5C85A3\",\n \"profile_sidebar_border_color\": \"A8C7F7\",\n \"profile_sidebar_fill_color\": \"C0DFEC\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"nycHealthy\",\n \"statuses_count\": 18555,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/6bcwqWmZLV\",\n \"utc_offset\": null,\n \"verified\": true\n }\n },\n \"source\": \"<a href=\\\"http://twitter.com/download/iphone\\\" rel=\\\"nofollow\\\">Twitter for iPhone</a>\",\n \"text\": \"RT @nycHealthy: ICYMI: We are alerting New Yorkers about the dangers of smoking #hookah: https://t.co/4v1ApjyCRO https://t.co/43aWNGsj3C\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Thu Jul 09 19:42:27 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Live from City Hall, in the greatest city on earth. @NYCMayor Bill de Blasio.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"NYC.gov\",\n \"expanded_url\": \"http://www.NYC.gov\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/gbCFBEvClg\"\n }\n ]\n }\n },\n \"favourites_count\": 1240,\n \"follow_request_sent\": false,\n \"followers_count\": 945050,\n \"following\": true,\n \"friends_count\": 738,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 55338739,\n \"id_str\": \"55338739\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 5713,\n \"location\": \"New York, NY\",\n \"name\": \"NYC Mayor's Office\",\n \"notifications\": false,\n \"profile_background_color\": \"9AE4E8\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/55338739/1527875021\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg\",\n \"profile_link_color\": \"0084B4\",\n \"profile_sidebar_border_color\": \"BDDCAD\",\n \"profile_sidebar_fill_color\": \"DDFFCC\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYCMayorsOffice\",\n \"statuses_count\": 25912,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/gbCFBEvClg\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:07:26 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002959888367177728\",\n \"indices\": [\n 117,\n 140\n ],\n \"url\": \"https://t.co/SlgbHhQ02V\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 14,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002959888367177728,\n \"id_str\": \"1002959888367177728\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 6,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialflow.com\\\" rel=\\\"nofollow\\\">SocialFlow</a>\",\n \"text\": \"Experts on workplace abuse on how to recognize it, the toll it takes on workers, and why it so often flies under th\\u2026 https://t.co/SlgbHhQ02V\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Jun 08 13:30:34 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"The ideas, people, and cultural currents that are forever reshaping the world.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nymag.com\",\n \"expanded_url\": \"http://nymag.com\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/uvSpg4t2HC\"\n }\n ]\n }\n },\n \"favourites_count\": 1767,\n \"follow_request_sent\": false,\n \"followers_count\": 1781637,\n \"following\": true,\n \"friends_count\": 871,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 45564482,\n \"id_str\": \"45564482\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 13777,\n \"location\": \"New York, NY\",\n \"name\": \"New York Magazine\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/45564482/1443719391\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_link_color\": \"1F638A\",\n \"profile_sidebar_border_color\": \"000000\",\n \"profile_sidebar_fill_color\": \"DDEEF6\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYMag\",\n \"statuses_count\": 128566,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/uvSpg4t2HC\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:07:21 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/NYCTSubway/sta\\u2026\",\n \"expanded_url\": \"https://twitter.com/NYCTSubway/status/1002958408105037824\",\n \"indices\": [\n 29,\n 52\n ],\n \"url\": \"https://t.co/q6pdumcC4l\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 1,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002959867856998404,\n \"id_str\": \"1002959867856998404\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": true,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"quoted_status\": {\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:01:33 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [],\n \"user_mentions\": []\n },\n \"favorite_count\": 3,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002958408105037824,\n \"id_str\": \"1002958408105037824\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"retweet_count\": 1,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://gms.mtanyct.info/GMSTwitter/Default.aspx\\\" rel=\\\"nofollow\\\">GMS Web Pro App</a>\",\n \"text\": \"Southbound 4 trains are running express from Bedford Park Blvd to Burnside Av because of NYPD activity at 183 St.\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Aug 17 15:28:03 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"mta.info\",\n \"expanded_url\": \"http://www.mta.info\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/A32pJWLkKU\"\n }\n ]\n }\n },\n \"favourites_count\": 1490,\n \"follow_request_sent\": false,\n \"followers_count\": 949461,\n \"following\": true,\n \"friends_count\": 296,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 66379182,\n \"id_str\": \"66379182\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4007,\n \"location\": \"New York City\",\n \"name\": \"NYCT Subway\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/66379182/1525279294\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_link_color\": \"000003\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"F0D108\",\n \"profile_text_color\": \"0A070F\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYCTSubway\",\n \"statuses_count\": 269223,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/A32pJWLkKU\",\n \"utc_offset\": null,\n \"verified\": true\n }\n },\n \"quoted_status_id\": 1002958408105037824,\n \"quoted_status_id_str\": \"1002958408105037824\",\n \"retweet_count\": 0,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.conversocial.com\\\" rel=\\\"nofollow\\\">Conversocial</a>\",\n \"text\": \"4 train service has resumed. https://t.co/q6pdumcC4l\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Aug 17 15:28:03 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"mta.info\",\n \"expanded_url\": \"http://www.mta.info\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/A32pJWLkKU\"\n }\n ]\n }\n },\n \"favourites_count\": 1490,\n \"follow_request_sent\": false,\n \"followers_count\": 949461,\n \"following\": true,\n \"friends_count\": 296,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 66379182,\n \"id_str\": \"66379182\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4007,\n \"location\": \"New York City\",\n \"name\": \"NYCT Subway\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/66379182/1525279294\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_link_color\": \"000003\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"F0D108\",\n \"profile_text_color\": \"0A070F\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYCTSubway\",\n \"statuses_count\": 269223,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/A32pJWLkKU\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:05:00 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002959278225969152\",\n \"indices\": [\n 117,\n 140\n ],\n \"url\": \"https://t.co/stRGDkmryO\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 1,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002959278225969152,\n \"id_str\": \"1002959278225969152\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 2,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialnewsdesk.com\\\" rel=\\\"nofollow\\\">SocialNewsDesk</a>\",\n \"text\": \"Calvin Moreland said he was ordered to get out of his car during a stop, but an officer tased him when he reached t\\u2026 https://t.co/stRGDkmryO\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Fri May 29 22:37:45 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny1.com\",\n \"expanded_url\": \"http://www.ny1.com\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/xPLV2Nm1aQ\"\n }\n ]\n }\n },\n \"favourites_count\": 992,\n \"follow_request_sent\": false,\n \"followers_count\": 455646,\n \"following\": true,\n \"friends_count\": 88,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 43425975,\n \"id_str\": \"43425975\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4150,\n \"location\": \"New York City\",\n \"name\": \"Spectrum News NY1\",\n \"notifications\": false,\n \"profile_background_color\": \"19334C\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/43425975/1526580308\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_link_color\": \"17324D\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"DAE4EE\",\n \"profile_text_color\": \"000000\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NY1\",\n \"statuses_count\": 91284,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/xPLV2Nm1aQ\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:01:33 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [],\n \"user_mentions\": []\n },\n \"favorite_count\": 3,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002958408105037824,\n \"id_str\": \"1002958408105037824\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"retweet_count\": 1,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://gms.mtanyct.info/GMSTwitter/Default.aspx\\\" rel=\\\"nofollow\\\">GMS Web Pro App</a>\",\n \"text\": \"Southbound 4 trains are running express from Bedford Park Blvd to Burnside Av because of NYPD activity at 183 St.\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Aug 17 15:28:03 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"mta.info\",\n \"expanded_url\": \"http://www.mta.info\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/A32pJWLkKU\"\n }\n ]\n }\n },\n \"favourites_count\": 1490,\n \"follow_request_sent\": false,\n \"followers_count\": 949461,\n \"following\": true,\n \"friends_count\": 296,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 66379182,\n \"id_str\": \"66379182\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4007,\n \"location\": \"New York City\",\n \"name\": \"NYCT Subway\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/66379182/1525279294\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_link_color\": \"000003\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"F0D108\",\n \"profile_text_color\": \"0A070F\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYCTSubway\",\n \"statuses_count\": 269223,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/A32pJWLkKU\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:01:19 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002958350282383360\",\n \"indices\": [\n 117,\n 140\n ],\n \"url\": \"https://t.co/K3tJs2pVP9\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 20,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002958350282383360,\n \"id_str\": \"1002958350282383360\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 6,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialflow.com\\\" rel=\\\"nofollow\\\">SocialFlow</a>\",\n \"text\": \"Rivka Galchen on parenting: \\\"At three, my daughter became aware that at age four she would get another round of vac\\u2026 https://t.co/K3tJs2pVP9\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Tue May 06 19:36:33 +0000 2008\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"The New Yorker is a weekly magazine with a mix of reporting on politics and culture, humor and cartoons, fiction and poetry, and reviews and criticism.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"newyorker.com\",\n \"expanded_url\": \"http://www.newyorker.com\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/RLTwD4Ft0i\"\n }\n ]\n }\n },\n \"favourites_count\": 1793,\n \"follow_request_sent\": false,\n \"followers_count\": 8619393,\n \"following\": true,\n \"friends_count\": 422,\n \"geo_enabled\": false,\n \"has_extended_profile\": false,\n \"id\": 14677919,\n \"id_str\": \"14677919\",\n \"is_translation_enabled\": true,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 63156,\n \"location\": \"New York, NY\",\n \"name\": \"The New Yorker\",\n \"notifications\": false,\n \"profile_background_color\": \"9AE4E8\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme16/bg.gif\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme16/bg.gif\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/14677919/1478111474\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg\",\n \"profile_link_color\": \"0084B4\",\n \"profile_sidebar_border_color\": \"BDDCAD\",\n \"profile_sidebar_fill_color\": \"DDFFCC\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NewYorker\",\n \"statuses_count\": 75774,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/RLTwD4Ft0i\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 17:01:16 +0000 2018\",\n \"entities\": {\n \"hashtags\": [\n {\n \"indices\": [\n 109,\n 124\n ],\n \"text\": \"BrooklynBridge\"\n }\n ],\n \"symbols\": [],\n \"urls\": [],\n \"user_mentions\": [\n {\n \"id\": 72613712,\n \"id_str\": \"72613712\",\n \"indices\": [\n 3,\n 12\n ],\n \"name\": \"Amy Yensi\",\n \"screen_name\": \"amyyensi\"\n }\n ]\n },\n \"favorite_count\": 0,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002958336738947073,\n \"id_str\": \"1002958336738947073\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"retweet_count\": 5,\n \"retweeted\": false,\n \"retweeted_status\": {\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:51:45 +0000 2018\",\n \"entities\": {\n \"hashtags\": [\n {\n \"indices\": [\n 95,\n 110\n ],\n \"text\": \"BrooklynBridge\"\n }\n ],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002955940956647425\",\n \"indices\": [\n 121,\n 144\n ],\n \"url\": \"https://t.co/ZERLDnQOTV\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 4,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002955940956647425,\n \"id_str\": \"1002955940956647425\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 5,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://twitter.com/download/iphone\\\" rel=\\\"nofollow\\\">Twitter for iPhone</a>\",\n \"text\": \"Somber Symbol at the Youth Against Gun Violence Rally and March. They\\u2019ll be walking across the #BrooklynBridge & wa\\u2026 https://t.co/ZERLDnQOTV\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Tue Sep 08 17:40:49 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Reporter @NY1 Native New Yorker #BronxGirl Brunch&Broadway lover. Proud Dominican-American. Links & Retweet\\u2019s are not endorsements.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"facebook.com/AmyYensi\",\n \"expanded_url\": \"http://facebook.com/AmyYensi\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/deN7bl1sRW\"\n }\n ]\n }\n },\n \"favourites_count\": 221,\n \"follow_request_sent\": false,\n \"followers_count\": 1415,\n \"following\": false,\n \"friends_count\": 2605,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 72613712,\n \"id_str\": \"72613712\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 30,\n \"location\": \"New York, NY\",\n \"name\": \"Amy Yensi\",\n \"notifications\": false,\n \"profile_background_color\": \"642D8B\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme10/bg.gif\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme10/bg.gif\",\n \"profile_background_tile\": true,\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/907582283749699585/qLvKmKsr_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/907582283749699585/qLvKmKsr_normal.jpg\",\n \"profile_link_color\": \"FF0000\",\n \"profile_sidebar_border_color\": \"65B0DA\",\n \"profile_sidebar_fill_color\": \"7AC3EE\",\n \"profile_text_color\": \"3D1957\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"amyyensi\",\n \"statuses_count\": 1315,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/deN7bl1sRW\",\n \"utc_offset\": null,\n \"verified\": false\n }\n },\n \"source\": \"<a href=\\\"http://www.socialnewsdesk.com\\\" rel=\\\"nofollow\\\">SocialNewsDesk</a>\",\n \"text\": \"RT @amyyensi: Somber Symbol at the Youth Against Gun Violence Rally and March. They\\u2019ll be walking across the #BrooklynBridge & want #gunref\\u2026\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Fri May 29 22:37:45 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny1.com\",\n \"expanded_url\": \"http://www.ny1.com\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/xPLV2Nm1aQ\"\n }\n ]\n }\n },\n \"favourites_count\": 992,\n \"follow_request_sent\": false,\n \"followers_count\": 455646,\n \"following\": true,\n \"friends_count\": 88,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 43425975,\n \"id_str\": \"43425975\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4150,\n \"location\": \"New York City\",\n \"name\": \"Spectrum News NY1\",\n \"notifications\": false,\n \"profile_background_color\": \"19334C\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/43425975/1526580308\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_link_color\": \"17324D\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"DAE4EE\",\n \"profile_text_color\": \"000000\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NY1\",\n \"statuses_count\": 91284,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/xPLV2Nm1aQ\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:59:27 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"nyti.ms/2LdLS2n\",\n \"expanded_url\": \"https://nyti.ms/2LdLS2n\",\n \"indices\": [\n 81,\n 104\n ],\n \"url\": \"https://t.co/wSme1kPUyu\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 7,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002957879761145857,\n \"id_str\": \"1002957879761145857\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 2,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialflow.com\\\" rel=\\\"nofollow\\\">SocialFlow</a>\",\n \"text\": \"Last chance to catch \\u201cZoe Leonard: Survey\\u201d at the Whitney Museum of American Art https://t.co/wSme1kPUyu\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Sun Mar 18 20:30:33 +0000 2007\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Arts and entertainment news from The New York Times.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nytimes.com/arts\",\n \"expanded_url\": \"http://www.nytimes.com/arts\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/0H74AaBX8Y\"\n }\n ]\n }\n },\n \"favourites_count\": 319,\n \"follow_request_sent\": false,\n \"followers_count\": 2652074,\n \"following\": true,\n \"friends_count\": 230,\n \"geo_enabled\": false,\n \"has_extended_profile\": false,\n \"id\": 1440641,\n \"id_str\": \"1440641\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 19383,\n \"location\": \"New York, NY\",\n \"name\": \"New York Times Arts\",\n \"notifications\": false,\n \"profile_background_color\": \"FFFFFF\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/1440641/1510847448\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/964180969702895616/wJcdJ1MU_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/964180969702895616/wJcdJ1MU_normal.jpg\",\n \"profile_link_color\": \"FF691F\",\n \"profile_sidebar_border_color\": \"323232\",\n \"profile_sidebar_fill_color\": \"E7EFF8\",\n \"profile_text_color\": \"000000\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"nytimesarts\",\n \"statuses_count\": 144228,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/0H74AaBX8Y\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:45:04 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"nym.ag/2J4fEtL\",\n \"expanded_url\": \"https://nym.ag/2J4fEtL\",\n \"indices\": [\n 86,\n 109\n ],\n \"url\": \"https://t.co/G9vsnJKed9\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 15,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002954262693937153,\n \"id_str\": \"1002954262693937153\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 3,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialflow.com\\\" rel=\\\"nofollow\\\">SocialFlow</a>\",\n \"text\": \"Moisturizer with SPF is essential year-round, but it's especially necessary in summer https://t.co/G9vsnJKed9\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Jun 08 13:30:34 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"The ideas, people, and cultural currents that are forever reshaping the world.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nymag.com\",\n \"expanded_url\": \"http://nymag.com\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/uvSpg4t2HC\"\n }\n ]\n }\n },\n \"favourites_count\": 1767,\n \"follow_request_sent\": false,\n \"followers_count\": 1781637,\n \"following\": true,\n \"friends_count\": 871,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 45564482,\n \"id_str\": \"45564482\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 13777,\n \"location\": \"New York, NY\",\n \"name\": \"New York Magazine\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/45564482/1443719391\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_link_color\": \"1F638A\",\n \"profile_sidebar_border_color\": \"000000\",\n \"profile_sidebar_fill_color\": \"DDEEF6\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYMag\",\n \"statuses_count\": 128566,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/uvSpg4t2HC\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:27:29 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/ny1/status/100\\u2026\",\n \"expanded_url\": \"https://twitter.com/ny1/status/1002943072165036034\",\n \"indices\": [\n 44,\n 67\n ],\n \"url\": \"https://t.co/6vipDlMyw3\"\n }\n ],\n \"user_mentions\": [\n {\n \"id\": 100043275,\n \"id_str\": \"100043275\",\n \"indices\": [\n 3,\n 14\n ],\n \"name\": \"NY1 - ON STAGE\",\n \"screen_name\": \"NY1onstage\"\n }\n ]\n },\n \"favorite_count\": 0,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002949835794894849,\n \"id_str\": \"1002949835794894849\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": true,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"quoted_status_id\": 1002943072165036034,\n \"quoted_status_id_str\": \"1002943072165036034\",\n \"retweet_count\": 1,\n \"retweeted\": false,\n \"retweeted_status\": {\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:22:38 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/ny1/status/100\\u2026\",\n \"expanded_url\": \"https://twitter.com/ny1/status/1002943072165036034\",\n \"indices\": [\n 28,\n 51\n ],\n \"url\": \"https://t.co/6vipDlMyw3\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 1,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002948615772491781,\n \"id_str\": \"1002948615772491781\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": true,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"quoted_status\": {\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:00:36 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"media\": [\n {\n \"display_url\": \"pic.twitter.com/6q46uEFIjP\",\n \"expanded_url\": \"https://twitter.com/NY1/status/1002943072165036034/video/1\",\n \"id\": 1002942923078492165,\n \"id_str\": \"1002942923078492165\",\n \"indices\": [\n 112,\n 135\n ],\n \"media_url\": \"http://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 720,\n \"resize\": \"fit\",\n \"w\": 1280\n },\n \"medium\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"small\": {\n \"h\": 383,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"type\": \"photo\",\n \"url\": \"https://t.co/6q46uEFIjP\"\n }\n ],\n \"symbols\": [],\n \"urls\": [],\n \"user_mentions\": [\n {\n \"id\": 100043275,\n \"id_str\": \"100043275\",\n \"indices\": [\n 99,\n 110\n ],\n \"name\": \"NY1 - ON STAGE\",\n \"screen_name\": \"NY1onstage\"\n }\n ]\n },\n \"extended_entities\": {\n \"media\": [\n {\n \"additional_media_info\": {\n \"monetizable\": false\n },\n \"display_url\": \"pic.twitter.com/6q46uEFIjP\",\n \"expanded_url\": \"https://twitter.com/NY1/status/1002943072165036034/video/1\",\n \"id\": 1002942923078492165,\n \"id_str\": \"1002942923078492165\",\n \"indices\": [\n 112,\n 135\n ],\n \"media_url\": \"http://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/ext_tw_video_thumb/1002942923078492165/pu/img/IoBW0F3S2Vl-fX-C.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 720,\n \"resize\": \"fit\",\n \"w\": 1280\n },\n \"medium\": {\n \"h\": 675,\n \"resize\": \"fit\",\n \"w\": 1200\n },\n \"small\": {\n \"h\": 383,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"type\": \"video\",\n \"url\": \"https://t.co/6q46uEFIjP\",\n \"video_info\": {\n \"aspect_ratio\": [\n 16,\n 9\n ],\n \"duration_millis\": 42843,\n \"variants\": [\n {\n \"content_type\": \"application/x-mpegURL\",\n \"url\": \"https://video.twimg.com/ext_tw_video/1002942923078492165/pu/pl/iyGNzXX6Vc1HF6_q.m3u8?tag=3\"\n },\n {\n \"bitrate\": 2176000,\n \"content_type\": \"video/mp4\",\n \"url\": \"https://video.twimg.com/ext_tw_video/1002942923078492165/pu/vid/1280x720/LZ5bsAnqhJbQzkNJ.mp4?tag=3\"\n },\n {\n \"bitrate\": 832000,\n \"content_type\": \"video/mp4\",\n \"url\": \"https://video.twimg.com/ext_tw_video/1002942923078492165/pu/vid/640x360/xoKd4ghCMGtI0k4G.mp4?tag=3\"\n },\n {\n \"bitrate\": 256000,\n \"content_type\": \"video/mp4\",\n \"url\": \"https://video.twimg.com/ext_tw_video/1002942923078492165/pu/vid/320x180/edaunxpdgPpqUlXY.mp4?tag=3\"\n }\n ]\n }\n }\n ]\n },\n \"favorite_count\": 3,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002943072165036034,\n \"id_str\": \"1002943072165036034\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 1,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialnewsdesk.com\\\" rel=\\\"nofollow\\\">SocialNewsDesk</a>\",\n \"text\": \"Don\\u2019t forget to tune in a half hour earlier tonight at 7pm for our \\u201cRoad to the Tonys\\u201d special on @NY1onstage! https://t.co/6q46uEFIjP\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Fri May 29 22:37:45 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny1.com\",\n \"expanded_url\": \"http://www.ny1.com\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/xPLV2Nm1aQ\"\n }\n ]\n }\n },\n \"favourites_count\": 992,\n \"follow_request_sent\": false,\n \"followers_count\": 455646,\n \"following\": true,\n \"friends_count\": 88,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 43425975,\n \"id_str\": \"43425975\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4150,\n \"location\": \"New York City\",\n \"name\": \"Spectrum News NY1\",\n \"notifications\": false,\n \"profile_background_color\": \"19334C\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/43425975/1526580308\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_link_color\": \"17324D\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"DAE4EE\",\n \"profile_text_color\": \"000000\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NY1\",\n \"statuses_count\": 91284,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/xPLV2Nm1aQ\",\n \"utc_offset\": null,\n \"verified\": true\n }\n },\n \"quoted_status_id\": 1002943072165036034,\n \"quoted_status_id_str\": \"1002943072165036034\",\n \"retweet_count\": 1,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://twitter.com/download/iphone\\\" rel=\\\"nofollow\\\">Twitter for iPhone</a>\",\n \"text\": \"Tune in alert! 7pm tonight! https://t.co/6vipDlMyw3\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Dec 28 20:46:16 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"ON STAGE on Spectrum News @NY1 is a weekly theater program hosted by @fdilella and dedicated to the NYC theater scene and beyond.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny1.com\",\n \"expanded_url\": \"http://www.ny1.com\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/xPLV2N4pMg\"\n }\n ]\n }\n },\n \"favourites_count\": 655,\n \"follow_request_sent\": false,\n \"followers_count\": 8850,\n \"following\": false,\n \"friends_count\": 227,\n \"geo_enabled\": false,\n \"has_extended_profile\": false,\n \"id\": 100043275,\n \"id_str\": \"100043275\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 266,\n \"location\": \"New York City\",\n \"name\": \"NY1 - ON STAGE\",\n \"notifications\": false,\n \"profile_background_color\": \"42160B\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/100043275/1516239248\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/953802883174141952/9h86QUTB_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/953802883174141952/9h86QUTB_normal.jpg\",\n \"profile_link_color\": \"94000C\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"EBB484\",\n \"profile_text_color\": \"030303\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NY1onstage\",\n \"statuses_count\": 2052,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/xPLV2N4pMg\",\n \"utc_offset\": null,\n \"verified\": false\n }\n },\n \"source\": \"<a href=\\\"http://www.socialnewsdesk.com\\\" rel=\\\"nofollow\\\">SocialNewsDesk</a>\",\n \"text\": \"RT @NY1onstage: Tune in alert! 7pm tonight! https://t.co/6vipDlMyw3\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Fri May 29 22:37:45 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Spectrum News NY1 is a 24-hr news network in NYC. @NY1 is on Facebook (NY1News), Instagram (NY1) and Snapchat (NY1News).\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny1.com\",\n \"expanded_url\": \"http://www.ny1.com\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/xPLV2Nm1aQ\"\n }\n ]\n }\n },\n \"favourites_count\": 992,\n \"follow_request_sent\": false,\n \"followers_count\": 455646,\n \"following\": true,\n \"friends_count\": 88,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 43425975,\n \"id_str\": \"43425975\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4150,\n \"location\": \"New York City\",\n \"name\": \"Spectrum News NY1\",\n \"notifications\": false,\n \"profile_background_color\": \"19334C\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/43425975/1526580308\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/834494355712966662/yLFVss5n_normal.jpg\",\n \"profile_link_color\": \"17324D\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"DAE4EE\",\n \"profile_text_color\": \"000000\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NY1\",\n \"statuses_count\": 91284,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/xPLV2Nm1aQ\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:25:10 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"media\": [\n {\n \"display_url\": \"pic.twitter.com/mBl5GqlKs9\",\n \"expanded_url\": \"https://twitter.com/NY1weather/status/1002949254594392065/photo/1\",\n \"id\": 1002948655584772098,\n \"id_str\": \"1002948655584772098\",\n \"indices\": [\n 102,\n 125\n ],\n \"media_url\": \"http://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 419,\n \"resize\": \"fit\",\n \"w\": 746\n },\n \"medium\": {\n \"h\": 419,\n \"resize\": \"fit\",\n \"w\": 746\n },\n \"small\": {\n \"h\": 382,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"type\": \"photo\",\n \"url\": \"https://t.co/mBl5GqlKs9\"\n }\n ],\n \"symbols\": [],\n \"urls\": [],\n \"user_mentions\": []\n },\n \"extended_entities\": {\n \"media\": [\n {\n \"display_url\": \"pic.twitter.com/mBl5GqlKs9\",\n \"expanded_url\": \"https://twitter.com/NY1weather/status/1002949254594392065/photo/1\",\n \"id\": 1002948655584772098,\n \"id_str\": \"1002948655584772098\",\n \"indices\": [\n 102,\n 125\n ],\n \"media_url\": \"http://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg\",\n \"media_url_https\": \"https://pbs.twimg.com/media/DeswfQgWAAI-NCO.jpg\",\n \"sizes\": {\n \"large\": {\n \"h\": 419,\n \"resize\": \"fit\",\n \"w\": 746\n },\n \"medium\": {\n \"h\": 419,\n \"resize\": \"fit\",\n \"w\": 746\n },\n \"small\": {\n \"h\": 382,\n \"resize\": \"fit\",\n \"w\": 680\n },\n \"thumb\": {\n \"h\": 150,\n \"resize\": \"crop\",\n \"w\": 150\n }\n },\n \"type\": \"photo\",\n \"url\": \"https://t.co/mBl5GqlKs9\"\n }\n ]\n },\n \"favorite_count\": 10,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002949254594392065,\n \"id_str\": \"1002949254594392065\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 2,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://twitter.com\\\" rel=\\\"nofollow\\\">Twitter Web Client</a>\",\n \"text\": \"A few showers have popped-up around the area, but, the five boroughs remain mostly dry at the moment. https://t.co/mBl5GqlKs9\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Fri May 29 23:37:52 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Weather info from New York City's 24-hour newschannel\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny1.com/weather\",\n \"expanded_url\": \"http://ny1.com/weather\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/ora6dbI5aQ\"\n }\n ]\n }\n },\n \"favourites_count\": 16376,\n \"follow_request_sent\": false,\n \"followers_count\": 376088,\n \"following\": true,\n \"friends_count\": 37,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 43435902,\n \"id_str\": \"43435902\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 1919,\n \"location\": \"New York City\",\n \"name\": \"NY1 Weather\",\n \"notifications\": false,\n \"profile_background_color\": \"2A6398\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg\",\n \"profile_link_color\": \"C72126\",\n \"profile_sidebar_border_color\": \"184D98\",\n \"profile_sidebar_fill_color\": \"CCE3F5\",\n \"profile_text_color\": \"181D33\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NY1weather\",\n \"statuses_count\": 28294,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/ora6dbI5aQ\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:23:23 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"nym.ag/2HeTuz1\",\n \"expanded_url\": \"https://nym.ag/2HeTuz1\",\n \"indices\": [\n 89,\n 112\n ],\n \"url\": \"https://t.co/LHDAVWnk5y\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 7,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002948802549108737,\n \"id_str\": \"1002948802549108737\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 3,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialflow.com\\\" rel=\\\"nofollow\\\">SocialFlow</a>\",\n \"text\": \"The White House is working to set up a summit between President Trump and Vladimir Putin https://t.co/LHDAVWnk5y\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Jun 08 13:30:34 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"The ideas, people, and cultural currents that are forever reshaping the world.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nymag.com\",\n \"expanded_url\": \"http://nymag.com\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/uvSpg4t2HC\"\n }\n ]\n }\n },\n \"favourites_count\": 1767,\n \"follow_request_sent\": false,\n \"followers_count\": 1781637,\n \"following\": true,\n \"friends_count\": 871,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 45564482,\n \"id_str\": \"45564482\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 13777,\n \"location\": \"New York, NY\",\n \"name\": \"New York Magazine\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/45564482/1443719391\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_link_color\": \"1F638A\",\n \"profile_sidebar_border_color\": \"000000\",\n \"profile_sidebar_fill_color\": \"DDEEF6\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYMag\",\n \"statuses_count\": 128566,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/uvSpg4t2HC\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:23:16 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"nym.ag/2J7NBK0\",\n \"expanded_url\": \"https://nym.ag/2J7NBK0\",\n \"indices\": [\n 86,\n 109\n ],\n \"url\": \"https://t.co/Y4kMs05sWN\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 24,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002948776175329281,\n \"id_str\": \"1002948776175329281\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 8,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://www.socialflow.com\\\" rel=\\\"nofollow\\\">SocialFlow</a>\",\n \"text\": \"\\\"My looks definitely opened doors for me. I never interviewed for a job I didn\\u2019t get\\\" https://t.co/Y4kMs05sWN\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Jun 08 13:30:34 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"The ideas, people, and cultural currents that are forever reshaping the world.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nymag.com\",\n \"expanded_url\": \"http://nymag.com\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/uvSpg4t2HC\"\n }\n ]\n }\n },\n \"favourites_count\": 1767,\n \"follow_request_sent\": false,\n \"followers_count\": 1781637,\n \"following\": true,\n \"friends_count\": 871,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 45564482,\n \"id_str\": \"45564482\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 13777,\n \"location\": \"New York, NY\",\n \"name\": \"New York Magazine\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/45564482/1443719391\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_normal.png\",\n \"profile_link_color\": \"1F638A\",\n \"profile_sidebar_border_color\": \"000000\",\n \"profile_sidebar_fill_color\": \"DDEEF6\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYMag\",\n \"statuses_count\": 128566,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/uvSpg4t2HC\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:23:00 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002948708189851649\",\n \"indices\": [\n 117,\n 140\n ],\n \"url\": \"https://t.co/aeymVPrEST\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 7,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002948708189851649,\n \"id_str\": \"1002948708189851649\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 0,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"https://about.twitter.com/products/tweetdeck\\\" rel=\\\"nofollow\\\">TweetDeck</a>\",\n \"text\": \"Dumplings are one of those cross-cultural culinary wonders that tend to be both very comforting and affordably fill\\u2026 https://t.co/aeymVPrEST\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Sat Nov 03 16:15:19 +0000 2007\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Food news and dining guides for New York City.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny.eater.com\",\n \"expanded_url\": \"http://ny.eater.com\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/zePlLx1Yt5\"\n }\n ]\n }\n },\n \"favourites_count\": 508,\n \"follow_request_sent\": false,\n \"followers_count\": 442264,\n \"following\": true,\n \"friends_count\": 197,\n \"geo_enabled\": false,\n \"has_extended_profile\": false,\n \"id\": 9917652,\n \"id_str\": \"9917652\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 3760,\n \"location\": \"New York, NY\",\n \"name\": \"Eater NY\",\n \"notifications\": false,\n \"profile_background_color\": \"FDF7F7\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/9917652/1418407817\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/513844477476081665/tgVPjKD1_normal.png\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/513844477476081665/tgVPjKD1_normal.png\",\n \"profile_link_color\": \"B40041\",\n \"profile_sidebar_border_color\": \"FDF7F7\",\n \"profile_sidebar_fill_color\": \"FFFFFF\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": false,\n \"protected\": false,\n \"screen_name\": \"EaterNY\",\n \"statuses_count\": 38530,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/zePlLx1Yt5\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:22:45 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [],\n \"user_mentions\": []\n },\n \"favorite_count\": 1,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002948645124177927,\n \"id_str\": \"1002948645124177927\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"retweet_count\": 0,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://gms.mtanyct.info/GMSTwitter/Default.aspx\\\" rel=\\\"nofollow\\\">GMS Web Pro App</a>\",\n \"text\": \"Northbound A and Rockaway S trains are running with delays because of a train with mechanical problems at Broad Channel.\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Aug 17 15:28:03 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Official source for news and service change information for MTA NYC Transit subway service. Monitored 24/7. Emergency call 911.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"mta.info\",\n \"expanded_url\": \"http://www.mta.info\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/A32pJWLkKU\"\n }\n ]\n }\n },\n \"favourites_count\": 1490,\n \"follow_request_sent\": false,\n \"followers_count\": 949461,\n \"following\": true,\n \"friends_count\": 296,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 66379182,\n \"id_str\": \"66379182\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4007,\n \"location\": \"New York City\",\n \"name\": \"NYCT Subway\",\n \"notifications\": false,\n \"profile_background_color\": \"000000\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/66379182/1525279294\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/902288411280760832/IU1D9DJd_normal.jpg\",\n \"profile_link_color\": \"000003\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"F0D108\",\n \"profile_text_color\": \"0A070F\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYCTSubway\",\n \"statuses_count\": 269223,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/A32pJWLkKU\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:17:22 +0000 2018\",\n \"entities\": {\n \"hashtags\": [\n {\n \"indices\": [\n 10,\n 24\n ],\n \"text\": \"CPRSavesLives\"\n },\n {\n \"indices\": [\n 133,\n 138\n ],\n \"text\": \"FDNY\"\n }\n ],\n \"symbols\": [],\n \"urls\": [],\n \"user_mentions\": [\n {\n \"id\": 134846593,\n \"id_str\": \"134846593\",\n \"indices\": [\n 3,\n 8\n ],\n \"name\": \"FDNY\",\n \"screen_name\": \"FDNY\"\n }\n ]\n },\n \"favorite_count\": 0,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002947291534319616,\n \"id_str\": \"1002947291534319616\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"retweet_count\": 13,\n \"retweeted\": false,\n \"retweeted_status\": {\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 15:10:05 +0000 2018\",\n \"entities\": {\n \"hashtags\": [\n {\n \"indices\": [\n 0,\n 14\n ],\n \"text\": \"CPRSavesLives\"\n }\n ],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002930357400952832\",\n \"indices\": [\n 117,\n 140\n ],\n \"url\": \"https://t.co/6LDwHATZtd\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 25,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002930357400952832,\n \"id_str\": \"1002930357400952832\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 13,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"https://www.hootsuite.com\\\" rel=\\\"nofollow\\\">Hootsuite Inc.</a>\",\n \"text\": \"#CPRSavesLives and National CPR and AED Awareness Week is a great time to sign up for a FREE hands-only CPR class w\\u2026 https://t.co/6LDwHATZtd\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Mon Apr 19 16:26:00 +0000 2010\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"The official New York City Fire Department feed. Call 911 for all emergencies, 311 for non-emergencies. Account is not monitored 24/7\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nyc.gov/fdny\",\n \"expanded_url\": \"http://www.nyc.gov/fdny\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/baW8ITvn7T\"\n }\n ]\n }\n },\n \"favourites_count\": 341,\n \"follow_request_sent\": false,\n \"followers_count\": 233195,\n \"following\": false,\n \"friends_count\": 269,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 134846593,\n \"id_str\": \"134846593\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 2789,\n \"location\": \"New York, NY\",\n \"name\": \"FDNY\",\n \"notifications\": false,\n \"profile_background_color\": \"131516\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme14/bg.gif\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme14/bg.gif\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/134846593/1452639153\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/884856237552275456/ulMRDdJd_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/884856237552275456/ulMRDdJd_normal.jpg\",\n \"profile_link_color\": \"89C9FA\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"102459\",\n \"profile_text_color\": \"F0E8F0\",\n \"profile_use_background_image\": false,\n \"protected\": false,\n \"screen_name\": \"FDNY\",\n \"statuses_count\": 32023,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/baW8ITvn7T\",\n \"utc_offset\": null,\n \"verified\": true\n }\n },\n \"source\": \"<a href=\\\"http://twitter.com/download/iphone\\\" rel=\\\"nofollow\\\">Twitter for iPhone</a>\",\n \"text\": \"RT @FDNY: #CPRSavesLives and National CPR and AED Awareness Week is a great time to sign up for a FREE hands-only CPR class with the #FDNY\\u2026\",\n \"truncated\": false,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Thu Jul 09 19:42:27 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Live from City Hall, in the greatest city on earth. @NYCMayor Bill de Blasio.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"NYC.gov\",\n \"expanded_url\": \"http://www.NYC.gov\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/gbCFBEvClg\"\n }\n ]\n }\n },\n \"favourites_count\": 1240,\n \"follow_request_sent\": false,\n \"followers_count\": 945050,\n \"following\": true,\n \"friends_count\": 738,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 55338739,\n \"id_str\": \"55338739\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 5713,\n \"location\": \"New York, NY\",\n \"name\": \"NYC Mayor's Office\",\n \"notifications\": false,\n \"profile_background_color\": \"9AE4E8\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/55338739/1527875021\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/925449870000865281/0MX3bBDX_normal.jpg\",\n \"profile_link_color\": \"0084B4\",\n \"profile_sidebar_border_color\": \"BDDCAD\",\n \"profile_sidebar_fill_color\": \"DDFFCC\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NYCMayorsOffice\",\n \"statuses_count\": 25912,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/gbCFBEvClg\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:15:45 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002946882216185856\",\n \"indices\": [\n 116,\n 139\n ],\n \"url\": \"https://t.co/iK3yhDSoKU\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 223,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002946882216185856,\n \"id_str\": \"1002946882216185856\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 115,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://snappytv.com\\\" rel=\\\"nofollow\\\">SnappyTV.com</a>\",\n \"text\": \"In an ancient valley in the Honduran jungle, a scientific expedition used motion-sensing cameras to capture images\\u2026 https://t.co/iK3yhDSoKU\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Tue May 06 19:36:33 +0000 2008\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"The New Yorker is a weekly magazine with a mix of reporting on politics and culture, humor and cartoons, fiction and poetry, and reviews and criticism.\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"newyorker.com\",\n \"expanded_url\": \"http://www.newyorker.com\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/RLTwD4Ft0i\"\n }\n ]\n }\n },\n \"favourites_count\": 1793,\n \"follow_request_sent\": false,\n \"followers_count\": 8619393,\n \"following\": true,\n \"friends_count\": 422,\n \"geo_enabled\": false,\n \"has_extended_profile\": false,\n \"id\": 14677919,\n \"id_str\": \"14677919\",\n \"is_translation_enabled\": true,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 63156,\n \"location\": \"New York, NY\",\n \"name\": \"The New Yorker\",\n \"notifications\": false,\n \"profile_background_color\": \"9AE4E8\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme16/bg.gif\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme16/bg.gif\",\n \"profile_background_tile\": false,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/14677919/1478111474\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/900059590586486784/fmY_4l3f_normal.jpg\",\n \"profile_link_color\": \"0084B4\",\n \"profile_sidebar_border_color\": \"BDDCAD\",\n \"profile_sidebar_fill_color\": \"DDFFCC\",\n \"profile_text_color\": \"333333\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NewYorker\",\n \"statuses_count\": 75774,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/RLTwD4Ft0i\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:15:44 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002946878491807744\",\n \"indices\": [\n 117,\n 140\n ],\n \"url\": \"https://t.co/henixBbnSV\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 6,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002946878491807744,\n \"id_str\": \"1002946878491807744\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 4,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"http://twitter.com\\\" rel=\\\"nofollow\\\">Twitter Web Client</a>\",\n \"text\": \"Summer-like warmth and moderate levels of humidity are in store for the afternoon hours. We could also see a shower\\u2026 https://t.co/henixBbnSV\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Fri May 29 23:37:52 +0000 2009\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Weather info from New York City's 24-hour newschannel\",\n \"entities\": {\n \"description\": {\n \"urls\": []\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"ny1.com/weather\",\n \"expanded_url\": \"http://ny1.com/weather\",\n \"indices\": [\n 0,\n 22\n ],\n \"url\": \"http://t.co/ora6dbI5aQ\"\n }\n ]\n }\n },\n \"favourites_count\": 16376,\n \"follow_request_sent\": false,\n \"followers_count\": 376088,\n \"following\": true,\n \"friends_count\": 37,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 43435902,\n \"id_str\": \"43435902\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 1919,\n \"location\": \"New York City\",\n \"name\": \"NY1 Weather\",\n \"notifications\": false,\n \"profile_background_color\": \"2A6398\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme1/bg.png\",\n \"profile_background_tile\": false,\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/959067130/NY1_Twit_Weather_Icon_normal.jpg\",\n \"profile_link_color\": \"C72126\",\n \"profile_sidebar_border_color\": \"184D98\",\n \"profile_sidebar_fill_color\": \"CCE3F5\",\n \"profile_text_color\": \"181D33\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"NY1weather\",\n \"statuses_count\": 28294,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"http://t.co/ora6dbI5aQ\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n{\n \"contributors\": null,\n \"coordinates\": null,\n \"created_at\": \"Sat Jun 02 16:14:00 +0000 2018\",\n \"entities\": {\n \"hashtags\": [],\n \"symbols\": [],\n \"urls\": [\n {\n \"display_url\": \"twitter.com/i/web/status/1\\u2026\",\n \"expanded_url\": \"https://twitter.com/i/web/status/1002946443190177793\",\n \"indices\": [\n 116,\n 139\n ],\n \"url\": \"https://t.co/Yh5kpvmZEr\"\n }\n ],\n \"user_mentions\": []\n },\n \"favorite_count\": 7,\n \"favorited\": false,\n \"geo\": null,\n \"id\": 1002946443190177793,\n \"id_str\": \"1002946443190177793\",\n \"in_reply_to_screen_name\": null,\n \"in_reply_to_status_id\": null,\n \"in_reply_to_status_id_str\": null,\n \"in_reply_to_user_id\": null,\n \"in_reply_to_user_id_str\": null,\n \"is_quote_status\": false,\n \"lang\": \"en\",\n \"place\": null,\n \"possibly_sensitive\": false,\n \"possibly_sensitive_appealable\": false,\n \"retweet_count\": 2,\n \"retweeted\": false,\n \"source\": \"<a href=\\\"https://about.twitter.com/products/tweetdeck\\\" rel=\\\"nofollow\\\">TweetDeck</a>\",\n \"text\": \"The Brooklyn Army Terminal\\u2019s 100th year: Unveiling new space for over 1,000 new jobs, launching strategies for the\\u2026 https://t.co/Yh5kpvmZEr\",\n \"truncated\": true,\n \"user\": {\n \"contributors_enabled\": false,\n \"created_at\": \"Sat Feb 12 00:43:55 +0000 2011\",\n \"default_profile\": false,\n \"default_profile_image\": false,\n \"description\": \"Official New York City government Twitter. Keep up with NYC news, services, programs, free events and emergency notifications. https://t.co/N0igPl3T7S\",\n \"entities\": {\n \"description\": {\n \"urls\": [\n {\n \"display_url\": \"nyc.gov/socialmediapol\\u2026\",\n \"expanded_url\": \"http://nyc.gov/socialmediapolicy\",\n \"indices\": [\n 127,\n 150\n ],\n \"url\": \"https://t.co/N0igPl3T7S\"\n }\n ]\n },\n \"url\": {\n \"urls\": [\n {\n \"display_url\": \"nyc.gov\",\n \"expanded_url\": \"http://nyc.gov\",\n \"indices\": [\n 0,\n 23\n ],\n \"url\": \"https://t.co/HSvs3qcfig\"\n }\n ]\n }\n },\n \"favourites_count\": 2644,\n \"follow_request_sent\": false,\n \"followers_count\": 1171727,\n \"following\": true,\n \"friends_count\": 243,\n \"geo_enabled\": true,\n \"has_extended_profile\": false,\n \"id\": 250884927,\n \"id_str\": \"250884927\",\n \"is_translation_enabled\": false,\n \"is_translator\": false,\n \"lang\": \"en\",\n \"listed_count\": 4414,\n \"location\": \"New York City\",\n \"name\": \"City of New York\",\n \"notifications\": false,\n \"profile_background_color\": \"7DC7FF\",\n \"profile_background_image_url\": \"http://abs.twimg.com/images/themes/theme13/bg.gif\",\n \"profile_background_image_url_https\": \"https://abs.twimg.com/images/themes/theme13/bg.gif\",\n \"profile_background_tile\": true,\n \"profile_banner_url\": \"https://pbs.twimg.com/profile_banners/250884927/1525899407\",\n \"profile_image_url\": \"http://pbs.twimg.com/profile_images/879455346179354624/uWMfEYZH_normal.jpg\",\n \"profile_image_url_https\": \"https://pbs.twimg.com/profile_images/879455346179354624/uWMfEYZH_normal.jpg\",\n \"profile_link_color\": \"0099B9\",\n \"profile_sidebar_border_color\": \"FFFFFF\",\n \"profile_sidebar_fill_color\": \"E5E8E8\",\n \"profile_text_color\": \"3C3940\",\n \"profile_use_background_image\": true,\n \"protected\": false,\n \"screen_name\": \"nycgov\",\n \"statuses_count\": 27885,\n \"time_zone\": null,\n \"translator_type\": \"none\",\n \"url\": \"https://t.co/HSvs3qcfig\",\n \"utc_offset\": null,\n \"verified\": true\n }\n}\n"
]
],
[
[
"# Students Turn Activity 2\n# Get My Tweets\n\n## Instructions\n\n* In this activity, you will retrieve the most recent tweets sent out from your Twitter account using the Tweepy library.\n\n * Import the necessary libraries needed to talk to Twitter's API.\n\n * Import your keys from your `config.py` file.\n\n * Set up Tweepy authentication.\n\n * Write code to fetch all tweets from your home feed.\n\n * Loop through and print out tweets.\n\n## Hint:\n\n* Consult the [Tweepy](http://docs.tweepy.org/en/v3.5.0/api.html?) documentation for the method used to accomplish this task.\n\n## Bonus\n\n* If you finish the activity early, try tweaking the parameters. For example, can you fetch ten tweets with the script? If you haven't yet sent out more than ten tweets from your account, do that first.",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json",
"_____no_output_____"
],
[
"# Import Twitter API Keys\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n",
"_____no_output_____"
],
[
"# Setup Tweepy API Authentication\n# YOUR CODE HERE\n",
"_____no_output_____"
],
[
"# Get all tweets from home feed\n# YOUR CODE HERE\n",
"_____no_output_____"
],
[
"# Loop through all tweets and print a prettified JSON of each tweet\n# YOUR CODE HERE\n",
"_____no_output_____"
]
],
[
[
"# Students Turn Activity 3\n# Get Other Tweets\n\n* In this activity, we will retrieve tweets sent out by any account of our choosing!\n\n## Instructions\n\n* Choose a twitter account and save the screen name to a variable.\n\n* Retrieve the latest tweets sent out from that account.\n\n* Use the code from the previous activities to get you started!\n\n* Consult the [Tweepy Docs](http://docs.tweepy.org/en/v3.5.0/api.html) as needed.",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret",
"_____no_output_____"
],
[
"# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Target User\n# CODE HERE\n",
"_____no_output_____"
],
[
"# Get all tweets from home feed\n# CODE HERE\n",
"_____no_output_____"
],
[
"# Loop through all tweets\n# CODE HERE\n",
"_____no_output_____"
]
],
[
[
"# Everyone Turn Activity 4",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport json",
"_____no_output_____"
],
[
"# Read JSONs\nsample = \"./Resources/SampleX.json\"",
"_____no_output_____"
],
[
"def load_json(jsonfile):\n \"\"\"Load JSON from a file\"\"\"\n with open(jsonfile) as file_handle:\n return json.load(file_handle)",
"_____no_output_____"
],
[
"sample_data = load_json(sample)\nprint(json.dumps(sample_data[0], indent=4, sort_keys=True))",
"_____no_output_____"
],
[
"print(\"------------------------------------------------------------------\")\n\n# Using the Sample_Data provided above, write code to answer each of the\n# following questions:",
"_____no_output_____"
],
[
"# Question 1: What user account is the tweets in the Sample associated\n# with?\nuser_account = sample_data[0][\"user\"][\"name\"]\nprint(f\"User Account: {user_account}\")",
"_____no_output_____"
],
[
"# Question 2: How many followers does this account have associated with it?\nfollower_count = sample_data[0][\"user\"][\"followers_count\"]\nprint(f\"Follower Count: {follower_count}\")",
"_____no_output_____"
],
[
"# Question 3: How many tweets are included in the Sample?\nprint(f\"Tweet Count (In Sample): {len(sample_data)}\")",
"_____no_output_____"
],
[
"# Question 4: How many tweets total has this account made?\ntotal_tweets = sample_data[0][\"user\"][\"statuses_count\"]\nprint(f\"Tweet Count (Total): {total_tweets}\")",
"_____no_output_____"
],
[
"# Question 5: What was the text in the most recent tweet?\nrecent_tweet = sample_data[0][\"text\"]\nprint(f\"Most Recent Tweet: {recent_tweet}\")",
"_____no_output_____"
],
[
"# Question 6: What was the text associated with each of the tweets\n# included in this sample data?\nprint(\"All Tweets:\")\nfor tweet in sample_data:\n print(f'{tweet[\"text\"]}')",
"_____no_output_____"
],
[
"# Question 7 (Bonus): Which of the user's tweets was most frequently\n# retweeted? How many retweets were there?\ntop_tweet = \"\"\ntop_tweet_follower_count = 0\n\nfor tweet in sample_data:\n if(tweet[\"retweet_count\"] > top_tweet_follower_count):\n top_tweet = tweet[\"text\"]\n top_tweet_follower_count = tweet[\"retweet_count\"]\nprint(f\"Most Popular Tweet: {top_tweet}\")\nprint(f\"Number of Retweets: {top_tweet_follower_count}\")",
"_____no_output_____"
]
],
[
[
"# Students Activity 5\n### Popular Users\n\n### Instructions\n\n* In this activity, you are given an incomplete CSV file of Twitter's most popular accounts. You will use this CSV file in conjunction with Tweepy's API to create a pandas DataFrame.\n\n* Consult the Jupyter Notebook file for instructions, but here are your tasks:\n\n * The \"PopularAccounts.csv\" file has columns whose info needs to be filled in.\n\n * Import the CSV into a pandas DataFrame.\n\n * Iterate over the rows and use Tweepy to retrieve the info for the missing columns. Add the information to the DataFrame.\n\n * Export the results to a new CSV file called \"PopularAccounts_New.csv\"\n\n * Calculate the averages of each column and create a DataFrame of the averages.\n\n### Hints:\n\n* Make sure to use the appropriate method from the [Tweepy Docs](http://docs.tweepy.org/en/v3.5.0/api.html)\n\n* You may have to use try/except to avoid missing users.",
"_____no_output_____"
]
],
[
[
"# Import Dependencies\nimport tweepy\nimport json\nimport pandas as pd\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret",
"_____no_output_____"
],
[
"# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Import CSV file into Data Frame\n",
"_____no_output_____"
],
[
"# Iterate through DataFrame\n",
"_____no_output_____"
],
[
"# Export the new CSV\n\n\n# View the DataFrame\n",
"_____no_output_____"
],
[
"# Calculate Averages\n\n# Create DataFrame\n\n# Create a Dataframe of hte averages\n",
"_____no_output_____"
]
],
[
[
"# Students Turn Activity 6\n# Plot Popular Accounts\n\n## Instructions\n\n* In this activity, you will use MatPlotLib to render three scatterplot charts of the results from the last activity.\n\n1. The first scatterplot will plot Tweet Counts (x-axis) vs Follower Counts (y-axis) to determine a relationship, if any, between the two sets of values. It should look like this:\n\n\n\n2. Likewise, build a scatterplot for Number Following (x-axis) vs Follower Counts (y-axis).\n\n3. Finally, build a scatterplot for Number of Favorites (x-axis) vs Follower Counts (y-axis).",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n# Setup Tweepy API Authentication\n",
"_____no_output_____"
],
[
"# Import CSV file into Data Frame\npopular_tweeters = pd.read_csv(\"./Resources/PopularAccounts.csv\", dtype=str)\n\n# Iterate through DataFrame\n\n# Export the new CSV\n\n# View the DataFrame\n",
"_____no_output_____"
],
[
"# Calculate Averages\n\n\n# Create DataFrame\n\n# Create a Dataframe of hte averages\n",
"_____no_output_____"
],
[
"# Extract Tweet Counts and Follower Counts\n\n# Easy preview of headers\n",
"_____no_output_____"
],
[
"# Tweet Counts vs Follower Counts \n",
"_____no_output_____"
],
[
"# Number Following vs Follower Counts\n",
"_____no_output_____"
],
[
"# Number of Favorites vs Follower Counts\n",
"_____no_output_____"
]
],
[
[
"# Instructors Turn Activity 7 Pagination",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Target User\ntarget_user = \"GuardianData\"\n\n# Tweet Texts\ntweet_texts = []\n\n# Get all tweets from home feed\npublic_tweets = api.user_timeline(target_user)\n\n# Loop through all tweets\nfor tweet in public_tweets:\n\n # Print Tweet\n print(tweet[\"text\"])\n\n # Store Tweet in Array\n tweet_texts.append(tweet[\"text\"])",
"_____no_output_____"
],
[
"# Print the Tweet Count\nprint(f\"Tweet Count: {len(tweet_texts)}\")",
"_____no_output_____"
],
[
"# With pagination",
"_____no_output_____"
],
[
"# Dependencies\nimport tweepy\nimport json\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Target User\ntarget_user = \"GuardianData\"\n\n# Tweet Texts\ntweet_texts = []\n\n# Create a loop to iteratively run API requests\nfor x in range(1, 11):\n\n # Get all tweets from home feed (for each page specified)\n public_tweets = api.user_timeline(target_user, page=x)\n\n # Loop through all tweets\n for tweet in public_tweets:\n\n # Print Tweet\n print(tweet[\"text\"])\n\n # Store Tweet in Array\n tweet_texts.append(tweet[\"text\"])",
"_____no_output_____"
],
[
"\n# Print the Tweet Count# Print \nprint(f\"Tweet Count: {len(tweet_texts)}\")",
"_____no_output_____"
]
],
[
[
"# Everyone Turn Activity 8 Datetime Objects",
"_____no_output_____"
]
],
[
[
"# New Dependency\nfrom datetime import datetime",
"_____no_output_____"
],
[
"# Dependencies\nimport tweepy\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Target User\ntarget_user = 'latimes'\n\n# Get all tweets from home feed\npublic_tweets = api.user_timeline(target_user)\n\n# A list to hold tweet timestamps\ntweet_times = []\n\n# Loop through all tweets\nfor tweet in public_tweets:\n raw_time = tweet[\"created_at\"]\n print(raw_time)\n tweet_times.append(raw_time)",
"_____no_output_____"
],
[
"# Convert tweet timestamps to datetime objects that can be manipulated by\n# Python\nconverted_timestamps = []\nfor raw_time in tweet_times:\n # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior\n # http://strftime.org/\n converted_time = datetime.strptime(raw_time, \"%a %b %d %H:%M:%S %z %Y\")\n converted_timestamps.append(converted_time)",
"_____no_output_____"
],
[
"print(tweet_times[0])\nprint(tweet_times[1])",
"_____no_output_____"
],
[
"print(converted_timestamps[0])\nprint(converted_timestamps[1])",
"_____no_output_____"
],
[
"diff = converted_timestamps[0] - converted_timestamps[1]\nprint(\"Time difference: \", diff)\nprint('seconds: {}'.format(diff.seconds))",
"_____no_output_____"
],
[
"converted_length = len(converted_timestamps)\nprint(f\"length of converted timestamps list: {converted_length}\")\n\ntime_diffs = []\n\nfor x in range(converted_length - 1):\n time_diff = converted_timestamps[x] - converted_timestamps[x + 1]\n# print(f'time diff: {time_diff}')\n# print(f'time diff (in seconds): {time_diff.seconds}')\n# print(f'time diff (in minutes): {time_diff.seconds / 60}')\n# print(f'time diff (in hours): {time_diff.seconds / 3600}')\n\n # convert time_diff to hours\n time_diff = time_diff.seconds / 3600\n time_diffs.append(time_diff)\n\nprint(f\"Avg. Hours Between Tweets: {np.mean(time_diffs)}\")",
"_____no_output_____"
]
],
[
[
"# Students Turn Activity 9\n# Twitter Velocity\n\n## Instructions\n\n* You are a political data consultant, and have been asked to evaluate how frequently Donald Trump tweets. As a savvy data visualization specialist, you decide on the following course of action: first, you will collect the timestamps of the 500 most recent tweets sent out by Trump. After making a list of the timestamps, you will convert the timestamps into datetime objects. Then you will calculate the time difference from one tweet to the next, and plot those data points in a scatterplot chart.\n\n* The tools you will use for this task are Tweepy and MatPlotLib. You will also need to use the `datetime` library to convert Twitter timestamps to Python datetime objects.\n\n* Your plot should look something like this:\n\n \n\n* This handy chart visually demonstrates Trump's tweet pattern: the majority of his tweets are sent within five hours of each other, but he goes up to 24 hours without tweeting!\n\n* See, in contrast, the tweet pattern of a major news organization, the LA Times, whose tweets are sent out much more frequently:\n\n \n\n* **Note**: Feel free to plot the tweets of another Twitter account. It does not have to be Donald Trump's!",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json\nimport numpy as np\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n\n# Setup Tweepy API Authentication\n",
"_____no_output_____"
],
[
"# Target User\n\n# Create array to record all date-times of tweets\n\n# Create a counter for viewing every 100 tweets\n\n\n# Loop through 500 tweets\n\n \n\n# Confirm tweet counts\n",
"_____no_output_____"
],
[
"# Convert all tweet times into datetime objects\n\n\n# Add each datetime object into the array\n",
"_____no_output_____"
],
[
"# Calculate the time between tweets\n\n\n# Calculate the time in between each tweet\n\n# Hours Between Tweets\n",
"_____no_output_____"
],
[
"# Plot Time Between Tweets\n",
"_____no_output_____"
]
],
[
[
"# Instructor Turn Activity 10",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Search Term\nsearch_term = input(\"Which term would you like to search for? \")\n\n# Search for all tweets\npublic_tweets = api.search(search_term)\npublic_tweets",
"_____no_output_____"
],
[
"# View Search Object\n# print(public_tweets)\n\n# Loop through all tweets\nfor tweet in public_tweets[\"statuses\"]:\n\n # Utilize JSON dumps to generate a pretty-printed json\n # print(json.dumps(tweet, sort_keys=True, indent=4, separators=(',', ': ')))\n print(tweet[\"text\"])",
"_____no_output_____"
]
],
[
[
"# Students Turn Activity 11\n# Hashtag Popularity\n\n## Instructions\n\n* In this activity, you will calculate the frequency of tweets containing the following hashtags: **#bigdata, #ai, #vr, #foreverchuck**\n\n* Accomplish this task by using Tweepy to search for tweets containing these search terms (Hint: use a loop), then identifying how frequently tweets are sent that contain these keywords.\n\n* You may, of course, use other hashtags.\n\n* You can do this. Good luck!",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json\nimport numpy as np\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Target Hashtags\n\n\n# Loop through each hashtag\n",
"_____no_output_____"
]
],
[
[
"# Students turn Activity 11 ",
"_____no_output_____"
],
[
"# Subway Delays in New York City\n\n## Instructions\n\n* In this activity, you will use data gathered from Twitter to plot which trains in the NYC subway system most frequently cause delays.\n\n* The Twitter account **SubwayStats** announces delays and changes in the NYC subway system.\n\n* Your goal is to pull the 1,000 most recent tweets from that account and use MatPlotLib to generate a bar chart of the number of delays per each train:\n\n \n\n* Accomplish this task by first compiling a Python dictionary, whose key value pairs consist of each train and the number of delays:\n\n \n\n* In order to build such a dictionary, you will need to filter the tweet texts.\n\n* See the Jupyter Notebook file for more specific instructions at each step. Good luck!",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport tweepy\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom config import consumer_key, consumer_secret, access_token, access_token_secret\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())",
"_____no_output_____"
],
[
"# Array of Trains\ndelayed_trains = {}\n \n# Target User\ntarget_user = \"SubwayStats\"\n\n# Loop through 50 pages of \n",
"_____no_output_____"
],
[
"# Print the Train Delay counts\n\n\n# Convert Train Delay object into a series\n\n# Preview the results\n",
"_____no_output_____"
],
[
"# Create a plot \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",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4a92d6813f2d51a10fc4ee4cfd1f58207facf41f
| 9,051 |
ipynb
|
Jupyter Notebook
|
PySparkSQL.ipynb
|
Santhoshkumard11/Learning-PySpark
|
316571e709569d9c865198473674918d05d0fb04
|
[
"Apache-2.0"
] | 2 |
2021-08-01T18:13:46.000Z
|
2022-03-08T11:07:37.000Z
|
PySparkSQL.ipynb
|
Santhoshkumard11/Learning-PySpark
|
316571e709569d9c865198473674918d05d0fb04
|
[
"Apache-2.0"
] | null | null | null |
PySparkSQL.ipynb
|
Santhoshkumard11/Learning-PySpark
|
316571e709569d9c865198473674918d05d0fb04
|
[
"Apache-2.0"
] | null | null | null | 25.86 | 117 | 0.405591 |
[
[
[
"# PySpark Learning Notes",
"_____no_output_____"
]
],
[
[
"# Simple SQL query\r\nimport findspark\r\nfindspark.init()\r\nimport pyspark\r\nfrom pyspark.sql import SparkSession\r\nspark = SparkSession.builder.config('spark.sql.repl.eagerEval.enabled', True).getOrCreate()\r\ndf = spark.sql('''select 'spark' as hello ''')\r\ndf.show()\r\n",
"+-----+\n|hello|\n+-----+\n|spark|\n+-----+\n\n"
],
[
"from datetime import datetime, date\r\nfrom pyspark.sql import Row\r\ndf = spark.createDataFrame([\r\nRow(a=1, b=2., c='string1', d=date(2000, 1, 1), e=datetime(2000, 1, 1, 12, 0)),\r\nRow(a=2, b=3., c='string2', d=date(2000, 2, 1), e=datetime(2000, 1, 2, 12, 0)),\r\nRow(a=4, b=5., c='string3', d=date(2000, 3, 1), e=datetime(2000, 1, 3, 12, 0))\r\n])\r\n",
"_____no_output_____"
],
[
"df.show()",
"+---+---+-------+----------+-------------------+\n| a| b| c| d| e|\n+---+---+-------+----------+-------------------+\n| 1|2.0|string1|2000-01-01|2000-01-01 12:00:00|\n| 2|3.0|string2|2000-02-01|2000-01-02 12:00:00|\n| 4|5.0|string3|2000-03-01|2000-01-03 12:00:00|\n+---+---+-------+----------+-------------------+\n\n"
],
[
"df.printSchema()",
"root\n |-- a: long (nullable = true)\n |-- b: double (nullable = true)\n |-- c: string (nullable = true)\n |-- d: date (nullable = true)\n |-- e: timestamp (nullable = true)\n\n"
],
[
"# enabling more elegant look\r\nspark.conf.set('spark.sql.repl.eagerEval.enabled', True)\r\ndf",
"_____no_output_____"
],
[
"# adding a new row to the existing dataframe\r\ndf2 = spark.createDataFrame([Row(a=4, b=8.4, c='string4', d=date(2021, 8, 1), e=datetime(2021, 8, 1, 13, 46))])",
"_____no_output_____"
],
[
"df = df.union(df2)\r\ndf.show()",
"+---+---+-------+----------+-------------------+\n| a| b| c| d| e|\n+---+---+-------+----------+-------------------+\n| 1|2.0|string1|2000-01-01|2000-01-01 12:00:00|\n| 2|3.0|string2|2000-02-01|2000-01-02 12:00:00|\n| 4|5.0|string3|2000-03-01|2000-01-03 12:00:00|\n| 4|8.4|string4|2021-08-01|2021-08-01 13:46:00|\n| 4|8.4|string4|2021-08-01|2021-08-01 13:46:00|\n+---+---+-------+----------+-------------------+\n\n"
],
[
"# spark user defined functions\r\nimport pandas as pd\r\nfrom pyspark.sql.functions import pandas_udf\r\n\r\n\r\n@pandas_udf('long')\r\ndef pandas_plus_one(series: pd.Series) -> pd.Series:\r\n # Simply plus one by using pandas Series.\r\n return series + 1\r\n\r\n\r\ndf.select(pandas_plus_one(df.a)).show()\r\n",
"+------------------+\n|pandas_plus_one(a)|\n+------------------+\n| 2|\n| 3|\n| 5|\n| 5|\n| 5|\n+------------------+\n\n"
],
[
"# checking the grouping and aggregation functions\r\ndf.groupBy(\"a\").sum().show()",
"+---+------+------+\n| a|sum(a)|sum(b)|\n+---+------+------+\n| 1| 1| 2.0|\n| 2| 2| 3.0|\n| 4| 12| 21.8|\n+---+------+------+\n\n"
],
[
"# Storing the dataframe to a csv\r\ndf.write.csv('file:///bar.csv\"',mode=\"append\", quoteAll=True)",
"_____no_output_____"
],
[
"df.show()",
"+---+---+-------+----------+-------------------+\n| a| b| c| d| e|\n+---+---+-------+----------+-------------------+\n| 1|2.0|string1|2000-01-01|2000-01-01 12:00:00|\n| 2|3.0|string2|2000-02-01|2000-01-02 12:00:00|\n| 4|5.0|string3|2000-03-01|2000-01-03 12:00:00|\n| 4|8.4|string4|2021-08-01|2021-08-01 13:46:00|\n+---+---+-------+----------+-------------------+\n\n"
]
],
[
[
"# SPARK SQL - Creating a view",
"_____no_output_____"
]
],
[
[
"# creating a view or consider it as a temp table where you can run SQL queries on them\r\ndf.createOrReplaceTempView(\"demoTable\")\r\nspark.sql(\"SELECT count(*) from demoTable\").show()",
"+--------+\n|count(1)|\n+--------+\n| 4|\n+--------+\n\n"
],
[
"spark.sql(\"select * from demoTable where a = 4\").show()",
"+---+---+-------+----------+-------------------+\n| a| b| c| d| e|\n+---+---+-------+----------+-------------------+\n| 4|5.0|string3|2000-03-01|2000-01-03 12:00:00|\n| 4|8.4|string4|2021-08-01|2021-08-01 13:46:00|\n+---+---+-------+----------+-------------------+\n\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4a92f21e98df1286dee0329acbf002341922e360
| 4,046 |
ipynb
|
Jupyter Notebook
|
submission_from_nb.ipynb
|
hno2/emlie
|
6ccb2a55c569e9384beecd14e6272dbc1a5bddf3
|
[
"MIT"
] | null | null | null |
submission_from_nb.ipynb
|
hno2/emlie
|
6ccb2a55c569e9384beecd14e6272dbc1a5bddf3
|
[
"MIT"
] | 46 |
2021-05-10T09:59:40.000Z
|
2021-09-21T07:39:49.000Z
|
submission_from_nb.ipynb
|
hno2/emlie
|
6ccb2a55c569e9384beecd14e6272dbc1a5bddf3
|
[
"MIT"
] | null | null | null | 27.903448 | 129 | 0.555858 |
[
[
[
"def get_colab():\n try:\n from google.colab import _message\n return _message.blocking_request('get_ipynb', request='', timeout_sec=5)\n except:\n raise NotImplementedError(\"You seem to use the colab function eventhough colab is not availabe\")\n",
"_____no_output_____"
],
[
"def get_saved_nb_content():\n try:\n from IPython.display import display, Javascript\n except ImportError:\n print(\"Could not import IPython Display Function\")\n # can have comments here :)\n js_cmd = 'IPython.notebook.kernel.execute(\\'filepath = \"\\' + IPython.notebook.notebook_name + \\'\"\\')'\n display(Javascript(js_cmd))\n with open(filepath,\"r\") as file:\n return(json.load(file))",
"_____no_output_____"
],
[
"from requests import post\nmode=\"jupyter\"\n\nif mode == \"jupyter\":\n display(Javascript('IPython.notebook.save_checkpoint();'))\n display(Javascript('IPython.notebook.save_notebook();'))\n notebook_json_string=get_saved_nb_content()\n \nelif mode == \"jupyterlab\":\n display(Javascript('document.querySelector(\\'[data-command=\"docmanager:save\"]\\').click();')) \n notebook_json_string=get_saved_nb_content()\nelif mode==\"colab\":\n notebook_json_string=get_colab()\nelse: \n raise NotImplementedError(\"You seem to work in an unkown environment, where we can not programatically submit\")\n\nmain_url=\"http://localhost:5000/upload/\"\nassignment=\"Into the wild\" # Or Maybe NB name\nsubmissionurl=main_url+assignment\nif not \"auth_token\" in locals():\n auth_token=input(\"Please enter your auth token here:\")\nx=post(submissionurl, files={\"file\":(\"submission.ipynb\",str(notebook_json_string))}, data={\"auth_token\": auth_token})",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
4a92f6572ea542e018625cc3e7b33571c6a1f70f
| 28,891 |
ipynb
|
Jupyter Notebook
|
Text_Classification_20_newsgroups.ipynb
|
AmritK10/20_Newsgroups_Text_classification
|
5edfb0f5ac8a3fdf66b024d043088915d34a31d7
|
[
"MIT"
] | 1 |
2019-06-23T16:03:22.000Z
|
2019-06-23T16:03:22.000Z
|
Text_Classification_20_newsgroups.ipynb
|
AmritK10/20_Newsgroups_Text_classification
|
5edfb0f5ac8a3fdf66b024d043088915d34a31d7
|
[
"MIT"
] | null | null | null |
Text_Classification_20_newsgroups.ipynb
|
AmritK10/20_Newsgroups_Text_classification
|
5edfb0f5ac8a3fdf66b024d043088915d34a31d7
|
[
"MIT"
] | 2 |
2020-04-26T06:18:53.000Z
|
2021-04-05T03:24:37.000Z
| 36.068664 | 179 | 0.411824 |
[
[
[
"#importing modules\nimport os\nimport codecs\nimport numpy as np\nimport string\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"# **Data Preprocessing**",
"_____no_output_____"
]
],
[
[
"#downloading and extracting the files on colab server\nimport urllib.request\nurllib.request.urlretrieve (\"https://archive.ics.uci.edu/ml/machine-learning-databases/20newsgroups-mld/20_newsgroups.tar.gz\", \"a.tar.gz\")\nimport tarfile\ntar = tarfile.open(\"a.tar.gz\")\ntar.extractall()\ntar.close()",
"_____no_output_____"
],
[
"#making a list of all the file paths and their corresponding class\nf_paths=[]\ni=-1\npath=\"20_newsgroups\"\nfolderlist=os.listdir(path)\nif \".DS_Store\" in folderlist:\n folderlist.remove('.DS_Store')\nfor folder in folderlist:\n i+=1\n filelist=os.listdir(path+'/'+folder)\n for file in filelist:\n f_paths.append((path+'/'+folder+'/'+file,i))\nlen(f_paths)",
"_____no_output_____"
],
[
"#splitting the list of paths into training and testing data\nfrom sklearn import model_selection\nx_train,x_test=model_selection.train_test_split(f_paths)\nlen(x_train),len(x_test)",
"_____no_output_____"
],
[
"#Making the lists X_train and X_test containg only the paths of the files in training and testing data\n#First making lists Y_train and Y_test containing the classes of the training and testing data\nX_train=[]\nX_test=[]\nY_train=[]\nY_test=[]\nfor i in range(len(x_train)):\n X_train.append(x_train[i][0])\n Y_train.append(x_train[i][1])\nfor i in range(len(x_test)):\n X_test.append(x_test[i][0])\n Y_test.append(x_test[i][1])\n#Transforming Y_train and Y_test into 1 dimensional np arrays\nY_train=(np.array([Y_train])).reshape(-1)\nY_test=(np.array([Y_test])).reshape(-1)\n#shape of Y_train and Y_test np arrays\nY_train.shape,Y_test.shape",
"_____no_output_____"
],
[
"import nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nstop=set(stopwords.words(\"english\"))",
"[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n"
],
[
"#adding all the above lists and including punctuations to stop words\nstop_words=list(stop)+list(set(string.punctuation))\nlen(stop_words)",
"_____no_output_____"
],
[
"#making vocabulary from the files in X_train i.e. training data\nvocab={}\ncount =0\nfor filename in X_train:\n count+=1\n f = open(filename,'r',errors='ignore')\n record=f.read()\n words=record.split()\n for word in words:\n if len(word)>2:\n if word.lower() not in stop_words:\n if word.lower() in vocab:\n vocab[word.lower()]+=1\n else:\n vocab[word.lower()]=1\n f.close()",
"_____no_output_____"
],
[
"#length of the vocabulary\nlen(vocab)",
"_____no_output_____"
],
[
"#sorting the vocabulary on the basis of the frequency of the word\n#making the sorted vocabulary\nimport operator\nsorted_vocab = sorted(vocab.items(), key= operator.itemgetter(1), reverse= True) # sort the vocab based on frequency",
"_____no_output_____"
],
[
"#making the list feature_names containg the words with the frequency of the top 2000 words\nfeature_names = []\nfor i in range(len(sorted_vocab)):\n if(sorted_vocab[2000][1] <= sorted_vocab[i][1]):\n feature_names.append(sorted_vocab[i][0])",
"_____no_output_____"
],
[
"#length of the feature_names i.e. number of our features\nprint(len(feature_names))",
"2008\n"
],
[
"#making dataframes df_train and df_test with columns having the feature names i.e. the words\ndf_train=pd.DataFrame(columns=feature_names)\ndf_test=pd.DataFrame(columns=feature_names)",
"_____no_output_____"
],
[
"count_train,count_test=0,0\n\n#transforming each file in X_train into a row in the dataframe df_train having columns as feature names and values as the frequency of that feature name i.e that word\nfor filename in X_train:\n count_train+=1\n #adding a row of zeros for each file\n df_train.loc[len(df_train)]=np.zeros(len(feature_names))\n f = open(filename,'r',errors='ignore')\n record=f.read()\n words=record.split()\n #parsing through all the words of the file\n for word in words:\n if word.lower() in df_train.columns:\n df_train[word.lower()][len(df_train)-1]+=1 #if the word is in the column names then adding 1 to the frequency of that word in the row\n f.close()\n \n#transforming each file in X_test into a row in the dataframe df_test having columns as feature names and values as the frequency of that feature name i.e that word \nfor filename in X_test:\n count_test+=1\n #adding a row of zeros for each file\n df_test.loc[len(df_test)]=np.zeros(len(feature_names))\n f = open(filename,'r',errors='ignore')\n record=f.read()\n words=record.split()\n #parsing through all the words of the file\n for word in words:\n if word.lower() in df_test.columns:\n df_test[word.lower()][len(df_test)-1]+=1 #if the word is in the column names then adding 1 to the frequency of that word in the row\n f.close()\n \n#printing the number files tranformed in training and testing data\nprint(count_train,count_test)",
"14997 5000\n"
],
[
"#putting the values of the datafames into X_train and X_test\nX_train=df_train.values\nX_test=df_test.values",
"_____no_output_____"
]
],
[
[
"# **Using the inbuilt Multinomial Naive Bayes classifier from sklearn**",
"_____no_output_____"
]
],
[
[
"from sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import classification_report,confusion_matrix\nclf=MultinomialNB()\n#fitting the classifier on training data\nclf.fit(X_train,Y_train)\n#prediciting the classes of the testing data\nY_pred=clf.predict(X_test)\n#classification report\nprint(classification_report(Y_test,Y_pred))\n#testing score\nprint(\"Testing: \",clf.score(X_test,Y_test))",
" precision recall f1-score support\n\n 0 0.90 0.80 0.85 243\n 1 0.79 0.71 0.75 256\n 2 0.95 0.87 0.90 260\n 3 0.95 0.99 0.97 231\n 4 0.95 0.75 0.84 253\n 5 0.94 0.95 0.95 233\n 6 0.65 0.51 0.57 252\n 7 0.82 0.89 0.85 225\n 8 0.87 0.80 0.84 241\n 9 0.81 0.91 0.86 251\n 10 0.83 0.80 0.81 245\n 11 0.98 0.94 0.96 261\n 12 0.75 0.79 0.77 268\n 13 0.70 0.85 0.77 254\n 14 0.83 0.81 0.82 242\n 15 0.90 0.84 0.87 275\n 16 0.71 0.54 0.61 235\n 17 0.87 0.94 0.90 285\n 18 0.65 0.90 0.76 251\n 19 0.69 0.85 0.76 239\n\n micro avg 0.82 0.82 0.82 5000\n macro avg 0.83 0.82 0.82 5000\nweighted avg 0.83 0.82 0.82 5000\n\nTesting: 0.8216\n"
]
],
[
[
"# **Self implemented Multinomial Naive Bayes**",
"_____no_output_____"
]
],
[
[
"#makes the nested dictionary required for NB using the training data\ndef fit(X,Y):\n dictionary={}\n y_classes=set(Y)\n #iterating over each class of y\n for y_class in y_classes:\n #adding the class as a key to the dictionary\n dictionary[y_class]={}\n n_features=X.shape[1]\n rows=(Y==y_class)\n #making the arrays having only those rows where class is y_class\n X_y_class=X[rows]\n Y_y_class=Y[rows]\n #adding the total number of files as total_data\n dictionary[\"total_data\"]=X.shape[0]\n #iterating over each feature\n for i in range(n_features):\n #adding the feature as a key which has the count of that word in Y=y_class as its value\n dictionary[y_class][i]=X_y_class[:,i].sum()\n #adding the total number of files as total_class\n dictionary[y_class][\"total_class\"]=X_y_class.shape[0]\n #adding the sum of all the words in Y=y_class i.e. total no. of words in Y=y_class\n dictionary[y_class][\"total_words\"]=X_y_class.sum()\n return dictionary",
"_____no_output_____"
],
[
"#calculates the probability of the feature vector belonging to a particular class and the probability of the class\n#returns the product of the above 2 probabilities\ndef probability(x,dictionary,y_class):\n #output intially has probability of the particular class in log terms\n output=np.log(dictionary[y_class][\"total_class\"])-np.log(dictionary[\"total_data\"])\n n_features=len(dictionary[y_class].keys())-2\n #calculates probability of x being in a particular class by calulating probability of each word being in that class\n for i in range(n_features):\n if x[i]>0:\n #probability of the ith word being in this class in terms of log\n p_i=x[i]*(np.log(dictionary[y_class][i] + 1) - np.log(dictionary[y_class][\"total_words\"]+n_features))\n output+=p_i\n return output",
"_____no_output_____"
],
[
"#predicts the class to which a single file feature vector belongs to\ndef predictSinglePoint(x,dictionary):\n classes=dictionary.keys()\n #contains the class having the max probability\n best_class=1\n #max probability\n best_prob=-1000\n first=True\n #iterating over all the classes\n for y_class in classes:\n if y_class==\"total_data\":\n continue\n #finding probability of this file feature vector belonging to y_class\n p_class=probability(x,dictionary,y_class)\n if(first or p_class>best_prob):\n best_prob=p_class\n best_class=y_class\n first=False\n return best_class",
"_____no_output_____"
],
[
"#predicts the classes to which all the file feature vectors belong in the testing data\ndef predict(X_test,dictionary):\n y_pred=[]\n #iterates over all the file feature vectors\n for x in X_test:\n #predicts the class of a particular file feature vector\n x_class=predictSinglePoint(x,dictionary)\n y_pred.append(x_class)\n return y_pred",
"_____no_output_____"
],
[
"dictionary=fit(X_train,Y_train) #makes the required dictionary\ny_pred=predict(X_test,dictionary)# predicts the classes\nprint(classification_report(Y_test,y_pred)) #classification report for testing data",
" precision recall f1-score support\n\n 0 0.90 0.80 0.85 243\n 1 0.79 0.71 0.75 256\n 2 0.95 0.87 0.90 260\n 3 0.95 0.99 0.97 231\n 4 0.95 0.75 0.84 253\n 5 0.94 0.95 0.95 233\n 6 0.65 0.51 0.57 252\n 7 0.82 0.89 0.85 225\n 8 0.87 0.80 0.84 241\n 9 0.81 0.91 0.86 251\n 10 0.83 0.80 0.81 245\n 11 0.98 0.94 0.96 261\n 12 0.75 0.79 0.77 268\n 13 0.70 0.85 0.77 254\n 14 0.83 0.81 0.82 242\n 15 0.90 0.84 0.87 275\n 16 0.71 0.54 0.61 235\n 17 0.87 0.94 0.90 285\n 18 0.65 0.90 0.76 251\n 19 0.69 0.85 0.76 239\n\n micro avg 0.82 0.82 0.82 5000\n macro avg 0.83 0.82 0.82 5000\nweighted avg 0.83 0.82 0.82 5000\n\n"
]
],
[
[
"# **Comparison of results between inbuilt and self implemented Multinomial NB**",
"_____no_output_____"
]
],
[
[
"print(\"----------------------------------------------------------------------------\")\nprint(\"Classification report for inbuilt Multinomial NB on testing data: \")\nprint(\"----------------------------------------------------------------------------\")\nprint(classification_report(Y_test,Y_pred))\nprint(\"----------------------------------------------------------------------------\")\nprint(\"Classification report for self implemented Multinomial NB on testing data: \")\nprint(\"----------------------------------------------------------------------------\")\nprint(classification_report(Y_test,y_pred))",
"----------------------------------------------------------------------------\nClassification report for inbuilt Multinomial NB on testing data: \n----------------------------------------------------------------------------\n precision recall f1-score support\n\n 0 0.90 0.80 0.85 243\n 1 0.79 0.71 0.75 256\n 2 0.95 0.87 0.90 260\n 3 0.95 0.99 0.97 231\n 4 0.95 0.75 0.84 253\n 5 0.94 0.95 0.95 233\n 6 0.65 0.51 0.57 252\n 7 0.82 0.89 0.85 225\n 8 0.87 0.80 0.84 241\n 9 0.81 0.91 0.86 251\n 10 0.83 0.80 0.81 245\n 11 0.98 0.94 0.96 261\n 12 0.75 0.79 0.77 268\n 13 0.70 0.85 0.77 254\n 14 0.83 0.81 0.82 242\n 15 0.90 0.84 0.87 275\n 16 0.71 0.54 0.61 235\n 17 0.87 0.94 0.90 285\n 18 0.65 0.90 0.76 251\n 19 0.69 0.85 0.76 239\n\n micro avg 0.82 0.82 0.82 5000\n macro avg 0.83 0.82 0.82 5000\nweighted avg 0.83 0.82 0.82 5000\n\n----------------------------------------------------------------------------\nClassification report for self implemented Multinomial NB on testing data: \n----------------------------------------------------------------------------\n precision recall f1-score support\n\n 0 0.90 0.80 0.85 243\n 1 0.79 0.71 0.75 256\n 2 0.95 0.87 0.90 260\n 3 0.95 0.99 0.97 231\n 4 0.95 0.75 0.84 253\n 5 0.94 0.95 0.95 233\n 6 0.65 0.51 0.57 252\n 7 0.82 0.89 0.85 225\n 8 0.87 0.80 0.84 241\n 9 0.81 0.91 0.86 251\n 10 0.83 0.80 0.81 245\n 11 0.98 0.94 0.96 261\n 12 0.75 0.79 0.77 268\n 13 0.70 0.85 0.77 254\n 14 0.83 0.81 0.82 242\n 15 0.90 0.84 0.87 275\n 16 0.71 0.54 0.61 235\n 17 0.87 0.94 0.90 285\n 18 0.65 0.90 0.76 251\n 19 0.69 0.85 0.76 239\n\n micro avg 0.82 0.82 0.82 5000\n macro avg 0.83 0.82 0.82 5000\nweighted avg 0.83 0.82 0.82 5000\n\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a93073a5ad4552cae763e3d4d28935c251e7f35
| 6,897 |
ipynb
|
Jupyter Notebook
|
notebooks/ch08.ipynb
|
codingalzi/pyfast
|
bba69b83e554dde39869b91565807d69ce3d2e11
|
[
"MIT"
] | null | null | null |
notebooks/ch08.ipynb
|
codingalzi/pyfast
|
bba69b83e554dde39869b91565807d69ce3d2e11
|
[
"MIT"
] | null | null | null |
notebooks/ch08.ipynb
|
codingalzi/pyfast
|
bba69b83e554dde39869b91565807d69ce3d2e11
|
[
"MIT"
] | null | null | null | 25.928571 | 110 | 0.419313 |
[
[
[
"# 예외 처리",
"_____no_output_____"
],
[
"It is likely that you have raised Exceptions if you have\ntyped all the previous commands of the tutorial. For example, you may\nhave raised an exception if you entered a command with a typo.\n\nExceptions are raised by different kinds of errors arising when executing\nPython code. In your own code, you may also catch errors, or define custom\nerror types. You may want to look at the descriptions of the \n[the built-in Exceptions](https://docs.python.org/2/library/exceptions.html)\nwhen looking for the right exception type.",
"_____no_output_____"
],
[
"## Exceptions",
"_____no_output_____"
],
[
"Exceptions are raised by errors in Python:\n\n```python\nIn [1]: 1/0\n---------------------------------------------------------------------------\nZeroDivisionError: integer division or modulo by zero\n\nIn [2]: 1 + 'e'\n---------------------------------------------------------------------------\nTypeError: unsupported operand type(s) for +: 'int' and 'str'\n\nIn [3]: d = {1:1, 2:2}\n\nIn [4]: d[3]\n---------------------------------------------------------------------------\nKeyError: 3\n\nIn [5]: l = [1, 2, 3]\n\nIn [6]: l[4]\n---------------------------------------------------------------------------\nIndexError: list index out of range\n\nIn [7]: l.foobar\n---------------------------------------------------------------------------\nAttributeError: 'list' object has no attribute 'foobar'\n```",
"_____no_output_____"
],
[
"As you can see, there are **different types** of exceptions for different errors.",
"_____no_output_____"
],
[
"## Catching exceptions",
"_____no_output_____"
],
[
"### try/except",
"_____no_output_____"
],
[
"```python\nIn [10]: while True:\n ....: try:\n ....: x = int(raw_input('Please enter a number: '))\n ....: break\n ....: except ValueError:\n ....: print('That was no valid number. Try again...')\n ....: \nPlease enter a number: a\nThat was no valid number. Try again...\nPlease enter a number: 1\n\nIn [9]: x\nOut[9]: 1\n```python",
"_____no_output_____"
],
[
"### try/finally",
"_____no_output_____"
],
[
"```python\nIn [10]: try:\n ....: x = int(raw_input('Please enter a number: '))\n ....: finally:\n ....: print('Thank you for your input')\n ....:\n ....:\nPlease enter a number: a\nThank you for your input\n---------------------------------------------------------------------------\nValueError: invalid literal for int() with base 10: 'a'\n```",
"_____no_output_____"
],
[
"Important for resource management (e.g. closing a file)",
"_____no_output_____"
],
[
"### Easier to ask for forgiveness than for permission",
"_____no_output_____"
],
[
"```python\nIn [11]: def print_sorted(collection):\n ....: try:\n ....: collection.sort()\n ....: except AttributeError:\n ....: pass # The pass statement does nothing\n ....: print(collection)\n ....:\n ....:\n\nIn [12]: print_sorted([1, 3, 2])\n[1, 2, 3]\n\nIn [13]: print_sorted(set((1, 3, 2)))\nset([1, 2, 3])\n\nIn [14]: print_sorted('132')\n132\n```",
"_____no_output_____"
],
[
"## Raising exceptions",
"_____no_output_____"
],
[
"* Capturing and reraising an exception:\n\n ```python\n In [15]: def filter_name(name):\n ....:\ttry:\n ....:\t name = name.encode('ascii')\n ....:\texcept UnicodeError as e:\n ....:\t if name == 'Gaël':\n ....:\t\tprint('OK, Gaël')\n ....:\t else:\n ....:\t\traise e\n ....:\treturn name\n ....:\n\n In [16]: filter_name('Gaël')\n OK, Gaël\n Out[16]: 'Ga\\xc3\\xabl'\n\n In [17]: filter_name('Stéfan')\n ---------------------------------------------------------------------------\n UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)\n ```",
"_____no_output_____"
],
[
"* Exceptions to pass messages between parts of the code:\n\n ```python\n In [17]: def achilles_arrow(x):\n ....: if abs(x - 1) < 1e-3:\n ....: raise StopIteration\n ....: x = 1 - (1-x)/2.\n ....: return x\n ....:\n\n In [18]: x = 0\n\n In [19]: while True:\n ....: try:\n ....: x = achilles_arrow(x)\n ....: except StopIteration:\n ....: break\n ....:\n ....:\n\n In [20]: x\n Out[20]: 0.9990234375\n ```",
"_____no_output_____"
],
[
"Use exceptions to notify certain conditions are met (e.g.\nStopIteration) or not (e.g. custom error raising)",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4a930ee7f52b4fc6ede75dd8e7d0b13a400d0b1c
| 227,513 |
ipynb
|
Jupyter Notebook
|
Machine_Learning_Clustering_ and_ Retrieval/1_nearest-neighbors-lsh-implementation_blank.ipynb
|
nkmah2/ML_Uni_Washington_Coursera
|
a5852f1716189a1126919b12d767f894ad8490ac
|
[
"MIT"
] | null | null | null |
Machine_Learning_Clustering_ and_ Retrieval/1_nearest-neighbors-lsh-implementation_blank.ipynb
|
nkmah2/ML_Uni_Washington_Coursera
|
a5852f1716189a1126919b12d767f894ad8490ac
|
[
"MIT"
] | null | null | null |
Machine_Learning_Clustering_ and_ Retrieval/1_nearest-neighbors-lsh-implementation_blank.ipynb
|
nkmah2/ML_Uni_Washington_Coursera
|
a5852f1716189a1126919b12d767f894ad8490ac
|
[
"MIT"
] | null | null | null | 67.651799 | 44,922 | 0.676713 |
[
[
[
"# Locality Sensitive Hashing",
"_____no_output_____"
],
[
"Locality Sensitive Hashing (LSH) provides for a fast, efficient approximate nearest neighbor search. The algorithm scales well with respect to the number of data points as well as dimensions.\n\nIn this assignment, you will\n* Implement the LSH algorithm for approximate nearest neighbor search\n* Examine the accuracy for different documents by comparing against brute force search, and also contrast runtimes\n* Explore the role of the algorithm’s tuning parameters in the accuracy of the method",
"_____no_output_____"
],
[
"**Note to Amazon EC2 users**: To conserve memory, make sure to stop all the other notebooks before running this notebook.",
"_____no_output_____"
],
[
"## Import necessary packages",
"_____no_output_____"
],
[
"The following code block will check if you have the correct version of GraphLab Create. Any version later than 1.8.5 will do. To upgrade, read [this page](https://turi.com/download/upgrade-graphlab-create.html).",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport graphlab\nfrom scipy.sparse import csr_matrix\nfrom sklearn.metrics.pairwise import pairwise_distances\nimport time\nfrom copy import copy\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n'''Check GraphLab Create version'''\nfrom distutils.version import StrictVersion\nassert (StrictVersion(graphlab.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.'\n\n'''compute norm of a sparse vector\n Thanks to: Jaiyam Sharma'''\ndef norm(x):\n sum_sq=x.dot(x.T)\n norm=np.sqrt(sum_sq)\n return(norm)",
"[INFO] graphlab.cython.cy_server: GraphLab Create v2.1 started. Logging: /tmp/graphlab_server_1482000195.log\nINFO:graphlab.cython.cy_server:GraphLab Create v2.1 started. Logging: /tmp/graphlab_server_1482000195.log\n"
]
],
[
[
"## Load in the Wikipedia dataset",
"_____no_output_____"
]
],
[
[
"wiki = graphlab.SFrame('people_wiki.gl/')\nwiki",
"_____no_output_____"
]
],
[
[
"For this assignment, let us assign a unique ID to each document.",
"_____no_output_____"
]
],
[
[
"wiki = wiki.add_row_number()\nwiki",
"_____no_output_____"
]
],
[
[
"## Extract TF-IDF matrix",
"_____no_output_____"
],
[
"We first use GraphLab Create to compute a TF-IDF representation for each document.",
"_____no_output_____"
]
],
[
[
"wiki['tf_idf'] = graphlab.text_analytics.tf_idf(wiki['text'])\nwiki",
"_____no_output_____"
]
],
[
[
"For the remainder of the assignment, we will use sparse matrices. Sparse matrices are [matrices](https://en.wikipedia.org/wiki/Matrix_(mathematics%29 ) that have a small number of nonzero entries. A good data structure for sparse matrices would only store the nonzero entries to save space and speed up computation. SciPy provides a highly-optimized library for sparse matrices. Many matrix operations available for NumPy arrays are also available for SciPy sparse matrices.\n\nWe first convert the TF-IDF column (in dictionary format) into the SciPy sparse matrix format.",
"_____no_output_____"
]
],
[
[
"def sframe_to_scipy(column):\n \"\"\" \n Convert a dict-typed SArray into a SciPy sparse matrix.\n \n Returns\n -------\n mat : a SciPy sparse matrix where mat[i, j] is the value of word j for document i.\n mapping : a dictionary where mapping[j] is the word whose values are in column j.\n \"\"\"\n # Create triples of (row_id, feature_id, count).\n x = graphlab.SFrame({'X1':column})\n \n # 1. Add a row number.\n x = x.add_row_number()\n # 2. Stack will transform x to have a row for each unique (row, key) pair.\n x = x.stack('X1', ['feature', 'value'])\n\n # Map words into integers using a OneHotEncoder feature transformation.\n f = graphlab.feature_engineering.OneHotEncoder(features=['feature'])\n\n # We first fit the transformer using the above data.\n f.fit(x)\n\n # The transform method will add a new column that is the transformed version\n # of the 'word' column.\n x = f.transform(x)\n\n # Get the feature mapping.\n mapping = f['feature_encoding']\n\n # Get the actual word id.\n x['feature_id'] = x['encoded_features'].dict_keys().apply(lambda x: x[0])\n\n # Create numpy arrays that contain the data for the sparse matrix.\n i = np.array(x['id'])\n j = np.array(x['feature_id'])\n v = np.array(x['value'])\n width = x['id'].max() + 1\n height = x['feature_id'].max() + 1\n\n # Create a sparse matrix.\n mat = csr_matrix((v, (i, j)), shape=(width, height))\n\n return mat, mapping",
"_____no_output_____"
]
],
[
[
"The conversion should take a few minutes to complete.",
"_____no_output_____"
]
],
[
[
"start=time.time()\ncorpus, mapping = sframe_to_scipy(wiki['tf_idf'])\nend=time.time()\nprint end-start",
"37.2376871109\n"
]
],
[
[
"**Checkpoint**: The following code block should return 'Check passed correctly', indicating that your matrix contains TF-IDF values for 59071 documents and 547979 unique words. Otherwise, it will return Error.",
"_____no_output_____"
]
],
[
[
"assert corpus.shape == (59071, 547979)\nprint 'Check passed correctly!'",
"Check passed correctly!\n"
]
],
[
[
"## Train an LSH model",
"_____no_output_____"
],
[
"LSH performs an efficient neighbor search by randomly partitioning all reference data points into different bins. Today we will build a popular variant of LSH known as random binary projection, which approximates cosine distance. There are other variants we could use for other choices of distance metrics.\n\nThe first step is to generate a collection of random vectors from the standard Gaussian distribution.",
"_____no_output_____"
]
],
[
[
"def generate_random_vectors(num_vector, dim):\n return np.random.randn(dim, num_vector)",
"_____no_output_____"
]
],
[
[
"To visualize these Gaussian random vectors, let's look at an example in low-dimensions. Below, we generate 3 random vectors each of dimension 5.",
"_____no_output_____"
]
],
[
[
"# Generate 3 random vectors of dimension 5, arranged into a single 5 x 3 matrix.\nnp.random.seed(0) # set seed=0 for consistent results\ngenerate_random_vectors(num_vector=3, dim=5)",
"_____no_output_____"
]
],
[
[
"We now generate random vectors of the same dimensionality as our vocubulary size (547979). Each vector can be used to compute one bit in the bin encoding. We generate 16 vectors, leading to a 16-bit encoding of the bin index for each document.",
"_____no_output_____"
]
],
[
[
"# Generate 16 random vectors of dimension 547979\nnp.random.seed(0)\nrandom_vectors = generate_random_vectors(num_vector=16, dim=547979)\nrandom_vectors.shape",
"_____no_output_____"
]
],
[
[
"Next, we partition data points into bins. Instead of using explicit loops, we'd like to utilize matrix operations for greater efficiency. Let's walk through the construction step by step.\n\nWe'd like to decide which bin document 0 should go. Since 16 random vectors were generated in the previous cell, we have 16 bits to represent the bin index. The first bit is given by the sign of the dot product between the first random vector and the document's TF-IDF vector.",
"_____no_output_____"
]
],
[
[
"doc = corpus[0, :] # vector of tf-idf values for document 0\ndoc.dot(random_vectors[:, 0]) >= 0 # True if positive sign; False if negative sign",
"_____no_output_____"
]
],
[
[
"Similarly, the second bit is computed as the sign of the dot product between the second random vector and the document vector.",
"_____no_output_____"
]
],
[
[
"doc.dot(random_vectors[:, 1]) >= 0 # True if positive sign; False if negative sign",
"_____no_output_____"
]
],
[
[
"We can compute all of the bin index bits at once as follows. Note the absence of the explicit `for` loop over the 16 vectors. Matrix operations let us batch dot-product computation in a highly efficent manner, unlike the `for` loop construction. Given the relative inefficiency of loops in Python, the advantage of matrix operations is even greater.",
"_____no_output_____"
]
],
[
[
"doc.dot(random_vectors) >= 0 # should return an array of 16 True/False bits",
"_____no_output_____"
],
[
"np.array(doc.dot(random_vectors) >= 0, dtype=int) # display index bits in 0/1's",
"_____no_output_____"
]
],
[
[
"All documents that obtain exactly this vector will be assigned to the same bin. We'd like to repeat the identical operation on all documents in the Wikipedia dataset and compute the corresponding bin indices. Again, we use matrix operations so that no explicit loop is needed.",
"_____no_output_____"
]
],
[
[
"corpus[0:2].dot(random_vectors) >= 0 # compute bit indices of first two documents",
"_____no_output_____"
],
[
"corpus.dot(random_vectors) >= 0 # compute bit indices of ALL documents",
"_____no_output_____"
]
],
[
[
"We're almost done! To make it convenient to refer to individual bins, we convert each binary bin index into a single integer: \n```\nBin index integer\n[0,0,0,0,0,0,0,0,0,0,0,0] => 0\n[0,0,0,0,0,0,0,0,0,0,0,1] => 1\n[0,0,0,0,0,0,0,0,0,0,1,0] => 2\n[0,0,0,0,0,0,0,0,0,0,1,1] => 3\n...\n[1,1,1,1,1,1,1,1,1,1,0,0] => 65532\n[1,1,1,1,1,1,1,1,1,1,0,1] => 65533\n[1,1,1,1,1,1,1,1,1,1,1,0] => 65534\n[1,1,1,1,1,1,1,1,1,1,1,1] => 65535 (= 2^16-1)\n```\nBy the [rules of binary number representation](https://en.wikipedia.org/wiki/Binary_number#Decimal), we just need to compute the dot product between the document vector and the vector consisting of powers of 2:",
"_____no_output_____"
]
],
[
[
"doc = corpus[0, :] # first document\nindex_bits = (doc.dot(random_vectors) >= 0)\npowers_of_two = (1 << np.arange(15, -1, -1))\nprint index_bits\nprint powers_of_two\nprint index_bits.dot(powers_of_two)",
"[[ True True False False False True True False True True True False\n False True False True]]\n[32768 16384 8192 4096 2048 1024 512 256 128 64 32 16\n 8 4 2 1]\n[50917]\n"
]
],
[
[
"Since it's the dot product again, we batch it with a matrix operation:",
"_____no_output_____"
]
],
[
[
"index_bits = corpus.dot(random_vectors) >= 0\nindex_bits.dot(powers_of_two)",
"_____no_output_____"
]
],
[
[
"This array gives us the integer index of the bins for all documents.\n\nNow we are ready to complete the following function. Given the integer bin indices for the documents, you should compile a list of document IDs that belong to each bin. Since a list is to be maintained for each unique bin index, a dictionary of lists is used.\n\n1. Compute the integer bin indices. This step is already completed.\n2. For each document in the dataset, do the following:\n * Get the integer bin index for the document.\n * Fetch the list of document ids associated with the bin; if no list yet exists for this bin, assign the bin an empty list.\n * Add the document id to the end of the list.\n",
"_____no_output_____"
]
],
[
[
"def train_lsh(data, num_vector=16, seed=None):\n \n dim = data.shape[1]\n if seed is not None:\n np.random.seed(seed)\n random_vectors = generate_random_vectors(num_vector, dim)\n \n powers_of_two = 1 << np.arange(num_vector-1, -1, -1)\n \n table = {}\n \n # Partition data points into bins\n bin_index_bits = (data.dot(random_vectors) >= 0)\n \n # Encode bin index bits into integers\n bin_indices = bin_index_bits.dot(powers_of_two)\n \n # Update `table` so that `table[i]` is the list of document ids with bin index equal to i.\n for data_index, bin_index in enumerate(bin_indices):\n if bin_index not in table:\n # If no list yet exists for this bin, assign the bin an empty list.\n table[bin_index] = [] # YOUR CODE HERE\n # Fetch the list of document ids associated with the bin and add the document id to the end.\n table[bin_index] = table[bin_index]+[data_index] # YOUR CODE HERE\n\n model = {'data': data,\n 'bin_index_bits': bin_index_bits,\n 'bin_indices': bin_indices,\n 'table': table,\n 'random_vectors': random_vectors,\n 'num_vector': num_vector}\n \n return model",
"_____no_output_____"
]
],
[
[
"**Checkpoint**. ",
"_____no_output_____"
]
],
[
[
"model = train_lsh(corpus, num_vector=16, seed=143)\ntable = model['table']\nif 0 in table and table[0] == [39583] and \\\n 143 in table and table[143] == [19693, 28277, 29776, 30399]:\n print 'Passed!'\nelse:\n print 'Check your code.'",
"Passed!\n"
]
],
[
[
"**Note.** We will be using the model trained here in the following sections, unless otherwise indicated.",
"_____no_output_____"
],
[
"## Inspect bins",
"_____no_output_____"
],
[
"Let us look at some documents and see which bins they fall into.",
"_____no_output_____"
]
],
[
[
"wiki[wiki['name'] == 'Barack Obama']",
"_____no_output_____"
]
],
[
[
"**Quiz Question**. What is the document `id` of Barack Obama's article?\n\n**Quiz Question**. Which bin contains Barack Obama's article? Enter its integer index.",
"_____no_output_____"
]
],
[
[
"obama_l =index_bits[35817]\nprint obama_l.dot(powers_of_two)",
"29090\n"
]
],
[
[
"Recall from the previous assignment that Joe Biden was a close neighbor of Barack Obama.",
"_____no_output_____"
]
],
[
[
"wiki[wiki['name'] == 'Joe Biden']",
"_____no_output_____"
]
],
[
[
"**Quiz Question**. Examine the bit representations of the bins containing Barack Obama and Joe Biden. In how many places do they agree?\n\n1. 16 out of 16 places (Barack Obama and Joe Biden fall into the same bin)\n2. 14 out of 16 places\n3. 12 out of 16 places\n4. 10 out of 16 places\n5. 8 out of 16 places",
"_____no_output_____"
]
],
[
[
"print np.array(model['bin_index_bits'][35817], dtype=int) # list of 0/1's\nprint np.array(model['bin_index_bits'][24478], dtype=int) # list of 0/1's",
"[1 1 0 0 0 1 0 0 0 0 0 1 0 0 1 0]\n[1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0]\n"
],
[
"model['bin_index_bits'][35817] == model['bin_index_bits'][24478]",
"_____no_output_____"
]
],
[
[
"Compare the result with a former British diplomat, whose bin representation agrees with Obama's in only 8 out of 16 places.",
"_____no_output_____"
]
],
[
[
"wiki[wiki['name']=='Wynn Normington Hugh-Jones']",
"_____no_output_____"
],
[
"print np.array(model['bin_index_bits'][22745], dtype=int) # list of 0/1's\nprint model['bin_indices'][22745] # integer format\nmodel['bin_index_bits'][35817] == model['bin_index_bits'][22745]",
"[0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0]\n4660\n"
]
],
[
[
"How about the documents in the same bin as Barack Obama? Are they necessarily more similar to Obama than Biden? Let's look at which documents are in the same bin as the Barack Obama article.",
"_____no_output_____"
]
],
[
[
"model['table'][model['bin_indices'][35817]]",
"_____no_output_____"
]
],
[
[
"There are four other documents that belong to the same bin. Which documents are they?",
"_____no_output_____"
]
],
[
[
"doc_ids = list(model['table'][model['bin_indices'][35817]])\ndoc_ids.remove(35817) # display documents other than Obama\n\ndocs = wiki.filter_by(values=doc_ids, column_name='id') # filter by id column\ndocs",
"_____no_output_____"
]
],
[
[
"It turns out that Joe Biden is much closer to Barack Obama than any of the four documents, even though Biden's bin representation differs from Obama's by 2 bits.",
"_____no_output_____"
]
],
[
[
"def cosine_distance(x, y):\n xy = x.dot(y.T)\n dist = xy/(norm(x)*norm(y))\n return 1-dist[0,0]\n\nobama_tf_idf = corpus[35817,:]\nbiden_tf_idf = corpus[24478,:]\n\nprint '================= Cosine distance from Barack Obama'\nprint 'Barack Obama - {0:24s}: {1:f}'.format('Joe Biden',\n cosine_distance(obama_tf_idf, biden_tf_idf))\nfor doc_id in doc_ids:\n doc_tf_idf = corpus[doc_id,:]\n print 'Barack Obama - {0:24s}: {1:f}'.format(wiki[doc_id]['name'],\n cosine_distance(obama_tf_idf, doc_tf_idf))",
"================= Cosine distance from Barack Obama\nBarack Obama - Joe Biden : 0.703139\nBarack Obama - Mark Boulware : 0.950867\nBarack Obama - John Wells (politician) : 0.975966\nBarack Obama - Francis Longstaff : 0.978256\nBarack Obama - Madurai T. Srinivasan : 0.993092\n"
]
],
[
[
"**Moral of the story**. Similar data points will in general _tend to_ fall into _nearby_ bins, but that's all we can say about LSH. In a high-dimensional space such as text features, we often get unlucky with our selection of only a few random vectors such that dissimilar data points go into the same bin while similar data points fall into different bins. **Given a query document, we must consider all documents in the nearby bins and sort them according to their actual distances from the query.**",
"_____no_output_____"
],
[
"## Query the LSH model",
"_____no_output_____"
],
[
"Let us first implement the logic for searching nearby neighbors, which goes like this:\n```\n1. Let L be the bit representation of the bin that contains the query documents.\n2. Consider all documents in bin L.\n3. Consider documents in the bins whose bit representation differs from L by 1 bit.\n4. Consider documents in the bins whose bit representation differs from L by 2 bits.\n...\n```",
"_____no_output_____"
],
[
"To obtain candidate bins that differ from the query bin by some number of bits, we use `itertools.combinations`, which produces all possible subsets of a given list. See [this documentation](https://docs.python.org/3/library/itertools.html#itertools.combinations) for details.\n```\n1. Decide on the search radius r. This will determine the number of different bits between the two vectors.\n2. For each subset (n_1, n_2, ..., n_r) of the list [0, 1, 2, ..., num_vector-1], do the following:\n * Flip the bits (n_1, n_2, ..., n_r) of the query bin to produce a new bit vector.\n * Fetch the list of documents belonging to the bin indexed by the new bit vector.\n * Add those documents to the candidate set.\n```\n\nEach line of output from the following cell is a 3-tuple indicating where the candidate bin would differ from the query bin. For instance,\n```\n(0, 1, 3)\n```\nindicates that the candiate bin differs from the query bin in first, second, and fourth bits.",
"_____no_output_____"
]
],
[
[
"from itertools import combinations",
"_____no_output_____"
],
[
"num_vector = 16\nsearch_radius = 3\n\nfor diff in combinations(range(num_vector), search_radius):\n print diff",
"(0, 1, 2)\n(0, 1, 3)\n(0, 1, 4)\n(0, 1, 5)\n(0, 1, 6)\n(0, 1, 7)\n(0, 1, 8)\n(0, 1, 9)\n(0, 1, 10)\n(0, 1, 11)\n(0, 1, 12)\n(0, 1, 13)\n(0, 1, 14)\n(0, 1, 15)\n(0, 2, 3)\n(0, 2, 4)\n(0, 2, 5)\n(0, 2, 6)\n(0, 2, 7)\n(0, 2, 8)\n(0, 2, 9)\n(0, 2, 10)\n(0, 2, 11)\n(0, 2, 12)\n(0, 2, 13)\n(0, 2, 14)\n(0, 2, 15)\n(0, 3, 4)\n(0, 3, 5)\n(0, 3, 6)\n(0, 3, 7)\n(0, 3, 8)\n(0, 3, 9)\n(0, 3, 10)\n(0, 3, 11)\n(0, 3, 12)\n(0, 3, 13)\n(0, 3, 14)\n(0, 3, 15)\n(0, 4, 5)\n(0, 4, 6)\n(0, 4, 7)\n(0, 4, 8)\n(0, 4, 9)\n(0, 4, 10)\n(0, 4, 11)\n(0, 4, 12)\n(0, 4, 13)\n(0, 4, 14)\n(0, 4, 15)\n(0, 5, 6)\n(0, 5, 7)\n(0, 5, 8)\n(0, 5, 9)\n(0, 5, 10)\n(0, 5, 11)\n(0, 5, 12)\n(0, 5, 13)\n(0, 5, 14)\n(0, 5, 15)\n(0, 6, 7)\n(0, 6, 8)\n(0, 6, 9)\n(0, 6, 10)\n(0, 6, 11)\n(0, 6, 12)\n(0, 6, 13)\n(0, 6, 14)\n(0, 6, 15)\n(0, 7, 8)\n(0, 7, 9)\n(0, 7, 10)\n(0, 7, 11)\n(0, 7, 12)\n(0, 7, 13)\n(0, 7, 14)\n(0, 7, 15)\n(0, 8, 9)\n(0, 8, 10)\n(0, 8, 11)\n(0, 8, 12)\n(0, 8, 13)\n(0, 8, 14)\n(0, 8, 15)\n(0, 9, 10)\n(0, 9, 11)\n(0, 9, 12)\n(0, 9, 13)\n(0, 9, 14)\n(0, 9, 15)\n(0, 10, 11)\n(0, 10, 12)\n(0, 10, 13)\n(0, 10, 14)\n(0, 10, 15)\n(0, 11, 12)\n(0, 11, 13)\n(0, 11, 14)\n(0, 11, 15)\n(0, 12, 13)\n(0, 12, 14)\n(0, 12, 15)\n(0, 13, 14)\n(0, 13, 15)\n(0, 14, 15)\n(1, 2, 3)\n(1, 2, 4)\n(1, 2, 5)\n(1, 2, 6)\n(1, 2, 7)\n(1, 2, 8)\n(1, 2, 9)\n(1, 2, 10)\n(1, 2, 11)\n(1, 2, 12)\n(1, 2, 13)\n(1, 2, 14)\n(1, 2, 15)\n(1, 3, 4)\n(1, 3, 5)\n(1, 3, 6)\n(1, 3, 7)\n(1, 3, 8)\n(1, 3, 9)\n(1, 3, 10)\n(1, 3, 11)\n(1, 3, 12)\n(1, 3, 13)\n(1, 3, 14)\n(1, 3, 15)\n(1, 4, 5)\n(1, 4, 6)\n(1, 4, 7)\n(1, 4, 8)\n(1, 4, 9)\n(1, 4, 10)\n(1, 4, 11)\n(1, 4, 12)\n(1, 4, 13)\n(1, 4, 14)\n(1, 4, 15)\n(1, 5, 6)\n(1, 5, 7)\n(1, 5, 8)\n(1, 5, 9)\n(1, 5, 10)\n(1, 5, 11)\n(1, 5, 12)\n(1, 5, 13)\n(1, 5, 14)\n(1, 5, 15)\n(1, 6, 7)\n(1, 6, 8)\n(1, 6, 9)\n(1, 6, 10)\n(1, 6, 11)\n(1, 6, 12)\n(1, 6, 13)\n(1, 6, 14)\n(1, 6, 15)\n(1, 7, 8)\n(1, 7, 9)\n(1, 7, 10)\n(1, 7, 11)\n(1, 7, 12)\n(1, 7, 13)\n(1, 7, 14)\n(1, 7, 15)\n(1, 8, 9)\n(1, 8, 10)\n(1, 8, 11)\n(1, 8, 12)\n(1, 8, 13)\n(1, 8, 14)\n(1, 8, 15)\n(1, 9, 10)\n(1, 9, 11)\n(1, 9, 12)\n(1, 9, 13)\n(1, 9, 14)\n(1, 9, 15)\n(1, 10, 11)\n(1, 10, 12)\n(1, 10, 13)\n(1, 10, 14)\n(1, 10, 15)\n(1, 11, 12)\n(1, 11, 13)\n(1, 11, 14)\n(1, 11, 15)\n(1, 12, 13)\n(1, 12, 14)\n(1, 12, 15)\n(1, 13, 14)\n(1, 13, 15)\n(1, 14, 15)\n(2, 3, 4)\n(2, 3, 5)\n(2, 3, 6)\n(2, 3, 7)\n(2, 3, 8)\n(2, 3, 9)\n(2, 3, 10)\n(2, 3, 11)\n(2, 3, 12)\n(2, 3, 13)\n(2, 3, 14)\n(2, 3, 15)\n(2, 4, 5)\n(2, 4, 6)\n(2, 4, 7)\n(2, 4, 8)\n(2, 4, 9)\n(2, 4, 10)\n(2, 4, 11)\n(2, 4, 12)\n(2, 4, 13)\n(2, 4, 14)\n(2, 4, 15)\n(2, 5, 6)\n(2, 5, 7)\n(2, 5, 8)\n(2, 5, 9)\n(2, 5, 10)\n(2, 5, 11)\n(2, 5, 12)\n(2, 5, 13)\n(2, 5, 14)\n(2, 5, 15)\n(2, 6, 7)\n(2, 6, 8)\n(2, 6, 9)\n(2, 6, 10)\n(2, 6, 11)\n(2, 6, 12)\n(2, 6, 13)\n(2, 6, 14)\n(2, 6, 15)\n(2, 7, 8)\n(2, 7, 9)\n(2, 7, 10)\n(2, 7, 11)\n(2, 7, 12)\n(2, 7, 13)\n(2, 7, 14)\n(2, 7, 15)\n(2, 8, 9)\n(2, 8, 10)\n(2, 8, 11)\n(2, 8, 12)\n(2, 8, 13)\n(2, 8, 14)\n(2, 8, 15)\n(2, 9, 10)\n(2, 9, 11)\n(2, 9, 12)\n(2, 9, 13)\n(2, 9, 14)\n(2, 9, 15)\n(2, 10, 11)\n(2, 10, 12)\n(2, 10, 13)\n(2, 10, 14)\n(2, 10, 15)\n(2, 11, 12)\n(2, 11, 13)\n(2, 11, 14)\n(2, 11, 15)\n(2, 12, 13)\n(2, 12, 14)\n(2, 12, 15)\n(2, 13, 14)\n(2, 13, 15)\n(2, 14, 15)\n(3, 4, 5)\n(3, 4, 6)\n(3, 4, 7)\n(3, 4, 8)\n(3, 4, 9)\n(3, 4, 10)\n(3, 4, 11)\n(3, 4, 12)\n(3, 4, 13)\n(3, 4, 14)\n(3, 4, 15)\n(3, 5, 6)\n(3, 5, 7)\n(3, 5, 8)\n(3, 5, 9)\n(3, 5, 10)\n(3, 5, 11)\n(3, 5, 12)\n(3, 5, 13)\n(3, 5, 14)\n(3, 5, 15)\n(3, 6, 7)\n(3, 6, 8)\n(3, 6, 9)\n(3, 6, 10)\n(3, 6, 11)\n(3, 6, 12)\n(3, 6, 13)\n(3, 6, 14)\n(3, 6, 15)\n(3, 7, 8)\n(3, 7, 9)\n(3, 7, 10)\n(3, 7, 11)\n(3, 7, 12)\n(3, 7, 13)\n(3, 7, 14)\n(3, 7, 15)\n(3, 8, 9)\n(3, 8, 10)\n(3, 8, 11)\n(3, 8, 12)\n(3, 8, 13)\n(3, 8, 14)\n(3, 8, 15)\n(3, 9, 10)\n(3, 9, 11)\n(3, 9, 12)\n(3, 9, 13)\n(3, 9, 14)\n(3, 9, 15)\n(3, 10, 11)\n(3, 10, 12)\n(3, 10, 13)\n(3, 10, 14)\n(3, 10, 15)\n(3, 11, 12)\n(3, 11, 13)\n(3, 11, 14)\n(3, 11, 15)\n(3, 12, 13)\n(3, 12, 14)\n(3, 12, 15)\n(3, 13, 14)\n(3, 13, 15)\n(3, 14, 15)\n(4, 5, 6)\n(4, 5, 7)\n(4, 5, 8)\n(4, 5, 9)\n(4, 5, 10)\n(4, 5, 11)\n(4, 5, 12)\n(4, 5, 13)\n(4, 5, 14)\n(4, 5, 15)\n(4, 6, 7)\n(4, 6, 8)\n(4, 6, 9)\n(4, 6, 10)\n(4, 6, 11)\n(4, 6, 12)\n(4, 6, 13)\n(4, 6, 14)\n(4, 6, 15)\n(4, 7, 8)\n(4, 7, 9)\n(4, 7, 10)\n(4, 7, 11)\n(4, 7, 12)\n(4, 7, 13)\n(4, 7, 14)\n(4, 7, 15)\n(4, 8, 9)\n(4, 8, 10)\n(4, 8, 11)\n(4, 8, 12)\n(4, 8, 13)\n(4, 8, 14)\n(4, 8, 15)\n(4, 9, 10)\n(4, 9, 11)\n(4, 9, 12)\n(4, 9, 13)\n(4, 9, 14)\n(4, 9, 15)\n(4, 10, 11)\n(4, 10, 12)\n(4, 10, 13)\n(4, 10, 14)\n(4, 10, 15)\n(4, 11, 12)\n(4, 11, 13)\n(4, 11, 14)\n(4, 11, 15)\n(4, 12, 13)\n(4, 12, 14)\n(4, 12, 15)\n(4, 13, 14)\n(4, 13, 15)\n(4, 14, 15)\n(5, 6, 7)\n(5, 6, 8)\n(5, 6, 9)\n(5, 6, 10)\n(5, 6, 11)\n(5, 6, 12)\n(5, 6, 13)\n(5, 6, 14)\n(5, 6, 15)\n(5, 7, 8)\n(5, 7, 9)\n(5, 7, 10)\n(5, 7, 11)\n(5, 7, 12)\n(5, 7, 13)\n(5, 7, 14)\n(5, 7, 15)\n(5, 8, 9)\n(5, 8, 10)\n(5, 8, 11)\n(5, 8, 12)\n(5, 8, 13)\n(5, 8, 14)\n(5, 8, 15)\n(5, 9, 10)\n(5, 9, 11)\n(5, 9, 12)\n(5, 9, 13)\n(5, 9, 14)\n(5, 9, 15)\n(5, 10, 11)\n(5, 10, 12)\n(5, 10, 13)\n(5, 10, 14)\n(5, 10, 15)\n(5, 11, 12)\n(5, 11, 13)\n(5, 11, 14)\n(5, 11, 15)\n(5, 12, 13)\n(5, 12, 14)\n(5, 12, 15)\n(5, 13, 14)\n(5, 13, 15)\n(5, 14, 15)\n(6, 7, 8)\n(6, 7, 9)\n(6, 7, 10)\n(6, 7, 11)\n(6, 7, 12)\n(6, 7, 13)\n(6, 7, 14)\n(6, 7, 15)\n(6, 8, 9)\n(6, 8, 10)\n(6, 8, 11)\n(6, 8, 12)\n(6, 8, 13)\n(6, 8, 14)\n(6, 8, 15)\n(6, 9, 10)\n(6, 9, 11)\n(6, 9, 12)\n(6, 9, 13)\n(6, 9, 14)\n(6, 9, 15)\n(6, 10, 11)\n(6, 10, 12)\n(6, 10, 13)\n(6, 10, 14)\n(6, 10, 15)\n(6, 11, 12)\n(6, 11, 13)\n(6, 11, 14)\n(6, 11, 15)\n(6, 12, 13)\n(6, 12, 14)\n(6, 12, 15)\n(6, 13, 14)\n(6, 13, 15)\n(6, 14, 15)\n(7, 8, 9)\n(7, 8, 10)\n(7, 8, 11)\n(7, 8, 12)\n(7, 8, 13)\n(7, 8, 14)\n(7, 8, 15)\n(7, 9, 10)\n(7, 9, 11)\n(7, 9, 12)\n(7, 9, 13)\n(7, 9, 14)\n(7, 9, 15)\n(7, 10, 11)\n(7, 10, 12)\n(7, 10, 13)\n(7, 10, 14)\n(7, 10, 15)\n(7, 11, 12)\n(7, 11, 13)\n(7, 11, 14)\n(7, 11, 15)\n(7, 12, 13)\n(7, 12, 14)\n(7, 12, 15)\n(7, 13, 14)\n(7, 13, 15)\n(7, 14, 15)\n(8, 9, 10)\n(8, 9, 11)\n(8, 9, 12)\n(8, 9, 13)\n(8, 9, 14)\n(8, 9, 15)\n(8, 10, 11)\n(8, 10, 12)\n(8, 10, 13)\n(8, 10, 14)\n(8, 10, 15)\n(8, 11, 12)\n(8, 11, 13)\n(8, 11, 14)\n(8, 11, 15)\n(8, 12, 13)\n(8, 12, 14)\n(8, 12, 15)\n(8, 13, 14)\n(8, 13, 15)\n(8, 14, 15)\n(9, 10, 11)\n(9, 10, 12)\n(9, 10, 13)\n(9, 10, 14)\n(9, 10, 15)\n(9, 11, 12)\n(9, 11, 13)\n(9, 11, 14)\n(9, 11, 15)\n(9, 12, 13)\n(9, 12, 14)\n(9, 12, 15)\n(9, 13, 14)\n(9, 13, 15)\n(9, 14, 15)\n(10, 11, 12)\n(10, 11, 13)\n(10, 11, 14)\n(10, 11, 15)\n(10, 12, 13)\n(10, 12, 14)\n(10, 12, 15)\n(10, 13, 14)\n(10, 13, 15)\n(10, 14, 15)\n(11, 12, 13)\n(11, 12, 14)\n(11, 12, 15)\n(11, 13, 14)\n(11, 13, 15)\n(11, 14, 15)\n(12, 13, 14)\n(12, 13, 15)\n(12, 14, 15)\n(13, 14, 15)\n"
]
],
[
[
"With this output in mind, implement the logic for nearby bin search:",
"_____no_output_____"
]
],
[
[
"def search_nearby_bins(query_bin_bits, table, search_radius=2, initial_candidates=set()):\n \"\"\"\n For a given query vector and trained LSH model, return all candidate neighbors for\n the query among all bins within the given search radius.\n \n Example usage\n -------------\n >>> model = train_lsh(corpus, num_vector=16, seed=143)\n >>> q = model['bin_index_bits'][0] # vector for the first document\n \n >>> candidates = search_nearby_bins(q, model['table'])\n \"\"\"\n num_vector = len(query_bin_bits)\n powers_of_two = 1 << np.arange(num_vector-1, -1, -1)\n \n # Allow the user to provide an initial set of candidates.\n candidate_set = copy(initial_candidates)\n \n for different_bits in combinations(range(num_vector), search_radius): \n # Flip the bits (n_1,n_2,...,n_r) of the query bin to produce a new bit vector.\n ## Hint: you can iterate over a tuple like a list\n alternate_bits = copy(query_bin_bits)\n for i in different_bits:\n alternate_bits[i] = not alternate_bits[i] # YOUR CODE HERE \n \n # Convert the new bit vector to an integer index\n nearby_bin = alternate_bits.dot(powers_of_two)\n \n # Fetch the list of documents belonging to the bin indexed by the new bit vector.\n # Then add those documents to candidate_set\n # Make sure that the bin exists in the table!\n # Hint: update() method for sets lets you add an entire list to the set\n if nearby_bin in table:\n candidate_set.update(table[nearby_bin]) # YOUR CODE HERE: Update candidate_set with the documents in this bin.\n \n return candidate_set",
"_____no_output_____"
]
],
[
[
"**Checkpoint**. Running the function with `search_radius=0` should yield the list of documents belonging to the same bin as the query.",
"_____no_output_____"
]
],
[
[
"obama_bin_index = model['bin_index_bits'][35817] # bin index of Barack Obama\ncandidate_set = search_nearby_bins(obama_bin_index, model['table'], search_radius=0)\nif candidate_set == set([35817, 21426, 53937, 39426, 50261]):\n print 'Passed test'\nelse:\n print 'Check your code'\nprint 'List of documents in the same bin as Obama: 35817, 21426, 53937, 39426, 50261'",
"Passed test\nList of documents in the same bin as Obama: 35817, 21426, 53937, 39426, 50261\n"
]
],
[
[
"**Checkpoint**. Running the function with `search_radius=1` adds more documents to the fore.",
"_____no_output_____"
]
],
[
[
"candidate_set = search_nearby_bins(obama_bin_index, model['table'], search_radius=1, initial_candidates=candidate_set)\nif candidate_set == set([39426, 38155, 38412, 28444, 9757, 41631, 39207, 59050, 47773, 53937, 21426, 34547,\n 23229, 55615, 39877, 27404, 33996, 21715, 50261, 21975, 33243, 58723, 35817, 45676,\n 19699, 2804, 20347]):\n print 'Passed test'\nelse:\n print 'Check your code'",
"Passed test\n"
]
],
[
[
"**Note**. Don't be surprised if few of the candidates look similar to Obama. This is why we add as many candidates as our computational budget allows and sort them by their distance to the query.",
"_____no_output_____"
],
[
"Now we have a function that can return all the candidates from neighboring bins. Next we write a function to collect all candidates and compute their true distance to the query.",
"_____no_output_____"
]
],
[
[
"def query(vec, model, k, max_search_radius):\n \n data = model['data']\n table = model['table']\n random_vectors = model['random_vectors']\n num_vector = random_vectors.shape[1]\n \n \n # Compute bin index for the query vector, in bit representation.\n bin_index_bits = (vec.dot(random_vectors) >= 0).flatten()\n \n # Search nearby bins and collect candidates\n candidate_set = set()\n for search_radius in xrange(max_search_radius+1):\n candidate_set = search_nearby_bins(bin_index_bits, table, search_radius, initial_candidates=candidate_set)\n \n # Sort candidates by their true distances from the query\n nearest_neighbors = graphlab.SFrame({'id':candidate_set})\n candidates = data[np.array(list(candidate_set)),:]\n nearest_neighbors['distance'] = pairwise_distances(candidates, vec, metric='cosine').flatten()\n \n return nearest_neighbors.topk('distance', k, reverse=True), len(candidate_set)",
"_____no_output_____"
]
],
[
[
"Let's try it out with Obama:",
"_____no_output_____"
]
],
[
[
"query(corpus[35817,:], model, k=10, max_search_radius=3)",
"_____no_output_____"
]
],
[
[
"To identify the documents, it's helpful to join this table with the Wikipedia table:",
"_____no_output_____"
]
],
[
[
"query(corpus[35817,:], model, k=10, max_search_radius=3)[0].join(wiki[['id', 'name']], on='id').sort('distance')",
"_____no_output_____"
]
],
[
[
"We have shown that we have a working LSH implementation!",
"_____no_output_____"
],
[
"# Experimenting with your LSH implementation",
"_____no_output_____"
],
[
"In the following sections we have implemented a few experiments so that you can gain intuition for how your LSH implementation behaves in different situations. This will help you understand the effect of searching nearby bins and the performance of LSH versus computing nearest neighbors using a brute force search.",
"_____no_output_____"
],
[
"## Effect of nearby bin search",
"_____no_output_____"
],
[
"How does nearby bin search affect the outcome of LSH? There are three variables that are affected by the search radius:\n* Number of candidate documents considered\n* Query time\n* Distance of approximate neighbors from the query",
"_____no_output_____"
],
[
"Let us run LSH multiple times, each with different radii for nearby bin search. We will measure the three variables as discussed above.",
"_____no_output_____"
]
],
[
[
"wiki[wiki['name']=='Barack Obama']",
"_____no_output_____"
],
[
"num_candidates_history = []\nquery_time_history = []\nmax_distance_from_query_history = []\nmin_distance_from_query_history = []\naverage_distance_from_query_history = []\n\nfor max_search_radius in xrange(17):\n start=time.time()\n result, num_candidates = query(corpus[35817,:], model, k=10,\n max_search_radius=max_search_radius)\n end=time.time()\n query_time = end-start\n \n print 'Radius:', max_search_radius\n print result.join(wiki[['id', 'name']], on='id').sort('distance')\n \n average_distance_from_query = result['distance'][1:].mean()\n max_distance_from_query = result['distance'][1:].max()\n min_distance_from_query = result['distance'][1:].min()\n \n num_candidates_history.append(num_candidates)\n query_time_history.append(query_time)\n average_distance_from_query_history.append(average_distance_from_query)\n max_distance_from_query_history.append(max_distance_from_query)\n min_distance_from_query_history.append(min_distance_from_query)",
"Radius: 0\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 21426 | 0.950866757525 | Mark Boulware |\n| 39426 | 0.97596600411 | John Wells (politician) |\n| 50261 | 0.978256163041 | Francis Longstaff |\n| 53937 | 0.993092148424 | Madurai T. Srinivasan |\n+-------+--------------------+-------------------------+\n[5 rows x 3 columns]\n\nRadius: 1\n+-------+--------------------+-------------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 41631 | 0.947459482005 | Binayak Sen |\n| 21426 | 0.950866757525 | Mark Boulware |\n| 33243 | 0.951765770113 | Janice Lachance |\n| 33996 | 0.960859054157 | Rufus Black |\n| 28444 | 0.961080585824 | John Paul Phelan |\n| 20347 | 0.974129605472 | Gianni De Fraja |\n| 39426 | 0.97596600411 | John Wells (politician) |\n| 34547 | 0.978214931987 | Nathan Murphy (Australian ... |\n| 50261 | 0.978256163041 | Francis Longstaff |\n+-------+--------------------+-------------------------------+\n[10 rows x 3 columns]\n\nRadius: 2\n+-------+--------------------+---------------------+\n| id | distance | name |\n+-------+--------------------+---------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 9267 | 0.898377208819 | Vikramaditya Khanna |\n| 55909 | 0.899340396322 | Herman Cain |\n| 6949 | 0.925713001103 | Harrison J. Goldin |\n| 23524 | 0.926397988994 | Paul Bennecke |\n| 5823 | 0.928498260316 | Adeleke Mamora |\n| 37262 | 0.93445433211 | Becky Cain |\n| 10121 | 0.936896394645 | Bill Bradley |\n| 54782 | 0.937809202206 | Thomas F. Hartnett |\n+-------+--------------------+---------------------+\n[10 rows x 3 columns]\n\nRadius: 3\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 56008 | 0.856848127628 | Nathan Cullen |\n| 37199 | 0.874668698194 | Barry Sullivan (lawyer) |\n| 40353 | 0.890034225981 | Neil MacBride |\n| 9267 | 0.898377208819 | Vikramaditya Khanna |\n| 55909 | 0.899340396322 | Herman Cain |\n| 9165 | 0.900921029925 | Raymond F. Clevenger |\n| 57958 | 0.903003263483 | Michael J. Malbin |\n| 49872 | 0.909532800353 | Lowell Barron |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 4\n+-------+--------------------+--------------------+\n| id | distance | name |\n+-------+--------------------+--------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 36452 | 0.833985493688 | Bill Clinton |\n| 24848 | 0.839406735668 | John C. Eastman |\n| 43155 | 0.840839007484 | Goodwin Liu |\n| 42965 | 0.849077676943 | John O. Brennan |\n| 56008 | 0.856848127628 | Nathan Cullen |\n| 38495 | 0.857573828556 | Barney Frank |\n| 18752 | 0.858899032522 | Dan W. Reicher |\n| 2092 | 0.874643264756 | Richard Blumenthal |\n+-------+--------------------+--------------------+\n[10 rows x 3 columns]\n\nRadius: 5\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46811 | 0.800197384104 | Jeff Sessions |\n| 14754 | 0.826854025897 | Mitt Romney |\n| 36452 | 0.833985493688 | Bill Clinton |\n| 40943 | 0.834534928232 | Jonathan Alter |\n| 55044 | 0.837013236281 | Wesley Clark |\n| 24848 | 0.839406735668 | John C. Eastman |\n| 43155 | 0.840839007484 | Goodwin Liu |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 6\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 46811 | 0.800197384104 | Jeff Sessions |\n| 48693 | 0.809192212293 | Artur Davis |\n| 23737 | 0.810164633465 | John D. McCormick |\n| 4032 | 0.814554748671 | Kenneth D. Thompson |\n| 28447 | 0.823228984384 | George W. Bush |\n| 14754 | 0.826854025897 | Mitt Romney |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 7\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 46811 | 0.800197384104 | Jeff Sessions |\n| 48693 | 0.809192212293 | Artur Davis |\n| 23737 | 0.810164633465 | John D. McCormick |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 8\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 46811 | 0.800197384104 | Jeff Sessions |\n| 48693 | 0.809192212293 | Artur Davis |\n| 23737 | 0.810164633465 | John D. McCormick |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 9\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 46811 | 0.800197384104 | Jeff Sessions |\n| 39357 | 0.809050776238 | John McCain |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 10\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 2412 | 0.799466360042 | Joe the Plumber |\n| 46811 | 0.800197384104 | Jeff Sessions |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 11\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 2412 | 0.799466360042 | Joe the Plumber |\n| 46811 | 0.800197384104 | Jeff Sessions |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 12\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 6796 | 0.788039072943 | Eric Holder |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 2412 | 0.799466360042 | Joe the Plumber |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 13\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 6796 | 0.788039072943 | Eric Holder |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 2412 | 0.799466360042 | Joe the Plumber |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 14\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 6796 | 0.788039072943 | Eric Holder |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 2412 | 0.799466360042 | Joe the Plumber |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 15\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 6796 | 0.788039072943 | Eric Holder |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 2412 | 0.799466360042 | Joe the Plumber |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\nRadius: 16\n+-------+--------------------+-------------------------+\n| id | distance | name |\n+-------+--------------------+-------------------------+\n| 35817 | -6.66133814775e-16 | Barack Obama |\n| 24478 | 0.703138676734 | Joe Biden |\n| 38376 | 0.742981902328 | Samantha Power |\n| 57108 | 0.758358397887 | Hillary Rodham Clinton |\n| 38714 | 0.770561227601 | Eric Stern (politician) |\n| 46140 | 0.784677504751 | Robert Gibbs |\n| 6796 | 0.788039072943 | Eric Holder |\n| 44681 | 0.790926415366 | Jesse Lee (politician) |\n| 18827 | 0.798322602893 | Henry Waxman |\n| 2412 | 0.799466360042 | Joe the Plumber |\n+-------+--------------------+-------------------------+\n[10 rows x 3 columns]\n\n"
]
],
[
[
"Notice that the top 10 query results become more relevant as the search radius grows. Let's plot the three variables:",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(7,4.5))\nplt.plot(num_candidates_history, linewidth=4)\nplt.xlabel('Search radius')\nplt.ylabel('# of documents searched')\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()\n\nplt.figure(figsize=(7,4.5))\nplt.plot(query_time_history, linewidth=4)\nplt.xlabel('Search radius')\nplt.ylabel('Query time (seconds)')\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()\n\nplt.figure(figsize=(7,4.5))\nplt.plot(average_distance_from_query_history, linewidth=4, label='Average of 10 neighbors')\nplt.plot(max_distance_from_query_history, linewidth=4, label='Farthest of 10 neighbors')\nplt.plot(min_distance_from_query_history, linewidth=4, label='Closest of 10 neighbors')\nplt.xlabel('Search radius')\nplt.ylabel('Cosine distance of neighbors')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"Some observations:\n* As we increase the search radius, we find more neighbors that are a smaller distance away.\n* With increased search radius comes a greater number documents that have to be searched. Query time is higher as a consequence.\n* With sufficiently high search radius, the results of LSH begin to resemble the results of brute-force search.",
"_____no_output_____"
],
[
"**Quiz Question**. What was the smallest search radius that yielded the correct nearest neighbor, namely Joe Biden?\n\n\n**Quiz Question**. Suppose our goal was to produce 10 approximate nearest neighbors whose average distance from the query document is within 0.01 of the average for the true 10 nearest neighbors. For Barack Obama, the true 10 nearest neighbors are on average about 0.77. What was the smallest search radius for Barack Obama that produced an average distance of 0.78 or better?",
"_____no_output_____"
]
],
[
[
"#2 and 7",
"_____no_output_____"
]
],
[
[
"## Quality metrics for neighbors",
"_____no_output_____"
],
[
"The above analysis is limited by the fact that it was run with a single query, namely Barack Obama. We should repeat the analysis for the entirety of data. Iterating over all documents would take a long time, so let us randomly choose 10 documents for our analysis.\n\nFor each document, we first compute the true 25 nearest neighbors, and then run LSH multiple times. We look at two metrics:\n\n* Precision@10: How many of the 10 neighbors given by LSH are among the true 25 nearest neighbors?\n* Average cosine distance of the neighbors from the query\n\nThen we run LSH multiple times with different search radii.",
"_____no_output_____"
]
],
[
[
"def brute_force_query(vec, data, k):\n num_data_points = data.shape[0]\n \n # Compute distances for ALL data points in training set\n nearest_neighbors = graphlab.SFrame({'id':range(num_data_points)})\n nearest_neighbors['distance'] = pairwise_distances(data, vec, metric='cosine').flatten()\n \n return nearest_neighbors.topk('distance', k, reverse=True)",
"_____no_output_____"
]
],
[
[
"The following cell will run LSH with multiple search radii and compute the quality metrics for each run. Allow a few minutes to complete.",
"_____no_output_____"
]
],
[
[
"max_radius = 17\nprecision = {i:[] for i in xrange(max_radius)}\naverage_distance = {i:[] for i in xrange(max_radius)}\nquery_time = {i:[] for i in xrange(max_radius)}\n\nnp.random.seed(0)\nnum_queries = 10\nfor i, ix in enumerate(np.random.choice(corpus.shape[0], num_queries, replace=False)):\n print('%s / %s' % (i, num_queries))\n ground_truth = set(brute_force_query(corpus[ix,:], corpus, k=25)['id'])\n # Get the set of 25 true nearest neighbors\n \n for r in xrange(1,max_radius):\n start = time.time()\n result, num_candidates = query(corpus[ix,:], model, k=10, max_search_radius=r)\n end = time.time()\n\n query_time[r].append(end-start)\n # precision = (# of neighbors both in result and ground_truth)/10.0\n precision[r].append(len(set(result['id']) & ground_truth)/10.0)\n average_distance[r].append(result['distance'][1:].mean())",
"0 / 10\n1 / 10\n2 / 10\n3 / 10\n4 / 10\n5 / 10\n6 / 10\n7 / 10\n8 / 10\n9 / 10\n"
],
[
"plt.figure(figsize=(7,4.5))\nplt.plot(range(1,17), [np.mean(average_distance[i]) for i in xrange(1,17)], linewidth=4, label='Average over 10 neighbors')\nplt.xlabel('Search radius')\nplt.ylabel('Cosine distance')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()\n\nplt.figure(figsize=(7,4.5))\nplt.plot(range(1,17), [np.mean(precision[i]) for i in xrange(1,17)], linewidth=4, label='Precison@10')\nplt.xlabel('Search radius')\nplt.ylabel('Precision')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()\n\nplt.figure(figsize=(7,4.5))\nplt.plot(range(1,17), [np.mean(query_time[i]) for i in xrange(1,17)], linewidth=4, label='Query time')\nplt.xlabel('Search radius')\nplt.ylabel('Query time (seconds)')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"The observations for Barack Obama generalize to the entire dataset.",
"_____no_output_____"
],
[
"## Effect of number of random vectors",
"_____no_output_____"
],
[
"Let us now turn our focus to the remaining parameter: the number of random vectors. We run LSH with different number of random vectors, ranging from 5 to 20. We fix the search radius to 3.\n\nAllow a few minutes for the following cell to complete.",
"_____no_output_____"
]
],
[
[
"precision = {i:[] for i in xrange(5,20)}\naverage_distance = {i:[] for i in xrange(5,20)}\nquery_time = {i:[] for i in xrange(5,20)}\nnum_candidates_history = {i:[] for i in xrange(5,20)}\nground_truth = {}\n\nnp.random.seed(0)\nnum_queries = 10\ndocs = np.random.choice(corpus.shape[0], num_queries, replace=False)\n\nfor i, ix in enumerate(docs):\n ground_truth[ix] = set(brute_force_query(corpus[ix,:], corpus, k=25)['id'])\n # Get the set of 25 true nearest neighbors\n\nfor num_vector in xrange(5,20):\n print('num_vector = %s' % (num_vector))\n model = train_lsh(corpus, num_vector, seed=143)\n \n for i, ix in enumerate(docs):\n start = time.time()\n result, num_candidates = query(corpus[ix,:], model, k=10, max_search_radius=3)\n end = time.time()\n \n query_time[num_vector].append(end-start)\n precision[num_vector].append(len(set(result['id']) & ground_truth[ix])/10.0)\n average_distance[num_vector].append(result['distance'][1:].mean())\n num_candidates_history[num_vector].append(num_candidates)",
"_____no_output_____"
],
[
"plt.figure(figsize=(7,4.5))\nplt.plot(range(5,20), [np.mean(average_distance[i]) for i in xrange(5,20)], linewidth=4, label='Average over 10 neighbors')\nplt.xlabel('# of random vectors')\nplt.ylabel('Cosine distance')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()\n\nplt.figure(figsize=(7,4.5))\nplt.plot(range(5,20), [np.mean(precision[i]) for i in xrange(5,20)], linewidth=4, label='Precison@10')\nplt.xlabel('# of random vectors')\nplt.ylabel('Precision')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()\n\nplt.figure(figsize=(7,4.5))\nplt.plot(range(5,20), [np.mean(query_time[i]) for i in xrange(5,20)], linewidth=4, label='Query time (seconds)')\nplt.xlabel('# of random vectors')\nplt.ylabel('Query time (seconds)')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()\n\nplt.figure(figsize=(7,4.5))\nplt.plot(range(5,20), [np.mean(num_candidates_history[i]) for i in xrange(5,20)], linewidth=4,\n label='# of documents searched')\nplt.xlabel('# of random vectors')\nplt.ylabel('# of documents searched')\nplt.legend(loc='best', prop={'size':15})\nplt.rcParams.update({'font.size':16})\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"We see a similar trade-off between quality and performance: as the number of random vectors increases, the query time goes down as each bin contains fewer documents on average, but on average the neighbors are likewise placed farther from the query. On the other hand, when using a small enough number of random vectors, LSH becomes very similar brute-force search: Many documents appear in a single bin, so searching the query bin alone covers a lot of the corpus; then, including neighboring bins might result in searching all documents, just as in the brute-force approach.",
"_____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"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4a9312075da81b8a1c4c51149a05f26d1a9650a1
| 909,987 |
ipynb
|
Jupyter Notebook
|
convolutional-neural-networks/cifar-cnn/cifar10_cnn_exercise.ipynb
|
michael135/deep-learning-v2-pytorch
|
9dcb006e1f78eb4c19bbc57cbfda5083ef96f415
|
[
"MIT"
] | null | null | null |
convolutional-neural-networks/cifar-cnn/cifar10_cnn_exercise.ipynb
|
michael135/deep-learning-v2-pytorch
|
9dcb006e1f78eb4c19bbc57cbfda5083ef96f415
|
[
"MIT"
] | null | null | null |
convolutional-neural-networks/cifar-cnn/cifar10_cnn_exercise.ipynb
|
michael135/deep-learning-v2-pytorch
|
9dcb006e1f78eb4c19bbc57cbfda5083ef96f415
|
[
"MIT"
] | null | null | null | 1,348.128889 | 654,252 | 0.95515 |
[
[
[
"# Convolutional Neural Networks\n---\nIn this notebook, we train a **CNN** to classify images from the CIFAR-10 database.\n\nThe images in this database are small color images that fall into one of ten classes; some example images are pictured below.\n\n<img src='notebook_ims/cifar_data.png' width=70% height=70% />",
"_____no_output_____"
],
[
"### Test for [CUDA](http://pytorch.org/docs/stable/cuda.html)\n\nSince these are larger (32x32x3) images, it may prove useful to speed up your training time by using a GPU. CUDA is a parallel computing platform and CUDA Tensors are the same as typical Tensors, only they utilize GPU's for computation.",
"_____no_output_____"
]
],
[
[
"import torch\nimport numpy as np\n\n# check if CUDA is available\ntrain_on_gpu = torch.cuda.is_available()\n\nif not train_on_gpu:\n print('CUDA is not available. Training on CPU ...')\nelse:\n print('CUDA is available! Training on GPU ...')",
"CUDA is not available. Training on CPU ...\n"
]
],
[
[
"---\n## Load the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)\n\nDownloading may take a minute. We load in the training and test data, split the training data into a training and validation set, then create DataLoaders for each of these sets of data.",
"_____no_output_____"
]
],
[
[
"from torchvision import datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\n# number of subprocesses to use for data loading\nnum_workers = 0\n# how many samples per batch to load\nbatch_size = 20\n# percentage of training set to use as validation\nvalid_size = 0.2\n\n# convert data to a normalized torch.FloatTensor\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n\n# choose the training and test datasets\ntrain_data = datasets.CIFAR10('data', train=True,\n download=True, transform=transform)\ntest_data = datasets.CIFAR10('data', train=False,\n download=True, transform=transform)\n\n# obtain training indices that will be used for validation\nnum_train = len(train_data)\nindices = list(range(num_train))\nnp.random.shuffle(indices)\nsplit = int(np.floor(valid_size * num_train))\ntrain_idx, valid_idx = indices[split:], indices[:split]\n\n# define samplers for obtaining training and validation batches\ntrain_sampler = SubsetRandomSampler(train_idx)\nvalid_sampler = SubsetRandomSampler(valid_idx)\n\n# prepare data loaders (combine dataset and sampler)\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,\n sampler=train_sampler, num_workers=num_workers)\nvalid_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, \n sampler=valid_sampler, num_workers=num_workers)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, \n num_workers=num_workers)\n\n# specify the image classes\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck']",
"Files already downloaded and verified\nFiles already downloaded and verified\n"
]
],
[
[
"### Visualize a Batch of Training Data",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n\n# helper function to un-normalize and display an image\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n plt.imshow(np.transpose(img, (1, 2, 0))) # convert from Tensor image",
"_____no_output_____"
],
[
"# obtain one batch of training images\ndataiter = iter(train_loader)\nimages, labels = dataiter.next()\nimages = images.numpy() # convert images to numpy for display\n\n# plot the images in the batch, along with the corresponding labels\nfig = plt.figure(figsize=(25, 4))\n# display 20 images\nfor idx in np.arange(20):\n ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n imshow(images[idx])\n ax.set_title(classes[labels[idx]])",
"_____no_output_____"
]
],
[
[
"### View an Image in More Detail\n\nHere, we look at the normalized red, green, and blue (RGB) color channels as three separate, grayscale intensity images.",
"_____no_output_____"
]
],
[
[
"rgb_img = np.squeeze(images[3])\nchannels = ['red channel', 'green channel', 'blue channel']\n\nfig = plt.figure(figsize = (36, 36)) \nfor idx in np.arange(rgb_img.shape[0]):\n ax = fig.add_subplot(1, 3, idx + 1)\n img = rgb_img[idx]\n ax.imshow(img, cmap='gray')\n ax.set_title(channels[idx])\n width, height = img.shape\n thresh = img.max()/2.5\n for x in range(width):\n for y in range(height):\n val = round(img[x][y],2) if img[x][y] !=0 else 0\n ax.annotate(str(val), xy=(y,x),\n horizontalalignment='center',\n verticalalignment='center', size=8,\n color='white' if img[x][y]<thresh else 'black')",
"_____no_output_____"
]
],
[
[
"---\n## Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html)\n\nThis time, you'll define a CNN architecture. Instead of an MLP, which used linear, fully-connected layers, you'll use the following:\n* [Convolutional layers](https://pytorch.org/docs/stable/nn.html#conv2d), which can be thought of as stack of filtered images.\n* [Maxpooling layers](https://pytorch.org/docs/stable/nn.html#maxpool2d), which reduce the x-y size of an input, keeping only the most _active_ pixels from the previous layer.\n* The usual Linear + Dropout layers to avoid overfitting and produce a 10-dim output.\n\nA network with 2 convolutional layers is shown in the image below and in the code, and you've been given starter code with one convolutional and one maxpooling layer.\n\n<img src='notebook_ims/2_layer_conv.png' height=50% width=50% />\n\n#### TODO: Define a model with multiple convolutional layers, and define the feedforward network behavior.\n\nThe more convolutional layers you include, the more complex patterns in color and shape a model can detect. It's suggested that your final model include 2 or 3 convolutional layers as well as linear layers + dropout in between to avoid overfitting. \n\nIt's good practice to look at existing research and implementations of related models as a starting point for defining your own models. You may find it useful to look at [this PyTorch classification example](https://github.com/pytorch/tutorials/blob/master/beginner_source/blitz/cifar10_tutorial.py) or [this, more complex Keras example](https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py) to help decide on a final structure.\n\n#### Output volume for a convolutional layer\n\nTo compute the output size of a given convolutional layer we can perform the following calculation (taken from [Stanford's cs231n course](http://cs231n.github.io/convolutional-networks/#layers)):\n> We can compute the spatial size of the output volume as a function of the input volume size (W), the kernel/filter size (F), the stride with which they are applied (S), and the amount of zero padding used (P) on the border. The correct formula for calculating how many neurons define the output_W is given by `(W−F+2P)/S+1`. \n\nFor example for a 7x7 input and a 3x3 filter with stride 1 and pad 0 we would get a 5x5 output. With stride 2 we would get a 3x3 output.",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\nimport torch.nn.functional as F\n\n# define the CNN architecture\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n # convolutional layer\n # (32,32,3)\n self.conv1 = nn.Conv2d(3, 6, 5)\n # (14,14,6)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n # (5,5,16)\n self.fc1 = nn.Linear(16 * 5 * 5, 64)\n self.fc2 = nn.Linear(64, 32)\n self.fc3 = nn.Linear(32, 10)\n\n def forward(self, x):\n # add sequence of convolutional and max pooling layers\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n\n\n# def __init__(self):\n# super(Net, self).__init__()\n# self.conv1 = nn.Conv2d(3, 6, 5)\n# self.pool = nn.MaxPool2d(2, 2)\n# self.conv2 = nn.Conv2d(6, 16, 5)\n# self.fc1 = nn.Linear(16 * 5 * 5, 120)\n# self.fc2 = nn.Linear(120, 84)\n# self.fc3 = nn.Linear(84, 10)\n\n# def forward(self, x):\n# x = self.pool(F.relu(self.conv1(x)))\n# x = self.pool(F.relu(self.conv2(x)))\n# x = x.view(-1, 16 * 5 * 5)\n# x = F.relu(self.fc1(x))\n# x = F.relu(self.fc2(x))\n# x = self.fc3(x)\n\n\n return x\n\n# create a complete CNN\nmodel = Net()\nprint(model)\n\n# move tensors to GPU if CUDA is available\nif train_on_gpu:\n model.cuda()\n \n \n# self.conv1 = nn.Conv2d(3, 6, 5)\n# self.pool = nn.MaxPool2d(2, 2)\n# self.conv2 = nn.Conv2d(6, 16, 5)\n# self.fc1 = nn.Linear(16 * 5 * 5, 120)\n# self.fc2 = nn.Linear(120, 84)\n# self.fc3 = nn.Linear(84, 10)",
"Net(\n (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))\n (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n (fc1): Linear(in_features=400, out_features=64, bias=True)\n (fc2): Linear(in_features=64, out_features=32, bias=True)\n (fc3): Linear(in_features=32, out_features=10, bias=True)\n)\n"
]
],
[
[
"### Specify [Loss Function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html)\n\nDecide on a loss and optimization function that is best suited for this classification task. The linked code examples from above, may be a good starting point; [this PyTorch classification example](https://github.com/pytorch/tutorials/blob/master/beginner_source/blitz/cifar10_tutorial.py) or [this, more complex Keras example](https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py). Pay close attention to the value for **learning rate** as this value determines how your model converges to a small error.\n\n#### TODO: Define the loss and optimizer and see how these choices change the loss over time.",
"_____no_output_____"
]
],
[
[
"import torch.optim as optim\n\n# specify loss function\ncriterion = torch.nn.CrossEntropyLoss()\n\n# specify optimizer\noptimizer = optim.SGD(model.parameters(), lr=0.01)",
"_____no_output_____"
]
],
[
[
"---\n## Train the Network\n\nRemember to look at how the training and validation loss decreases over time; if the validation loss ever increases it indicates possible overfitting.",
"_____no_output_____"
]
],
[
[
"# number of epochs to train the model\nn_epochs = 10# you may increase this number to train a final model\n\nvalid_loss_min = np.Inf # track change in validation loss\n\nfor epoch in range(1, n_epochs+1):\n\n # keep track of training and validation loss\n train_loss = 0.0\n valid_loss = 0.0\n \n ###################\n # train the model #\n ###################\n model.train()\n for data, target in train_loader:\n # move tensors to GPU if CUDA is available\n if train_on_gpu:\n data, target = data.cuda(), target.cuda()\n # clear the gradients of all optimized variables\n optimizer.zero_grad()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the batch loss\n loss = criterion(output, target)\n # backward pass: compute gradient of the loss with respect to model parameters\n loss.backward()\n # perform a single optimization step (parameter update)\n optimizer.step()\n # update training loss\n train_loss += loss.item()*data.size(0)\n \n ###################### \n # validate the model #\n ######################\n model.eval()\n for data, target in valid_loader:\n # move tensors to GPU if CUDA is available\n if train_on_gpu:\n data, target = data.cuda(), target.cuda()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the batch loss\n loss = criterion(output, target)\n # update average validation loss \n valid_loss += loss.item()*data.size(0)\n \n # calculate average losses\n train_loss = train_loss/len(train_loader.dataset)\n valid_loss = valid_loss/len(valid_loader.dataset)\n \n # print training/validation statistics \n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n epoch, train_loss, valid_loss))\n \n # save model if validation loss has decreased\n if valid_loss <= valid_loss_min:\n print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(\n valid_loss_min,\n valid_loss))\n torch.save(model.state_dict(), 'model_cifar.pt')\n valid_loss_min = valid_loss",
"Epoch: 1 \tTraining Loss: 0.943819 \tValidation Loss: 0.246939\nValidation loss decreased (inf --> 0.246939). Saving model ...\nEpoch: 2 \tTraining Loss: 0.908377 \tValidation Loss: 0.226820\nValidation loss decreased (0.246939 --> 0.226820). Saving model ...\nEpoch: 3 \tTraining Loss: 0.881034 \tValidation Loss: 0.224919\nValidation loss decreased (0.226820 --> 0.224919). Saving model ...\nEpoch: 4 \tTraining Loss: 0.852853 \tValidation Loss: 0.224350\nValidation loss decreased (0.224919 --> 0.224350). Saving model ...\nEpoch: 5 \tTraining Loss: 0.828191 \tValidation Loss: 0.221754\nValidation loss decreased (0.224350 --> 0.221754). Saving model ...\nEpoch: 6 \tTraining Loss: 0.807982 \tValidation Loss: 0.215698\nValidation loss decreased (0.221754 --> 0.215698). Saving model ...\nEpoch: 7 \tTraining Loss: 0.788726 \tValidation Loss: 0.215811\nEpoch: 8 \tTraining Loss: 0.769984 \tValidation Loss: 0.212842\nValidation loss decreased (0.215698 --> 0.212842). Saving model ...\nEpoch: 9 \tTraining Loss: 0.752059 \tValidation Loss: 0.210421\nValidation loss decreased (0.212842 --> 0.210421). Saving model ...\nEpoch: 10 \tTraining Loss: 0.734618 \tValidation Loss: 0.215502\n"
]
],
[
[
"### Load the Model with the Lowest Validation Loss",
"_____no_output_____"
]
],
[
[
"model.load_state_dict(torch.load('model_cifar.pt'))",
"_____no_output_____"
]
],
[
[
"---\n## Test the Trained Network\n\nTest your trained model on previously unseen data! A \"good\" result will be a CNN that gets around 70% (or more, try your best!) accuracy on these test images.",
"_____no_output_____"
]
],
[
[
"# track test loss\ntest_loss = 0.0\nclass_correct = list(0. for i in range(10))\nclass_total = list(0. for i in range(10))\n\nmodel.eval()\n# iterate over test data\nfor data, target in test_loader:\n # move tensors to GPU if CUDA is available\n if train_on_gpu:\n data, target = data.cuda(), target.cuda()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the batch loss\n loss = criterion(output, target)\n # update test loss \n test_loss += loss.item()*data.size(0)\n # convert output probabilities to predicted class\n _, pred = torch.max(output, 1) \n # compare predictions to true label\n correct_tensor = pred.eq(target.data.view_as(pred))\n correct = np.squeeze(correct_tensor.numpy()) if not train_on_gpu else np.squeeze(correct_tensor.cpu().numpy())\n # calculate test accuracy for each object class\n for i in range(batch_size):\n label = target.data[i]\n class_correct[label] += correct[i].item()\n class_total[label] += 1\n\n# average test loss\ntest_loss = test_loss/len(test_loader.dataset)\nprint('Test Loss: {:.6f}\\n'.format(test_loss))\n\nfor i in range(10):\n if class_total[i] > 0:\n print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (\n classes[i], 100 * class_correct[i] / class_total[i],\n np.sum(class_correct[i]), np.sum(class_total[i])))\n else:\n print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i]))\n\nprint('\\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % (\n 100. * np.sum(class_correct) / np.sum(class_total),\n np.sum(class_correct), np.sum(class_total)))",
"Test Loss: 1.057423\n\nTest Accuracy of airplane: 65% (651/1000)\nTest Accuracy of automobile: 74% (744/1000)\nTest Accuracy of bird: 39% (398/1000)\nTest Accuracy of cat: 38% (389/1000)\nTest Accuracy of deer: 59% (596/1000)\nTest Accuracy of dog: 59% (599/1000)\nTest Accuracy of frog: 81% (816/1000)\nTest Accuracy of horse: 65% (652/1000)\nTest Accuracy of ship: 78% (787/1000)\nTest Accuracy of truck: 68% (680/1000)\n\nTest Accuracy (Overall): 63% (6312/10000)\n"
]
],
[
[
"### Question: What are your model's weaknesses and how might they be improved?",
"_____no_output_____"
],
[
"**Answer**: (double-click to edit and add an answer)",
"_____no_output_____"
],
[
"### Visualize Sample Test Results",
"_____no_output_____"
]
],
[
[
"# obtain one batch of test images\ndataiter = iter(test_loader)\nimages, labels = dataiter.next()\nimages.numpy()\n\n# move model inputs to cuda, if GPU available\nif train_on_gpu:\n images = images.cuda()\n\n# get sample outputs\noutput = model(images)\n# convert output probabilities to predicted class\n_, preds_tensor = torch.max(output, 1)\npreds = np.squeeze(preds_tensor.numpy()) if not train_on_gpu else np.squeeze(preds_tensor.cpu().numpy())\n\n# plot the images in the batch, along with predicted and true labels\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(20):\n ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n imshow(images[idx])\n ax.set_title(\"{} ({})\".format(classes[preds[idx]], classes[labels[idx]]),\n color=(\"green\" if preds[idx]==labels[idx].item() else \"red\"))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
4a932069587a904de15347676ca7c75aea5b9a03
| 41,621 |
ipynb
|
Jupyter Notebook
|
Datascience_With_Python/Machine Learning/Tutorials/Introduction to Unsupervised Learning/introduction_to _unsupervised_learning.ipynb
|
vishnupriya129/winter-of-contributing
|
8632c74d0c2d55bb4fddee9d6faac30159f376e1
|
[
"MIT"
] | 1,078 |
2021-09-05T09:44:33.000Z
|
2022-03-27T01:16:02.000Z
|
Datascience_With_Python/Machine Learning/Tutorials/Introduction to Unsupervised Learning/introduction_to _unsupervised_learning.ipynb
|
vishnupriya129/winter-of-contributing
|
8632c74d0c2d55bb4fddee9d6faac30159f376e1
|
[
"MIT"
] | 6,845 |
2021-09-05T12:49:50.000Z
|
2022-03-12T16:41:13.000Z
|
Datascience_With_Python/Machine Learning/Tutorials/Introduction to Unsupervised Learning/introduction_to _unsupervised_learning.ipynb
|
vishnupriya129/winter-of-contributing
|
8632c74d0c2d55bb4fddee9d6faac30159f376e1
|
[
"MIT"
] | 2,629 |
2021-09-03T04:53:16.000Z
|
2022-03-20T17:45:00.000Z
| 20,810.5 | 41,620 | 0.890464 |
[
[
[
" ",
"_____no_output_____"
]
],
[
[
"\n\n\n\n\n\n# INTRODUCTION TO UNSUPERVISED LEARNING\n\nUnsupervised learning is the training of a machine using information that is neither classified nor labeled and allowing the algorithm to act on that information without guidance. Here the task of the machine is to group unsorted information according to similarities, patterns, and differences without any prior training of data. \n\n\n\n\n\n\n\n\n\n\nUnlike supervised learning, no teacher is provided that means no training will be given to the machine. Therefore the machine is restricted to find the hidden structure in unlabeled data by itself. \n\n\n#Example of Unsupervised Machine Learning\n\nFor instance, suppose a image having both dogs and cats which it has never seen.\n\nThus the machine has no idea about the features of dogs and cats so we can’t categorize it as ‘dogs and cats ‘. But it can categorize them according to their similarities, patterns, and differences, i.e., we can easily categorize the picture into two parts. The first may contain all pics having dogs in it and the second part may contain all pics having cats in it. Here you didn’t learn anything before, which means no training data or examples. \n\nIt allows the model to work on its own to discover patterns and information that was previously undetected. It mainly deals with unlabelled data.\n\n#Why Unsupervised Learning?\n\nHere, are prime reasons for using Unsupervised Learning in Machine Learning:\n\n>Unsupervised machine learning finds all kind of unknown patterns in data.\n\n\n\n>Unsupervised methods help you to find features which can be useful for categorization.\n\n\n >It is taken place in real time, so all the input data to be analyzed and labeled in the presence of learners.\n\n\n\n>It is easier to get unlabeled data from a computer than labeled data, which needs manual intervention.\n\n#Unsupervised Learning Algorithms\n\n\n\nUnsupervised Learning Algorithms allow users to perform more complex processing tasks compared to supervised learning. Although, unsupervised learning can be more unpredictable compared with other natural learning methods. Unsupervised learning algorithms include clustering, anomaly detection, neural networks, etc.\n\n#Unsupervised learning is classified into two categories of algorithms: \n \n\n>Clustering: A clustering problem is where you want to discover the inherent groupings in the data, such as grouping customers by purchasing behavior.\n\n\n>Association: An association rule learning problem is where you want to discover rules that describe large portions of your data, such as people that buy X also tend to buy Y.\n\n\n#a)Clustering\n\n\nClustering is an important concept when it comes to unsupervised learning.\n\n It mainly deals with finding a structure or pattern in a collection of uncategorized data. \n \n Unsupervised Learning Clustering algorithms will process your data and find natural clusters(groups) if they exist in the data.\n \n You can also modify how many clusters your algorithms should identify. It allows you to adjust the granularity of these groups.\n\n#There are different types of clustering you can utilize:\n\n#1.Exclusive (partitioning)\n\nIn this clustering method, Data are grouped in such a way that one data can belong to one cluster only.\n\nExample: K-means\n\n#2.Agglomerative\n\nIn this clustering technique, every data is a cluster. The iterative unions between the two nearest clusters reduce the number of clusters.\n\nExample: Hierarchical clustering\n\n#3.Overlapping\nIn this technique, fuzzy sets is used to cluster data. Each point may belong to two or more clusters with separate degrees of membership.\n\nHere, data will be associated with an appropriate membership value.\n\n Example: Fuzzy C-Means\n\n#4.Probabilistic\nThis technique uses probability distribution to create the clusters\n\nExample: Following keywords\n\n“man’s shoe.”\n\n“women’s shoe.”\n\n“women’s glove.”\n\n“man’s glove.”\n\ncan be clustered into two categories “shoe” and “glove” or “man” and “women.”\n\n#Clustering Types\nFollowing are the clustering types of Machine Learning:\n\nHierarchical clustering\n\nK-means clustering\n\nK-NN (k nearest neighbors)\n\nPrincipal Component Analysis\n\nSingular value decomposition\n\nIndependent Component Analysis\n\n\n\n\n\n#1.Hierarchical Clustering\n>Hierarchical clustering is an algorithm which builds a hierarchy of clusters. It begins with all the data which is assigned to a cluster of their own. Here, two close cluster are going to be in the same cluster. This algorithm ends when there is only one cluster left.\n\n#2.K-means Clustering\n>K-means it is an iterative clustering algorithm which helps you to find the highest value for every iteration. Initially, the desired number of clusters are selected. In this clustering method, you need to cluster the data points into k groups. A larger k means smaller groups with more granularity in the same way. A lower k means larger groups with less granularity.\n\n>The output of the algorithm is a group of “labels.” It assigns data point to one of the k groups. In k-means clustering, each group is defined by creating a centroid for each group. The centroids are like the heart of the cluster, which captures the points closest to them and adds them to the cluster.\n\nK-mean clustering further defines two subgroups:\n\nAgglomerative clustering\n\nDendrogram\n\n\n#Agglomerative clustering\n\n>This type of K-means clustering starts with a fixed number of clusters. It allocates all data into the exact number of clusters. This clustering method does not require the number of clusters K as an input. Agglomeration process starts by forming each data as a single cluster.\n\n>This method uses some distance measure, reduces the number of clusters (one in each iteration) by merging process. Lastly, we have one big cluster that contains all the objects.\n\n#Dendrogram\n>In the Dendrogram clustering method, each level will represent a possible cluster. The height of dendrogram shows the level of similarity between two join clusters. The closer to the bottom of the process they are more similar cluster which is finding of the group from dendrogram which is not natural and mostly subjective.\n\n#K- Nearest neighbors\n\n>K- nearest neighbour is the simplest of all machine learning classifiers. It differs from other machine learning techniques, in that it doesn’t produce a model. It is a simple algorithm which stores all available cases and classifies new instances based on a similarity measure.\n\nIt works very well when there is a distance between examples. The learning speed is slow when the training set is large, and the distance calculation is nontrivial.\n\n#4.Principal Components Analysis\n>In case you want a higher-dimensional space. You need to select a basis for that space and only the 200 most important scores of that basis. This base is known as a principal component. The subset you select constitute is a new space which is small in size compared to original space. It maintains as much of the complexity of data as possible.\n\n#5.Singular value decomposition\n>The singular value decomposition of a matrix is usually referred to as the SVD.\nThis is the final and best factorization of a matrix:\nA = UΣV^T\nwhere U is orthogonal, Σ is diagonal, and V is orthogonal.\nIn the decomoposition A = UΣV^T, A can be any matrix. We know that if A\nis symmetric positive definite its eigenvectors are orthogonal and we can write\nA = QΛQ^T. This is a special case of a SVD, with U = V = Q. For more general\nA, the SVD requires two different matrices U and V.\nWe’ve also learned how to write A = SΛS^−1, where S is the matrix of n\ndistinct eigenvectors of A. However, S may not be orthogonal; the matrices U\nand V in the SVD will be. \n\n\n#6.Independent Component Analysis\n>Independent Component Analysis (ICA) is a machine learning technique to separate independent sources from a mixed signal. Unlike principal component analysis which focuses on maximizing the variance of the data points, the independent component analysis focuses on independence, i.e. independent components.\n\n#b)Association\n>Association rules allow you to establish associations amongst data objects inside large databases. This unsupervised technique is about discovering interesting relationships between variables in large databases. For example, people that buy a new home most likely to buy new furniture.\n\n>Other Examples:\n\n>A subgroup of cancer patients grouped by their gene expression measurements\n\n>Groups of shopper based on their browsing and purchasing histories\n\n>Movie group by the rating given by movies viewers\n\n\n\n \n#Applications of Unsupervised Machine Learning\nSome application of Unsupervised Learning Techniques are:\n\n1.Clustering automatically split the dataset into groups base on their similarities\n\n\n2.Anomaly detection can discover unusual data points in your dataset. It is useful for finding fraudulent transactions\n\n\n3.Association mining identifies sets of items which often occur together in your dataset\n\n\n4.Latent variable models are widely used for data preprocessing. Like reducing the number of features in a dataset or decomposing the dataset into multiple components.\n\n#Real-life Applications Of Unsupervised Learning\n\nMachines are not that quick, unlike humans. It takes a lot of resources to train a model based on patterns in data. Below are a few of the wonderful real-life simulations of unsupervised learning.\n\n\n1.Anomaly detection –The advent of technology and the internet has given birth to enormous anomalies in the past and is still growing. Unsupervised learning has huge scope when it comes to anomaly detection.\n\n\n2.Segmentation – Unsupervised learning can be used to segment the customers based on certain patterns. Each cluster of customers is different whereas customers within a cluster share common properties. Customer segmentation is a widely opted approach used in devising marketing plans.\n\n#Advantages of unsupervised learning\n\n1.It can see what human minds cannot visualize.\n\n2.It is used to dig hidden patterns which hold utmost importance in the industry and has widespread applications in real-time.\n\n3.The outcome of an unsupervised task can yield an entirely new business vertical or venture.\n\n4.There is lesser complexity compared to the supervised learning task. Here, no one is required to interpret the associated labels and hence it holds lesser complexities.\n\n5.It is reasonably easier to obtain unlabeled data.\n\n\n#Disadvantages of Unsupervised Learning\n\n1.You cannot get precise information regarding data sorting, and the output as data used in unsupervised learning is labeled and not known.\n\n2.Less accuracy of the results is because the input data is not known and not labeled by people in advance. This means that the machine requires to do this itself.\n\n3.The spectral classes do not always correspond to informational classes.\nThe user needs to spend time interpreting and label the classes which follow that classification.\n\n4.Spectral properties of classes can also change over time so you can’t have the same class information while moving from one image to another.\n\n\n#How to use Unsupervised learning to find patterns in data\n\n#CODE:\n\n\nfrom sklearn import datasets\n\n\nimport matplotlib.pyplot as plt\n\n\n\n\niris_df = datasets.load_iris()\n\n\n\nprint(dir(iris_df)\n\nprint(iris_df.feature_names)\n\n\nprint(iris_df.target)\n\n\nprint(iris_df.target_names)\n\nlabel = {0: 'red', 1: 'blue', 2: 'green'}\n\nx_axis = iris_df.data[:, 0] \n\ny_axis = iris_df.data[:, 2] \n\nplt.scatter(x_axis, y_axis, c=iris_df.target)\n\nplt.show()\n\n#Explanation:\n\nAs the above code shows, we have used the Iris dataset to make predictions.The dataset contains a records under four attributes-petal length, petal width, sepal length, sepal width.And also it contains three iris classes:setosa, virginica and versicolor .We'll feed the four features of our flowers to the unsupervised algorithm and it will predict which class the iris belongs.For that we have used scikit-learn library in python to load the Iris dataset and matplotlib for data visualisation. \n\n\n#OUTPUT:\n\nAs we can see here the violet colour represents setosa,green colour represents versicolor and yellow\n colour represents virginica.\n\n\n\n\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4a932af03ed08b96c9b84779e98e5a4e410888ba
| 298,311 |
ipynb
|
Jupyter Notebook
|
lesson5-25/Finding Edges and Custom Kernels.ipynb
|
nmpegetis/udacity-facebook-pytorch
|
36a9de03c71892836e184e58695143960c6a7d2b
|
[
"MIT"
] | null | null | null |
lesson5-25/Finding Edges and Custom Kernels.ipynb
|
nmpegetis/udacity-facebook-pytorch
|
36a9de03c71892836e184e58695143960c6a7d2b
|
[
"MIT"
] | null | null | null |
lesson5-25/Finding Edges and Custom Kernels.ipynb
|
nmpegetis/udacity-facebook-pytorch
|
36a9de03c71892836e184e58695143960c6a7d2b
|
[
"MIT"
] | null | null | null | 1,291.38961 | 135,588 | 0.957709 |
[
[
[
"# Creating a Filter, Edge Detection",
"_____no_output_____"
]
],
[
[
"### Import resources and display image",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport cv2\nimport numpy as np\n\n%matplotlib inline\n\n# Read in the image\nimage = mpimg.imread('images/curved_lane.jpg')\n\nplt.imshow(image)",
"_____no_output_____"
]
],
[
[
"### Convert the image to grayscale",
"_____no_output_____"
]
],
[
[
"# Convert to grayscale for filtering\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\nplt.imshow(gray, cmap='gray')",
"_____no_output_____"
]
],
[
[
"### TODO: Create a custom kernel\n\nBelow, you've been given one common type of edge detection filter: a Sobel operator.\n\nThe Sobel filter is very commonly used in edge detection and in finding patterns in intensity in an image. Applying a Sobel filter to an image is a way of **taking (an approximation) of the derivative of the image** in the x or y direction, separately. The operators look as follows.\n\n<img src=\"images/sobel_ops.png\" width=200 height=200>\n\n**It's up to you to create a Sobel x operator and apply it to the given image.**\n\nFor a challenge, see if you can put the image through a series of filters: first one that blurs the image (takes an average of pixels), and then one that detects the edges.",
"_____no_output_____"
]
],
[
[
"# Create a custom kernel\n\n# 3x3 array for edge detection\nsobel_y = np.array([[ -1, -2, -1], \n [ 0, 0, 0], \n [ 1, 2, 1]])\n\n## TODO: Create and apply a Sobel x operator\n\n\n# Filter the image using filter2D, which has inputs: (grayscale image, bit-depth, kernel) \nfiltered_image = cv2.filter2D(gray, -1, sobel_y)\n\nplt.imshow(filtered_image, cmap='gray')",
"_____no_output_____"
]
],
[
[
"### Test out other filters!\n\nYou're encouraged to create other kinds of filters and apply them to see what happens! As an **optional exercise**, try the following:\n* Create a filter with decimal value weights.\n* Create a 5x5 filter\n* Apply your filters to the other images in the `images` directory.\n\n",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a932ed0986fd513678c2f2ee4247f367aa53c96
| 5,317 |
ipynb
|
Jupyter Notebook
|
Perceptron/perceptron.ipynb
|
Now-Tiger/Neural-Nets
|
e6fe9a561a580e633142b557caac621a37ea82fc
|
[
"MIT"
] | null | null | null |
Perceptron/perceptron.ipynb
|
Now-Tiger/Neural-Nets
|
e6fe9a561a580e633142b557caac621a37ea82fc
|
[
"MIT"
] | null | null | null |
Perceptron/perceptron.ipynb
|
Now-Tiger/Neural-Nets
|
e6fe9a561a580e633142b557caac621a37ea82fc
|
[
"MIT"
] | null | null | null | 34.525974 | 391 | 0.577769 |
[
[
[
"# Perceptron",
"_____no_output_____"
],
[
"__The Perceptron is a linear machine learning algorithm for binary classification tasks.__\n\nIt may be considered one of the first and one of the simplest types of artificial neural networks. It is definitely not “deep” learning but is an important building block.\n\nLike logistic regression, it can quickly learn a linear separation in feature space for two-class classification tasks, although unlike logistic regression, it learns using the stochastic gradient descent optimization algorithm and does not predict calibrated probabilities.",
"_____no_output_____"
],
[
"# Perceptron Algorithm\n\nThe Perceptron algorithm is a two-class (binary) classification machine learning algorithm.\n\nIt is a type of neural network model, perhaps the simplest type of neural network model.\n\nIt consists of a single node or neuron that takes a row of data as input and predicts a class label. This is achieved by calculating the weighted sum of the inputs and a bias (set to 1). The weighted sum of the input of the model is called the activation.\n\n- Activation = Weights * Inputs + Bias<br><br>\n__If the activation is above 0.0, the model will output 1.0; otherwise, it will output 0.0__<br><br>\n\n- Predict 1: If Activation > 0.0\n- Predict 0: If Activation <= 0.0",
"_____no_output_____"
],
[
"Model weights are updated with a small proportion of the error each batch, and the proportion is controlled by a hyperparameter called the learning rate, typically set to a small value. This is to ensure learning does not occur too quickly, resulting in a possibly lower skill model, referred to as premature convergence of the optimization (search) procedure for the model weights.\n\n__weights(t + 1) = weights(t) + learning_rate * (expected_i – predicted_) * input_i__<br>\n\nTraining is stopped when the error made by the model falls to a low level or no longer improves, or a maximum number of epochs is performed.\n\nThe learning rate and number of training epochs are hyperparameters of the algorithm that can be set using heuristics or hyperparameter tuning.",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import make_classification\nfrom sklearn.model_selection import GridSearchCV, RepeatedStratifiedKFold\nfrom sklearn.linear_model import Perceptron",
"_____no_output_____"
],
[
"if __name__ == '__main__' :\n X, y = make_classification(n_samples = 1000, \n n_features = 10, n_informative = 10, \n n_redundant = 0, random_state = 1)\n\n model = Perceptron(eta0=0.0001)\n\n cv = RepeatedStratifiedKFold(n_splits = 10, n_repeats = 3, random_state = 1)\n\n grid = dict()\n grid['max_iter'] = [1, 10, 100, 1000, 10000]\n\n search = GridSearchCV(model, grid, scoring = 'accuracy', cv = cv, n_jobs = -1)\n \n result = search.fit(X, y)\n\n # Summarize :\n print('Mean Accuracy : {}'.format(round(result.best_score_, 4)))\n print('-'*50)\n print('Config : {}'.format(result.best_params_))\n print('-'*50)\n\n # Summarize all :\n means = result.cv_results_['mean_test_score']\n params = result.cv_results_['params']\n\n for mean, param in zip(means, params) :\n print('{} with : {}'.format(round(mean, 3),(param)))\n ",
"Mean Accuracy : 0.857\n--------------------------------------------------\nConfig : {'max_iter': 10}\n--------------------------------------------------\n0.85 with : {'max_iter': 1}\n0.857 with : {'max_iter': 10}\n0.857 with : {'max_iter': 100}\n0.857 with : {'max_iter': 1000}\n0.857 with : {'max_iter': 10000}\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4a9347861a8051d5845bd0b6a6d7df59b1444800
| 945,036 |
ipynb
|
Jupyter Notebook
|
notebooks/seasonality,_holiday_effects,_and_regressors.ipynb
|
lishuai2016/prophet
|
0d260699e4776c449703a957f08eca8013461a47
|
[
"MIT"
] | 2 |
2020-10-01T11:09:45.000Z
|
2020-10-12T09:36:39.000Z
|
notebooks/seasonality,_holiday_effects,_and_regressors.ipynb
|
lishuai2016/prophet
|
0d260699e4776c449703a957f08eca8013461a47
|
[
"MIT"
] | 2 |
2021-11-04T21:17:15.000Z
|
2022-02-26T07:38:48.000Z
|
notebooks/seasonality,_holiday_effects,_and_regressors.ipynb
|
algharak/prophet
|
f16d9df33337be93d34f0f69904e9fa25e1b6a10
|
[
"MIT"
] | 1 |
2021-04-18T09:40:58.000Z
|
2021-04-18T09:40:58.000Z
| 768.947111 | 95,892 | 0.947332 |
[
[
[
"%load_ext rpy2.ipython\n%matplotlib inline\nfrom fbprophet import Prophet\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport logging\nlogging.getLogger('fbprophet').setLevel(logging.ERROR)\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ndf = pd.read_csv('../examples/example_wp_log_peyton_manning.csv')\nm = Prophet()\nm.fit(df)\nfuture = m.make_future_dataframe(periods=366)",
"_____no_output_____"
],
[
"%%R\nlibrary(prophet)\ndf <- read.csv('../examples/example_wp_log_peyton_manning.csv')\nm <- prophet(df)\nfuture <- make_future_dataframe(m, periods=366)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Loading required package: Rcpp\n\nWARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Loading required package: rlang\n\nWARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n\n"
]
],
[
[
"### Modeling Holidays and Special Events\nIf you have holidays or other recurring events that you'd like to model, you must create a dataframe for them. It has two columns (`holiday` and `ds`) and a row for each occurrence of the holiday. It must include all occurrences of the holiday, both in the past (back as far as the historical data go) and in the future (out as far as the forecast is being made). If they won't repeat in the future, Prophet will model them and then not include them in the forecast.\n\nYou can also include columns `lower_window` and `upper_window` which extend the holiday out to `[lower_window, upper_window]` days around the date. For instance, if you wanted to include Christmas Eve in addition to Christmas you'd include `lower_window=-1,upper_window=0`. If you wanted to use Black Friday in addition to Thanksgiving, you'd include `lower_window=0,upper_window=1`. You can also include a column `prior_scale` to set the prior scale separately for each holiday, as described below.\n\nHere we create a dataframe that includes the dates of all of Peyton Manning's playoff appearances:",
"_____no_output_____"
]
],
[
[
"%%R\nlibrary(dplyr)\nplayoffs <- data_frame(\n holiday = 'playoff',\n ds = as.Date(c('2008-01-13', '2009-01-03', '2010-01-16',\n '2010-01-24', '2010-02-07', '2011-01-08',\n '2013-01-12', '2014-01-12', '2014-01-19',\n '2014-02-02', '2015-01-11', '2016-01-17',\n '2016-01-24', '2016-02-07')),\n lower_window = 0,\n upper_window = 1\n)\nsuperbowls <- data_frame(\n holiday = 'superbowl',\n ds = as.Date(c('2010-02-07', '2014-02-02', '2016-02-07')),\n lower_window = 0,\n upper_window = 1\n)\nholidays <- bind_rows(playoffs, superbowls)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: \nAttaching package: ‘dplyr’\n\n\nWARNING:rpy2.rinterface_lib.callbacks:R[write to console]: The following objects are masked from ‘package:stats’:\n\n filter, lag\n\n\nWARNING:rpy2.rinterface_lib.callbacks:R[write to console]: The following objects are masked from ‘package:base’:\n\n intersect, setdiff, setequal, union\n\n\n"
],
[
"playoffs = pd.DataFrame({\n 'holiday': 'playoff',\n 'ds': pd.to_datetime(['2008-01-13', '2009-01-03', '2010-01-16',\n '2010-01-24', '2010-02-07', '2011-01-08',\n '2013-01-12', '2014-01-12', '2014-01-19',\n '2014-02-02', '2015-01-11', '2016-01-17',\n '2016-01-24', '2016-02-07']),\n 'lower_window': 0,\n 'upper_window': 1,\n})\nsuperbowls = pd.DataFrame({\n 'holiday': 'superbowl',\n 'ds': pd.to_datetime(['2010-02-07', '2014-02-02', '2016-02-07']),\n 'lower_window': 0,\n 'upper_window': 1,\n})\nholidays = pd.concat((playoffs, superbowls))",
"_____no_output_____"
]
],
[
[
"Above we have included the superbowl days as both playoff games and superbowl games. This means that the superbowl effect will be an additional additive bonus on top of the playoff effect.\n\nOnce the table is created, holiday effects are included in the forecast by passing them in with the `holidays` argument. Here we do it with the Peyton Manning data from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html):",
"_____no_output_____"
]
],
[
[
"%%R\nm <- prophet(df, holidays = holidays)\nforecast <- predict(m, future)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n\n"
],
[
"m = Prophet(holidays=holidays)\nforecast = m.fit(df).predict(future)",
"_____no_output_____"
]
],
[
[
"The holiday effect can be seen in the `forecast` dataframe:",
"_____no_output_____"
]
],
[
[
"%%R\nforecast %>% \n select(ds, playoff, superbowl) %>% \n filter(abs(playoff + superbowl) > 0) %>%\n tail(10)",
"_____no_output_____"
],
[
"forecast[(forecast['playoff'] + forecast['superbowl']).abs() > 0][\n ['ds', 'playoff', 'superbowl']][-10:]",
"_____no_output_____"
]
],
[
[
"The holiday effects will also show up in the components plot, where we see that there is a spike on the days around playoff appearances, with an especially large spike for the superbowl:",
"_____no_output_____"
]
],
[
[
"%%R -w 9 -h 12 -u in\nprophet_plot_components(m, forecast)",
"_____no_output_____"
],
[
"fig = m.plot_components(forecast)",
"_____no_output_____"
]
],
[
[
"Individual holidays can be plotted using the `plot_forecast_component` function (imported from `fbprophet.plot` in Python) like `plot_forecast_component(m, forecast, 'superbowl')` to plot just the superbowl holiday component.",
"_____no_output_____"
],
[
"### Built-in Country Holidays\n\nYou can use a built-in collection of country-specific holidays using the `add_country_holidays` method (Python) or function (R). The name of the country is specified, and then major holidays for that country will be included in addition to any holidays that are specified via the `holidays` argument described above:",
"_____no_output_____"
]
],
[
[
"%%R\nm <- prophet(holidays = holidays)\nm <- add_country_holidays(m, country_name = 'US')\nm <- fit.prophet(m, df)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n\n"
],
[
"m = Prophet(holidays=holidays)\nm.add_country_holidays(country_name='US')\nm.fit(df)",
"_____no_output_____"
]
],
[
[
"You can see which holidays were included by looking at the `train_holiday_names` (Python) or `train.holiday.names` (R) attribute of the model:",
"_____no_output_____"
]
],
[
[
"%%R\nm$train.holiday.names",
"_____no_output_____"
],
[
"m.train_holiday_names",
"_____no_output_____"
]
],
[
[
"The holidays for each country are provided by the `holidays` package in Python. A list of available countries, and the country name to use, is available on their page: https://github.com/dr-prodigy/python-holidays. In addition to those countries, Prophet includes holidays for these countries: Brazil (BR), Indonesia (ID), India (IN), Malaysia (MY), Vietnam (VN), Thailand (TH), Philippines (PH), Turkey (TU), Pakistan (PK), Bangladesh (BD), Egypt (EG), China (CN), and Russian (RU), Korea (KR), Belarus (BY), and United Arab Emirates (AE).\n\nIn Python, most holidays are computed deterministically and so are available for any date range; a warning will be raised if dates fall outside the range supported by that country. In R, holiday dates are computed for 1995 through 2044 and stored in the package as `data-raw/generated_holidays.csv`. If a wider date range is needed, this script can be used to replace that file with a different date range: https://github.com/facebook/prophet/blob/master/python/scripts/generate_holidays_file.py.\n\nAs above, the country-level holidays will then show up in the components plot:",
"_____no_output_____"
]
],
[
[
"%%R -w 9 -h 12 -u in\nforecast <- predict(m, future)\nprophet_plot_components(m, forecast)",
"_____no_output_____"
],
[
"forecast = m.predict(future)\nfig = m.plot_components(forecast)",
"_____no_output_____"
]
],
[
[
"### Fourier Order for Seasonalities\n\nSeasonalities are estimated using a partial Fourier sum. See [the paper](https://peerj.com/preprints/3190/) for complete details, and [this figure on Wikipedia](https://en.wikipedia.org/wiki/Fourier_series#/media/File:Fourier_Series.svg) for an illustration of how a partial Fourier sum can approximate an aribtrary periodic signal. The number of terms in the partial sum (the order) is a parameter that determines how quickly the seasonality can change. To illustrate this, consider the Peyton Manning data from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html). The default Fourier order for yearly seasonality is 10, which produces this fit:",
"_____no_output_____"
]
],
[
[
"%%R -w 9 -h 3 -u in\nm <- prophet(df)\nprophet:::plot_yearly(m)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n\n"
],
[
"from fbprophet.plot import plot_yearly\nm = Prophet().fit(df)\na = plot_yearly(m)",
"_____no_output_____"
]
],
[
[
"The default values are often appropriate, but they can be increased when the seasonality needs to fit higher-frequency changes, and generally be less smooth. The Fourier order can be specified for each built-in seasonality when instantiating the model, here it is increased to 20:",
"_____no_output_____"
]
],
[
[
"%%R -w 9 -h 3 -u in\nm <- prophet(df, yearly.seasonality = 20)\nprophet:::plot_yearly(m)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n\n"
],
[
"from fbprophet.plot import plot_yearly\nm = Prophet(yearly_seasonality=20).fit(df)\na = plot_yearly(m)",
"_____no_output_____"
]
],
[
[
"Increasing the number of Fourier terms allows the seasonality to fit faster changing cycles, but can also lead to overfitting: N Fourier terms corresponds to 2N variables used for modeling the cycle\n\n### Specifying Custom Seasonalities\n\nProphet will by default fit weekly and yearly seasonalities, if the time series is more than two cycles long. It will also fit daily seasonality for a sub-daily time series. You can add other seasonalities (monthly, quarterly, hourly) using the `add_seasonality` method (Python) or function (R).\n\nThe inputs to this function are a name, the period of the seasonality in days, and the Fourier order for the seasonality. For reference, by default Prophet uses a Fourier order of 3 for weekly seasonality and 10 for yearly seasonality. An optional input to `add_seasonality` is the prior scale for that seasonal component - this is discussed below.\n\nAs an example, here we fit the Peyton Manning data from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html), but replace the weekly seasonality with monthly seasonality. The monthly seasonality then will appear in the components plot:",
"_____no_output_____"
]
],
[
[
"%%R -w 9 -h 9 -u in\nm <- prophet(weekly.seasonality=FALSE)\nm <- add_seasonality(m, name='monthly', period=30.5, fourier.order=5)\nm <- fit.prophet(m, df)\nforecast <- predict(m, future)\nprophet_plot_components(m, forecast)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n\n"
],
[
"m = Prophet(weekly_seasonality=False)\nm.add_seasonality(name='monthly', period=30.5, fourier_order=5)\nforecast = m.fit(df).predict(future)\nfig = m.plot_components(forecast)",
"_____no_output_____"
]
],
[
[
"### Seasonalities that depend on other factors\nIn some instances the seasonality may depend on other factors, such as a weekly seasonal pattern that is different during the summer than it is during the rest of the year, or a daily seasonal pattern that is different on weekends vs. on weekdays. These types of seasonalities can be modeled using conditional seasonalities.\n\nConsider the Peyton Manning example from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html). The default weekly seasonality assumes that the pattern of weekly seasonality is the same throughout the year, but we'd expect the pattern of weekly seasonality to be different during the on-season (when there are games every Sunday) and the off-season. We can use conditional seasonalities to construct separate on-season and off-season weekly seasonalities.\n\nFirst we add a boolean column to the dataframe that indicates whether each date is during the on-season or the off-season:",
"_____no_output_____"
]
],
[
[
"%%R\nis_nfl_season <- function(ds) {\n dates <- as.Date(ds)\n month <- as.numeric(format(dates, '%m'))\n return(month > 8 | month < 2)\n}\ndf$on_season <- is_nfl_season(df$ds)\ndf$off_season <- !is_nfl_season(df$ds)",
"_____no_output_____"
],
[
"def is_nfl_season(ds):\n date = pd.to_datetime(ds)\n return (date.month > 8 or date.month < 2)\n\ndf['on_season'] = df['ds'].apply(is_nfl_season)\ndf['off_season'] = ~df['ds'].apply(is_nfl_season)",
"_____no_output_____"
]
],
[
[
"Then we disable the built-in weekly seasonality, and replace it with two weekly seasonalities that have these columns specified as a condition. This means that the seasonality will only be applied to dates where the `condition_name` column is `True`. We must also add the column to the `future` dataframe for which we are making predictions.",
"_____no_output_____"
]
],
[
[
"%%R -w 9 -h 12 -u in\nm <- prophet(weekly.seasonality=FALSE)\nm <- add_seasonality(m, name='weekly_on_season', period=7, fourier.order=3, condition.name='on_season')\nm <- add_seasonality(m, name='weekly_off_season', period=7, fourier.order=3, condition.name='off_season')\nm <- fit.prophet(m, df)\n\nfuture$on_season <- is_nfl_season(future$ds)\nfuture$off_season <- !is_nfl_season(future$ds)\nforecast <- predict(m, future)\nprophet_plot_components(m, forecast)",
"WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n\n"
],
[
"m = Prophet(weekly_seasonality=False)\nm.add_seasonality(name='weekly_on_season', period=7, fourier_order=3, condition_name='on_season')\nm.add_seasonality(name='weekly_off_season', period=7, fourier_order=3, condition_name='off_season')\n\nfuture['on_season'] = future['ds'].apply(is_nfl_season)\nfuture['off_season'] = ~future['ds'].apply(is_nfl_season)\nforecast = m.fit(df).predict(future)\nfig = m.plot_components(forecast)",
"_____no_output_____"
]
],
[
[
"Both of the seasonalities now show up in the components plots above. We can see that during the on-season when games are played every Sunday, there are large increases on Sunday and Monday that are completely absent during the off-season.",
"_____no_output_____"
],
[
"### Prior scale for holidays and seasonality\nIf you find that the holidays are overfitting, you can adjust their prior scale to smooth them using the parameter `holidays_prior_scale`. By default this parameter is 10, which provides very little regularization. Reducing this parameter dampens holiday effects:",
"_____no_output_____"
]
],
[
[
"%%R\nm <- prophet(df, holidays = holidays, holidays.prior.scale = 0.05)\nforecast <- predict(m, future)\nforecast %>% \n select(ds, playoff, superbowl) %>% \n filter(abs(playoff + superbowl) > 0) %>%\n tail(10)",
"_____no_output_____"
],
[
"m = Prophet(holidays=holidays, holidays_prior_scale=0.05).fit(df)\nforecast = m.predict(future)\nforecast[(forecast['playoff'] + forecast['superbowl']).abs() > 0][\n ['ds', 'playoff', 'superbowl']][-10:]",
"_____no_output_____"
]
],
[
[
"The magnitude of the holiday effect has been reduced compared to before, especially for superbowls, which had the fewest observations. There is a parameter `seasonality_prior_scale` which similarly adjusts the extent to which the seasonality model will fit the data.\n\nPrior scales can be set separately for individual holidays by including a column `prior_scale` in the holidays dataframe. Prior scales for individual seasonalities can be passed as an argument to `add_seasonality`. For instance, the prior scale for just weekly seasonality can be set using:",
"_____no_output_____"
]
],
[
[
"%%R\nm <- prophet()\nm <- add_seasonality(\n m, name='weekly', period=7, fourier.order=3, prior.scale=0.1)",
"_____no_output_____"
],
[
"m = Prophet()\nm.add_seasonality(\n name='weekly', period=7, fourier_order=3, prior_scale=0.1)",
"_____no_output_____"
]
],
[
[
"\n### Additional regressors\nAdditional regressors can be added to the linear part of the model using the `add_regressor` method or function. A column with the regressor value will need to be present in both the fitting and prediction dataframes. For example, we can add an additional effect on Sundays during the NFL season. On the components plot, this effect will show up in the 'extra_regressors' plot:",
"_____no_output_____"
]
],
[
[
"%%R -w 9 -h 12 -u in\nnfl_sunday <- function(ds) {\n dates <- as.Date(ds)\n month <- as.numeric(format(dates, '%m'))\n as.numeric((weekdays(dates) == \"Sunday\") & (month > 8 | month < 2))\n}\ndf$nfl_sunday <- nfl_sunday(df$ds)\n\nm <- prophet()\nm <- add_regressor(m, 'nfl_sunday')\nm <- fit.prophet(m, df)\n\nfuture$nfl_sunday <- nfl_sunday(future$ds)\n\nforecast <- predict(m, future)\nprophet_plot_components(m, forecast)",
"_____no_output_____"
],
[
"def nfl_sunday(ds):\n date = pd.to_datetime(ds)\n if date.weekday() == 6 and (date.month > 8 or date.month < 2):\n return 1\n else:\n return 0\ndf['nfl_sunday'] = df['ds'].apply(nfl_sunday)\n\nm = Prophet()\nm.add_regressor('nfl_sunday')\nm.fit(df)\n\nfuture['nfl_sunday'] = future['ds'].apply(nfl_sunday)\n\nforecast = m.predict(future)\nfig = m.plot_components(forecast)",
"_____no_output_____"
]
],
[
[
"NFL Sundays could also have been handled using the \"holidays\" interface described above, by creating a list of past and future NFL Sundays. The `add_regressor` function provides a more general interface for defining extra linear regressors, and in particular does not require that the regressor be a binary indicator. Another time series could be used as a regressor, although its future values would have to be known.\n\n[This notebook](https://nbviewer.jupyter.org/github/nicolasfauchereau/Auckland_Cycling/blob/master/notebooks/Auckland_cycling_and_weather.ipynb) shows an example of using weather factors as extra regressors in a forecast of bicycle usage, and provides an excellent illustration of how other time series can be included as extra regressors.\n\nThe `add_regressor` function has optional arguments for specifying the prior scale (holiday prior scale is used by default) and whether or not the regressor is standardized - see the docstring with `help(Prophet.add_regressor)` in Python and `?add_regressor` in R. Note that regressors must be added prior to model fitting.\n\nThe extra regressor must be known for both the history and for future dates. It thus must either be something that has known future values (such as `nfl_sunday`), or something that has separately been forecasted elsewhere. Prophet will also raise an error if the regressor is constant throughout the history, since there is nothing to fit from it.\n\nExtra regressors are put in the linear component of the model, so the underlying model is that the time series depends on the extra regressor as either an additive or multiplicative factor (see the next section for multiplicativity).",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4a9360b639158930a5ba5062200e772cf5349792
| 23,445 |
ipynb
|
Jupyter Notebook
|
examples/Notebooks/flopy3_get_transmissivities_example.ipynb
|
briochh/flopy
|
51d4442cb0ff96024be0bc81c554a4e1d2d9ed78
|
[
"CC0-1.0",
"BSD-3-Clause"
] | 1 |
2019-11-03T15:06:10.000Z
|
2019-11-03T15:06:10.000Z
|
examples/Notebooks/flopy3_get_transmissivities_example.ipynb
|
anguanping/flopy
|
4a9ea1a8f47467239f40c67b6f6823a424a845df
|
[
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null |
examples/Notebooks/flopy3_get_transmissivities_example.ipynb
|
anguanping/flopy
|
4a9ea1a8f47467239f40c67b6f6823a424a845df
|
[
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | 76.12013 | 14,180 | 0.782384 |
[
[
[
"### Demonstration of `flopy.utils.get_transmissivities` method\nfor computing open interval transmissivities (for weighted averages of heads or fluxes)\nIn practice this method might be used to: \n\n* compute vertically-averaged head target values representative of observation wells of varying open intervals (including variability in saturated thickness due to the position of the water table)\n* apportion boundary fluxes (e.g. from an analytic element model) among model layers based on transmissivity.\n* any other analysis where a distribution of transmissivity by layer is needed for a specified vertical interval of the model.",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n# run installed version of flopy or add local path\ntry:\n import flopy\nexcept:\n fpth = os.path.abspath(os.path.join('..', '..'))\n sys.path.append(fpth)\n import flopy\n\nprint(sys.version)\nprint('numpy version: {}'.format(np.__version__))\nprint('matplotlib version: {}'.format(mpl.__version__))\nprint('flopy version: {}'.format(flopy.__version__))",
"flopy is installed in /Users/jdhughes/Documents/Development/flopy_git/flopy_us/flopy\n3.7.3 (default, Mar 27 2019, 16:54:48) \n[Clang 4.0.1 (tags/RELEASE_401/final)]\nnumpy version: 1.16.2\nmatplotlib version: 3.0.3\nflopy version: 3.2.12\n"
]
],
[
[
"### Make up some open interval tops and bottoms and some heads\n* (these could be lists of observation well screen tops and bottoms)\n* the heads array contains the simulated head in each model layer,\n at the location of each observation well (for example, what you would get back from HYDMOD if you had an entry for each layer at the location of each head target).\n* make up a model grid with uniform horizontal k of 2.",
"_____no_output_____"
]
],
[
[
"sctop = [-.25, .5, 1.7, 1.5, 3., 2.5] # screen tops\nscbot = [-1., -.5, 1.2, 0.5, 1.5, -.2] # screen bottoms\n# head in each layer, for 6 head target locations\nheads = np.array([[1., 2.0, 2.05, 3., 4., 2.5],\n [1.1, 2.1, 2.2, 2., 3.5, 3.],\n [1.2, 2.3, 2.4, 0.6, 3.4, 3.2]\n ])\nnl, nr = heads.shape\nnc = nr\nbotm = np.ones((nl, nr, nc), dtype=float)\ntop = np.ones((nr, nc), dtype=float) * 2.1\nhk = np.ones((nl, nr, nc), dtype=float) * 2.\nfor i in range(nl):\n botm[nl-i-1, :, :] = i\nbotm",
"_____no_output_____"
]
],
[
[
"### Make a flopy modflow model",
"_____no_output_____"
]
],
[
[
"m = flopy.modflow.Modflow('junk', version='mfnwt', model_ws='data')\ndis = flopy.modflow.ModflowDis(m, nlay=nl, nrow=nr, ncol=nc, botm=botm, top=top)\nupw = flopy.modflow.ModflowUpw(m, hk=hk)",
"_____no_output_____"
]
],
[
[
"### Get transmissivities along the diagonal cells\n* alternatively, if a model's coordinate information has been set up, the real-world x and y coordinates could be supplied with the `x` and `y` arguments\n* if `sctop` and `scbot` arguments are given, the transmissivites are computed for the open intervals only\n (cells that are partially within the open interval have reduced thickness, cells outside of the open interval have transmissivities of 0). If no `sctop` or `scbot` arguments are supplied, trasmissivites reflect the full saturated thickness in each column of cells (see plot below, which shows different open intervals relative to the model layering)",
"_____no_output_____"
]
],
[
[
"r, c = np.arange(nr), np.arange(nc)\nT = flopy.utils.get_transmissivities(heads, m, r=r, c=c, sctop=sctop, scbot=scbot)\nnp.round(T, 2)",
"_____no_output_____"
],
[
"m.dis.botm.array[:, r, c]",
"_____no_output_____"
]
],
[
[
"### Plot the model top and layer bottoms (colors)\nopen intervals are shown as boxes\n* well 0 has zero transmissivities for each layer, as it is below the model bottom\n* well 1 has T values of 0 for layers 1 and 2, and 1 for layer 3 (K=2 x 0.5 thickness)",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots()\nplt.plot(m.dis.top.array[r, c], label='model top')\nfor i, l in enumerate(m.dis.botm.array[:, r, c]):\n label = 'layer {} bot'.format(i+1)\n if i == m.nlay -1:\n label = 'model bot'\n plt.plot(l, label=label)\nplt.plot(heads[0], label='piezometric surface', color='b', linestyle=':')\nfor iw in range(len(sctop)):\n ax.fill_between([iw-.25, iw+.25], scbot[iw], sctop[iw], \n facecolor='None', edgecolor='k')\nax.legend(loc=2)",
"_____no_output_____"
]
],
[
[
"### example of transmissivites without `sctop` and `scbot`\n* well zero has T=0 in layer 1 because it is dry; T=0.2 in layer 2 because the sat. thickness there is only 0.1",
"_____no_output_____"
]
],
[
[
"T = flopy.utils.get_transmissivities(heads, m, r=r, c=c)\nnp.round(T, 2)",
"_____no_output_____"
]
]
] |
[
"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"
]
] |
4a936dec8b53871913e71527d69df2047d71bb29
| 181,221 |
ipynb
|
Jupyter Notebook
|
Stats module 2/Stats_types_of_analysis.ipynb
|
RIT-MESH/Statistics-for-Data-Science-using-Python
|
6edfd641dd90a2b480ac72cdce6e5516b4bc00b8
|
[
"MIT"
] | null | null | null |
Stats module 2/Stats_types_of_analysis.ipynb
|
RIT-MESH/Statistics-for-Data-Science-using-Python
|
6edfd641dd90a2b480ac72cdce6e5516b4bc00b8
|
[
"MIT"
] | null | null | null |
Stats module 2/Stats_types_of_analysis.ipynb
|
RIT-MESH/Statistics-for-Data-Science-using-Python
|
6edfd641dd90a2b480ac72cdce6e5516b4bc00b8
|
[
"MIT"
] | null | null | null | 473.16188 | 148,980 | 0.93764 |
[
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"df=pd.read_csv('F:\\Statistics\\Data/Iris.csv')\ndf",
"_____no_output_____"
],
[
"df['SepalLengthCm'].hist()",
"_____no_output_____"
],
[
"df['Species'].value_counts().plot(kind='bar')",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.scatter(df['SepalLengthCm'],df['SepalWidthCm'])\nplt.xlabel('sepallength')\nplt.ylabel('sepalwidth')",
"_____no_output_____"
],
[
"import seaborn as sns",
"_____no_output_____"
],
[
"sns.pairplot(df)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a9374b649341f7de7232a00ebbe7d9dd483821d
| 45,778 |
ipynb
|
Jupyter Notebook
|
machine_learning/ML_Talking_factors.ipynb
|
ArtTucker/mental_health_and_economics
|
4112d769df4efb6405665efd8fe02b0c2e3fa5dd
|
[
"MIT"
] | 1 |
2021-05-09T23:19:55.000Z
|
2021-05-09T23:19:55.000Z
|
machine_learning/ML_Talking_factors.ipynb
|
ArtTucker/mental_health_and_economics
|
4112d769df4efb6405665efd8fe02b0c2e3fa5dd
|
[
"MIT"
] | 17 |
2021-04-19T10:48:53.000Z
|
2022-02-08T18:39:15.000Z
|
machine_learning/ML_Talking_factors.ipynb
|
ArtTucker/mental_health_and_economics
|
4112d769df4efb6405665efd8fe02b0c2e3fa5dd
|
[
"MIT"
] | 1 |
2021-04-26T04:48:14.000Z
|
2021-04-26T04:48:14.000Z
| 36.534717 | 1,254 | 0.364891 |
[
[
[
"import pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Dependencies for interaction with database:\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\n\n\n# Machine Learning dependencies:\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\n# Validation libraries\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score, mean_squared_error, precision_recall_curve\nfrom sklearn.model_selection import cross_val_score\n\nfrom collections import Counter\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom imblearn.metrics import classification_report_imbalanced",
"_____no_output_____"
],
[
"# Create engine and link to local postgres database:\nengine = create_engine('postgresql://postgres:[email protected]:5432/postgres')\nconnect = engine.connect()",
"_____no_output_____"
],
[
"# Create session:\nsession = Session(engine)\n",
"_____no_output_____"
],
[
"# Import clean_dataset_2016 table:\nclean_2016_df = pd.read_sql(sql = 'SELECT * FROM \"survey_2016\"',con=connect)",
"_____no_output_____"
],
[
"clean_2016_df.head()",
"_____no_output_____"
],
[
"# Check data for insights:\nprint(clean_2016_df.shape)\nprint(clean_2016_df.columns.tolist())\nprint(clean_2016_df.value_counts)",
"(1004, 55)\n['SurveyID', 'new_id', 'self_employed', 'company_size', 'tech_company', 'mh_coverage', 'mh_coverage_awareness', 'mh_employer_discussion', 'mh_resources_provided', 'mh_anonimity', 'mh_medical_leave', 'mh_discussion_negative_impact', 'ph_discussion_negative_impact', 'mh_discussion_coworkers', 'mh_discussion_supervisors', 'mh_equal_ph', 'mh_observed_consequences_coworkers', 'prev_employers', 'prev_mh_benefits', 'prev_mh_benefits_awareness', 'prev_mh_discussion', 'prev_mh_resources', 'prev_mh_anonimity', 'prev_mh_discuss_negative_consequences', 'prev_ph_discuss_negative_consequences', 'prev_mh_discussion_coworkers', 'prev_mh_discussion_supervisors', 'prev_mh_importance_employer', 'prev_mh_consequences_coworkers', 'future_ph_specification', 'future_mh_specification', 'mh_hurt_on_career', 'mh_neg_view_coworkers', 'mh_sharing_friends_family', 'mh_bad_response_workplace', 'mh_for_others_bad_response_workplace', 'mh_family_history', 'mh_dx_past', 'mh_dx_current', 'yes_what_dx?', 'mh_dx_pro', 'yes_condition_dx', 'mh_sought_pro_tx', 'mh_eff_tx_impact_on_work', 'mh_not_eff_tx_impact_on_work', 'age', 'gender', 'country_live', 'live_us_state', 'country_work', 'work_us_state', 'work_position', 'remote', 'quantile_age_1', 'quantile_age_2']\n<bound method DataFrame.value_counts of SurveyID new_id self_employed company_size tech_company \\\n0 2016 1 0 26-100 1 \n1 2016 2 0 25-Jun 1 \n2 2016 3 0 25-Jun 1 \n3 2016 4 0 25-Jun 0 \n4 2016 5 0 More than 1000 1 \n... ... ... ... ... ... \n999 2016 1003 0 100-500 1 \n1000 2016 1004 0 500-1000 1 \n1001 2016 1005 0 100-500 1 \n1002 2016 1006 0 100-500 0 \n1003 2016 1007 0 100-500 1 \n\n mh_coverage mh_coverage_awareness \\\n0 Not eligible for coverage / N/A I am not sure \n1 No Yes \n2 No I am not sure \n3 Yes Yes \n4 Yes I am not sure \n... ... ... \n999 I don't know I am not sure \n1000 Yes No \n1001 Yes Yes \n1002 I don't know I am not sure \n1003 Yes No \n\n mh_employer_discussion mh_resources_provided mh_anonimity ... age \\\n0 No No I don't know ... 39 \n1 Yes Yes Yes ... 29 \n2 No No I don't know ... 38 \n3 No No No ... 43 \n4 No Yes Yes ... 42 \n... ... ... ... ... .. \n999 No I don't know I don't know ... 26 \n1000 No No Yes ... 38 \n1001 Yes Yes I don't know ... 52 \n1002 No Yes I don't know ... 30 \n1003 No No I don't know ... 25 \n\n gender country_live live_us_state \\\n0 male United Kingdom none \n1 male United States of America Illinois \n2 male United Kingdom none \n3 female United States of America Illinois \n4 male United Kingdom none \n... ... ... ... \n999 female Canada none \n1000 female United States of America Illinois \n1001 male United States of America Georgia \n1002 female United States of America Nebraska \n1003 nonbinary Canada none \n\n country_work work_us_state \\\n0 United Kingdom none \n1 United States of America Illinois \n2 United Kingdom none \n3 United States of America Illinois \n4 United Kingdom none \n... ... ... \n999 Canada none \n1000 United States of America Illinois \n1001 United States of America Georgia \n1002 United States of America Nebraska \n1003 Canada none \n\n work_position remote \\\n0 Back-end Developer Sometimes \n1 Back-end Developer|Front-end Developer Never \n2 Back-end Developer Always \n3 Executive Leadership|Supervisor/Team Lead|Dev ... Sometimes \n4 DevOps/SysAdmin|Support|Back-end Developer|Fro... Sometimes \n... ... ... \n999 Other Sometimes \n1000 Support Always \n1001 Back-end Developer Sometimes \n1002 DevOps/SysAdmin Sometimes \n1003 Other Sometimes \n\n quantile_age_1 quantile_age_2 \n0 (38.0, 99.0] (37.0, 39.0] \n1 (28.0, 32.0] (27.0, 29.0] \n2 (32.0, 38.0] (37.0, 39.0] \n3 (38.0, 99.0] (39.0, 44.0] \n4 (38.0, 99.0] (39.0, 44.0] \n... ... ... \n999 (19.999, 28.0] (25.0, 27.0] \n1000 (32.0, 38.0] (37.0, 39.0] \n1001 (38.0, 99.0] (44.0, 99.0] \n1002 (28.0, 32.0] (29.0, 30.0] \n1003 (19.999, 28.0] (19.0, 25.0] \n\n[1004 rows x 55 columns]>\n"
],
[
"##Test:\n#Dataset filtered on tech_company = \"yes\"\n#Target: \n#Features: company_size, age, gender, country_live, identified_with_mh, mh_employer, employer_discus_mh, employer_provide_mh_coverage,treatment_mh_from_professional, employers_options_help, protected_anonymity_mh",
"_____no_output_____"
],
[
"# Filter tech_or_not columns:\nclean_2016_df[\"tech_company\"].head()",
"_____no_output_____"
],
[
"tech_df = pd.read_sql('SELECT * FROM \"survey_2016\" WHERE \"tech_company\" = 1', connect)\ntech_df.shape",
"_____no_output_____"
],
[
"ml_df = tech_df[[\"mh_sought_pro_tx\",\"mh_dx_pro\",\"company_size\",\"mh_discussion_coworkers\", \"mh_discussion_supervisors\",\"mh_employer_discussion\",\"prev_mh_discussion_coworkers\",\"prev_mh_discussion_supervisors\",\"mh_sharing_friends_family\"]]\nml_df",
"_____no_output_____"
],
[
"# Encode dataset:\n\n# Create label encoder instance:\nle = LabelEncoder()\n\n# Make a copy of desire data:\nencoded_df = ml_df.copy()\n\n# Apply encoder:\n#encoded_df[\"age\"] = le.fit_transform(encoded_df[\"age\"] )\n#encoded_df[\"company_size\"] = le.fit_transform(encoded_df[\"company_size\"])\n#encoded_df[\"gender\"] = le.fit_transform(encoded_df[\"gender\"])\n#encoded_df[\"country_live\"] = le.fit_transform(encoded_df[\"country_live\"])\n#encoded_df[\"identified_with_mh\"] = le.fit_transform(encoded_df[\"identified_with_mh\"])\n#encoded_df[\"dx_mh_disorder\"] = le.fit_transform(encoded_df[\"dx_mh_disorder\"])\n#encoded_df[\"employer_discus_mh\"] = le.fit_transform(encoded_df[\"employer_discus_mh\"])\n#encoded_df[\"mh_employer\"] = le.fit_transform(encoded_df[\"mh_employer\"])\n#encoded_df[\"treatment_mh_from_professional\"] = le.fit_transform(encoded_df[\"treatment_mh_from_professional\"])\n#encoded_df[\"employer_provide_mh_coverage\"] = le.fit_transform(encoded_df[\"employer_provide_mh_coverage\"])\n#encoded_df[\"employers_options_help\"] = le.fit_transform(encoded_df[\"employers_options_help\"])\n#encoded_df[\"protected_anonymity_mh\"] = le.fit_transform(encoded_df[\"protected_anonymity_mh\"])\n\nfeatures = encoded_df.columns.tolist()\nfor feature in features:\n encoded_df[feature] = le.fit_transform(encoded_df[feature])\n \n# Check:\nencoded_df.head()",
"_____no_output_____"
],
[
"from sklearn.preprocessing import OneHotEncoder\nencoder = OneHotEncoder(sparse = False)\n\nencoded_df1 = ml_df.copy()\n\n# Apply encoder:\nencoded_df1 = encoder.fit_transform(encoded_df1)\nencoded_df1",
"_____no_output_____"
],
[
"# Create our target:\ny = encoded_df[\"mh_sought_pro_tx\"]\n\n# Create our features:\nX = encoded_df.drop(columns = \"mh_sought_pro_tx\", axis =1)",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, \n y, \n random_state=40, \n stratify=y)\nX_train.shape",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(solver='lbfgs',\n max_iter=200,\n random_state=1)",
"_____no_output_____"
],
[
"classifier.fit(X_train, y_train)",
"_____no_output_____"
],
[
"y_pred = classifier.predict(X_test)\nresults = pd.DataFrame({\"Prediction\": y_pred, \"Actual\": y_test}).reset_index(drop=True)\nresults.head(20)\n",
"_____no_output_____"
],
[
"from sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test, y_pred))",
"0.859375\n"
],
[
"from sklearn.metrics import confusion_matrix, classification_report\nmatrix = confusion_matrix(y_test,y_pred)\nprint(matrix)",
"[[69 7]\n [20 96]]\n"
],
[
"report = classification_report(y_test, y_pred)\nprint(report)",
" precision recall f1-score support\n\n 0 0.78 0.91 0.84 76\n 1 0.93 0.83 0.88 116\n\n accuracy 0.86 192\n macro avg 0.85 0.87 0.86 192\nweighted avg 0.87 0.86 0.86 192\n\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a9389b8e13066c8640daaecf189ab29c904db5c
| 44,826 |
ipynb
|
Jupyter Notebook
|
site/en/guide/keras.ipynb
|
Papaass/docs
|
b3445700ccea4b2bdb1091284166c362923b923e
|
[
"Apache-2.0"
] | 1 |
2019-04-26T00:28:17.000Z
|
2019-04-26T00:28:17.000Z
|
site/en/guide/keras.ipynb
|
1272857430/docs
|
e785a902c34cf20fd47901dc07bac403d2df5c8e
|
[
"Apache-2.0"
] | 1 |
2019-04-24T12:17:40.000Z
|
2019-04-24T12:17:40.000Z
|
site/en/guide/keras.ipynb
|
1272857430/docs
|
e785a902c34cf20fd47901dc07bac403d2df5c8e
|
[
"Apache-2.0"
] | 2 |
2019-04-24T09:49:54.000Z
|
2019-04-24T11:37:47.000Z
| 32.83956 | 234 | 0.522152 |
[
[
[
"##### Copyright 2018 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Keras",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/keras\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/keras.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/guide/keras.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"Keras is a high-level API to build and train deep learning models. It's used for\nfast prototyping, advanced research, and production, with three key advantages:\n\n- *User friendly*<br>\n Keras has a simple, consistent interface optimized for common use cases. It\n provides clear and actionable feedback for user errors.\n- *Modular and composable*<br>\n Keras models are made by connecting configurable building blocks together,\n with few restrictions.\n- *Easy to extend*<br> Write custom building blocks to express new ideas for\n research. Create new layers, loss functions, and develop state-of-the-art\n models.",
"_____no_output_____"
],
[
"## Import tf.keras\n\n`tf.keras` is TensorFlow's implementation of the\n[Keras API specification](https://keras.io). This is a high-level\nAPI to build and train models that includes first-class support for\nTensorFlow-specific functionality, such as [eager execution](#eager_execution),\n`tf.data` pipelines, and [Estimators](./estimators.md).\n`tf.keras` makes TensorFlow easier to use without sacrificing flexibility and\nperformance.\n\nTo get started, import `tf.keras` as part of your TensorFlow program setup:",
"_____no_output_____"
]
],
[
[
"!pip install -q pyyaml # Required to save models in YAML format",
"_____no_output_____"
],
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\n\nprint(tf.VERSION)\nprint(tf.keras.__version__)",
"_____no_output_____"
]
],
[
[
"`tf.keras` can run any Keras-compatible code, but keep in mind:\n\n* The `tf.keras` version in the latest TensorFlow release might not be the same\n as the latest `keras` version from PyPI. Check `tf.keras.__version__`.\n* When [saving a model's weights](#weights_only), `tf.keras` defaults to the\n [checkpoint format](./checkpoints.md). Pass `save_format='h5'` to\n use HDF5.",
"_____no_output_____"
],
[
"## Build a simple model\n\n### Sequential model\n\nIn Keras, you assemble *layers* to build *models*. A model is (usually) a graph\nof layers. The most common type of model is a stack of layers: the\n`tf.keras.Sequential` model.\n\nTo build a simple, fully-connected network (i.e. multi-layer perceptron):",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential()\n# Adds a densely-connected layer with 64 units to the model:\nmodel.add(layers.Dense(64, activation='relu'))\n# Add another:\nmodel.add(layers.Dense(64, activation='relu'))\n# Add a softmax layer with 10 output units:\nmodel.add(layers.Dense(10, activation='softmax'))",
"_____no_output_____"
]
],
[
[
"### Configure the layers\n\nThere are many `tf.keras.layers` available with some common constructor\nparameters:\n\n* `activation`: Set the activation function for the layer. This parameter is\n specified by the name of a built-in function or as a callable object. By\n default, no activation is applied.\n* `kernel_initializer` and `bias_initializer`: The initialization schemes\n that create the layer's weights (kernel and bias). This parameter is a name or\n a callable object. This defaults to the `\"Glorot uniform\"` initializer.\n* `kernel_regularizer` and `bias_regularizer`: The regularization schemes\n that apply the layer's weights (kernel and bias), such as L1 or L2\n regularization. By default, no regularization is applied.\n\nThe following instantiates `tf.keras.layers.Dense` layers using constructor\narguments:",
"_____no_output_____"
]
],
[
[
"# Create a sigmoid layer:\nlayers.Dense(64, activation='sigmoid')\n# Or:\nlayers.Dense(64, activation=tf.sigmoid)\n\n# A linear layer with L1 regularization of factor 0.01 applied to the kernel matrix:\nlayers.Dense(64, kernel_regularizer=tf.keras.regularizers.l1(0.01))\n\n# A linear layer with L2 regularization of factor 0.01 applied to the bias vector:\nlayers.Dense(64, bias_regularizer=tf.keras.regularizers.l2(0.01))\n\n# A linear layer with a kernel initialized to a random orthogonal matrix:\nlayers.Dense(64, kernel_initializer='orthogonal')\n\n# A linear layer with a bias vector initialized to 2.0s:\nlayers.Dense(64, bias_initializer=tf.keras.initializers.constant(2.0))",
"_____no_output_____"
]
],
[
[
"## Train and evaluate\n\n### Set up training\n\nAfter the model is constructed, configure its learning process by calling the\n`compile` method:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([\n# Adds a densely-connected layer with 64 units to the model:\nlayers.Dense(64, activation='relu', input_shape=(32,)),\n# Add another:\nlayers.Dense(64, activation='relu'),\n# Add a softmax layer with 10 output units:\nlayers.Dense(10, activation='softmax')])\n\nmodel.compile(optimizer=tf.train.AdamOptimizer(0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"`tf.keras.Model.compile` takes three important arguments:\n\n* `optimizer`: This object specifies the training procedure. Pass it optimizer\n instances from the `tf.train` module, such as\n `tf.train.AdamOptimizer`, `tf.train.RMSPropOptimizer`, or\n `tf.train.GradientDescentOptimizer`.\n* `loss`: The function to minimize during optimization. Common choices include\n mean square error (`mse`), `categorical_crossentropy`, and\n `binary_crossentropy`. Loss functions are specified by name or by\n passing a callable object from the `tf.keras.losses` module.\n* `metrics`: Used to monitor training. These are string names or callables from\n the `tf.keras.metrics` module.\n\nThe following shows a few examples of configuring a model for training:",
"_____no_output_____"
]
],
[
[
"# Configure a model for mean-squared error regression.\nmodel.compile(optimizer=tf.train.AdamOptimizer(0.01),\n loss='mse', # mean squared error\n metrics=['mae']) # mean absolute error\n\n# Configure a model for categorical classification.\nmodel.compile(optimizer=tf.train.RMSPropOptimizer(0.01),\n loss=tf.keras.losses.categorical_crossentropy,\n metrics=[tf.keras.metrics.categorical_accuracy])",
"_____no_output_____"
]
],
[
[
"### Input NumPy data\n\nFor small datasets, use in-memory [NumPy](https://www.numpy.org/)\narrays to train and evaluate a model. The model is \"fit\" to the training data\nusing the `fit` method:",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\ndef random_one_hot_labels(shape):\n n, n_class = shape\n classes = np.random.randint(0, n_class, n)\n labels = np.zeros((n, n_class))\n labels[np.arange(n), classes] = 1\n return labels\n\ndata = np.random.random((1000, 32))\nlabels = random_one_hot_labels((1000, 10))\n\nmodel.fit(data, labels, epochs=10, batch_size=32)",
"_____no_output_____"
]
],
[
[
"`tf.keras.Model.fit` takes three important arguments:\n\n* `epochs`: Training is structured into *epochs*. An epoch is one iteration over\n the entire input data (this is done in smaller batches).\n* `batch_size`: When passed NumPy data, the model slices the data into smaller\n batches and iterates over these batches during training. This integer\n specifies the size of each batch. Be aware that the last batch may be smaller\n if the total number of samples is not divisible by the batch size.\n* `validation_data`: When prototyping a model, you want to easily monitor its\n performance on some validation data. Passing this argument—a tuple of inputs\n and labels—allows the model to display the loss and metrics in inference mode\n for the passed data, at the end of each epoch.\n\nHere's an example using `validation_data`:",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\ndata = np.random.random((1000, 32))\nlabels = random_one_hot_labels((1000, 10))\n\nval_data = np.random.random((100, 32))\nval_labels = random_one_hot_labels((100, 10))\n\nmodel.fit(data, labels, epochs=10, batch_size=32,\n validation_data=(val_data, val_labels))",
"_____no_output_____"
]
],
[
[
"### Input tf.data datasets\n\nUse the [Datasets API](./datasets.md) to scale to large datasets\nor multi-device training. Pass a `tf.data.Dataset` instance to the `fit`\nmethod:",
"_____no_output_____"
]
],
[
[
"# Instantiates a toy dataset instance:\ndataset = tf.data.Dataset.from_tensor_slices((data, labels))\ndataset = dataset.batch(32)\ndataset = dataset.repeat()\n\n# Don't forget to specify `steps_per_epoch` when calling `fit` on a dataset.\nmodel.fit(dataset, epochs=10, steps_per_epoch=30)",
"_____no_output_____"
]
],
[
[
"Here, the `fit` method uses the `steps_per_epoch` argument—this is the number of\ntraining steps the model runs before it moves to the next epoch. Since the\n`Dataset` yields batches of data, this snippet does not require a `batch_size`.\n\nDatasets can also be used for validation:",
"_____no_output_____"
]
],
[
[
"dataset = tf.data.Dataset.from_tensor_slices((data, labels))\ndataset = dataset.batch(32).repeat()\n\nval_dataset = tf.data.Dataset.from_tensor_slices((val_data, val_labels))\nval_dataset = val_dataset.batch(32).repeat()\n\nmodel.fit(dataset, epochs=10, steps_per_epoch=30,\n validation_data=val_dataset,\n validation_steps=3)",
"_____no_output_____"
]
],
[
[
"### Evaluate and predict\n\nThe `tf.keras.Model.evaluate` and `tf.keras.Model.predict` methods can use NumPy\ndata and a `tf.data.Dataset`.\n\nTo *evaluate* the inference-mode loss and metrics for the data provided:",
"_____no_output_____"
]
],
[
[
"data = np.random.random((1000, 32))\nlabels = random_one_hot_labels((1000, 10))\n\nmodel.evaluate(data, labels, batch_size=32)\n\nmodel.evaluate(dataset, steps=30)",
"_____no_output_____"
]
],
[
[
"And to *predict* the output of the last layer in inference for the data provided,\nas a NumPy array:",
"_____no_output_____"
]
],
[
[
"result = model.predict(data, batch_size=32)\nprint(result.shape)",
"_____no_output_____"
]
],
[
[
"## Build advanced models\n\n### Functional API\n\n The `tf.keras.Sequential` model is a simple stack of layers that cannot\nrepresent arbitrary models. Use the\n[Keras functional API](https://keras.io/getting-started/functional-api-guide/)\nto build complex model topologies such as:\n\n* Multi-input models,\n* Multi-output models,\n* Models with shared layers (the same layer called several times),\n* Models with non-sequential data flows (e.g. residual connections).\n\nBuilding a model with the functional API works like this:\n\n1. A layer instance is callable and returns a tensor.\n2. Input tensors and output tensors are used to define a `tf.keras.Model`\n instance.\n3. This model is trained just like the `Sequential` model.\n\nThe following example uses the functional API to build a simple, fully-connected\nnetwork:",
"_____no_output_____"
]
],
[
[
"inputs = tf.keras.Input(shape=(32,)) # Returns a placeholder tensor\n\n# A layer instance is callable on a tensor, and returns a tensor.\nx = layers.Dense(64, activation='relu')(inputs)\nx = layers.Dense(64, activation='relu')(x)\npredictions = layers.Dense(10, activation='softmax')(x)",
"_____no_output_____"
]
],
[
[
"Instantiate the model given inputs and outputs.",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Model(inputs=inputs, outputs=predictions)\n\n# The compile step specifies the training configuration.\nmodel.compile(optimizer=tf.train.RMSPropOptimizer(0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n# Trains for 5 epochs\nmodel.fit(data, labels, batch_size=32, epochs=5)",
"_____no_output_____"
]
],
[
[
"### Model subclassing\n\nBuild a fully-customizable model by subclassing `tf.keras.Model` and defining\nyour own forward pass. Create layers in the `__init__` method and set them as\nattributes of the class instance. Define the forward pass in the `call` method.\n\nModel subclassing is particularly useful when\n[eager execution](./eager.md) is enabled since the forward pass\ncan be written imperatively.\n\nKey Point: Use the right API for the job. While model subclassing offers\nflexibility, it comes at a cost of greater complexity and more opportunities for\nuser errors. If possible, prefer the functional API.\n\nThe following example shows a subclassed `tf.keras.Model` using a custom forward\npass:",
"_____no_output_____"
]
],
[
[
"class MyModel(tf.keras.Model):\n\n def __init__(self, num_classes=10):\n super(MyModel, self).__init__(name='my_model')\n self.num_classes = num_classes\n # Define your layers here.\n self.dense_1 = layers.Dense(32, activation='relu')\n self.dense_2 = layers.Dense(num_classes, activation='sigmoid')\n\n def call(self, inputs):\n # Define your forward pass here,\n # using layers you previously defined (in `__init__`).\n x = self.dense_1(inputs)\n return self.dense_2(x)\n\n def compute_output_shape(self, input_shape):\n # You need to override this function if you want to use the subclassed model\n # as part of a functional-style model.\n # Otherwise, this method is optional.\n shape = tf.TensorShape(input_shape).as_list()\n shape[-1] = self.num_classes\n return tf.TensorShape(shape)",
"_____no_output_____"
]
],
[
[
"Instantiate the new model class:",
"_____no_output_____"
]
],
[
[
"model = MyModel(num_classes=10)\n\n# The compile step specifies the training configuration.\nmodel.compile(optimizer=tf.train.RMSPropOptimizer(0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n# Trains for 5 epochs.\nmodel.fit(data, labels, batch_size=32, epochs=5)",
"_____no_output_____"
]
],
[
[
"### Custom layers\n\nCreate a custom layer by subclassing `tf.keras.layers.Layer` and implementing\nthe following methods:\n\n* `build`: Create the weights of the layer. Add weights with the `add_weight`\n method.\n* `call`: Define the forward pass.\n* `compute_output_shape`: Specify how to compute the output shape of the layer\n given the input shape.\n* Optionally, a layer can be serialized by implementing the `get_config` method\n and the `from_config` class method.\n\nHere's an example of a custom layer that implements a `matmul` of an input with\na kernel matrix:",
"_____no_output_____"
]
],
[
[
"class MyLayer(layers.Layer):\n\n def __init__(self, output_dim, **kwargs):\n self.output_dim = output_dim\n super(MyLayer, self).__init__(**kwargs)\n\n def build(self, input_shape):\n shape = tf.TensorShape((input_shape[1], self.output_dim))\n # Create a trainable weight variable for this layer.\n self.kernel = self.add_weight(name='kernel',\n shape=shape,\n initializer='uniform',\n trainable=True)\n # Make sure to call the `build` method at the end\n super(MyLayer, self).build(input_shape)\n\n def call(self, inputs):\n return tf.matmul(inputs, self.kernel)\n\n def compute_output_shape(self, input_shape):\n shape = tf.TensorShape(input_shape).as_list()\n shape[-1] = self.output_dim\n return tf.TensorShape(shape)\n\n def get_config(self):\n base_config = super(MyLayer, self).get_config()\n base_config['output_dim'] = self.output_dim\n return base_config\n\n @classmethod\n def from_config(cls, config):\n return cls(**config)",
"_____no_output_____"
]
],
[
[
"Create a model using your custom layer:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([\n MyLayer(10),\n layers.Activation('softmax')])\n\n# The compile step specifies the training configuration\nmodel.compile(optimizer=tf.train.RMSPropOptimizer(0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n# Trains for 5 epochs.\nmodel.fit(data, labels, batch_size=32, epochs=5)",
"_____no_output_____"
]
],
[
[
"## Callbacks\n\nA callback is an object passed to a model to customize and extend its behavior\nduring training. You can write your own custom callback, or use the built-in\n`tf.keras.callbacks` that include:\n\n* `tf.keras.callbacks.ModelCheckpoint`: Save checkpoints of your model at\n regular intervals.\n* `tf.keras.callbacks.LearningRateScheduler`: Dynamically change the learning\n rate.\n* `tf.keras.callbacks.EarlyStopping`: Interrupt training when validation\n performance has stopped improving.\n* `tf.keras.callbacks.TensorBoard`: Monitor the model's behavior using\n [TensorBoard](./summaries_and_tensorboard.md).\n\nTo use a `tf.keras.callbacks.Callback`, pass it to the model's `fit` method:",
"_____no_output_____"
]
],
[
[
"callbacks = [\n # Interrupt training if `val_loss` stops improving for over 2 epochs\n tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),\n # Write TensorBoard logs to `./logs` directory\n tf.keras.callbacks.TensorBoard(log_dir='./logs')\n]\nmodel.fit(data, labels, batch_size=32, epochs=5, callbacks=callbacks,\n validation_data=(val_data, val_labels))",
"_____no_output_____"
]
],
[
[
"<a id='weights_only'></a>\n## Save and restore",
"_____no_output_____"
],
[
"### Weights only\n\nSave and load the weights of a model using `tf.keras.Model.save_weights`:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([\nlayers.Dense(64, activation='relu', input_shape=(32,)),\nlayers.Dense(10, activation='softmax')])\n\nmodel.compile(optimizer=tf.train.AdamOptimizer(0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"# Save weights to a TensorFlow Checkpoint file\nmodel.save_weights('./weights/my_model')\n\n# Restore the model's state,\n# this requires a model with the same architecture.\nmodel.load_weights('./weights/my_model')",
"_____no_output_____"
]
],
[
[
"By default, this saves the model's weights in the\n[TensorFlow checkpoint](./checkpoints.md) file format. Weights can\nalso be saved to the Keras HDF5 format (the default for the multi-backend\nimplementation of Keras):",
"_____no_output_____"
]
],
[
[
"# Save weights to a HDF5 file\nmodel.save_weights('my_model.h5', save_format='h5')\n\n# Restore the model's state\nmodel.load_weights('my_model.h5')",
"_____no_output_____"
]
],
[
[
"### Configuration only\n\nA model's configuration can be saved—this serializes the model architecture\nwithout any weights. A saved configuration can recreate and initialize the same\nmodel, even without the code that defined the original model. Keras supports\nJSON and YAML serialization formats:",
"_____no_output_____"
]
],
[
[
"# Serialize a model to JSON format\njson_string = model.to_json()\njson_string",
"_____no_output_____"
],
[
"import json\nimport pprint\npprint.pprint(json.loads(json_string))",
"_____no_output_____"
]
],
[
[
"Recreate the model (newly initialized) from the JSON:",
"_____no_output_____"
]
],
[
[
"fresh_model = tf.keras.models.model_from_json(json_string)",
"_____no_output_____"
]
],
[
[
"Serializing a model to YAML format requires that you install `pyyaml` *before you import TensorFlow*:",
"_____no_output_____"
]
],
[
[
"yaml_string = model.to_yaml()\nprint(yaml_string)",
"_____no_output_____"
]
],
[
[
"Recreate the model from the YAML:",
"_____no_output_____"
]
],
[
[
"fresh_model = tf.keras.models.model_from_yaml(yaml_string)",
"_____no_output_____"
]
],
[
[
"Caution: Subclassed models are not serializable because their architecture is\ndefined by the Python code in the body of the `call` method.",
"_____no_output_____"
],
[
"\n### Entire model\n\nThe entire model can be saved to a file that contains the weight values, the\nmodel's configuration, and even the optimizer's configuration. This allows you\nto checkpoint a model and resume training later—from the exact same\nstate—without access to the original code.",
"_____no_output_____"
]
],
[
[
"# Create a trivial model\nmodel = tf.keras.Sequential([\n layers.Dense(10, activation='softmax', input_shape=(32,)),\n layers.Dense(10, activation='softmax')\n])\nmodel.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\nmodel.fit(data, labels, batch_size=32, epochs=5)\n\n\n# Save entire model to a HDF5 file\nmodel.save('my_model.h5')\n\n# Recreate the exact same model, including weights and optimizer.\nmodel = tf.keras.models.load_model('my_model.h5')",
"_____no_output_____"
]
],
[
[
"## Eager execution\n\n[Eager execution](./eager.md) is an imperative programming\nenvironment that evaluates operations immediately. This is not required for\nKeras, but is supported by `tf.keras` and useful for inspecting your program and\ndebugging.\n\nAll of the `tf.keras` model-building APIs are compatible with eager execution.\nAnd while the `Sequential` and functional APIs can be used, eager execution\nespecially benefits *model subclassing* and building *custom layers*—the APIs\nthat require you to write the forward pass as code (instead of the APIs that\ncreate models by assembling existing layers).\n\nSee the [eager execution guide](./eager.md#build_a_model) for\nexamples of using Keras models with custom training loops and `tf.GradientTape`.",
"_____no_output_____"
],
[
"## Distribution\n\n### Estimators\n\nThe [Estimators](./estimators.md) API is used for training models\nfor distributed environments. This targets industry use cases such as\ndistributed training on large datasets that can export a model for production.\n\nA `tf.keras.Model` can be trained with the `tf.estimator` API by converting the\nmodel to an `tf.estimator.Estimator` object with\n`tf.keras.estimator.model_to_estimator`. See\n[Creating Estimators from Keras models](./estimators.md#creating_estimators_from_keras_models).",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([layers.Dense(10,activation='softmax'),\n layers.Dense(10,activation='softmax')])\n\nmodel.compile(optimizer=tf.train.RMSPropOptimizer(0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nestimator = tf.keras.estimator.model_to_estimator(model)",
"_____no_output_____"
]
],
[
[
"Note: Enable [eager execution](./eager.md) for debugging\n[Estimator input functions](./premade_estimators.md#create_input_functions)\nand inspecting data.",
"_____no_output_____"
],
[
"### Multiple GPUs\n\n`tf.keras` models can run on multiple GPUs using\n`tf.contrib.distribute.DistributionStrategy`. This API provides distributed\ntraining on multiple GPUs with almost no changes to existing code.\n\nCurrently, `tf.contrib.distribute.MirroredStrategy` is the only supported\ndistribution strategy. `MirroredStrategy` does in-graph replication with\nsynchronous training using all-reduce on a single machine. To use\n`DistributionStrategy` with Keras, convert the `tf.keras.Model` to a\n`tf.estimator.Estimator` with `tf.keras.estimator.model_to_estimator`, then\ntrain the estimator\n\nThe following example distributes a `tf.keras.Model` across multiple GPUs on a\nsingle machine.\n\nFirst, define a simple model:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential()\nmodel.add(layers.Dense(16, activation='relu', input_shape=(10,)))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\noptimizer = tf.train.GradientDescentOptimizer(0.2)\n\nmodel.compile(loss='binary_crossentropy', optimizer=optimizer)\nmodel.summary()",
"_____no_output_____"
]
],
[
[
"Define an *input pipeline*. The `input_fn` returns a `tf.data.Dataset` object\nused to distribute the data across multiple devices—with each device processing\na slice of the input batch.",
"_____no_output_____"
]
],
[
[
"def input_fn():\n x = np.random.random((1024, 10))\n y = np.random.randint(2, size=(1024, 1))\n x = tf.cast(x, tf.float32)\n dataset = tf.data.Dataset.from_tensor_slices((x, y))\n dataset = dataset.repeat(10)\n dataset = dataset.batch(32)\n return dataset",
"_____no_output_____"
]
],
[
[
"Next, create a `tf.estimator.RunConfig` and set the `train_distribute` argument\nto the `tf.contrib.distribute.MirroredStrategy` instance. When creating\n`MirroredStrategy`, you can specify a list of devices or set the `num_gpus`\nargument. The default uses all available GPUs, like the following:",
"_____no_output_____"
]
],
[
[
"strategy = tf.contrib.distribute.MirroredStrategy()\nconfig = tf.estimator.RunConfig(train_distribute=strategy)",
"_____no_output_____"
]
],
[
[
"Convert the Keras model to a `tf.estimator.Estimator` instance:",
"_____no_output_____"
]
],
[
[
"keras_estimator = tf.keras.estimator.model_to_estimator(\n keras_model=model,\n config=config,\n model_dir='/tmp/model_dir')",
"_____no_output_____"
]
],
[
[
"Finally, train the `Estimator` instance by providing the `input_fn` and `steps`\narguments:",
"_____no_output_____"
]
],
[
[
"keras_estimator.train(input_fn=input_fn, steps=10)",
"_____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",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4a93a075ff0299d10ef7fea4cdb1f45b02af4ed0
| 66,973 |
ipynb
|
Jupyter Notebook
|
histogram.ipynb
|
akshhpatil/Matplotlib-demo
|
5efbef7956588dffe4f6dd99a43e8b70281d00b8
|
[
"MIT"
] | 1 |
2021-04-22T15:23:09.000Z
|
2021-04-22T15:23:09.000Z
|
histogram.ipynb
|
akshhpatil/Matplotlib-demo
|
5efbef7956588dffe4f6dd99a43e8b70281d00b8
|
[
"MIT"
] | null | null | null |
histogram.ipynb
|
akshhpatil/Matplotlib-demo
|
5efbef7956588dffe4f6dd99a43e8b70281d00b8
|
[
"MIT"
] | null | null | null | 287.437768 | 23,356 | 0.931286 |
[
[
[
"# ploting histograms",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt \nimport numpy as np \nimport random ",
"_____no_output_____"
],
[
"m_stud_age = np.random.randint( 18,45, (100)) # age between 18 to 45 and 100 student \ndata_sci_stude =np.random.randint( 20,40, (100)) # age between 20 to 40 and 100 student \n \n ",
"_____no_output_____"
],
[
"print(m_stud_age)\nprint(data_sci_stude)",
"[22 44 24 24 41 29 31 26 29 40 44 41 32 43 30 30 41 34 23 39 44 27 20 43\n 29 41 39 30 24 35 30 36 28 23 26 32 39 29 43 28 19 24 36 29 19 41 42 36\n 39 28 27 37 29 35 24 42 23 43 41 27 31 22 31 44 43 30 23 35 44 37 40 26\n 22 41 20 31 19 37 42 42 21 31 27 26 42 21 23 30 44 43 29 40 37 36 32 20\n 27 29 23 19]\n[39 28 36 27 25 27 30 33 28 28 27 33 36 34 32 25 39 35 20 36 35 38 23 25\n 39 25 31 20 28 37 25 31 39 38 29 25 33 23 25 29 22 30 30 38 29 28 33 38\n 32 32 37 24 30 37 28 35 23 23 21 27 38 35 32 32 28 23 27 34 32 39 32 22\n 38 33 27 21 31 28 38 28 36 35 37 32 22 37 38 25 38 32 24 27 21 20 32 39\n 26 37 36 26]\n"
],
[
"plt.hist(m_stud_age )\n\nplt.title(\"Machine learning student histogram\")\nplt.xlabel(\"Student age \")\nplt.ylabel(\"no of student age\")\nplt.show()",
"_____no_output_____"
],
[
"bins = [ 15,20,25,30,35,40,45]",
"_____no_output_____"
],
[
"plt.hist(m_stud_age,bins ,rwidth = 0.8 , color = 'm' ,label = \"ML student\")\n\nplt.title(\"Machine learning student histogram\")\nplt.xlabel(\"Student age \")\nplt.ylabel(\"no of student age\")\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"plt.figure(figsize = (15,9)) # increase the value of histogram\n\nplt.hist([m_stud_age,data_sci_stude], bins ,rwidth = 0.7 , color = ['m','y'] ,label = [\"ML student\",\"data sc stud \"])\n\n#plt.hist(data_sci_stude,bins ,rwidth = 0.7 , color = 'y' ,label = \"data sc stud\")\n\n\nplt.title(\"Machine learning student histogram\")\nplt.xlabel(\"Student age \")\nplt.ylabel(\"no of student age\")\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"from matplotlib import style\n\nstyle.use(\"ggplot\")\n\nplt.figure(figsize = (15,9)) # increase the value of histogram\n\nplt.hist([m_stud_age,data_sci_stude], bins ,rwidth = 0.7 , color = ['m','y'] ,label = [\"ML student\",\"data sc stud \"])\n\n#plt.hist(data_sci_stude,bins ,rwidth = 0.7 , color = 'y' ,label = \"data sc stud\")\n\n\nplt.title(\"Machine learning student histogram\")\nplt.xlabel(\"Student age \")\nplt.ylabel(\"no of student age\")\n#plt.grid(color='y')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a93a2ef3ac4ff980da3c4f6d8b7e5269c701269
| 5,458 |
ipynb
|
Jupyter Notebook
|
Algorithms/mElo Algo - Biscuits.ipynb
|
christiangilson/MSc-Applied-Statistics-Project-Code
|
f1aeed8864cf506c88c9236345934aed528d81d5
|
[
"MIT"
] | 4 |
2021-09-02T10:18:25.000Z
|
2021-09-24T21:08:34.000Z
|
Algorithms/mElo Algo - Biscuits.ipynb
|
christiangilson/MSc-Applied-Statistics-Project-Code
|
f1aeed8864cf506c88c9236345934aed528d81d5
|
[
"MIT"
] | null | null | null |
Algorithms/mElo Algo - Biscuits.ipynb
|
christiangilson/MSc-Applied-Statistics-Project-Code
|
f1aeed8864cf506c88c9236345934aed528d81d5
|
[
"MIT"
] | null | null | null | 24.150442 | 132 | 0.482228 |
[
[
[
"import math\nimport numpy as np\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"### Initial conditions",
"_____no_output_____"
]
],
[
[
"initial_rating = 400\nk = 100\n\nthings = ['Malted Milk','Rich Tea','Hobnob','Digestive']",
"_____no_output_____"
]
],
[
[
"### Elo Algos",
"_____no_output_____"
]
],
[
[
"def expected_win(r1, r2):\n \"\"\"\n Expected probability of player 1 beating player 2\n if player 1 has rating 1 (r1) and player 2 has rating 2 (r2)\n \"\"\"\n return 1.0 / (1 + math.pow(10, (r2-r1)/400))\n\ndef update_rating(R, k, P, d):\n \"\"\"\n d = 1 = WIN\n d = 0 = LOSS\n \"\"\"\n return R + k*(d-P)",
"_____no_output_____"
],
[
"def elo(Ra, Rb, k, d):\n \"\"\"\n d = 1 when player A wins\n d = 0 when player B wins\n \"\"\"\n \n Pa = expected_win(Ra, Rb)\n Pb = expected_win(Rb, Ra)\n \n # update if A wins\n if d == 1:\n Ra = update_rating(Ra, k, Pa, d)\n Rb = update_rating(Rb, k, Pb, d-1)\n \n # update if B wins\n elif d == 0:\n Ra = update_rating(Ra, k, Pa, d)\n Rb = update_rating(Rb, k, Pb, d+1)\n \n return Pa, Pb, Ra, Rb",
"_____no_output_____"
],
[
"def elo_sequence(things, initial_rating, k, results):\n \"\"\"\n Initialises score dictionary, and runs through sequence of pairwise results, returning final dictionary of Elo rankings\n \"\"\"\n\n dic_scores = {i:initial_rating for i in things}\n\n for result in results:\n\n winner, loser = result\n Ra, Rb = dic_scores[winner], dic_scores[loser]\n _, _, newRa, newRb = elo(Ra, Rb, k, 1)\n dic_scores[winner], dic_scores[loser] = newRa, newRb\n\n return dic_scores",
"_____no_output_____"
]
],
[
[
"### Mean Elo",
"_____no_output_____"
]
],
[
[
"def mElo(things, initial_rating, k, results, numEpochs):\n \"\"\"\n Randomises the sequence of the pairwise comparisons, running the Elo sequence in a random\n sequence for a number of epochs\n \n Returns the mean Elo ratings over the randomised epoch sequences\n \"\"\"\n \n lst_outcomes = []\n \n for i in np.arange(numEpochs):\n np.random.shuffle(results)\n lst_outcomes.append(elo_sequence(things, initial_rating, k, results))\n \n return pd.DataFrame(lst_outcomes).mean().sort_values(ascending=False)\n ",
"_____no_output_____"
]
],
[
[
"### Pairwise Outcomes from Christian's Taste Test\n\n> **Format** (Winner, Loser)",
"_____no_output_____"
]
],
[
[
"results = np.array([('Malted Milk','Rich Tea'),('Malted Milk','Digestive'),('Malted Milk','Hobnob')\\\n ,('Hobnob','Rich Tea'),('Hobnob','Digestive'),('Digestive','Rich Tea')])",
"_____no_output_____"
],
[
"jenResults = np.array([('Rich Tea','Malted Milk'),('Digestive','Malted Milk'),('Hobnob','Malted Milk')\\\n ,('Hobnob','Rich Tea'),('Hobnob','Digestive'),('Digestive','Rich Tea')])",
"_____no_output_____"
],
[
"mElo(things, initial_rating, k, jenResults, 1000)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a93afb96846dab6cd0b9edf8027bae3f95623a6
| 769,244 |
ipynb
|
Jupyter Notebook
|
juno_EDA.ipynb
|
Junhojuno/San-Francisco-Crime
|
174a28a3f7326d1c0e5cb4e8e77f527acab02ae9
|
[
"MIT"
] | null | null | null |
juno_EDA.ipynb
|
Junhojuno/San-Francisco-Crime
|
174a28a3f7326d1c0e5cb4e8e77f527acab02ae9
|
[
"MIT"
] | null | null | null |
juno_EDA.ipynb
|
Junhojuno/San-Francisco-Crime
|
174a28a3f7326d1c0e5cb4e8e77f527acab02ae9
|
[
"MIT"
] | null | null | null | 139.989809 | 117,252 | 0.821156 |
[
[
[
"##### 1. Dates (사건일자)\n: timestamp of the crime incident\n##### 2. Category (범죄유형 - 종속변수)\n: category of the crime incident (only in train.csv). This is the target variable you are going to predict.\n##### 3. Descript (범죄 세부정보)\n: detailed description of the crime incident (only in train.csv)\n##### 4. DayOfWeek (요일)\n: the day of the week\n##### 5. PdDistrict (관할서)\n: name of the Police Department District\n##### 6. Resolution (처벌결과)\n: how the crime incident was resolved (only in train.csv)\n##### 7. Address (사건현장 대략적 주소)\n: the approximate street address of the crime incident \n##### 8. X (경도)\n:Longitude\n##### 9. Y (위도)\n: Latitude",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"train.csv\", parse_dates=['Dates'])\n# 연,월,주차,시간(1시간단위)\ndf['year'] = df['Dates'].map(lambda x: x.year)\ndf['month'] = df['Dates'].map(lambda x: x.month)\ndf['week'] = df['Dates'].map(lambda x: x.week)\ndf['hour'] = df['Dates'].map(lambda x: x.hour)\ndf.tail()",
"_____no_output_____"
],
[
"for i in df.columns:\n print(i, \"\\n\", df[i].unique(), len(df[i].unique()))",
"Dates \n ['2015-05-13T23:53:00.000000000' '2015-05-13T23:33:00.000000000'\n '2015-05-13T23:30:00.000000000' ..., '2003-01-06T00:20:00.000000000'\n '2003-01-06T00:15:00.000000000' '2003-01-06T00:01:00.000000000'] 389257\nCategory \n ['WARRANTS' 'OTHER OFFENSES' 'LARCENY/THEFT' 'VEHICLE THEFT' 'VANDALISM'\n 'NON-CRIMINAL' 'ROBBERY' 'ASSAULT' 'WEAPON LAWS' 'BURGLARY'\n 'SUSPICIOUS OCC' 'DRUNKENNESS' 'FORGERY/COUNTERFEITING' 'DRUG/NARCOTIC'\n 'STOLEN PROPERTY' 'SECONDARY CODES' 'TRESPASS' 'MISSING PERSON' 'FRAUD'\n 'KIDNAPPING' 'RUNAWAY' 'DRIVING UNDER THE INFLUENCE'\n 'SEX OFFENSES FORCIBLE' 'PROSTITUTION' 'DISORDERLY CONDUCT' 'ARSON'\n 'FAMILY OFFENSES' 'LIQUOR LAWS' 'BRIBERY' 'EMBEZZLEMENT' 'SUICIDE'\n 'LOITERING' 'SEX OFFENSES NON FORCIBLE' 'EXTORTION' 'GAMBLING'\n 'BAD CHECKS' 'TREA' 'RECOVERED VEHICLE' 'PORNOGRAPHY/OBSCENE MAT'] 39\nDescript \n ['WARRANT ARREST' 'TRAFFIC VIOLATION ARREST' 'GRAND THEFT FROM LOCKED AUTO'\n 'GRAND THEFT FROM UNLOCKED AUTO' 'STOLEN AUTOMOBILE'\n 'PETTY THEFT FROM LOCKED AUTO' 'MISCELLANEOUS INVESTIGATION'\n 'MALICIOUS MISCHIEF, VANDALISM OF VEHICLES' 'FOUND PROPERTY'\n 'ROBBERY, ARMED WITH A KNIFE' 'AGGRAVATED ASSAULT WITH BODILY FORCE'\n 'TRAFFIC VIOLATION' 'ROBBERY, BODILY FORCE'\n 'STAY AWAY OR COURT ORDER, NON-DV RELATED' 'LOST PROPERTY'\n 'ATTEMPTED THEFT FROM LOCKED VEHICLE' 'CIVIL SIDEWALKS, CITATION'\n 'MALICIOUS MISCHIEF, VANDALISM' 'SUSPICIOUS PACKAGE'\n 'AIDED CASE, MENTAL DISTURBED' 'PETTY THEFT SHOPLIFTING'\n 'PROBATION VIOLATION' 'STAY AWAY ORDER VIOLATION, DV RELATED'\n 'DRIVERS LICENSE, SUSPENDED OR REVOKED' 'STOLEN MOTORCYCLE'\n 'GRAND THEFT FROM PERSON' 'BURGLARY, VEHICLE (ARREST MADE)'\n 'ATTEMPTED ROBBERY ON THE STREET WITH BODILY FORCE'\n 'PETTY THEFT FROM A BUILDING' 'INVESTIGATIVE DETENTION'\n 'GRAND THEFT OF PROPERTY' 'STOLEN AND RECOVERED VEHICLE'\n 'UNDER INFLUENCE OF ALCOHOL IN A PUBLIC PLACE' 'ENROUTE TO PAROLE OFFICER'\n 'ENROUTE TO OUTSIDE JURISDICTION'\n 'EXHIBITING DEADLY WEAPON IN A THREATING MANNER'\n 'GRAND THEFT FROM A BUILDING'\n 'BURGLARY OF RESIDENCE, ATTEMPTED FORCIBLE ENTRY'\n 'PETTY THEFT OF PROPERTY' 'BURGLARY OF APARTMENT HOUSE, UNLAWFUL ENTRY'\n 'FORGERY, NOTES' 'CHECKS, POSSESSION WITH INTENT TO PASS'\n 'BURGLARY,STORE UNDER CONSTRUCTION, UNLAWFUL ENTRY'\n 'GRAND THEFT SHOPLIFTING' 'POSSESSION OF NARCOTICS PARAPHERNALIA'\n 'RESISTING ARREST' 'CHILD ABUSE (PHYSICAL)'\n 'STOLEN PROPERTY, POSSESSION WITH KNOWLEDGE, RECEIVING'\n 'DOMESTIC VIOLENCE' 'THREATS AGAINST LIFE' 'AIDED CASE' 'TRESPASSING'\n 'BURGLARY OF HOTEL ROOM, UNLAWFUL ENTRY' 'POSSESSION OF MARIJUANA'\n 'LOST/STOLEN LICENSE PLATE'\n 'BURGLARY,BLDG. UNDER CONSTRUCTION, UNLAWFUL ENTRY'\n 'ROBBERY OF A COMMERCIAL ESTABLISHMENT W/ A KNIFE'\n 'FORGERY & COUNTERFEITING (GENERAL)'\n 'FRAUDULENT GAME OR TRICK, OBTAINING MONEY OR PROPERTY' 'STOLEN TRUCK'\n 'MISSING JUVENILE' 'RECKLESS DRIVING'\n 'ROBBERY, ARMED WITH A DANGEROUS WEAPON' 'VIOLATION OF RESTRAINING ORDER'\n 'JUVENILE INVOLVED' 'BATTERY, FORMER SPOUSE OR DATING RELATIONSHIP'\n 'TRAFFIC ACCIDENT' 'SHOOTING INTO INHABITED DWELLING OR OCCUPIED VEHICLE'\n 'SUSPICIOUS OCCURRENCE' 'BURGLARY, HOT PROWL, UNLAWFUL ENTRY'\n 'ENROUTE TO DEPARTMENT OF CORRECTIONS' 'POSSESSION OF MARIJUANA FOR SALES'\n 'SALE OF MARIJUANA' 'BURGLARY, HOT PROWL, ATTEMPTED FORCIBLE ENTRY'\n 'VIOLATION OF MUNICIPAL CODE' 'PAROLE VIOLATION' 'BATTERY'\n 'BURGLARY OF APARTMENT HOUSE, FORCIBLE ENTRY'\n 'BURGLARY OF RESIDENCE, FORCIBLE ENTRY'\n 'ROBBERY OF A CHAIN STORE WITH A DANGEROUS WEAPON'\n 'AGGRAVATED ASSAULT WITH A DEADLY WEAPON' 'POSSESSION OF METH-AMPHETAMINE'\n 'ROBBERY OF A BANK WITH A DANGEROUS WEAPON' 'BURGLARY, UNLAWFUL ENTRY'\n 'THEFT OF ANIMALS (GENERAL)' 'AGGRAVATED ASSAULT WITH A KNIFE'\n 'CREDIT CARD, THEFT BY USE OF' 'AIDED CASE -PROPERTY FOR DESTRUCTION'\n 'FALSE IMPRISONMENT' 'ROBBERY ON THE STREET, STRONGARM'\n 'SUSPICIOUS PERSON' 'PETTY THEFT BICYCLE' 'MISSING ADULT' 'FOUND PERSON'\n 'RUNAWAY' 'LOITERING WHERE NARCOTICS ARE SOLD/USED'\n 'HARASSING PHONE CALLS' 'INCIDENT ON SCHOOL GROUNDS' 'GRAND THEFT BICYCLE'\n 'ATTEMPTED THEFT OF A BICYCLE' 'VIOLATION OF PARK CODE'\n 'ATTEMPTED ROBBERY ON THE STREET W/DEADLY WEAPON'\n 'ATTEMPTED GRAND THEFT PURSESNATCH' 'ATTEMPTED ROBBERY WITH BODILY FORCE'\n 'BURGLARY OF STORE, FORCIBLE ENTRY'\n 'POSSESSION OF BURGLARY TOOLS W/PRIORS' 'KIDNAPPING DURING ROBBERY'\n 'ROBBERY, ATM, GUN' 'CONSPIRACY'\n 'RESTRAINING ORDER NOTIFICATION/SERVICE OF RESTRAINING ORDER'\n 'AIDED CASE, INJURED PERSON'\n 'DRIVING WHILE UNDER THE INFLUENCE OF ALCOHOL'\n 'INFLICT INJURY ON COHABITEE' 'DISCHARGE FIREARM AT AN INHABITED DWELLING'\n 'ROBBERY OF A CHAIN STORE WITH A GUN' 'PENETRATION, FORCED, WITH OBJECT'\n 'ORAL COPULATION, UNLAWFUL (ADULT VICTIM)'\n 'FRAUDULENT USE OF AUTOMATED TELLER CARD' 'ATM RELATED CRIME'\n 'TAMPERING WITH A VEHICLE' 'FORGERY, CREDIT CARD'\n 'THEFT OF COMPUTERS OR CELL PHONES' 'AIDED CASE, SICK PERSON'\n 'ENGAGING IN LEWD CONDUCT - PROSTITUTION RELATED' 'POSSESSION OF HEROIN'\n 'ASSAULT WITH CAUSTIC CHEMICALS' 'VIOLATION OF MUNICIPAL POLICE CODE'\n 'BURGLARY, HOT PROWL, FORCIBLE ENTRY'\n 'MALICIOUS MISCHIEF, BREAKING WINDOWS'\n 'ATTEMPTED ROBBERY OF A BANK WITH BODILY FORCE' 'FALSE PERSONATION'\n 'ATTEMPTED ROBBERY WITH A DEADLY WEAPON' 'AGGRAVATED ASSAULT WITH A GUN'\n 'ASSAULT, AGGRAVATED, W/ GUN'\n 'POSSESSION OF CONTROLLED SUBSTANCE FOR SALE' 'BURGLARY, FORCIBLE ENTRY'\n 'GRAND THEFT PICKPOCKET'\n 'ELDER ADULT OR DEPENDENT ABUSE (NOT EMBEZZLEMENT OR THEFT)'\n 'BURGLARY OF APARTMENT HOUSE, ATT FORCIBLE ENTRY'\n 'ROBBERY OF A CHAIN STORE WITH A KNIFE'\n 'BURGLARY OF STORE, UNLAWFUL ENTRY' 'FIRE REPORT' 'DISTURBING THE PEACE'\n 'DEATH REPORT, CAUSE UNKNOWN' 'PETTY THEFT FROM UNLOCKED AUTO'\n 'BURGLARY OF RESIDENCE, UNLAWFUL ENTRY' 'BURGLARY OF FLAT, UNLAWFUL ENTRY'\n 'MONEY, CHANGING FACE AMOUNT'\n 'BURGLARY,STORE UNDER CONSTRUCTION, FORCIBLE ENTRY' 'ARSON OF A VEHICLE'\n 'POSSESSION OF BURGLARY TOOLS' 'BURGLARY, VEHICLE, ATT. (ARREST MADE)'\n 'TRESPASS WITHIN 30 DAYS OF CREDIBLE THREAT'\n 'UNDER INFLUENCE OF DRUGS IN A PUBLIC PLACE' 'SODOMY (ADULT VICTIM)'\n 'BATTERY OF A POLICE OFFICER'\n 'FORGERY, POSSESSION DRIVERS LICENSE OR ID-CARD'\n 'MALICIOUS MISCHIEF, GRAFFITI' 'VANDALISM OR GRAFFITI TOOLS, POSSESSION'\n 'LOCATED PROPERTY' 'POSS OF LOADED FIREARM' 'FALSE PRETENSES, GRAND THEFT'\n 'CREDIT CARD, THEFT OF' 'AIDED CASE, DOG BITE'\n 'THEFT FROM MERCHANT OR LIBRARY' 'PROBATION SEARCH'\n 'ATTEMPTED ROBBERY RESIDENCE WITH BODILY FORCE'\n 'POSS OF FIREARM BY CONVICTED FELON/ADDICT/ALIEN'\n 'FIREARM, LOADED, IN VEHICLE, POSSESSION OR USE'\n 'CARRYING A CONCEALED WEAPON' 'MINOR WITHOUT PROPER PARENTAL CARE'\n 'FRAUDULENT CREDIT APPLICATION'\n 'FALSE PERSONATION TO RECEIVE MONEY OR PROPERTY'\n 'POSSESSION OF CONTROLLED SUBSTANCE' 'SEXUAL BATTERY'\n 'TRAFFIC COLLISION, HIT & RUN, INJURY' 'COUNTERFEITING, COINS OR NOTES'\n 'POSSESSION OF BASE/ROCK COCAINE FOR SALE' 'GANG ACTIVITY'\n 'ATTEMPTED HOMICIDE WITH A GUN' 'SEARCH WARRANT SERVICE' 'CHILD STEALING'\n 'COURTESY REPORT' 'ATTEMPTED THEFT FROM A BUILDING'\n 'ENROUTE TO ADULT AUTHORITY' 'CHILD ABUSE, PORNOGRAPHY'\n 'SUSPICIOUS ACT TOWARDS FEMALE' 'HUMAN TRAFFICKING'\n 'THEFT OF CHECKS OR CREDIT CARDS' 'AMMUNITION, POSS. BY PROHIBITED PERSON'\n 'ASSAULT' 'ASSAULT TO RAPE WITH BODILY FORCE' 'CASE CLOSURE'\n 'ATTEMPTED HOMICIDE WITH BODILY FORCE' 'SHOPLIFTING, FORCE AGAINST AGENT'\n 'POSSESSION OF HEROIN FOR SALES' 'ARSON'\n 'MALICIOUS MISCHIEF, ADULT SUSPECT'\n 'BURGLARY OF WAREHOUSE, FORCIBLE ENTRY' 'POSS OF PROHIBITED WEAPON'\n 'DISCHARGE FIREARM WITHIN CITY LIMITS' 'OBSCENE PHONE CALLS(S)'\n 'POSSESSION OF ALCOHOL BY MINOR' 'SALE OF BASE/ROCK COCAINE'\n 'FIREARM, CARRYING LOADED WITH INTENT TO COMMIT FELONY'\n 'SALE OF CONTROLLED SUBSTANCE' 'CIVIL SIDEWALKS, WARNING'\n 'FALSE PRETENSES, PETTY THEFT' 'MALICIOUS MISCHIEF, TIRE SLASHING'\n 'FORCIBLE RAPE, BODILY FORCE' 'DEFRAUDING AN INNKEEPER'\n 'ATTEMPTED SHOPLIFTING' 'DEATH REPORT, NATURAL CAUSES'\n 'ENGAGING IN LEWD ACT' 'LICENSE PLATE, FOUND'\n 'ROBBERY ON THE STREET WITH A KNIFE' 'ROBBERY, ARMED WITH A GUN'\n 'ROBBERY OF A CHAIN STORE WITH BODILY FORCE' 'THREATENING PHONE CALL(S)'\n 'EVADING A POLICE OFFICER RECKLESSLY'\n 'FIREARM, DISCHARGING AT OCCUPIED BLDG, VEHICLE, OR AIRCRAFT'\n 'KIDNAPPING, ADULT VICTIM' 'SUSPICIOUS OCCURRENCE, POSSIBLE SHOTS FIRED'\n 'DEFRAUDING TAXI DRIVER' 'LOST PROPERTY, PETTY THEFT'\n 'PERMIT VIOLATION, POLICE (GENERAL)' 'ATTEMPTED HOMICIDE WITH A KNIFE'\n 'CONSUMING ALCOHOL IN PUBLIC VIEW'\n 'FALSE EVIDENCE OF VEHICLE REGISTRATION' 'DISTURBING THE PEACE, COMMOTION'\n 'ATTEMPTED THEFT FROM UNLOCKED VEHICLE' 'FALSE FIRE ALARM'\n 'DOG, STRAY OR VICIOUS' 'THEFT, GRAND, OF FIREARM'\n 'DISSUADING WITNESS, VICTIM' 'POSS OF TEAR GAS WEAPON'\n 'INJURY TO TELEGRAPH/TELEPHONE LINES'\n 'ROBBERY OF A RESIDENCE WITH BODILY FORCE'\n 'DRIVING WHILE UNDER THE INFLUENCE OF DRUGS'\n 'ROBBERY ON THE STREET WITH A GUN' 'TRICK AND DEVICE, PETTY THEFT'\n 'ATTEMPTED ARSON' 'FLAMMABLE OR EXPLOSIVE DEVICE, POSSESSION'\n 'POSSESSION OF METH-AMPHETAMINE FOR SALE'\n 'TRANSPORTATION OF METH-AMPHETAMINE' 'GRAND THEFT AUTO STRIP'\n 'WEAPON, DEADLY, EXHIBITING TO RESIST ARREST'\n 'THREAT OR FORCE TO RESIST EXECUTIVE OFFICER'\n 'SELL OR FURNISH ALCOHOL TO INTOXICATED PERSON'\n 'TRAFFIC COLLISION, HIT & RUN, PROPERTY DAMAGE'\n 'STOLEN MISCELLANEOUS VEHICLE' 'FALSE ID TO PEACE OFFICER'\n 'ROBBERY ON THE STREET WITH A DANGEROUS WEAPON'\n 'CIVIL SIDEWALKS, VIOLATION' 'THREATS TO SCHOOL TEACHERS'\n 'POSSESSION OF AIR GUN' 'POSSESSION OF BASE/ROCK COCAINE'\n 'ATTEMPTED MAYHEM WITH A DEADLY WEAPON'\n 'ROBBERY OF A COMMERCIAL ESTABLISHMENT, STRONGARM'\n 'BURGLARY,BLDG. UNDER CONSTRUCTION, FORCIBLE ENTRY' 'STALKING'\n 'CHECKS, MAKE OR PASS FICTITIOUS'\n 'CHECKS OR LEGAL INSTRUMENTS, UTTERING FORGED'\n 'SOLICITS FOR ACT OF PROSTITUTION' 'LOITERING FOR PURPOSE OF PROSTITUTION'\n 'LICENSE PLATE, RECOVERED' 'POSSESSION OF COCAINE FOR SALES'\n 'TARASOFF REPORT' 'EMBEZZLED VEHICLE'\n 'FAILURE TO REGISTER AS SEX OFFENDER' 'ROBBERY, ATM, GUN, ATT.'\n 'PROBATION VIOLATION, DV RELATED' 'PREJUDICE-BASED INCIDENT'\n 'DEATH, ACCIDENTAL' 'IMPOUNDED VEHICLE' 'BATTERY WITH SERIOUS INJURIES'\n 'DISORDERLY HOUSE, KEEPING' 'TRANSPORTATION OF MARIJUANA'\n 'ATTEMPTED STOLEN VEHICLE'\n 'VEHICLE ALARM CODE GRABBING DEVICE, POSSESS OR USE'\n 'CARRYING OF CONCEALED WEAPON BY CONVICTED FELON'\n 'MAINTAINING A PUBLIC NUISANCE AFTER NOTIFICATION'\n 'OBSTRUCTIONS ON STREETS/SIDEWALKS'\n 'VIOLATION OF EMERGENCY PROTECTIVE ORDER' 'MAINTAINING A PUBLIC NUISANCE'\n 'BURGLARY, ATTEMPTED FORCIBLE ENTRY' 'COMMITTING PUBLIC NUISANCE'\n 'ANNOY OR MOLEST CHILDREN' 'INDECENT EXPOSURE'\n 'AGGRAVATED ASSAULT OF POLICE OFFICER,BODILY FORCE'\n 'ATTEMPTED KIDNAPPING, JUVENILE VICTIM'\n 'ATTEMPTED GRAND THEFT FROM PERSON' 'ROBBERY OF A RESIDENCE WITH A KNIFE'\n 'VIOLATION OF STAY AWAY ORDER' 'MISCELLANEOUS STATE FELONY'\n 'ATTEMPTED SUICIDE' 'PROPERTY FOR IDENTIFICATION'\n 'PLANTING/CULTIVATING MARIJUANA' 'ACCESS CARD INFORMATION, THEFT OF'\n 'MISCELLANEOUS STATE MISDEMEANOR' 'SHORT CHANGE, PETTY THEFT'\n 'THEFT, DRUNK ROLL, <$50' 'KIDNAPPING, JUVENILE VICTIM' 'TRUANT, HABITUAL'\n 'DISTURBING THE PEACE, FIGHTING' 'SUSPICIOUS AUTO, POSSIBLY SEX'\n 'BURGLARY,RESIDENCE UNDER CONSTRT, FORCIBLE ENTRY'\n 'BRIBERY OF EXECUTIVE OFFICER' 'THREATENING SCHOOL OR PUBLIC EMPLOYEE'\n 'CRUELTY TO ANIMALS' 'BURGLARY OF HOTEL ROOM, FORCIBLE ENTRY'\n 'LOITERING ABOUT SCHOOL/PLAYGROUND' 'POSSESSION OF COCAINE' 'SPEEDING'\n 'SCHOOL, PUBLIC, TRESPASS'\n 'ROBBERY OF A COMMERCIAL ESTABLISHMENT W/ WEAPON'\n 'ENROUTE TO U.S. MARSHALL'\n 'ASSAULT ON A POLICE OFFICER WITH A DEADLY WEAPON'\n 'PETTY THEFT AUTO STRIP' 'ATTEMPTED PETTY THEFT OF PROPERTY'\n 'ATTEMPTED SIMPLE ASSAULT' 'BURGLARY OF FLAT, FORCIBLE ENTRY'\n 'COUNTERFEITING, POSSESSION COINS OR NOTES'\n 'ATTEMPTED ROBBERY ON THE STREET WITH A GUN'\n 'MALICIOUS MISCHIEF, JUVENILE SUSPECT' 'MAYHEM WITH A KNIFE'\n 'UNLAWFUL DISSUADING/THREATENING OF A WITNESS'\n 'DRIVING, RECKLESS, WITH INJURY'\n 'WEAPON, DEADLY, CARRYING WITH INTENT TO COMMIT ASSAULT'\n 'OPEN CONTAINER OF ALCOHOL IN VEHICLE'\n 'RESISTING PEACE OFFICER, CAUSING THEIR SERIOUS INJURY OR DEATH'\n 'ENROUTE TO PROBATION OFFICER' 'REMAINING ON CAMPUS WITHOUT CONSENT'\n 'SCHOOL PROPERTY, DISTURBANCE ON'\n 'WEAPON, POSSESS OR BRING OTHER ON SCHOOL GROUNDS' 'UNUSUAL OCCURENCE'\n 'FALSE PERSONATION AND CHEAT CRIMES (GENERAL)' 'CURFEW VIOLATION'\n 'POSSESSION OF HALLUCINOGENIC FOR SALES' 'SALE OF HALLUCINOGENIC'\n 'CARJACKING WITH A KNIFE' 'KIDNAPPING DURING CARJACKING'\n 'MAINTAINING PREMISE WHERE NARCOTICS ARE SOLD/USED'\n 'ARMOR PENETRATING AMMUNITION, POSSESSION'\n 'POST RELEASE COMMUNITY SUPERVISION' 'FORGE OR ALTER PRESCRIPTION'\n 'DISCHARGING IN GROSSLY NEGLIGENT MANNER' 'GRAND THEFT PURSESNATCH'\n 'ATTEMPTED ROBBERY WITH A KNIFE' 'CARJACKING WITH BODILY FORCE'\n 'CHILD, INFLICTING INJURY RESULTING IN TRAUMATIC CONDITION'\n 'WEAPON, POSSESSING IN PUBLIC BUILDING OR OPEN MEETING'\n 'EMBEZZLEMENT FROM DEPENDENT OR ELDER ADULT BY CARETAKER'\n 'BURGLARY,RESIDENCE UNDER CONSTRT, UNLAWFUL ENTRY' 'AUTO, GRAND THEFT OF'\n 'DESTITUTE MINOR' 'STOLEN CHECKS, POSSESSION' 'FIRE, UNLAWFULLY CAUSING'\n 'ROBBERY OF A BANK WITH BODILY FORCE' 'BEYOND PARENTAL CONTROL'\n 'FIREARMS, SEIZING AT SCENE OF DV'\n 'FALSE CLAIMS, PRESENTING TO GOVERNMENT' 'TURNED IN GUN'\n 'LOCATED EXPLOSIVE DEVICE' 'SUICIDE BY JUMPING' 'ANIMAL, FIGHTING'\n 'ARSON OF AN INHABITED DWELLING'\n 'BURGLARY,STORE UNDER CONSTRUCTION, ATT. FORCIBLE'\n 'LOITERING WHILE CARRYING CONCEALED WEAPON'\n 'DANGER OF LEADING IMMORAL LIFE' 'CHECKS, FORGERY (MISDEMEANOR)'\n 'DRIVES VEHICLE ALONG TRACK OF RAILROAD' 'TRANSPORTATION OF HEROIN'\n 'POSSESSION OF OPIATES FOR SALES' 'TRANSPORTATION OF OPIATES'\n 'DRIVING WHILE UNDER THE INFLUENCE OF ALCOHOL, W/INJURY'\n 'ATTEMPTED KIDNAPPING, ADULT VICTIM' 'PHONE CALLS, OBSCENE'\n 'VIOLATION OF FIRE CODE' 'UNLAWFUL SEXUAL INTERCOURSE'\n 'SUSPICIOUS ACT TOWARDS CHILD' 'SALE OF OPIUM'\n 'PHONE CALLS IN VIOLATION OF DV COURT ORDER'\n 'EMBEZZLEMENT, GRAND THEFT BY BROOKERS/AGENTS'\n 'TRANSPORTAION OF CONTROLLED SUBSTANCE' 'STOLEN TRAILER'\n 'FALSE REPORT OF EMERGENCY' 'ATTEMPTED ROBBERY CHAIN STORE WITH A KNIFE'\n 'POSSESSION OF HALLUCINOGENIC' 'THEFT, DRUNK ROLL, $50-$200'\n 'FAILURE TO PROVIDE FOR CHILD'\n 'ELECTRICAL OR GAS LINES, INTERFERING WITH'\n 'WEAPON, ASSAULT, POSSESSION, MANUFACTURE, OR SALE' 'VIN, ALTER OR REMOVE'\n 'ATTEMPTED ROBBERY CHAIN STORE WITH BODILY FORCE'\n 'LODGING WITHOUT PERMISSION' 'LOST PROPERTY, GRAND THEFT'\n 'ROBBERY, ATM, FORCE, ATT.'\n 'CELLULAR OR CORDLESS PHONE COMMUNICATIONS, INTERCEPTING'\n 'EVADING A POLICE VEHICLE OR BICYCLE' 'EXTORTION'\n 'LICENSE PLATE OR TAB, THEFT OF' 'PAROLE SEARCH'\n 'THEFT OF UTILITY SERVICES'\n 'FIREARM, ARMED WHILE POSSESSING CONTROLLED SUBSTANCE'\n 'ATTEMPTED MAYHEM WITH BODILY FORCE' 'MAYHEM WITH A DEADLY WEAPON'\n 'ATTEMPTED HOMICIDE WITH A DANGEROUS WEAPON' 'GAMBLING'\n 'POSSESSION OF GAMBLING DEVICES' 'SEXUAL ASSAULT, AGGRAVATED, OF CHILD'\n 'CREDIT CARD, INCOMPLETE OR COUNTERFEIT'\n 'CONTRIBUTING TO THE DELINQUENCY OF MINOR'\n 'ATTEMPTED ROBBERY ON THE STREET WITH A KNIFE'\n 'STOLEN ACCESS CARD, POSSESSION'\n 'BURGLARY,APT UNDER CONSTRUCTION, UNLAWFUL ENTRY'\n 'DISTURBING THE PEACE, SWEARING' 'ROBBERY OF A BANK WITH A GUN'\n 'MALICIOUS MISCHIEF, STREET CARS/BUSES' 'FALSE REPORT OF CRIME'\n 'SALE OF ALCOHOL TO MINOR'\n 'MONEY, PROPERTY OR LABOR, FRAUDULENTLY OBTAINING'\n 'DAMAGE TO PARKING METERS' 'THROWING INJURIOUS SUBSTANCE ON HIGHWAY'\n 'FIREARM, DISCHARGING IN GROSSLY NEGLIGENT MANNER'\n 'POSSESSION OF AMPHETAMINE FOR SALES' 'PRIVACY, INVASION OF (GENERAL)'\n 'TOBACCO PRODUCTS, SELLING OR FURNISHING TO MINOR'\n 'EMBEZZLEMENT, PETTY THEFT BY EMPLOYEE' 'IMPERSONATING A POLICE OFFICER'\n 'TRICK AND DEVICE, ATTEMPTED'\n 'ROBBERY, VEHICLE FOR HIRE, ATT., W/ OTHER WEAPON'\n 'ROBBERY OF A BANK WITH A KNIFE'\n 'THEFT, BICYCLE, <$50, SERIAL NUMBER KNOWN'\n 'BURGLARY OF STORE, ATTEMPTED FORCIBLE ENTRY'\n 'SWITCHBLADE KNIFE, POSSESSION'\n 'WEAPON, ASSAULT, REGISTRATION OR TRANSFER VIOLATION'\n 'VEHICLE, DISABLED PLACARD VIOLATION' 'POSSESSION OF CAUSTIC CHEMICAL'\n 'TRANSPORTATION OF COCAINE' 'CHECKS, FORGERY (FELONY)'\n 'FIREARM, POSSESSION OF WHILE WEARING MASK' 'ROBBERY, ATM, OTHER WEAPON'\n 'EMBEZZLEMENT, PETTY THEFT'\n 'AEROSOL CONTAINER; SALE, PURCHASE OR POSSESSION OF'\n 'ATTEMPTED ROBBERY COMM. ESTAB. WITH BODILY FORCE'\n 'IMMORAL ACTS OR DRUNK IN PRESENCE OF CHILD' 'POSSESSION OF METHADONE'\n 'PUBLIC TRANSIT CRIMES - INFRACTIONS' 'EVADING PAYMENT OF RAILROAD FARE'\n 'SHELTER' 'INTOXICATED JUVENILE' 'ATTEMPTED EXTORTION'\n 'ROBBERY OF A COMMERCIAL ESTABLISHMENT WITH A GUN'\n 'POSSESSION OF ARTICLES WITH IDENTIFICATION REMOVE'\n 'CHECKS, NON-SUFFICIENT FUNDS (MISDEMEANOR)'\n 'THEFT, GRAND, BY FIDUCIARY, >$400 IN 12 MONTHS'\n 'BURGLARY,RESIDENCE UNDER CONSTRT, ATT. FORCIBLE'\n 'MANUFACTURE OR SALE OF COUNTERFEIT GOODS'\n 'UNDER THE INFLUENCE OF CONTROLLED SUBSTANCES' 'ROBBERY, ATM, KNIFE'\n 'ARSON OF A COMMERCIAL BUILDING'\n 'STOLEN CELLULAR PHONE, NON-CLONED, POSSESSION'\n 'MALICIOUS MISCHIEF, BREAKING WINDOWS WITH BB GUN'\n 'AUDIOVISUAL (VIDEO OR SOUND) RECORDINGS, UNAUTHORIZED'\n 'STOLEN ELECTRONICS, POSSESSION' 'RAPE, SPOUSAL'\n 'FORGERY, DRIVERS LICENSE OR ID-CARD' 'WILLFUL CRUELTY TO CHILD'\n 'FALSIFYING JUDICIAL & PUBLIC RECORDS & DOCUMENTS'\n 'CASH DISPENSING MACHINES (ATM), LOITERING PROHIBI'\n 'EMBEZZLEMENT, GRAND THEFT BY EMPLOYEE'\n 'INDECENT EXPOSURE (JUVENILE VICTIM)' 'CHILD ABUSE SEXUAL'\n 'CHILDREN, ABANDONMENT & NEGLECT OF (GENERAL)'\n 'AGGRAVATED ASSAULT ON POLICE OFFICER WITH A KNIFE' 'AUTO IMPOUNDED'\n 'INTERFERRING WITH A FIREMAN' 'THROWING SUBSTANCE AT VEHICLE'\n 'TRICK AND DEVICE, GRAND THEFT'\n 'VANDALISM OR GRAFFITI ON OR WITHIN 100 FT OF HIGHWAY'\n 'ARSON OF A VACANT BUILDING'\n 'TRADE SECRETS, THEFT OR UNAUTHORIZED COPYING'\n 'MINOR PURCHASING OR RECEIVING TOBACCO PRODUCT' 'SALE OF HEROIN'\n 'EMBEZZLEMENT, GRAND THEFT LEASED PROPERTY' 'VIOLATION OF FEDERAL STATUTE'\n 'ATTEMPTED RAPE, BODILY FORCE' 'PETTY THEFT COIN OPERATED MACHINE'\n 'POSSESSION OF OPIATES' 'GRAND THEFT BY PROSTITUTE'\n 'OTHER OFFENSES AGAINST PUBLIC JUSTICE' 'PEDDLING WITHOUT A LICENSE'\n 'SALE OF METH-AMPHETAMINE' 'FAILURE TO HEED RED LIGHT AND SIREN'\n 'SUICIDE BY ASPHYXIATION'\n 'BURGLARY,HOTEL UNDER CONSTRUCTION, FORCIBLE ENTRY'\n 'VIOLATION OF RESTRICTIONS ON A FIREARM TRANSFER'\n 'ATTEMPTED ROBBERY WITH A GUN' 'ORAL COPULATION'\n 'PERMIT VIOLATION, ENTERTAINMENT' 'CARJACKING WITH A GUN'\n 'REAL ESTATE FRAUD' 'BURGLARY OF FLAT, ATTEMPTED FORCIBLE ENTRY'\n 'THREAT TO STATE OFFICIAL OR JUDGE'\n 'IDENTIFICATION, GOVERNMENT, POSSESS, MAKE OR SELL FALSE'\n 'ATTEMPTED ROBBERY RESIDENCE WITH A KNIFE'\n 'INDECENT EXPOSURE WITH PRIOR CONVICTION'\n 'INTERFERRING WITH A POLICE OFFICER' 'ROBBERY OF A RESIDENCE WITH A GUN'\n 'MAYHEM WITH BODILY FORCE'\n 'COMPUTER SYSTEM, ACCESSING, COPYING, OR DAMAGING'\n 'FORCIBLE RAPE, ARMED WITH A SHARP INSTRUMENT' 'CHILD ABUSE, EXPLOITATION'\n 'DAMAGE TO MAIL BOX' 'MISCELLANEOUS LIQOUR LAW VIOLATION'\n 'SALE OF COCAINE' 'ABANDONMENT OF CHILD' 'PLACING TRASH ON THE STREET'\n 'SPITTING ON SIDEWALK' 'ACTS AGAINST PUBLIC TRANSIT'\n 'HAZARDOUS MATERIALS, SPILL ON ROADWAY' 'OPERATING TAXI WITHOUT A PERMIT'\n 'PETTY THEFT WITH PRIOR' 'FALSE REPORT OF BOMB'\n 'CARJACKING WITH A DANGEROUS WEAPON'\n 'THROWING OBJECT AT COMMON CARRIER, PASSENGER OR FREIGHT'\n 'DUMPING OF OFFENSIVE MATTER' 'DEATH, NON-MANSLAUGHTER AUTO ACCIDENT'\n 'FIREARM WITH ALTERED IDENTIFICATION' 'TAMPERING WITH MARKS ON FIREARM'\n 'FIREARM POSSESSION IN SCHOOL ZONE' 'PERMIT VIOLATION, VALET PARKING'\n 'BURGLARY,FLAT UNDER CONSTRUCTION, FORCIBLE ENTRY' 'SODOMY'\n 'JUDGE/JUROR ACCEPTING A BRIBE'\n 'TRESPASSING OR LOITERING NEAR POSTED INDUSTRIAL PROPERTY'\n 'OBSTRUCTING PUBLIC THOROUGHFARE'\n 'GRAFFITI ON GOVERNMENT VEHICLES OR PUBLIC TRANSPORTATION'\n 'UNLAWFUL TRANSPORTATION OF ALCOHOL' 'CIVIL SIDEWALKS, BOOKING'\n 'WEARING MASK OR DISGUISE FOR UNLAWFUL PURPOSE'\n 'ATTEMPTED SUICIDE BY LACERATION' 'EMBEZZLEMENT (GENERAL)'\n 'POSSESSION OF FIRECRACKERS'\n 'POSS OF DEADLY WEAPON WITH INTENT TO ASSAULT'\n 'BURGLARY,WAREHOUSE UNDER CONSTRT, FORCIBLE ENTRY'\n 'SAFE BURGLARY OF A HOTEL' 'PRESCRIPTION, FORGE OR ALTER (4390 B&P)'\n 'THEFT OF WRITTEN INSTRUMENT'\n 'SEXUAL ASSAULT, ADMINISTERING DRUG TO COMMIT'\n 'BURGLARY,APT UNDER CONSTRUCTION, FORCIBLE ENTRY'\n 'ATTEMPTED SUICIDE BY JUMPING' 'AGGRESSIVE SOLICITING' 'HABITUAL TRUANT'\n 'HYPODERMIC NEEDLE OR SYRINGE, POSSESSION' 'DAMAGE/DESTRUCTION OF MAIL'\n 'ATTEMPTED ROBBERY OF A BANK WITH A DEADLY WEAPON'\n 'ATTEMPTED ROBBERY RESIDENCE WITH A GUN' 'BEGGING'\n 'SAFE BURGLARY OF A STORE' 'EMBEZZLEMENT, GRAND THEFT' 'SALE OF OPIATES'\n 'PANDERING' 'MALICIOUS MISCHIEF, FICTITIOUS PHONE CALLS'\n 'PETTY THEFT MOTORCYCLE STRIP' 'THEFT, BOAT'\n 'CHECKS, NON-SUFFICIENT FUNDS (FELONY)' 'ESCAPE OR ASSISTING ESCAPE'\n 'ATTEMPTED SUICIDE BY INGESTION' 'TAKING CONTRABAND INTO A REFORMATORY'\n 'UNLAWFUL ASSEMBLY' 'BURGLARY OF WAREHOUSE, ATTEMPTED FORCIBLE ENTRY'\n 'ATTEMPTED ROBBERY RESIDENCE WITH A DEADLY WEAPON'\n 'BURGLARY OF WAREHOUSE, UNLAWFUL ENTRY' 'PIMPING'\n 'DISRUPTS SCHOOL ACTIVITIES'\n 'CONCEAL CRIME OR WITHHOLD EVIDENCE, ACCEPTING PAYMENT TO'\n 'ATTEMPTED ROBBERY COMM. ESTABLISHMENT WITH A GUN'\n 'DAMAGE TO FIRE ALARM APPARATUS' 'THEFT, DRUNK ROLL, $200-$400'\n 'STOLEN COMPUTER, POSSESSION' 'THEFT, BICYCLE, <$50, NO SERIAL NUMBER'\n 'PHONE CALLS, HARASSING, TO 911' 'RIOT' 'DOG, BARKING'\n 'ATTEMPTED ROBBERY OF A BANK WITH A GUN'\n 'FAILURE TO REGISTER AS NARCOTICS ADDICT'\n 'ASSAULT TO COMMIT MAYHEM OR SPECIFIC SEX OFFENSES' 'STOLEN BUS'\n 'SOLICITING COMMISSION OF A CRIME' 'SALE OF ALCOHOL AFTER HOURS'\n 'SAFE BURGLARY' 'DOG OR CAT, ABANDONMENT OF'\n 'MINOR ON ON-SALE LICENSED PREMISE' 'RECEIVING STOLEN PROPERTY'\n 'FIREARM, NEGLIGENT DISCHARGE' 'EVADING A POLICE OFFICER, INJURY OR DEATH'\n 'DRIVING WHILE UNDER THE INFLUENCE OF DRUGS, W/INJURY'\n 'SUICIDE BY STRANGULATION' 'REFUSING TO DISPERSE UPON LAWFUL COMMAND'\n 'INCITING TO RIOT' 'DESTRUCTION OF PROPERTY WITH EXPLOSIVES'\n 'FIREWORKS, THROW AT PERSON OR DISCHARGE IN CROWD'\n 'BURGLARY,FLAT UNDER CONSTRUCTION, UNLAWFUL ENTRY'\n 'BALLOONS, ELECTRICALLY CONDUCTIVE' 'DESERTION OF CHILD'\n 'LYNCHING BY RIOT' 'PEEPING TOM' 'FURNISHING MARIJUANA'\n 'ROBBERY OF A RESIDENCE WITH A DANGEROUS WEAPON'\n 'ROBBERY OF A SERVICE STATION W/DANGEROUS WEAPON'\n 'DEFRAUDING OF VEHICLE REPAIRMAN' 'DEATH REPORT, IN CUSTODY'\n 'LICENSE REQUIRED TO SELL ALCOHOL'\n 'BURGLARY,BLDG. UNDER CONSTRUCTION, ATT. FORCIBLE'\n 'COUNTERFEITING, PLATES OR DIES' 'ABORTION' 'SUICIDE BY FIREARMS'\n 'ATTEMPTED SUICIDE BY STRANGULATION'\n 'ROBBERY OF A SERVICE STATION WITH A GUN' 'MAYHEM WITH A GUN'\n 'AID OR HARBOR FELON' 'LOITERING' 'FALSE EVIDENCE OF AGE BY MINOR'\n 'ANIMAL, WITHOUT PROPER CARE OR ATTENTION' 'GRAND THEFT MOTORCYCLE STRIP'\n 'ROBBERY OF A SERVICE STATION WITH BODILY FORCE'\n 'FORCIBLE RAPE, ARMED WITH A GUN'\n 'SEXUAL CONTACT WITH PATIENT, FORMER PATIENT' 'LICENSE PLATE, STOLEN'\n 'POSSESSION OF EXPLOSIVE DEVICE'\n 'INDECENT EXPOSURE - PROSTITUTION RELATED'\n 'IMPERSONATING FIRE DEPARTMENT MEMBER'\n 'WEAPON, TAKING OR ATTEMPTING TO TAKE FROM PEACE OFFICER'\n 'SAFE BURGLARY OF A RESIDENCE' 'INMATE/KEEPER OF HOUSE OF PROSTITUTION'\n 'ATTEMPTED ROBBERY SERVICE STATION WITH A KNIFE' 'SCALPING TICKETS'\n 'POSSESSION OF OPIUM DERIVATIVE' 'POSSESSION OF METHADONE FOR SALES'\n 'ATTEMPTED ROBBERY COMM. ESTAB. WITH DEADLY WEAPON'\n 'IMPERSONATING PUBLIC UTILITY MEMBER' 'SOLICITS LEWD ACT'\n 'FORCIBLE RAPE, ARMED WITH A DANGEROUS WEAPON'\n 'FORGERY, GOVERNMENT OR CORPORATE SEALS'\n 'ATTEMPTED ROBBERY CHAIN STORE WITH DEADLY WEAPON'\n 'FOOD STAMPS, MISUSE OF'\n 'INSURED PROPERTY, DESTRUCTION TO DEFRAUD INSURER'\n 'VEHICLE, RENTAL, FAILURE TO RETURN'\n 'DEMONSTRATION, VIDEO EVIDENCE, MISC. INVESTIGATION'\n 'DISASTER AREA, ENTERING OR REMAINING IN'\n 'DESTROYING JAIL PROPERTY-OVER $200' 'THEFT, DRUNK ROLL, >$400'\n 'MASSAGE ESTABLISHMENT PERMIT VIOLATION'\n 'FALSE REPRESENTATION TO SECONDHAND DEALER'\n 'DISCHARGING OFFENSIVE OR INJURIOUS SUBSTANCE IN PUBLIC AREA'\n 'LOITERS AROUND PUBLIC TOILET FOR LEWD ACT'\n 'VIOLATION OF CIVIL GANG INJUNCTION' 'PERMIT VIOLATION, SIDEWALK SALES'\n 'TRANSPORTATION OF AMPHETAMINE' 'SUICIDE BY LACERATION'\n 'DISTURBING RELIGIOUS MEETINGS' 'THEFT, GRAND, AGRICULTURAL'\n 'LOITERING WITHOUT LAWFUL BUSINESS WITH OWNER OR OCCUPANT'\n 'ATTEMPTED GRAND THEFT PICKPOCKET' 'SELLING/DISCHARGING OF FIRECRACKERS'\n 'THEFT, ANIMAL, ATT.' 'ATTEMPTED SUICIDE BY FIRE'\n 'THEFT OF TELECOMMUNICATION SERVICES, INCL. CLONE PHONE'\n 'ARSON OF A POLICE BUILDING' 'ADVERTISING DISTRIBUTORS PERMIT VIOLATION'\n 'CIVIL RIGHTS, INCL. INJURY, THREAT, OR DAMAGE (HATE CRIMES)'\n 'ENCOURAGING MINOR TO USE MARIJUANA' 'TRESPASSING ON RAILROAD TRAINS'\n 'CITIZENSHIP DOCUMENT, USING FALSE'\n 'HAZARDOUS MATERIALS, DUMPING IN UNAUTHORIZED LOCATN' 'SALE OF METHADONE'\n 'RESCUING PRISONER FROM LAWFUL CUSTODY'\n 'ASSAULT, AGGRAVATED, ON POLICE OFFICER, W/ GUN'\n 'FINANCIAL STATEMENTS, FALSE'\n 'EMBEZZLEMENT, PETTY THEFT PUBLIC/PRIVATE OFFICIAL'\n 'ILLEGAL TRANSPORTAION OF EXPLOSIVES' 'STOLEN METALS, RECEIVING'\n 'ASSAULT TO RAPE WITH A GUN' 'ASSAULT BY POLICE OFFICER'\n 'FALSIFICATION OF MEDICAL RECORDS'\n 'MALICIOUS MISCHIEF, BUILDING UNDER CONSTRUCTION'\n 'WEAPONS POSSESSION BY JUVENILE SUSPECT'\n 'VIOLATION OF CALIF UNEMPLOYMENT INSURANCE ACT'\n 'LASERS, DISCHARGING OR LIGHTS AT AIRCRAFT'\n 'ATTEMPTED MAYHEM WITH A KNIFE' 'ATTEMPTED RAPE WITH A GUN'\n 'HAZARDOUS SUBSTANCES, DEPOSITING' 'SAFE BURGLARY OF AN APARTMENT'\n 'ACCIDENTAL SHOOTING' 'SCHOOL GROUNDS, ENTRY BY SEX OFFENDER'\n 'BURGLARY,HOTEL UNDER CONSTRUCTION, UNLAWFUL ENTRY'\n 'OBSCENE MATTER, DISTRIBUTION TO MINORS' 'POSSESSION OF AMPHETAMINE'\n \"ASSAULT OR ATTEMPTED MURDER UPON GOV'T OFFICERS\"\n 'RECOVERED VEHICLE - STOLEN OUTSIDE SF'\n 'VEHICLE, RECOVERED, CAMPER-HOUSE CAR-MOTOR HOME'\n 'ATTEMPTED ROBBERY SERVICE STATION W/DEADLY WEAPON'\n 'VANDALISM WITH NOXIOUS CHEMICAL' 'VEHICLE, RECOVERED, AUTO'\n 'POSS OF FIREARM SILENCER' 'ESCAPEE, JUVENILE' 'SUICIDE'\n 'TELEPHONE OR TELEGRAPH MESSAGE, SENDING FALSE'\n 'POSSESSION OF OPIUM FOR SALES' 'SAFE BURGLARY OF A WAREHOUSE'\n 'EAVESDROPPING DEVICES, SALE OR USE' 'TAMPERING WITH MAIL'\n 'BATTERY DURING LABOR DISPUTE' 'VEHICLE, RECOVERED, MOTORCYCLE'\n 'BURGLARY OF HOTEL ROOM, ATTEMPTED FORCIBLE ENTRY'\n 'TRANSPORTATION OF METHADONE' 'SELLING RESTRICTED GLUE TO JUVENILES'\n 'CONTROLLED SUBSTANCE VIOLATION, LOITERING FOR'\n 'POSSESSION OF GAMBLING PARAPHERNALIA'\n 'ROBBERY OF A SERVICE STATION WITH A KNIFE'\n 'GRAND THEFT COIN OPERATED MACHINE'\n 'ATTEMPTED THEFT COIN OPERATED MACHINE' 'SUICIDE BY DROWNING'\n 'POSSESSION OF OPIUM' \"MEGAN'S LAW NOTIFICATION\" 'ATTEMPTED AUTO STRIP'\n 'SALES COCAINE BASE/SCHOOLYARD TRAFFICKING ACT VIO'\n 'ASSAULT TO RAPE WITH A DANGEROUS WEAPON'\n 'CRIMES AGAINST REVENUE & PROPERTY OF STATE' 'FORTUNE TELLING'\n 'VISITING WHERE DRUGS ARE USED OR SMOKED' 'ROBBERY, ATM, KNIFE, ATT.'\n 'POSSESSION OF OBSCENE MATTER FOR SALE'\n 'SCHOOL STUDENT OR EMPLOYEE ENTERING CAMPUS AFTER SUSPENSION OR DISMISSAL'\n 'POSSESSION OF OPIUM DERIVATIVE FOR SALES' 'HEATING VIOLATION APT/HOTEL'\n 'ASSAULT, AGGRAVATED, ON POLICE OFFICER, W/ SEMI AUTO'\n 'POSSESSION OF BARBITUATES' 'VIN SWITCH'\n 'HAZARDOUS MATERIALS, DUMP OIL INTO SEWERS'\n 'FALSE REPORT OF POLICE MISCONDUCT' 'PETTY THEFT PHONE BOOTH'\n 'BATHROOM HOLE, LOOKING THROUGH'\n 'FORGERY, FALSE ENTRIES IN RECORDS OR RETURNS'\n 'BURGLARY,FLAT UNDER CONSTRUCTION, ATT. FORCIBLE'\n 'ATTEMPTED SUICIDE BY ASPHYXIATION' 'OPERATING WITHOUT DANCEHALL PERMIT'\n 'SOLICITS TO VISIT HOUSE OF PROSTITUTION'\n 'PUBLIC UTILITY INFORMATION, FRAUDULENTLY OBTAINING'\n 'EMBEZZLEMENT, PETTY THEFT PRIVATE PROPERTY'\n 'ATTEMPTED RAPE, ARMED WITH A SHARP INSTRUMENT'\n 'GUIDE DOG, INTERFERING WITH' 'TRANSPORTATION OF HALLUCINOGENIC'\n 'ACCESS CARD INFORMATION, PUBLICATION OF'\n 'ASSAULT, AGGRAVATED, W/ MACHINE GUN' 'ASSAULT, AGGRAVATED, W/ SEMI AUTO'\n 'LODGING IN PARK' 'ESCAPES' 'DRIVING, DRAG RACING' 'PERJURY'\n 'ASSAULT BY POISONING' 'LOUDSPEAKER OR SOUND TRUCK PERMIT VIOLATION'\n 'DRUG OFFENDER, PRESENCE NEAR SCHOOL GROUNDS' 'MISPLACED VEHICLE'\n 'ESCAPE FROM HOSPITAL WITH FORCE' 'POSSESSION OF MACHINE GUN'\n 'MONEY OFFENSE RELATED TO NARCOTICS TRAFFICKING' 'KIDNAPPER, POSING AS'\n 'COMMISSION OF FELONY WHILE ARMED'\n 'DESTRUCTIVE DEVICE, POSSESSION OF MATERIALS' 'JUVENILE PAROLE VIOLATOR'\n 'SHORT CHANGE, GRAND THEFT' 'VEHICLE, RECOVERED, OTHER VEHICLE'\n 'THEFT, DRUNK ROLL, ATT.' 'SALE OF ALCOHOL BY MINOR' 'MALICIOUS MISCHIEF'\n 'PROCUREMENT, PIMPING, & PANDERING' 'POSSESSION OF BARBITUATES FOR SALES'\n 'SALE OF ALCOHOL TO MINOR IN BAR'\n 'HAZARDOUS MATERIALS, DUMPING IN UNAUTHORIZED LOCATION'\n 'OBSTRUCTING HEALTH FACILITY, PLACE OF WORSHIP, OR SCHOOL'\n 'POLICE BROADCAST, INTERCEPTION TO COMMIT CRIME'\n 'ATTEMPTED ROBBERY OF A BANK WITH A KNIFE'\n 'ATTEMPTED ROBBERY CHAIN STORE WITH A GUN'\n 'ATTEMPTED ROBBERY COMM. ESTABLISHMENT W/KNIFE'\n 'ASSAULT, AGGRAVATED, ON POLICE OFFICER, W/ FULL AUTO'\n 'DISPLAY & SALE OF SPRAY PAINT & MARKER PENS'\n 'ATTEMPTED RAPE, ARMED WITH A DANGEROUS WEAPON'\n 'AGGRAVATED ASSAULT ON POLICE OFFICER WITH A GUN' 'BRIBERY OF WITNESSES'\n 'HAZARDOUS MATERIALS, DUMP ANY SUBSTANCE INTO WATER'\n 'DOG, FIGHTING; OWNING, FIGHTING, OR ATTENDING FIGHT'\n 'PUTTING SLUGS IN COIN OPERATED MACHINES'\n 'ATTEMPTED ROBBERY SERVICE STATION W/BODILY FORCE'\n 'SOLICITING MINOR TO COMMIT FELONY'\n 'EMBEZZLEMENT, GRAND THEFT BY COLLECTOR' 'POISONING ANIMALS'\n 'TERRORIZING BY ARSON OR EXPLOSIVE DEVICE'\n 'WEARING THE APPAREL OF OPPOSITE SEX TO DECEIVE'\n 'VEHICLE, RECOVERED, MOBILE HOME-TRAILER' 'SALE OF AMPHETAMINE'\n 'EMBEZZLEMENT, GRAND THEFT PRIVATE PROPERTY'\n 'BURGLARY,APT UNDER CONSTRUCTION, ATT. FORCIBLE'\n 'ROBBERY, VEHICLE FOR HIRE, ATT., W/ GUN'\n 'ASSAULT TO RAPE WITH A SHARP INSTRUMENT' 'MINOR PURCHASING ALCOHOL'\n 'SUICIDE BY INGESTION' 'HAZARDOUS MATERIALS, SPILL LOAD'\n 'EMBEZZLEMENT, GRAND THEFT BY PROPERTY CARRIER'\n 'HAZARDOUS MATERIALS, FAILURE TO COMPLY W/REGULATIONS'\n 'ROBBERY, VEHICLE FOR HIRE, ATT., W/ FORCE'\n 'ALCOHOLIC BEVERAGE, PROCURING SALE OF' 'ASSAULT TO ROB WITH BODILY FORCE'\n 'VIOLATION OF STATE LABOR CODE' 'YOUTH COURT' 'ESCAPE FROM JAIL'\n 'BATTERY BY JUVENILE SUSPECT'\n 'BURGLARY,WAREHOUSE UNDER CONSTRT, UNLAWFUL ENTRY'\n 'ATTEMPTED ROBBERY SERVICE STATION WITH A GUN'\n 'DRUG LAB APPARATUS, POSSESSION' 'PUSH-CART PEDDLER PERMIT VIOLATION'\n 'ATTEMPTED SUICIDE BY FIREARMS' 'INCEST'\n 'ENCOURAGE MINOR TO USE CONTROLLED SUBSTANCE'\n 'BIGAMY, INCEST, AND THE CRIME AGAINST NATURE (GENERAL)'\n 'DISTURBANCE OF NON-RELIGIOUS, NON-POLITICAL ASSEMBLY' 'POSS OF FIRE BOMB'\n 'CITIZENSHIP OR ALIEN REGISTRATION, MAKING FALSE DOCUMENT'\n 'FAILURE TO PROVIDE FOR PARENTS'\n 'CABLE TV CONNECTION OR DECODING DEVICE, UNAUTHORIZED'\n 'SALE OF SATELLITE TELEPHONE NUMBER' 'SNIPER SCOPE, POSSESSION OF'\n 'TERRORIZING BY MARKING PRIVATE PROPERTY'\n 'OBSCENE OR LEWD PLAYS/PERFORMANCES'\n 'ESCAPE OF PRISONER WHILE HOSPITALIZED'\n 'INJURY TO RAILROADS/RAILROAD BRIDGES' 'OPERATING WITHOUT CABARET PERMIT'\n 'SALE OF BARBITUATES' 'BOOKMAKING' 'PUTTING SLUGS IN TELEPHONE BOX'\n 'AFFIXING ADVERTISMENTS TO POLES'\n 'EMBEZZLEMENT, PETTY THEFT BY BROOKERS/AGENTS' 'ACCIDENTAL BURNS'\n 'SAFE BURGLARY OF A FLAT' 'SUICIDE BY FIRE'\n 'PUTTING SLUGS IN PARKING METERS'\n 'CONCEALMENT/REMOVAL OF CHILD WITHOUT CONSENT'\n 'ENCOURAGING MINOR TO USE COCAINE' 'ATTEMPTED MOTORCYCLE STRIP'\n 'ENCOURAGE MINOR TO USE BARBITUATES' 'ARSON OF A POLICE VEHICLE'\n 'ILLEGAL CHARITABLE SOLICITATIONS' 'OBSCENE MOVIES/ACTS'\n 'PLACING WIFE IN HOUSE OF PROSTITUTION' 'ATTEMPTED MAYHEM WITH A GUN'\n 'OVERCHARGING TAXI FARE' 'UNKNOWN COMPLAINT' 'ASSAULT BY JUVENILE SUSPECT'\n 'UNAUTHORIZED USE OF LOUD SPEAKERS' 'FRAUDULENT AUCTION'\n 'SALE OF OPIUM DERIVATIVE' 'SAFE BURGLARY OF A WAREHOUSE WITH EXPLOSIVES'\n 'AGGRAVATED ASSAULT OF POLICE OFFICER, SNIPING'\n 'BURGLARY,WAREHOUSE UNDER CONSTRT, ATT. FORCIBLE'\n 'ATTEMPTED HOMICIDE WITH EXPLOSIVES'\n 'PURCHASE FEMALE FOR THE PURPOSE OF PROSTITUTION'\n 'GRAND THEFT PHONE BOOTH' 'ATTEMPTED THEFT PHONE BOOTH'\n 'VEHICLE, RECOVERED, BUS' 'ATTEMPTED SUICIDE BY DROWNING'\n 'ASSAULT TO ROB BANK WITH A GUN'\n 'BURGLARY,HOTEL UNDER CONSTRUCTION, ATT. FORCIBLE'\n 'PLANTING/CULTIVATING PEYOTE' 'REFUSAL TO IDENTIFY'\n 'SHOOTING BY JUVENILE SUSPECT' 'DESTROYING JAIL PROPERTY-$200 OR UNDER'\n 'EMBEZZLEMENT, GRAND THEFT PUBLIC/PRIVATE OFFICIAL'] 879\nDayOfWeek \n ['Wednesday' 'Tuesday' 'Monday' 'Sunday' 'Saturday' 'Friday' 'Thursday'] 7\nPdDistrict \n ['NORTHERN' 'PARK' 'INGLESIDE' 'BAYVIEW' 'RICHMOND' 'CENTRAL' 'TARAVAL'\n 'TENDERLOIN' 'MISSION' 'SOUTHERN'] 10\nResolution \n ['ARREST, BOOKED' 'NONE' 'ARREST, CITED' 'PSYCHOPATHIC CASE'\n 'JUVENILE BOOKED' 'UNFOUNDED' 'EXCEPTIONAL CLEARANCE' 'LOCATED'\n 'CLEARED-CONTACT JUVENILE FOR MORE INFO' 'NOT PROSECUTED'\n 'JUVENILE DIVERTED' 'COMPLAINANT REFUSES TO PROSECUTE'\n 'JUVENILE ADMONISHED' 'JUVENILE CITED'\n 'DISTRICT ATTORNEY REFUSES TO PROSECUTE' 'PROSECUTED BY OUTSIDE AGENCY'\n 'PROSECUTED FOR LESSER OFFENSE'] 17\n"
],
[
"df['event'] = 1",
"_____no_output_____"
],
[
"df.year.value_counts()",
"_____no_output_____"
]
],
[
[
"2015년의 데이터가 현저하게 적다.",
"_____no_output_____"
],
[
"## 1 .시간에 따른 분석",
"_____no_output_____"
],
[
"##### 1) 연도별 범죄발생횟수",
"_____no_output_____"
]
],
[
[
"event_by_year = df[['year','event']].groupby('year').count().reset_index()",
"_____no_output_____"
],
[
"event_by_year.plot(kind='bar',x='year', y='event')",
"_____no_output_____"
]
],
[
[
"##### 1-2) 연도별 범죄유형별 범죄발생횟수",
"_____no_output_____"
]
],
[
[
"event_by_year_category = df[['year','Category','event']].groupby(['year','Category']).count().reset_index()",
"_____no_output_____"
],
[
"event_by_year_category_pivot = event_by_year_category.pivot(index=\"year\", columns='Category', values='event').fillna(0)",
"_____no_output_____"
],
[
"f, ax = plt.subplots(figsize=(11, 9))\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n\nsns.heatmap(event_by_year_category_pivot, cmap=cmap, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})",
"_____no_output_____"
]
],
[
[
"해를 거듭할수록 절도가 증가함.\n\nNON-CRIMINAL은 형사상 책임을 묻지 않는 걸 말하는 건가...(대부분 정신치료)",
"_____no_output_____"
],
[
"##### 2) 시간대별 사건발생수",
"_____no_output_____"
]
],
[
[
"event_by_hour = df[['hour','event']].groupby(['hour']).sum().reset_index()",
"_____no_output_____"
],
[
"event_by_hour.plot(kind='bar', title=\"events by hour\")",
"_____no_output_____"
]
],
[
[
"##### 2-1) 연도별 시간대별 사건발생수",
"_____no_output_____"
]
],
[
[
"event_by_year_hour = df[['year','hour','event']].groupby(['year','hour']).count().reset_index()",
"_____no_output_____"
],
[
"event_by_year_hour_pivot = event_by_year_hour.pivot(index='hour', columns='year', values='event')",
"_____no_output_____"
],
[
"event_by_year_hour_pivot",
"_____no_output_____"
],
[
"event_by_year_hour_pivot.plot(figsize=(10,7))",
"_____no_output_____"
]
],
[
[
"2015년을 제외한 2003~2014년까지 시간대별로 사건발생패턴이 유사하다.",
"_____no_output_____"
],
[
"##### 2-2) 연도별 월별 사건발생수",
"_____no_output_____"
]
],
[
[
"event_by_year_month = df[['year','month','event']].groupby(['year','month']).count().reset_index()",
"_____no_output_____"
],
[
"event_by_year_month_pivot = event_by_year_month.pivot(index='month', columns='year', values='event').fillna(method='ffill')",
"_____no_output_____"
],
[
"event_by_year_month_pivot.plot(title=\"events by year and month\")",
"_____no_output_____"
]
],
[
[
"##### 2-3) 연도별 주차별 사건발생수",
"_____no_output_____"
]
],
[
[
"event_by_year_week = df[['year','week','event']].groupby(['year','week']).count().reset_index()",
"_____no_output_____"
],
[
"event_by_year_week_pivot = event_by_year_week.pivot(index='week', columns='year', values='event').fillna(method='ffill')",
"_____no_output_____"
],
[
"event_by_year_week_pivot.plot(title=\"events by year and week\")",
"_____no_output_____"
]
],
[
[
"##### 3. 시간대별 범죄 발생수",
"_____no_output_____"
]
],
[
[
"crime = df.Category.unique()\ncrime",
"_____no_output_____"
],
[
"count = 1\nfor i in df.Category.unique():\n crime = df[df.Category == i]\n crime = crime[['year','hour','event']].groupby(['year','hour']).count().reset_index()\n crime_pivot = crime.pivot(index='hour', columns='year', values='event')\n plt.subplot(len(df.Category.unique()), 1, count)\n crime_pivot.plot()\n count += 1\nplt.show()",
"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\matplotlib\\pyplot.py:528: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).\n max_open_warning, RuntimeWarning)\n"
],
[
"crime = df[df.Category == \"WARRANTS\"]\ncrime = crime[['year','hour','event']].groupby(['year','hour']).count().reset_index()\ncrime_pivot = crime.pivot(index='hour', columns='year', values='event')\ncrime_pivot.plot()",
"_____no_output_____"
]
],
[
[
"##### 4. 요일별 범죄수",
"_____no_output_____"
]
],
[
[
"dayofweek_event = df[['DayOfWeek','event']].groupby(['DayOfWeek']).count().reset_index()",
"_____no_output_____"
],
[
"dayofweek_event.plot(x='DayOfWeek', y='event',kind='bar', color='r')",
"_____no_output_____"
]
],
[
[
"## 2. 장소별",
"_____no_output_____"
],
[
"##### 1) PdDistrict별 사건발생수",
"_____no_output_____"
]
],
[
[
"event_by_PdDistrict = df[['PdDistrict','event']].groupby('PdDistrict').count().reset_index()",
"_____no_output_____"
],
[
"event_by_PdDistrict.sort_values(by='event', ascending=False, inplace=True)",
"_____no_output_____"
],
[
"event_by_PdDistrict.plot(kind='bar', x='PdDistrict')",
"_____no_output_____"
]
],
[
[
"##### 2) Address별 사건발생수",
"_____no_output_____"
]
],
[
[
"event_by_address_pd = df[['PdDistrict','Address','event']].groupby(['PdDistrict','Address']).count().reset_index()\nevent_by_address_pd.sort_values(by='event', ascending=False)",
"_____no_output_____"
],
[
"most_crime = df[['Category','event']].groupby(\"Category\").sum().reset_index().sort_values(by=\"event\", ascending=False)\nmost_crime.plot(kind='bar', x='Category', title=\"What is most crime?\")",
"_____no_output_____"
]
],
[
[
"##### 각 범죄가 일어난 곳은 어느 곳일까? 어디서 제일 많이 일어날까?",
"_____no_output_____"
]
],
[
[
"crime_address = df[['Category','Address','event']].groupby(['Category','Address']).sum().reset_index()\ncrime_address.sort_values(by=['Category','event'], ascending=False, inplace=True)",
"_____no_output_____"
],
[
"len(crime_address[crime_address.Category == \"LARCENY/THEFT\"]), crime_address[crime_address.Category == \"LARCENY/THEFT\"]",
"_____no_output_____"
]
],
[
[
"#### 각 범죄별로 가장 많이 발생한 위치 5군데를 뽑아보자",
"_____no_output_____"
]
],
[
[
"for crime in crime_address.Category.unique():\n result = crime_address[crime_address.Category == crime]\n print(\"Crime: \",crime,\"\\t\", \"Address count: \",len(result),\"\\n\" ,result.head(),\"\\n\")",
"Crime: WEAPON LAWS \t Address count: 3565 \n Category Address event\n169473 WEAPON LAWS 800 Block of BRYANT ST 156\n168393 WEAPON LAWS 2000 Block of MISSION ST 77\n167176 WEAPON LAWS 0 Block of 6TH ST 44\n167431 WEAPON LAWS 0 Block of TURK ST 42\n169555 WEAPON LAWS 900 Block of ELLSWORTH ST 37 \n\nCrime: WARRANTS \t Address count: 7836 \n Category Address event\n163882 WARRANTS 800 Block of BRYANT ST 1719\n161754 WARRANTS 2000 Block of MISSION ST 567\n163946 WARRANTS 800 Block of MARKET ST 477\n159860 WARRANTS 0 Block of TURK ST 392\n160343 WARRANTS 1000 Block of POTRERO AV 322 \n\nCrime: VEHICLE THEFT \t Address count: 14588 \n Category Address event\n147669 VEHICLE THEFT 1500 Block of BAY SHORE BL 162\n150974 VEHICLE THEFT 300 Block of OFARRELL ST 145\n153595 VEHICLE THEFT 800 Block of BRYANT ST 128\n152065 VEHICLE THEFT 400 Block of STOCKTON ST 92\n150942 VEHICLE THEFT 300 Block of MASON ST 82 \n\nCrime: VANDALISM \t Address count: 12395 \n Category Address event\n140471 VANDALISM 800 Block of BRYANT ST 1155\n136268 VANDALISM 200 Block of INTERSTATE80 HY 110\n134193 VANDALISM 1000 Block of POTRERO AV 104\n133066 VANDALISM 0 Block of PHELAN AV 88\n133732 VANDALISM 100 Block of KISKA RD 83 \n\nCrime: TRESPASS \t Address count: 2591 \n Category Address event\n130305 TRESPASS 1000 Block of POTRERO AV 248\n132010 TRESPASS 800 Block of BRYANT ST 150\n132047 TRESPASS 800 Block of MARKET ST 149\n129878 TRESPASS 0 Block of GROVE ST 107\n131320 TRESPASS 300 Block of ELLIS ST 106 \n\nCrime: TREA \t Address count: 6 \n Category Address event\n129752 TREA 1000 Block of IOWA ST 1\n129753 TREA 1300 Block of ARMSTRONG AV 1\n129754 TREA 2300 Block of STOCKTON ST 1\n129755 TREA 300 Block of 20TH ST 1\n129756 TREA 500 Block of CASTRO ST 1 \n\nCrime: SUSPICIOUS OCC \t Address count: 9297 \n Category Address event\n127166 SUSPICIOUS OCC 800 Block of BRYANT ST 1153\n121956 SUSPICIOUS OCC 1000 Block of POTRERO AV 186\n123945 SUSPICIOUS OCC 2000 Block of MISSION ST 103\n120479 SUSPICIOUS OCC 0 Block of 6TH ST 100\n127254 SUSPICIOUS OCC 800 Block of MARKET ST 100 \n\nCrime: SUICIDE \t Address count: 410 \n Category Address event\n120114 SUICIDE 100 Block of GGBRIDGE HY 21\n120416 SUICIDE 800 Block of BRYANT ST 16\n120147 SUICIDE 1000 Block of POTRERO AV 12\n120430 SUICIDE 800 Block of POTRERO AV 6\n120047 SUICIDE 0 Block of 6TH ST 4 \n\nCrime: STOLEN PROPERTY \t Address count: 2640 \n Category Address event\n119218 STOLEN PROPERTY 800 Block of BRYANT ST 93\n117849 STOLEN PROPERTY 1100 Block of MARKET ST 90\n119250 STOLEN PROPERTY 800 Block of MARKET ST 44\n117596 STOLEN PROPERTY 0 Block of UNITEDNATIONS PZ 40\n117799 STOLEN PROPERTY 1000 Block of MARKET ST 37 \n\nCrime: SEX OFFENSES NON FORCIBLE \t Address count: 132 \n Category Address event\n117382 SEX OFFENSES NON FORCIBLE 800 Block of BRYANT ST 12\n117289 SEX OFFENSES NON FORCIBLE 1000 Block of POTRERO AV 4\n117280 SEX OFFENSES NON FORCIBLE 0 Block of PARK ST 2\n117373 SEX OFFENSES NON FORCIBLE 600 Block of LONDON ST 2\n117273 SEX OFFENSES NON FORCIBLE 0 Block of 5THSTNORTH ST 1 \n\nCrime: SEX OFFENSES FORCIBLE \t Address count: 2273 \n Category Address event\n116720 SEX OFFENSES FORCIBLE 800 Block of BRYANT ST 296\n115375 SEX OFFENSES FORCIBLE 1000 Block of POTRERO AV 59\n116259 SEX OFFENSES FORCIBLE 3400 Block of 17TH ST 37\n115008 SEX OFFENSES FORCIBLE 0 Block of 6TH ST 27\n116749 SEX OFFENSES FORCIBLE 800 Block of MARKET ST 19 \n\nCrime: SECONDARY CODES \t Address count: 4293 \n Category Address event\n114087 SECONDARY CODES 800 Block of BRYANT ST 312\n112516 SECONDARY CODES 2100 Block of 24TH AV 82\n112484 SECONDARY CODES 2000 Block of MISSION ST 38\n112338 SECONDARY CODES 200 Block of INTERSTATE80 HY 36\n111023 SECONDARY CODES 0 Block of POWELL ST 35 \n\nCrime: RUNAWAY \t Address count: 559 \n Category Address event\n110291 RUNAWAY 1200 Block of PAGE ST 338\n110679 RUNAWAY 900 Block of POTRERO AV 174\n110653 RUNAWAY 800 Block of CAPITOL AV 94\n110179 RUNAWAY 0 Block of HAROLD AV 90\n110328 RUNAWAY 1400 Block of PHELPS ST 74 \n\nCrime: ROBBERY \t Address count: 7717 \n Category Address event\n106672 ROBBERY 800 Block of BRYANT ST 591\n104606 ROBBERY 2000 Block of MISSION ST 167\n106730 ROBBERY 800 Block of MARKET ST 156\n106838 ROBBERY 900 Block of MARKET ST 112\n103985 ROBBERY 16TH ST / MISSION ST 110 \n\nCrime: RECOVERED VEHICLE \t Address count: 2319 \n Category Address event\n101090 RECOVERED VEHICLE 200 Block of INTERSTATE80 HY 12\n100999 RECOVERED VEHICLE 1800 Block of SUNNYDALE AV 11\n101640 RECOVERED VEHICLE 400 Block of MINNA ST 11\n102028 RECOVERED VEHICLE 800 Block of MISSION ST 11\n102079 RECOVERED VEHICLE 900 Block of MISSION ST 11 \n\nCrime: PROSTITUTION \t Address count: 752 \n Category Address event\n99905 PROSTITUTION ELLIS ST / HYDE ST 422\n99525 PROSTITUTION 17TH ST / SHOTWELL ST 353\n99555 PROSTITUTION 19TH ST / SHOTWELL ST 350\n100027 PROSTITUTION POST ST / LARKIN ST 250\n100068 PROSTITUTION SUTTER ST / LARKIN ST 231 \n\nCrime: PORNOGRAPHY/OBSCENE MAT \t Address count: 22 \n Category Address event\n99338 PORNOGRAPHY/OBSCENE MAT 0 Block of BLAKE ST 1\n99339 PORNOGRAPHY/OBSCENE MAT 0 Block of HALLAM ST 1\n99340 PORNOGRAPHY/OBSCENE MAT 100 Block of OLIVE ST 1\n99341 PORNOGRAPHY/OBSCENE MAT 1000 Block of POTRERO AV 1\n99342 PORNOGRAPHY/OBSCENE MAT 1100 Block of FILLMORE ST 1 \n\nCrime: OTHER OFFENSES \t Address count: 16072 \n Category Address event\n92320 OTHER OFFENSES 800 Block of BRYANT ST 3019\n87989 OTHER OFFENSES 2000 Block of MISSION ST 1209\n86676 OTHER OFFENSES 16TH ST / MISSION ST 673\n84289 OTHER OFFENSES 0 Block of TURK ST 565\n92435 OTHER OFFENSES 800 Block of MARKET ST 562 \n\nCrime: NON-CRIMINAL \t Address count: 13580 \n Category Address event\n78505 NON-CRIMINAL 800 Block of BRYANT ST 5583\n71712 NON-CRIMINAL 1000 Block of POTRERO AV 795\n75705 NON-CRIMINAL 300 Block of EDDY ST 628\n78046 NON-CRIMINAL 600 Block of VALENCIA ST 549\n78611 NON-CRIMINAL 800 Block of MARKET ST 449 \n\nCrime: MISSING PERSON \t Address count: 4890 \n Category Address event\n66160 MISSING PERSON 1400 Block of PHELPS ST 1468\n68760 MISSING PERSON 800 Block of BRYANT ST 777\n68963 MISSING PERSON 900 Block of POTRERO AV 624\n65143 MISSING PERSON 0 Block of MOSS ST 547\n65083 MISSING PERSON 0 Block of LEDYARD ST 540 \n\nCrime: LOITERING \t Address count: 490 \n Category Address event\n64711 LOITERING MISSION ST / SOUTH VAN NESS AV 49\n64651 LOITERING HARRISON ST / 5TH ST 45\n64763 LOITERING SOUTH VAN NESS AV / MISSION ST 39\n64757 LOITERING SOUTH VAN NESS AV / 13TH ST 36\n64321 LOITERING 0 Block of GROVE ST 35 \n\nCrime: LIQUOR LAWS \t Address count: 994 \n Category Address event\n63990 LIQUOR LAWS 800 Block of 3RD ST 51\n63991 LIQUOR LAWS 800 Block of BRYANT ST 29\n64017 LIQUOR LAWS 900 Block of MARKET ST 26\n63313 LIQUOR LAWS 0 Block of 6TH ST 20\n64122 LIQUOR LAWS HAIGHT ST / COLE ST 18 \n\n"
]
],
[
[
"1. 800 Block of BRYANT ST : 거의 모든 범죄가 일어남...범죄소굴\n2. 각 범죄별로 상위 랭크된 Address에 block이 많이 들어간다. block유무로 binarize..?",
"_____no_output_____"
],
[
"#### Address에 block유무로 binarize",
"_____no_output_____"
]
],
[
[
"a = np.array([1 if 'Block' in i else 0 for i in df.Address.values])\na",
"_____no_output_____"
]
],
[
[
"### Crime Visualization",
"_____no_output_____"
]
],
[
[
"event_by_crimeAddress = df[['Category','Address','X','Y','event']].groupby(['Category','Address','X','Y']).sum().reset_index()\nevent_by_crimeAddress",
"_____no_output_____"
],
[
"df[df.Y == event_by_crimeAddress.Y.max()]",
"_____no_output_____"
]
],
[
[
"뜬금없이 위도 90은 뭐냐...구글맵에 바다로 뜨는데ㅡㅡ",
"_____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"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4a93b5375b73b06f4b053899b334124bd0a2f160
| 28,388 |
ipynb
|
Jupyter Notebook
|
docs/tutorials/starting/analysis_2.ipynb
|
aaguasca/gammapy
|
b1a4e9dbaeec23b3eaca1c874752e92432920a42
|
[
"BSD-3-Clause"
] | null | null | null |
docs/tutorials/starting/analysis_2.ipynb
|
aaguasca/gammapy
|
b1a4e9dbaeec23b3eaca1c874752e92432920a42
|
[
"BSD-3-Clause"
] | null | null | null |
docs/tutorials/starting/analysis_2.ipynb
|
aaguasca/gammapy
|
b1a4e9dbaeec23b3eaca1c874752e92432920a42
|
[
"BSD-3-Clause"
] | null | null | null | 28.849593 | 310 | 0.5763 |
[
[
[
"# Low level API\n\n## Prerequisites\n\n- Understanding the gammapy data workflow, in particular what are DL3 events and instrument response functions (IRF).\n- Understanding of the data reduction and modeling fitting process as shown in the [analysis with the high level interface tutorial](analysis_1.ipynb)\n\n## Context\n\nThis notebook is an introduction to gammapy analysis this time using the lower level classes and functions\nthe library.\nThis allows to understand what happens during two main gammapy analysis steps, data reduction and modeling/fitting. \n\n**Objective: Create a 3D dataset of the Crab using the H.E.S.S. DL3 data release 1 and perform a simple model fitting of the Crab nebula using the lower level gammapy API.**\n\n## Proposed approach\n\nHere, we have to interact with the data archive (with the `~gammapy.data.DataStore`) to retrieve a list of selected observations (`~gammapy.data.Observations`). Then, we define the geometry of the `~gammapy.datasets.MapDataset` object we want to produce and the maker object that reduce an observation\nto a dataset. \n\nWe can then proceed with data reduction with a loop over all selected observations to produce datasets in the relevant geometry and stack them together (i.e. sum them all).\n\nIn practice, we have to:\n- Create a `~gammapy.data.DataStore` poiting to the relevant data \n- Apply an observation selection to produce a list of observations, a `~gammapy.data.Observations` object.\n- Define a geometry of the Map we want to produce, with a sky projection and an energy range.\n - Create a `~gammapy.maps.MapAxis` for the energy\n - Create a `~gammapy.maps.WcsGeom` for the geometry\n- Create the necessary makers : \n - the map dataset maker : `~gammapy.makers.MapDatasetMaker`\n - the background normalization maker, here a `~gammapy.makers.FoVBackgroundMaker`\n - and usually the safe range maker : `~gammapy.makers.SafeRangeMaker`\n- Perform the data reduction loop. And for every observation:\n - Apply the makers sequentially to produce the current `~gammapy.datasets.MapDataset`\n - Stack it on the target one.\n- Define the `~gammapy.modeling.models.SkyModel` to apply to the dataset.\n- Create a `~gammapy.modeling.Fit` object and run it to fit the model parameters\n- Apply a `~gammapy.estimators.FluxPointsEstimator` to compute flux points for the spectral part of the fit.\n\n## Setup\nFirst, we setup the analysis by performing required imports.\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"from pathlib import Path\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom regions import CircleSkyRegion",
"_____no_output_____"
],
[
"from gammapy.data import DataStore\nfrom gammapy.datasets import MapDataset\nfrom gammapy.maps import WcsGeom, MapAxis\nfrom gammapy.makers import MapDatasetMaker, SafeMaskMaker, FoVBackgroundMaker\nfrom gammapy.modeling.models import (\n SkyModel,\n PowerLawSpectralModel,\n PointSpatialModel,\n FoVBackgroundModel,\n)\nfrom gammapy.modeling import Fit\nfrom gammapy.estimators import FluxPointsEstimator",
"_____no_output_____"
]
],
[
[
"## Defining the datastore and selecting observations\n\nWe first use the `~gammapy.data.DataStore` object to access the observations we want to analyse. Here the H.E.S.S. DL3 DR1. ",
"_____no_output_____"
]
],
[
[
"data_store = DataStore.from_dir(\"$GAMMAPY_DATA/hess-dl3-dr1\")",
"_____no_output_____"
]
],
[
[
"We can now define an observation filter to select only the relevant observations. \nHere we use a cone search which we define with a python dict.\n\nWe then filter the `ObservationTable` with `~gammapy.data.ObservationTable.select_observations()`.",
"_____no_output_____"
]
],
[
[
"selection = dict(\n type=\"sky_circle\",\n frame=\"icrs\",\n lon=\"83.633 deg\",\n lat=\"22.014 deg\",\n radius=\"5 deg\",\n)\nselected_obs_table = data_store.obs_table.select_observations(selection)",
"_____no_output_____"
]
],
[
[
"We can now retrieve the relevant observations by passing their `obs_id` to the`~gammapy.data.DataStore.get_observations()` method.",
"_____no_output_____"
]
],
[
[
"observations = data_store.get_observations(selected_obs_table[\"OBS_ID\"])",
"_____no_output_____"
]
],
[
[
"## Preparing reduced datasets geometry\n\nNow we define a reference geometry for our analysis, We choose a WCS based geometry with a binsize of 0.02 deg and also define an energy axis: ",
"_____no_output_____"
]
],
[
[
"energy_axis = MapAxis.from_energy_bounds(1.0, 10.0, 4, unit=\"TeV\")\n\ngeom = WcsGeom.create(\n skydir=(83.633, 22.014),\n binsz=0.02,\n width=(2, 2),\n frame=\"icrs\",\n proj=\"CAR\",\n axes=[energy_axis],\n)\n\n# Reduced IRFs are defined in true energy (i.e. not measured energy).\nenergy_axis_true = MapAxis.from_energy_bounds(\n 0.5, 20, 10, unit=\"TeV\", name=\"energy_true\"\n)",
"_____no_output_____"
]
],
[
[
"Now we can define the target dataset with this geometry.",
"_____no_output_____"
]
],
[
[
"stacked = MapDataset.create(\n geom=geom, energy_axis_true=energy_axis_true, name=\"crab-stacked\"\n)",
"_____no_output_____"
]
],
[
[
"## Data reduction\n\n### Create the maker classes to be used\n\nThe `~gammapy.datasets.MapDatasetMaker` object is initialized as well as the `~gammapy.makers.SafeMaskMaker` that carries here a maximum offset selection.",
"_____no_output_____"
]
],
[
[
"offset_max = 2.5 * u.deg\nmaker = MapDatasetMaker()\nmaker_safe_mask = SafeMaskMaker(\n methods=[\"offset-max\", \"aeff-max\"], offset_max=offset_max\n)",
"_____no_output_____"
],
[
"circle = CircleSkyRegion(\n center=SkyCoord(\"83.63 deg\", \"22.14 deg\"), radius=0.2 * u.deg\n)\nexclusion_mask = ~geom.region_mask(regions=[circle])\nmaker_fov = FoVBackgroundMaker(method=\"fit\", exclusion_mask=exclusion_mask)",
"_____no_output_____"
]
],
[
[
"### Perform the data reduction loop",
"_____no_output_____"
]
],
[
[
"%%time\n\nfor obs in observations:\n # First a cutout of the target map is produced\n cutout = stacked.cutout(\n obs.pointing_radec, width=2 * offset_max, name=f\"obs-{obs.obs_id}\"\n )\n # A MapDataset is filled in this cutout geometry\n dataset = maker.run(cutout, obs)\n # The data quality cut is applied\n dataset = maker_safe_mask.run(dataset, obs)\n # fit background model\n dataset = maker_fov.run(dataset)\n print(\n f\"Background norm obs {obs.obs_id}: {dataset.background_model.spectral_model.norm.value:.2f}\"\n )\n # The resulting dataset cutout is stacked onto the final one\n stacked.stack(dataset)",
"_____no_output_____"
],
[
"print(stacked)",
"_____no_output_____"
]
],
[
[
"### Inspect the reduced dataset",
"_____no_output_____"
]
],
[
[
"stacked.counts.sum_over_axes().smooth(0.05 * u.deg).plot(\n stretch=\"sqrt\", add_cbar=True\n);",
"_____no_output_____"
]
],
[
[
"## Save dataset to disk\n\nIt is common to run the preparation step independent of the likelihood fit, because often the preparation of maps, PSF and energy dispersion is slow if you have a lot of data. We first create a folder:",
"_____no_output_____"
]
],
[
[
"path = Path(\"analysis_2\")\npath.mkdir(exist_ok=True)",
"_____no_output_____"
]
],
[
[
"And then write the maps and IRFs to disk by calling the dedicated `~gammapy.datasets.MapDataset.write()` method:",
"_____no_output_____"
]
],
[
[
"filename = path / \"crab-stacked-dataset.fits.gz\"\nstacked.write(filename, overwrite=True)",
"_____no_output_____"
]
],
[
[
"## Define the model\nWe first define the model, a `SkyModel`, as the combination of a point source `SpatialModel` with a powerlaw `SpectralModel`:",
"_____no_output_____"
]
],
[
[
"target_position = SkyCoord(ra=83.63308, dec=22.01450, unit=\"deg\")\nspatial_model = PointSpatialModel(\n lon_0=target_position.ra, lat_0=target_position.dec, frame=\"icrs\"\n)\n\nspectral_model = PowerLawSpectralModel(\n index=2.702,\n amplitude=4.712e-11 * u.Unit(\"1 / (cm2 s TeV)\"),\n reference=1 * u.TeV,\n)\n\nsky_model = SkyModel(\n spatial_model=spatial_model, spectral_model=spectral_model, name=\"crab\"\n)\n\nbkg_model = FoVBackgroundModel(dataset_name=\"crab-stacked\")",
"_____no_output_____"
]
],
[
[
"Now we assign this model to our reduced dataset:",
"_____no_output_____"
]
],
[
[
"stacked.models = [sky_model, bkg_model]",
"_____no_output_____"
]
],
[
[
"## Fit the model\n\nThe `~gammapy.modeling.Fit` class is orchestrating the fit, connecting the `stats` method of the dataset to the minimizer. By default, it uses `iminuit`.\n\nIts constructor takes a list of dataset as argument.",
"_____no_output_____"
]
],
[
[
"%%time\nfit = Fit(optimize_opts={\"print_level\": 1})\nresult = fit.run([stacked])",
"_____no_output_____"
]
],
[
[
"The `FitResult` contains information about the optimization and parameter error calculation.",
"_____no_output_____"
]
],
[
[
"print(result)",
"_____no_output_____"
]
],
[
[
"The fitted parameters are visible from the `~astropy.modeling.models.Models` object.",
"_____no_output_____"
]
],
[
[
"stacked.models.to_parameters_table()",
"_____no_output_____"
]
],
[
[
"### Inspecting residuals\n\nFor any fit it is useful to inspect the residual images. We have a few options on the dataset object to handle this. First we can use `.plot_residuals_spatial()` to plot a residual image, summed over all energies:",
"_____no_output_____"
]
],
[
[
"stacked.plot_residuals_spatial(method=\"diff/sqrt(model)\", vmin=-0.5, vmax=0.5);",
"_____no_output_____"
]
],
[
[
"In addition, we can also specify a region in the map to show the spectral residuals:",
"_____no_output_____"
]
],
[
[
"region = CircleSkyRegion(\n center=SkyCoord(\"83.63 deg\", \"22.14 deg\"), radius=0.5 * u.deg\n)",
"_____no_output_____"
],
[
"stacked.plot_residuals(\n kwargs_spatial=dict(method=\"diff/sqrt(model)\", vmin=-0.5, vmax=0.5),\n kwargs_spectral=dict(region=region),\n);",
"_____no_output_____"
]
],
[
[
"We can also directly access the `.residuals()` to get a map, that we can plot interactively:",
"_____no_output_____"
]
],
[
[
"residuals = stacked.residuals(method=\"diff\")\nresiduals.smooth(\"0.08 deg\").plot_interactive(\n cmap=\"coolwarm\", vmin=-0.2, vmax=0.2, stretch=\"linear\", add_cbar=True\n);",
"_____no_output_____"
]
],
[
[
"## Plot the fitted spectrum",
"_____no_output_____"
],
[
"### Making a butterfly plot \n\nThe `SpectralModel` component can be used to produce a, so-called, butterfly plot showing the envelope of the model taking into account parameter uncertainties:",
"_____no_output_____"
]
],
[
[
"spec = sky_model.spectral_model",
"_____no_output_____"
]
],
[
[
"Now we can actually do the plot using the `plot_error` method:",
"_____no_output_____"
]
],
[
[
"energy_bounds = [1, 10] * u.TeV\nspec.plot(energy_bounds=energy_bounds, energy_power=2)\nax = spec.plot_error(energy_bounds=energy_bounds, energy_power=2)",
"_____no_output_____"
]
],
[
[
"### Computing flux points\n\nWe can now compute some flux points using the `~gammapy.estimators.FluxPointsEstimator`. \n\nBesides the list of datasets to use, we must provide it the energy intervals on which to compute flux points as well as the model component name. ",
"_____no_output_____"
]
],
[
[
"energy_edges = [1, 2, 4, 10] * u.TeV\nfpe = FluxPointsEstimator(energy_edges=energy_edges, source=\"crab\")",
"_____no_output_____"
],
[
"%%time\nflux_points = fpe.run(datasets=[stacked])",
"_____no_output_____"
],
[
"ax = spec.plot_error(energy_bounds=energy_bounds, energy_power=2)\nflux_points.plot(ax=ax, energy_power=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",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a93c48400007b101b7f4b3a6710881e91280a70
| 284,598 |
ipynb
|
Jupyter Notebook
|
benchmarking_FRESA-CAD.ipynb
|
joseTamezPena/jupyter
|
0c994f879d3b8cf03e987cbb7cf1b5cebf203973
|
[
"Apache-2.0"
] | 2 |
2019-11-29T12:39:52.000Z
|
2021-11-09T02:58:24.000Z
|
benchmarking_FRESA-CAD.ipynb
|
joseTamezPena/jupyter
|
0c994f879d3b8cf03e987cbb7cf1b5cebf203973
|
[
"Apache-2.0"
] | null | null | null |
benchmarking_FRESA-CAD.ipynb
|
joseTamezPena/jupyter
|
0c994f879d3b8cf03e987cbb7cf1b5cebf203973
|
[
"Apache-2.0"
] | 5 |
2020-07-23T00:55:06.000Z
|
2020-12-19T22:16:45.000Z
| 48.541361 | 1,461 | 0.542551 |
[
[
[
"# Benchmark FRESA.CAD BSWIMS final Script\n",
"_____no_output_____"
],
[
"This algorithm implementation uses R code and a Python library (rpy2) to connect with it, in order to run the following it is necesary to have installed both on your computer:\n\n- R (you can download in https://www.r-project.org/) <br>\n- install rpy2 by <code> pip install rpy2 </code>",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport sys\nfrom pathlib import Path\nsys.path.append(\"../tadpole-algorithms\")\nimport tadpole_algorithms\nfrom tadpole_algorithms.models import Benchmark_FRESACAD_R\nfrom tadpole_algorithms.preprocessing.split import split_test_train_tadpole\n#rpy2 libs and funcs\nimport rpy2.robjects.packages as rpackages\nfrom rpy2.robjects.vectors import StrVector\nfrom rpy2.robjects import r, pandas2ri \nfrom rpy2 import robjects\nfrom rpy2.robjects.conversion import localconverter\n",
"_____no_output_____"
],
[
"# Load D1_D2 train and possible test data set\ndata_path_train_test = Path(\"data/TADPOLE_D1_D2.csv\")\ndata_df_train_test = pd.read_csv(data_path_train_test)\n\n# Load data Dictionary\ndata_path_Dictionaty = Path(\"data/TADPOLE_D1_D2_Dict.csv\")\ndata_Dictionaty = pd.read_csv(data_path_Dictionaty)\n\n# Load D3 possible test set\ndata_path_test = Path(\"data/TADPOLE_D3.csv\")\ndata_D3 = pd.read_csv(data_path_test)\n\n# Load D4 evaluation data set \ndata_path_eval = Path(\"data/TADPOLE_D4_corr.csv\")\ndata_df_eval = pd.read_csv(data_path_eval)\n\n# Split data in test, train and evaluation data\ntrain_df, test_df, eval_df = split_test_train_tadpole(data_df_train_test, data_df_eval)\n\n#instanciate the model to get the functions\nmodel = Benchmark_FRESACAD_R()\n#set the flag to true to use a preprocessed data\nUSE_PREPROC = False\n",
"c:\\program files\\python38\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3146: DtypeWarning: Columns (471,473,474,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,569,570,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,599,601,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,624,625,626,627,628,629,630,631,632,633,634,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,745,746,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,770,771,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,794,795,797,798,799,800,801,802,803,804,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831) have mixed types.Specify dtype option on import or set low_memory=False.\n has_raised = await self.run_ast_nodes(code_ast.body, cell_name,\n"
],
[
"#preprocess the data\nD1Train,D2Test,D3Train,D3Test = model.extractTrainTestDataSets_R(\"data/TADPOLE_D1_D2.csv\",\"data/TADPOLE_D3.csv\")\n",
"2020-12-25 13:03:12,155 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Extract Training and Testing sets\n"
],
[
"# AdjustedTrainFrame,testingFrame,Train_Imputed,Test_Imputed = model.preproc_tadpole_D1_D2(data_df_train_test,USE_PREPROC)\nAdjustedTrainFrame,testingFrame,Train_Imputed,Test_Imputed = model.preproc_with_R(D1Train,D2Test,data_Dictionaty,usePreProc=USE_PREPROC)\n",
"2020-12-25 13:04:04,571 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Prepocess Data Frames\n2020-12-25 13:04:36,208 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: Rcpp\n\n2020-12-25 13:04:36,675 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: stringr\n\n2020-12-25 13:04:36,847 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: miscTools\n\n2020-12-25 13:04:36,960 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: Hmisc\n\n2020-12-25 13:04:36,968 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: lattice\n\n2020-12-25 13:04:37,099 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: survival\n\n2020-12-25 13:04:37,992 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: Formula\n\n2020-12-25 13:04:38,021 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: ggplot2\n\n2020-12-25 13:04:39,715 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \nAttaching package: 'Hmisc'\n\n\n2020-12-25 13:04:39,717 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: The following objects are masked from 'package:base':\n\n format.pval, units\n\n\n2020-12-25 13:04:39,723 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Loading required package: pROC\n\n2020-12-25 13:04:39,866 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Type 'citation(\"pROC\")' for a citation.\n\n2020-12-25 13:04:39,869 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \nAttaching package: 'pROC'\n\n\n2020-12-25 13:04:39,870 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: The following objects are masked from 'package:stats':\n\n cov, smooth, var\n\n\n[1] \"Cortical Thickness Average of RightBankssts\" \n[2] \"Cortical Thickness Average of RightCaudalAnteriorCingulate\"\n[3] \"Cortical Thickness Average of RightCaudalMiddleFrontal\" \n[4] \"Cortical Thickness Average of RightBankssts\" \n[5] \"Cortical Thickness Average of RightCaudalAnteriorCingulate\"\n[1] \"Cortical Thickness Average of LeftBankssts\" \n[2] \"Cortical Thickness Average of LeftCaudalAnteriorCingulate\"\n[3] \"Cortical Thickness Average of LeftCaudalMiddleFrontal\" \n[4] \"Cortical Thickness Average of LeftBankssts\" \n[5] \"Cortical Thickness Average of LeftCaudalAnteriorCingulate\"\n[1] 1907 782\n[1] 371\n [1] \"RID\" \n [2] \"D1\" \n [3] \"D2\" \n [4] \"SITE\" \n [5] \"COLPROT\" \n [6] \"ORIGPROT\" \n [7] \"VISCODE\" \n [8] \"EXAMDATE_bl\" \n [9] \"EXAMDATE\" \n [10] \"Years_bl\" \n [11] \"Month_bl\" \n [12] \"Month\" \n [13] \"M\" \n [14] \"DX\" \n [15] \"DX_bl\" \n [16] \"DXCHANGE\" \n [17] \"AGE\" \n [18] \"PTGENDER\" \n [19] \"PTEDUCAT\" \n [20] \"PTETHCAT\" \n [21] \"PTRACCAT\" \n [22] \"PTMARRY\" \n [23] \"CDRSB\" \n [24] \"ADAS11\" \n [25] \"ADAS13\" \n [26] \"MMSE\" \n [27] \"RAVLT_learning\" \n [28] \"RAVLT_immediate\" \n [29] \"FAQ\" \n [30] \"CDRSB_bl\" \n [31] \"ADAS11_bl\" \n [32] \"ADAS13_bl\" \n [33] \"MMSE_bl\" \n [34] \"RAVLT_learning_bl\" \n [35] \"RAVLT_immediate_bl\" \n [36] \"FAQ_bl\" \n [37] \"APOE4\" \n [38] \"Ventricles\" \n [39] \"WholeBrain\" \n [40] \"ICV\" \n [41] \"Ventricles_bl\" \n [42] \"Hippocampus_bl\" \n [43] \"WholeBrain_bl\" \n [44] \"Entorhinal_bl\" \n [45] \"Fusiform_bl\" \n [46] \"MidTemp_bl\" \n [47] \"ICV_bl\" \n [48] \"FDG_bl\" \n [49] \"ST10CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [50] \"ST1SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [51] \"ST2SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [52] \"ST3SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [53] \"ST4SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [54] \"ST5SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [55] \"ST6SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [56] \"ST7SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [57] \"ST9SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [58] \"ST68SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [59] \"ST69SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [60] \"ST127SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [61] \"ST128SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [62] \"nICV\" \n [63] \"Mean_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [64] \"Mean_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [65] \"Mean_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [66] \"Mean_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [67] \"Mean_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [68] \"Mean_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [69] \"Mean_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [70] \"Mean_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [71] \"Mean_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [72] \"Mean_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [73] \"Mean_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [74] \"Mean_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [75] \"Mean_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [76] \"Mean_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [77] \"Mean_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [78] \"Mean_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [79] \"Mean_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [80] \"Mean_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [81] \"Mean_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [82] \"Mean_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [83] \"Mean_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [84] \"Mean_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [85] \"Mean_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [86] \"Mean_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [87] \"Mean_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [88] \"Mean_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [89] \"Mean_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [90] \"Mean_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [91] \"Mean_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [92] \"Mean_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [93] \"Mean_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [94] \"Mean_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [95] \"Mean_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [96] \"Mean_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [97] \"Mean_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [98] \"Mean_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [99] \"Mean_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[100] \"Mean_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[101] \"Mean_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[102] \"Mean_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[103] \"Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[104] \"Mean_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[105] \"Mean_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[106] \"Mean_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[107] \"Mean_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[108] \"Mean_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[109] \"Mean_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[110] \"Mean_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[111] \"Dif_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[112] \"Dif_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[113] \"Dif_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[114] \"Dif_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[115] \"Dif_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[116] \"Dif_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[117] \"Dif_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[118] \"Dif_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[119] \"Dif_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[120] \"Dif_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[121] \"Dif_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[122] \"Dif_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[123] \"Dif_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[124] \"Dif_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[125] \"Dif_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[126] \"Dif_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[127] \"Dif_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[128] \"Dif_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[129] \"Dif_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[130] \"Dif_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[131] \"Dif_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[132] \"Dif_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[133] \"Dif_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[134] \"Dif_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[135] \"Dif_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[136] \"Dif_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[137] \"Dif_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[138] \"Dif_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[139] \"Dif_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[140] \"Dif_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[141] \"Dif_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[142] \"Dif_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[143] \"Dif_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[144] \"Dif_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[145] \"Dif_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[146] \"Dif_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[147] \"Dif_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[148] \"Dif_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[149] \"Dif_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[150] \"Dif_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[151] \"Dif_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[152] \"Dif_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[153] \"Dif_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[154] \"Dif_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[155] \"Dif_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[156] \"Dif_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[157] \"Dif_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[158] \"Dif_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[159] \"Mean_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[160] \"Mean_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[161] \"Mean_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[162] \"Mean_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[163] \"Mean_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[164] \"Mean_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[165] \"Mean_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[166] \"Mean_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[167] \"Mean_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[168] \"Mean_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[169] \"Mean_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[170] \"Mean_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[171] \"Mean_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[172] \"Mean_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[173] \"Mean_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[174] \"Mean_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[175] \"Mean_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[176] \"Mean_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[177] \"Mean_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[178] \"Mean_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[179] \"Mean_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[180] \"Mean_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[181] \"Mean_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[182] \"Mean_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[183] \"Mean_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[184] \"Mean_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[185] \"Mean_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[186] \"Mean_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[187] \"Mean_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[188] \"Mean_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[189] \"Mean_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[190] \"Mean_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[191] \"Mean_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[192] \"Mean_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[193] \"Dif_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[194] \"Dif_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[195] \"Dif_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[196] \"Dif_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[197] \"Dif_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[198] \"Dif_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[199] \"Dif_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[200] \"Dif_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[201] \"Dif_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[202] \"Dif_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[203] \"Dif_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[204] \"Dif_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[205] \"Dif_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[206] \"Dif_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[207] \"Dif_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[208] \"Dif_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[209] \"Dif_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[210] \"Dif_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[211] \"Dif_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[212] \"Dif_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[213] \"Dif_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[214] \"Dif_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[215] \"Dif_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[216] \"Dif_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[217] \"Dif_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[218] \"Dif_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[219] \"Dif_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[220] \"Dif_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[221] \"Dif_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[222] \"Dif_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[223] \"Dif_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[224] \"Dif_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[225] \"Dif_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[226] \"Dif_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[227] \"Mean_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[228] \"Mean_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[229] \"Mean_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[230] \"Mean_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[231] \"Mean_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[232] \"Mean_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[233] \"Mean_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[234] \"Mean_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[235] \"Mean_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[236] \"Mean_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[237] \"Mean_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[238] \"Mean_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[239] \"Mean_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[240] \"Mean_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[241] \"Mean_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[242] \"Mean_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[243] \"Mean_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[244] \"Mean_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[245] \"Mean_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[246] \"Mean_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[247] \"Mean_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[248] \"Mean_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[249] \"Mean_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[250] \"Mean_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[251] \"Mean_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[252] \"Mean_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[253] \"Mean_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[254] \"Mean_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[255] \"Mean_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[256] \"Mean_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[257] \"Mean_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[258] \"Mean_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[259] \"Mean_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[260] \"Mean_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[261] \"Mean_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[262] \"Mean_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[263] \"Mean_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[264] \"Mean_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[265] \"Mean_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[266] \"Mean_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[267] \"Mean_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[268] \"Mean_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[269] \"Mean_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[270] \"Mean_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[271] \"Mean_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[272] \"Mean_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[273] \"Mean_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[274] \"Mean_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[275] \"Mean_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[276] \"Mean_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[277] \"Mean_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[278] \"Mean_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[279] \"Mean_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[280] \"Mean_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[281] \"Mean_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[282] \"Mean_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[283] \"Mean_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[284] \"Mean_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[285] \"Mean_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[286] \"Mean_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[287] \"Mean_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[288] \"Mean_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[289] \"Mean_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[290] \"Mean_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[291] \"Mean_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[292] \"Mean_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[293] \"Mean_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[294] \"Mean_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[295] \"Dif_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[296] \"Dif_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[297] \"Dif_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[298] \"Dif_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[299] \"Dif_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[300] \"Dif_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[301] \"Dif_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[302] \"Dif_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[303] \"Dif_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[304] \"Dif_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[305] \"Dif_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[306] \"Dif_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[307] \"Dif_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[308] \"Dif_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[309] \"Dif_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[310] \"Dif_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[311] \"Dif_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[312] \"Dif_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[313] \"Dif_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[314] \"Dif_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[315] \"Dif_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[316] \"Dif_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[317] \"Dif_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[318] \"Dif_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[319] \"Dif_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[320] \"Dif_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[321] \"Dif_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[322] \"Dif_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[323] \"Dif_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[324] \"Dif_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[325] \"Dif_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[326] \"Dif_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[327] \"Dif_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[328] \"Dif_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[329] \"Dif_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[330] \"Dif_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[331] \"Dif_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[332] \"Dif_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[333] \"Dif_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[334] \"Dif_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[335] \"Dif_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[336] \"Dif_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[337] \"Dif_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[338] \"Dif_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[339] \"Dif_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[340] \"Dif_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[341] \"Dif_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[342] \"Dif_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[343] \"Dif_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[344] \"Dif_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[345] \"Dif_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[346] \"Dif_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[347] \"Dif_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[348] \"Dif_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[349] \"Dif_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[350] \"Dif_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[351] \"Dif_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[352] \"Dif_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[353] \"Dif_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[354] \"Dif_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[355] \"Dif_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[356] \"Dif_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[357] \"Dif_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[358] \"Dif_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[359] \"Dif_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[360] \"Dif_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[361] \"Dif_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[362] \"Dif_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[363] \"MeanVolumes\" \n[364] \"StdVolumes\" \n[365] \"COVOlumens\" \n[366] \"MeanArea\" \n[367] \"StdArea\" \n[368] \"COArea\" \n[369] \"MeanThickness\" \n[370] \"StdThickness\" \n[371] \"COMeanThickness\" \n[1] 7884\n..................................................500 \n..................................................1000 \n..................................................1500 \n..................................................2000 \n..................................................2500 \n..................................................3000 \n..................................................3500 \n..................................................4000 \n..................................................4500 \n..................................................5000 \n..................................................5500 \n..................................................6000 \n..................................................6500 \n..................................................7000 \n..................................................7500 \n......................................[1] 24\n[1] 0\n[1] 7660\n[1] 7660 7660\n[1] 7660\n[1] 352\n [1] \"D1\" \"D2\" \"SITE\" \"COLPROT\" \"ORIGPROT\" \n [6] \"VISCODE\" \"EXAMDATE_bl\" \"EXAMDATE\" \"Years_bl\" \"Month_bl\" \n[11] \"Month\" \"M\" \"DX\" \"DX_bl\" \"DXCHANGE\" \n[16] \"PTEDUCAT\" \"PTETHCAT\" \"PTRACCAT\" \"PTMARRY\" \n..................................................500 \n..................................................1000 \n..................................................1500 \n..................................................2000 \n..................................................2500 \n..................................................3000 \n..................................................3500 \n..................................................4000 \n..................................................4500 \n..................................................5000 \n..................................................5500 \n..................................................6000 \n..................................................6500 \n..................................................7000 \n..................................................7500 \n................[1] 7660 352\n[1] 7660 371\n\n 0 1 \n3425 4235 \n[1] 7660 371\n[1] 7660 371\n"
],
[
"#Train Congitive Models\nmodelfilename = model.Train_Congitive(AdjustedTrainFrame,usePreProc=USE_PREPROC)",
"2020-12-25 13:31:01,115 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Train Cognitive Models\n [1] \"AGE\" \n [2] \"PTGENDER\" \n [3] \"CDRSB\" \n [4] \"ADAS11\" \n [5] \"ADAS13\" \n [6] \"MMSE\" \n [7] \"RAVLT_learning\" \n [8] \"RAVLT_immediate\" \n [9] \"FAQ\" \n [10] \"CDRSB_bl\" \n [11] \"ADAS11_bl\" \n [12] \"ADAS13_bl\" \n [13] \"MMSE_bl\" \n [14] \"RAVLT_learning_bl\" \n [15] \"RAVLT_immediate_bl\" \n [16] \"FAQ_bl\" \n [17] \"APOE4\" \n [18] \"Ventricles\" \n [19] \"WholeBrain\" \n [20] \"ICV\" \n [21] \"Ventricles_bl\" \n [22] \"Hippocampus_bl\" \n [23] \"WholeBrain_bl\" \n [24] \"Entorhinal_bl\" \n [25] \"Fusiform_bl\" \n [26] \"MidTemp_bl\" \n [27] \"ICV_bl\" \n [28] \"FDG_bl\" \n [29] \"ST10CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [30] \"ST1SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [31] \"ST2SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [32] \"ST3SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [33] \"ST4SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [34] \"ST5SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [35] \"ST6SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [36] \"ST7SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [37] \"ST9SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [38] \"ST68SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [39] \"ST69SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [40] \"ST127SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [41] \"ST128SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [42] \"nICV\" \n [43] \"Mean_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [44] \"Mean_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [45] \"Mean_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [46] \"Mean_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [47] \"Mean_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [48] \"Mean_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [49] \"Mean_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [50] \"Mean_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [51] \"Mean_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [52] \"Mean_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [53] \"Mean_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [54] \"Mean_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [55] \"Mean_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [56] \"Mean_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [57] \"Mean_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [58] \"Mean_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [59] \"Mean_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [60] \"Mean_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [61] \"Mean_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [62] \"Mean_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [63] \"Mean_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [64] \"Mean_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [65] \"Mean_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [66] \"Mean_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [67] \"Mean_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [68] \"Mean_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [69] \"Mean_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [70] \"Mean_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [71] \"Mean_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [72] \"Mean_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [73] \"Mean_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [74] \"Mean_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [75] \"Mean_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [76] \"Mean_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [77] \"Mean_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [78] \"Mean_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [79] \"Mean_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [80] \"Mean_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [81] \"Mean_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [82] \"Mean_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [83] \"Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [84] \"Mean_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [85] \"Mean_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [86] \"Mean_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [87] \"Mean_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [88] \"Mean_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [89] \"Mean_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [90] \"Mean_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [91] \"Dif_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [92] \"Dif_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [93] \"Dif_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [94] \"Dif_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [95] \"Dif_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [96] \"Dif_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [97] \"Dif_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [98] \"Dif_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [99] \"Dif_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[100] \"Dif_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[101] \"Dif_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[102] \"Dif_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[103] \"Dif_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[104] \"Dif_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[105] \"Dif_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[106] \"Dif_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[107] \"Dif_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[108] \"Dif_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[109] \"Dif_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[110] \"Dif_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[111] \"Dif_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[112] \"Dif_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[113] \"Dif_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[114] \"Dif_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[115] \"Dif_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[116] \"Dif_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[117] \"Dif_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[118] \"Dif_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[119] \"Dif_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[120] \"Dif_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[121] \"Dif_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[122] \"Dif_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[123] \"Dif_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[124] \"Dif_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[125] \"Dif_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[126] \"Dif_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[127] \"Dif_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[128] \"Dif_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[129] \"Dif_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[130] \"Dif_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[131] \"Dif_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[132] \"Dif_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[133] \"Dif_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[134] \"Dif_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[135] \"Dif_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[136] \"Dif_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[137] \"Dif_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[138] \"Dif_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[139] \"Mean_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[140] \"Mean_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[141] \"Mean_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[142] \"Mean_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[143] \"Mean_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[144] \"Mean_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[145] \"Mean_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[146] \"Mean_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[147] \"Mean_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[148] \"Mean_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[149] \"Mean_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[150] \"Mean_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[151] \"Mean_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[152] \"Mean_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[153] \"Mean_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[154] \"Mean_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[155] \"Mean_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[156] \"Mean_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[157] \"Mean_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[158] \"Mean_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[159] \"Mean_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[160] \"Mean_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[161] \"Mean_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[162] \"Mean_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[163] \"Mean_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[164] \"Mean_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[165] \"Mean_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[166] \"Mean_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[167] \"Mean_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[168] \"Mean_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[169] \"Mean_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[170] \"Mean_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[171] \"Mean_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[172] \"Mean_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[173] \"Dif_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[174] \"Dif_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[175] \"Dif_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[176] \"Dif_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[177] \"Dif_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[178] \"Dif_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[179] \"Dif_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[180] \"Dif_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[181] \"Dif_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[182] \"Dif_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[183] \"Dif_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[184] \"Dif_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[185] \"Dif_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[186] \"Dif_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[187] \"Dif_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[188] \"Dif_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[189] \"Dif_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[190] \"Dif_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[191] \"Dif_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[192] \"Dif_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[193] \"Dif_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[194] \"Dif_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[195] \"Dif_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[196] \"Dif_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[197] \"Dif_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[198] \"Dif_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[199] \"Dif_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[200] \"Dif_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[201] \"Dif_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[202] \"Dif_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[203] \"Dif_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[204] \"Dif_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[205] \"Dif_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[206] \"Dif_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[207] \"Mean_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[208] \"Mean_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[209] \"Mean_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[210] \"Mean_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[211] \"Mean_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[212] \"Mean_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[213] \"Mean_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[214] \"Mean_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[215] \"Mean_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[216] \"Mean_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[217] \"Mean_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[218] \"Mean_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[219] \"Mean_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[220] \"Mean_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[221] \"Mean_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[222] \"Mean_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[223] \"Mean_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[224] \"Mean_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[225] \"Mean_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[226] \"Mean_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[227] \"Mean_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[228] \"Mean_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[229] \"Mean_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[230] \"Mean_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[231] \"Mean_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[232] \"Mean_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[233] \"Mean_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[234] \"Mean_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[235] \"Mean_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[236] \"Mean_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[237] \"Mean_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[238] \"Mean_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[239] \"Mean_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[240] \"Mean_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[241] \"Mean_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[242] \"Mean_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[243] \"Mean_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[244] \"Mean_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[245] \"Mean_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[246] \"Mean_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[247] \"Mean_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[248] \"Mean_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[249] \"Mean_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[250] \"Mean_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[251] \"Mean_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[252] \"Mean_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[253] \"Mean_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[254] \"Mean_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[255] \"Mean_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[256] \"Mean_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[257] \"Mean_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[258] \"Mean_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[259] \"Mean_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[260] \"Mean_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[261] \"Mean_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[262] \"Mean_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[263] \"Mean_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[264] \"Mean_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[265] \"Mean_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[266] \"Mean_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[267] \"Mean_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[268] \"Mean_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[269] \"Mean_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[270] \"Mean_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[271] \"Mean_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[272] \"Mean_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[273] \"Mean_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[274] \"Mean_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[275] \"Dif_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[276] \"Dif_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[277] \"Dif_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[278] \"Dif_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[279] \"Dif_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[280] \"Dif_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[281] \"Dif_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[282] \"Dif_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[283] \"Dif_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[284] \"Dif_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[285] \"Dif_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[286] \"Dif_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[287] \"Dif_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[288] \"Dif_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[289] \"Dif_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[290] \"Dif_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[291] \"Dif_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[292] \"Dif_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[293] \"Dif_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[294] \"Dif_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[295] \"Dif_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[296] \"Dif_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[297] \"Dif_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[298] \"Dif_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[299] \"Dif_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[300] \"Dif_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[301] \"Dif_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[302] \"Dif_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[303] \"Dif_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[304] \"Dif_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[305] \"Dif_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[306] \"Dif_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[307] \"Dif_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[308] \"Dif_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[309] \"Dif_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[310] \"Dif_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[311] \"Dif_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[312] \"Dif_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[313] \"Dif_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[314] \"Dif_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[315] \"Dif_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[316] \"Dif_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[317] \"Dif_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[318] \"Dif_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[319] \"Dif_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[320] \"Dif_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[321] \"Dif_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[322] \"Dif_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[323] \"Dif_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[324] \"Dif_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[325] \"Dif_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[326] \"Dif_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[327] \"Dif_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[328] \"Dif_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[329] \"Dif_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[330] \"Dif_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[331] \"Dif_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[332] \"Dif_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[333] \"Dif_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[334] \"Dif_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[335] \"Dif_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[336] \"Dif_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[337] \"Dif_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[338] \"Dif_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[339] \"Dif_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[340] \"Dif_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[341] \"Dif_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[342] \"Dif_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[343] \"MeanVolumes\" \n[344] \"StdVolumes\" \n[345] \"COVOlumens\" \n[346] \"MeanArea\" \n[347] \"StdArea\" \n[348] \"COArea\" \n[349] \"MeanThickness\" \n[350] \"StdThickness\" \n[351] \"COMeanThickness\" \n [1] 0 3 6 12 18 24 36 48 60 72 84 96 108 120\n\n Dementia Dementia to MCI MCI MCI to Dementia MCI to NL \n 1356 9 3199 279 61 \n NL NL to Dementia NL to MCI \n 2132 1 66 \n[1] 908\n[1] 1635\n[1] 677\n[1] 280\n\n 0 1 \n494 797 \n\n bl m06 m12 m18 m24 m36 m48 m60 m72 m84 \n436 328 246 122 89 38 14 9 5 4 \n[1] 454\n\n 0 1 \n175 279 \n[+++++--][1] 279\n[+++-][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[+++++-][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[++++--][1] 454\n\n 0 1 \n175 279 \n[++--][1] 279\n[+++++-][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[++-][1] 454\n\n 0 1 \n175 279 \n[++++-][1] 279\n[++-][1] 454\n\n 0 1 \n175 279 \n[++++-][1] 279\n[+++-][1] 454\n\n 0 1 \n175 279 \n[++++-][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[+++-][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[++-][1] 454\n\n 0 1 \n175 279 \n[+++-][1] 279\n[+++++-][1] 454\n\n 0 1 \n175 279 \n[+++-+-][1] 279\n[++-+-][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[+++-][1] 279\n[+++++-][1] 454\n\n 0 1 \n175 279 \n[+++-][1] 279\n[++++-][1] 454\n\n 0 1 \n175 279 \n[+++++-][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[++++-][1] 279\n[+++--][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[+++++-][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[++++-][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[+++-][1] 279\n[++-][1] 454\n\n 0 1 \n175 279 \n[++++++-][1] 279\n[++--][1] 454\n\n 0 1 \n175 279 \n[++++-][1] 279\n[+-][1] 454\n\n 0 1 \n175 279 \n[++++--][1] 279\n[+-][1] 280\n[1] 335\n[1] 117\n\n 0 1 \n774 151 \n\n bl m06 m12 m18 m24 m36 m48 m60 m72 \n331 231 171 82 70 27 8 4 1 \n[1] 332\n\n 0 1 \n276 56 \n[++++++++++-++-].[1] 56\n[++++++++][1] 332\n\n 0 1 \n276 56 \n[++++++++++-++++++++].[1] 56\n[+--][1] 332\n\n 0 1 \n276 56 \n[+++++++++++++++++-].[1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[+++++++++++++-].[1] 56\n[+-][1] 332\n\n 0 1 \n276 56 \n[++++++++-][1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[++++++++-++++-+-].[1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[++++++++-][1] 56\n[+++++][1] 332\n\n 0 1 \n276 56 \n[++++++++++++++++++-].[1] 56\n[+++][1] 332\n\n 0 1 \n276 56 \n[++++++++-][1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[++++-++-][1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[+++++++++-][1] 56\n[-+][1] 332\n\n 0 1 \n276 56 \n[++++++++++++++++-+-].[1] 56\n[++][1] 332\n\n 0 1 \n276 56 \n[+++++++++++++++++--].[1] 56\n[+++++][1] 332\n\n 0 1 \n276 56 \n[++++++++++++++-].[1] 56\n[--][1] 332\n\n 0 1 \n276 56 \n[+++++--][1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[++++++++++++++++-].[1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[+++++++-+++-].[1] 56\n[++++][1] 332\n\n 0 1 \n276 56 \n[+++++++++++++-].[1] 56\n[--][1] 332\n\n 0 1 \n276 56 \n[+++++++-++++-++-+].[1] 56\n[+-][1] 332\n\n 0 1 \n276 56 \n[+++++-][1] 56\n[++][1] 332\n\n 0 1 \n276 56 \n[++++++++-][1] 56\n[+][1] 332\n\n 0 1 \n276 56 \n[++++++++++++++++-].[1] 56\n[++++++++++].[1] 332\n\n 0 1 \n276 56 \n[+++++++++++++-].[1] 56\n[+++][1] 332\n\n 0 1 \n276 56 \n[++++++++++++++++--].[1] 56\n[++][1] 332\n\n 0 1 \n276 56 \n[++++++++++++++++--].[1] 56\n[+]\n Dementia Dementia to MCI MCI MCI to Dementia MCI to NL \n 1356 9 3199 279 61 \n NL NL to Dementia NL to MCI \n 2132 1 66 \n[1] 561\n[1] 3266\n[1] 258\n[1] 118\n[1] 229\n\n 0 1 \n159 70 \n[+++-][1] 70\n[+++++-][1] 229\n\n 0 1 \n159 70 \n[++++-][1] 70\n[++-][1] 229\n\n 0 1 \n159 70 \n[++--][1] 70\n[+-][1] 229\n\n 0 1 \n159 70 \n[++-][1] 70\n[++][1] 229\n\n 0 1 \n159 70 \n[+++++-][1] 70\n[+][1] 229\n\n 0 1 \n159 70 \n[+-++-][1] 70\n[++++][1] 229\n\n 0 1 \n159 70 \n[+++++-][1] 70\n[++-][1] 229\n\n 0 1 \n159 70 \n[+++++++-][1] 70\n[+++++++][1] 229\n\n 0 1 \n159 70 \n[+++++-][1] 70\n[+][1] 229\n\n 0 1 \n159 70 \n[+++++++-+-][1] 70\n[++-][1] 229\n\n 0 1 \n159 70 \n[+-][1] 70\n[+][1] 229\n\n 0 1 \n159 70 \n[++++-][1] 70\n[+++++][1] 229\n\n 0 1 \n159 70 \n[+++++---][1] 70\n[+--][1] 229\n\n 0 1 \n159 70 \n[+++++++++++].[1] 70\n[+-][1] 229\n\n 0 1 \n159 70 \n[++---][1] 70\n[++++][1] 229\n\n 0 1 \n159 70 \n[+++-][1] 70\n[+-][1] 229\n\n 0 1 \n159 70 \n[++++++-][1] 70\n[++---][1] 229\n\n 0 1 \n159 70 \n[+++-][1] 70\n[++][1] 229\n\n 0 1 \n159 70 \n[++-][1] 70\n[+++--][1] 229\n\n 0 1 \n159 70 \n[+++++-+-][1] 70\n[+--][1] 229\n\n 0 1 \n159 70 \n[+++++--][1] 70\n[+++][1] 229\n\n 0 1 \n159 70 \n[+++-][1] 70\n[+][1] 229\n\n 0 1 \n159 70 \n[++-+-][1] 70\n[++][1] 229\n\n 0 1 \n159 70 \n[+--][1] 70\n[+-][1] 229\n\n 0 1 \n159 70 \n[+++++-][1] 70\n[+++][1] 1493\n \n 0 1 2\n AD 0 2 287\n CN 341 21 2\n EMCI 9 229 6\n LMCI 11 401 96\n SMC 86 1 1\n[+-][1] 1487\n \n 0 1 2\n AD 0 2 281\n CN 366 11 2\n EMCI 10 224 5\n LMCI 13 395 98\n SMC 78 2 0\n[+-][1] 1484\n \n 0 1 2\n AD 0 2 278\n CN 346 20 4\n EMCI 9 222 5\n LMCI 9 400 100\n SMC 86 3 0\n[+-][1] 1481\n \n 0 1 2\n AD 0 1 283\n CN 339 22 1\n EMCI 7 224 7\n LMCI 13 403 102\n SMC 76 3 0\n[+-][1] 1478\n \n 0 1 2\n AD 0 3 277\n CN 348 19 4\n EMCI 5 220 8\n LMCI 12 399 102\n SMC 77 3 1\n[+-][1] 1508\n \n 0 1 2\n AD 0 1 289\n CN 358 15 1\n EMCI 8 233 7\n LMCI 12 398 99\n SMC 84 3 0\n[+-][1] 1476\n \n 0 1 2\n AD 0 3 281\n CN 350 17 2\n EMCI 9 210 9\n LMCI 13 395 103\n SMC 79 4 1\n[+-][1] 1490\n \n 0 1 2\n AD 0 0 287\n CN 352 18 1\n EMCI 14 215 6\n LMCI 9 402 102\n SMC 80 3 1\n[+-][1] 1488\n \n 0 1 2\n AD 0 3 288\n CN 344 17 2\n EMCI 12 224 4\n LMCI 13 396 107\n SMC 76 1 1\n[+-][1] 1484\n \n 0 1 2\n AD 0 2 278\n CN 354 17 2\n EMCI 7 217 8\n LMCI 10 405 99\n SMC 80 5 0\n[+-][1] 1497\n \n 0 1 2\n AD 0 2 289\n CN 357 15 4\n EMCI 13 220 8\n LMCI 14 400 91\n SMC 79 4 1\n[+-][1] 1471\n \n 0 1 2\n AD 0 2 288\n CN 350 15 0\n EMCI 6 223 5\n LMCI 7 386 114\n SMC 70 4 1\n[+-][1] 1499\n \n 0 1 2\n AD 0 2 283\n CN 347 20 2\n EMCI 10 220 8\n LMCI 11 404 104\n SMC 83 4 1\n[+-][1] 1487\n \n 0 1 2\n AD 0 2 283\n CN 356 19 3\n EMCI 11 208 9\n LMCI 12 400 97\n SMC 82 4 1\n[+-][1] 1486\n \n 0 1 2\n AD 0 3 284\n CN 346 19 0\n EMCI 9 228 7\n LMCI 11 401 95\n SMC 79 3 1\n[+--][1] 1484\n \n 0 1 2\n AD 0 4 278\n CN 353 18 3\n EMCI 7 222 5\n LMCI 11 405 97\n SMC 76 4 1\n[+-][1] 1488\n \n 0 1 2\n AD 0 2 282\n CN 358 17 4\n EMCI 12 208 8\n LMCI 7 398 106\n SMC 82 4 0\n[+-][1] 1492\n \n 0 1 2\n AD 0 1 278\n CN 350 22 1\n EMCI 8 218 10\n LMCI 9 400 108\n SMC 82 4 1\n[+-][1] 1483\n \n 0 1 2\n AD 0 1 278\n CN 353 16 1\n EMCI 8 227 9\n LMCI 11 370 128\n SMC 79 1 1\n[+--][1] 1479\n \n 0 1 2\n AD 0 5 279\n CN 354 20 2\n EMCI 6 215 6\n LMCI 10 393 106\n SMC 79 3 1\n[+-][1] 1502\n \n 0 1 2\n AD 0 2 280\n CN 360 15 2\n EMCI 11 228 5\n LMCI 13 404 96\n SMC 83 3 0\n[+-][1] 1482\n \n 0 1 2\n AD 0 4 279\n CN 352 17 4\n EMCI 6 222 3\n LMCI 12 398 104\n SMC 77 3 1\n[+-][1] 1463\n \n 0 1 2\n AD 0 2 272\n CN 345 19 1\n EMCI 7 220 10\n LMCI 11 384 109\n SMC 78 4 1\n[+-][1] 1481\n \n 0 1 2\n AD 0 3 279\n CN 343 19 3\n EMCI 10 217 8\n LMCI 9 415 92\n SMC 79 3 1\n[+-][1] 1460\n \n 0 1 2\n AD 0 3 270\n CN 344 22 3\n EMCI 11 213 8\n LMCI 18 386 100\n SMC 79 2 1\n[+--]"
],
[
"#Train ADAS/Ventricles Models\nregresionModelfilename = model.Train_Regression(AdjustedTrainFrame,Train_Imputed,usePreProc=USE_PREPROC)\nprint(regresionModelfilename)",
"2020-12-25 14:12:56,719 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Train ADAS13 and Ventricles Models\n [1] \"AGE\" \n [2] \"PTGENDER\" \n [3] \"CDRSB\" \n [4] \"ADAS11\" \n [5] \"ADAS13\" \n [6] \"MMSE\" \n [7] \"RAVLT_learning\" \n [8] \"RAVLT_immediate\" \n [9] \"FAQ\" \n [10] \"CDRSB_bl\" \n [11] \"ADAS11_bl\" \n [12] \"ADAS13_bl\" \n [13] \"MMSE_bl\" \n [14] \"RAVLT_learning_bl\" \n [15] \"RAVLT_immediate_bl\" \n [16] \"FAQ_bl\" \n [17] \"APOE4\" \n [18] \"Ventricles\" \n [19] \"WholeBrain\" \n [20] \"ICV\" \n [21] \"Ventricles_bl\" \n [22] \"Hippocampus_bl\" \n [23] \"WholeBrain_bl\" \n [24] \"Entorhinal_bl\" \n [25] \"Fusiform_bl\" \n [26] \"MidTemp_bl\" \n [27] \"ICV_bl\" \n [28] \"FDG_bl\" \n [29] \"ST10CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [30] \"ST1SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [31] \"ST2SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [32] \"ST3SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [33] \"ST4SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [34] \"ST5SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [35] \"ST6SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [36] \"ST7SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [37] \"ST9SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [38] \"ST68SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [39] \"ST69SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [40] \"ST127SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [41] \"ST128SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [42] \"nICV\" \n [43] \"Mean_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [44] \"Mean_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [45] \"Mean_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [46] \"Mean_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [47] \"Mean_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [48] \"Mean_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [49] \"Mean_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [50] \"Mean_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [51] \"Mean_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [52] \"Mean_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [53] \"Mean_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [54] \"Mean_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [55] \"Mean_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [56] \"Mean_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [57] \"Mean_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [58] \"Mean_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [59] \"Mean_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [60] \"Mean_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [61] \"Mean_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [62] \"Mean_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [63] \"Mean_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [64] \"Mean_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [65] \"Mean_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [66] \"Mean_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [67] \"Mean_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [68] \"Mean_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [69] \"Mean_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [70] \"Mean_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [71] \"Mean_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [72] \"Mean_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [73] \"Mean_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [74] \"Mean_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [75] \"Mean_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [76] \"Mean_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [77] \"Mean_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [78] \"Mean_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [79] \"Mean_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [80] \"Mean_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [81] \"Mean_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [82] \"Mean_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [83] \"Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [84] \"Mean_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [85] \"Mean_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [86] \"Mean_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [87] \"Mean_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [88] \"Mean_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [89] \"Mean_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [90] \"Mean_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [91] \"Dif_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [92] \"Dif_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [93] \"Dif_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [94] \"Dif_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [95] \"Dif_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [96] \"Dif_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [97] \"Dif_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [98] \"Dif_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [99] \"Dif_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[100] \"Dif_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[101] \"Dif_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[102] \"Dif_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[103] \"Dif_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[104] \"Dif_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[105] \"Dif_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[106] \"Dif_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[107] \"Dif_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[108] \"Dif_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[109] \"Dif_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[110] \"Dif_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[111] \"Dif_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[112] \"Dif_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[113] \"Dif_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[114] \"Dif_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[115] \"Dif_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[116] \"Dif_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[117] \"Dif_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[118] \"Dif_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[119] \"Dif_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[120] \"Dif_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[121] \"Dif_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[122] \"Dif_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[123] \"Dif_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[124] \"Dif_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[125] \"Dif_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[126] \"Dif_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[127] \"Dif_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[128] \"Dif_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[129] \"Dif_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[130] \"Dif_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[131] \"Dif_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[132] \"Dif_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[133] \"Dif_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[134] \"Dif_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[135] \"Dif_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[136] \"Dif_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[137] \"Dif_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[138] \"Dif_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[139] \"Mean_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[140] \"Mean_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[141] \"Mean_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[142] \"Mean_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[143] \"Mean_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[144] \"Mean_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[145] \"Mean_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[146] \"Mean_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[147] \"Mean_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[148] \"Mean_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[149] \"Mean_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[150] \"Mean_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[151] \"Mean_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[152] \"Mean_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[153] \"Mean_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[154] \"Mean_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[155] \"Mean_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[156] \"Mean_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[157] \"Mean_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[158] \"Mean_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[159] \"Mean_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[160] \"Mean_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[161] \"Mean_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[162] \"Mean_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[163] \"Mean_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[164] \"Mean_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[165] \"Mean_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[166] \"Mean_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[167] \"Mean_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[168] \"Mean_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[169] \"Mean_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[170] \"Mean_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[171] \"Mean_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[172] \"Mean_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[173] \"Dif_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[174] \"Dif_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[175] \"Dif_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[176] \"Dif_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[177] \"Dif_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[178] \"Dif_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[179] \"Dif_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[180] \"Dif_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[181] \"Dif_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[182] \"Dif_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[183] \"Dif_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[184] \"Dif_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[185] \"Dif_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[186] \"Dif_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[187] \"Dif_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[188] \"Dif_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[189] \"Dif_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[190] \"Dif_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[191] \"Dif_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[192] \"Dif_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[193] \"Dif_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[194] \"Dif_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[195] \"Dif_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[196] \"Dif_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[197] \"Dif_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[198] \"Dif_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[199] \"Dif_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[200] \"Dif_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[201] \"Dif_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[202] \"Dif_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[203] \"Dif_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[204] \"Dif_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[205] \"Dif_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[206] \"Dif_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[207] \"Mean_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[208] \"Mean_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[209] \"Mean_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[210] \"Mean_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[211] \"Mean_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[212] \"Mean_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[213] \"Mean_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[214] \"Mean_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[215] \"Mean_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[216] \"Mean_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[217] \"Mean_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[218] \"Mean_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[219] \"Mean_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[220] \"Mean_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[221] \"Mean_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[222] \"Mean_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[223] \"Mean_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[224] \"Mean_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[225] \"Mean_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[226] \"Mean_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[227] \"Mean_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[228] \"Mean_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[229] \"Mean_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[230] \"Mean_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[231] \"Mean_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[232] \"Mean_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[233] \"Mean_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[234] \"Mean_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[235] \"Mean_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[236] \"Mean_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[237] \"Mean_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[238] \"Mean_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[239] \"Mean_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[240] \"Mean_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[241] \"Mean_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[242] \"Mean_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[243] \"Mean_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[244] \"Mean_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[245] \"Mean_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[246] \"Mean_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[247] \"Mean_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[248] \"Mean_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[249] \"Mean_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[250] \"Mean_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[251] \"Mean_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[252] \"Mean_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[253] \"Mean_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[254] \"Mean_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[255] \"Mean_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[256] \"Mean_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[257] \"Mean_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[258] \"Mean_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[259] \"Mean_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[260] \"Mean_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[261] \"Mean_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[262] \"Mean_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[263] \"Mean_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[264] \"Mean_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[265] \"Mean_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[266] \"Mean_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[267] \"Mean_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[268] \"Mean_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[269] \"Mean_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[270] \"Mean_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[271] \"Mean_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[272] \"Mean_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[273] \"Mean_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[274] \"Mean_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[275] \"Dif_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[276] \"Dif_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[277] \"Dif_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[278] \"Dif_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[279] \"Dif_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[280] \"Dif_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[281] \"Dif_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[282] \"Dif_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[283] \"Dif_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[284] \"Dif_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[285] \"Dif_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[286] \"Dif_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[287] \"Dif_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[288] \"Dif_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[289] \"Dif_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[290] \"Dif_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[291] \"Dif_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[292] \"Dif_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[293] \"Dif_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[294] \"Dif_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[295] \"Dif_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[296] \"Dif_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[297] \"Dif_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[298] \"Dif_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[299] \"Dif_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[300] \"Dif_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[301] \"Dif_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[302] \"Dif_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[303] \"Dif_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[304] \"Dif_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[305] \"Dif_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[306] \"Dif_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[307] \"Dif_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[308] \"Dif_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[309] \"Dif_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[310] \"Dif_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[311] \"Dif_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[312] \"Dif_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[313] \"Dif_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[314] \"Dif_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[315] \"Dif_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[316] \"Dif_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[317] \"Dif_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[318] \"Dif_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[319] \"Dif_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[320] \"Dif_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[321] \"Dif_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[322] \"Dif_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[323] \"Dif_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[324] \"Dif_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[325] \"Dif_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[326] \"Dif_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[327] \"Dif_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[328] \"Dif_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[329] \"Dif_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[330] \"Dif_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[331] \"Dif_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[332] \"Dif_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[333] \"Dif_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[334] \"Dif_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[335] \"Dif_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[336] \"Dif_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[337] \"Dif_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[338] \"Dif_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[339] \"Dif_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[340] \"Dif_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[341] \"Dif_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[342] \"Dif_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[343] \"MeanVolumes\" \n[344] \"StdVolumes\" \n[345] \"COVOlumens\" \n[346] \"MeanArea\" \n[347] \"StdArea\" \n[348] \"COArea\" \n[349] \"MeanThickness\" \n[350] \"StdThickness\" \n[351] \"COMeanThickness\" \n[1] 7884 371\n [1] 0 3 6 12 18 24 36 48 60 72 84 96 108 120\n\n bl m03 m06 m108 m12 m120 m18 m24 m36 m48 m60 m72 m84 m96 \n 54 41 90 11 263 1 33 606 187 181 39 120 16 25 \n[1] 1667\n\n Dementia Dementia to MCI MCI MCI to Dementia MCI to NL \n 466 4 538 101 18 \n NL NL to Dementia NL to MCI \n 460 1 29 \n[1] \"FOR 1\"\n[1] 1653\n[1] 770\n[1] 1436\n[1] 1392\n[1] 295\n[1] 1125\n[1] 455\n[1] 341\n[1] 171\n[1] 163\n[1] 39\n[1] 32\n[1] 11\n[1] 1\n[1] 0\n[1] 7884 380\n[1] 3274\n[1] 0\n\nDementia to MCI MCI NL to MCI \n 4 865 39 \n[1] 908\n[+-][1] 0.5452049\n[+-][1] 0.6835351\n\nDementia to MCI MCI NL to MCI \n 3 863 42 \n[1] 908\n[+-][1] 0.4026537\n[+-][1] 0.6276329\n\nDementia to MCI MCI NL to MCI \n 7 858 43 \n[1] 908\n[+-][1] 0.4890935\n[+-][1] 0.6275621\n\nDementia to MCI MCI NL to MCI \n 3 865 40 \n[1] 908\n[+-][1] 0.4739508\n[+-][1] 0.642712\n\nDementia to MCI MCI NL to MCI \n 7 858 43 \n[1] 908\n[+-][1] 0.4740166\n[+-][1] 0.6000614\n\nDementia to MCI MCI NL to MCI \n 5 865 38 \n[1] 908\n[+-][1] 0.4988516\n[+-][1] 0.5520245\n\nDementia to MCI MCI NL to MCI \n 3 860 45 \n[1] 908\n[+-][1] 0.4028269\n[+-][1] 0.6670539\n\nDementia to MCI MCI NL to MCI \n 2 864 42 \n[1] 908\n[+-][1] 0.4783887\n[+-][1] 0.6011105\n\nDementia to MCI MCI NL to MCI \n 5 856 47 \n[1] 908\n[+-][1] 0.5305958\n[+-][1] 0.680189\n\nDementia to MCI MCI NL to MCI \n 3 863 42 \n[1] 908\n[+-][1] 0.4352768\n[+-][1] 0.6343458\n\nDementia to MCI MCI NL to MCI \n 3 863 42 \n[1] 908\n[+-][1] 0.3829661\n[+-][1] 0.6587498\n\nDementia to MCI MCI NL to MCI \n 3 865 40 \n[1] 908\n[+-][1] 0.520653\n[+-][1] 0.6416103\n\nDementia to MCI MCI NL to MCI \n 5 857 46 \n[1] 908\n[+-][1] 0.439018\n[+-][1] 0.6896482\n\nDementia to MCI MCI NL to MCI \n 4 863 41 \n[1] 908\n[+-][1] 0.4673402\n[+-][1] 0.6355118\n\nDementia to MCI MCI NL to MCI \n 4 860 44 \n[1] 908\n[+-][1] 0.4999766\n[+-][1] 0.6307444\n\nDementia to MCI MCI NL to MCI \n 4 863 41 \n[1] 908\n[+-][1] 0.425228\n[+-][1] 0.673335\n\nDementia to MCI MCI NL to MCI \n 3 858 47 \n[1] 908\n[+-][1] 0.3962363\n[+-][1] 0.6247132\n\nDementia to MCI MCI NL to MCI \n 5 863 40 \n[1] 908\n[+-][1] 0.4725228\n[+-][1] 0.6491112\n\nDementia to MCI MCI NL to MCI \n 4 862 42 \n[1] 908\n[+-][1] 0.4834264\n[+-][1] 0.6553226\n\nDementia to MCI MCI NL to MCI \n 4 863 41 \n[1] 908\n[+-][1] 0.4695662\n[+-][1] 0.621148\n\nDementia to MCI MCI NL to MCI \n 3 866 39 \n[1] 908\n[+-][1] 0.4753275\n[+-][1] 0.6582428\n\nDementia to MCI MCI NL to MCI \n 6 858 44 \n[1] 908\n[+-][1] 0.4014453\n[+-][1] 0.6591347\n\nDementia to MCI MCI NL to MCI \n 5 864 39 \n[1] 908\n[+-][1] 0.4357593\n[+-][1] 0.6394811\n\nDementia to MCI MCI NL to MCI \n 3 863 42 \n[1] 908\n[+-][1] 0.4737774\n[+-][1] 0.6275097\n\nDementia to MCI MCI NL to MCI \n 4 863 41 \n[1] 908\n[+-][1] 0.5095446\n[+-][1] 0.6687494\n\nDementia to MCI MCI NL to MCI \n 2 865 41 \n[1] 908\n[+-][1] 0.4870897\n[+-][1] 0.6388564\n\nDementia to MCI MCI NL to MCI \n 7 862 39 \n[1] 908\n[+-][1] 0.5489359\n[+-][1] 0.674293\n\nDementia to MCI MCI NL to MCI \n 4 865 39 \n[1] 908\n[+-][1] 0.332645\n[+-][1] 0.6452123\n\nDementia to MCI MCI NL to MCI \n 3 867 38 \n[1] 908\n[+-][1] 0.4443186\n[+-][1] 0.6023041\n\nDementia to MCI MCI NL to MCI \n 5 862 41 \n[1] 908\n[+-][1] 0.4591454\n[+-][1] 0.6037636\n\nDementia to MCI MCI NL to MCI \n 5 864 39 \n[1] 908\n[+-][1] 0.5092231\n[+-][1] 0.5680968\n\nDementia to MCI MCI NL to MCI \n 4 856 48 \n[1] 908\n[+-][1] 0.439228\n[+-][1] 0.6097067\n\nDementia to MCI MCI NL to MCI \n 2 866 40 \n[1] 908\n[+-][1] 0.4891188\n[+-][1] 0.6804121\n\nDementia to MCI MCI NL to MCI \n 6 858 44 \n[1] 908\n[+-][1] 0.4670534\n[+-][1] 0.6185116\n\nDementia to MCI MCI NL to MCI \n 5 863 40 \n[1] 908\n[+-][1] 0.4576587\n[+-][1] 0.6256261\n\nDementia to MCI MCI NL to MCI \n 5 865 38 \n[1] 908\n[+-][1] 0.5272743\n[+-][1] 0.6480396\n\nDementia to MCI MCI NL to MCI \n 4 858 46 \n[1] 908\n[+-][1] 0.4506045\n[+-][1] 0.6225474\n\nDementia to MCI MCI NL to MCI \n 4 864 40 \n[1] 908\n[+-][1] 0.4846985\n[+-][1] 0.6443237\n\nDementia to MCI MCI NL to MCI \n 5 859 44 \n[1] 908\n[+-][1] 0.4601731\n[+-][1] 0.6204349\n\nDementia to MCI MCI NL to MCI \n 4 864 40 \n[1] 908\n[+-][1] 0.497724\n[+-][1] 0.6364488\n\nDementia to MCI MCI NL to MCI \n 3 864 41 \n[1] 908\n[+-][1] 0.4629668\n[+-][1] 0.6804132\n\nDementia to MCI MCI NL to MCI \n 6 860 42 \n[1] 908\n[+-][1] 0.4283554\n[+-][1] 0.6404653\n\nDementia to MCI MCI NL to MCI \n 4 860 44 \n[1] 908\n[+-][1] 0.3913233\n[+-][1] 0.6538847\n\nDementia to MCI MCI NL to MCI \n 3 860 45 \n[1] 908\n[+-][1] 0.4731085\n[+-][1] 0.6081432\n\nDementia to MCI MCI NL to MCI \n 5 858 45 \n[1] 908\n[+-][1] 0.393587\n[+-][1] 0.5729258\n\nDementia to MCI MCI NL to MCI \n 3 854 51 \n[1] 908\n[+-][1] 0.4425618\n[+-][1] 0.5999218\n\nDementia to MCI MCI NL to MCI \n 3 863 42 \n[1] 908\n[+-][1] 0.5014486\n[+-][1] 0.6140125\n\nDementia to MCI MCI NL to MCI \n 6 860 42 \n[1] 908\n[+-][1] 0.4620518\n[+-][1] 0.5953444\n\nDementia to MCI MCI NL to MCI \n 3 861 44 \n[1] 908\n[+-][1] 0.4967671\n[+-][1] 0.6191488\n\nDementia to MCI MCI NL to MCI \n 5 861 42 \n[1] 908\n[+-][1] 0.4322128\n[+-][1] 0.6614018\n[1] 2192\n[1] 0\n[1] 561\n[++-][1] 0.253658\n[+-][1] 0.6494593\n[1] 561\n[++-][1] 0.2834384\n[+-][1] 0.6154804\n[1] 561\n[+-][1] 0.3048034\n[+-][1] 0.5794766\n[1] 561\n[+-][1] 0.3520149\n[+-][1] 0.5732346\n[1] 561\n[+-][1] 0.2588554\n[+-][1] 0.6518386\n[1] 561\n[++-][1] 0.1708701\n[+-][1] 0.6596189\n[1] 561\n[+--][1] 0.3026717\n[+-][1] 0.6125344\n[1] 561\n[++--][1] 0.3518076\n[+-][1] 0.6593815\n[1] 561\n[+-][1] 0.3799041\n[+-][1] 0.6775834\n[1] 561\n[+-][1] 0.2995549\n[+-][1] 0.6069933\n[1] 561\n[+-][1] 0.3032266\n[+-][1] 0.6353384\n[1] 561\n[+-][1] 0.4548455\n[+-][1] 0.6283923\n[1] 561\n[+-][1] 0.35719\n[+-][1] 0.6147913\n[1] 561\n[+-][1] 0.3247373\n[+-][1] 0.6462735\n[1] 561\n[+-][1] 0.3475851\n[+-][1] 0.6615285\n[1] 561\n[+-][1] 0.3803176\n[+-][1] 0.6622784\n[1] 561\n[++-][1] 0.3385975\n[+-][1] 0.565674\n[1] 561\n[+-][1] 0.2688978\n[+-][1] 0.6362356\n[1] 561\n[+-][1] 0.3889765\n[+-][1] 0.6764462\n[1] 561\n[++-][1] 0.3714044\n[+-][1] 0.6323138\n[1] 561\n[+-][1] 0.3921987\n[+-][1] 0.6674177\n[1] 561\n[+--][1] 0.3473617\n[+-][1] 0.637436\n[1] 561\n[+-][1] 0.3209712\n[+-][1] 0.6053684\n[1] 561\n[+--][1] 0.2156145\n[+-][1] 0.5915388\n[1] 561\n[+-][1] 0.3104031\n[+-][1] 0.5198363\n[1] 561\n[+-][1] 0.3597015\n[+-][1] 0.6154274\n[1] 561\n[+-][1] 0.3248696\n[+-][1] 0.597809\n[1] 561\n[+-][1] 0.3065548\n[+-][1] 0.6427351\n[1] 561\n[+-][1] 0.3399208\n[+-][1] 0.5686359\n[1] 561\n[+--][1] 0.2721354\n[+-][1] 0.6100675\n[1] 561\n[+-][1] 0.2824437\n[+-][1] 0.6351053\n[1] 561\n[++-][1] 0.3001783\n[+-][1] 0.6018615\n[1] 561\n[+-][1] 0.4222012\n[+-][1] 0.6033083\n[1] 561\n[+-][1] 0.3626668\n[+-][1] 0.6009137\n[1] 561\n[+++-][1] 0.2594641\n[+-][1] 0.5629743\n[1] 561\n[+-][1] 0.3614873\n[+-][1] 0.6254453\n[1] 561\n[+-][1] 0.3896822\n[+-][1] 0.6111997\n[1] 561\n[+++-][1] 0.2670738\n[+-][1] 0.6198783\n[1] 561\n[++++-][1] 0.1895351\n[+-][1] 0.6776395\n[1] 561\n[+-][1] 0.3931717\n[+-][1] 0.6291873\n[1] 561\n[+-][1] 0.3827868\n[+-][1] 0.6458999\n[1] 561\n[++-][1] 0.3086791\n[+-][1] 0.5864117\n[1] 561\n[++-][1] 0.276482\n[+--][1] 0.5650578\n[1] 561\n[+-][1] 0.4611726\n[+-][1] 0.6465229\n[1] 561\n[++-][1] 0.3254337\n[+-][1] 0.6250775\n[1] 561\n[+-][1] 0.2678542\n[+-][1] 0.6106189\n[1] 561\n[+-][1] 0.3958972\n[+-][1] 0.601758\n[1] 561\n[+-][1] 0.3303581\n[+-][1] 0.659547\n[1] 561\n[+--][1] 0.2930224\n[+-][1] 0.6032922\n[1] 561\n[++-][1] 0.3373469\n[+-][1] 0.6046739\n[1] 1635\n[1] 0\n[1] 594\n[+-][1] 0.5545031\n[+++-][1] 0.3862797\n[1] 594\n[+-][1] 0.4355553\n[+-][1] 0.484681\n[1] 594\n[+-][1] 0.4911303\n[++-][1] 0.5508267\n[1] 594\n[+-][1] 0.5040193\n[++-][1] 0.441255\n[1] 594\n[+-][1] 0.5479771\n[++-][1] 0.5630245\n[1] 594\n[++-][1] 0.557305\n[++--][1] 0.4312288\n[1] 594\n[+-][1] 0.5270791\n[++-][1] 0.520465\n[1] 594\n[+-][1] 0.488218\n[+++-][1] 0.3154034\n[1] 594\n[+-][1] 0.4940049\n[+++-][1] 0.4439091\n[1] 594\n[+-][1] 0.4998591\n[++-][1] 0.6390448\n[1] 594\n[+-][1] 0.6160403\n[+-][1] 0.5500426\n[1] 594\n[+-][1] 0.4443359\n[+-][1] 0.6644286\n[1] 594\n[+-][1] 0.5342993\n[++-][1] 0.4116417\n[1] 594\n[+-][1] 0.4601688\n[+++-][1] 0.4554514\n[1] 594\n[+-][1] 0.5182174\n[++-][1] 0.312307\n[1] 594\n[+-][1] 0.50172\n[++-][1] 0.4851941\n[1] 594\n[+-][1] 0.6254198\n[++-][1] 0.4576909\n[1] 594\n[+-][1] 0.585437\n[+-][1] 0.7460026\n[1] 594\n[+-][1] 0.5265915\n[++--][1] 0.5138493\n[1] 594\n[+-][1] 0.5698596\n[+--][1] 0.5518644\n[1] 594\n[+-][1] 0.4212785\n[+-][1] 0.6113612\n[1] 594\n[+-][1] 0.5759259\n[+-][1] 0.6756715\n[1] 594\n[+-][1] 0.5366505\n[+-][1] 0.6347252\n[1] 594\n[++-][1] 0.5072722\n[+-][1] 0.6705333\n[1] 594\n[+-][1] 0.4030987\n[+++-][1] 0.4090218\n[1] 594\n[+-][1] 0.626478\n[++-][1] 0.4000121\n[1] 594\n[+-][1] 0.5338675\n[++-][1] 0.3958751\n[1] 594\n[+-][1] 0.5350397\n[++-][1] 0.4116831\n[1] 594\n[+-][1] 0.5536848\n[++-][1] 0.4764633\n[1] 594\n[+-][1] 0.5522583\n[+-][1] 0.5455233\n[1] 594\n[+-][1] 0.5044836\n[++-][1] 0.4592446\n[1] 594\n[+-][1] 0.6106451\n[+-][1] 0.6860215\n[1] 594\n[+-][1] 0.5102551\n[++-][1] 0.5140555\n[1] 594\n[+-][1] 0.5318734\n[+-][1] 0.6361839\n[1] 594\n[+-][1] 0.5406719\n[+-][1] 0.6344104\n[1] 594\n[++-][1] 0.5134909\n[+--][1] 0.5776867\n[1] 594\n[+-][1] 0.5244516\n[++-][1] 0.5119129\n[1] 594\n[+-][1] 0.5207076\n[++-][1] 0.4899229\n[1] 594\n[+-][1] 0.500221\n[+--][1] 0.4981237\n[1] 594\n[+-][1] 0.4617051\n[+-][1] 0.6892447\n[1] 594\n[+-][1] 0.4512998\n[++-][1] 0.4727597\n[1] 594\n[+-][1] 0.5228696\n[+-][1] 0.4272182\n[1] 594\n[+-][1] 0.4808405\n[+--][1] 0.5106642\n[1] 594\n[++-][1] 0.4779048\n[++--][1] 0.4831128\n[1] 594\n[+-][1] 0.5200677\n[+-][1] 0.715578\n[1] 594\n[+-][1] 0.4771609\n[+-][1] 0.6169694\n[1] 594\n[+--][1] 0.4172689\n[+++-][1] 0.5117927\n[1] 594\n[+-][1] 0.4710958\n[+-][1] 0.5605615\n[1] 594\n[++-][1] 0.4810713\n[++-][1] 0.480391\n[1] 594\n[+-][1] 0.487785\n[+-][1] 0.5877336\n[1] \"data/_RegressionModels_50_Nolog.RDATA\"\n\n"
],
[
"print(regresionModelfilename)\nprint(type(regresionModelfilename))",
"[1] \"data/_RegressionModels_50_Nolog.RDATA\"\n\n<class 'rpy2.robjects.vectors.StrVector'>\n"
],
[
"#Predict \nForecast_D2 = model.Forecast_All(modelfilename,\n regresionModelfilename,\n testingFrame,\n Test_Imputed,\n submissionTemplateFileName=\"data/TADPOLE_Simple_Submission_TeamName.xlsx\",\n usePreProc=USE_PREPROC)",
"2020-12-25 16:01:36,503 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Forecast Congitive Status, ADAS13 and Ventricles\n2020-12-25 16:01:44,433 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n2020-12-25 16:01:44,434 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: -\n2020-12-25 16:01:44,590 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n2020-12-25 16:01:44,591 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \\\n - R[write to console]: \n2020-12-25 16:01:44,592 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n [1] 0 3 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96 102\n[20] 108 114 120\n[1] 7660\n[1] 896\n[1] 896\n[1] 0\n[1] 7660\n[1] 896\n[1] 587\n[1] 1\nstatusLO\n 1 2 3 \n342 341 212 \n[1] 0.8648029 0.7377718 0.7631522\n[1] 0.6145374 0.3056769 0.1686747\n[1] 0.7296057 0.4755436 0.5263043\n [1] 7.945294 16.607153 15.101204 11.487556 17.127943 10.144713 11.515525\n [8] 19.467535 21.589277 18.720183 16.094958 17.007863 8.995762 15.717069\n[15] 12.816384 14.231144 12.785339 13.069562 12.974779 13.768014 19.614001\n[22] 16.600814 9.050131 16.972430 14.836030 13.186218 12.609599 10.806963\n[29] 16.952277 12.755083 18.888452 12.603355 12.310995 16.519059 18.289593\n[36] 17.972494 12.256691 12.348876 11.883470 10.573478 18.801192 16.147742\n[43] 18.704076 16.383771 18.598392 15.151017 10.667181 9.013218 21.999728\n[50] 9.988931\n [1] 0.01274492 0.01721336 0.01265018 0.01518589 0.01386928 0.01303069\n [7] 0.01368644 0.01711872 0.01443796 0.01484598 0.01532723 0.01430373\n[13] 0.01448296 0.01769096 0.01426804 0.01619595 0.01456654 0.01562378\n[19] 0.01563076 0.01422372 0.01504987 0.01605969 0.01414131 0.01618090\n[25] 0.01560195 0.01611598 0.01520165 0.01405160 0.01414358 0.01418392\n[31] 0.01649774 0.01475266 0.01596404 0.01598110 0.01359348 0.01490996\n[37] 0.01446900 0.01561181 0.01613947 0.01402539 0.01574187 0.01735757\n[43] 0.01388380 0.01533810 0.01559007 0.01664008 0.01404544 0.01246686\n[49] 0.01446280 0.01554006\n[1] \"2018-02-01\"\n[1] \"2018-03-01\"\n[1] \"2018-04-01\"\n[1] \"2018-05-01\"\n[1] \"2018-06-01\"\n[1] \"2018-07-01\"\n[1] \"2018-08-01\"\n[1] \"2018-09-01\"\n[1] \"2018-10-01\"\n[1] \"2018-11-01\"\n[1] \"2018-12-01\"\n[1] \"2019-01-01\"\n[1] \"2019-02-01\"\n[1] \"2019-03-01\"\n[1] \"2019-04-01\"\n[1] \"2019-05-01\"\n[1] \"2019-06-01\"\n[1] \"2019-07-01\"\n[1] \"2019-08-01\"\n[1] \"2019-09-01\"\n[1] \"2019-10-01\"\n[1] \"2019-11-01\"\n[1] \"2019-12-01\"\n[1] \"2020-01-01\"\n[1] \"2020-02-01\"\n[1] \"2020-03-01\"\n[1] \"2020-04-01\"\n[1] \"2020-05-01\"\n[1] \"2020-06-01\"\n[1] \"2020-07-01\"\n[1] \"2020-08-01\"\n[1] \"2020-09-01\"\n[1] \"2020-10-01\"\n[1] \"2020-11-01\"\n[1] \"2020-12-01\"\n[1] \"2021-01-01\"\n[1] \"2021-02-01\"\n[1] \"2021-03-01\"\n[1] \"2021-04-01\"\n[1] \"2021-05-01\"\n[1] \"2021-06-01\"\n[1] \"2021-07-01\"\n[1] \"2021-08-01\"\n[1] \"2021-09-01\"\n[1] \"2021-10-01\"\n[1] \"2021-11-01\"\n[1] \"2021-12-01\"\n[1] \"2022-01-01\"\n[1] \"2022-02-01\"\n[1] \"2022-03-01\"\n[1] \"2022-04-01\"\n[1] \"2022-05-01\"\n[1] \"2022-06-01\"\n[1] \"2022-07-01\"\n[1] \"2022-08-01\"\n[1] \"2022-09-01\"\n[1] \"2022-10-01\"\n[1] \"2022-11-01\"\n[1] \"2022-12-01\"\ndata/_ForecastFRESACAD.csv\n<class 'str'>\n"
],
[
"#data_forecast_test = Path(\"data/_ForecastFRESACAD.csv\")\n#Forecast_D2 = pd.read_csv(data_forecast_test)\n\nfrom tadpole_algorithms.evaluation import evaluate_forecast\nfrom tadpole_algorithms.evaluation import print_metrics\n# Evaluate the model \ndictionary = evaluate_forecast(eval_df, Forecast_D2)\n# Print metrics\nprint_metrics(dictionary)",
"c:\\program files\\python38\\lib\\site-packages\\sklearn\\utils\\validation.py:67: FutureWarning: Pass labels=[0, 1, 2] as keyword args. From version 0.25 passing these as positional arguments will result in an error\n warnings.warn(\"Pass {} as keyword args. From version 0.25 \"\n"
],
[
"# AdjustedTrainFrame,testingFrame,Train_Imputed,Test_Imputed = model.preproc_tadpole_D1_D2(data_df_train_test,USE_PREPROC)\nD3AdjustedTrainFrame,D3testingFrame,D3Train_Imputed,D3Test_Imputed = model.preproc_with_R(D3Train,\n D3Test,\n data_Dictionaty,\n MinVisit=18,\n colImputeThreshold=0.15,\n rowImputeThreshold=0.10,\n includeID=False,\n usePreProc=USE_PREPROC)",
"2020-12-25 16:27:51,148 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Prepocess Data Frames\n[1] \"Cortical Thickness Average of RightBankssts\" \n[2] \"Cortical Thickness Average of RightCaudalAnteriorCingulate\"\n[3] \"Cortical Thickness Average of RightCaudalMiddleFrontal\" \n[4] \"Cortical Thickness Average of RightBankssts\" \n[5] \"Cortical Thickness Average of RightCaudalAnteriorCingulate\"\n[1] \"Cortical Thickness Average of LeftBankssts\" \n[2] \"Cortical Thickness Average of LeftCaudalAnteriorCingulate\"\n[3] \"Cortical Thickness Average of LeftCaudalMiddleFrontal\" \n[4] \"Cortical Thickness Average of LeftBankssts\" \n[5] \"Cortical Thickness Average of LeftCaudalAnteriorCingulate\"\n[1] 383 782\n [1] \"D1\" \n [2] \"D2\" \n [3] \"SITE\" \n [4] \"ORIGPROT\" \n [5] \"EXAMDATE_bl\" \n [6] \"Years_bl\" \n [7] \"Month_bl\" \n [8] \"Month\" \n [9] \"M\" \n [10] \"DX_bl\" \n [11] \"DXCHANGE\" \n [12] \"CDRSB\" \n [13] \"ADAS11\" \n [14] \"RAVLT_learning\" \n [15] \"RAVLT_immediate\" \n [16] \"FAQ\" \n [17] \"MOCA\" \n [18] \"EcogPtMem\" \n [19] \"EcogPtLang\" \n [20] \"EcogPtVisspat\" \n [21] \"EcogPtPlan\" \n [22] \"EcogPtOrgan\" \n [23] \"EcogPtDivatt\" \n [24] \"EcogPtTotal\" \n [25] \"EcogSPMem\" \n [26] \"EcogSPLang\" \n [27] \"EcogSPVisspat\" \n [28] \"EcogSPPlan\" \n [29] \"EcogSPOrgan\" \n [30] \"EcogSPDivatt\" \n [31] \"EcogSPTotal\" \n [32] \"CDRSB_bl\" \n [33] \"ADAS11_bl\" \n [34] \"ADAS13_bl\" \n [35] \"MMSE_bl\" \n [36] \"RAVLT_learning_bl\" \n [37] \"RAVLT_immediate_bl\" \n [38] \"FAQ_bl\" \n [39] \"MOCA_bl\" \n [40] \"EcogPtMem_bl\" \n [41] \"EcogPtLang_bl\" \n [42] \"EcogPtVisspat_bl\" \n [43] \"EcogPtPlan_bl\" \n [44] \"EcogPtOrgan_bl\" \n [45] \"EcogPtDivatt_bl\" \n [46] \"EcogPtTotal_bl\" \n [47] \"EcogSPMem_bl\" \n [48] \"EcogSPLang_bl\" \n [49] \"EcogSPVisspat_bl\" \n [50] \"EcogSPPlan_bl\" \n [51] \"EcogSPOrgan_bl\" \n [52] \"EcogSPDivatt_bl\" \n [53] \"EcogSPTotal_bl\" \n [54] \"APOE4\" \n [55] \"FDG\" \n [56] \"PIB\" \n [57] \"AV45\" \n [58] \"Ventricles_bl\" \n [59] \"Hippocampus_bl\" \n [60] \"WholeBrain_bl\" \n [61] \"Entorhinal_bl\" \n [62] \"Fusiform_bl\" \n [63] \"MidTemp_bl\" \n [64] \"ICV_bl\" \n [65] \"FDG_bl\" \n [66] \"PIB_bl\" \n [67] \"AV45_bl\" \n [68] \"ABETA_UPENNBIOMK9_04_19_17\" \n [69] \"TAU_UPENNBIOMK9_04_19_17\" \n [70] \"PTAU_UPENNBIOMK9_04_19_17\" \n [71] \"ST10CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [72] \"ST1SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [73] \"ST2SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [74] \"ST3SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [75] \"ST4SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [76] \"ST5SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [77] \"ST6SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [78] \"ST7SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [79] \"ST8SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [80] \"ST9SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [81] \"ST68SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [82] \"ST69SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [83] \"ST127SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n [84] \"ST128SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n [85] \"ST72CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [86] \"ST73CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [87] \"ST74CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [88] \"ST81CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [89] \"ST82CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [90] \"ST83CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [91] \"ST84CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [92] \"ST85CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [93] \"ST87CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [94] \"ST90CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [95] \"ST91CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [96] \"ST130CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n [97] \"ST93CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [98] \"ST94CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n [99] \"ST95CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[100] \"ST97CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[101] \"ST98CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[102] \"ST99CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[103] \"ST102CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[104] \"ST103CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[105] \"ST104CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[106] \"ST105CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[107] \"ST106CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[108] \"ST107CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[109] \"ST108CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[110] \"ST109CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[111] \"ST110CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[112] \"ST111CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[113] \"ST113CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[114] \"ST114CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[115] \"ST115CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[116] \"ST116CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[117] \"ST117CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[118] \"ST118CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[119] \"ST119CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[120] \"ST121CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[121] \"ST123CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[122] \"ST70SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[123] \"ST71SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[124] \"ST75SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[125] \"ST76SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[126] \"ST77SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[127] \"ST78SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[128] \"ST79SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[129] \"ST80SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[130] \"ST88SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[131] \"ST89SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[132] \"ST92SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[133] \"ST96SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[134] \"ST100SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[135] \"ST101SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[136] \"ST112SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[137] \"ST120SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[138] \"ST122SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[139] \"ST124SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[140] \"ST125SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[141] \"ST126SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[142] \"ST13CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[143] \"ST14CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[144] \"ST15CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[145] \"ST22CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[146] \"ST23CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[147] \"ST24CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[148] \"ST25CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[149] \"ST26CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[150] \"ST28CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[151] \"ST31CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[152] \"ST32CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[153] \"ST129CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[154] \"ST34CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[155] \"ST35CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[156] \"ST36CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[157] \"ST38CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[158] \"ST39CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[159] \"ST40CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[160] \"ST43CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[161] \"ST44CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[162] \"ST45CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[163] \"ST46CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[164] \"ST47CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[165] \"ST48CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[166] \"ST49CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[167] \"ST50CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[168] \"ST51CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[169] \"ST52CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[170] \"ST54CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[171] \"ST55CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[172] \"ST56CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[173] \"ST57CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[174] \"ST58CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[175] \"ST59CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[176] \"ST60CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[177] \"ST62CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[178] \"ST64CV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[179] \"ST11SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[180] \"ST12SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[181] \"ST16SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[182] \"ST17SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[183] \"ST18SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[184] \"ST19SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[185] \"ST20SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[186] \"ST21SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[187] \"ST29SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[188] \"ST30SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[189] \"ST33SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[190] \"ST37SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[191] \"ST41SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[192] \"ST42SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[193] \"ST53SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[194] \"ST61SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[195] \"ST63SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[196] \"ST65SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[197] \"ST66SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[198] \"ST67SV_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[199] \"ST72SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[200] \"ST73SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[201] \"ST74SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[202] \"ST81SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[203] \"ST82SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[204] \"ST83SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[205] \"ST84SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[206] \"ST85SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[207] \"ST86SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[208] \"ST90SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[209] \"ST91SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[210] \"ST130SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[211] \"ST93SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[212] \"ST94SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[213] \"ST95SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[214] \"ST97SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[215] \"ST98SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[216] \"ST99SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[217] \"ST102SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[218] \"ST103SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[219] \"ST104SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[220] \"ST105SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[221] \"ST106SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[222] \"ST107SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[223] \"ST108SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[224] \"ST109SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[225] \"ST110SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[226] \"ST111SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[227] \"ST113SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[228] \"ST114SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[229] \"ST115SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[230] \"ST116SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[231] \"ST117SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[232] \"ST118SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[233] \"ST119SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[234] \"ST121SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[235] \"ST123SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[236] \"ST13SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[237] \"ST14SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[238] \"ST15SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[239] \"ST22SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[240] \"ST23SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[241] \"ST24SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[242] \"ST25SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[243] \"ST26SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[244] \"ST27SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[245] \"ST31SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[246] \"ST32SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[247] \"ST129SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[248] \"ST34SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[249] \"ST35SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[250] \"ST36SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[251] \"ST38SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[252] \"ST39SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[253] \"ST40SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[254] \"ST43SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[255] \"ST44SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[256] \"ST45SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[257] \"ST46SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[258] \"ST47SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[259] \"ST48SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[260] \"ST49SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[261] \"ST50SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[262] \"ST51SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[263] \"ST52SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[264] \"ST54SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[265] \"ST55SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[266] \"ST56SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[267] \"ST57SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[268] \"ST58SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[269] \"ST59SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[270] \"ST60SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[271] \"ST62SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[272] \"ST64SA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[273] \"ST72TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[274] \"ST73TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[275] \"ST74TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[276] \"ST81TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[277] \"ST82TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[278] \"ST83TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[279] \"ST84TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[280] \"ST85TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[281] \"ST90TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[282] \"ST91TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[283] \"ST130TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[284] \"ST93TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[285] \"ST94TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[286] \"ST95TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[287] \"ST97TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[288] \"ST98TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[289] \"ST99TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[290] \"ST102TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[291] \"ST103TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[292] \"ST104TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[293] \"ST105TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[294] \"ST106TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[295] \"ST107TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[296] \"ST108TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[297] \"ST109TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[298] \"ST110TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[299] \"ST111TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[300] \"ST113TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[301] \"ST114TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[302] \"ST115TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[303] \"ST116TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[304] \"ST117TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[305] \"ST118TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[306] \"ST119TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[307] \"ST121TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[308] \"ST123TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[309] \"ST72TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[310] \"ST73TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[311] \"ST74TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[312] \"ST81TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[313] \"ST82TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[314] \"ST83TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[315] \"ST84TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[316] \"ST85TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[317] \"ST90TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[318] \"ST91TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[319] \"ST130TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[320] \"ST93TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[321] \"ST94TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[322] \"ST95TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[323] \"ST97TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[324] \"ST98TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[325] \"ST99TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[326] \"ST102TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[327] \"ST103TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[328] \"ST104TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[329] \"ST105TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[330] \"ST106TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[331] \"ST107TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[332] \"ST108TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[333] \"ST109TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[334] \"ST110TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[335] \"ST111TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[336] \"ST113TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[337] \"ST114TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[338] \"ST115TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[339] \"ST116TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[340] \"ST117TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[341] \"ST118TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[342] \"ST119TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[343] \"ST121TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[344] \"ST123TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[345] \"ST13TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[346] \"ST14TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[347] \"ST15TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[348] \"ST22TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[349] \"ST23TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[350] \"ST24TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[351] \"ST25TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[352] \"ST26TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[353] \"ST31TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[354] \"ST32TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[355] \"ST129TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[356] \"ST34TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[357] \"ST35TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[358] \"ST36TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[359] \"ST38TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[360] \"ST39TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[361] \"ST40TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[362] \"ST43TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[363] \"ST44TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[364] \"ST45TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[365] \"ST46TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[366] \"ST47TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[367] \"ST48TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[368] \"ST49TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[369] \"ST50TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[370] \"ST51TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[371] \"ST52TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[372] \"ST54TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[373] \"ST55TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[374] \"ST56TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[375] \"ST57TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[376] \"ST58TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[377] \"ST59TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[378] \"ST60TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[379] \"ST62TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[380] \"ST64TA_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[381] \"ST13TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[382] \"ST14TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[383] \"ST15TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[384] \"ST22TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[385] \"ST23TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[386] \"ST24TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[387] \"ST25TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[388] \"ST26TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[389] \"ST31TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[390] \"ST32TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[391] \"ST129TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\"\n[392] \"ST34TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[393] \"ST35TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[394] \"ST36TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[395] \"ST38TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[396] \"ST39TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[397] \"ST40TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[398] \"ST43TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[399] \"ST44TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[400] \"ST45TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[401] \"ST46TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[402] \"ST47TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[403] \"ST48TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[404] \"ST49TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[405] \"ST50TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[406] \"ST51TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[407] \"ST52TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[408] \"ST54TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[409] \"ST55TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[410] \"ST56TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[411] \"ST57TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[412] \"ST58TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[413] \"ST59TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[414] \"ST60TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[415] \"ST62TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[416] \"ST64TS_UCSFFSL_02_01_16_UCSFFSL51ALL_08_01_16\" \n[1] 370\n [1] \"RID\" \n [2] \"D1\" \n [3] \"D2\" \n [4] \"SITE\" \n [5] \"COLPROT\" \n [6] \"ORIGPROT\" \n [7] \"VISCODE\" \n [8] \"EXAMDATE_bl\" \n [9] \"EXAMDATE\" \n [10] \"Years_bl\" \n [11] \"Month_bl\" \n [12] \"Month\" \n [13] \"M\" \n [14] \"DX\" \n [15] \"DX_bl\" \n [16] \"DXCHANGE\" \n [17] \"AGE\" \n [18] \"PTGENDER\" \n [19] \"PTEDUCAT\" \n [20] \"PTETHCAT\" \n [21] \"PTRACCAT\" \n [22] \"PTMARRY\" \n [23] \"CDRSB\" \n [24] \"ADAS11\" \n [25] \"ADAS13\" \n [26] \"MMSE\" \n [27] \"RAVLT_learning\" \n [28] \"RAVLT_immediate\" \n [29] \"FAQ\" \n [30] \"CDRSB_bl\" \n [31] \"ADAS11_bl\" \n [32] \"ADAS13_bl\" \n [33] \"MMSE_bl\" \n [34] \"RAVLT_learning_bl\" \n [35] \"RAVLT_immediate_bl\" \n [36] \"FAQ_bl\" \n [37] \"APOE4\" \n [38] \"Ventricles\" \n [39] \"WholeBrain\" \n [40] \"ICV\" \n [41] \"Ventricles_bl\" \n [42] \"Hippocampus_bl\" \n [43] \"WholeBrain_bl\" \n [44] \"Entorhinal_bl\" \n [45] \"Fusiform_bl\" \n [46] \"MidTemp_bl\" \n [47] \"ICV_bl\" \n [48] \"ST10CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [49] \"ST1SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [50] \"ST2SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [51] \"ST3SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [52] \"ST4SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [53] \"ST5SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [54] \"ST6SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [55] \"ST7SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [56] \"ST9SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [57] \"ST68SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [58] \"ST69SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [59] \"ST127SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [60] \"ST128SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [61] \"nICV\" \n [62] \"Mean_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [63] \"Mean_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [64] \"Mean_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [65] \"Mean_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [66] \"Mean_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [67] \"Mean_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [68] \"Mean_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [69] \"Mean_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [70] \"Mean_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [71] \"Mean_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [72] \"Mean_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [73] \"Mean_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [74] \"Mean_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [75] \"Mean_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [76] \"Mean_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [77] \"Mean_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [78] \"Mean_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [79] \"Mean_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [80] \"Mean_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [81] \"Mean_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [82] \"Mean_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [83] \"Mean_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [84] \"Mean_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [85] \"Mean_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [86] \"Mean_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [87] \"Mean_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [88] \"Mean_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [89] \"Mean_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [90] \"Mean_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [91] \"Mean_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [92] \"Mean_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [93] \"Mean_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [94] \"Mean_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [95] \"Mean_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [96] \"Mean_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [97] \"Mean_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [98] \"Mean_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [99] \"Mean_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[100] \"Mean_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[101] \"Mean_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[102] \"Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[103] \"Mean_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[104] \"Mean_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[105] \"Mean_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[106] \"Mean_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[107] \"Mean_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[108] \"Mean_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[109] \"Mean_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[110] \"Dif_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[111] \"Dif_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[112] \"Dif_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[113] \"Dif_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[114] \"Dif_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[115] \"Dif_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[116] \"Dif_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[117] \"Dif_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[118] \"Dif_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[119] \"Dif_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[120] \"Dif_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[121] \"Dif_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[122] \"Dif_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[123] \"Dif_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[124] \"Dif_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[125] \"Dif_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[126] \"Dif_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[127] \"Dif_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[128] \"Dif_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[129] \"Dif_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[130] \"Dif_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[131] \"Dif_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[132] \"Dif_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[133] \"Dif_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[134] \"Dif_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[135] \"Dif_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[136] \"Dif_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[137] \"Dif_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[138] \"Dif_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[139] \"Dif_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[140] \"Dif_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[141] \"Dif_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[142] \"Dif_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[143] \"Dif_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[144] \"Dif_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[145] \"Dif_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[146] \"Dif_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[147] \"Dif_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[148] \"Dif_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[149] \"Dif_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[150] \"Dif_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[151] \"Dif_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[152] \"Dif_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[153] \"Dif_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[154] \"Dif_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[155] \"Dif_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[156] \"Dif_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[157] \"Dif_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[158] \"Mean_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[159] \"Mean_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[160] \"Mean_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[161] \"Mean_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[162] \"Mean_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[163] \"Mean_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[164] \"Mean_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[165] \"Mean_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[166] \"Mean_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[167] \"Mean_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[168] \"Mean_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[169] \"Mean_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[170] \"Mean_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[171] \"Mean_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[172] \"Mean_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[173] \"Mean_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[174] \"Mean_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[175] \"Mean_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[176] \"Mean_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[177] \"Mean_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[178] \"Mean_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[179] \"Mean_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[180] \"Mean_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[181] \"Mean_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[182] \"Mean_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[183] \"Mean_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[184] \"Mean_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[185] \"Mean_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[186] \"Mean_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[187] \"Mean_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[188] \"Mean_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[189] \"Mean_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[190] \"Mean_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[191] \"Mean_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[192] \"Dif_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[193] \"Dif_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[194] \"Dif_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[195] \"Dif_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[196] \"Dif_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[197] \"Dif_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[198] \"Dif_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[199] \"Dif_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[200] \"Dif_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[201] \"Dif_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[202] \"Dif_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[203] \"Dif_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[204] \"Dif_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[205] \"Dif_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[206] \"Dif_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[207] \"Dif_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[208] \"Dif_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[209] \"Dif_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[210] \"Dif_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[211] \"Dif_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[212] \"Dif_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[213] \"Dif_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[214] \"Dif_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[215] \"Dif_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[216] \"Dif_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[217] \"Dif_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[218] \"Dif_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[219] \"Dif_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[220] \"Dif_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[221] \"Dif_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[222] \"Dif_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[223] \"Dif_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[224] \"Dif_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[225] \"Dif_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[226] \"Mean_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[227] \"Mean_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[228] \"Mean_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[229] \"Mean_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[230] \"Mean_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[231] \"Mean_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[232] \"Mean_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[233] \"Mean_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[234] \"Mean_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[235] \"Mean_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[236] \"Mean_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[237] \"Mean_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[238] \"Mean_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[239] \"Mean_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[240] \"Mean_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[241] \"Mean_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[242] \"Mean_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[243] \"Mean_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[244] \"Mean_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[245] \"Mean_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[246] \"Mean_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[247] \"Mean_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[248] \"Mean_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[249] \"Mean_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[250] \"Mean_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[251] \"Mean_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[252] \"Mean_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[253] \"Mean_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[254] \"Mean_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[255] \"Mean_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[256] \"Mean_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[257] \"Mean_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[258] \"Mean_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[259] \"Mean_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[260] \"Mean_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[261] \"Mean_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[262] \"Mean_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[263] \"Mean_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[264] \"Mean_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[265] \"Mean_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[266] \"Mean_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[267] \"Mean_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[268] \"Mean_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[269] \"Mean_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[270] \"Mean_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[271] \"Mean_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[272] \"Mean_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[273] \"Mean_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[274] \"Mean_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[275] \"Mean_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[276] \"Mean_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[277] \"Mean_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[278] \"Mean_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[279] \"Mean_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[280] \"Mean_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[281] \"Mean_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[282] \"Mean_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[283] \"Mean_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[284] \"Mean_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[285] \"Mean_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[286] \"Mean_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[287] \"Mean_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[288] \"Mean_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[289] \"Mean_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[290] \"Mean_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[291] \"Mean_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[292] \"Mean_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[293] \"Mean_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[294] \"Dif_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[295] \"Dif_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[296] \"Dif_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[297] \"Dif_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[298] \"Dif_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[299] \"Dif_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[300] \"Dif_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[301] \"Dif_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[302] \"Dif_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[303] \"Dif_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[304] \"Dif_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[305] \"Dif_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[306] \"Dif_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[307] \"Dif_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[308] \"Dif_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[309] \"Dif_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[310] \"Dif_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[311] \"Dif_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[312] \"Dif_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[313] \"Dif_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[314] \"Dif_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[315] \"Dif_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[316] \"Dif_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[317] \"Dif_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[318] \"Dif_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[319] \"Dif_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[320] \"Dif_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[321] \"Dif_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[322] \"Dif_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[323] \"Dif_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[324] \"Dif_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[325] \"Dif_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[326] \"Dif_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[327] \"Dif_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[328] \"Dif_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[329] \"Dif_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[330] \"Dif_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[331] \"Dif_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[332] \"Dif_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[333] \"Dif_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[334] \"Dif_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[335] \"Dif_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[336] \"Dif_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[337] \"Dif_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[338] \"Dif_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[339] \"Dif_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[340] \"Dif_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[341] \"Dif_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[342] \"Dif_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[343] \"Dif_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[344] \"Dif_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[345] \"Dif_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[346] \"Dif_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[347] \"Dif_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[348] \"Dif_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[349] \"Dif_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[350] \"Dif_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[351] \"Dif_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[352] \"Dif_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[353] \"Dif_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[354] \"Dif_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[355] \"Dif_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[356] \"Dif_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[357] \"Dif_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[358] \"Dif_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[359] \"Dif_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[360] \"Dif_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[361] \"Dif_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[362] \"MeanVolumes\" \n[363] \"StdVolumes\" \n[364] \"COVOlumens\" \n[365] \"MeanArea\" \n[366] \"StdArea\" \n[367] \"COArea\" \n[368] \"MeanThickness\" \n[369] \"StdThickness\" \n[370] \"COMeanThickness\" \n[1] 3401\n..................................................500 \n..................................................1000 \n..................................................1500 \n..................................................2000 \n..................................................2500 \n..................................................3000 \n........................................[1] 6\n[1] 0\n[1] 896\n[1] 896 896\n[1] 896\n[1] 350\n [1] \"RID\" \"D1\" \"D2\" \"SITE\" \"COLPROT\" \n [6] \"ORIGPROT\" \"VISCODE\" \"EXAMDATE_bl\" \"EXAMDATE\" \"Years_bl\" \n[11] \"Month_bl\" \"Month\" \"M\" \"DX\" \"DX_bl\" \n[16] \"DXCHANGE\" \"PTEDUCAT\" \"PTETHCAT\" \"PTRACCAT\" \"PTMARRY\" \n..................................................500 \n.......................................[1] 896 350\n[1] 896 370\n\n 0 1 \n417 479 \n[1] 896 370\n[1] 896 370\n"
],
[
"#Train Congitive Models\nD3modelfilename = model.Train_Congitive(D3AdjustedTrainFrame,usePreProc=USE_PREPROC)",
"2020-12-25 16:31:47,407 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Train Cognitive Models\n [1] \"AGE\" \n [2] \"PTGENDER\" \n [3] \"CDRSB\" \n [4] \"ADAS11\" \n [5] \"ADAS13\" \n [6] \"MMSE\" \n [7] \"RAVLT_learning\" \n [8] \"RAVLT_immediate\" \n [9] \"FAQ\" \n [10] \"CDRSB_bl\" \n [11] \"ADAS11_bl\" \n [12] \"ADAS13_bl\" \n [13] \"MMSE_bl\" \n [14] \"RAVLT_learning_bl\" \n [15] \"RAVLT_immediate_bl\" \n [16] \"FAQ_bl\" \n [17] \"APOE4\" \n [18] \"Ventricles\" \n [19] \"WholeBrain\" \n [20] \"ICV\" \n [21] \"Ventricles_bl\" \n [22] \"Hippocampus_bl\" \n [23] \"WholeBrain_bl\" \n [24] \"Entorhinal_bl\" \n [25] \"Fusiform_bl\" \n [26] \"MidTemp_bl\" \n [27] \"ICV_bl\" \n [28] \"ST10CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [29] \"ST1SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [30] \"ST2SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [31] \"ST3SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [32] \"ST4SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [33] \"ST5SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [34] \"ST6SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [35] \"ST7SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [36] \"ST9SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [37] \"ST68SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [38] \"ST69SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [39] \"ST127SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [40] \"ST128SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [41] \"nICV\" \n [42] \"Mean_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [43] \"Mean_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [44] \"Mean_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [45] \"Mean_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [46] \"Mean_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [47] \"Mean_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [48] \"Mean_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [49] \"Mean_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [50] \"Mean_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [51] \"Mean_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [52] \"Mean_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [53] \"Mean_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [54] \"Mean_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [55] \"Mean_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [56] \"Mean_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [57] \"Mean_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [58] \"Mean_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [59] \"Mean_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [60] \"Mean_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [61] \"Mean_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [62] \"Mean_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [63] \"Mean_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [64] \"Mean_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [65] \"Mean_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [66] \"Mean_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [67] \"Mean_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [68] \"Mean_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [69] \"Mean_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [70] \"Mean_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [71] \"Mean_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [72] \"Mean_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [73] \"Mean_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [74] \"Mean_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [75] \"Mean_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [76] \"Mean_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [77] \"Mean_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [78] \"Mean_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [79] \"Mean_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [80] \"Mean_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [81] \"Mean_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [82] \"Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [83] \"Mean_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [84] \"Mean_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [85] \"Mean_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [86] \"Mean_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [87] \"Mean_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [88] \"Mean_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [89] \"Mean_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [90] \"Dif_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [91] \"Dif_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [92] \"Dif_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [93] \"Dif_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [94] \"Dif_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [95] \"Dif_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [96] \"Dif_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [97] \"Dif_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [98] \"Dif_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [99] \"Dif_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[100] \"Dif_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[101] \"Dif_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[102] \"Dif_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[103] \"Dif_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[104] \"Dif_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[105] \"Dif_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[106] \"Dif_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[107] \"Dif_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[108] \"Dif_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[109] \"Dif_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[110] \"Dif_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[111] \"Dif_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[112] \"Dif_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[113] \"Dif_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[114] \"Dif_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[115] \"Dif_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[116] \"Dif_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[117] \"Dif_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[118] \"Dif_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[119] \"Dif_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[120] \"Dif_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[121] \"Dif_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[122] \"Dif_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[123] \"Dif_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[124] \"Dif_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[125] \"Dif_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[126] \"Dif_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[127] \"Dif_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[128] \"Dif_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[129] \"Dif_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[130] \"Dif_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[131] \"Dif_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[132] \"Dif_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[133] \"Dif_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[134] \"Dif_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[135] \"Dif_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[136] \"Dif_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[137] \"Dif_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[138] \"Mean_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[139] \"Mean_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[140] \"Mean_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[141] \"Mean_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[142] \"Mean_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[143] \"Mean_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[144] \"Mean_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[145] \"Mean_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[146] \"Mean_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[147] \"Mean_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[148] \"Mean_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[149] \"Mean_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[150] \"Mean_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[151] \"Mean_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[152] \"Mean_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[153] \"Mean_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[154] \"Mean_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[155] \"Mean_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[156] \"Mean_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[157] \"Mean_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[158] \"Mean_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[159] \"Mean_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[160] \"Mean_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[161] \"Mean_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[162] \"Mean_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[163] \"Mean_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[164] \"Mean_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[165] \"Mean_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[166] \"Mean_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[167] \"Mean_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[168] \"Mean_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[169] \"Mean_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[170] \"Mean_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[171] \"Mean_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[172] \"Dif_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[173] \"Dif_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[174] \"Dif_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[175] \"Dif_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[176] \"Dif_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[177] \"Dif_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[178] \"Dif_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[179] \"Dif_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[180] \"Dif_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[181] \"Dif_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[182] \"Dif_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[183] \"Dif_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[184] \"Dif_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[185] \"Dif_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[186] \"Dif_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[187] \"Dif_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[188] \"Dif_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[189] \"Dif_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[190] \"Dif_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[191] \"Dif_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[192] \"Dif_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[193] \"Dif_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[194] \"Dif_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[195] \"Dif_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[196] \"Dif_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[197] \"Dif_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[198] \"Dif_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[199] \"Dif_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[200] \"Dif_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[201] \"Dif_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[202] \"Dif_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[203] \"Dif_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[204] \"Dif_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[205] \"Dif_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[206] \"Mean_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[207] \"Mean_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[208] \"Mean_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[209] \"Mean_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[210] \"Mean_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[211] \"Mean_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[212] \"Mean_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[213] \"Mean_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[214] \"Mean_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[215] \"Mean_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[216] \"Mean_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[217] \"Mean_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[218] \"Mean_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[219] \"Mean_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[220] \"Mean_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[221] \"Mean_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[222] \"Mean_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[223] \"Mean_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[224] \"Mean_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[225] \"Mean_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[226] \"Mean_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[227] \"Mean_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[228] \"Mean_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[229] \"Mean_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[230] \"Mean_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[231] \"Mean_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[232] \"Mean_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[233] \"Mean_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[234] \"Mean_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[235] \"Mean_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[236] \"Mean_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[237] \"Mean_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[238] \"Mean_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[239] \"Mean_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[240] \"Mean_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[241] \"Mean_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[242] \"Mean_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[243] \"Mean_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[244] \"Mean_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[245] \"Mean_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[246] \"Mean_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[247] \"Mean_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[248] \"Mean_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[249] \"Mean_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[250] \"Mean_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[251] \"Mean_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[252] \"Mean_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[253] \"Mean_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[254] \"Mean_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[255] \"Mean_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[256] \"Mean_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[257] \"Mean_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[258] \"Mean_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[259] \"Mean_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[260] \"Mean_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[261] \"Mean_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[262] \"Mean_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[263] \"Mean_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[264] \"Mean_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[265] \"Mean_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[266] \"Mean_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[267] \"Mean_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[268] \"Mean_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[269] \"Mean_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[270] \"Mean_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[271] \"Mean_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[272] \"Mean_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[273] \"Mean_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[274] \"Dif_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[275] \"Dif_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[276] \"Dif_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[277] \"Dif_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[278] \"Dif_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[279] \"Dif_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[280] \"Dif_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[281] \"Dif_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[282] \"Dif_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[283] \"Dif_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[284] \"Dif_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[285] \"Dif_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[286] \"Dif_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[287] \"Dif_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[288] \"Dif_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[289] \"Dif_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[290] \"Dif_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[291] \"Dif_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[292] \"Dif_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[293] \"Dif_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[294] \"Dif_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[295] \"Dif_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[296] \"Dif_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[297] \"Dif_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[298] \"Dif_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[299] \"Dif_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[300] \"Dif_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[301] \"Dif_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[302] \"Dif_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[303] \"Dif_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[304] \"Dif_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[305] \"Dif_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[306] \"Dif_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[307] \"Dif_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[308] \"Dif_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[309] \"Dif_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[310] \"Dif_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[311] \"Dif_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[312] \"Dif_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[313] \"Dif_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[314] \"Dif_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[315] \"Dif_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[316] \"Dif_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[317] \"Dif_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[318] \"Dif_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[319] \"Dif_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[320] \"Dif_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[321] \"Dif_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[322] \"Dif_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[323] \"Dif_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[324] \"Dif_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[325] \"Dif_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[326] \"Dif_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[327] \"Dif_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[328] \"Dif_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[329] \"Dif_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[330] \"Dif_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[331] \"Dif_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[332] \"Dif_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[333] \"Dif_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[334] \"Dif_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[335] \"Dif_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[336] \"Dif_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[337] \"Dif_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[338] \"Dif_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[339] \"Dif_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[340] \"Dif_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[341] \"Dif_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[342] \"MeanVolumes\" \n[343] \"StdVolumes\" \n[344] \"COVOlumens\" \n[345] \"MeanArea\" \n[346] \"StdArea\" \n[347] \"COArea\" \n[348] \"MeanThickness\" \n[349] \"StdThickness\" \n[350] \"COMeanThickness\" \n [1] 0 3 6 12 18 24 36 48 60 72 84 96\n\n Dementia Dementia to MCI MCI MCI to Dementia MCI to NL \n 476 1 516 62 6 \n NL NL to Dementia NL to MCI \n 289 1 8 \n[1] 172\n[1] 538\n[1] 155\n[1] 65\n\n 0 1 \n 25 187 \n\n bl m06 m12 m18 m24 m36 m48 m60 \n 79 58 38 18 12 4 2 1 \n[1] 76\n\n 0 1 \n11 65 \n[++++++++++++++++++++]..[1] 65\n[+++--++---][1] 77\n\n 0 1 \n12 65 \n[+++++++++-+++++++++].[1] 65\n[++++++-++][1] 76\n\n 0 1 \n11 65 \n[++++++++++++++++++++]..[1] 65\n[+-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[+++][1] 76\n\n 0 1 \n11 65 \n[++++++++++++-++++++].[1] 65\n[+-][1] 76\n\n 0 1 \n11 65 \n[++++++++++++++++++].[1] 65\n[+-][1] 77\n\n 0 1 \n12 65 \n[++++++++-++++++-].[1] 65\n[+++++-][1] 76\n\n 0 1 \n11 65 \n[+++++++++++++++++++].[1] 65\n[++-][1] 76\n\n 0 1 \n11 65 \n[++++++++++++++++++++]..[1] 65\n[+++-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[++][1] 77\n\n 0 1 \n12 65 \n[++++++++++++-++++++].[1] 65\n[++++-][1] 76\n\n 0 1 \n11 65 \n[++++++++++++-++++++].[1] 65\n[++++-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[+-][1] 76\n\n 0 1 \n11 65 \n[++++++++++++++++++].[1] 65\n[+++-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[+++-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[+++-+][1] 76\n\n 0 1 \n11 65 \n[++++++++++++-++++].[1] 65\n[+-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[++++++-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[+-++-][1] 77\n\n 0 1 \n12 65 \n[++++++++-][1] 65\n[++--][1] 76\n\n 0 1 \n11 65 \n[+++++++++++++++++++].[1] 65\n[++++---][1] 76\n\n 0 1 \n11 65 \n[+++++++++++++++++].[1] 65\n[++-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++++]..[1] 65\n[+][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++-++].[1] 65\n[++-][1] 77\n\n 0 1 \n12 65 \n[++++++++++++++++++].[1] 65\n[+-][1] 65\n[1] 40\n[1] 13\n\n 0 1 \n88 9 \n\n bl m06 m12 m18 m24 m36 \n 47 23 16 5 4 2 \n[1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[+++++---+----][1] 42\n\n 0 1 \n37 5 \n[+++][1] 5\n[+++++-][1] 41\n\n 0 1 \n36 5 \n[++++][1] 5\n[+++---------][1] 42\n\n 0 1 \n37 5 \n[+++][1] 5\n[++++++][1] 42\n\n 0 1 \n37 5 \n[+++][1] 5\n[++++-][1] 41\n\n 0 1 \n36 5 \n[+++][1] 5\n[+++++--][1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[++--][1] 42\n\n 0 1 \n37 5 \n[+++][1] 5\n[++++++][1] 41\n\n 0 1 \n36 5 \n[+--+][1] 5\n[+++++-+-+++-+].[1] 42\n\n 0 1 \n37 5 \n[++][1] 5\n[++--][1] 42\n\n 0 1 \n37 5 \n[+++][1] 5\n[++++-+----][1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[++---][1] 41\n\n 0 1 \n36 5 \n[++++][1] 5\n[+++++-][1] 42\n\n 0 1 \n37 5 \n[+++][1] 5\n[++++++-][1] 41\n\n 0 1 \n36 5 \n[++][1] 5\n[++++++++++--+].[1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[+++---------][1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[++++----+----][1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[+++---------][1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[++--][1] 41\n\n 0 1 \n36 5 \n[+++++][1] 5\n[++++++++++++].[1] 41\n\n 0 1 \n36 5 \n[+---][1] 5\n[++++++-][1] 41\n\n 0 1 \n36 5 \n[+++][1] 5\n[+++++-+-][1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[+++---------][1] 42\n\n 0 1 \n37 5 \n[++++][1] 5\n[++---][1] 41\n\n 0 1 \n36 5 \n[+++++][1] 5\n[++-]\n Dementia Dementia to MCI MCI MCI to Dementia MCI to NL \n 476 1 516 62 6 \n NL NL to Dementia NL to MCI \n 289 1 8 \n[1] 74\n[1] 525\n[1] 24\n[1] 14\n[1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[--][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[+++][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++++][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+++][1] 34\n\n 0 1 \n25 9 \n[+][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+][1] 34\n\n 0 1 \n25 9 \n[+++][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+++++][1] 34\n\n 0 1 \n25 9 \n[+][1] 9\n[--][1] 34\n\n 0 1 \n25 9 \n[+][1] 9\n[++-++++-+--][1] 34\n\n 0 1 \n25 9 \n[+++][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+][1] 34\n\n 0 1 \n25 9 \n[++++++][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[-+][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+][1] 34\n\n 0 1 \n25 9 \n[+][1] 9\n[+-][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+][1] 34\n\n 0 1 \n25 9 \n[+][1] 9\n[++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+][1] 34\n\n 0 1 \n25 9 \n[+][1] 9\n[+][1] 34\n\n 0 1 \n25 9 \n[++++][1] 9\n[++++][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+][1] 34\n\n 0 1 \n25 9 \n[++][1] 9\n[+++++][1] 328\n \n 0 1 2\n AD 0 0 112\n CN 57 4 0\n EMCI 2 26 0\n LMCI 1 96 25\n SMC 4 1 0\n[++-][1] 328\n \n 0 1 2\n AD 0 0 115\n CN 59 2 1\n EMCI 1 23 0\n LMCI 0 97 26\n SMC 4 0 0\n[+--+-]2020-12-25 16:34:47,697 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Error in optim(s0, fmin, gmin, method = \"BFGS\", ...) : \n initial value in 'vmmin' is not finite\n\n2020-12-25 16:34:47,698 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In addition: \n2020-12-25 16:34:47,699 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: There were 50 or more warnings (use warnings() to see the first 50)\n2020-12-25 16:34:47,700 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n\nclass ~ 1 + CDRSB_bl + CDRSB + MMSE_bl + RAVLT_learning + Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16 + MMSE + ADAS13_bl + RAVLT_learning_bl \n[1] 333\n \n 0 1 2\n AD 0 0 115\n CN 57 5 0\n EMCI 1 26 1\n LMCI 2 93 29\n SMC 4 0 0\n[++-][1] 326\n \n 0 1 2\n AD 0 0 114\n CN 58 3 0\n EMCI 1 26 0\n LMCI 0 94 25\n SMC 4 1 0\n[++-][1] 324\n \n 0 1 2\n AD 0 0 110\n CN 57 5 1\n EMCI 0 24 1\n LMCI 2 93 27\n SMC 3 1 0\n[++-]2020-12-25 16:34:59,012 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Error in MASS::polr(frma, data) : \n attempt to find suitable starting values failed\n\n2020-12-25 16:34:59,013 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In addition: \n2020-12-25 16:34:59,014 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Warning messages:\n\n2020-12-25 16:34:59,015 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 1: \n2020-12-25 16:34:59,015 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In MLMethod(class ~ ., AllADNISets[[n]], ...) :\n2020-12-25 16:34:59,016 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n \n2020-12-25 16:34:59,017 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: class ~ 1 + CDRSB_bl + CDRSB + MMSE_bl + RAVLT_learning + Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16 + MMSE + ADAS13_bl + RAVLT_learning_bl : No ordinal model\n\n\n2020-12-25 16:34:59,017 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 2: \n2020-12-25 16:34:59,018 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In MLMethod(class ~ ., AllADNISets[[n]], ...) :\n2020-12-25 16:34:59,019 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Ordinal Model Fit\n\n\n2020-12-25 16:34:59,019 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 3: glm.fit: fitted probabilities numerically 0 or 1 occurred \n\n2020-12-25 16:34:59,020 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 4: \n2020-12-25 16:34:59,021 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In MLMethod(class ~ ., AllADNISets[[n]], ...) :\n2020-12-25 16:34:59,021 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Ordinal Model Fit\n\n\n2020-12-25 16:34:59,022 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 5: glm.fit: fitted probabilities numerically 0 or 1 occurred \n\n2020-12-25 16:34:59,023 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 6: \n2020-12-25 16:34:59,023 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In MLMethod(class ~ ., AllADNISets[[n]], ...) :\n2020-12-25 16:34:59,024 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Ordinal Model Fit\n\n\n2020-12-25 16:34:59,025 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 7: glm.fit: algorithm did not converge \n\n2020-12-25 16:34:59,025 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 8: glm.fit: fitted probabilities numerically 0 or 1 occurred \n\nclass ~ 1 + CDRSB + FAQ_bl + CDRSB_bl + ADAS13 + FAQ + MMSE_bl \n[1] 327\n \n 0 1 2\n AD 0 0 110\n CN 58 3 0\n EMCI 2 28 0\n LMCI 1 92 28\n SMC 5 0 0\n[+--][1] 338\n \n 0 1 2\n AD 0 1 116\n CN 57 3 1\n EMCI 2 29 1\n LMCI 1 102 20\n SMC 4 1 0\n[+-]2020-12-25 16:35:05,089 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Error in optim(s0, fmin, gmin, method = \"BFGS\", ...) : \n initial value in 'vmmin' is not finite\n\n2020-12-25 16:35:05,091 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In addition: \n2020-12-25 16:35:05,092 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Warning messages:\n\n2020-12-25 16:35:05,092 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 1: \n2020-12-25 16:35:05,093 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In MLMethod(class ~ ., AllADNISets[[n]], ...) :\n2020-12-25 16:35:05,094 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n \n2020-12-25 16:35:05,094 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: class ~ 1 + CDRSB + FAQ_bl + CDRSB_bl + ADAS13 + FAQ + MMSE_bl : No ordinal model\n\n\n2020-12-25 16:35:05,095 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 2: \n2020-12-25 16:35:05,096 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In MLMethod(class ~ ., AllADNISets[[n]], ...) :\n2020-12-25 16:35:05,096 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Ordinal Model Fit\n\n\n2020-12-25 16:35:05,097 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 3: glm.fit: fitted probabilities numerically 0 or 1 occurred \n\n2020-12-25 16:35:05,097 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 4: \n2020-12-25 16:35:05,098 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In MLMethod(class ~ ., AllADNISets[[n]], ...) :\n2020-12-25 16:35:05,099 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Ordinal Model Fit\n\n\n2020-12-25 16:35:05,099 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: 5: glm.fit: fitted probabilities numerically 0 or 1 occurred \n\nclass ~ 1 + CDRSB_bl + Mean_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16 + CDRSB + FAQ + RAVLT_learning_bl \n[1] 325\n \n 0 1 2\n AD 0 0 112\n CN 59 1 2\n EMCI 1 23 1\n LMCI 1 91 30\n SMC 4 0 0\n[+---][1] 328\n \n 0 1 2\n AD 0 1 112\n CN 60 2 0\n EMCI 1 26 0\n LMCI 2 94 26\n SMC 3 1 0\n[+-][1] 329\n \n 0 1 2\n AD 0 1 114\n CN 58 1 1\n EMCI 1 26 0\n LMCI 2 89 31\n SMC 5 0 0\n[+--][1] 332\n \n 0 1 2\n AD 0 0 112\n CN 61 1 0\n EMCI 1 27 1\n LMCI 2 92 30\n SMC 4 1 0\n[+-][1] 336\n \n 0 1 2\n AD 0 0 114\n CN 62 1 0\n EMCI 1 28 2\n LMCI 2 97 24\n SMC 5 0 0\n[+--][1] 329\n \n 0 1 2\n AD 0 0 112\n CN 59 2 1\n EMCI 2 26 0\n LMCI 1 97 25\n SMC 4 0 0\n[+-][1] 336\n \n 0 1 2\n AD 0 0 115\n CN 60 3 0\n EMCI 2 32 1\n LMCI 2 90 26\n SMC 4 1 0\n[++-][1] 333\n \n 0 1 2\n AD 0 0 114\n CN 60 3 0\n EMCI 1 27 1\n LMCI 2 92 28\n SMC 5 0 0\n[+-][1] 326\n \n 0 1 2\n AD 0 0 109\n CN 59 2 0\n EMCI 1 28 0\n LMCI 3 95 25\n SMC 4 0 0\n[+--][1] 338\n \n 0 1 2\n AD 0 1 118\n CN 59 2 1\n EMCI 2 30 0\n LMCI 1 97 23\n SMC 4 0 0\n[++-][1] 332\n \n 0 1 2\n AD 0 1 115\n CN 57 3 1\n EMCI 1 25 1\n LMCI 1 94 28\n SMC 5 0 0\n[+--][1] 328\n \n 0 1 2\n AD 0 0 114\n CN 58 3 0\n EMCI 1 25 1\n LMCI 1 92 27\n SMC 6 0 0\n[++-]2020-12-25 16:35:45,516 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: Error in optim(s0, fmin, gmin, method = \"BFGS\", ...) : \n initial value in 'vmmin' is not finite\n\n2020-12-25 16:35:45,517 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: In addition: \n2020-12-25 16:35:45,518 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: There were 25 warnings (use warnings() to see them)\n2020-12-25 16:35:45,519 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n\nclass ~ 1 + CDRSB_bl + CDRSB + FAQ + MMSE_bl + ADAS13 + FAQ_bl \n[1] 329\n \n 0 1 2\n AD 0 0 114\n CN 58 3 0\n EMCI 2 25 1\n LMCI 2 93 26\n SMC 5 0 0\n[+---][1] 335\n \n 0 1 2\n AD 0 1 116\n CN 58 4 0\n EMCI 2 26 0\n LMCI 2 97 23\n SMC 5 1 0\n[++-][1] 321\n \n 0 1 2\n AD 0 1 110\n CN 60 1 1\n EMCI 0 25 0\n LMCI 2 91 25\n SMC 5 0 0\n[+-][1] 328\n \n 0 1 2\n AD 0 0 110\n CN 55 3 1\n EMCI 2 29 0\n LMCI 2 95 26\n SMC 5 0 0\n[+-][1] 329\n \n 0 1 2\n AD 0 0 115\n CN 58 1 1\n EMCI 1 29 1\n LMCI 2 91 26\n SMC 4 0 0\n[++-][1] 330\n \n 0 1 2\n AD 0 0 113\n CN 59 3 0\n EMCI 1 28 1\n LMCI 2 96 22\n SMC 5 0 0\n[+-]"
],
[
"#Train ADAS/Ventricles Models\nD3regresionModelfilename = model.Train_Regression(D3AdjustedTrainFrame,D3Train_Imputed,usePreProc=USE_PREPROC)\n",
"2020-12-25 16:36:07,635 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Train ADAS13 and Ventricles Models\n [1] \"AGE\" \n [2] \"PTGENDER\" \n [3] \"CDRSB\" \n [4] \"ADAS11\" \n [5] \"ADAS13\" \n [6] \"MMSE\" \n [7] \"RAVLT_learning\" \n [8] \"RAVLT_immediate\" \n [9] \"FAQ\" \n [10] \"CDRSB_bl\" \n [11] \"ADAS11_bl\" \n [12] \"ADAS13_bl\" \n [13] \"MMSE_bl\" \n [14] \"RAVLT_learning_bl\" \n [15] \"RAVLT_immediate_bl\" \n [16] \"FAQ_bl\" \n [17] \"APOE4\" \n [18] \"Ventricles\" \n [19] \"WholeBrain\" \n [20] \"ICV\" \n [21] \"Ventricles_bl\" \n [22] \"Hippocampus_bl\" \n [23] \"WholeBrain_bl\" \n [24] \"Entorhinal_bl\" \n [25] \"Fusiform_bl\" \n [26] \"MidTemp_bl\" \n [27] \"ICV_bl\" \n [28] \"ST10CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [29] \"ST1SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [30] \"ST2SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [31] \"ST3SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [32] \"ST4SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [33] \"ST5SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [34] \"ST6SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [35] \"ST7SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [36] \"ST9SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [37] \"ST68SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [38] \"ST69SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [39] \"ST127SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [40] \"ST128SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [41] \"nICV\" \n [42] \"Mean_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [43] \"Mean_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [44] \"Mean_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [45] \"Mean_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [46] \"Mean_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [47] \"Mean_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [48] \"Mean_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [49] \"Mean_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [50] \"Mean_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [51] \"Mean_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [52] \"Mean_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [53] \"Mean_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [54] \"Mean_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [55] \"Mean_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [56] \"Mean_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [57] \"Mean_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [58] \"Mean_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [59] \"Mean_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [60] \"Mean_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [61] \"Mean_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [62] \"Mean_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [63] \"Mean_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [64] \"Mean_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [65] \"Mean_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [66] \"Mean_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [67] \"Mean_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [68] \"Mean_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [69] \"Mean_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [70] \"Mean_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [71] \"Mean_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [72] \"Mean_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [73] \"Mean_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [74] \"Mean_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [75] \"Mean_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [76] \"Mean_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [77] \"Mean_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [78] \"Mean_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [79] \"Mean_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [80] \"Mean_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [81] \"Mean_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [82] \"Mean_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [83] \"Mean_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [84] \"Mean_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [85] \"Mean_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [86] \"Mean_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [87] \"Mean_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [88] \"Mean_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [89] \"Mean_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n [90] \"Dif_ST72CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [91] \"Dif_ST73CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [92] \"Dif_ST74CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [93] \"Dif_ST82CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [94] \"Dif_ST83CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [95] \"Dif_ST84CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [96] \"Dif_ST85CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [97] \"Dif_ST90CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [98] \"Dif_ST91CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n [99] \"Dif_ST130CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[100] \"Dif_ST93CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[101] \"Dif_ST94CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[102] \"Dif_ST95CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[103] \"Dif_ST97CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[104] \"Dif_ST98CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[105] \"Dif_ST99CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[106] \"Dif_ST102CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[107] \"Dif_ST103CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[108] \"Dif_ST104CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[109] \"Dif_ST105CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[110] \"Dif_ST106CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[111] \"Dif_ST107CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[112] \"Dif_ST108CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[113] \"Dif_ST109CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[114] \"Dif_ST110CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[115] \"Dif_ST111CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[116] \"Dif_ST113CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[117] \"Dif_ST114CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[118] \"Dif_ST115CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[119] \"Dif_ST116CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[120] \"Dif_ST117CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[121] \"Dif_ST118CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[122] \"Dif_ST119CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[123] \"Dif_ST121CV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[124] \"Dif_ST70SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[125] \"Dif_ST71SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[126] \"Dif_ST75SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[127] \"Dif_ST76SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[128] \"Dif_ST77SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[129] \"Dif_ST80SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[130] \"Dif_ST88SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[131] \"Dif_ST89SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[132] \"Dif_ST96SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[133] \"Dif_ST101SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[134] \"Dif_ST112SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[135] \"Dif_ST120SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[136] \"Dif_ST124SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[137] \"Dif_ST125SV_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[138] \"Mean_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[139] \"Mean_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[140] \"Mean_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[141] \"Mean_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[142] \"Mean_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[143] \"Mean_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[144] \"Mean_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[145] \"Mean_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[146] \"Mean_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[147] \"Mean_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[148] \"Mean_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[149] \"Mean_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[150] \"Mean_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[151] \"Mean_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[152] \"Mean_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[153] \"Mean_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[154] \"Mean_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[155] \"Mean_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[156] \"Mean_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[157] \"Mean_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[158] \"Mean_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[159] \"Mean_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[160] \"Mean_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[161] \"Mean_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[162] \"Mean_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[163] \"Mean_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[164] \"Mean_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[165] \"Mean_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[166] \"Mean_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[167] \"Mean_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[168] \"Mean_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[169] \"Mean_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[170] \"Mean_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[171] \"Mean_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[172] \"Dif_ST72SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[173] \"Dif_ST73SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[174] \"Dif_ST74SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[175] \"Dif_ST82SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[176] \"Dif_ST83SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[177] \"Dif_ST84SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[178] \"Dif_ST85SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[179] \"Dif_ST90SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[180] \"Dif_ST91SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[181] \"Dif_ST130SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[182] \"Dif_ST93SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[183] \"Dif_ST94SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[184] \"Dif_ST95SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[185] \"Dif_ST97SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[186] \"Dif_ST98SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[187] \"Dif_ST99SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[188] \"Dif_ST102SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[189] \"Dif_ST103SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[190] \"Dif_ST104SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[191] \"Dif_ST105SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[192] \"Dif_ST106SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[193] \"Dif_ST107SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[194] \"Dif_ST108SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[195] \"Dif_ST109SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[196] \"Dif_ST110SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[197] \"Dif_ST111SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[198] \"Dif_ST113SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[199] \"Dif_ST114SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[200] \"Dif_ST115SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[201] \"Dif_ST116SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[202] \"Dif_ST117SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[203] \"Dif_ST118SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[204] \"Dif_ST119SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[205] \"Dif_ST121SA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[206] \"Mean_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[207] \"Mean_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[208] \"Mean_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[209] \"Mean_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[210] \"Mean_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[211] \"Mean_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[212] \"Mean_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[213] \"Mean_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[214] \"Mean_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[215] \"Mean_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[216] \"Mean_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[217] \"Mean_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[218] \"Mean_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[219] \"Mean_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[220] \"Mean_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[221] \"Mean_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[222] \"Mean_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[223] \"Mean_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[224] \"Mean_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[225] \"Mean_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[226] \"Mean_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[227] \"Mean_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[228] \"Mean_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[229] \"Mean_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[230] \"Mean_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[231] \"Mean_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[232] \"Mean_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[233] \"Mean_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[234] \"Mean_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[235] \"Mean_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[236] \"Mean_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[237] \"Mean_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[238] \"Mean_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[239] \"Mean_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[240] \"Mean_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[241] \"Mean_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[242] \"Mean_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[243] \"Mean_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[244] \"Mean_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[245] \"Mean_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[246] \"Mean_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[247] \"Mean_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[248] \"Mean_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[249] \"Mean_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[250] \"Mean_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[251] \"Mean_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[252] \"Mean_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[253] \"Mean_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[254] \"Mean_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[255] \"Mean_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[256] \"Mean_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[257] \"Mean_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[258] \"Mean_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[259] \"Mean_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[260] \"Mean_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[261] \"Mean_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[262] \"Mean_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[263] \"Mean_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[264] \"Mean_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[265] \"Mean_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[266] \"Mean_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[267] \"Mean_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[268] \"Mean_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[269] \"Mean_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[270] \"Mean_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[271] \"Mean_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[272] \"Mean_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[273] \"Mean_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\"\n[274] \"Dif_ST72TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[275] \"Dif_ST73TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[276] \"Dif_ST74TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[277] \"Dif_ST82TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[278] \"Dif_ST83TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[279] \"Dif_ST84TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[280] \"Dif_ST85TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[281] \"Dif_ST90TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[282] \"Dif_ST91TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[283] \"Dif_ST130TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[284] \"Dif_ST93TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[285] \"Dif_ST94TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[286] \"Dif_ST95TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[287] \"Dif_ST97TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[288] \"Dif_ST98TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[289] \"Dif_ST99TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[290] \"Dif_ST102TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[291] \"Dif_ST103TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[292] \"Dif_ST104TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[293] \"Dif_ST105TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[294] \"Dif_ST106TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[295] \"Dif_ST107TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[296] \"Dif_ST108TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[297] \"Dif_ST109TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[298] \"Dif_ST110TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[299] \"Dif_ST111TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[300] \"Dif_ST113TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[301] \"Dif_ST114TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[302] \"Dif_ST115TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[303] \"Dif_ST116TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[304] \"Dif_ST117TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[305] \"Dif_ST118TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[306] \"Dif_ST119TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[307] \"Dif_ST121TA_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[308] \"Dif_ST72TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[309] \"Dif_ST73TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[310] \"Dif_ST74TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[311] \"Dif_ST82TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[312] \"Dif_ST83TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[313] \"Dif_ST84TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[314] \"Dif_ST85TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[315] \"Dif_ST90TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[316] \"Dif_ST91TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[317] \"Dif_ST130TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[318] \"Dif_ST93TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[319] \"Dif_ST94TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[320] \"Dif_ST95TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[321] \"Dif_ST97TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[322] \"Dif_ST98TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[323] \"Dif_ST99TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[324] \"Dif_ST102TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[325] \"Dif_ST103TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[326] \"Dif_ST104TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[327] \"Dif_ST105TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[328] \"Dif_ST106TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[329] \"Dif_ST107TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[330] \"Dif_ST108TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[331] \"Dif_ST109TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[332] \"Dif_ST110TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[333] \"Dif_ST111TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[334] \"Dif_ST113TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[335] \"Dif_ST114TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[336] \"Dif_ST115TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[337] \"Dif_ST116TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[338] \"Dif_ST117TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[339] \"Dif_ST118TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[340] \"Dif_ST119TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[341] \"Dif_ST121TS_UCSFFSX_11_02_15_UCSFFSX51_08_01_16\" \n[342] \"MeanVolumes\" \n[343] \"StdVolumes\" \n[344] \"COVOlumens\" \n[345] \"MeanArea\" \n[346] \"StdArea\" \n[347] \"COArea\" \n[348] \"MeanThickness\" \n[349] \"StdThickness\" \n[350] \"COMeanThickness\" \n[1] 3401 370\n [1] 0 3 6 12 18 24 36 48 60 72 84 96\n\n bl m03 m06 m12 m18 m24 m36 m48 m60 m72 m84 m96 \n 23 21 70 141 31 264 129 53 16 31 3 3 \n[1] 785\n\n Dementia Dementia to MCI MCI MCI to Dementia MCI to NL \n 350 2 202 63 3 \n NL NL to Dementia NL to MCI \n 131 1 11 \n[1] \"FOR 1\"\n[1] 780\n[1] 166\n[1] 709\n[1] 649\n[1] 221\n[1] 475\n[1] 219\n[1] 92\n[1] 46\n[1] 35\n[1] 6\n[1] 3\n[1] 0\n[1] 1446 379\n[1] 525\n[1] 0\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.7254072\n[+-][1] 0.7740041\n\nDementia to MCI MCI NL to MCI \n 1 163 8 \n[1] 172\n[+-][1] 0.684284\n[+-][1] 0.8472892\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.816443\n[++-][1] 0.8652917\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[++-][1] 0.6725511\n[++-][1] 0.6592314\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.8415878\n[+-][1] 0.6897174\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.6607673\n[+-][1] 0.7304578\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.7192527\n[+-][1] 0.7327905\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.7790598\n[+-][1] 0.7360197\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.6863083\n[+-][1] 0.8165127\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.8029195\n[+-][1] 0.8534705\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.7866018\n[+-][1] 0.7574922\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.7808415\n[+-][1] 0.7773724\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+--][1] 0.5729364\n[+-][1] 0.6838503\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.6071765\n[+-][1] 0.6842546\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[++-][1] 0.7762479\n[+-][1] 0.8167948\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.7540461\n[+-][1] 0.7874617\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.7183801\n[++-][1] 0.6879908\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.6391238\n[+--][1] 0.6589574\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.7390757\n[+-][1] 0.7926508\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+--][1] 0.555634\n[+-][1] 0.7003327\n\nDementia to MCI MCI NL to MCI \n 1 163 8 \n[1] 172\n[++-][1] 0.6116829\n[++-][1] 0.705367\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.6659559\n[++-][1] 0.648334\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.7239071\n[+-][1] 0.7943048\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.5632597\n[+-][1] 0.7378513\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[++-][1] 0.7420982\n[+-][1] 0.8827338\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[++-][1] 0.8150615\n[++-][1] 0.7525601\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.5754409\n[+-][1] 0.7139357\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[++-][1] 0.6974244\n[+-][1] 0.7535934\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+++-][1] 0.7048701\n[+-][1] 0.8282903\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.702756\n[+-][1] 0.766783\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.6260368\n[+-][1] 0.7702782\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[++-][1] 0.5719594\n[+-][1] 0.6369104\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.7383394\n[++-][1] 0.7111544\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.6448784\n[+-][1] 0.7435425\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[++-][1] 0.6659522\n[+-][1] 0.7614593\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.7330518\n[+-][1] 0.7009093\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[++-][1] 0.8018124\n[+-][1] 0.8286416\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.6260289\n[+-][1] 0.7737629\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+++-][1] 0.6858213\n[+-][1] 0.664282\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[++-][1] 0.6385515\n[+++-][1] 0.6984942\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[++-][1] 0.7170738\n[+-][1] 0.7579083\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.766276\n[+-][1] 0.8258271\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.7059793\n[+-][1] 0.68233\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.7795817\n[+-][1] 0.7686715\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.7427936\n[+-][1] 0.7928205\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.6093567\n[+-][1] 0.7897222\n\nDementia to MCI MCI NL to MCI \n 1 166 5 \n[1] 172\n[+-][1] 0.6072137\n[+-][1] 0.8288072\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.7095982\n[+-][1] 0.7399425\n\nDementia to MCI MCI NL to MCI \n 1 165 6 \n[1] 172\n[+-][1] 0.7994088\n[+-][1] 0.8622353\n\nDementia to MCI MCI NL to MCI \n 1 164 7 \n[1] 172\n[+-][1] 0.6525168\n[+--][1] 0.7800293\n[1] 295\n[1] 0\n[1] 74\n[+-][1] 0.9427371\n[+++-][1] 0.8864567\n[1] 74\n[+++-][1] 0.8623228\n[+-][1] 0.7877115\n[1] 74\n[+-][1] 0.8216976\n[+-][1] 0.8900514\n[1] 74\n[+++-][1] 0.8685512\n[+-][1] 0.8838866\n[1] 74\n[+-][1] 0.5470929\n[++++-][1] 0.8566988\n[1] 74\n[+-+-][1] 0.8399483\n[+-][1] 0.8347973\n[1] 74\n[+-][1] 0.768678\n[++-][1] 0.8940185\n[1] 74\n[+++++][1] 0.8782517\n[+-+--][1] 0.7404262\n[1] 74\n[++++--][1] 0.6124469\n[++++--][1] 0.7620664\n[1] 74\n[+-][1] 0.7301997\n[+-][1] 0.7636545\n[1] 74\n[+-][1] 0.6318129\n[+-][1] 0.8705401\n[1] 74\n[++-][1] 0.816129\n[++-][1] 0.6295442\n[1] 74\n[+-][1] 0.8082798\n[+-][1] 0.4747132\n[1] 74\n[+-][1] 0.706288\n[+++-][1] 0.6416253\n[1] 74\n[+-][1] 0.8314023\n[++-][1] 0.848739\n[1] 74\n[+-][1] 0.5715101\n[+-][1] 0.8928283\n[1] 74\n[++++++-][1] 0.4515934\n[+-][1] 0.8537422\n[1] 74\n[++-][1] 0.8842837\n[+++-][1] 0.79368\n[1] 74\n[+-][1] 0.8403115\n[++-][1] 0.8233741\n[1] 74\n[+-][1] 0.9398637\n[+-][1] 0.8869371\n[1] 74\n[+-][1] 0.881836\n[++-][1] 0.9697768\n[1] 74\n[+-][1] 0.85134\n[+++-][1] 0.889534\n[1] 74\n[++-][1] 0.9466641\n[+-][1] 0.892647\n[1] 74\n[+-][1] 0.8668257\n[+-][1] 0.9209254\n[1] 74\n[+-][1] 0.8758872\n[++-][1] 0.8072981\n[1] 74\n[++--][1] 0.680155\n[+-][1] 0.8539727\n[1] 74\n[++-][1] 0.9506732\n[+-][1] 0.9496871\n[1] 74\n[+--][1] 0.7485264\n[+++-][1] 0.8613719\n[1] 74\n[+-][1] 0.8553091\n[+-][1] 0.9191092\n[1] 74\n[+++-][1] 0.8680167\n[+-][1] 0.9758886\n[1] 74\n[++-][1] 0.5752781\n[+-][1] 0.9083107\n[1] 74\n[++-][1] 0.6880617\n[++-][1] 0.9552005\n[1] 74\n[+-][1] 0.9086332\n[+-][1] 0.9709481\n[1] 74\n[+-][1] 0.7555516\n[++++-][1] 0.861786\n[1] 74\n[+-][1] 0.781517\n[+-][1] 0.8897634\n[1] 74\n[+][1] 0.5539135\n[+-][1] 0.7890462\n[1] 74\n[++-][1] 0.8172984\n[+-][1] 0.8018426\n[1] 74\n[+-][1] 0.9385834\n[+++][1] 0.9231901\n[1] 74\n[+-][1] 0.875053\n[+-][1] 0.9248131\n[1] 74\n[++-][1] 0.8391315\n[++-][1] 0.9562925\n[1] 74\n[++-][1] 0.9147276\n[+-][1] 0.7351092\n[1] 74\n[+-][1] 0.7176959\n[+++-][1] 0.8227837\n[1] 74\n[++][1] 0.6053086\n[+-][1] 0.8758461\n[1] 74\n[+++-][1] 0.8754816\n[+-][1] 0.9644587\n[1] 74\n[+-][1] 0.8220633\n[+-][1] 0.8681759\n[1] 74\n[+--][1] 0.7307584\n[++-][1] 0.394346\n[1] 74\n[+-][1] 0.7547411\n[++-][1] 0.9010791\n[1] 74\n[+-][1] 0.7479701\n[+-][1] 0.7445538\n[1] 74\n[+++-][1] 0.9024612\n[+-][1] 0.9669155\n[1] 74\n[+-][1] 0.7281783\n[+++-++-][1] 0.9625854\n[1] 538\n[1] 0\n[1] 186\n[++-][1] 0.597993\n[+-][1] 0.7205208\n[1] 186\n[+-][1] 0.5497251\n[+-][1] 0.6950895\n[1] 186\n[+++-][1] 0.631803\n[+-][1] 0.7848884\n[1] 186\n[+-][1] 0.5448165\n[+-][1] 0.7219598\n[1] 186\n[+-][1] 0.5112021\n[+-][1] 0.7034169\n[1] 186\n[+-][1] 0.541783\n[++-][1] 0.6518802\n[1] 186\n[+-][1] 0.6240437\n[+-][1] 0.6779415\n[1] 186\n[+-][1] 0.7182147\n[+-][1] 0.6923413\n[1] 186\n[+-][1] 0.7434335\n[+-][1] 0.7644456\n[1] 186\n[+-][1] 0.6740708\n[+-][1] 0.7615663\n[1] 186\n[+++-][1] 0.6786259\n[+-][1] 0.7076507\n[1] 186\n[+-][1] 0.5005567\n[++-][1] 0.7210418\n[1] 186\n[+-][1] 0.5328153\n[+-][1] 0.8422949\n[1] 186\n[+-][1] 0.5574448\n[++--][1] 0.7250308\n[1] 186\n[+-][1] 0.6700453\n[+-][1] 0.7131594\n[1] 186\n[+-][1] 0.5325025\n[++-][1] 0.5783141\n[1] 186\n[++-][1] 0.642186\n[++-][1] 0.7088961\n[1] 186\n[+-][1] 0.6413583\n[+-][1] 0.6670824\n[1] 186\n[++-][1] 0.559047\n[++-][1] 0.7844101\n[1] 186\n[++-][1] 0.6295081\n[+-][1] 0.7364968\n[1] 186\n[+-][1] 0.7398865\n[+-][1] 0.6149805\n[1] 186\n[+-][1] 0.7121652\n[+-][1] 0.7429647\n[1] 186\n[+++-][1] 0.5390814\n[++-][1] 0.7377159\n[1] 186\n[+-][1] 0.7607081\n[+-][1] 0.7830476\n[1] 186\n[+++-][1] 0.7110764\n[++-][1] 0.7042469\n[1] 186\n[+-][1] 0.7187318\n[+++-][1] 0.5770044\n[1] 186\n[+++-][1] 0.7868109\n[++-][1] 0.742766\n[1] 186\n[+-][1] 0.5611466\n[+-][1] 0.7024513\n[1] 186\n[+-][1] 0.615613\n[++-][1] 0.6588679\n[1] 186\n[+-][1] 0.667334\n[++-][1] 0.7531148\n[1] 186\n[+-][1] 0.6679729\n[+-][1] 0.8730569\n[1] 186\n[+-][1] 0.535832\n[++-][1] 0.6703071\n[1] 186\n[+-][1] 0.5359346\n[++-][1] 0.6250998\n[1] 186\n[++-][1] 0.5554252\n[+-][1] 0.7569628\n[1] 186\n[++-][1] 0.5906455\n[+-][1] 0.7990742\n[1] 186\n[++--][1] 0.6330309\n[+-][1] 0.7495359\n[1] 186\n[++-][1] 0.6332639\n[+-][1] 0.6102876\n[1] 186\n[+-][1] 0.6028507\n[+--][1] 0.650304\n[1] 186\n[++-][1] 0.5530454\n[+-][1] 0.7367269\n[1] 186\n[+++-][1] 0.6527884\n[+-][1] 0.8020405\n[1] 186\n[++--][1] 0.6930596\n[+-][1] 0.8215065\n[1] 186\n[++-][1] 0.6876849\n[+-][1] 0.5669657\n[1] 186\n[+-][1] 0.7606654\n[+-][1] 0.7857169\n[1] 186\n[++-][1] 0.6765068\n[+-][1] 0.7610603\n[1] 186\n[+-][1] 0.6987504\n[+-][1] 0.724183\n[1] 186\n[+-][1] 0.7283737\n[+-][1] 0.7290029\n[1] 186\n[+-][1] 0.4808685\n[+-][1] 0.6731704\n[1] 186\n[+-][1] 0.6284845\n[+-][1] 0.8329279\n[1] 186\n[+++-][1] 0.5116435\n[+-][1] 0.736395\n[1] 186\n[++-][1] 0.7198006\n[+-][1] 0.7575731\n"
],
[
"#Predict \nForecast_D3 = model.Forecast_All(D3modelfilename,\n D3regresionModelfilename,\n D3testingFrame,\n D3Test_Imputed,\n submissionTemplateFileName=\"data/TADPOLE_Simple_Submission_TeamName.xlsx\",\n usePreProc=USE_PREPROC)",
"2020-12-25 17:11:27,199 - MainThread - tadpole_algorithms.models.benchmark_FRESACAD_R - INFO - Forecast Congitive Status, ADAS13 and Ventricles\n2020-12-25 17:11:28,707 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n2020-12-25 17:11:28,708 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: -\n2020-12-25 17:11:28,847 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \n2020-12-25 17:11:28,848 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \\\n - R[write to console]: \n2020-12-25 17:11:28,848 - MainThread - rpy2.rinterface_lib.callbacks - WARNING - R[write to console]: \nnumeric(0)\n[1] 896\n[1] 896\n[1] 896\n[1] 896\n[1] 896\n[1] 10521\n[1] 896\n[1] 10104\n[1] 192\nstatusLO\n 1 2 3 \n299 269 136 \n[1] 0.9083706 0.8237333 0.9530631\n[1] 0.8490431 0.2647059 0.1200929\n[1] 0.8167413 0.6474667 0.9061261\n [1] 25.91857 15.91885 15.49022 17.60166 20.93196 24.86620 16.50024 21.10952\n [9] 21.66178 18.53301 32.48228 32.43584 22.91725 24.28200 17.99913 24.53007\n[17] 26.05407 20.46631 21.56001 28.95034 17.29605 22.20299 25.28400 19.19062\n[25] 21.92299 19.83896 19.15475 18.20468 19.65691 26.73694 23.09497 18.62733\n[33] 27.59333 23.70387 19.13439 25.42909 23.84380 20.55026 21.46640 22.50424\n[41] 22.72242 17.26193 24.99871 24.89041 22.32071 19.08006 17.07279 23.33548\n[49] 18.99002 16.21040\n [1] 0.02912703 0.02918922 0.02832816 0.02856555 0.02623074 0.02835011\n [7] 0.02652424 0.03008932 0.02880934 0.02804958 0.02858816 0.02930045\n[13] 0.02947522 0.02849511 0.02823556 0.02975861 0.02735616 0.02850511\n[19] 0.02780900 0.02756039 0.02659129 0.02803533 0.03056249 0.02769025\n[25] 0.02726773 0.02498826 0.02745080 0.02693619 0.02723113 0.02818365\n[31] 0.02546998 0.02769604 0.02829610 0.02954666 0.02926472 0.02814399\n[37] 0.02885816 0.02739863 0.02901366 0.02762364 0.02952245 0.02994856\n[43] 0.02803682 0.02836706 0.02640694 0.02813299 0.02783775 0.02865664\n[49] 0.02832685 0.02573361\n[1] \"2018-02-01\"\n[1] \"2018-03-01\"\n[1] \"2018-04-01\"\n[1] \"2018-05-01\"\n[1] \"2018-06-01\"\n[1] \"2018-07-01\"\n[1] \"2018-08-01\"\n[1] \"2018-09-01\"\n[1] \"2018-10-01\"\n[1] \"2018-11-01\"\n[1] \"2018-12-01\"\n[1] \"2019-01-01\"\n[1] \"2019-02-01\"\n[1] \"2019-03-01\"\n[1] \"2019-04-01\"\n[1] \"2019-05-01\"\n[1] \"2019-06-01\"\n[1] \"2019-07-01\"\n[1] \"2019-08-01\"\n[1] \"2019-09-01\"\n[1] \"2019-10-01\"\n[1] \"2019-11-01\"\n[1] \"2019-12-01\"\n[1] \"2020-01-01\"\n[1] \"2020-02-01\"\n[1] \"2020-03-01\"\n[1] \"2020-04-01\"\n[1] \"2020-05-01\"\n[1] \"2020-06-01\"\n[1] \"2020-07-01\"\n[1] \"2020-08-01\"\n[1] \"2020-09-01\"\n[1] \"2020-10-01\"\n[1] \"2020-11-01\"\n[1] \"2020-12-01\"\n[1] \"2021-01-01\"\n[1] \"2021-02-01\"\n[1] \"2021-03-01\"\n[1] \"2021-04-01\"\n[1] \"2021-05-01\"\n[1] \"2021-06-01\"\n[1] \"2021-07-01\"\n[1] \"2021-08-01\"\n[1] \"2021-09-01\"\n[1] \"2021-10-01\"\n[1] \"2021-11-01\"\n[1] \"2021-12-01\"\n[1] \"2022-01-01\"\n[1] \"2022-02-01\"\n[1] \"2022-03-01\"\n[1] \"2022-04-01\"\n[1] \"2022-05-01\"\n[1] \"2022-06-01\"\n[1] \"2022-07-01\"\n[1] \"2022-08-01\"\n[1] \"2022-09-01\"\n[1] \"2022-10-01\"\n[1] \"2022-11-01\"\n[1] \"2022-12-01\"\ndata/_ForecastFRESACAD.csv\n<class 'str'>\n"
],
[
"from tadpole_algorithms.evaluation import evaluate_forecast\nfrom tadpole_algorithms.evaluation import print_metrics\n# Evaluate the D3 model \ndictionary = evaluate_forecast(eval_df,Forecast_D3)\n\n# Print metrics\nprint_metrics(dictionary)",
"[[74 11 1]\n [20 62 10]\n [ 2 11 19]]\nmAUC (multiclass Area Under Curve): 0.858\nbca (balanced classification accuracy): 0.784\nadasMAE (ADAS13 Mean Absolute Error): 5.631\nventsMAE (Ventricles Mean Absolute Error), in % ICV: 1.110\nadasWES (ADAS13 Weighted Error Score): 5.659\nventsWES (Ventricles Weighted Error Score ), in % ICV: 1.111\nadasCPA (ADAS13 Coverage Probability Accuracy for 50% Confidence Interval: 0.162\nventsCPA (Ventricles Coverage Probability Accuracy for 50% Confidence Interval: 0.393\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a93caaace0c2b1e0950a0ca4d868c36ce46f8a4
| 244,962 |
ipynb
|
Jupyter Notebook
|
deeplearning2/rossman.ipynb
|
anhquan0412/deeplearning_fastai
|
ac9b52900ebd91a6c3f64a6b04227ccedee96837
|
[
"Apache-2.0"
] | 125 |
2017-09-20T14:01:40.000Z
|
2020-09-22T12:11:58.000Z
|
deeplearning2/rossman.ipynb
|
anhquan0412/deeplearning_fastai
|
ac9b52900ebd91a6c3f64a6b04227ccedee96837
|
[
"Apache-2.0"
] | 11 |
2017-09-26T05:38:59.000Z
|
2019-12-28T08:34:34.000Z
|
deeplearning2/rossman.ipynb
|
anhquan0412/deeplearning_fastai
|
ac9b52900ebd91a6c3f64a6b04227ccedee96837
|
[
"Apache-2.0"
] | 54 |
2017-09-25T13:19:23.000Z
|
2021-03-25T12:55:20.000Z
| 40.349531 | 44,442 | 0.559858 |
[
[
[
"This notebook contains an implementation of the third place result in the Rossman Kaggle competition as detailed in Guo/Berkhahn's [Entity Embeddings of Categorical Variables](https://arxiv.org/abs/1604.06737).",
"_____no_output_____"
],
[
"The motivation behind exploring this architecture is it's relevance to real-world application. Much of our focus has been computer-vision and NLP tasks, which largely deals with unstructured data.\n\nHowever, most of the data informing KPI's in industry are structured, time-series data. Here we explore the end-to-end process of using neural networks with practical structured data problems.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import math, keras, datetime, pandas as pd, numpy as np, keras.backend as K\nimport matplotlib.pyplot as plt, xgboost, operator, random, pickle",
"Using TensorFlow backend.\n/home/roebius/pj/p3/lib/python3.5/site-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n \"This module will be removed in 0.20.\", DeprecationWarning)\n"
],
[
"from utils2 import *",
"_____no_output_____"
],
[
"np.set_printoptions(threshold=50, edgeitems=20)",
"_____no_output_____"
],
[
"limit_mem()",
"_____no_output_____"
],
[
"from isoweek import Week\nfrom pandas_summary import DataFrameSummary",
"_____no_output_____"
],
[
"%cd data/rossman/",
"/home/roebius/pj/fastai/nbs2/data/rossman\n"
]
],
[
[
"## Create datasets",
"_____no_output_____"
],
[
"In addition to the provided data, we will be using external datasets put together by participants in the Kaggle competition. You can download all of them [here](http://files.fast.ai/part2/lesson14/rossmann.tgz).\n\nFor completeness, the implementation used to put them together is included below.",
"_____no_output_____"
]
],
[
[
"def concat_csvs(dirname):\n os.chdir(dirname)\n filenames=glob.glob(\"*.csv\")\n\n wrote_header = False\n with open(\"../\"+dirname+\".csv\",\"w\") as outputfile:\n for filename in filenames:\n name = filename.split(\".\")[0]\n with open(filename) as f:\n line = f.readline()\n if not wrote_header:\n wrote_header = True\n outputfile.write(\"file,\"+line)\n for line in f:\n outputfile.write(name + \",\" + line)\n outputfile.write(\"\\n\")\n\n os.chdir(\"..\")",
"_____no_output_____"
],
[
"# concat_csvs('googletrend')\n# concat_csvs('weather')",
"_____no_output_____"
]
],
[
[
"Feature Space:\n* train: Training set provided by competition\n* store: List of stores\n* store_states: mapping of store to the German state they are in\n* List of German state names\n* googletrend: trend of certain google keywords over time, found by users to correlate well w/ given data\n* weather: weather\n* test: testing set",
"_____no_output_____"
]
],
[
[
"table_names = ['train', 'store', 'store_states', 'state_names', \n 'googletrend', 'weather', 'test']",
"_____no_output_____"
]
],
[
[
"We'll be using the popular data manipulation framework pandas.\n\nAmong other things, pandas allows you to manipulate tables/data frames in python as one would in a database.",
"_____no_output_____"
],
[
"We're going to go ahead and load all of our csv's as dataframes into a list `tables`.",
"_____no_output_____"
]
],
[
[
"tables = [pd.read_csv(fname+'.csv', low_memory=False) for fname in table_names]",
"_____no_output_____"
],
[
"from IPython.display import HTML",
"_____no_output_____"
]
],
[
[
"We can use `head()` to get a quick look at the contents of each table:\n* train: Contains store information on a daily basis, tracks things like sales, customers, whether that day was a holdiay, etc.\n* store: general info about the store including competition, etc.\n* store_states: maps store to state it is in\n* state_names: Maps state abbreviations to names\n* googletrend: trend data for particular week/state\n* weather: weather conditions for each state\n* test: Same as training table, w/o sales and customers\n",
"_____no_output_____"
]
],
[
[
"for t in tables: display(t.head())",
"_____no_output_____"
]
],
[
[
"This is very representative of a typical industry dataset.",
"_____no_output_____"
],
[
"The following returns summarized aggregate information to each table accross each field.",
"_____no_output_____"
]
],
[
[
"for t in tables: display(DataFrameSummary(t).summary())",
"_____no_output_____"
]
],
[
[
"## Data Cleaning / Feature Engineering",
"_____no_output_____"
],
[
"As a structured data problem, we necessarily have to go through all the cleaning and feature engineering, even though we're using a neural network.",
"_____no_output_____"
]
],
[
[
"train, store, store_states, state_names, googletrend, weather, test = tables",
"_____no_output_____"
],
[
"len(train),len(test)",
"_____no_output_____"
]
],
[
[
"Turn state Holidays to Bool",
"_____no_output_____"
]
],
[
[
"train.StateHoliday = train.StateHoliday!='0'\ntest.StateHoliday = test.StateHoliday!='0'",
"_____no_output_____"
]
],
[
[
"Define function for joining tables on specific fields.\n\nBy default, we'll be doing a left outer join of `right` on the `left` argument using the given fields for each table.\n\nPandas does joins using the `merge` method. The `suffixes` argument describes the naming convention for duplicate fields. We've elected to leave the duplicate field names on the left untouched, and append a \"_y\" to those on the right.",
"_____no_output_____"
]
],
[
[
"def join_df(left, right, left_on, right_on=None):\n if right_on is None: right_on = left_on\n return left.merge(right, how='left', left_on=left_on, right_on=right_on, \n suffixes=(\"\", \"_y\"))",
"_____no_output_____"
]
],
[
[
"Join weather/state names.",
"_____no_output_____"
]
],
[
[
"weather = join_df(weather, state_names, \"file\", \"StateName\")",
"_____no_output_____"
]
],
[
[
"In pandas you can add new columns to a dataframe by simply defining it. We'll do this for googletrends by extracting dates and state names from the given data and adding those columns.\n\nWe're also going to replace all instances of state name 'NI' with the usage in the rest of the table, 'HB,NI'. This is a good opportunity to highlight pandas indexing. We can use `.ix[rows, cols]` to select a list of rows and a list of columns from the dataframe. In this case, we're selecting rows w/ statename 'NI' by using a boolean list `googletrend.State=='NI'` and selecting \"State\".",
"_____no_output_____"
]
],
[
[
"googletrend['Date'] = googletrend.week.str.split(' - ', expand=True)[0]\ngoogletrend['State'] = googletrend.file.str.split('_', expand=True)[2]\ngoogletrend.loc[googletrend.State=='NI', \"State\"] = 'HB,NI'",
"_____no_output_____"
]
],
[
[
"The following extracts particular date fields from a complete datetime for the purpose of constructing categoricals.\n\nYou should always consider this feature extraction step when working with date-time. Without expanding your date-time into these additional fields, you can't capture any trend/cyclical behavior as a function of time at any of these granularities.",
"_____no_output_____"
]
],
[
[
"def add_datepart(df):\n df.Date = pd.to_datetime(df.Date)\n df[\"Year\"] = df.Date.dt.year\n df[\"Month\"] = df.Date.dt.month\n df[\"Week\"] = df.Date.dt.week\n df[\"Day\"] = df.Date.dt.day",
"_____no_output_____"
]
],
[
[
"We'll add to every table w/ a date field.",
"_____no_output_____"
]
],
[
[
"add_datepart(weather)\nadd_datepart(googletrend)\nadd_datepart(train)\nadd_datepart(test)",
"_____no_output_____"
],
[
"trend_de = googletrend[googletrend.file == 'Rossmann_DE']",
"_____no_output_____"
]
],
[
[
"Now we can outer join all of our data into a single dataframe.\n\nRecall that in outer joins everytime a value in the joining field on the left table does not have a corresponding value on the right table, the corresponding row in the new table has Null values for all right table fields.\n\nOne way to check that all records are consistent and complete is to check for Null values post-join, as we do here.\n\n*Aside*: Why note just do an inner join?\nIf you are assuming that all records are complete and match on the field you desire, an inner join will do the same thing as an outer join. However, in the event you are wrong or a mistake is made, an outer join followed by a null-check will catch it. (Comparing before/after # of rows for inner join is equivalent, but requires keeping track of before/after row #'s. Outer join is easier.)",
"_____no_output_____"
]
],
[
[
"store = join_df(store, store_states, \"Store\")\nlen(store[store.State.isnull()])",
"_____no_output_____"
],
[
"joined = join_df(train, store, \"Store\")\nlen(joined[joined.StoreType.isnull()])",
"_____no_output_____"
],
[
"joined = join_df(joined, googletrend, [\"State\",\"Year\", \"Week\"])\nlen(joined[joined.trend.isnull()])",
"_____no_output_____"
],
[
"joined = joined.merge(trend_de, 'left', [\"Year\", \"Week\"], suffixes=('', '_DE'))\nlen(joined[joined.trend_DE.isnull()])",
"_____no_output_____"
],
[
"joined = join_df(joined, weather, [\"State\",\"Date\"])\nlen(joined[joined.Mean_TemperatureC.isnull()])",
"_____no_output_____"
],
[
"joined_test = test.merge(store, how='left', left_on='Store', right_index=True)\nlen(joined_test[joined_test.StoreType.isnull()])",
"_____no_output_____"
]
],
[
[
"Next we'll fill in missing values to avoid complications w/ na's.",
"_____no_output_____"
]
],
[
[
"joined.CompetitionOpenSinceYear = joined.CompetitionOpenSinceYear.fillna(1900).astype(np.int32)\njoined.CompetitionOpenSinceMonth = joined.CompetitionOpenSinceMonth.fillna(1).astype(np.int32)\njoined.Promo2SinceYear = joined.Promo2SinceYear.fillna(1900).astype(np.int32)\njoined.Promo2SinceWeek = joined.Promo2SinceWeek.fillna(1).astype(np.int32)",
"_____no_output_____"
]
],
[
[
"Next we'll extract features \"CompetitionOpenSince\" and \"CompetitionDaysOpen\". Note the use of `apply()` in mapping a function across dataframe values.",
"_____no_output_____"
]
],
[
[
"joined[\"CompetitionOpenSince\"] = pd.to_datetime(joined.apply(lambda x: datetime.datetime(\n x.CompetitionOpenSinceYear, x.CompetitionOpenSinceMonth, 15), axis=1).astype(pd.datetime))\njoined[\"CompetitionDaysOpen\"] = joined.Date.subtract(joined[\"CompetitionOpenSince\"]).dt.days",
"_____no_output_____"
]
],
[
[
"We'll replace some erroneous / outlying data.",
"_____no_output_____"
]
],
[
[
"joined.loc[joined.CompetitionDaysOpen<0, \"CompetitionDaysOpen\"] = 0\njoined.loc[joined.CompetitionOpenSinceYear<1990, \"CompetitionDaysOpen\"] = 0",
"_____no_output_____"
]
],
[
[
"Added \"CompetitionMonthsOpen\" field, limit the maximum to 2 years to limit number of unique embeddings.",
"_____no_output_____"
]
],
[
[
"joined[\"CompetitionMonthsOpen\"] = joined[\"CompetitionDaysOpen\"]//30\njoined.loc[joined.CompetitionMonthsOpen>24, \"CompetitionMonthsOpen\"] = 24\njoined.CompetitionMonthsOpen.unique()",
"_____no_output_____"
]
],
[
[
"Same process for Promo dates.",
"_____no_output_____"
]
],
[
[
"joined[\"Promo2Since\"] = pd.to_datetime(joined.apply(lambda x: Week(\n x.Promo2SinceYear, x.Promo2SinceWeek).monday(), axis=1).astype(pd.datetime))\njoined[\"Promo2Days\"] = joined.Date.subtract(joined[\"Promo2Since\"]).dt.days",
"_____no_output_____"
],
[
"joined.loc[joined.Promo2Days<0, \"Promo2Days\"] = 0\njoined.loc[joined.Promo2SinceYear<1990, \"Promo2Days\"] = 0",
"_____no_output_____"
],
[
"joined[\"Promo2Weeks\"] = joined[\"Promo2Days\"]//7\njoined.loc[joined.Promo2Weeks<0, \"Promo2Weeks\"] = 0\njoined.loc[joined.Promo2Weeks>25, \"Promo2Weeks\"] = 25\njoined.Promo2Weeks.unique()",
"_____no_output_____"
]
],
[
[
"## Durations",
"_____no_output_____"
],
[
"It is common when working with time series data to extract data that explains relationships across rows as opposed to columns, e.g.:\n* Running averages\n* Time until next event\n* Time since last event\n\nThis is often difficult to do with most table manipulation frameworks, since they are designed to work with relationships across columns. As such, we've created a class to handle this type of data.",
"_____no_output_____"
]
],
[
[
"columns = [\"Date\", \"Store\", \"Promo\", \"StateHoliday\", \"SchoolHoliday\"]",
"_____no_output_____"
]
],
[
[
"We've defined a class `elapsed` for cumulative counting across a sorted dataframe.\n\nGiven a particular field `fld` to monitor, this object will start tracking time since the last occurrence of that field. When the field is seen again, the counter is set to zero.\n\nUpon initialization, this will result in datetime na's until the field is encountered. This is reset every time a new store is seen.\n\nWe'll see how to use this shortly.",
"_____no_output_____"
]
],
[
[
"class elapsed(object):\n def __init__(self, fld):\n self.fld = fld\n self.last = pd.to_datetime(np.nan)\n self.last_store = 0\n \n def get(self, row):\n if row.Store != self.last_store:\n self.last = pd.to_datetime(np.nan)\n self.last_store = row.Store\n if (row[self.fld]): self.last = row.Date\n return row.Date-self.last",
"_____no_output_____"
],
[
"df = train[columns]",
"_____no_output_____"
]
],
[
[
"And a function for applying said class across dataframe rows and adding values to a new column.",
"_____no_output_____"
]
],
[
[
"def add_elapsed(fld, prefix):\n sh_el = elapsed(fld)\n df[prefix+fld] = df.apply(sh_el.get, axis=1)",
"_____no_output_____"
]
],
[
[
"Let's walk through an example.\n\nSay we're looking at School Holiday. We'll first sort by Store, then Date, and then call `add_elapsed('SchoolHoliday', 'After')`:\nThis will generate an instance of the `elapsed` class for School Holiday:\n* Instance applied to every row of the dataframe in order of store and date\n* Will add to the dataframe the days since seeing a School Holiday\n* If we sort in the other direction, this will count the days until another promotion.",
"_____no_output_____"
]
],
[
[
"fld = 'SchoolHoliday'\ndf = df.sort_values(['Store', 'Date'])\nadd_elapsed(fld, 'After')\ndf = df.sort_values(['Store', 'Date'], ascending=[True, False])\nadd_elapsed(fld, 'Before')",
"_____no_output_____"
]
],
[
[
"We'll do this for two more fields.",
"_____no_output_____"
]
],
[
[
"fld = 'StateHoliday'\ndf = df.sort_values(['Store', 'Date'])\nadd_elapsed(fld, 'After')\ndf = df.sort_values(['Store', 'Date'], ascending=[True, False])\nadd_elapsed(fld, 'Before')",
"_____no_output_____"
],
[
"fld = 'Promo'\ndf = df.sort_values(['Store', 'Date'])\nadd_elapsed(fld, 'After')\ndf = df.sort_values(['Store', 'Date'], ascending=[True, False])\nadd_elapsed(fld, 'Before')",
"_____no_output_____"
],
[
"display(df.head())",
"_____no_output_____"
]
],
[
[
"We're going to set the active index to Date.",
"_____no_output_____"
]
],
[
[
"df = df.set_index(\"Date\")",
"_____no_output_____"
]
],
[
[
"Then set null values from elapsed field calculations to 0.",
"_____no_output_____"
]
],
[
[
"columns = ['SchoolHoliday', 'StateHoliday', 'Promo']",
"_____no_output_____"
],
[
"for o in ['Before', 'After']:\n for p in columns:\n a = o+p\n df[a] = df[a].fillna(pd.Timedelta(0)).dt.days",
"_____no_output_____"
]
],
[
[
"Next we'll demonstrate window functions in pandas to calculate rolling quantities.\n\nHere we're sorting by date (`sort_index()`) and counting the number of events of interest (`sum()`) defined in `columns` in the following week (`rolling()`), grouped by Store (`groupby()`). We do the same in the opposite direction.",
"_____no_output_____"
]
],
[
[
"bwd = df[['Store']+columns].sort_index().groupby(\"Store\").rolling(7, min_periods=1).sum()",
"_____no_output_____"
],
[
"fwd = df[['Store']+columns].sort_index(ascending=False\n ).groupby(\"Store\").rolling(7, min_periods=1).sum()",
"_____no_output_____"
]
],
[
[
"Next we want to drop the Store indices grouped together in the window function.\n\nOften in pandas, there is an option to do this in place. This is time and memory efficient when working with large datasets.",
"_____no_output_____"
]
],
[
[
"bwd.drop('Store',1,inplace=True)\nbwd.reset_index(inplace=True)",
"_____no_output_____"
],
[
"fwd.drop('Store',1,inplace=True)\nfwd.reset_index(inplace=True)",
"_____no_output_____"
],
[
"df.reset_index(inplace=True)",
"_____no_output_____"
]
],
[
[
"Now we'll merge these values onto the df.",
"_____no_output_____"
]
],
[
[
"df = df.merge(bwd, 'left', ['Date', 'Store'], suffixes=['', '_bw'])\ndf = df.merge(fwd, 'left', ['Date', 'Store'], suffixes=['', '_fw'])",
"_____no_output_____"
],
[
"df.drop(columns,1,inplace=True)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"It's usually a good idea to back up large tables of extracted / wrangled features before you join them onto another one, that way you can go back to it easily if you need to make changes to it.",
"_____no_output_____"
]
],
[
[
"df.to_csv('df.csv')",
"_____no_output_____"
],
[
"df = pd.read_csv('df.csv', index_col=0)",
"_____no_output_____"
],
[
"df[\"Date\"] = pd.to_datetime(df.Date)",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"joined = join_df(joined, df, ['Store', 'Date'])",
"_____no_output_____"
]
],
[
[
"We'll back this up as well.",
"_____no_output_____"
]
],
[
[
"joined.to_csv('joined.csv')",
"_____no_output_____"
]
],
[
[
"We now have our final set of engineered features.",
"_____no_output_____"
]
],
[
[
"joined = pd.read_csv('joined.csv', index_col=0)\njoined[\"Date\"] = pd.to_datetime(joined.Date)\njoined.columns",
"_____no_output_____"
]
],
[
[
"While these steps were explicitly outlined in the paper, these are all fairly typical feature engineering steps for dealing with time series data and are practical in any similar setting.",
"_____no_output_____"
],
[
"## Create features",
"_____no_output_____"
],
[
"Now that we've engineered all our features, we need to convert to input compatible with a neural network.\n\nThis includes converting categorical variables into contiguous integers or one-hot encodings, normalizing continuous features to standard normal, etc...",
"_____no_output_____"
]
],
[
[
"from sklearn_pandas import DataFrameMapper\nfrom sklearn.preprocessing import LabelEncoder, Imputer, StandardScaler",
"_____no_output_____"
]
],
[
[
"This dictionary maps categories to embedding dimensionality. In generally, categories we might expect to be conceptually more complex have larger dimension.",
"_____no_output_____"
]
],
[
[
"cat_var_dict = {'Store': 50, 'DayOfWeek': 6, 'Year': 2, 'Month': 6,\n'Day': 10, 'StateHoliday': 3, 'CompetitionMonthsOpen': 2,\n'Promo2Weeks': 1, 'StoreType': 2, 'Assortment': 3, 'PromoInterval': 3,\n'CompetitionOpenSinceYear': 4, 'Promo2SinceYear': 4, 'State': 6,\n'Week': 2, 'Events': 4, 'Promo_fw': 1,\n'Promo_bw': 1, 'StateHoliday_fw': 1,\n'StateHoliday_bw': 1, 'SchoolHoliday_fw': 1,\n'SchoolHoliday_bw': 1}",
"_____no_output_____"
]
],
[
[
"Name categorical variables",
"_____no_output_____"
]
],
[
[
"cat_vars = [o[0] for o in \n sorted(cat_var_dict.items(), key=operator.itemgetter(1), reverse=True)]",
"_____no_output_____"
],
[
"\"\"\"cat_vars = ['Store', 'DayOfWeek', 'Year', 'Month', 'Day', 'StateHoliday',\n 'StoreType', 'Assortment', 'Week', 'Events', 'Promo2SinceYear',\n 'CompetitionOpenSinceYear', 'PromoInterval', 'Promo', 'SchoolHoliday', 'State']\"\"\"",
"_____no_output_____"
]
],
[
[
"Likewise for continuous",
"_____no_output_____"
]
],
[
[
"# mean/max wind; min temp; cloud; min/mean humid; \ncontin_vars = ['CompetitionDistance', \n 'Max_TemperatureC', 'Mean_TemperatureC', 'Min_TemperatureC',\n 'Max_Humidity', 'Mean_Humidity', 'Min_Humidity', 'Max_Wind_SpeedKm_h', \n 'Mean_Wind_SpeedKm_h', 'CloudCover', 'trend', 'trend_DE',\n 'AfterStateHoliday', 'BeforeStateHoliday', 'Promo', 'SchoolHoliday']",
"_____no_output_____"
],
[
"\"\"\"contin_vars = ['CompetitionDistance', 'Max_TemperatureC', 'Mean_TemperatureC', \n 'Max_Humidity', 'trend', 'trend_DE', 'AfterStateHoliday', 'BeforeStateHoliday']\"\"\"",
"_____no_output_____"
]
],
[
[
"Replace nulls w/ 0 for continuous, \"\" for categorical.",
"_____no_output_____"
]
],
[
[
"for v in contin_vars: joined.loc[joined[v].isnull(), v] = 0\nfor v in cat_vars: joined.loc[joined[v].isnull(), v] = \"\"",
"_____no_output_____"
]
],
[
[
"Here we create a list of tuples, each containing a variable and an instance of a transformer for that variable.\n\nFor categoricals, we use a label encoder that maps categories to continuous integers. For continuous variables, we standardize them.",
"_____no_output_____"
]
],
[
[
"cat_maps = [(o, LabelEncoder()) for o in cat_vars]\ncontin_maps = [([o], StandardScaler()) for o in contin_vars]",
"_____no_output_____"
]
],
[
[
"The same instances need to be used for the test set as well, so values are mapped/standardized appropriately.\n\nDataFrame mapper will keep track of these variable-instance mappings.",
"_____no_output_____"
]
],
[
[
"cat_mapper = DataFrameMapper(cat_maps)\ncat_map_fit = cat_mapper.fit(joined)\ncat_cols = len(cat_map_fit.features)\ncat_cols",
"_____no_output_____"
],
[
"contin_mapper = DataFrameMapper(contin_maps)\ncontin_map_fit = contin_mapper.fit(joined)\ncontin_cols = len(contin_map_fit.features)\ncontin_cols",
"/home/roebius/pj/p3/lib/python3.5/site-packages/sklearn/utils/validation.py:429: DataConversionWarning: Data with input dtype int64 was converted to float64 by StandardScaler.\n warnings.warn(msg, _DataConversionWarning)\n"
]
],
[
[
"Example of first five rows of zeroth column being transformed appropriately.",
"_____no_output_____"
]
],
[
[
"cat_map_fit.transform(joined)[0,:5], contin_map_fit.transform(joined)[0,:5]",
"/home/roebius/pj/p3/lib/python3.5/site-packages/sklearn/utils/validation.py:429: DataConversionWarning: Data with input dtype int64 was converted to float64 by StandardScaler.\n warnings.warn(msg, _DataConversionWarning)\n"
]
],
[
[
"We can also pickle these mappings, which is great for portability!",
"_____no_output_____"
]
],
[
[
"pickle.dump(contin_map_fit, open('contin_maps.pickle', 'wb'))\npickle.dump(cat_map_fit, open('cat_maps.pickle', 'wb'))",
"_____no_output_____"
],
[
"[len(o[1].classes_) for o in cat_map_fit.features]",
"_____no_output_____"
]
],
[
[
"## Sample data",
"_____no_output_____"
],
[
"Next, the authors removed all instances where the store had zero sale / was closed.",
"_____no_output_____"
]
],
[
[
"joined_sales = joined[joined.Sales!=0]\nn = len(joined_sales)",
"_____no_output_____"
]
],
[
[
"We speculate that this may have cost them a higher standing in the competition. One reason this may be the case is that a little EDA reveals that there are often periods where stores are closed, typically for refurbishment. Before and after these periods, there are naturally spikes in sales that one might expect. Be ommitting this data from their training, the authors gave up the ability to leverage information about these periods to predict this otherwise volatile behavior.",
"_____no_output_____"
]
],
[
[
"n",
"_____no_output_____"
]
],
[
[
"We're going to run on a sample.",
"_____no_output_____"
]
],
[
[
"samp_size = 100000\nnp.random.seed(42)\nidxs = sorted(np.random.choice(n, samp_size, replace=False))",
"_____no_output_____"
],
[
"joined_samp = joined_sales.iloc[idxs].set_index(\"Date\")",
"_____no_output_____"
],
[
"samp_size = n\njoined_samp = joined_sales.set_index(\"Date\")",
"_____no_output_____"
]
],
[
[
"In time series data, cross-validation is not random. Instead, our holdout data is always the most recent data, as it would be in real application.",
"_____no_output_____"
],
[
"We've taken the last 10% as our validation set.",
"_____no_output_____"
]
],
[
[
"train_ratio = 0.9\ntrain_size = int(samp_size * train_ratio)",
"_____no_output_____"
],
[
"train_size",
"_____no_output_____"
],
[
"joined_valid = joined_samp[train_size:]\njoined_train = joined_samp[:train_size]\nlen(joined_valid), len(joined_train)",
"_____no_output_____"
]
],
[
[
"Here's a preprocessor for our categoricals using our instance mapper.",
"_____no_output_____"
]
],
[
[
"def cat_preproc(dat):\n return cat_map_fit.transform(dat).astype(np.int64)",
"_____no_output_____"
],
[
"cat_map_train = cat_preproc(joined_train)\ncat_map_valid = cat_preproc(joined_valid)",
"_____no_output_____"
]
],
[
[
"Same for continuous.",
"_____no_output_____"
]
],
[
[
"def contin_preproc(dat):\n return contin_map_fit.transform(dat).astype(np.float32)",
"_____no_output_____"
],
[
"contin_map_train = contin_preproc(joined_train)\ncontin_map_valid = contin_preproc(joined_valid)",
"/home/roebius/pj/p3/lib/python3.5/site-packages/sklearn/utils/validation.py:429: DataConversionWarning: Data with input dtype int64 was converted to float64 by StandardScaler.\n warnings.warn(msg, _DataConversionWarning)\n"
]
],
[
[
"Grab our targets.",
"_____no_output_____"
]
],
[
[
"y_train_orig = joined_train.Sales\ny_valid_orig = joined_valid.Sales",
"_____no_output_____"
]
],
[
[
"Finally, the authors modified the target values by applying a logarithmic transformation and normalizing to unit scale by dividing by the maximum log value.\n\nLog transformations are used on this type of data frequently to attain a nicer shape. \n\nFurther by scaling to the unit interval we can now use a sigmoid output in our neural network. Then we can multiply by the maximum log value to get the original log value and transform back.",
"_____no_output_____"
]
],
[
[
"max_log_y = np.max(np.log(joined_samp.Sales))\ny_train = np.log(y_train_orig)/max_log_y\ny_valid = np.log(y_valid_orig)/max_log_y",
"_____no_output_____"
]
],
[
[
"Note: Some testing shows this doesn't make a big difference.",
"_____no_output_____"
]
],
[
[
"\"\"\"#y_train = np.log(y_train)\nymean=y_train_orig.mean()\nystd=y_train_orig.std()\ny_train = (y_train_orig-ymean)/ystd\n#y_valid = np.log(y_valid)\ny_valid = (y_valid_orig-ymean)/ystd\"\"\"",
"_____no_output_____"
]
],
[
[
"Root-mean-squared percent error is the metric Kaggle used for this competition.",
"_____no_output_____"
]
],
[
[
"def rmspe(y_pred, targ = y_valid_orig):\n pct_var = (targ - y_pred)/targ\n return math.sqrt(np.square(pct_var).mean())",
"_____no_output_____"
]
],
[
[
"These undo the target transformations.",
"_____no_output_____"
]
],
[
[
"def log_max_inv(preds, mx = max_log_y):\n return np.exp(preds * mx)",
"_____no_output_____"
],
[
"# - This can be used if ymean and ystd are calculated above (they are currently commented out)\ndef normalize_inv(preds):\n return preds * ystd + ymean",
"_____no_output_____"
]
],
[
[
"## Create models",
"_____no_output_____"
],
[
"Now we're ready to put together our models.",
"_____no_output_____"
],
[
"Much of the following code has commented out portions / alternate implementations.",
"_____no_output_____"
]
],
[
[
"\"\"\"\n1 97s - loss: 0.0104 - val_loss: 0.0083\n2 93s - loss: 0.0076 - val_loss: 0.0076\n3 90s - loss: 0.0071 - val_loss: 0.0076\n4 90s - loss: 0.0068 - val_loss: 0.0075\n5 93s - loss: 0.0066 - val_loss: 0.0075\n6 95s - loss: 0.0064 - val_loss: 0.0076\n7 98s - loss: 0.0063 - val_loss: 0.0077\n8 97s - loss: 0.0062 - val_loss: 0.0075\n9 95s - loss: 0.0061 - val_loss: 0.0073\n0 101s - loss: 0.0061 - val_loss: 0.0074\n\"\"\"",
"_____no_output_____"
],
[
"def split_cols(arr):\n return np.hsplit(arr,arr.shape[1])",
"_____no_output_____"
],
[
"# - This gives the correct list length for the model\n# - (list of 23 elements: 22 embeddings + 1 array of 16-dim elements) \nmap_train = split_cols(cat_map_train) + [contin_map_train]\nmap_valid = split_cols(cat_map_valid) + [contin_map_valid]",
"_____no_output_____"
],
[
"len(map_train)",
"_____no_output_____"
],
[
"# map_train = split_cols(cat_map_train) + split_cols(contin_map_train)\n# map_valid = split_cols(cat_map_valid) + split_cols(contin_map_valid)",
"_____no_output_____"
]
],
[
[
"Helper function for getting categorical name and dim.",
"_____no_output_____"
]
],
[
[
"def cat_map_info(feat): return feat[0], len(feat[1].classes_)",
"_____no_output_____"
],
[
"cat_map_info(cat_map_fit.features[1])",
"_____no_output_____"
],
[
"# - In Keras 2 the \"initializations\" module is not available.\n# - To keep here the custom initializer the code from Keras 1 \"uniform\" initializer is exploited \ndef my_init(scale):\n# return lambda shape, name=None: initializations.uniform(shape, scale=scale, name=name)\n return K.variable(np.random.uniform(low=-scale, high=scale, size=shape),\n name=name)",
"_____no_output_____"
],
[
"# - In Keras 2 the \"initializations\" module is not available.\n# - To keep here the custom initializer the code from Keras 1 \"uniform\" initializer is exploited \ndef emb_init(shape, name=None): \n# return initializations.uniform(shape, scale=2/(shape[1]+1), name=name)\n return K.variable(np.random.uniform(low=-2/(shape[1]+1), high=2/(shape[1]+1), size=shape),\n name=name)",
"_____no_output_____"
]
],
[
[
"Helper function for constructing embeddings. Notice commented out codes, several different ways to compute embeddings at play.\n\nAlso, note we're flattening the embedding. Embeddings in Keras come out as an element of a sequence like we might use in a sequence of words; here we just want to concatenate them so we flatten the 1-vector sequence into a vector.",
"_____no_output_____"
]
],
[
[
"def get_emb(feat):\n name, c = cat_map_info(feat)\n #c2 = cat_var_dict[name]\n c2 = (c+1)//2\n if c2>50: c2=50\n inp = Input((1,), dtype='int64', name=name+'_in')\n # , kernel_regularizer=l2(1e-6) # Keras 2\n u = Flatten(name=name+'_flt')(Embedding(c, c2, input_length=1, embeddings_initializer=emb_init)(inp)) # Keras 2\n# u = Flatten(name=name+'_flt')(Embedding(c, c2, input_length=1)(inp))\n return inp,u",
"_____no_output_____"
]
],
[
[
"Helper function for continuous inputs.",
"_____no_output_____"
]
],
[
[
"def get_contin(feat):\n name = feat[0][0]\n inp = Input((1,), name=name+'_in')\n return inp, Dense(1, name=name+'_d', kernel_initializer=my_init(1.))(inp) # Keras 2",
"_____no_output_____"
]
],
[
[
"Let's build them.",
"_____no_output_____"
]
],
[
[
"contin_inp = Input((contin_cols,), name='contin')\ncontin_out = Dense(contin_cols*10, activation='relu', name='contin_d')(contin_inp)\n#contin_out = BatchNormalization()(contin_out)",
"_____no_output_____"
]
],
[
[
"Now we can put them together. Given the inputs, continuous and categorical embeddings, we're going to concatenate all of them.\n\nNext, we're going to pass through some dropout, then two dense layers w/ ReLU activations, then dropout again, then the sigmoid activation we mentioned earlier.",
"_____no_output_____"
]
],
[
[
"embs = [get_emb(feat) for feat in cat_map_fit.features]\n#conts = [get_contin(feat) for feat in contin_map_fit.features]\n#contin_d = [d for inp,d in conts]\nx = concatenate([emb for inp,emb in embs] + [contin_out]) # Keras 2\n#x = concatenate([emb for inp,emb in embs] + contin_d) # Keras 2\n\nx = Dropout(0.02)(x)\nx = Dense(1000, activation='relu', kernel_initializer='uniform')(x)\nx = Dense(500, activation='relu', kernel_initializer='uniform')(x)\nx = Dropout(0.2)(x)\nx = Dense(1, activation='sigmoid')(x)\n\nmodel = Model([inp for inp,emb in embs] + [contin_inp], x)\n#model = Model([inp for inp,emb in embs] + [inp for inp,d in conts], x)\nmodel.compile('adam', 'mean_absolute_error')\n#model.compile(Adam(), 'mse')",
"_____no_output_____"
]
],
[
[
"### Start training",
"_____no_output_____"
]
],
[
[
"%%time \nhist = model.fit(map_train, y_train, batch_size=128, epochs=25,\n verbose=1, validation_data=(map_valid, y_valid))",
"Train on 759904 samples, validate on 84434 samples\nEpoch 1/25\n759904/759904 [==============================] - 53s - loss: 0.0115 - val_loss: 0.0109\nEpoch 2/25\n759904/759904 [==============================] - 52s - loss: 0.0081 - val_loss: 0.0106\nEpoch 3/25\n759904/759904 [==============================] - 53s - loss: 0.0072 - val_loss: 0.0103\nEpoch 4/25\n759904/759904 [==============================] - 53s - loss: 0.0068 - val_loss: 0.0098\nEpoch 5/25\n759904/759904 [==============================] - 53s - loss: 0.0066 - val_loss: 0.0099\nEpoch 6/25\n759904/759904 [==============================] - 54s - loss: 0.0064 - val_loss: 0.0098\nEpoch 7/25\n759904/759904 [==============================] - 54s - loss: 0.0063 - val_loss: 0.0099\nEpoch 8/25\n759904/759904 [==============================] - 54s - loss: 0.0062 - val_loss: 0.0099\nEpoch 9/25\n759904/759904 [==============================] - 54s - loss: 0.0062 - val_loss: 0.0098\nEpoch 10/25\n759904/759904 [==============================] - 53s - loss: 0.0061 - val_loss: 0.0097\nEpoch 11/25\n759904/759904 [==============================] - 53s - loss: 0.0061 - val_loss: 0.0101\nEpoch 12/25\n759904/759904 [==============================] - 53s - loss: 0.0061 - val_loss: 0.0096\nEpoch 13/25\n759904/759904 [==============================] - 53s - loss: 0.0060 - val_loss: 0.0098\nEpoch 14/25\n759904/759904 [==============================] - 53s - loss: 0.0060 - val_loss: 0.0098\nEpoch 15/25\n759904/759904 [==============================] - 53s - loss: 0.0060 - val_loss: 0.0096\nEpoch 16/25\n759904/759904 [==============================] - 53s - loss: 0.0060 - val_loss: 0.0096\nEpoch 17/25\n759904/759904 [==============================] - 53s - loss: 0.0059 - val_loss: 0.0100\nEpoch 18/25\n759904/759904 [==============================] - 53s - loss: 0.0059 - val_loss: 0.0095\nEpoch 19/25\n759904/759904 [==============================] - 53s - loss: 0.0059 - val_loss: 0.0097\nEpoch 20/25\n759904/759904 [==============================] - 53s - loss: 0.0059 - val_loss: 0.0098\nEpoch 21/25\n759904/759904 [==============================] - 53s - loss: 0.0059 - val_loss: 0.0094\nEpoch 22/25\n759904/759904 [==============================] - 53s - loss: 0.0059 - val_loss: 0.0095\nEpoch 23/25\n759904/759904 [==============================] - 53s - loss: 0.0058 - val_loss: 0.0095\nEpoch 24/25\n759904/759904 [==============================] - 53s - loss: 0.0058 - val_loss: 0.0096\nEpoch 25/25\n759904/759904 [==============================] - 53s - loss: 0.0058 - val_loss: 0.0097\nCPU times: user 48min 2s, sys: 5min 7s, total: 53min 10s\nWall time: 22min 22s\n"
],
[
"hist.history",
"_____no_output_____"
],
[
"plot_train(hist)",
"_____no_output_____"
],
[
"preds = np.squeeze(model.predict(map_valid, 1024))",
"_____no_output_____"
]
],
[
[
"Result on validation data: 0.1678 (samp 150k, 0.75 trn)",
"_____no_output_____"
]
],
[
[
"log_max_inv(preds)",
"_____no_output_____"
],
[
"# - This will work if ymean and ystd are calculated in the \"Data\" section above (in this case uncomment)\n# normalize_inv(preds)",
"_____no_output_____"
]
],
[
[
"## Using 3rd place data",
"_____no_output_____"
]
],
[
[
"pkl_path = '/data/jhoward/github/entity-embedding-rossmann/'",
"_____no_output_____"
],
[
"def load_pickle(fname): \n return pickle.load(open(pkl_path+fname + '.pickle', 'rb'))",
"_____no_output_____"
],
[
"[x_pkl_orig, y_pkl_orig] = load_pickle('feature_train_data')",
"_____no_output_____"
],
[
"max_log_y_pkl = np.max(np.log(y_pkl_orig))\ny_pkl = np.log(y_pkl_orig)/max_log_y_pkl",
"_____no_output_____"
],
[
"pkl_vars = ['Open', 'Store', 'DayOfWeek', 'Promo', 'Year', 'Month', 'Day', \n 'StateHoliday', 'SchoolHoliday', 'CompetitionMonthsOpen', 'Promo2Weeks', \n 'Promo2Weeks_L', 'CompetitionDistance',\n 'StoreType', 'Assortment', 'PromoInterval', 'CompetitionOpenSinceYear',\n 'Promo2SinceYear', 'State', 'Week', 'Max_TemperatureC', 'Mean_TemperatureC', \n 'Min_TemperatureC', 'Max_Humidity', 'Mean_Humidity', 'Min_Humidity', 'Max_Wind_SpeedKm_h', \n 'Mean_Wind_SpeedKm_h', 'CloudCover','Events', 'Promo_fw', 'Promo_bw', \n 'StateHoliday_fw', 'StateHoliday_bw', 'AfterStateHoliday', 'BeforeStateHoliday', \n 'SchoolHoliday_fw', 'SchoolHoliday_bw', 'trend_DE', 'trend']",
"_____no_output_____"
],
[
"x_pkl = np.array(x_pkl_orig)",
"_____no_output_____"
],
[
"gt_enc = StandardScaler()\ngt_enc.fit(x_pkl[:,-2:])",
"_____no_output_____"
],
[
"x_pkl[:,-2:] = gt_enc.transform(x_pkl[:,-2:])",
"_____no_output_____"
],
[
"x_pkl.shape",
"_____no_output_____"
],
[
"x_pkl = x_pkl[idxs]\ny_pkl = y_pkl[idxs]",
"_____no_output_____"
],
[
"x_pkl_trn, x_pkl_val = x_pkl[:train_size], x_pkl[train_size:]\ny_pkl_trn, y_pkl_val = y_pkl[:train_size], y_pkl[train_size:]",
"_____no_output_____"
],
[
"x_pkl_trn.shape",
"_____no_output_____"
],
[
"xgb_parms = {'learning_rate': 0.1, 'subsample': 0.6, \n 'colsample_bylevel': 0.6, 'silent': True, 'objective': 'reg:linear'}",
"_____no_output_____"
],
[
"xdata_pkl = xgboost.DMatrix(x_pkl_trn, y_pkl_trn, feature_names=pkl_vars)",
"_____no_output_____"
],
[
"xdata_val_pkl = xgboost.DMatrix(x_pkl_val, y_pkl_val, feature_names=pkl_vars)",
"_____no_output_____"
],
[
"xgb_parms['seed'] = random.randint(0,1e9)\nmodel_pkl = xgboost.train(xgb_parms, xdata_pkl)",
"_____no_output_____"
],
[
"model_pkl.eval(xdata_val_pkl)",
"_____no_output_____"
],
[
"#0.117473",
"_____no_output_____"
],
[
"importance = model_pkl.get_fscore()\nimportance = sorted(importance.items(), key=operator.itemgetter(1))\n\ndf = pd.DataFrame(importance, columns=['feature', 'fscore'])\ndf['fscore'] = df['fscore'] / df['fscore'].sum()\n\ndf.plot(kind='barh', x='feature', y='fscore', legend=False, figsize=(6, 10))\nplt.title('XGBoost Feature Importance')\nplt.xlabel('relative importance');",
"_____no_output_____"
]
],
[
[
"### Neural net",
"_____no_output_____"
]
],
[
[
"#np.savez_compressed('vars.npz', pkl_cats, pkl_contins)\n#np.savez_compressed('deps.npz', y_pkl)",
"_____no_output_____"
],
[
"pkl_cats = np.stack([x_pkl[:,pkl_vars.index(f)] for f in cat_vars], 1)\npkl_contins = np.stack([x_pkl[:,pkl_vars.index(f)] for f in contin_vars], 1)",
"_____no_output_____"
],
[
"co_enc = StandardScaler().fit(pkl_contins)\npkl_contins = co_enc.transform(pkl_contins)",
"_____no_output_____"
],
[
"pkl_contins_trn, pkl_contins_val = pkl_contins[:train_size], pkl_contins[train_size:]\npkl_cats_trn, pkl_cats_val = pkl_cats[:train_size], pkl_cats[train_size:]\ny_pkl_trn, y_pkl_val = y_pkl[:train_size], y_pkl[train_size:]",
"_____no_output_____"
],
[
"def get_emb_pkl(feat):\n name, c = cat_map_info(feat)\n c2 = (c+2)//3\n if c2>50: c2=50\n inp = Input((1,), dtype='int64', name=name+'_in')\n u = Flatten(name=name+'_flt')(Embedding(c, c2, input_length=1, init=emb_init)(inp))\n return inp,u",
"_____no_output_____"
],
[
"n_pkl_contin = pkl_contins_trn.shape[1]\ncontin_inp = Input((n_pkl_contin,), name='contin')\ncontin_out = BatchNormalization()(contin_inp)",
"_____no_output_____"
],
[
"map_train_pkl = split_cols(pkl_cats_trn) + [pkl_contins_trn]\nmap_valid_pkl = split_cols(pkl_cats_val) + [pkl_contins_val]",
"_____no_output_____"
],
[
"def train_pkl(bs=128, ne=10):\n return model_pkl.fit(map_train_pkl, y_pkl_trn, batch_size=bs, nb_epoch=ne,\n verbose=0, validation_data=(map_valid_pkl, y_pkl_val))",
"_____no_output_____"
],
[
"def get_model_pkl(): \n conts = [get_contin_pkl(feat) for feat in contin_map_fit.features]\n embs = [get_emb_pkl(feat) for feat in cat_map_fit.features]\n x = merge([emb for inp,emb in embs] + [contin_out], mode='concat')\n\n x = Dropout(0.02)(x)\n x = Dense(1000, activation='relu', init='uniform')(x)\n x = Dense(500, activation='relu', init='uniform')(x)\n x = Dense(1, activation='sigmoid')(x)\n\n model_pkl = Model([inp for inp,emb in embs] + [contin_inp], x)\n model_pkl.compile('adam', 'mean_absolute_error')\n #model.compile(Adam(), 'mse')\n return model_pkl",
"_____no_output_____"
],
[
"model_pkl = get_model_pkl()",
"_____no_output_____"
],
[
"train_pkl(128, 10).history['val_loss']",
"_____no_output_____"
],
[
"K.set_value(model_pkl.optimizer.lr, 1e-4)\ntrain_pkl(128, 5).history['val_loss']",
"_____no_output_____"
],
[
"\"\"\"\n1 97s - loss: 0.0104 - val_loss: 0.0083\n2 93s - loss: 0.0076 - val_loss: 0.0076\n3 90s - loss: 0.0071 - val_loss: 0.0076\n4 90s - loss: 0.0068 - val_loss: 0.0075\n5 93s - loss: 0.0066 - val_loss: 0.0075\n6 95s - loss: 0.0064 - val_loss: 0.0076\n7 98s - loss: 0.0063 - val_loss: 0.0077\n8 97s - loss: 0.0062 - val_loss: 0.0075\n9 95s - loss: 0.0061 - val_loss: 0.0073\n0 101s - loss: 0.0061 - val_loss: 0.0074\n\"\"\"",
"_____no_output_____"
],
[
"plot_train(hist)",
"_____no_output_____"
],
[
"preds = np.squeeze(model_pkl.predict(map_valid_pkl, 1024))",
"_____no_output_____"
],
[
"y_orig_pkl_val = log_max_inv(y_pkl_val, max_log_y_pkl)",
"_____no_output_____"
],
[
"rmspe(log_max_inv(preds, max_log_y_pkl), y_orig_pkl_val)",
"_____no_output_____"
]
],
[
[
"## XGBoost",
"_____no_output_____"
],
[
"Xgboost is extremely quick and easy to use. Aside from being a powerful predictive model, it gives us information about feature importance.",
"_____no_output_____"
]
],
[
[
"X_train = np.concatenate([cat_map_train, contin_map_train], axis=1)",
"_____no_output_____"
],
[
"X_valid = np.concatenate([cat_map_valid, contin_map_valid], axis=1)",
"_____no_output_____"
],
[
"all_vars = cat_vars + contin_vars",
"_____no_output_____"
],
[
"xgb_parms = {'learning_rate': 0.1, 'subsample': 0.6, \n 'colsample_bylevel': 0.6, 'silent': True, 'objective': 'reg:linear'}",
"_____no_output_____"
],
[
"xdata = xgboost.DMatrix(X_train, y_train, feature_names=all_vars)",
"_____no_output_____"
],
[
"xdata_val = xgboost.DMatrix(X_valid, y_valid, feature_names=all_vars)",
"_____no_output_____"
],
[
"xgb_parms['seed'] = random.randint(0,1e9)\nmodel = xgboost.train(xgb_parms, xdata)",
"_____no_output_____"
],
[
"model.eval(xdata_val)",
"_____no_output_____"
],
[
"model.eval(xdata_val)",
"_____no_output_____"
]
],
[
[
"Easily, competition distance is the most important, while events are not important at all.\n\nIn real applications, putting together a feature importance plot is often a first step. Oftentimes, we can remove hundreds of thousands of features from consideration with importance plots. ",
"_____no_output_____"
]
],
[
[
"importance = model.get_fscore()\nimportance = sorted(importance.items(), key=operator.itemgetter(1))\n\ndf = pd.DataFrame(importance, columns=['feature', 'fscore'])\ndf['fscore'] = df['fscore'] / df['fscore'].sum()\n\ndf.plot(kind='barh', x='feature', y='fscore', legend=False, figsize=(6, 10))\nplt.title('XGBoost Feature Importance')\nplt.xlabel('relative importance');",
"_____no_output_____"
]
],
[
[
"## End",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a94022e87e9c007e6f59efbbd6a0bca4240bc3e
| 44,183 |
ipynb
|
Jupyter Notebook
|
AAeIMD/Tareas/T6-NLP/ProyectoNLP-BRC-AAIMD.ipynb
|
BenchHPZ/UG-Compu
|
fa3551a862ee04b59a5ba97a791f39a77ce2df60
|
[
"MIT"
] | null | null | null |
AAeIMD/Tareas/T6-NLP/ProyectoNLP-BRC-AAIMD.ipynb
|
BenchHPZ/UG-Compu
|
fa3551a862ee04b59a5ba97a791f39a77ce2df60
|
[
"MIT"
] | null | null | null |
AAeIMD/Tareas/T6-NLP/ProyectoNLP-BRC-AAIMD.ipynb
|
BenchHPZ/UG-Compu
|
fa3551a862ee04b59a5ba97a791f39a77ce2df60
|
[
"MIT"
] | null | null | null | 29.474983 | 561 | 0.415544 |
[
[
[
"from math import inf\nfrom collections import Counter\nfrom collections import OrderedDict ",
"_____no_output_____"
]
],
[
[
"# 1.Codigo de norving",
"_____no_output_____"
]
],
[
[
"\"\"\"\n Spelling Corrector in Python 3; see http://norvig.com/spell-correct.html\n\n Copyright (c) 2007-2016 Peter Norvig\n MIT license: www.opensource.org/licenses/mit-license.php\n\"\"\"\n################ Spelling Corrector ################\n####################################################\nimport re\nfrom collections import Counter\n\ndef words(text): return re.findall(r'\\w+', text.lower())\n\nWORDS = Counter(words(open('big.txt').read()))\n\ndef P(word, N=sum(WORDS.values())): \n \"Probability of `word`.\"\n return WORDS[word] / N\n\ndef correction(word): \n \"Most probable spelling correction for word.\"\n return max(candidates(word), key=P)\n\ndef candidates(word): \n \"Generate possible spelling corrections for word.\"\n return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])\n\ndef known(words): \n \"The subset of `words` that appear in the dictionary of WORDS.\"\n return set(w for w in words if w in WORDS)\n\ndef edits1(word):\n \"All edits that are one edit away from `word`.\"\n letters = 'abcdefghijklmnopqrstuvwxyz'\n splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]\n deletes = [L + R[1:] for L, R in splits if R]\n transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]\n replaces = [L + c + R[1:] for L, R in splits if R for c in letters]\n inserts = [L + c + R for L, R in splits for c in letters]\n return set(deletes + transposes + replaces + inserts)\n\ndef edits2(word): \n \"All edits that are two edits away from `word`.\"\n return (e2 for e1 in edits1(word) for e2 in edits1(e1))\n\n################ Test Code \n\ndef unit_tests():\n assert correction('speling') == 'spelling','Err: insert'# insert\n assert correction('korrectud') == 'corrected' # replace 2\n assert correction('bycycle') == 'bicycle' # replace\n assert correction('inconvient') == 'inconvenient' # insert 2\n assert correction('arrainged') == 'arranged' # delete\n assert correction('peotry') =='poetry' # transpose\n assert correction('peotryy') =='poetry' # transpose + delete\n assert correction('word') == 'word' # known\n assert correction('quintessential') == 'quintessential' # unknown\n assert words('This is a TEST.') == ['this', 'is', 'a', 'test']\n assert Counter(words('This is a test. 123; A TEST this is.')) == (\n Counter({'123': 1, 'a': 2, 'is': 2, 'test': 2, 'this': 2}))\n assert len(WORDS) == 32198\n assert sum(WORDS.values()) == 1115585\n assert WORDS.most_common(10) == [\n ('the', 79809),\n ('of', 40024),\n ('and', 38312),\n ('to', 28765),\n ('in', 22023),\n ('a', 21124),\n ('that', 12512),\n ('he', 12401),\n ('was', 11410),\n ('it', 10681)]\n assert WORDS['the'] == 79809\n assert P('quintessential') == 0\n assert 0.07 < P('the') < 0.08\n return 'unit_tests pass'",
"_____no_output_____"
],
[
"print(unit_tests())\nprint(correction('speling'))\nprint(correction('korrectud'))\nprint(correction('thu'))",
"unit_tests pass\nspelling\ncorrected\nthe\n"
]
],
[
[
"# 2.La siguiente palabra m\\'as probable\n\nUsando _big.txt_ crear una funci\\'on que estime la siguiente palabra m\\'as probable dada una anterior. La funci\\'on debbe calcular \n $$w_{i+1} = \\text{argmax}_{w_{i+1}}P(W_{i+1}|w_i)$$\nPara este trabajo\n1. Podemos asumir que ambas palabras siempre existir\\'an en la colecci\\'on\n2. Requerimos una funci\\'on similar a $P$, que calcule $P(w_1|w_2)$",
"_____no_output_____"
]
],
[
[
"################################\n### Funciones para trabajar ###\n################################\n\ndef words_from_file( fileName ):\n \"\"\" Obtenemos las palabras de un archivo. \"\"\"\n file = open(fileName).read()\n return re.findall(r'\\w+', file.lower())\n\ndef create_dict(texto):\n \"\"\" Funcion para crear el diccionario auxiliar para \n calcular las probabilidades necesarias. \n \"\"\"\n ret = {}\n for i in range(1,len(texto)):\n if texto[i] not in ret:\n ret[texto[i]] = {}\n if texto[i-1] not in ret[texto[i]]:\n (ret[texto[i]])[texto[i-1]] = 0\n \n (ret[texto[i]])[texto[i-1]] += 1\n \n # Pre-ordenado\n for word in ret:\n ret[word] = OrderedDict(sorted(ret[word].items(), \n key=lambda x: \n prob_cond(x[0], word, ret),\n reverse=True))\n \n return ret\n\ndef prob_cond(a, b, dic):\n \"\"\" Probabilidad de A dado B en funcion de dic \"\"\"\n try:\n return ((dic[a])[b])/sum(dic[b].values())\n except KeyError:\n return -1\n\ndef next_word(word, dic):\n \"\"\" Obtenemos la siguiente palabra mas probable en funcion\n del dicionario y sus probabiliodades. \"\"\"\n try:\n return next(iter(dic[word]))\n except:\n return word",
"_____no_output_____"
],
[
"dic = create_dict(words_from_file('big.txt'))\nword = 'new'\n\nprint( word +' '+next_word( word, dic) )\nprint( prob_cond('york','new', dic) )",
"new york\n0.15811258278145696\n"
]
],
[
[
"## 2.1.Aqu\\'i la maquina juega al ahorcado\nSe recomienda extender y mejorar de alg\\'un modo la funci\\'on propuesta por __Norving__.",
"_____no_output_____"
]
],
[
[
"def under(word):\n word = word.split('_')\n if len(word) > 5:\n print('Demasiadas letras desconocidas')\n return None\n return word\n\ndef candidatos(word):\n ''' Recibe a word ya con el 'split' aplicado \n y regresamos las posibles palabras \n ''' \n letters = 'abcdefghijklmnopqrstuvwxyz'\n n_letters = len(letters)\n flag = word[-1] if word[-1] != '' else 'BrendA'\n \n # Creamos los posibles 'pedacitos' de la palabra\n words = [ele + letter \n for ele in word[:len(word)-1] \n for letter in letters]\n \n # Variables auxiliares\n options = words[:n_letters]\n options_t = []\n \n # Concatenamos los posibles 'pedacitos'\n for k in range( 1, len(words)//n_letters ):\n for option in options:\n for i in range(n_letters):\n options_t.append(option + words[n_letters*k + i])\n options = options_t; options_t = []\n \n if flag != 'BrendA': # Checamos si al final hay un '_' o una letra\n for i in range(len(options)): \n options[i] = options[i] + flag\n \n # Regresamos unicamente las palabras que esten en el diccionario\n return set(opt for opt in options if opt in WORDS)\n\ndef dist_lev(source, target):\n if source == target: return 0\n # Crear matriz\n n_s, n_t = len(source), len(target)\n dist = [[0 for i in range(n_t+1)] for x in range(n_s+1)]\n for i in range(n_s+1): dist[i][0] = i\n for j in range(n_t+1): dist[0][j] = j\n # Calculando la distancia\n for i in range(n_s):\n for j in range(n_t):\n cost = 0 if source[i] == target[j] else 1\n dist[i+1][j+1] = min(\n dist[i][j+1] + 1, # deletion\n dist[i+1][j] + 1, # insertion\n dist[i][j] + cost # substitution\n )\n return dist[-1][-1]\n\ndef closest(word, options):\n ret = 'BrendA', inf\n for opt in options:\n dist = dist_lev(word, opt)\n ret = (opt, dist) if dist < ret[1] else ret\n return ret\n \ndef hangman(word):\n options = candidatos( under(word) )\n return closest(word, options)",
"_____no_output_____"
],
[
"print(hangman('s_e_l_c_')[0]) #sherlock\nprint(hangman('no_eb_o_')[0]) #notebook\nprint(hangman('he__o')[0]) #hello\n\nprint(hangman('pe_p_e')[0]) #people\nprint(hangman('phi__sop_y')[0]) #philospphy\nprint(hangman('si_nif_c_nc_')[0]) #significance\nprint(hangman('kn__l_d_e')[0]) #sun",
"sherlock\nnotebook\nhello\npeople\nphilosophy\nsignificance\nknowledge\n"
]
],
[
[
"## 2.2.Ahorcado al extremo\nUnir la funci\\'on de _2_ y _2.1_ para, utilizando una palabra de contexto, completar palabras con mayor precisi\\'on",
"_____no_output_____"
]
],
[
[
"def super_under(word):\n ct = Counter(word)\n if len(word) - ct['_'] < 1:\n print('Demasiadas letras desconocidas')\n return None\n word = word.split('_')\n return word\n\ndef super_closest( context, options):\n ret = 'BrendA', -inf\n for opt in options: # Buscando el ret adecuado\n # Esta es la misma funcion de probabilidad del ejercicio anterior\n prob = prob_cond(opt, context, dic)\n # En caso de que las proabilidades empaten\n # utilizamos las distancia entre las palabras\n # para responder.\n ret = ((opt, prob) if dist_lev(context, opt) < dist_lev(context, ret[0]) else ret) if prob == ret[1] else ret\n ret = (opt, prob) if prob > ret[1] else ret \n return ret\n\ndef super_hangman(context, word):\n options = candidatos( super_under(word) )\n return super_closest(context, options)",
"_____no_output_____"
],
[
"print(super_hangman('sherlock', '_____s')) #holmes\nprint(super_hangman('united', '_t_t__')) #states\nprint(super_hangman('white', '___s_')) #house\nprint(super_hangman('new', 'y___')) #york\nprint(super_hangman('abraham', 'l_____n')) #lincoln",
"('holmes', 1.0)\n('states', 0.7620751341681574)\n('house', 0.037142857142857144)\n('york', 0.15811258278145696)\n('lincoln', 0.6666666666666666)\n"
]
],
[
[
"# 3.Correci\\'on ortografica simple",
"_____no_output_____"
],
[
"### Funciones auxiliares",
"_____no_output_____"
]
],
[
[
"import os, re\n\n# simple extraction of words\ndef words (text) : \n return re.findall(r'\\w+', text.lower())\n\n# siple loading of the documents\nfrom keras.preprocessing.text import Tokenizer\ndef get_texts_from_catdir( catdir ):\n texts = [ ]\n TARGET_DIR = catdir # \"./target\"\n for f_name in sorted( os.listdir( TARGET_DIR )) :\n if f_name.endswith('.txt'):\n f_path = os.path.join( TARGET_DIR, f_name )\n #print(f_name)\n #print(f_path)\n f = open( f_path , 'r', encoding='utf8' )\n #print( f_name )\n texts += [ f.read( ) ]\n f.close( )\n print( '%d files loaded . ' %len(texts) )\n return texts\n\n# Load the RAW text\ntarget_txt = get_texts_from_catdir( './target' )\n\n# Print first 10 words in document0\nprint( words(target_txt[0])[:10] )",
"10 files loaded . \n['scientists', 'witness', 'huge', 'cosmic', 'crash', 'find', 'origins', 'of', 'gold', 'even']\n"
]
],
[
[
"### Mezclar diccionarios",
"_____no_output_____"
]
],
[
[
"import json\n\nWORDS = Counter(words(open('big.txt').read()))\nwith open('WORDS_IN_NEWS.txt', 'r') as infile: # Exportando WORDS_IN_NEWS\n WORDS_IN_NEWS = json.load( infile )\nWORDS_IN_NEWS = Counter(WORDS_IN_NEWS)\n\nWORDS = WORDS + WORDS_IN_NEWS\nprint(WORDS['the'])\nprint(WORDS.most_common(5))",
"80337\n[('the', 80337), ('of', 40265), ('and', 38564), ('to', 29063), ('in', 22262)]\n"
]
],
[
[
"### Detectar las plabras mal escritas",
"_____no_output_____"
]
],
[
[
"def mispelled_and_candidates( target_words ):\n mispelled_candidates = []\n for word in target_words:\n temp = list(candidates(word)) # candidates de Norving\n if len(temp) > 1:\n temp.sort(key=lambda x: dist_lev(word, x))\n mispelled_candidates.append((word, temp[:10])) #Tomamos las primeras 10\n return mispelled_candidates\n\ndef mispelled_and_candidates( target_words ):\n mispelled_candidates = []\n \n for word in target_words:\n candidatos = list(candidates(word))\n candidatos.sort(key=lambda x: dist_lev(word, x))\n if len(candidatos) > 1:\n # En caso de que haya una opcion\n mispelled_candidates.append((word, candidatos[:10]))\n elif len(candidatos) == 1 and word not in candidatos:\n # En caso de que la unica opcion sea distinta\n mispelled_candidates.append((word, candidatos))\n\n return mispelled_candidates\n\n#print ( mispelled_and_candidates( words( target_txt[0] )))\n\n# Print misspelled words and candidates for each document in\n# target_txt list\nfor text in target_txt:\n print ( mispelled_and_candidates ( words ( text ) ) )\n pass",
"[('detcted', ['detected']), ('intoo', ['into'])]\n[('conttinue', ['continue'])]\n[('thhe', ['thee', 'the'])]\n[('statment', ['statement'])]\n[('watchng', ['watching'])]\n[('possiblle', ['possible'])]\n[('saiid', ['said'])]\n[('addresss', ['address', 'addresses'])]\n[('essetially', ['essentially'])]\n[('gennerral', ['general'])]\n"
]
],
[
[
"### Correccion completa",
"_____no_output_____"
],
[
"Para este ejercicio supondremos que la primera palabra esta bien escrita y tiene sentido. \n\nLa funcion `spell_correction` tiene una caracteristica que puede o no mejorar dependiendo de ciertos casos. De manera general, primero pasamos por la funcion del iniciso anterior al texto e identificamos todas las palabras mal escritas, luego, priorizando la probabilidad que ofrece la palabra anterior, escogemos la mejor opcione de entre aquellas que se generen por `candidates` _de Norvng_.\n\nEsta forma de actuar tiene la principal desventaja de que no detectara problemas como las ultimas dos pruebas (ejemplos) que se proponen. Donde son palabras bien escritas pero que no necesariamente son las correctas, para solucionar esto podemos dar una propuesta mas agresva donde, en caso de que la palabra que probabilisticamente halbando (y en funcion con el corpus) deberia de seguir, la ponemos sin preguntar. Esto permite solucionar mas incisos del ejemplo, pero tambien descompone otras partes (como se puede ver en las pruebas de las noticias)\n\nEn general creo que aqui es donde podemos darle la opcion al humano para que escoja la palabra que mejor se acomode. Para superar esto podriamos ampliar el corpus o considerar la palabra que mejor se complemente con la que sigue. En caso de empezar con estasconsideraciones me parece que seria mejor primero arreglar todos las palabras que estan claramente mal escritas y luego hacer otra pasada con probabilidades.\n\n\n#### Nota\n\nDado que _ham_ no parece estar en el corpus, causa problemas",
"_____no_output_____"
]
],
[
[
"# Creacion de diccionario ampliado\n# Aunque no sirve de mucho\nnbig = open('big.txt').read()\nfor text in target_txt:\n nbig += text\n \ndic = create_dict(words(nbig))",
"_____no_output_____"
],
[
"\ndef spell_correction( input_text, max_dist=2, profundo=False):\n \"\"\" Profundo le da mas libertad a la maquia para mejorar el texto. \"\"\"\n corrected_text = input_text\n mispeled = dict(mispelled_and_candidates(input_text))\n \n for iw in range(1, len(input_text)):\n pword = corrected_text[iw-1]\n \n word = input_text[iw]\n nword = next_word(pword, dic)\n \n # En otro caso consideramos las probabilidades\n if word in mispeled:\n corrected_text[iw] = max(mispeled[word], \n key=lambda x: prob_cond(x, pword, dic))\n # Si se parecem cambiamos sin preguntar\n if profundo and dist_lev(nword, word) <= max_dist:\n corrected_text[iw] = nword\n\n return corrected_text\n\ntests = [['i', 'hav', 'a', 'ham'],\n ['my', 'countr', 'is', 'biig'],\n ['i', 'want', 't00', 'eat'],\n ['the', 'science', '0ff', 'computer'],\n ['the', 'science', 'off', 'computer'],\n [ 'i', 'want' , 'too' , 'eat']\n ]\nfor s in tests:\n #print(mispelled_and_candidates(s))\n print(s)\n print( spell_correction( s, profundo=True ))\n print()\n\n\n",
"['i', 'hav', 'a', 'ham']\n['i', 'have', 'a', 'man']\n\n['my', 'countr', 'is', 'biig']\n['my', 'country', 'is', 'big']\n\n['i', 'want', 't00', 'eat']\n['i', 'want', 'to', 'eat']\n\n['the', 'science', '0ff', 'computer']\n['the', 'science', 'of', 'computer']\n\n['the', 'science', 'off', 'computer']\n['the', 'science', 'of', 'computer']\n\n['i', 'want', 'too', 'eat']\n['i', 'want', 'to', 'eat']\n\n"
]
],
[
[
"#### Chequeo con Golden",
"_____no_output_____"
]
],
[
[
"golden_txt = get_texts_from_catdir( './golden' )\ngolden_words = words(\" \".join(golden_txt))\ntarget_words = words(\" \".join(target_txt))\n\ni = 0\nfor gword, tword in zip(golden_words, target_words):\n if gword != tword:\n print(f\"{i} => {gword} != {tword}\")\n i+=1",
"10 files loaded . \n0 => detected != detcted\n1 => into != intoo\n2 => continue != conttinue\n3 => the != thhe\n4 => statement != statment\n5 => watching != watchng\n6 => possible != possiblle\n7 => said != saiid\n8 => address != addresss\n9 => essentially != essetially\n10 => general != gennerral\n"
],
[
"new_text = spell_correction(target_words)\nnew_words = words(\" \".join(new_text))\n\ni = 0\nfor gword, nword in zip(golden_words, new_words):\n if gword != nword:\n print(f\"{i} => {gword} != {nword}\")\n i+=1\nelse:\n if i==0:\n print(\"<-----|!!! No hay errores =D !!!|----->\")",
"<-----|!!! No hay errores =D !!!|----->\n"
],
[
"new_text = spell_correction(target_words, profundo=True)\nnew_words = words(\" \".join(new_text))\n\ni = 0\nfor gword, nword in zip(golden_words, new_words):\n if gword != nword:\n print(f\"{i} => {gword} != {nword}\")\n i+=1\nelse:\n if i==0:\n print(\"<-----|!!! No hay errores =D !!!|----->\")\n else:\n print(\" ='( Ahora si )'=\")",
"0 => in != if\n1 => ago != and\n2 => the != that\n3 => two != the\n4 => to != as\n5 => of != a\n6 => a != man\n7 => star != stars\n8 => a != to\n9 => a != it\n10 => an != a\n11 => to != in\n12 => on != i\n13 => the != to\n14 => one != be\n15 => we != the\n16 => in != of\n17 => would != gold\n18 => s != of\n19 => at != of\n20 => we != to\n21 => ve != be\n22 => this != the\n23 => the != to\n24 => on != and\n25 => 5 != to\n26 => 88 != be\n27 => the != to\n28 => in != and\n29 => how != to\n30 => are != and\n31 => for != to\n32 => 4 != in\n33 => the != he\n34 => this != the\n35 => s != of\n36 => out != you\n37 => the != are\n38 => 1 != he\n39 => are != he\n40 => a != had\n41 => was != is\n42 => to != s\n43 => of != a\n44 => this != the\n45 => to != of\n46 => the != her\n47 => that != the\n48 => into != it\n49 => said != and\n50 => has != he\n51 => 60 != in\n52 => do != he\n53 => that != the\n54 => have != he\n55 => was != is\n56 => said != david\n57 => in != and\n58 => we != he\n59 => in != and\n60 => said != and\n61 => the != to\n62 => one != the\n63 => on != and\n64 => any != a\n65 => that != this\n66 => get != be\n67 => in != and\n68 => the != he\n69 => said != david\n70 => the != her\n71 => this != the\n72 => they != the\n73 => 20 != in\n74 => a != and\n75 => to != the\n76 => we != he\n77 => at != a\n78 => we != of\n79 => this != him\n80 => it != he\n81 => has != had\n82 => been != then\n83 => a != he\n84 => as != to\n85 => to != it\n86 => in != twin\n87 => the != those\n88 => on != of\n89 => as != last\n90 => the != to\n91 => in != and\n92 => other != over\n93 => in != and\n94 => at != of\n95 => up != in\n96 => and != a\n97 => it != him\n98 => this != the\n99 => has != al\n100 => to != of\n101 => their != the\n102 => as != last\n103 => as != of\n104 => man != and\n105 => in != and\n106 => the != them\n107 => 70 != in\n108 => to != as\n109 => had != and\n110 => he != a\n111 => to != of\n112 => the != to\n113 => s != us\n114 => a != and\n115 => is != he\n116 => two != the\n117 => has != al\n118 => a != and\n119 => of != _\n120 => in != of\n121 => at != and\n122 => a != in\n123 => said != and\n124 => the != them\n125 => to != the\n126 => we != the\n127 => in != and\n128 => we != of\n129 => for != to\n130 => a != be\n131 => for != of\n132 => those != the\n133 => said != and\n134 => face != same\n135 => this != the\n136 => the != her\n137 => to != the\n138 => at != and\n139 => for != to\n140 => in != and\n141 => the != he\n142 => the != that\n143 => to != of\n144 => the != there\n145 => an != a\n146 => to != a\n147 => after != later\n148 => in != and\n149 => to != a\n150 => for != of\n151 => a != of\n152 => he != a\n153 => was != man\n154 => a != and\n155 => this != the\n156 => he != a\n157 => was != man\n158 => by != s\n159 => in != to\n160 => to != in\n161 => at != by\n162 => bay != at\n163 => a != by\n164 => a != of\n165 => the != he\n166 => be != of\n167 => to != not\n168 => a != to\n169 => is != he\n170 => to != the\n171 => a != and\n172 => for != of\n173 => his != him\n174 => who != two\n175 => in != and\n176 => he != the\n177 => case != same\n178 => t != i\n179 => as != of\n180 => is != he\n181 => out != not\n182 => in != and\n183 => to != of\n184 => he != the\n185 => he != it\n186 => his != it\n187 => s != of\n188 => to != he\n189 => the != be\n190 => of != to\n191 => he != of\n192 => he != the\n193 => he != him\n194 => he != the\n195 => said != same\n196 => that != they\n197 => then != this\n198 => plan != man\n199 => to != s\n200 => to != the\n201 => had != have\n202 => i != he\n203 => was != had\n204 => to != on\n205 => the != be\n206 => i != he\n207 => was != had\n208 => i != he\n209 => be != he\n210 => what != had\n211 => those != the\n212 => go != he\n213 => the != be\n214 => those != the\n215 => they != the\n216 => that != the\n217 => to != he\n218 => i != to\n219 => i != is\n220 => me != to\n221 => i != he\n222 => am != had\n223 => i != a\n224 => don != man\n225 => t != s\n226 => said != had\n227 => 20 != in\n228 => they != the\n229 => for != of\n230 => an != it\n231 => the != her\n232 => of != it\n233 => for != to\n234 => we != a\n235 => t != i\n236 => any != away\n237 => to != a\n238 => he != the\n239 => t != i\n240 => he != it\n241 => the != when\n242 => s != in\n243 => 7 != a\n244 => was != is\n245 => no != to\n246 => that != the\n247 => in != its\n248 => that != the\n249 => as != do\n250 => woman != man\n251 => her != be\n252 => i != a\n253 => i != it\n254 => ve != is\n255 => not != to\n256 => ago != as\n257 => then != the\n258 => it != a\n259 => me != the\n260 => 34 != it\n261 => an != and\n262 => to != the\n263 => was != is\n264 => did != i\n265 => the != her\n266 => an != a\n267 => and != a\n268 => one != and\n269 => in != do\n270 => an != in\n271 => the != her\n272 => off != of\n273 => on != of\n274 => to != of\n275 => a != be\n276 => the != be\n277 => to != of\n278 => it != or\n279 => the != one\n280 => see != are\n281 => a != be\n282 => on != to\n283 => t != be\n284 => on != and\n285 => it != a\n286 => if != i\n287 => have != are\n288 => it != i\n289 => they != he\n290 => to != tv\n291 => to != the\n292 => of != not\n293 => a != to\n294 => set != be\n295 => top != the\n296 => now != for\n297 => the != he\n298 => at != to\n299 => t != be\n300 => to != the\n301 => has != he\n302 => a != had\n303 => s != an\n304 => use != the\n305 => if != of\n306 => re != are\n307 => tie != be\n308 => a != and\n309 => as != and\n310 => at != a\n311 => in != and\n312 => for != of\n313 => to != you\n314 => up != to\n315 => tv != an\n316 => in != and\n317 => that != the\n318 => the != then\n319 => a != to\n320 => lg != a\n321 => by != to\n322 => the != be\n323 => the != he\n324 => ends != and\n325 => 50 != to\n326 => per != be\n327 => it != i\n328 => time != the\n329 => in != and\n330 => at != not\n331 => use != be\n332 => this != the\n333 => s != a\n334 => use != be\n335 => that != the\n336 => the != to\n337 => 7 != a\n338 => a != man\n339 => on != and\n340 => at != to\n341 => at != a\n342 => tv != the\n343 => to != the\n344 => tv != so\n345 => use != be\n346 => that != the\n347 => tv != the\n348 => on != a\n349 => a != man\n350 => tv != of\n351 => the != he\n352 => or != your\n353 => its != to\n354 => app != and\n355 => for != to\n356 => a != in\n357 => s != tv\n358 => you != to\n359 => to != be\n360 => tv != or\n361 => 50 != to\n362 => a != be\n363 => has != he\n364 => an != to\n365 => to != the\n366 => and != in\n367 => it != a\n368 => a != to\n369 => rob != for\n370 => a != to\n371 => d != and\n372 => c != a\n373 => a != to\n374 => e != of\n375 => at != and\n376 => him != it\n377 => on != is\n378 => s != is\n379 => got != to\n380 => or != for\n381 => now != not\n382 => be != to\n383 => able != be\n384 => to != the\n385 => and != a\n386 => these != the\n387 => to != now\n388 => be != he\n389 => as != had\n390 => as != and\n391 => so != to\n392 => and != a\n393 => it != to\n394 => in != and\n395 => in != of\n396 => if != to\n397 => the != be\n398 => or != for\n399 => one != he\n400 => to != a\n401 => you != of\n402 => to != you\n403 => a != it\n404 => s != is\n405 => ios != his\n406 => a != so\n407 => an != so\n408 => said != and\n409 => in != of\n410 => at != and\n411 => said != and\n412 => in != a\n413 => an != man\n414 => to != the\n415 => not != you\n416 => a != to\n417 => on != to\n418 => the != be\n419 => one != the\n420 => are != have\n421 => than != the\n422 => is != of\n423 => in != and\n424 => a != be\n425 => in != of\n426 => air != and\n427 => in != and\n428 => 3 != in\n429 => in != and\n430 => for != of\n431 => ag != and\n432 => in != of\n433 => not != it\n434 => as != and\n435 => the != to\n436 => a != way\n437 => on != and\n438 => due != the\n439 => the != be\n440 => on != to\n441 => the != be\n442 => no != a\n443 => than != the\n444 => the != than\n445 => said != and\n446 => its != it\n447 => is != as\n448 => to != the\n449 => at != and\n450 => 3 != to\n451 => in != to\n452 => the != be\n453 => to != the\n454 => its != is\n455 => on != of\n456 => this != his\n457 => in != s\n458 => can != and\n459 => so != tv\n460 => one != and\n461 => of != k5\n462 => u != he\n463 => a != be\n464 => the != other\n465 => u != he\n466 => law != a\n467 => t != he\n468 => in != by\n469 => if != he\n470 => was != is\n471 => do != be\n472 => u != of\n473 => u != he\n474 => had != and\n475 => to != a\n476 => hand != man\n477 => the != to\n478 => for != to\n479 => the != be\n480 => by != of\n481 => to != in\n482 => case != same\n483 => are != the\n484 => they != the\n485 => have != he\n486 => no != to\n487 => s != he\n488 => as != of\n489 => in != as\n490 => is != in\n491 => in != to\n492 => to != in\n493 => act != a\n494 => the != to\n495 => said != had\n496 => an != to\n497 => in != of\n498 => it != of\n499 => for != to\n500 => to != in\n501 => act != a\n502 => to != of\n503 => take != the\n504 => case != same\n505 => for != not\n506 => s != of\n507 => is != he\n508 => in != is\n509 => on != to\n510 => the != be\n511 => the != he\n512 => the != her\n513 => to != of\n514 => in != and\n515 => are != at\n516 => to != not\n517 => is != in\n518 => to != the\n519 => the != to\n520 => the != he\n521 => the != be\n522 => a != of\n523 => to != the\n524 => for != of\n525 => a != to\n526 => the != he\n527 => u != he\n528 => law != a\n529 => no != to\n530 => in != he\n531 => their != the\n532 => its != in\n533 => or != of\n534 => a != it\n535 => more != for\n536 => to != of\n537 => what != that\n538 => is != to\n539 => it != to\n540 => it != is\n541 => is != it\n542 => that != the\n543 => buy != be\n544 => as != of\n545 => are != and\n546 => buy != be\n547 => an != a\n548 => a != and\n549 => t != be\n550 => be != the\n551 => of != it\n552 => in != of\n553 => end != and\n554 => up != a\n555 => buy != be\n556 => it != i\n557 => win != man\n558 => in != and\n559 => the != he\n560 => if != i\n561 => stop != ship\n562 => it != of\n563 => to != in\n564 => in != a\n565 => an != or\n566 => this != the\n567 => time != same\n568 => s != of\n569 => more != for\n570 => t != be\n571 => his != him\n572 => this != the\n573 => a != to\n574 => to != a\n575 => is != of\n576 => as != if\n577 => his != he\n578 => in != and\n579 => t != i\n580 => rape != have\n581 => has != had\n582 => in != and\n583 => way != man\n584 => not != you\n585 => more != are\n586 => are != and\n587 => as != and\n588 => and != as\n589 => is != he\n590 => i != is\n591 => it != i\n592 => t != i\n593 => as != and\n594 => us != a\n595 => it != i\n596 => the != he\n597 => the != he\n598 => can != and\n599 => t != a\n600 => i != so\n601 => it != i\n602 => if != he\n603 => re != were\n604 => go != not\n605 => was != had\n606 => of != an\n607 => as != of\n608 => a != to\n609 => he != is\n610 => re != were\n611 => he != is\n612 => and != a\n613 => re != were\n614 => the != to\n615 => i != a\n616 => don != man\n617 => t != s\n618 => it != i\n619 => a != to\n620 => man != and\n621 => he != i\n622 => not != to\n623 => all != and\n624 => of != a\n625 => as != and\n626 => is != of\n627 => there != the\n628 => in != of\n629 => s != is\n630 => a != to\n631 => there != the\n632 => no != a\n633 => do != of\n634 => in != a\n635 => in != of\n636 => the != her\n637 => she != he\n638 => get != be\n639 => the != to\n640 => it != of\n641 => a != of\n642 => in != as\n643 => or != of\n644 => want != was\n645 => to != a\n646 => do != be\n647 => a != to\n648 => or != of\n649 => a != if\n650 => a != way\n651 => them != the\n652 => it != to\n653 => man != and\n654 => to != so\n655 => in != and\n656 => his != if\n657 => don != in\n658 => by != be\n659 => and != a\n660 => t != i\n ='( Ahora si )'=\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4a94188e2e39c5b6715a88ebef5add4680e3e30f
| 878,519 |
ipynb
|
Jupyter Notebook
|
verbose/alphafold_noTemplates_noMD.ipynb
|
pstansfeld/ColabFold
|
b33126662b7ddba98d7640aa51bef275c336985f
|
[
"MIT"
] | 2 |
2021-09-26T23:53:13.000Z
|
2022-01-08T03:06:21.000Z
|
verbose/alphafold_noTemplates_noMD.ipynb
|
pstansfeld/ColabFold
|
b33126662b7ddba98d7640aa51bef275c336985f
|
[
"MIT"
] | null | null | null |
verbose/alphafold_noTemplates_noMD.ipynb
|
pstansfeld/ColabFold
|
b33126662b7ddba98d7640aa51bef275c336985f
|
[
"MIT"
] | 1 |
2022-02-21T07:06:42.000Z
|
2022-02-21T07:06:42.000Z
| 1,016.804398 | 174,929 | 0.506185 |
[
[
[
"<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/verbose/alphafold_noTemplates_noMD.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"#AlphaFold",
"_____no_output_____"
]
],
[
[
"#################\n# WARNING \n#################\n# - This notebook is intended as a \"quick\" demo, it disables many aspects of the full alphafold2 pipeline \n# (input MSA/templates, amber MD refinement, and number of models). For best results, we recommend using the\n# full pipeline: https://github.com/deepmind/alphafold\n# - That being said, it was found that input templates and amber-relax did not help much.\n# The key input features are the MSA (Multiple Sequence Alignment) of related proteins. Where you see a \n# significant drop in predicted accuracy when MSA < 30, but only minor improvements > 100. \n# - This notebook does NOT include the alphafold2 MSA generation pipeline, and is designed to work with a\n# single sequence, custom MSA input (that you can upload) or MMseqs2 webserver.\n# - Single sequence mode is particularly useful for denovo designed proteins (where there are no sequence\n# homologs by definition). For natural proteins, an MSA input will make a huge difference.\n\n#################\n# EXTRA\n#################\n# For other related notebooks see: https://github.com/sokrypton/ColabFold",
"_____no_output_____"
],
[
"# install/import alphafold (and required libs)\nimport os, sys\nif not os.path.isdir(\"/content/alphafold\"):\n %shell git clone -q https://github.com/deepmind/alphafold.git; cd alphafold; git checkout -q 1d43aaff941c84dc56311076b58795797e49107b\n %shell mkdir --parents params; curl -fsSL https://storage.googleapis.com/alphafold/alphafold_params_2021-07-14.tar | tar x -C params\n %shell pip -q install biopython dm-haiku==0.0.5 ml-collections py3Dmol\nif '/content/alphafold' not in sys.path:\n sys.path.append('/content/alphafold')\n\nimport numpy as np\nimport py3Dmol\nimport matplotlib.pyplot as plt\n\nfrom alphafold.common import protein\nfrom alphafold.data import pipeline\nfrom alphafold.data import templates\nfrom alphafold.model import data\nfrom alphafold.model import config\nfrom alphafold.model import model",
"_____no_output_____"
],
[
"# setup which model params to use\n# note: for this demo, we only use model 1, for all five models uncomments the others!\nmodel_runners = {}\nmodels = [\"model_1\"] #,\"model_2\",\"model_3\",\"model_4\",\"model_5\"]\nfor model_name in models:\n model_config = config.model_config(model_name)\n model_config.data.eval.num_ensemble = 1\n model_params = data.get_model_haiku_params(model_name=model_name, data_dir=\".\")\n model_runner = model.RunModel(model_config, model_params)\n model_runners[model_name] = model_runner",
"_____no_output_____"
],
[
"def mk_mock_template(query_sequence):\n '''create blank template'''\n ln = len(query_sequence)\n output_templates_sequence = \"-\"*ln\n templates_all_atom_positions = np.zeros((ln, templates.residue_constants.atom_type_num, 3))\n templates_all_atom_masks = np.zeros((ln, templates.residue_constants.atom_type_num))\n templates_aatype = templates.residue_constants.sequence_to_onehot(output_templates_sequence,templates.residue_constants.HHBLITS_AA_TO_ID)\n template_features = {'template_all_atom_positions': templates_all_atom_positions[None],\n 'template_all_atom_masks': templates_all_atom_masks[None],\n 'template_aatype': np.array(templates_aatype)[None],\n 'template_domain_names': [f'none'.encode()]}\n return template_features",
"_____no_output_____"
],
[
"def predict_structure(prefix, feature_dict, model_runners, random_seed=0): \n \"\"\"Predicts structure using AlphaFold for the given sequence.\"\"\"\n\n # Run the models.\n plddts = {}\n for model_name, model_runner in model_runners.items():\n processed_feature_dict = model_runner.process_features(feature_dict, random_seed=random_seed)\n prediction_result = model_runner.predict(processed_feature_dict)\n unrelaxed_protein = protein.from_prediction(processed_feature_dict,prediction_result)\n unrelaxed_pdb_path = f'{prefix}_unrelaxed_{model_name}.pdb'\n plddts[model_name] = prediction_result['plddt']\n\n print(f\"{model_name} {plddts[model_name].mean()}\")\n\n with open(unrelaxed_pdb_path, 'w') as f:\n f.write(protein.to_pdb(unrelaxed_protein))\n return plddts",
"_____no_output_____"
]
],
[
[
"# Single sequence input (no MSA)",
"_____no_output_____"
]
],
[
[
"# Change this line to sequence you want to predict\nquery_sequence = \"GWSTELEKHREELKEFLKKEGITNVEIRIDNGRLEVRVEGGTERLKRFLEELRQKLEKKGYTVDIKIE\"",
"_____no_output_____"
],
[
"%%time\nfeature_dict = {\n **pipeline.make_sequence_features(sequence=query_sequence,\n description=\"none\",\n num_res=len(query_sequence)),\n **pipeline.make_msa_features(msas=[[query_sequence]],\n deletion_matrices=[[[0]*len(query_sequence)]]),\n **mk_mock_template(query_sequence)\n}\nplddts = predict_structure(\"test\",feature_dict,model_runners)",
"model_1 83.72061105785679\nCPU times: user 6min 43s, sys: 10.4 s, total: 6min 54s\nWall time: 4min 44s\n"
],
[
"# confidence per position\nplt.figure(dpi=100)\nfor model,value in plddts.items():\n plt.plot(value,label=model)\nplt.legend()\nplt.ylim(0,100)\nplt.ylabel(\"predicted LDDT\")\nplt.xlabel(\"positions\")\nplt.show()",
"_____no_output_____"
],
[
" p = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n p.addModel(open(\"test_unrelaxed_model_1.pdb\",'r').read(),'pdb')\n p.setStyle({'cartoon': {'color':'spectrum'}})\n p.zoomTo()\n p.show()",
"_____no_output_____"
],
[
" p = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n p.addModel(open(\"test_unrelaxed_model_1.pdb\",'r').read(),'pdb')\n p.setStyle({'cartoon': {'color':'spectrum'},'stick':{}})\n p.zoomTo()\n p.show()",
"_____no_output_____"
]
],
[
[
"# Custom MSA input",
"_____no_output_____"
]
],
[
[
"%%bash\n# for this demo we will download a premade MSA input\nwget -qnc --no-check-certificate https://gremlin2.bakerlab.org/db/ECOLI/fasta/P0A8I3.fas",
"_____no_output_____"
],
[
"msa, deletion_matrix = pipeline.parsers.parse_a3m(\"\".join(open(\"P0A8I3.fas\",\"r\").readlines()))\nquery_sequence = msa[0]",
"_____no_output_____"
],
[
"%%time\nfeature_dict = {\n **pipeline.make_sequence_features(sequence=query_sequence,\n description=\"none\",\n num_res=len(query_sequence)),\n **pipeline.make_msa_features(msas=[msa],deletion_matrices=[deletion_matrix]),\n **mk_mock_template(query_sequence)\n}\nplddts = predict_structure(\"yaaa\",feature_dict,model_runners)",
"model_1 97.32114682607497\nCPU times: user 8min 20s, sys: 57.6 s, total: 9min 18s\nWall time: 6min 44s\n"
],
[
"# confidence per position\nplt.figure(dpi=100)\nfor model,value in plddts.items():\n plt.plot(value,label=model)\nplt.legend()\nplt.ylim(0,100)\nplt.ylabel(\"predicted LDDT\")\nplt.xlabel(\"positions\")\nplt.show()",
"_____no_output_____"
],
[
" p = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n p.addModel(open(\"yaaa_unrelaxed_model_1.pdb\",'r').read(),'pdb')\n p.setStyle({'cartoon': {'color':'spectrum'}})\n p.zoomTo()\n p.show()",
"_____no_output_____"
]
],
[
[
"#MSA from MMseqs2",
"_____no_output_____"
]
],
[
[
"##############################\n# Where do I get an MSA?\n##############################\n# For any \"serious\" use, I would recommend using the alphafold2 pipeline to make the MSAs, \n# since this is what it was trained on. \n\n# That being said, part of the MSA generation pipeline (specifically searching against uniprot database using hhblits)\n# can be done here: https://toolkit.tuebingen.mpg.de/tools/hhblits\n# Alternatively, using the SUPER FAST MMseqs2 pipeline below\n\n# for a HUMAN FRIENDLY version see:\n# https://colab.research.google.com/drive/1LVPSOf4L502F21RWBmYJJYYLDlOU2NTL",
"_____no_output_____"
],
[
"%%bash\napt-get -qq -y update 2>&1 1>/dev/null\napt-get -qq -y install jq curl zlib1g gawk 2>&1 1>/dev/null",
"_____no_output_____"
],
[
"# save query sequence to file\nname = \"YAII\"\nquery_sequence = \"MTIWVDADACPNVIKEILYRAAERMQMPLVLVANQSLRVPPSRFIRTLRVAAGFDVADNEIVRQCEAGDLVITADIPLAAEAIEKGAAALNPRGERYTPATIRERLTMRDFMDTLRASGIQTGGPDSLSQRDRQAFAAELEKWWLEVQRSRG\"\nwith open(f\"{name}.fasta\",\"w\") as out: out.write(f\">{name}\\n{query_sequence}\\n\")",
"_____no_output_____"
],
[
"%%bash -s \"$name\"\n# build msa using the MMseqs2 search server\nID=$(curl -s -F q=@$1.fasta -F mode=all https://a3m.mmseqs.com/ticket/msa | jq -r '.id')\nSTATUS=$(curl -s https://a3m.mmseqs.com/ticket/${ID} | jq -r '.status')\nwhile [ \"${STATUS}\" == \"RUNNING\" ]; do\n STATUS=$(curl -s https://a3m.mmseqs.com/ticket/${ID} | jq -r '.status')\n sleep 1\ndone\nif [ \"${STATUS}\" == \"COMPLETE\" ]; then\n curl -s https://a3m.mmseqs.com/result/download/${ID} > $1.tar.gz\n tar xzf $1.tar.gz\n tr -d '\\000' < uniref.a3m > $1.a3m\nelse\n echo \"MMseqs2 server did not return a valid result.\"\n exit 1\nfi\necho \"Found $(grep -c \">\" $1.a3m) sequences (after redundacy filtering)\"",
"Found 3090 sequences (after redundacy filtering)\n"
],
[
"msa, deletion_matrix = pipeline.parsers.parse_a3m(\"\".join(open(f\"{name}.a3m\",\"r\").readlines()))\nquery_sequence = msa[0]",
"_____no_output_____"
],
[
"%%time\nfeature_dict = {\n **pipeline.make_sequence_features(sequence=query_sequence,\n description=\"none\",\n num_res=len(query_sequence)),\n **pipeline.make_msa_features(msas=[msa],deletion_matrices=[deletion_matrix]),\n **mk_mock_template(query_sequence)\n}\nplddts = predict_structure(name,feature_dict,model_runners)",
"model_1 91.07940053970414\nCPU times: user 2min 24s, sys: 6.47 s, total: 2min 31s\nWall time: 2min 5s\n"
],
[
"plt.figure(dpi=100)\nplt.plot((feature_dict[\"msa\"] != 21).sum(0))\nplt.plot([0,len(query_sequence)],[30,30])\nplt.xlabel(\"positions\")\nplt.ylabel(\"number of sequences\")\nplt.show()",
"_____no_output_____"
],
[
"# confidence per position\nplt.figure(dpi=100)\nfor model,value in plddts.items():\n plt.plot(value,label=model)\nplt.legend()\nplt.ylim(0,100)\nplt.ylabel(\"predicted LDDT\")\nplt.xlabel(\"positions\")\nplt.show()",
"_____no_output_____"
],
[
" p = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n p.addModel(open(f\"{name}_unrelaxed_model_1.pdb\",'r').read(),'pdb')\n p.setStyle({'cartoon': {'color':'spectrum'}})\n p.zoomTo()\n p.show()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a9427f080c0574048652ff0d547a6a5f3b9a1c7
| 9,849 |
ipynb
|
Jupyter Notebook
|
nbs/00_first_steps.ipynb
|
aloiswirth/sort_fotos
|
1c2b29d1e8c65d062d245a716b7f8f311d9ea6b5
|
[
"Apache-2.0"
] | null | null | null |
nbs/00_first_steps.ipynb
|
aloiswirth/sort_fotos
|
1c2b29d1e8c65d062d245a716b7f8f311d9ea6b5
|
[
"Apache-2.0"
] | null | null | null |
nbs/00_first_steps.ipynb
|
aloiswirth/sort_fotos
|
1c2b29d1e8c65d062d245a716b7f8f311d9ea6b5
|
[
"Apache-2.0"
] | null | null | null | 22.384091 | 126 | 0.49406 |
[
[
[
"# default_exp first_steps",
"_____no_output_____"
]
],
[
[
"# First Steps\n\n> API details.",
"_____no_output_____"
]
],
[
[
"#hide\nfrom nbdev.showdoc import *",
"_____no_output_____"
],
[
"import os\n\nos.listdir(\"/home/alois\")",
"_____no_output_____"
],
[
"os.walk(\"$HOME\")",
"_____no_output_____"
],
[
"for item in os.walk((\"$HOME\")):\n print(item)",
"_____no_output_____"
]
],
[
[
"Apparently this does not work. So use the next try:",
"_____no_output_____"
]
],
[
[
"from os import listdir\nfrom os.path import isfile, join\nmypath = \"/home/alois\"\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\nonlyfiles",
"_____no_output_____"
]
],
[
[
"And shorter",
"_____no_output_____"
]
],
[
[
"from os import walk\n\nf = []\nfor (dirpath, dirnames, filenames) in walk(mypath):\n f.extend(filenames)\n break\nprint(\"filenames are\", filenames)\nprint(f)",
"_____no_output_____"
]
],
[
[
"More concise: ",
"_____no_output_____"
]
],
[
[
"from os import walk\n\nf = []\nfor (dirpath, dirnames, filenames) in walk(\"/home/alois\"):\n print(dirpath)\n print(dirnames)\n print(filenames)\n break",
"_____no_output_____"
],
[
"print(os.listdir(\"/media/mycloud/My Pictures\"))",
"_____no_output_____"
],
[
"from os import walk\nfor (dirpath, dirname, filename) in walk(\"/media/mycloud/My Pictures\"):\n print(dirpath)\n print(dirname)\n print(filename)\n break",
"_____no_output_____"
],
[
"def fast_scandir(dirname):\n subfolders= [f.path for f in os.scandir(dirname) if f.is_dir()]\n for dirname in (subfolders):\n subfolders.extend(fast_scandir(dirname))\n return subfolders",
"_____no_output_____"
],
[
"all_folders = fast_scandir(\"/media/mycloud/My Pictures\")",
"_____no_output_____"
],
[
"print(lenall_folders)",
"_____no_output_____"
],
[
"# -*- coding: utf-8 -*-\n# Python 3\n\n\nimport time\nimport os\nfrom glob import glob\nfrom pathlib import Path\n\n\ndirectory = r\"/media/mycloud/My Pictures\"\nRUNS = 1\n\ndef run_os_walk():\n a = time.time_ns()\n for i in range(RUNS):\n fu = [x[0] for x in os.walk(directory)]\n print(f\"os.walk\\t\\t\\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}\")\n return fu\n\n\ndef run_glob():\n a = time.time_ns()\n for i in range(RUNS):\n fu = glob(directory + \"/*/\")\n print(f\"glob.glob\\t\\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}\")\n\n\ndef run_pathlib_iterdir():\n a = time.time_ns()\n for i in range(RUNS):\n dirname = Path(directory)\n fu = [f for f in dirname.iterdir() if f.is_dir()]\n print(f\"pathlib.iterdir\\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}\")\n return fu\n\n\ndef run_os_listdir():\n a = time.time_ns()\n for i in range(RUNS):\n dirname = Path(directory)\n fu = [os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]\n print(f\"os.listdir\\t\\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}\")\n return fu\n\n\ndef run_os_scandir():\n a = time.time_ns()\n for i in range(RUNS):\n fu = [f.path for f in os.scandir(directory) if f.is_dir()]\n print(f\"os.scandir\\t\\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms.\\tFound dirs: {len(fu)}\")\n return fu\n\n\nif __name__ == '__main__':\n run_os_scandir()\n print(run_os_walk())\n run_glob()\n print(run_pathlib_iterdir())\n run_os_listdir()",
"_____no_output_____"
]
],
[
[
"The difference between \"walk\" and the others is that walk recognizes also the subfolders of the itunes library",
"_____no_output_____"
]
],
[
[
"with os.scandir() as dir_contents:\n for entry in dir_contents:\n info = entry.__dir__\n more_info = entry.stat()\n another_info = entry.inode()\n print(info)\n print(more_info, another_info)\n",
"_____no_output_____"
],
[
"import scandir",
"_____no_output_____"
],
[
"all_content = scandir.walk(\"/media/mycloud/My Pictures\")\nn = 0\nf = []\nprint(all_content)\nfor i in all_content:tures\")\n p\n n += 1\n f.append(i)rint(i)\n \n\nprint(n) break",
"_____no_output_____"
],
[
"print(len(f))\nfor dirpath, dirnames, filenames in f:\n print(filenames)",
"_____no_output_____"
],
[
"print(len(filenames))",
"_____no_output_____"
],
[
"from os import listdir\nfrom os.path import isfile, join, isdir\nmypath = \"/media/mycloud/My Pictures\"\nonlydirs = [f for f in listdir(mypath) if isdir(join(mypath, f))]\nprint(len(onlydirs), onlydirs)",
"_____no_output_____"
],
[
"absolute_path = \"/media/mycloud/\"",
"_____no_output_____"
],
[
"import glob\nfiles = []\nmyDir = mypath\nfor root, dirnames, filenames in os.walk(myDir):\n files.extend(glob.glob(root + \"/*\"))\n\nprint(len(files))\n\n",
"_____no_output_____"
],
[
"print(files[20:30])",
"_____no_output_____"
],
[
"from os import listdir\nfrom os.path import isfile, join\nmypath = \"/media/mycloud/My Pictures\"\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\nlen(onlyfiles)\n\nprint(onlyfiles[0:5])",
"_____no_output_____"
],
[
"import pandas as pd\n\ndf = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\nprint(df)\n\ndf2 = df.copy()\n\ndf2.rename(columns={\"A\": \"a\", \"B\": \"c\"})\ndf2",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a9428483b3151505fd6ff0276e03f7f772a22ac
| 17,699 |
ipynb
|
Jupyter Notebook
|
python/Personal Experience With Python.ipynb
|
simonada/Dev-Collection
|
830aa0dd8fa2ca3343d370cd4d3ec47a16153c1b
|
[
"MIT"
] | null | null | null |
python/Personal Experience With Python.ipynb
|
simonada/Dev-Collection
|
830aa0dd8fa2ca3343d370cd4d3ec47a16153c1b
|
[
"MIT"
] | null | null | null |
python/Personal Experience With Python.ipynb
|
simonada/Dev-Collection
|
830aa0dd8fa2ca3343d370cd4d3ec47a16153c1b
|
[
"MIT"
] | null | null | null | 26.980183 | 250 | 0.485621 |
[
[
[
"# Data Structures",
"_____no_output_____"
],
[
"## Pandas",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"### Preparation",
"_____no_output_____"
]
],
[
[
"# create dataframe with specific column names\ncorpus_df = pd.DataFrame(columns=['id', 'userurl', 'source', 'title', 'description', 'content', 'keywords'])",
"_____no_output_____"
],
[
"# append one row, fill by column name\ncorpus_df = corpus_df.append(\n {'id': 0, 'userurl': 'url', 'source': 'source', 'title': 'title',\n 'description': 'description', 'content': 'content',\n 'keywords': 'keywords'}, ignore_index=True)",
"_____no_output_____"
]
],
[
[
"### Transformation",
"_____no_output_____"
]
],
[
[
"# define new column, being the concatenation of other columns\ncorpus_df[\"text\"] = corpus_df[\"title\"].map(str) + ' ' + corpus_df[\"description\"] + ' ' + corpus_df[\n \"content\"].map(str) + ' ' + corpus_df[\"keywords\"]",
"_____no_output_____"
],
[
"# drop columns\ncorpus_df = corpus_df.drop(['source', 'userurl', 'title', 'description', 'keywords', 'content'], axis=1)",
"_____no_output_____"
],
[
"# concatenate dfs: https://stackoverflow.com/questions/32444138/combine-a-list-of-pandas-dataframes-to-one-pandas-dataframe\ndf = pd.concat(list_of_dataframes)",
"_____no_output_____"
]
],
[
[
"### Storing/ Reading",
"_____no_output_____"
]
],
[
[
"# write and read csv\nfile_name = 'test.csv'\ncorpus_df.to_csv(file_name, sep='\\t')\n# diff encoding\ncorpus_df.to_csv(file_name, sep='\\t', encoding='utf-8')\n# without index values\ncorpus_df.to_csv(file_name, encoding='utf-8', index=False)\n# append\nwith open(file_name, 'a') as f:\n df.to_csv(f, header=False)\n# load\ndf_corpus = pd.read_csv(file_name, delimiter='\\t')",
"_____no_output_____"
],
[
"# merging \ncomparison = pd.merge(results_sap, results_doc2vec, how='inner', on=['doc_id']) # if on is not specified, it is done on the index?",
"_____no_output_____"
]
],
[
[
"## Dictionaries",
"_____no_output_____"
]
],
[
[
"#https://stackoverflow.com/questions/4530611/saving-and-loading-objects-and-using-pickle\nwith open(r\"someobject.pickle\", \"wb\") as output_file:\n cPickle.dump(d, output_file)",
"_____no_output_____"
],
[
"with open(r\"someobject.pickle\", \"rb\") as input_file:\n e = cPickle.load(input_file)",
"_____no_output_____"
],
[
"#https://stackoverflow.com/questions/3108042/get-max-key-in-\nmax(dict_m, key=int)",
"_____no_output_____"
],
[
"# get value by key, where the values are tuples!\ndef get_url_key(url_to_find):\n url_key = -1\n for key, value in docs_dict.items():\n if value[0][0] == url_to_find:\n url_key = key\n return url_key",
"_____no_output_____"
],
[
"#https://stackoverflow.com/questions/32957708/python-pickle-error-unicodedecodeerror\n#https://stackoverflow.com/questions/9415785/merging-several-python-dictionaries",
"_____no_output_____"
]
],
[
[
"# Networ Communication\n- Interacting with the outside world",
"_____no_output_____"
],
[
"## DB",
"_____no_output_____"
]
],
[
[
"import sys\nsys.executable\n!{sys.executable} -m pip install pyhdb",
"_____no_output_____"
],
[
"connection = pyhdb.connect(host=\"<mo-6770....>\", port=<port>, user=\"<user>\", password=\"<pass>\") # dummy ",
"_____no_output_____"
],
[
"cursor = connection.cursor()",
"_____no_output_____"
],
[
"# sample query construction\nquery = ''' SELECT \"USERURL\",\"TITLE\", \"CONTENT\", \"DESCRIPTION\", \"SOURCE\",\"KEYWORDS\"\n FROM REPO_.\"T.CONTENT\" \n '''",
"_____no_output_____"
],
[
"# count how many rows match the query\nN = cursor.execute(\"SELECT COUNT(*) FROM (\" + query + \")\").fetchone()[0]\n print('Fetching ', N, ' documents...')",
"_____no_output_____"
],
[
"cursor.execute(query)",
"_____no_output_____"
],
[
"# work row by row\nfor i in range(N):\n try:\n row = cursor.fetchone()\n\n if i % 10000 == 0:\n print('Processing document ', i)\n if row[0] is not None:\n userurl = row[0]\n else:\n userurl = \"\"\n except UnicodeDecodeError:\n continue\n except UnicodeEncodeError:\n continue",
"_____no_output_____"
],
[
"# fetch all rows\nresults = cursor.fetchall()",
"_____no_output_____"
],
[
"#http://thepythonguru.com/fetching-records-using-fetchone-and-fetchmany/",
"_____no_output_____"
]
],
[
[
"## HTTP",
"_____no_output_____"
]
],
[
[
"import requests\nimport json",
"_____no_output_____"
],
[
"user = 'client'\npassw = 'dummypass'\nurl = 'https://<search>.com/api/v1/search'\nheaders = {'Content-Type': 'application/json'}",
"_____no_output_____"
],
[
"request_body = get_api_body(query)\nresp = requests.post(url, data=request_body, auth=(user, passw), headers=headers)\nresp_json = resp.json()\nresults = resp_json['result']",
"_____no_output_____"
],
[
"def get_api_body(self, query):\n data = ''' {\n \"repository\": \"srh\",\n \"type\": \"content\",\n \"filters\": [{\n \"field\": \"CONTENT\",\n \"type\": \"fuzzy\",\n \"values\": [\"''' + query + '''\"],\n \"fuzzy\": {\n \"level\": 0.9,\n \"weight\": 0.2,\n \"parameters\": \"def\"\"\n },\n \"logicalOperator\": \"or\"\n },\n {\n \"field\": \"TITLE\",\n \"type\": \"fuzzy\",\n \"values\": [\"''' + query + '''\"],\n \"fuzzy\": {\n \"level\": 0.9,\n \"weight\": 1,\n \"parameters\": \"def\"\"\n }\n }\n '''\n return data",
"_____no_output_____"
],
[
"# results being an array of separate JSON objects\ndef get_results_as_df(self, results):\n results_df = pd.DataFrame(columns=['doc_id', 'userurl', 'title'])\n # results[i] to access each subsequent/ separate JSON element\n for i in range(len(results)):\n results_df = results_df.append(\n {'doc_id': doc_id, 'userurl': results[i]['USERURL'], 'title': results[i]['TITLE'],\n 'keywords': results[i]['KEYWORDS']}, ignore_index=True)\n return results_df",
"_____no_output_____"
]
],
[
[
"# Hardware Utilization\n- usefull to check effects is htop, e.g. see https://peteris.rocks/blog/htop/",
"_____no_output_____"
]
],
[
[
"# results being a list of tuple(any) elements\ndef get_pool_data(results):\n \n pool = mp.Pool()\n deserialized_results_list = list(map(deserialize, results))\n \n results_mp = pool.map(preprocess_row, deserialized_results_list) \n df_global = pd.concat(results_mp)\n \n return df_global",
"_____no_output_____"
]
],
[
[
"# Web Deployment with Flask\n- small search & table view example",
"_____no_output_____"
]
],
[
[
"import logging\nlogging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S')\nlogger = logging.getLogger(__name__)\n\nimport os\nimport json\n\nfrom os.path import dirname, realpath\nfrom doc2vec_search import Doc2VecSearch\nfrom time import time\nfrom flask import Flask, Response, request\n\nPATH_TO_MODEL = \"data/models/model_dbow_100_10_no_ppl.d2v\"\nPATH_TO_DICT = \"data/dict/docs_dict.pickle\"\n\nif 'is_docker' in os.environ:\n CWD = \"/app/data\"\nelse:\n CWD = dirname(dirname(realpath(__file__))) + \"/data\"\n\napp = Flask(__name__, template_folder=dirname(realpath(__file__)))\n\ndoc2vec = Doc2VecSearch(PATH_TO_MODEL, PATH_TO_DICT)\nurl = \"/unique/search\"\n\[email protected](url, methods=['GET'])\ndef doc2vec_search():\n q = request.args.get('q')\n\n exec_time = 0\n response = dict()\n\n if q:\n q = q.lower()\n start = time()\n results = doc2vec.search(q, 10)\n exec_time = int((time() - start) * 1000)\n\n if results:\n for i in range(len(results)):\n response['data'+str(i)] = [{'userurl': results[i][0], 'title': results[i][1], 'keywords': results[i][2],\n 'source': results[i][3]}]\n response['metadata'+str(i)] = {'executionTime': exec_time, 'status': 200, 'itemCount': 1}\n return Response(json.dumps(response, indent=2), status=200, mimetype='application/json')\n\n response['data'] = []\n response['metadata'] = {'executionTime': exec_time, 'status': 200, 'itemCount': 0}\n return Response(json.dumps(response, indent=2), status=200, mimetype='application/json')\n\n\[email protected]('/healthcheck')\ndef healthckeck():\n return \"All is well\"\n\[email protected]('/' + 'pointer/testing')\ndef testing():\n page = \"\"\"\n <!DOCTYPE html>\n <html>\n <head>\n <link rel=\"stylesheet\" href=\"https://www.w3schools.com/w3css/4/w3.css\">\n </head>\n <body>\n <form>\n <input name=\"query\" autofocus>\n <input type=\"submit\">\n Number of results to show:\n <input name=\"n\">\n </form>\n <br>\n \"\"\"\n\n q = request.args.get('query')\n n = request.args.get('n')\n\n if q:\n q = q.lower().strip()\n page += \"Current query: <b><i>\" + q + \"</i></b><br>\\n\"\n\n if n:\n n = int(n)\n results = doc2vec.search(q, n)\n else:\n results = doc2vec.search(q, 10)\n\n page += \"<h2>Doc2Vec Search Results</h2>\"\n page += \"\"\"<table class=\"w3-table-all\"><tr><th></th><th>Userurl</th><th>Title</th><th>Keywords</th><th>Source</th><th>Similarity Score</th></tr>\"\"\"\n\n if results:\n for i in range(len(results)):\n page += \"<tr><td>\" + str(i) + \"</td><td>\" + results[i][0] + \"</td><td>\" + results[i][1] + \"</td><td>\" + results[i][2] + \"</td><td>\" + results[i][3]+ \"</td><td>\" + \"{0:.2f}\".format(results[i][4]) + \"</td><tr>\"\n page += \"</table>\"\n return page + \"</body></html>\"\n\nif __name__ == \"__main__\":\n # This is only called when starting file directly. Not in Docker container.\n logger.info(\"Api is ready. Try: http://localhost:5021/test/doc2vec?q=mster%20data%20mannagemnt\")\n app.run(port=5021)",
"_____no_output_____"
]
],
[
[
"# Useful things",
"_____no_output_____"
],
[
"- https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/\n- https://jakevdp.github.io/PythonDataScienceHandbook/01.05-ipython-and-shell-commands.html",
"_____no_output_____"
]
],
[
[
"for i in range(n):\n if i < 136000:\n print('skiping ',i)\n continue",
"_____no_output_____"
],
[
"import time\n\nstart = time.time()\nprint(\"hello\")\nend = time.time()\nprint(end - start)",
"_____no_output_____"
],
[
"import glob, os\ncount = 1\n# Read in all files from the current directory, that match the prefix. \nfor file in glob.glob(\"archive_sitemap_*\"):\n print(file)",
"_____no_output_____"
],
[
"#https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty\nif not a:\n print(\"List is empty\")",
"_____no_output_____"
],
[
"# Screen and Sessions\n# https://stackoverflow.com/questions/1509677/kill-detached-screen-session",
"_____no_output_____"
],
[
"# Remote connections\n#https://superuser.com/questions/23911/running-commands-on-putty-without-fear-of-losing-connection",
"_____no_output_____"
]
]
] |
[
"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"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a9442686d23b3f33236af4212663a5e96615334
| 138,402 |
ipynb
|
Jupyter Notebook
|
numpy/fancy_indexing.ipynb
|
Jeffresh/python-datascience-handbook
|
e3a14280c324782c323db73924e7495ee570029e
|
[
"MIT"
] | null | null | null |
numpy/fancy_indexing.ipynb
|
Jeffresh/python-datascience-handbook
|
e3a14280c324782c323db73924e7495ee570029e
|
[
"MIT"
] | null | null | null |
numpy/fancy_indexing.ipynb
|
Jeffresh/python-datascience-handbook
|
e3a14280c324782c323db73924e7495ee570029e
|
[
"MIT"
] | null | null | null | 177.666239 | 32,033 | 0.696356 |
[
[
[
"# Fancy Indexing\n\nIn the previous sections, we saw how to access and modify portions of arrays using simple indices `(arr[0])`, `slices(arr[:5])`, and Boolean masks `(arr[arr > 0])`. In this section, we'll llok at another style of array indexing, known as *fancy indexing*. Fancy indexing islike the simple indexing we've already seen, but we pass arrays of indices in place of single scalars. this allows us to very quickly access and modify copmlicated subsets of an array's values.",
"_____no_output_____"
],
[
"## Exploring Fancy Indexing\n\nFancy indexing is conceptually sipmle: it means passing and array of indices to access multiple array elements at once. For example, consider the following array:",
"_____no_output_____"
]
],
[
[
"import numpy as np \nrand = np.random.RandomState(42)\n\nx = rand.randint(100, size=10)\nprint(x)",
"[51 92 14 71 60 20 82 86 74 74]\n"
]
],
[
[
"Suppose we want to access three different elements. We could do it like this:",
"_____no_output_____"
]
],
[
[
"[x[3], x[7], x[2]]",
"_____no_output_____"
]
],
[
[
"When using fancy indexing, the shape of the result reflects the shape of the index arrays rather than the shape of the array being indexed:",
"_____no_output_____"
]
],
[
[
"ind = np.array([[3, 7], [4, 5]])",
"_____no_output_____"
],
[
"x[ind]",
"_____no_output_____"
]
],
[
[
"Fancy indexing also works in multiple dimensions. Consider the following array:",
"_____no_output_____"
]
],
[
[
"X = np.arange(12).reshape((3, 4))\nX",
"_____no_output_____"
]
],
[
[
"Like with standard indexing, the first index refers to the row, and the second to the column:",
"_____no_output_____"
]
],
[
[
"row = np.array([0, 1, 2])\ncol = np.array([2, 1, 3])\nX[row, col]",
"_____no_output_____"
]
],
[
[
"Notice that the first value in the result is `X[0, 2]`, the seconds is `X[1, 1]`, and the third is `X[2, 3]`. The pairing of the indices in fancy indexing follows all the broadcasting rules that were mentioned. So for example, if we combine a column vector and a row vector within the indices, we get a two-dimensional result:",
"_____no_output_____"
]
],
[
[
"X[row[:, np.newaxis], col]",
"_____no_output_____"
]
],
[
[
"Here, each row value is matched with each column vector, exactly as we saw in broadcasting of arithmetic operations. For example:",
"_____no_output_____"
]
],
[
[
"row[:, np.newaxis] * col",
"_____no_output_____"
]
],
[
[
"It is always important to remember with fancy indexing that the return value deflects the *broadcasted shape of the indices*, rather than the shape of the array being indexed",
"_____no_output_____"
],
[
"## Combined Indexing\nFor even more powerful operations, fancy indexing can be combined with the other indexing schemes we've seen:",
"_____no_output_____"
]
],
[
[
"print(X)",
"[[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n"
]
],
[
[
"We can also combine fancy indexing with slicing:",
"_____no_output_____"
]
],
[
[
"X[1:, [2, 0, 1]]",
"_____no_output_____"
]
],
[
[
"And we can combine fancy indexing with masking:",
"_____no_output_____"
]
],
[
[
"mask = np.array([1, 0, 1, 0], dtype=bool)\nX[row[:, np.newaxis], mask]",
"_____no_output_____"
]
],
[
[
"All of these indexing options combined lead to a very flexible set of operations for accessing and modifying array values.",
"_____no_output_____"
],
[
"## Example: Selecting Random Points\nOne common use of fancy indexing is the selection of subsets of rows from a matrix.\nFor example, we might have an **N** by **D** matrix representing **N** points in **D** dimensions, such as the following points \ndraw from a two-dimensional normal distribution:",
"_____no_output_____"
]
],
[
[
"mean = [0, 0]\ncov = [[1, 2], [2, 5]]\nX = rand.multivariate_normal(mean, cov, 100)\nX.shape",
"_____no_output_____"
]
],
[
[
"Using the plotting tools, we can visualize these points as a scatter-plot:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt \nimport seaborn; seaborn.set() # for plot styling \nplt.scatter(X[:, 0], X[:, 1])",
"_____no_output_____"
]
],
[
[
"Let's use fancy indexing to select 20 random points. We'll do this by first choosing 20 random indices with no repetas, and sue these indices to seelct a portion of original array:",
"_____no_output_____"
]
],
[
[
"indices = np.random.choice(X.shape[0], 20, replace=False)\nindices",
"_____no_output_____"
],
[
"selection = X[indices] # fancy indexing here \nselection.shape",
"_____no_output_____"
]
],
[
[
"Now to see which points were selected, let's over-plot large circles at the locations of the selected points:",
"_____no_output_____"
]
],
[
[
"plt.scatter(X[:, 0], X[:, 1], alpha=0.3)\nplt.scatter(selection[:, 0], selection[:, 1], facecolor='none', s=200);",
"_____no_output_____"
]
],
[
[
"## Modifying Values with Fancy Indexing\n\nJust as fancy indexing can be used to access parts of an array, it can also be used to modify parts of an array. For example, image we have an array of indices and we'd like to set the corresponding items in an array to some value:\n",
"_____no_output_____"
]
],
[
[
"x = np.arange(10)\ni = np.array([2, 1, 8, 4])\nx[i] = 99\nprint(x)",
"[ 0 99 99 3 99 5 6 7 99 9]\n"
]
],
[
[
"We can use any assignment-type operator for this. For example:",
"_____no_output_____"
]
],
[
[
"x[i] -= 10\nprint(x)",
"[ 0 89 89 3 89 5 6 7 89 9]\n"
]
],
[
[
"Notice, though, the repeated indices with these operations can cause some potentially unexpected results. Consider the following:",
"_____no_output_____"
]
],
[
[
"x = np.zeros(10)\nx[[0, 0]] = [4, 6]\nprint(x)",
"[6. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n"
]
],
[
[
"Where did the 4 go? The results of this operation is to first assign `x[0] = 4`, folowed b `x[0] = 6`. The result, of course, is that `x[0]`, followed by `x[0] = 6`. The result, of course, is that `x[0]` contains the value 6.\n\nFair enough, but consider this operation:",
"_____no_output_____"
]
],
[
[
"i = [2, 3, 3, 4, 4, 4]\nx[i] += 1\nx",
"_____no_output_____"
]
],
[
[
"You migth expect that `x[3]` would contain the value 2, and `x[4]` would contain the value 3, as this is how many times each index is repeated. Why is this not the case? Conceptually, this is because `x[i] += 1` is mean as a shorthand of `x[i] = x[i] + 1. x[i] + 1` is evaluated, and then the result is assigned to the indices in x. With this in mind, it is not the augmentation that happens multiple times, but the assignment, which leads to the rather nonintuitive results.\n\nSo what if you want the other behavior where the operation is repeated? For this you can use the `at()` method of ufuncs, and do the following:",
"_____no_output_____"
]
],
[
[
"x = np.zeros(10)\nnp.add.at(x, i, 1)\nprint(x)",
"[0. 0. 1. 2. 3. 0. 0. 0. 0. 0.]\n"
]
],
[
[
"The `at()` method does an in-place application of the given operator at the specified indices(here, `i`) with the specified value(here, 1). Another method that is simi;ar in spirit is the `reduceat()`.",
"_____no_output_____"
],
[
"## Binning Data\n\nYou can use these ideas to efficiently bin data to create a histogram by hand. For exmpale imagine we have 1,000 values and would like to quickly find where they fall within an array of bins. WE could compute it using `ufunc.at` like this:",
"_____no_output_____"
]
],
[
[
"np.random.seed(42)\nx = np.random.randn(100)\n\n# compute a histogram by hand\n\nbins = np.linspace(-5, 5, 20)\ncounts = np.zeros_like(bins)\n\n# find the appropriate bin for each x\n\ni = np.searchsorted(bins, x)\n\n# add 1 to each of these bins\n\nnp.add.at(counts, i, 1)",
"_____no_output_____"
]
],
[
[
"The counts now reflect the number of poitns within each bin-in other words, a histogram:",
"_____no_output_____"
]
],
[
[
"# plot the results \nplt.plot(bins, counts, drawstyle='steps');",
"_____no_output_____"
],
[
"plt.hist(x, bins, histtype='step');",
"_____no_output_____"
],
[
"print(\"NumPy routine:\")\n%timeit counts, edges = np.histogram(x, bins)\n\nprint(\"Custom routine:\")\n%timeit np.add.at(counts, np.searchsorted(bins, x), 1)",
"NumPy routine:\n27.2 µs ± 4.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\nCustom routine:\n14.9 µs ± 1.39 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
]
],
[
[
"The custom method is sevearl time faster thant the optimized algorithm in NumPy.",
"_____no_output_____"
]
],
[
[
"x = np.random.randn(1000000)\nprint(\"NumPy routine:\")\n%timeit counts, edges = np.histogram(x, bins)\n\nprint(\"Custom routine:\")\n%timeit np.add.at(counts, np.searchsorted(bins, x), 1)",
"NumPy routine:\n59.8 ms ± 3.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\nCustom routine:\n105 ms ± 7.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
],
[
[
"But as you can see, NumPy function is designed for better performance when the number of data points becomes large.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4a9443fbd21e67fdf26673d354be083fa5d97f8e
| 28,539 |
ipynb
|
Jupyter Notebook
|
tutorial_examples.ipynb
|
danieltgustafson/mlrose_cust
|
03c6dbcee9fa0bfd3c9e9c92b515d9b1dbddfadd
|
[
"BSD-3-Clause"
] | 1 |
2019-02-20T20:21:40.000Z
|
2019-02-20T20:21:40.000Z
|
tutorial_examples.ipynb
|
danieltgustafson/mlrose_cust
|
03c6dbcee9fa0bfd3c9e9c92b515d9b1dbddfadd
|
[
"BSD-3-Clause"
] | null | null | null |
tutorial_examples.ipynb
|
danieltgustafson/mlrose_cust
|
03c6dbcee9fa0bfd3c9e9c92b515d9b1dbddfadd
|
[
"BSD-3-Clause"
] | 1 |
2019-02-25T06:34:51.000Z
|
2019-02-25T06:34:51.000Z
| 22.365987 | 287 | 0.502646 |
[
[
[
"# mlrose Tutorial Examples - Genevieve Hayes",
"_____no_output_____"
],
[
"## Overview",
"_____no_output_____"
],
[
"mlrose is a Python package for applying some of the most common randomized optimization and search algorithms to a range of different optimization problems, over both discrete- and continuous-valued parameter spaces. This notebook contains the examples used in the mlrose tutorial.",
"_____no_output_____"
],
[
"### Import Libraries",
"_____no_output_____"
]
],
[
[
"import mlrose\nimport numpy as np\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler, OneHotEncoder\nfrom sklearn.metrics import accuracy_score",
"_____no_output_____"
]
],
[
[
"### Example 1: 8-Queens Using Pre-Defined Fitness Function",
"_____no_output_____"
]
],
[
[
"# Initialize fitness function object using pre-defined class\nfitness = mlrose.Queens()",
"_____no_output_____"
],
[
"# Define optimization problem object\nproblem = mlrose.DiscreteOpt(length = 8, fitness_fn = fitness, maximize=False, max_val=8)",
"_____no_output_____"
],
[
"# Define decay schedule\nschedule = mlrose.ExpDecay()",
"_____no_output_____"
],
[
"# Solve using simulated annealing - attempt 1\nnp.random.seed(1)\n \ninit_state = np.array([0, 1, 2, 3, 4, 5, 6, 7])\nbest_state, best_fitness = mlrose.simulated_annealing(problem, schedule = schedule, max_attempts = 10, \n max_iters = 1000, init_state = init_state)",
"_____no_output_____"
],
[
"print(best_state)",
"[6 4 7 3 6 2 5 1]\n"
],
[
"print(best_fitness)",
"2.0\n"
],
[
"# Solve using simulated annealing - attempt 2\nnp.random.seed(1)\n\nbest_state, best_fitness = mlrose.simulated_annealing(problem, schedule = schedule, max_attempts = 100, \n max_iters = 1000, init_state = init_state)",
"_____no_output_____"
],
[
"print(best_state)",
"[4 1 3 5 7 2 0 6]\n"
],
[
"print(best_fitness)",
"0.0\n"
]
],
[
[
"### Example 2: 8-Queens Using Custom Fitness Function",
"_____no_output_____"
]
],
[
[
"# Define alternative N-Queens fitness function for maximization problem\ndef queens_max(state):\n \n # Initialize counter\n fitness = 0\n \n # For all pairs of queens\n for i in range(len(state) - 1):\n for j in range(i + 1, len(state)):\n \n # Check for horizontal, diagonal-up and diagonal-down attacks\n if (state[j] != state[i]) \\\n and (state[j] != state[i] + (j - i)) \\\n and (state[j] != state[i] - (j - i)):\n \n # If no attacks, then increment counter\n fitness += 1\n\n return fitness",
"_____no_output_____"
],
[
"# Check function is working correctly\nstate = np.array([1, 4, 1, 3, 5, 5, 2, 7])\n\n# The fitness of this state should be 22\nqueens_max(state)",
"_____no_output_____"
],
[
"# Initialize custom fitness function object\nfitness_cust = mlrose.CustomFitness(queens_max)",
"_____no_output_____"
],
[
"# Define optimization problem object\nproblem_cust = mlrose.DiscreteOpt(length = 8, fitness_fn = fitness_cust, maximize = True, max_val = 8)",
"_____no_output_____"
],
[
"# Solve using simulated annealing - attempt 1\nnp.random.seed(1)\n\nbest_state, best_fitness = mlrose.simulated_annealing(problem_cust, schedule = schedule, \n max_attempts = 10, max_iters = 1000, \n init_state = init_state)",
"_____no_output_____"
],
[
"print(best_state)",
"[6 4 7 3 6 2 5 1]\n"
],
[
"print(best_fitness)",
"26.0\n"
],
[
"# Solve using simulated annealing - attempt 2\nnp.random.seed(1)\n\nbest_state, best_fitness = mlrose.simulated_annealing(problem_cust, schedule = schedule, \n max_attempts = 100, max_iters = 1000, \n init_state = init_state)",
"_____no_output_____"
],
[
"print(best_state)",
"[4 1 3 5 7 2 0 6]\n"
],
[
"print(best_fitness)",
"28.0\n"
]
],
[
[
"### Example 3: Travelling Salesperson Using Coordinate-Defined Fitness Function",
"_____no_output_____"
]
],
[
[
"# Create list of city coordinates\ncoords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]\n\n# Initialize fitness function object using coords_list\nfitness_coords = mlrose.TravellingSales(coords = coords_list)",
"_____no_output_____"
],
[
"# Define optimization problem object\nproblem_fit = mlrose.TSPOpt(length = 8, fitness_fn = fitness_coords, maximize = False)",
"_____no_output_____"
],
[
"# Solve using genetic algorithm - attempt 1\nnp.random.seed(2)\n\nbest_state, best_fitness = mlrose.genetic_alg(problem_fit)",
"_____no_output_____"
],
[
"print(best_state)",
"[1 3 4 5 6 7 0 2]\n"
],
[
"print(best_fitness)",
"18.8958046604\n"
],
[
"# Solve using genetic algorithm - attempt 2\nnp.random.seed(2)\n\nbest_state, best_fitness = mlrose.genetic_alg(problem_fit, mutation_prob = 0.2, max_attempts = 100)",
"_____no_output_____"
],
[
"print(best_state)",
"[7 6 5 4 3 2 1 0]\n"
],
[
"print(best_fitness)",
"17.3426175477\n"
]
],
[
[
"### Example 4: Travelling Salesperson Using Distance-Defined Fitness Function",
"_____no_output_____"
]
],
[
[
"# Create list of distances between pairs of cities\ndist_list = [(0, 1, 3.1623), (0, 2, 4.1231), (0, 3, 5.8310), (0, 4, 4.2426), (0, 5, 5.3852), \\\n (0, 6, 4.0000), (0, 7, 2.2361), (1, 2, 1.0000), (1, 3, 2.8284), (1, 4, 2.0000), \\\n (1, 5, 4.1231), (1, 6, 4.2426), (1, 7, 2.2361), (2, 3, 2.2361), (2, 4, 2.2361), \\\n (2, 5, 4.4721), (2, 6, 5.0000), (2, 7, 3.1623), (3, 4, 2.0000), (3, 5, 3.6056), \\\n (3, 6, 5.0990), (3, 7, 4.1231), (4, 5, 2.2361), (4, 6, 3.1623), (4, 7, 2.2361), \\\n (5, 6, 2.2361), (5, 7, 3.1623), (6, 7, 2.2361)]\n\n# Initialize fitness function object using dist_list\nfitness_dists = mlrose.TravellingSales(distances = dist_list)",
"_____no_output_____"
],
[
"# Define optimization problem object\nproblem_fit2 = mlrose.TSPOpt(length = 8, fitness_fn = fitness_dists, maximize = False)",
"_____no_output_____"
],
[
"# Solve using genetic algorithm\nnp.random.seed(2)\n\nbest_state, best_fitness = mlrose.genetic_alg(problem_fit2, mutation_prob = 0.2, max_attempts = 100)",
"_____no_output_____"
],
[
"print(best_state)",
"[7 6 5 4 3 2 1 0]\n"
],
[
"print(best_fitness)",
"17.3428\n"
]
],
[
[
"### Example 5: Travelling Salesperson Defining Fitness Function as Part of Optimization Problem Definition Step",
"_____no_output_____"
]
],
[
[
"# Create list of city coordinates\ncoords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]\n\n# Define optimization problem object\nproblem_no_fit = mlrose.TSPOpt(length = 8, coords = coords_list, maximize = False)",
"_____no_output_____"
],
[
"# Solve using genetic algorithm\nnp.random.seed(2)\n\nbest_state, best_fitness = mlrose.genetic_alg(problem_no_fit, mutation_prob = 0.2, max_attempts = 100)",
"_____no_output_____"
],
[
"print(best_state)",
"[7 6 5 4 3 2 1 0]\n"
],
[
"print(best_fitness)",
"17.3426175477\n"
]
],
[
[
"### Example 6: Fitting a Neural Network to the Iris Dataset",
"_____no_output_____"
]
],
[
[
"# Load the Iris dataset\ndata = load_iris()",
"_____no_output_____"
],
[
"# Get feature values of first observation\nprint(data.data[0])",
"[ 5.1 3.5 1.4 0.2]\n"
],
[
"# Get feature names\nprint(data.feature_names)",
"['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']\n"
],
[
"# Get target value of first observation\nprint(data.target[0])",
"0\n"
],
[
"# Get target name of first observation\nprint(data.target_names[data.target[0]])",
"setosa\n"
],
[
"# Get minimum feature values\nprint(np.min(data.data, axis = 0))",
"[ 4.3 2. 1. 0.1]\n"
],
[
"# Get maximum feature values\nprint(np.max(data.data, axis = 0))",
"[ 7.9 4.4 6.9 2.5]\n"
],
[
"# Get unique target values\nprint(np.unique(data.target))",
"[0 1 2]\n"
],
[
"# Split data into training and test sets\nX_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size = 0.2, \n random_state = 3)",
"_____no_output_____"
],
[
"# Normalize feature data\nscaler = MinMaxScaler()\n\nX_train_scaled = scaler.fit_transform(X_train)\nX_test_scaled = scaler.transform(X_test)",
"_____no_output_____"
],
[
"# One hot encode target values\none_hot = OneHotEncoder()\n\ny_train_hot = one_hot.fit_transform(y_train.reshape(-1, 1)).todense()\ny_test_hot = one_hot.transform(y_test.reshape(-1, 1)).todense()",
"_____no_output_____"
],
[
"# Initialize neural network object and fit object - attempt 1\n\nnp.random.seed(3)\n\nnn_model1 = mlrose.NeuralNetwork(hidden_nodes = [2], activation ='relu', \n algorithm ='random_hill_climb', \n max_iters = 1000, bias = True, is_classifier = True, \n learning_rate = 0.0001, early_stopping = True, \n clip_max = 5, max_attempts = 100)\n\nnn_model1.fit(X_train_scaled, y_train_hot)",
"_____no_output_____"
],
[
"# Predict labels for train set and assess accuracy\ny_train_pred = nn_model1.predict(X_train_scaled)\n\ny_train_accuracy = accuracy_score(y_train_hot, y_train_pred)\n\nprint(y_train_accuracy)",
"0.45\n"
],
[
"# Predict labels for test set and assess accuracy\ny_test_pred = nn_model1.predict(X_test_scaled)\n\ny_test_accuracy = accuracy_score(y_test_hot, y_test_pred)\n\nprint(y_test_accuracy)",
"0.533333333333\n"
],
[
"# Initialize neural network object and fit object - attempt 2\n\nnp.random.seed(3)\n\nnn_model2 = mlrose.NeuralNetwork(hidden_nodes = [2], activation = 'relu', \n algorithm = 'gradient_descent', \n max_iters = 1000, bias = True, is_classifier = True, \n learning_rate = 0.0001, early_stopping = True, \n clip_max = 5, max_attempts = 100)\n\nnn_model2.fit(X_train_scaled, y_train_hot)",
"_____no_output_____"
],
[
"# Predict labels for train set and assess accuracy\ny_train_pred = nn_model2.predict(X_train_scaled)\n\ny_train_accuracy = accuracy_score(y_train_hot, y_train_pred)\n\nprint(y_train_accuracy)",
"0.625\n"
],
[
"# Predict labels for test set and assess accuracy\ny_test_pred = nn_model2.predict(X_test_scaled)\n\ny_test_accuracy = accuracy_score(y_test_hot, y_test_pred)\n\nprint(y_test_accuracy)",
"0.566666666667\n"
]
],
[
[
"### Example 7: Fitting a Logistic Regression to the Iris Data",
"_____no_output_____"
]
],
[
[
"# Initialize logistic regression object and fit object - attempt 1\n\nnp.random.seed(3)\n\nlr_model1 = mlrose.LogisticRegression(algorithm = 'random_hill_climb', max_iters = 1000, \n bias = True, learning_rate = 0.0001, \n early_stopping = True, clip_max = 5, max_attempts = 100)\n\nlr_model1.fit(X_train_scaled, y_train_hot)",
"_____no_output_____"
],
[
"# Predict labels for train set and assess accuracy\ny_train_pred = lr_model1.predict(X_train_scaled)\n\ny_train_accuracy = accuracy_score(y_train_hot, y_train_pred)\n\nprint(y_train_accuracy)",
"0.191666666667\n"
],
[
"# Predict labels for test set and assess accuracy\ny_test_pred = lr_model1.predict(X_test_scaled)\n\ny_test_accuracy = accuracy_score(y_test_hot, y_test_pred)\n\nprint(y_test_accuracy)",
"0.0666666666667\n"
],
[
"# Initialize logistic regression object and fit object - attempt 2\n\nnp.random.seed(3)\n\nlr_model2 = mlrose.LogisticRegression(algorithm = 'random_hill_climb', max_iters = 1000, \n bias = True, learning_rate = 0.01, \n early_stopping = True, clip_max = 5, max_attempts = 100)\n\nlr_model2.fit(X_train_scaled, y_train_hot)",
"_____no_output_____"
],
[
"# Predict labels for train set and assess accuracy\ny_train_pred = lr_model2.predict(X_train_scaled)\n\ny_train_accuracy = accuracy_score(y_train_hot, y_train_pred)\n\nprint(y_train_accuracy)",
"0.683333333333\n"
],
[
"# Predict labels for test set and assess accuracy\ny_test_pred = lr_model2.predict(X_test_scaled)\n\ny_test_accuracy = accuracy_score(y_test_hot, y_test_pred)\n\nprint(y_test_accuracy)",
"0.7\n"
]
],
[
[
"### Example 8: Fitting a Logistic Regression to the Iris Data using the NeuralNetwork() class",
"_____no_output_____"
]
],
[
[
"# Initialize neural network object and fit object - attempt 1\n\nnp.random.seed(3)\n\nlr_nn_model1 = mlrose.NeuralNetwork(hidden_nodes = [], activation = 'sigmoid', \n algorithm = 'random_hill_climb', \n max_iters = 1000, bias = True, is_classifier = True, \n learning_rate = 0.0001, early_stopping = True, \n clip_max = 5, max_attempts = 100)\n\nlr_nn_model1.fit(X_train_scaled, y_train_hot)",
"_____no_output_____"
],
[
"# Predict labels for train set and assess accuracy\ny_train_pred = lr_nn_model1.predict(X_train_scaled)\n\ny_train_accuracy = accuracy_score(y_train_hot, y_train_pred)\n\nprint(y_train_accuracy)",
"0.191666666667\n"
],
[
"# Predict labels for test set and assess accuracy\ny_test_pred = lr_nn_model1.predict(X_test_scaled)\n\ny_test_accuracy = accuracy_score(y_test_hot, y_test_pred)\n\nprint(y_test_accuracy)",
"0.0666666666667\n"
],
[
"# Initialize neural network object and fit object - attempt 2\n\nnp.random.seed(3)\n\nlr_nn_model2 = mlrose.NeuralNetwork(hidden_nodes = [], activation = 'sigmoid', \n algorithm = 'random_hill_climb', \n max_iters = 1000, bias = True, is_classifier = True, \n learning_rate = 0.01, early_stopping = True, \n clip_max = 5, max_attempts = 100)\n\nlr_nn_model2.fit(X_train_scaled, y_train_hot)",
"_____no_output_____"
],
[
"# Predict labels for train set and assess accuracy\ny_train_pred = lr_nn_model2.predict(X_train_scaled)\n\ny_train_accuracy = accuracy_score(y_train_hot, y_train_pred)\n\nprint(y_train_accuracy)",
"0.683333333333\n"
],
[
"# Predict labels for test set and assess accuracy\ny_test_pred = lr_nn_model2.predict(X_test_scaled)\n\ny_test_accuracy = accuracy_score(y_test_hot, y_test_pred)\n\nprint(y_test_accuracy)",
"0.7\n"
]
]
] |
[
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a944705d7a1b1330d015e71876bb3a3a10bf51b
| 124,225 |
ipynb
|
Jupyter Notebook
|
notebooks/data_analysis/model_robustness.ipynb
|
NoahHA/tth-ML-project
|
51ae297fc0499d3ac25cf2d347cc424747deae38
|
[
"MIT"
] | null | null | null |
notebooks/data_analysis/model_robustness.ipynb
|
NoahHA/tth-ML-project
|
51ae297fc0499d3ac25cf2d347cc424747deae38
|
[
"MIT"
] | null | null | null |
notebooks/data_analysis/model_robustness.ipynb
|
NoahHA/tth-ML-project
|
51ae297fc0499d3ac25cf2d347cc424747deae38
|
[
"MIT"
] | null | null | null | 195.938486 | 28,866 | 0.826758 |
[
[
[
"import os\nimport numpy as np\nimport tensorflow.keras as keras\nfrom sklearn.metrics import roc_auc_score\nimport matplotlib.pyplot as plt\nimport pickle\nfrom tqdm.notebook import tqdm\nimport pandas as pd\nimport seaborn as sns\nfrom src.models.train_model import MonteCarloDropout, MCLSTM",
"_____no_output_____"
],
[
"model_name = r\"merged-ce-mc.h5\"\nmodel_path = r\"C:\\Users\\Noaja\\Downloads\\msci_project\\tth-ML-project\\models\\wandb_models\"\nload_path = r\"C:\\Users\\Noaja\\Downloads\\msci_project\\tth-ML-project\\data\\processed\"\n\nmodel_path = os.path.join(model_path, model_name)\n\nmodel = keras.models.load_model(model_path, custom_objects={\"MCLSTM\": MCLSTM, \"MonteCarloDropout\": MonteCarloDropout})\n\nwith open(os.path.join(load_path, \"processed_data.pickle\"), \"rb\") as handle:\n combined_data = pickle.load(handle)\n\ny_test = combined_data['y_test']\ny_train = combined_data['y_train']\n\nevent_X_train = combined_data['event_X_train']\nobject_X_train = combined_data['object_X_train']\n\nevent_X_test = combined_data['event_X_test']\nobject_X_test = combined_data['object_X_test']",
"_____no_output_____"
],
[
"from src.features.build_features import scale_event_data, scale_object_data\n\nevent_X_train, event_X_test = scale_event_data(event_X_train, event_X_test)\nobject_X_train, object_X_test = scale_object_data(object_X_train, object_X_test)",
"_____no_output_____"
],
[
"def add_noise(data, percentage):\n varied_data = data.copy()\n for col in range(data.shape[1]):\n mean = np.mean(data[:, col])\n std = np.std(data[:, col]) * percentage\n noise = np.random.normal(0, std, data[:, col].shape)\n varied_data[:, col] += noise\n\n return varied_data\n\n\ndef get_test_predictions(n_bins, type, max_percent=20, scale_range=0.2):\n x_values = []\n scores = []\n if n_bins % 2 == 0: n_bins += 1\n \n for i in range(1, n_bins+1):\n percentage = np.round((i / n_bins) * (max_percent/100), 4)\n scale_factor = (1 - scale_range) + (2 * scale_range * ((i-1) / (n_bins-1)))\n scale_factor = np.round(scale_factor, 4)\n\n varied_event_data = event_X_test.copy()\n varied_object_data = object_X_test.copy()\n\n if type == \"noise\":\n varied_event_data[:] = add_noise(event_X_test.values, percentage)\n varied_object_data = add_noise(object_X_test, percentage)\n x_values.append(percentage)\n\n elif type == \"scale\":\n varied_event_data['HT'] *= scale_factor\n x_values.append(scale_factor)\n\n preds = model.predict([varied_event_data, varied_object_data]).ravel()\n auc = roc_auc_score(y_test, preds)\n scores.append(auc)\n \n return (x_values, scores)",
"_____no_output_____"
],
[
"num_samples = 10\nn_bins = 9\nmax_percent = 20\nscale_range = 0.2\n\ndef noise_impact(num_samples, n_bins, max_percent):\n robust_df = pd.DataFrame(columns=['noise percentage', 'AUC'])\n for _ in tqdm(range(num_samples)):\n percentages, scores = get_test_predictions(n_bins, \"noise\", max_percent=max_percent)\n for percentage, score in zip(percentages, scores):\n robust_df = robust_df.append({'noise percentage': percentage*100, 'AUC': score}, ignore_index=True)\n\n baseline_preds = model.predict([event_X_test, object_X_test]).ravel()\n baseline_auc = roc_auc_score(y_test, baseline_preds)\n robust_df['Δ ROC AUC'] = robust_df['AUC'] - baseline_auc\n\n return robust_df\n\n\ndef scale_impact(num_samples, n_bins, scale_range):\n robust_df = pd.DataFrame(columns=['HT scale factor', 'AUC'])\n for _ in tqdm(range(num_samples)):\n factors, scores = get_test_predictions(n_bins, \"scale\", scale_range=scale_range)\n for factor, score in zip(factors, scores):\n robust_df = robust_df.append({'HT scale factor': factor, 'AUC': score}, ignore_index=True)\n\n return robust_df",
"_____no_output_____"
],
[
"robust_df = noise_impact(num_samples, n_bins, max_percent)\n\nwith plt.style.context(['science', 'grid', 'notebook', 'high-contrast']):\n plt.figure(figsize=(10, 10))\n sns.boxplot(x=\"noise percentage\", y=\"Δ ROC AUC\", data=robust_df)\n plt.axhline(y=0.0, color='r', linestyle='-')\n plt.show()",
"_____no_output_____"
],
[
"robust_df = scale_impact(num_samples=10, n_bins=9, scale_range=scale_range)",
"_____no_output_____"
],
[
"robust_df['Δ ROC AUC'] = robust_df['AUC'] - np.mean(robust_df.loc[robust_df['HT scale factor'] == 1, 'AUC'])\n\nwith plt.style.context(['science', 'grid', 'notebook', 'high-contrast']):\n plt.figure(figsize=(10, 10))\n sns.boxplot(x=\"HT scale factor\", y=\"Δ ROC AUC\", data=robust_df)\n plt.axhline(y=0.0, color='r', linestyle='-')\n plt.show()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4a944d6f59a656c3b2fc06c9348fc85736461621
| 22,229 |
ipynb
|
Jupyter Notebook
|
ml/pc/exercises/image_classification_part3.ipynb
|
prafullkotecha/eng-edu
|
d23f81c9a8f39dc399233544cacfe27ae62b63e3
|
[
"Apache-2.0"
] | null | null | null |
ml/pc/exercises/image_classification_part3.ipynb
|
prafullkotecha/eng-edu
|
d23f81c9a8f39dc399233544cacfe27ae62b63e3
|
[
"Apache-2.0"
] | null | null | null |
ml/pc/exercises/image_classification_part3.ipynb
|
prafullkotecha/eng-edu
|
d23f81c9a8f39dc399233544cacfe27ae62b63e3
|
[
"Apache-2.0"
] | null | null | null | 35.452951 | 540 | 0.547708 |
[
[
[
"#### Copyright 2018 Google LLC.",
"_____no_output_____"
]
],
[
[
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Cat vs. Dog Image Classification\n## Exercise 3: Feature Extraction and Fine-Tuning\n**_Estimated completion time: 30 minutes_**\n\nIn Exercise 1, we built a convnet from scratch, and were able to achieve an accuracy of about 70%. With the addition of data augmentation and dropout in Exercise 2, we were able to increase accuracy to about 80%. That seems decent, but 20% is still too high of an error rate. Maybe we just don't have enough training data available to properly solve the problem. What other approaches can we try?\n\nIn this exercise, we'll look at two techniques for repurposing feature data generated from image models that have already been trained on large sets of data, **feature extraction** and **fine tuning**, and use them to improve the accuracy of our cat vs. dog classification model.",
"_____no_output_____"
],
[
"## Feature Extraction Using a Pretrained Model\n\nOne thing that is commonly done in computer vision is to take a model trained on a very large dataset, run it on your own, smaller dataset, and extract the intermediate representations (features) that the model generates. These representations are frequently informative for your own computer vision task, even though the task may be quite different from the problem that the original model was trained on. This versatility and repurposability of convnets is one of the most interesting aspects of deep learning.\n\nIn our case, we will use the [Inception V3 model](https://arxiv.org/abs/1512.00567) developed at Google, and pre-trained on [ImageNet](http://image-net.org/), a large dataset of web images (1.4M images and 1000 classes). This is a powerful model; let's see what the features that it has learned can do for our cat vs. dog problem.\n\nFirst, we need to pick which intermediate layer of Inception V3 we will use for feature extraction. A common practice is to use the output of the very last layer before the `Flatten` operation, the so-called \"bottleneck layer.\" The reasoning here is that the following fully connected layers will be too specialized for the task the network was trained on, and thus the features learned by these layers won't be very useful for a new task. The bottleneck features, however, retain much generality.\n\nLet's instantiate an Inception V3 model preloaded with weights trained on ImageNet:\n",
"_____no_output_____"
]
],
[
[
"import os\nimport tensorflow as tf\n\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras import layers\nfrom keras.models import Model\nfrom keras.optimizers import RMSprop\nfrom keras import backend as K\n\n# Configure the TF backend session\ntf_config = tf.ConfigProto(\n gpu_options=tf.GPUOptions(allow_growth=True))\nK.set_session(tf.Session(config=tf_config))",
"_____no_output_____"
]
],
[
[
"Now let's download the weights:",
"_____no_output_____"
]
],
[
[
"!wget --no-check-certificate \\\n https://storage.googleapis.com/mledu-datasets/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5 \\\n -O /tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5",
"_____no_output_____"
],
[
"local_weights_file = '/tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'\npre_trained_model = InceptionV3(\n input_shape=(150, 150, 3), include_top=False, weights=None)\npre_trained_model.load_weights(local_weights_file)",
"_____no_output_____"
]
],
[
[
"By specifying the `include_top=False` argument, we load a network that doesn't include the classification layers at the top—ideal for feature extraction.",
"_____no_output_____"
],
[
"Let's make the model non-trainable, since we will only use it for feature extraction; we won't update the weights of the pretrained model during training.",
"_____no_output_____"
]
],
[
[
"for layer in pre_trained_model.layers:\n layer.trainable = False",
"_____no_output_____"
]
],
[
[
"The layer we will use for feature extraction in Inception v3 is called `mixed7`. It is not the bottleneck of the network, but we are using it to keep a sufficiently large feature map (7x7 in this case). (Using the bottleneck layer would have resulting in a 3x3 feature map, which is a bit small.) Let's get the output from `mixed7`:",
"_____no_output_____"
]
],
[
[
"last_layer = pre_trained_model.get_layer('mixed7')\nprint 'last layer output shape:', last_layer.output_shape\nlast_output = last_layer.output",
"_____no_output_____"
]
],
[
[
"Now let's stick a fully connected classifier on top of `last_output`:",
"_____no_output_____"
]
],
[
[
"# Flatten the output layer to 1 dimension\nx = layers.Flatten()(last_output)\n# Add a fully connected layer with 1,024 hidden units and ReLU activation\nx = layers.Dense(1024, activation='relu')(x)\n# Add a dropout rate of 0.2\nx = layers.Dropout(0.2)(x)\n# Add a final sigmoid layer for classification\nx = layers.Dense(1, activation='sigmoid')(x)\n\n# Configure and compile the model\nmodel = Model(pre_trained_model.input, x)\nmodel.compile(loss='binary_crossentropy',\n optimizer=RMSprop(lr=0.0001),\n metrics=['acc'])",
"_____no_output_____"
]
],
[
[
"For examples and data preprocessing, let's use the same files and `train_generator` as we did in Exercise 2.",
"_____no_output_____"
],
[
"**NOTE:** The 2,000 images used in this exercise are excerpted from the [\"Dogs vs. Cats\" dataset](https://www.kaggle.com/c/dogs-vs-cats/data) available on Kaggle, which contains 25,000 images. Here, we use a subset of the full dataset to decrease training time for educational purposes.",
"_____no_output_____"
]
],
[
[
"!wget --no-check-certificate \\\n https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip -O \\\n /tmp/cats_and_dogs_filtered.zip",
"_____no_output_____"
],
[
"import os\nimport zipfile\n\nlocal_zip = '/tmp/cats_and_dogs_filtered.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp')\nzip_ref.close()\n\n# Define our example directories and files\nbase_dir = '/tmp/cats_and_dogs_filtered'\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\n\n# Directory with our training cat pictures\ntrain_cats_dir = os.path.join(train_dir, 'cats')\n\n# Directory with our training dog pictures\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\n\n# Directory with our validation cat pictures\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\n\n# Directory with our validation dog pictures\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\n\ntrain_cat_fnames = os.listdir(train_cats_dir)\ntrain_dog_fnames = os.listdir(train_dogs_dir)\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Add our data-augmentation parameters to ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n# Note that the validation data should not be augmented!\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir, # This is the source directory for training images\n target_size=(150, 150), # All images will be resized to 150x150\n batch_size=20,\n # Since we use binary_crossentropy loss, we need binary labels\n class_mode='binary')\n\n# Flow validation images in batches of 20 using test_datagen generator\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size=(150, 150),\n batch_size=20,\n class_mode='binary')",
"_____no_output_____"
]
],
[
[
"Finally, let's train the model using the features we extracted. We'll train on all 2000 images available, for 2 epochs, and validate on all 1,000 test images.",
"_____no_output_____"
]
],
[
[
"history = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=2,\n validation_data=validation_generator,\n validation_steps=50,\n verbose=2)",
"_____no_output_____"
]
],
[
[
"You can see that we reach a validation accuracy of 88–90% very quickly. This is much better than the small model we trained from scratch.",
"_____no_output_____"
],
[
"## Further Improving Accuracy with Fine-Tuning\n\nIn our feature-extraction experiment, we only tried adding two classification layers on top of an Inception V3 layer. The weights of the pretrained network were not updated during training. One way to increase performance even further is to \"fine-tune\" the weights of the top layers of the pretrained model alongside the training of the top-level classifier. A couple of important notes on fine-tuning:\n\n- **Fine-tuning should only be attempted *after* you have trained the top-level classifier with the pretrained model set to non-trainable**. If you add a randomly initialized classifier on top of a pretrained model and attempt to train all layers jointly, the magnitude of the gradient updates will be too large (due to the random weights from the classifier), and your pretrained model will just forget everything it has learned.\n- Additionally, we **fine-tune only the *top layers* of the pre-trained model** rather than all layers of the pretrained model because, in a convnet, the higher up a layer is, the more specialized it is. The first few layers in a convnet learn very simple and generic features, which generalize to almost all types of images. But as you go higher up, the features are increasingly specific to the dataset that the model is trained on. The goal of fine-tuning is to adapt these specialized features to work with the new dataset.\n\nAll we need to do to implement fine-tuning is to set the top layers of Inception V3 to be trainable, recompile the model (necessary for these changes to take effect), and resume training. Let's unfreeze all layers belonging to the `mixed7` module—i.e., all layers found after `mixed6`—and recompile the model:",
"_____no_output_____"
]
],
[
[
"unfreeze = False\n\n# Unfreeze all models after \"mixed6\"\nfor layer in pre_trained_model.layers:\n if unfreeze:\n layer.trainable = True\n if layer.name == 'mixed6':\n unfreeze = True\n\nfrom keras.optimizers import SGD\n\n# As an optimizer, here we will use SGD \n# with a very low learning rate (0.00001)\nmodel.compile(loss='binary_crossentropy',\n optimizer=SGD(lr=0.00001, momentum=0.9),\n metrics=['acc'])",
"_____no_output_____"
]
],
[
[
"Now let's retrain the model. We'll train on all 2000 images available, for 50 epochs, and validate on all 1,000 test images. (This may take 15-20 minutes to run.)",
"_____no_output_____"
]
],
[
[
"history = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=50,\n validation_data=validation_generator,\n validation_steps=50,\n verbose=2)",
"_____no_output_____"
]
],
[
[
"We are seeing a nice improvement, with the validation loss going from ~1.7 down to ~1.2, and accuracy going from 88% to 92%. That's a 4.5% relative improvement in accuracy.\n\nLet's plot the training and validation loss and accuracy to show it conclusively:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# Retrieve a list of accuracy results on training and test data\n# sets for each training epoch\nacc = history.history['acc']\nval_acc = history.history['val_acc']\n\n# Retrieve a list of list results on training and test data\n# sets for each training epoch\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\n# Get number of epochs\nepochs = range(len(acc))\n\n# Plot training and validation accuracy per epoch\nplt.plot(epochs, acc)\nplt.plot(epochs, val_acc)\nplt.title('Training and validation accuracy')\n\nplt.figure()\n\n# Plot training and validation loss per epoch\nplt.plot(epochs, loss)\nplt.plot(epochs, val_loss)\nplt.title('Training and validation loss')",
"_____no_output_____"
]
],
[
[
"Congratulations! Using feature extraction and fine-tuning, you've built an image classification model that can identify cats vs. dogs in images with over 90% accuracy.",
"_____no_output_____"
],
[
"## Clean Up\n\nRun the following cell to terminate the kernel and free memory resources:",
"_____no_output_____"
]
],
[
[
"import os, signal\nos.kill(os.getpid(), signal.SIGKILL)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
4a9457e44c91badf7df281257b5ac56f292cd0c4
| 32,732 |
ipynb
|
Jupyter Notebook
|
analyze.ipynb
|
leelasd/openmm_runner
|
a6beae42a03fdaa8e33b8372bd2ebde9d3f3e87f
|
[
"CC-BY-4.0"
] | 1 |
2022-02-17T14:45:38.000Z
|
2022-02-17T14:45:38.000Z
|
analyze.ipynb
|
leelasd/openmm_runner
|
a6beae42a03fdaa8e33b8372bd2ebde9d3f3e87f
|
[
"CC-BY-4.0"
] | null | null | null |
analyze.ipynb
|
leelasd/openmm_runner
|
a6beae42a03fdaa8e33b8372bd2ebde9d3f3e87f
|
[
"CC-BY-4.0"
] | 1 |
2022-02-17T14:45:37.000Z
|
2022-02-17T14:45:37.000Z
| 139.880342 | 26,968 | 0.871105 |
[
[
[
"%matplotlib inline\nfrom openmm_runner import mdanalyzer\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport nglview as nv\nimport MDAnalysis as mda",
"_____no_output_____"
],
[
"HERE = Path(_dh[-1])\nDATA = HERE / \"data\"\nmd_universe = mda.Universe(str(DATA / \"topology.pdb\"), str(DATA / \"trajectory.xtc\"))\nview = nv.show_mdanalysis(md_universe)\nview",
"Warning: importing 'simtk.openmm' is deprecated. Import 'openmm' instead.\n"
],
[
"traj = mdanalyzer.align_trajectroy(DATA)",
"_____no_output_____"
],
[
"ligand_name = \"03P\"\nrmsd = mdanalyzer.rmsd_for_atomgroups(traj, \"backbone\", [\"protein\", f\"resname {ligand_name}\"])\nrmsd.head()",
"/home/iwatobipen/miniconda3/envs/chemoinfo/lib/python3.7/site-packages/MDAnalysis/analysis/rms.py:710: DeprecationWarning: The `rmsd` attribute was deprecated in MDAnalysis 2.0.0 and will be removed in MDAnalysis 3.0.0. Please use `results.rmsd` instead.\n warnings.warn(wmsg, DeprecationWarning)\n"
],
[
"rmsd.plot(title=\"RMSD of protein and ligand\")\nplt.ylabel(\"RMSD (Å)\");",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.