hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
sequence
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
sequence
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
sequence
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
sequence
cell_types
sequence
cell_type_groups
sequence
d01b58f074fe01478936d4ad965d6230fabc9008
710,446
ipynb
Jupyter Notebook
samples/notebooks/fsharp/Samples/HousingML.ipynb
BillWagner/interactive
9d1ecd3c06ba93e59bfef3842d2660c08d9e2ce5
[ "MIT" ]
1
2021-07-01T17:52:02.000Z
2021-07-01T17:52:02.000Z
samples/notebooks/fsharp/Samples/HousingML.ipynb
BillWagner/interactive
9d1ecd3c06ba93e59bfef3842d2660c08d9e2ce5
[ "MIT" ]
1
2020-11-13T01:07:23.000Z
2020-11-13T01:07:23.000Z
samples/notebooks/fsharp/Samples/HousingML.ipynb
BillWagner/interactive
9d1ecd3c06ba93e59bfef3842d2660c08d9e2ce5
[ "MIT" ]
2
2021-11-01T10:17:04.000Z
2021-11-01T16:40:11.000Z
1,435.244444
468,359
0.712402
[ [ [ "[this doc on github](https://github.com/dotnet/interactive/tree/master/samples/notebooks/fsharp/Samples)\n\n# Machine Learning over House Prices with ML.NET\n\n### Reference the packages", "_____no_output_____" ] ], [ [ "#r \"nuget:Microsoft.ML,1.4.0\"\r\n#r \"nuget:Microsoft.ML.AutoML,0.16.0\"\r\n#r \"nuget:Microsoft.Data.Analysis,0.2.0\"\r\n#r \"nuget: XPlot.Plotly.Interactive, 4.0.6\"\r\n \r\nopen Microsoft.Data.Analysis\r\nopen XPlot.Plotly", "_____no_output_____" ] ], [ [ "### Adding better default formatting for data frames\n\nRegister a formatter for data frames and data frame rows.\n", "_____no_output_____" ] ], [ [ "module DateFrameFormatter = \r\n \r\n // Locally open the F# HTML DSL.\r\n open Html\r\n\r\n let maxRows = 20\r\n\r\n Formatter.Register<DataFrame>((fun (df: DataFrame) (writer: TextWriter) ->\r\n\r\n let take = 20\r\n table [] [\r\n thead [] [\r\n th [] [ str \"Index\" ]\r\n for c in df.Columns do\r\n th [] [ str c.Name]\r\n ]\r\n tbody [] [\r\n for i in 0 .. min maxRows (int df.Rows.Count - 1) do\r\n tr [] [\r\n td [] [ i ]\r\n for o in df.Rows.[int64 i] do\r\n td [] [ o ]\r\n ]\r\n ]\r\n ]\r\n |> writer.Write\r\n\r\n ), mimeType = \"text/html\")\r\n \r\n Formatter.Register<DataFrameRow>((fun (row: DataFrameRow) (writer: TextWriter) ->\r\n\r\n table [] [\r\n tbody [] [\r\n tr [] [\r\n for o in row do\r\n td [] [ o ] \r\n ]\r\n ]\r\n ]\r\n |> writer.Write\r\n\r\n ), mimeType = \"text/html\")\r\n ", "_____no_output_____" ] ], [ [ "### Download the data", "_____no_output_____" ] ], [ [ "open System.Net.Http\nlet housingPath = \"housing.csv\"\nif not(File.Exists(housingPath)) then\n let contents = HttpClient().GetStringAsync(\"https://raw.githubusercontent.com/ageron/handson-ml2/master/datasets/housing/housing.csv\").Result\n File.WriteAllText(\"housing.csv\", contents)", "_____no_output_____" ] ], [ [ "### Add the data to the data frame", "_____no_output_____" ] ], [ [ "let housingData = DataFrame.LoadCsv(housingPath)\nhousingData", "_____no_output_____" ], [ "housingData.Description()", "_____no_output_____" ] ], [ [ "### Display the data", "_____no_output_____" ] ], [ [ "let graph =\n Histogram(x = housingData.[\"median_house_value\"],\n nbinsx = 20)\ngraph |> Chart.Plot", "_____no_output_____" ], [ "let graph =\r\n Scattergl(\r\n x = housingData.[\"longitude\"],\r\n y = housingData.[\"latitude\"],\r\n mode = \"markers\",\r\n marker =\r\n Marker(\r\n color = housingData.[\"median_house_value\"],\r\n colorscale = \"Jet\"))\r\n\r\nlet plot = Chart.Plot(graph)\r\nplot.Width <- 600\r\nplot.Height <- 600\r\ndisplay(plot)", "_____no_output_____" ] ], [ [ "### Prepare the training and validation sets", "_____no_output_____" ] ], [ [ "module Array = \n let shuffle (arr: 'T[]) =\n let rnd = Random()\n let arr = Array.copy arr\n for i in 0 .. arr.Length - 1 do\n let r = i + rnd.Next(arr.Length - i)\n let temp = arr.[r]\n arr.[r] <- arr.[i]\n arr.[i] <- temp\n arr\n\nlet randomIndices = [| 0 .. int housingData.Rows.Count - 1 |] |> Array.shuffle\n\nlet testSize = int (float (housingData.Rows.Count) * 0.1)\nlet trainRows = randomIndices.[testSize..]\nlet testRows = randomIndices.[..testSize - 1]\n\nlet housing_train = housingData.[trainRows]\nlet housing_test = housingData.[testRows]\n\ndisplay(housing_train.Rows.Count)\ndisplay(housing_test.Rows.Count)", "_____no_output_____" ] ], [ [ "### Create the regression model and train it", "_____no_output_____" ] ], [ [ "#!time\n\nopen Microsoft.ML\nopen Microsoft.ML.Data\nopen Microsoft.ML.AutoML\n\nlet mlContext = MLContext()\n\nlet experiment = mlContext.Auto().CreateRegressionExperiment(maxExperimentTimeInSeconds = 15u)\nlet result = experiment.Execute(housing_train, labelColumnName = \"median_house_value\")", "_____no_output_____" ] ], [ [ "### Display the training results", "_____no_output_____" ] ], [ [ "let scatters =\r\n result.RunDetails\r\n |> Seq.filter (fun d -> not (isNull d.ValidationMetrics))\r\n |> Seq.groupBy (fun r -> r.TrainerName)\r\n |> Seq.map (fun (name, details) ->\r\n Scattergl(\r\n name = name,\r\n x = (details |> Seq.map (fun r -> r.RuntimeInSeconds)),\r\n y = (details |> Seq.map (fun r -> r.ValidationMetrics.MeanAbsoluteError)),\r\n mode = \"markers\",\r\n marker = Marker(size = 12)))\r\n\r\nlet chart = Chart.Plot(scatters)\r\nchart.WithXTitle(\"Training Time\")\r\nchart.WithYTitle(\"Error\")\r\ndisplay(chart)\r\n\r\nConsole.WriteLine(\"Best Trainer:{0}\", result.BestRun.TrainerName);", "_____no_output_____" ] ], [ [ "### Validate and display the results ", "_____no_output_____" ] ], [ [ "let testResults = result.BestRun.Model.Transform(housing_test)\r\n\r\nlet trueValues = testResults.GetColumn<float32>(\"median_house_value\")\r\nlet predictedValues = testResults.GetColumn<float32>(\"Score\")\r\n\r\nlet predictedVsTrue =\r\n Scattergl(\r\n x = trueValues,\r\n y = predictedValues,\r\n mode = \"markers\")\r\n\r\nlet maximumValue = Math.Max(Seq.max trueValues, Seq.max predictedValues)\r\n\r\nlet perfectLine =\r\n Scattergl(\r\n x = [| 0.0f; maximumValue |],\r\n y = [| 0.0f; maximumValue |],\r\n mode = \"lines\")\r\n\r\nlet chart = Chart.Plot([| predictedVsTrue; perfectLine |])\r\nchart.WithXTitle(\"True Values\")\r\nchart.WithYTitle(\"Predicted Values\")\r\nchart.WithLegend(false)\r\nchart.Width = 600\r\nchart.Height = 600\r\ndisplay(chart)", "_____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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01b64a1f66ea8e8a9013e999d3350ae8f9277b2
419,428
ipynb
Jupyter Notebook
Lectures/1_ComputationalAndInferentialThinking/03_Featurization_and_NLP.ipynb
ijpulidos/ml_course
765e66e1a0c3c756aaf393147d3ae75403be2b4f
[ "BSD-3-Clause" ]
null
null
null
Lectures/1_ComputationalAndInferentialThinking/03_Featurization_and_NLP.ipynb
ijpulidos/ml_course
765e66e1a0c3c756aaf393147d3ae75403be2b4f
[ "BSD-3-Clause" ]
null
null
null
Lectures/1_ComputationalAndInferentialThinking/03_Featurization_and_NLP.ipynb
ijpulidos/ml_course
765e66e1a0c3c756aaf393147d3ae75403be2b4f
[ "BSD-3-Clause" ]
null
null
null
76.370721
61,500
0.725281
[ [ [ "ML Course, Bogotá, Colombia (&copy; Josh Bloom; June 2019)", "_____no_output_____" ] ], [ [ "%run ../talktools.py", "_____no_output_____" ] ], [ [ "# Featurization and Dirty Data (and NLP)", "_____no_output_____" ], [ "<img src=\"imgs/workflow.png\">\nSource: [V. Singh](https://www.slideshare.net/hortonworks/data-science-workshop)\n\n### Notes:\n\nBiased workflow :)\n\n* Labels → Answer\n* Feature extraction. Taking images/data and manipulate it, and do a feature matrix, each feature is a number (measurable). Domain-specific.\n* Run a ML model on the featurized data. Split in validation and test sets.\n* After predicting and validating results, the new results can become new training data. But you have to beware of skewing the results or the training data → introducing bias. One way to fight this is randomize sampling/results? (I didn't understand how to do this tbh).", "_____no_output_____" ], [ "<img src=\"imgs/feature.png\">\nSource: Lightsidelabs\n", "_____no_output_____" ], [ "<img src=\"imgs/feature2.png\">", "_____no_output_____" ], [ "# Featurization Examples\n\nIn the real world, we are very rarely presented with a clean feature matrix. Raw data are missing, noisy, ugly and unfiltered. And sometimes we dont even have the data we need to make models and predictions. Indeed the conversion of raw data to data that's suitable for learning on is time consuming, difficult, and where a lot of the domain understanding is required.\n\nWhen we extract features from raw data (say PDF documents) we often are presented with a variety of data types:\n<img src=\"imgs/feat.png\">", "_____no_output_____" ], [ "# Categorical & Missing Features\n\n\nOften times, we might be presented with raw data (say from an Excel spreadsheet) that looks like:\n\n| eye color | height | country of origin | gender |\n| ------------| ---------| ---------------------| ------- |\n| brown | 1.85 | Colombia | M |\n| brown | 1.25 | USA | |\n| blonde | 1.45 | Mexico | F |\n| red | 2.01 | Mexico | F |\n| | | Chile | F |\n| Brown | 1.02 | Colombia | | \n\nWhat do you notice in this dataset? \n\nSince many ML learn algorithms require, as we'll see, a full matrix of numerical input features, there's often times a lot of preprocessing work that is needed before we can learn.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame({\"eye color\": [\"brown\", \"brown\", \"blonde\", \"red\", None, \"Brown\"],\n \"height\": [1.85, 1.25, 1.45, 2.01, None, 1.02],\n \"country of origin\": [\"Colombia\", \"USA\", \"Mexico\", \"Mexico\", \"Chile\", \"Colombia\"],\n \"gender\": [\"M\", None, \"F\", \"F\",\"F\", None]})\ndf", "_____no_output_____" ] ], [ [ "Let's first normalize the data so it's all lower case. This will handle the \"Brown\" and \"brown\" issue.", "_____no_output_____" ] ], [ [ "df_new = df.copy()\ndf_new[\"eye color\"] = df_new[\"eye color\"].str.lower()\ndf_new", "_____no_output_____" ] ], [ [ "Let's next handle the NaN in the height. What should we use here?", "_____no_output_____" ] ], [ [ "# mean of everyone?\nnp.nanmean(df_new[\"height\"].values)", "_____no_output_____" ], [ "# mean of just females?\nnp.nanmean(df_new[df_new[\"gender\"] == 'F'][\"height\"]) ", "_____no_output_____" ], [ "df_new1 = df_new.copy()\ndf_new1.at[4, \"height\"] = np.nanmean(df_new[df_new[\"gender\"] == 'F'][\"height\"]) \ndf_new1", "_____no_output_____" ] ], [ [ "Let's next handle the eye color. What should we use?", "_____no_output_____" ] ], [ [ "df_new1[\"eye color\"].mode()", "_____no_output_____" ], [ "df_new2 = df_new1.copy()\ndf_new2.at[4, \"eye color\"] = df_new1[\"eye color\"].mode().values[0]\ndf_new2", "_____no_output_____" ] ], [ [ "How should we handle the missing gender entries?", "_____no_output_____" ] ], [ [ "df_new3 = df_new2.fillna(\"N/A\")\ndf_new3", "_____no_output_____" ] ], [ [ "We're done, right? No. We fixed the dirty, missing data problem but we still dont have a numerical feature matrix.\n\nWe could do a mapping such that \"Colombia\" -> 1, \"USA\" -> 2, ... etc. but then that would imply an ordering between what is fundamentally categories (without ordering). Instead we want to do `one-hot encoding`, where every unique value gets its own column. `pandas` as a method on DataFrames called `get_dummies` which does this for us.\n\n### Notes:\n\nMany algorithms/methods cannot handle cathegorical data, that's why you have to do the `one-hot encoding` \"trick\". An example of one that can handle it is Random forest.", "_____no_output_____" ] ], [ [ "pd.get_dummies(df_new3, prefix=['eye color', 'country of origin', 'gender'])", "_____no_output_____" ] ], [ [ "Note: depending on the learning algorithm you use, you may want to do `drop_first=True` in `get_dummies`.", "_____no_output_____" ], [ "Of course there are helpful tools that exist for us to deal with dirty, missing data.", "_____no_output_____" ] ], [ [ "%run transform", "_____no_output_____" ], [ "bt = BasicTransformer(return_df=True)\nbt.fit_transform(df_new)", "_____no_output_____" ] ], [ [ "## Time series\n\nThe [wafer dataset](http://www.timeseriesclassification.com/description.php?Dataset=Wafer) is a set of timeseries capturing sensor measurements (1000 training examples, 6164 test examples) of one silicon wafer during the manufacture of semiconductors. Each wafer has a classification of normal or abnormal. The abnormal wafers are representative of a range of problems commonly encountered during semiconductor manufacturing.", "_____no_output_____" ] ], [ [ "import requests\nfrom io import StringIO\ndat_file = requests.get(\"https://github.com/zygmuntz/time-series-classification/blob/master/data/wafer/Wafer.csv?raw=true\")\ndata = StringIO(dat_file.text)", "_____no_output_____" ], [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\ndata.seek(0)\ndf = pd.read_csv(data, header=None)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "0 to 151 time measurements, the latest colum is the label we are trying to predict.", "_____no_output_____" ] ], [ [ "df[152].value_counts()", "_____no_output_____" ], [ "## save the data as numpy arrays\ntarget = df.values[:,152].astype(int)\ntime_series = df.values[:,0:152]", "_____no_output_____" ], [ "normal_inds = np.argwhere(target == 1) ; np.random.shuffle(normal_inds)\nabnormal_inds = np.argwhere(target == -1); np.random.shuffle(abnormal_inds)\n\nnum_to_plot = 3\nfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(12,6))\n\nfor i in range(num_to_plot):\n ax1.plot(time_series[normal_inds[i][0],:], label=f\"#{normal_inds[i][0]}: {target[normal_inds[i][0]]}\")\n ax2.plot(time_series[abnormal_inds[i][0],:], label=f\"#{abnormal_inds[i][0]}: {target[abnormal_inds[i][0]]}\")\n\nax1.legend()\nax2.legend()\nax1.set_title(\"Normal\") ; ax2.set_title(\"Abnormal\") \nax1.set_xlabel(\"time\") ; ax2.set_xlabel(\"time\")\nax1.set_ylabel(\"Value\")", "_____no_output_____" ] ], [ [ "What would be good features here?", "_____no_output_____" ] ], [ [ "f1 = np.mean(time_series, axis=1) # how about the mean?\nf1.shape", "_____no_output_____" ], [ "import seaborn as sns, numpy as np\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nax = sns.distplot(f1)", "_____no_output_____" ], [ "# Plotting differences of means between normal and abnormal\nax = sns.distplot(f1[normal_inds], kde_kws={\"label\": \"normal\"})\nsns.distplot(f1[abnormal_inds], ax=ax, kde_kws={\"label\": \"abnormal\"})", "_____no_output_____" ], [ "f2 = np.min(time_series, axis=1) # how about the mean?\nf2.shape", "_____no_output_____" ], [ "# Differences in the minimum - Not much difference, just a small subset at the \"end that can tell something interesting\nax = sns.distplot(f2[normal_inds], kde_kws={\"label\": \"normal\"})\nsns.distplot(f2[abnormal_inds], ax=ax, kde_kws={\"label\": \"abnormal\"})", "_____no_output_____" ] ], [ [ "Often there are entire python packages devoted to help us build features from certain types of datasets (timeseries, text, images, movies, etc.). In the case of timeseries, a popular package is `tsfresh` (*\"It automatically calculates a large number of time series characteristics, the so called features. Further the package contains methods to evaluate the explaining power and importance of such characteristics for regression or classification tasks.\"*). See the [tsfresh docs](https://tsfresh.readthedocs.io/en/latest/) and the [list of features generated](https://tsfresh.readthedocs.io/en/latest/text/list_of_features.html).", "_____no_output_____" ] ], [ [ "# !pip install tsfresh", "_____no_output_____" ], [ "dfc = df.copy()\ndel dfc[152]\nd = dfc.stack()\nd = d.reset_index()\nd = d.rename(columns={\"level_0\": \"id\", \"level_1\": \"time\", 0: \"value\"})\ny = df[152]", "_____no_output_____" ], [ "from tsfresh import extract_features\n\nmax_num=300\n\nfrom tsfresh import extract_relevant_features\n\nfeatures_filtered_direct = extract_relevant_features(d[d[\"id\"] < max_num], y.iloc[0:max_num],\n column_id='id', column_sort='time', n_jobs=4)\n#extracted_features = extract_features(, column_id=\"id\", \n # column_sort=\"time\", disable_progressbar=False, n_jobs=3)", "Feature Extraction: 100%|██████████| 20/20 [00:19<00:00, 1.01it/s]\nWARNING:tsfresh.utilities.dataframe_functions:The columns ['value__fft_coefficient__coeff_77__attr_\"abs\"'\n 'value__fft_coefficient__coeff_77__attr_\"angle\"'\n 'value__fft_coefficient__coeff_77__attr_\"imag\"'\n 'value__fft_coefficient__coeff_77__attr_\"real\"'\n 'value__fft_coefficient__coeff_78__attr_\"abs\"'\n 'value__fft_coefficient__coeff_78__attr_\"angle\"'\n 'value__fft_coefficient__coeff_78__attr_\"imag\"'\n 'value__fft_coefficient__coeff_78__attr_\"real\"'\n 'value__fft_coefficient__coeff_79__attr_\"abs\"'\n 'value__fft_coefficient__coeff_79__attr_\"angle\"'\n 'value__fft_coefficient__coeff_79__attr_\"imag\"'\n 'value__fft_coefficient__coeff_79__attr_\"real\"'\n 'value__fft_coefficient__coeff_80__attr_\"abs\"'\n 'value__fft_coefficient__coeff_80__attr_\"angle\"'\n 'value__fft_coefficient__coeff_80__attr_\"imag\"'\n 'value__fft_coefficient__coeff_80__attr_\"real\"'\n 'value__fft_coefficient__coeff_81__attr_\"abs\"'\n 'value__fft_coefficient__coeff_81__attr_\"angle\"'\n 'value__fft_coefficient__coeff_81__attr_\"imag\"'\n 'value__fft_coefficient__coeff_81__attr_\"real\"'\n 'value__fft_coefficient__coeff_82__attr_\"abs\"'\n 'value__fft_coefficient__coeff_82__attr_\"angle\"'\n 'value__fft_coefficient__coeff_82__attr_\"imag\"'\n 'value__fft_coefficient__coeff_82__attr_\"real\"'\n 'value__fft_coefficient__coeff_83__attr_\"abs\"'\n 'value__fft_coefficient__coeff_83__attr_\"angle\"'\n 'value__fft_coefficient__coeff_83__attr_\"imag\"'\n 'value__fft_coefficient__coeff_83__attr_\"real\"'\n 'value__fft_coefficient__coeff_84__attr_\"abs\"'\n 'value__fft_coefficient__coeff_84__attr_\"angle\"'\n 'value__fft_coefficient__coeff_84__attr_\"imag\"'\n 'value__fft_coefficient__coeff_84__attr_\"real\"'\n 'value__fft_coefficient__coeff_85__attr_\"abs\"'\n 'value__fft_coefficient__coeff_85__attr_\"angle\"'\n 'value__fft_coefficient__coeff_85__attr_\"imag\"'\n 'value__fft_coefficient__coeff_85__attr_\"real\"'\n 'value__fft_coefficient__coeff_86__attr_\"abs\"'\n 'value__fft_coefficient__coeff_86__attr_\"angle\"'\n 'value__fft_coefficient__coeff_86__attr_\"imag\"'\n 'value__fft_coefficient__coeff_86__attr_\"real\"'\n 'value__fft_coefficient__coeff_87__attr_\"abs\"'\n 'value__fft_coefficient__coeff_87__attr_\"angle\"'\n 'value__fft_coefficient__coeff_87__attr_\"imag\"'\n 'value__fft_coefficient__coeff_87__attr_\"real\"'\n 'value__fft_coefficient__coeff_88__attr_\"abs\"'\n 'value__fft_coefficient__coeff_88__attr_\"angle\"'\n 'value__fft_coefficient__coeff_88__attr_\"imag\"'\n 'value__fft_coefficient__coeff_88__attr_\"real\"'\n 'value__fft_coefficient__coeff_89__attr_\"abs\"'\n 'value__fft_coefficient__coeff_89__attr_\"angle\"'\n 'value__fft_coefficient__coeff_89__attr_\"imag\"'\n 'value__fft_coefficient__coeff_89__attr_\"real\"'\n 'value__fft_coefficient__coeff_90__attr_\"abs\"'\n 'value__fft_coefficient__coeff_90__attr_\"angle\"'\n 'value__fft_coefficient__coeff_90__attr_\"imag\"'\n 'value__fft_coefficient__coeff_90__attr_\"real\"'\n 'value__fft_coefficient__coeff_91__attr_\"abs\"'\n 'value__fft_coefficient__coeff_91__attr_\"angle\"'\n 'value__fft_coefficient__coeff_91__attr_\"imag\"'\n 'value__fft_coefficient__coeff_91__attr_\"real\"'\n 'value__fft_coefficient__coeff_92__attr_\"abs\"'\n 'value__fft_coefficient__coeff_92__attr_\"angle\"'\n 'value__fft_coefficient__coeff_92__attr_\"imag\"'\n 'value__fft_coefficient__coeff_92__attr_\"real\"'\n 'value__fft_coefficient__coeff_93__attr_\"abs\"'\n 'value__fft_coefficient__coeff_93__attr_\"angle\"'\n 'value__fft_coefficient__coeff_93__attr_\"imag\"'\n 'value__fft_coefficient__coeff_93__attr_\"real\"'\n 'value__fft_coefficient__coeff_94__attr_\"abs\"'\n 'value__fft_coefficient__coeff_94__attr_\"angle\"'\n 'value__fft_coefficient__coeff_94__attr_\"imag\"'\n 'value__fft_coefficient__coeff_94__attr_\"real\"'\n 'value__fft_coefficient__coeff_95__attr_\"abs\"'\n 'value__fft_coefficient__coeff_95__attr_\"angle\"'\n 'value__fft_coefficient__coeff_95__attr_\"imag\"'\n 'value__fft_coefficient__coeff_95__attr_\"real\"'\n 'value__fft_coefficient__coeff_96__attr_\"abs\"'\n 'value__fft_coefficient__coeff_96__attr_\"angle\"'\n 'value__fft_coefficient__coeff_96__attr_\"imag\"'\n 'value__fft_coefficient__coeff_96__attr_\"real\"'\n 'value__fft_coefficient__coeff_97__attr_\"abs\"'\n 'value__fft_coefficient__coeff_97__attr_\"angle\"'\n 'value__fft_coefficient__coeff_97__attr_\"imag\"'\n 'value__fft_coefficient__coeff_97__attr_\"real\"'\n 'value__fft_coefficient__coeff_98__attr_\"abs\"'\n 'value__fft_coefficient__coeff_98__attr_\"angle\"'\n 'value__fft_coefficient__coeff_98__attr_\"imag\"'\n 'value__fft_coefficient__coeff_98__attr_\"real\"'\n 'value__fft_coefficient__coeff_99__attr_\"abs\"'\n 'value__fft_coefficient__coeff_99__attr_\"angle\"'\n 'value__fft_coefficient__coeff_99__attr_\"imag\"'\n 'value__fft_coefficient__coeff_99__attr_\"real\"'] did not have any finite values. Filling with zeros.\nWARNING:tsfresh.feature_selection.relevance:Infered classification as machine learning task\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__autocorrelation__lag_0 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.2__ql_0.2 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.2__ql_0.4 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.2__ql_0.6 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_True__qh_0.2__ql_0.2 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"var\"__isabs_True__qh_0.2__ql_0.2 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.2__ql_0.8 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.4__ql_0.4 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.4__ql_0.6 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.4__ql_0.8 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"var\"__isabs_True__qh_0.2__ql_0.4 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__fft_coefficient__coeff_0__attr_\"imag\" is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.6__ql_0.6 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_True__qh_0.2__ql_0.4 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_True__qh_0.2__ql_0.6 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_True__qh_0.2__ql_0.8 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.6__ql_0.8 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"var\"__isabs_True__qh_0.2__ql_0.6 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"var\"__isabs_True__qh_0.2__ql_0.8 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_True__qh_0.4__ql_0.4 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"mean\"__isabs_False__qh_0.8__ql_0.8 is constant\nWARNING:tsfresh.feature_selection.relevance:[test_feature_significance] Feature value__change_quantiles__f_agg_\"var\"__isabs_True__qh_0.4__ql_0.4 is constant\n" ], [ "feats = features_filtered_direct[features_filtered_direct.columns[0:4]].rename(lambda x: x[0:14], axis='columns')\nfeats[\"target\"] = y.iloc[0:max_num]\nsns.pairplot(feats, hue=\"target\")", "_____no_output_____" ] ], [ [ "# Text Data\n\nMany applications involve parsing and understanding something about natural language, ie. speech or text data. Categorization is a classic usage of Natural Language Processing (NLP): what bucket does this text belong to? \n\nQuestion: **What are some examples where learning on text has commerical or industrial applications?**", "_____no_output_____" ], [ "A classic dataset in text processing is the [20,000+ newsgroup documents corpus](http://qwone.com/~jason/20Newsgroups/). These texts taken from old discussion threads in 20 different [newgroups](https://en.wikipedia.org/wiki/Usenet_newsgroup):\n\n<pre>\ncomp.graphics\ncomp.os.ms-windows.misc\ncomp.sys.ibm.pc.hardware\ncomp.sys.mac.hardware\ncomp.windows.x\t\nrec.autos\nrec.motorcycles\nrec.sport.baseball\nrec.sport.hockey\t\nsci.crypt\nsci.electronics\nsci.med\nsci.space\nmisc.forsale\t\ntalk.politics.misc\ntalk.politics.guns\ntalk.politics.mideast\t\ntalk.religion.misc\nalt.atheism\nsoc.religion.christian\n</pre>\nOne of the tasks is to assign a document to the correct group, ie. classify which group this belongs to. `sklearn` has a download facility for this dataset:", "_____no_output_____" ] ], [ [ "from sklearn.datasets import fetch_20newsgroups\nnews_train = fetch_20newsgroups(subset='train', categories=['sci.space','rec.autos'], data_home='datatmp/')", "Downloading 20news dataset. This may take a few minutes.\nINFO:sklearn.datasets.twenty_newsgroups:Downloading 20news dataset. This may take a few minutes.\nDownloading dataset from https://ndownloader.figshare.com/files/5975967 (14 MB)\nINFO:sklearn.datasets.twenty_newsgroups:Downloading dataset from https://ndownloader.figshare.com/files/5975967 (14 MB)\n" ], [ "news_train.target_names", "_____no_output_____" ], [ "print(news_train.data[1])", "From: [email protected] (Lawrence C Smith)\nSubject: Re: MR2 - noisy engine.\nOrganization: Cabletron Systems, Inc.\nLines: 16\nDistribution: world\nReply-To: [email protected]\nNNTP-Posting-Host: glinda.ctron.com\n\nIn article <[email protected]>, [email protected] (eliot) writes:\n\n>if the noise really bugs you, there is nothing else that you can do\n>except to sell it and get a V6.\n\nPerhaps a nice used '88 Pontiac Fiero GT? 2.8 liters.\n\nDoes anyone know if the motor mounts for the 2.8 and the twin-dual-cam 3.4\nliter match? The 3.4 is supposedly derived from the pushrod 3.1, which was\na punched out 2.8 liter. Should be a drop-in replacement, eh? 205 horses in\na mid-engine the size of a Fiero?\n\nLarry Smith ([email protected]) No, I don't speak for Cabletron. Need you ask?\n-\nLiberty is not the freedom to do whatever we want,\nit is the freedom to do whatever we are able.\n\n" ], [ "news_train.target_names[news_train.target[1]]", "_____no_output_____" ], [ "autos = np.argwhere(news_train.target == 1) \nsci = np.argwhere(news_train.target == 0)", "_____no_output_____" ] ], [ [ "**How do you (as a human) classify text? What do you look for? How might we make these features?**", "_____no_output_____" ] ], [ [ "# total character count?\nf1 = np.array([len(x) for x in news_train.data])\nf1", "_____no_output_____" ], [ "ax = sns.distplot(f1[autos], kde_kws={\"label\": \"autos\"})\nsns.distplot(f1[sci], ax=ax, kde_kws={\"label\": \"sci\"})\nax.set_xscale(\"log\")\nax.set_xlabel(\"number of charaters\")", "_____no_output_____" ], [ "# total character words?\nf2 = np.array([len(x.split(\" \")) for x in news_train.data])\nf2", "_____no_output_____" ], [ "ax = sns.distplot(f2[autos], kde_kws={\"label\": \"autos\"})\nsns.distplot(f2[sci], ax=ax, kde_kws={\"label\": \"sci\"})\nax.set_xscale(\"log\")\nax.set_xlabel(\"number of words\")", "_____no_output_____" ], [ "# number of questions asked or exclaimations?\nf3 = np.array([x.count(\"?\") + x.count(\"!\") for x in news_train.data])\nf3", "_____no_output_____" ], [ "ax = sns.distplot(f3[autos], kde_kws={\"label\": \"autos\"})\nsns.distplot(f3[sci], ax=ax, kde_kws={\"label\": \"sci\"})\nax.set_xlabel(\"number of questions asked\")", "_____no_output_____" ] ], [ [ "We've got three fairly uninformative features now. We should be able to do better. \nUnsurprisingly, what matters most in NLP is the content: the words used, the tone, the meaning from the ordering of those words. The basic components of NLP are:\n\n * Tokenization - intelligently splitting up words in sentences, paying attention to conjunctions, punctuation, etc.\n * Lemmization - reducing a word to its base form\n * Entity recognition - finding proper names, places, etc. in documents\n \nThere a many Python packages that help with NLP, including `nltk`, `textblob`, `gensim`, etc. Here we'll use the fairly modern and battletested [`spaCy`](https://spacy.io/).\n\n### Notes:\n\n* For tokenization you need to know the language you are dealing with.\n* Lemmization idea is to kind of normalize the whole text content, and maybe reduce words, such as adverbs to adjectives or plurals to singular, etc.\n* For lemmization not only needs the language but also the kind of content you are dealing with.", "_____no_output_____" ] ], [ [ "#!pip install spacy", "_____no_output_____" ], [ "#!python -m spacy download en", "_____no_output_____" ], [ "#!python -m spacy download es", "_____no_output_____" ], [ "import spacy\n\n# Load English tokenizer, tagger, parser, NER and word vectors\nnlp = spacy.load(\"en\")\n\n# the spanish model is\n# nlp = spacy.load(\"es\")\n\ndoc = nlp(u\"Guido said that 'Python is one of the best languages for doing Data Science.' \"\n \"Why he said that should be clear to anyone who knows Python.\")\nen_doc = doc", "_____no_output_____" ] ], [ [ "`doc` is now an `iterable ` with each word/item properly tokenized and tagged. This is done by applying rules specific to each language. Linguistic annotations are available as Token attributes.", "_____no_output_____" ] ], [ [ "for token in doc:\n print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_,\n token.shape_, token.is_alpha, token.is_stop)", "Guido Guido PROPN NNP nsubj Xxxxx True False\nsaid say VERB VBD ROOT xxxx True False\nthat that ADP IN mark xxxx True True\n' ' PUNCT `` punct ' False False\nPython Python PROPN NNP nsubj Xxxxx True False\nis be VERB VBZ ccomp xx True True\none one NUM CD attr xxx True True\nof of ADP IN prep xx True True\nthe the DET DT det xxx True True\nbest good ADJ JJS amod xxxx True False\nlanguages language NOUN NNS pobj xxxx True False\nfor for ADP IN prep xxx True True\ndoing do VERB VBG pcomp xxxx True True\nData Data PROPN NNP compound Xxxx True False\nScience Science PROPN NNP dobj Xxxxx True False\n. . PUNCT . punct . False False\n' ' PUNCT '' punct ' False False\nWhy why ADV WRB advmod Xxx True True\nhe -PRON- PRON PRP nsubj xx True True\nsaid say VERB VBD ROOT xxxx True False\nthat that DET DT nsubj xxxx True True\nshould should VERB MD aux xxxx True True\nbe be VERB VB ccomp xx True True\nclear clear ADJ JJ acomp xxxx True False\nto to ADP IN prep xx True True\nanyone anyone NOUN NN pobj xxxx True True\nwho who PRON WP nsubj xxx True True\nknows know VERB VBZ relcl xxxx True False\nPython Python PROPN NNP dobj Xxxxx True False\n. . PUNCT . punct . False False\n" ], [ "from spacy import displacy\n\ndisplacy.serve(doc, style=\"dep\")", "_____no_output_____" ], [ "displacy.render(doc, style = \"ent\", jupyter = True)", "_____no_output_____" ], [ "nlp = spacy.load(\"es\")", "_____no_output_____" ], [ "# https://www.elespectador.com/noticias/ciencia/decenas-de-nuevas-supernovas-ayudaran-medir-la-expansion-del-universo-articulo-863683\ndoc = nlp(u'En los últimos años, los investigadores comenzaron a'\n 'informar un nuevo tipo de supernovas de cinco a diez veces'\n 'más brillantes que las supernovas de Tipo \"IA\". ')", "_____no_output_____" ], [ "for token in doc:\n print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_,\n token.shape_, token.is_alpha, token.is_stop)", "En En ADP ADP__AdpType=Prep case Xx True True\nlos lo DET DET__Definite=Def|Gender=Masc|Number=Plur|PronType=Art det xxx True True\núltimos último ADJ ADJ__Gender=Masc|Number=Plur|NumType=Ord amod xxxx True True\naños año NOUN NOUN__Gender=Masc|Number=Plur obl xxxx True False\n, , PUNCT PUNCT__PunctType=Comm punct , False False\nlos lo DET DET__Definite=Def|Gender=Masc|Number=Plur|PronType=Art det xxx True True\ninvestigadores investigador NOUN NOUN__Gender=Masc|Number=Plur nsubj xxxx True False\ncomenzaron comenzar AUX AUX__Mood=Ind|Number=Plur|Person=3|Tense=Past|VerbForm=Fin aux xxxx True False\nainformar ainformar VERB VERB__VerbForm=Inf ROOT xxxx True False\nun uno DET DET__Definite=Ind|Gender=Masc|Number=Sing|PronType=Art det xx True True\nnuevo nuevo ADJ ADJ__Gender=Masc|Number=Sing amod xxxx True True\ntipo tipo NOUN NOUN__Gender=Masc|Number=Sing obj xxxx True False\nde de ADP ADP__AdpType=Prep case xx True True\nsupernovas supernova NOUN NOUN__Gender=Fem|Number=Plur nmod xxxx True False\nde de ADP ADP__AdpType=Prep case xx True True\ncinco cincar NUM NUM__Number=Plur|NumType=Card nummod xxxx True True\na a ADP ADP__AdpType=Prep case x True False\ndiez diez NUM NUM__Number=Plur|NumType=Card obj xxxx True False\nvecesmás vecesmás AUX AUX__Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin amod xxxx True False\nbrillantes brillante ADJ ADJ__Number=Plur obj xxxx True False\nque que PRON PRON__PronType=Rel mark xxx True True\nlas los DET DET__Definite=Def|Gender=Fem|Number=Plur|PronType=Art det xxx True True\nsupernovas supernova NOUN NOUN__Gender=Fem|Number=Plur nmod xxxx True False\nde de ADP ADP__AdpType=Prep case xx True True\nTipo Tipo PROPN PROPN___ nmod Xxxx True False\n\" \" PUNCT PUNCT__PunctType=Quot punct \" False False\nIA IA PROPN PROPN___ flat XX True False\n\" \" PUNCT PUNCT__PunctType=Quot punct \" False False\n. . PUNCT PUNCT__PunctType=Peri punct . False False\n" ], [ "from spacy import displacy\n\ndisplacy.serve(doc, style=\"dep\")", "_____no_output_____" ], [ "[i for i in doc.sents]", "_____no_output_____" ] ], [ [ "One very powerful way to featurize text/documents is to count the frequency of words---this is called **bag of words**. Each individual token occurrence frequency is used to generate a feature. So the two sentences become:\n\n```json\n{\"Guido\": 1,\n \"said\": 2,\n \"that\": 2,\n \"Python\": 2,\n \"is\": 1,\n \"one\": 1,\n \"of\": 1,\n \"best\": 1,\n \"languages\": 1,\n \"for\": 1,\n \"Data\": 1,\n \"Science\": 1,\n \"Why\", 1,\n \"he\": 1,\n \"should\": 1,\n \"be\": 1,\n \"anyone\": 1,\n \"who\": 1\n }\n ```\n", "_____no_output_____" ], [ "A corpus of documents can be represented as a matrix with one row per document and one column per token.\n\nQuestion: **What are some challenges you see with brute force BoW?**", "_____no_output_____" ] ], [ [ "from spacy.lang.en.stop_words import STOP_WORDS\nSTOP_WORDS", "_____no_output_____" ] ], [ [ "`sklearn` has a number of helper functions, include the [`CountVectorizer`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html):\n\n> Convert a collection of text documents to a matrix of token counts. This implementation produces a sparse representation of the counts using `scipy.sparse.csr_matrix`.", "_____no_output_____" ] ], [ [ "# the following is from https://www.dataquest.io/blog/tutorial-text-classification-in-python-using-spacy/\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer\nfrom sklearn.base import TransformerMixin\nfrom sklearn.pipeline import Pipeline\nimport string\nfrom spacy.lang.en.stop_words import STOP_WORDS\nfrom spacy.lang.en import English\n\n# Create our list of punctuation marks\npunctuations = string.punctuation\n\n# Create our list of stopwords\nnlp = spacy.load('en')\nstop_words = spacy.lang.en.stop_words.STOP_WORDS\n\n# Load English tokenizer, tagger, parser, NER and word vectors\nparser = English()\n\n# Creating our tokenizer function\ndef spacy_tokenizer(sentence):\n # Creating our token object, which is used to create documents with linguistic annotations.\n mytokens = parser(sentence)\n\n # Lemmatizing each token and converting each token into lowercase\n mytokens = [ word.lemma_.lower().strip() if word.lemma_ != \"-PRON-\" else word.lower_ for word in mytokens ]\n\n # Removing stop words\n mytokens = [ word for word in mytokens if word not in stop_words and word not in punctuations ]\n\n # return preprocessed list of tokens\n return mytokens\n\n# Custom transformer using spaCy\nclass predictors(TransformerMixin):\n def transform(self, X, **transform_params):\n # Cleaning Text\n return [clean_text(text) for text in X]\n\n def fit(self, X, y=None, **fit_params):\n return self\n\n def get_params(self, deep=True):\n return {}\n\n# Basic function to clean the text\ndef clean_text(text):\n # Removing spaces and converting text into lowercase\n return text.strip().lower()", "_____no_output_____" ], [ "bow_vector = CountVectorizer(tokenizer = spacy_tokenizer, ngram_range=(1,1))", "_____no_output_____" ], [ "X = bow_vector.fit_transform([x.text for x in en_doc.sents])", "_____no_output_____" ], [ "X", "_____no_output_____" ], [ "bow_vector.get_feature_names()", "_____no_output_____" ] ], [ [ "Why did we get `datum` as one of our feature names?", "_____no_output_____" ] ], [ [ "X.toarray()", "_____no_output_____" ], [ "doc.text", "_____no_output_____" ] ], [ [ "Let's try a bigger corpus (the newsgroups):", "_____no_output_____" ] ], [ [ "news_train = fetch_20newsgroups(subset='train', \n remove=('headers', 'footers', 'quotes'),\n categories=['sci.space','rec.autos'], data_home='datatmp/')", "_____no_output_____" ], [ "%time X = bow_vector.fit_transform(news_train.data)", "CPU times: user 1.76 s, sys: 2.98 ms, total: 1.76 s\nWall time: 1.76 s\n" ], [ "X", "_____no_output_____" ], [ "bow_vector.get_feature_names()", "_____no_output_____" ] ], [ [ "Most of those features will only appear once and we might not want to include them (as they add noise). In order to reweight the count features into floating point values suitable for usage by a classifier it is very common to use the *tf–idf* transform. \n\nFrom [`sklearn`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html#sklearn.feature_extraction.text.TfidfTransformer): \n\n> Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency. This is a common term weighting scheme in information retrieval, that has also found good use in document classification.\nThe goal of using tf-idf instead of the raw frequencies of occurrence of a token in a given document is to scale down the impact of tokens that occur very frequently in a given corpus and that are hence empirically less informative than features that occur in a small fraction of the training corpus.\n\n\nLet's keep only those terms that show up in at least 3% of the docs, but not those that show up in more than 90%.", "_____no_output_____" ] ], [ [ "tfidf_vector = TfidfVectorizer(tokenizer = spacy_tokenizer, min_df=0.03, max_df=0.9, max_features=1000)", "_____no_output_____" ], [ "%time X = tfidf_vector.fit_transform(news_train.data)", "CPU times: user 1.27 s, sys: 1.23 ms, total: 1.27 s\nWall time: 1.28 s\n" ], [ "tfidf_vector.get_feature_names()", "_____no_output_____" ], [ "X", "_____no_output_____" ], [ "print(X[1,:])", " (0, 29)\t0.3815483132390864\n (0, 179)\t0.3115081012023542\n (0, 242)\t0.44371077138978526\n (0, 83)\t0.3573749506148357\n (0, 138)\t0.25772936628163756\n (0, 74)\t0.31784760138938223\n (0, 182)\t0.44889378780494893\n (0, 282)\t0.25264664433284\n" ], [ "y = news_train.target\nnp.savez(\"tfidf.npz\", X=X.todense(), y=y)", "_____no_output_____" ] ], [ [ "One of the challenges with BoW and TF-IDF is that we lose context. \"Me gusta esta clase, no\" is the same as \"No me gusta esta clase\". \n\nOne way to handle this is with N-grams -- not just frequencies of individual words but of groupings of n-words. Eg. \"Me gusta\", \"gusta esta\", \"esta clase\", \"clase no\", \"no me\" (bigrams). ", "_____no_output_____" ] ], [ [ "bow_vector = CountVectorizer(tokenizer = spacy_tokenizer, ngram_range=(1,2))\nX = bow_vector.fit_transform([x.text for x in en_doc.sents])\nbow_vector.get_feature_names()", "_____no_output_____" ] ], [ [ "As we'll see later in the week, while bigram TF-IDF certainly works to capture some small scale meaning, `word embeddings` tend to do very well.", "_____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", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01b6d5bb14e267937400806014d997776c3d0e3
19,493
ipynb
Jupyter Notebook
workflows/notebooks/calskymodel.ipynb
mfarrera/algorithm-reference-library
7331812aa7cc3501a15d3392cecf6ea65b43f91e
[ "Apache-2.0" ]
null
null
null
workflows/notebooks/calskymodel.ipynb
mfarrera/algorithm-reference-library
7331812aa7cc3501a15d3392cecf6ea65b43f91e
[ "Apache-2.0" ]
null
null
null
workflows/notebooks/calskymodel.ipynb
mfarrera/algorithm-reference-library
7331812aa7cc3501a15d3392cecf6ea65b43f91e
[ "Apache-2.0" ]
null
null
null
34.318662
310
0.615965
[ [ [ "# Calibration of non-isoplanatic low frequency data\n\nThis uses an implementation of the SageCAL algorithm to calibrate a simulated SKA1LOW observation in which sources inside the primary beam have one set of calibration errors and sources outside have different errors.\n\nIn this example, the peeler sources are held fixed in strength and location and only the gains solved. The other sources, inside the primary beam, are partitioned into weak (<5Jy) and strong (>5Jy). The weak sources are processed collectively as an image. The bright sources are processed individually.\n", "_____no_output_____" ] ], [ [ "% matplotlib inline\n\nimport os\nimport sys\n\nsys.path.append(os.path.join('..', '..'))\n\nfrom data_models.parameters import arl_path\n\nresults_dir = arl_path('test_results')\n\nimport numpy\n\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nfrom astropy.wcs.utils import pixel_to_skycoord\n\nfrom matplotlib import pyplot as plt\n\nfrom data_models.memory_data_models import SkyModel\nfrom data_models.polarisation import PolarisationFrame\n\nfrom workflows.arlexecute.execution_support.arlexecute import arlexecute\n\nfrom processing_components.skycomponent.operations import find_skycomponents\nfrom processing_components.calibration.calibration import solve_gaintable\nfrom processing_components.calibration.operations import apply_gaintable, create_gaintable_from_blockvisibility\nfrom processing_components.visibility.base import create_blockvisibility, copy_visibility\nfrom processing_components.image.deconvolution import restore_cube\nfrom processing_components.skycomponent.operations import select_components_by_separation, insert_skycomponent, \\\n select_components_by_flux\nfrom processing_components.image.operations import show_image, qa_image, copy_image, create_empty_image_like\nfrom processing_components.simulation.testing_support import create_named_configuration, create_low_test_beam, \\\n simulate_gaintable, create_low_test_skycomponents_from_gleam\nfrom processing_components.skycomponent.operations import apply_beam_to_skycomponent, find_skycomponent_matches\nfrom processing_components.imaging.base import create_image_from_visibility, advise_wide_field, \\\n predict_skycomponent_visibility\nfrom processing_components.imaging.imaging_functions import invert_function\n\nfrom workflows.arlexecute.calibration.calskymodel_workflows import calskymodel_solve_workflow\n\nfrom processing_components.image.operations import export_image_to_fits\n\nimport logging\n\ndef init_logging():\n log = logging.getLogger()\n logging.basicConfig(filename='%s/skymodel_cal.log' % results_dir,\n filemode='a',\n format='%(thread)s %(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S',\n level=logging.INFO)\nlog = logging.getLogger()\nlogging.info(\"Starting skymodel_cal\")\n", "_____no_output_____" ] ], [ [ "Use Dask throughout", "_____no_output_____" ] ], [ [ "arlexecute.set_client(use_dask=True)\narlexecute.run(init_logging)", "_____no_output_____" ] ], [ [ "We make the visibility. The parameter rmax determines the distance of the furthest antenna/stations used. All over parameters are determined from this number.\n\nWe set the w coordinate to be zero for all visibilities so as not to have to do full w-term processing. This speeds up the imaging steps.", "_____no_output_____" ] ], [ [ "nfreqwin = 1\nntimes = 1\nrmax = 750\nfrequency = numpy.linspace(0.8e8, 1.2e8, nfreqwin)\nif nfreqwin > 1:\n channel_bandwidth = numpy.array(nfreqwin * [frequency[1] - frequency[0]])\nelse:\n channel_bandwidth = [0.4e8]\ntimes = numpy.linspace(-numpy.pi / 3.0, numpy.pi / 3.0, ntimes)\n\nphasecentre=SkyCoord(ra=+30.0 * u.deg, dec=-45.0 * u.deg, frame='icrs', equinox='J2000')\nlowcore = create_named_configuration('LOWBD2', rmax=rmax)\n\nblock_vis = create_blockvisibility(lowcore, times, frequency=frequency,\n channel_bandwidth=channel_bandwidth, weight=1.0, phasecentre=phasecentre,\n polarisation_frame=PolarisationFrame(\"stokesI\"), zerow=True)", "_____no_output_____" ], [ "wprojection_planes=1\nadvice=advise_wide_field(block_vis, guard_band_image=5.0, delA=0.02, \n wprojection_planes=wprojection_planes)\n\nvis_slices = advice['vis_slices']\nnpixel=advice['npixels2']\ncellsize=advice['cellsize']", "_____no_output_____" ] ], [ [ "Generate the model from the GLEAM catalog, including application of the primary beam.", "_____no_output_____" ] ], [ [ "beam = create_image_from_visibility(block_vis, npixel=npixel, frequency=frequency,\n nchan=nfreqwin, cellsize=cellsize, phasecentre=phasecentre)\n\noriginal_gleam_components = create_low_test_skycomponents_from_gleam(flux_limit=1.0,\n phasecentre=phasecentre, frequency=frequency, \n polarisation_frame=PolarisationFrame('stokesI'),\n radius=npixel * cellsize/2.0)\n\nbeam = create_low_test_beam(beam)\npb_gleam_components = apply_beam_to_skycomponent(original_gleam_components, beam, \n flux_limit=0.5)\nfrom matplotlib import pylab\npylab.rcParams['figure.figsize'] = (12.0, 12.0)\npylab.rcParams['image.cmap'] = 'rainbow'\n\n\nshow_image(beam, components=pb_gleam_components, cm='Greys', title='Primary beam plus GLEAM components')\nprint(\"Number of components %d\" % len(pb_gleam_components))", "_____no_output_____" ] ], [ [ "Generate the template image", "_____no_output_____" ] ], [ [ "model = create_image_from_visibility(block_vis, npixel=npixel, \n frequency=[numpy.average(frequency)], \n nchan=1,\n channel_bandwidth=[numpy.sum(channel_bandwidth)], \n cellsize=cellsize, phasecentre=phasecentre)", "_____no_output_____" ] ], [ [ "Create sources to be peeled", "_____no_output_____" ] ], [ [ "peel_distance = 0.16\npeelers = select_components_by_separation(phasecentre, pb_gleam_components, \n min=peel_distance)\ngleam_components = select_components_by_separation(phasecentre, pb_gleam_components, \n max=peel_distance)\nprint(\"There are %d sources inside the primary beam and %d sources outside\"\n % (len(gleam_components), len(peelers)))", "_____no_output_____" ] ], [ [ "Create the model visibilities, applying a different gain table for peeled sources and other components", "_____no_output_____" ] ], [ [ "corrupted_vis = copy_visibility(block_vis, zero=True)\ngt = create_gaintable_from_blockvisibility(block_vis, timeslice='auto')\n\ncomponents_errors = [(p, 1.0) for p in peelers]\ncomponents_errors.append((pb_gleam_components, 0.1))\n\nfor sc, phase_error in components_errors:\n component_vis = copy_visibility(block_vis, zero=True)\n gt = simulate_gaintable(gt, amplitude_error=0.0, phase_error=phase_error)\n component_vis = predict_skycomponent_visibility(component_vis, sc)\n component_vis = apply_gaintable(component_vis, gt)\n corrupted_vis.data['vis'][...]+=component_vis.data['vis'][...]\n \ndirty, sumwt = invert_function(corrupted_vis, model, context='2d')\nqa=qa_image(dirty)\nvmax=qa.data['medianabs']*20.0\nvmin=-qa.data['medianabs']\nprint(qa)\nexport_image_to_fits(dirty, '%s/calskymodel_before_dirty.fits' % results_dir)\nshow_image(dirty, cm='Greys', components=peelers, vmax=vmax, vmin=vmin, title='Peelers')\nshow_image(dirty, cm='Greys', components=gleam_components, vmax=vmax, vmin=vmin, title='Targets')\nplt.show()", "_____no_output_____" ] ], [ [ "Find the components above the threshold", "_____no_output_____" ] ], [ [ "qa = qa_image(dirty)\nvmax=qa.data['medianabs']*20.0\nvmin=-qa.data['medianabs']*2.0\nprint(qa)\nthreshold = 10.0*qa.data['medianabs']\nprint(\"Selecting sources brighter than %f\" % threshold)\ninitial_found_components= find_skycomponents(dirty, threshold=threshold)\nshow_image(dirty, components=initial_found_components, cm='Greys', vmax=vmax, vmin=vmin,\n title='Dirty image plus found components')\nplt.show()", "_____no_output_____" ], [ "peel_distance = 0.16\nflux_threshold=5.0\npeelers = select_components_by_separation(phasecentre, initial_found_components, \n min=peel_distance)\n\ninbeam_components = select_components_by_separation(phasecentre, initial_found_components, \n max=peel_distance)\n\nbright_components = select_components_by_flux(inbeam_components, fmin=flux_threshold)\nfaint_components = select_components_by_flux(inbeam_components, fmax=flux_threshold)\n\nprint(\"%d sources will be peeled (i.e. held fixed but gain solved)\" % len(peelers))\nprint(\"%d bright sources will be processed as components (solved both as component and for gain)\" % len(bright_components))\nprint(\"%d faint sources will be processed collectively as a fixed image and gain solved\" % len(faint_components))\n\nfaint_model = create_empty_image_like(model)\nfaint_model = insert_skycomponent(faint_model, faint_components, insert_method='Lanczos')\n\nshow_image(faint_model, cm='Greys', title='Model for faint sources', vmax=0.3, vmin=-0.03)\nplt.show()\n \ncalskymodel_graph = [arlexecute.execute(SkyModel, nout=1)(components=[p], fixed=True) for p in peelers] \\\n + [arlexecute.execute(SkyModel, nout=1)(components=[b], fixed=False) for b in bright_components] \\\n + [arlexecute.execute(SkyModel, nout=1)(images=[faint_model], fixed=True)]", "_____no_output_____" ] ], [ [ "Run skymodel_cal using dask", "_____no_output_____" ] ], [ [ "corrupted_vis = arlexecute.scatter(corrupted_vis)\ngraph = calskymodel_solve_workflow(corrupted_vis, calskymodel_graph, niter=30, gain=0.25, tol=1e-8)\ncalskymodel, residual_vis = arlexecute.compute(graph, sync=True)", "_____no_output_____" ] ], [ [ "Combine all components for display", "_____no_output_____" ] ], [ [ "skymodel_components = list()\nfor csm in calskymodel:\n skymodel_components += csm[0].components", "_____no_output_____" ] ], [ [ "Check that the peeled sources are not altered", "_____no_output_____" ] ], [ [ "recovered_peelers = find_skycomponent_matches(peelers, skymodel_components, 1e-5)\nok = True\nfor p in recovered_peelers:\n ok = ok and numpy.abs(peelers[p[0]].flux[0,0] - skymodel_components[p[1]].flux[0,0]) < 1e-7\nprint(\"Peeler sources flux unchanged: %s\" % ok)\nok = True\nfor p in recovered_peelers:\n ok = ok and peelers[p[0]].direction.separation(skymodel_components[p[1]].direction).rad < 1e-15\nprint(\"Peeler sources directions unchanged: %s\" % ok)", "_____no_output_____" ] ], [ [ "Now we find the components in the residual image and add those to the existing model", "_____no_output_____" ] ], [ [ "residual, sumwt = invert_function(residual_vis, model, context='2d')\nqa = qa_image(residual)\nvmax=qa.data['medianabs']*30.0\nvmin=-qa.data['medianabs']*3.0\nprint(qa)\nthreshold = 20.0*qa.data['medianabs']\nprint(\"Selecting sources brighter than %f\" % threshold)\n\nfinal_found_components = find_skycomponents(residual, threshold=threshold)\nshow_image(residual, components=final_found_components, cm='Greys', \n title='Residual image after Sagecal with newly identified components', vmax=vmax, vmin=vmin)\n\nplt.show()\n\nfinal_components= skymodel_components + final_found_components", "_____no_output_____" ] ], [ [ "Make a restored image", "_____no_output_____" ] ], [ [ "psf, _ = invert_function(residual_vis, model, dopsf=True, context='2d')\n\ncomponent_image = copy_image(faint_model)\ncomponent_image = insert_skycomponent(component_image, final_components)\nrestored = restore_cube(component_image, psf, residual)\nexport_image_to_fits(restored, '%s/calskymodel_restored.fits' % results_dir)\n\nqa=qa_image(restored, context='Restored image after SageCal')\nprint(qa)\n\nshow_image(restored, components=final_components, cm='Greys', \n title='Restored image after SageCal', vmax=vmax, vmin=vmin)\nplt.show()", "_____no_output_____" ] ], [ [ "Now match the recovered components to the originals", "_____no_output_____" ] ], [ [ "original_bright_components = peelers + bright_components\nmatches = find_skycomponent_matches(final_components, original_bright_components, 3*cellsize)", "_____no_output_____" ] ], [ [ "Look at the range of separations found", "_____no_output_____" ] ], [ [ "separations = [match[2] for match in matches]\nplt.clf()\nplt.hist(separations/cellsize, bins=50)\nplt.title('Separation between input and recovered source in pixels')\nplt.xlabel('Separation in cells (cellsize = %g radians)' % cellsize)\nplt.ylabel('Number')\nplt.show()", "_____no_output_____" ] ], [ [ "Now look at the matches between the original components and those recovered.", "_____no_output_____" ] ], [ [ "totalfluxin = numpy.sum([c.flux[0,0] for c in pb_gleam_components]) \ntotalfluxout = numpy.sum([c.flux[0,0] for c in final_components]) + numpy.sum(faint_model.data)\nprint(\"Recovered %.3f (Jy) of original %.3f (Jy)\" % (totalfluxout, totalfluxin))\nfound = [match[1] for match in matches]\nnotfound = list()\nfor c in range(len(original_bright_components)):\n if c not in found:\n notfound.append(c)\n \nprint(\"The following original components were not found\", notfound)", "_____no_output_____" ] ], [ [ "Look at the recovered flux and the location of the unmatched components. From the image display these seem to be blends of close components.", "_____no_output_____" ] ], [ [ "fluxin = [original_bright_components[match[1]].flux[0,0] for match in matches]\nfluxout = [final_components[match[0]].flux[0,0] for match in matches]\nmissed_components = [original_bright_components[c] for c in notfound]\nmissed_flux = [match.flux[0,0] for match in missed_components]\n \nplt.clf()\nplt.plot(fluxin, fluxout, '.', color='blue')\nplt.plot(missed_flux, len(missed_flux)*[0.0], '.', color='red')\n\nplt.title('Recovered flux')\nplt.xlabel('Component input flux')\nplt.ylabel('Component recovered flux')\nplt.show()\n\nshow_image(restored, components=missed_components, cm='Greys', \n title='Restored original model with missing components', vmax=vmax, vmin=vmin)\nplt.show()\n", "_____no_output_____" ], [ "arlexecute.close()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d01b7182869882c8eaa4f44a26dd1c7cc6a33ae3
9,633
ipynb
Jupyter Notebook
additional_content/baselines/multiple_linear_regression_cell_based-R2B5.ipynb
agrundner24/iconml_clc
a9f3547fae15593288066fe1d30631a99e4ccbeb
[ "MIT" ]
null
null
null
additional_content/baselines/multiple_linear_regression_cell_based-R2B5.ipynb
agrundner24/iconml_clc
a9f3547fae15593288066fe1d30631a99e4ccbeb
[ "MIT" ]
null
null
null
additional_content/baselines/multiple_linear_regression_cell_based-R2B5.ipynb
agrundner24/iconml_clc
a9f3547fae15593288066fe1d30631a99e4ccbeb
[ "MIT" ]
null
null
null
24.7
150
0.564518
[ [ [ "## Multiple linear regression\n\n**For Table 3 of the paper**\n\nCell-based QUBICC R2B5 model", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.regularizers import l1_l2\nimport tensorflow as tf\nimport tensorflow.nn as nn\nimport gc\nimport numpy as np\nimport pandas as pd\nimport importlib\nimport os\nimport sys\n\n#Import sklearn before tensorflow (static Thread-local storage)\nfrom sklearn.preprocessing import StandardScaler\n\nfrom tensorflow.keras.optimizers import Nadam\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, BatchNormalization\n\npath = '/pf/b/b309170'\npath_data = path + '/my_work/icon-ml_data/cloud_cover_parameterization/grid_cell_based_QUBICC_R02B05/based_on_var_interpolated_data'\n\n# Add path with my_classes to sys.path\nsys.path.insert(0, path + '/workspace_icon-ml/cloud_cover_parameterization/')\n\nimport my_classes\nimportlib.reload(my_classes)\nfrom my_classes import simple_sundqvist_scheme\nfrom my_classes import write_infofile\nfrom my_classes import load_data\n\nimport matplotlib.pyplot as plt\nimport time\n\nNUM = 1", "_____no_output_____" ], [ "# Prevents crashes of the code\ngpus = tf.config.list_physical_devices('GPU')\ntf.config.set_visible_devices(gpus[0], 'GPU')", "_____no_output_____" ], [ "# Allow the growth of memory Tensorflow allocates (limits memory usage overall)\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)", "_____no_output_____" ], [ "scaler = StandardScaler()", "_____no_output_____" ], [ "# Data is not yet normalized\ninput_data = np.load(path_data + '/cloud_cover_input_qubicc.npy', mmap_mode='r')\noutput_data = np.load(path_data + '/cloud_cover_output_qubicc.npy', mmap_mode='r')", "_____no_output_____" ], [ "(samples_total, no_of_features) = input_data.shape\nassert no_of_features < samples_total # Making sure there's no mixup", "_____no_output_____" ], [ "# Scale the input data = (samples_total, no_of_features)\nscaler.fit(input_data)\nassert len(scaler.mean_) == no_of_features # Every feature has its own mean and std and we scale accordingly\ninput_data_scaled = scaler.transform(input_data)", "_____no_output_____" ] ], [ [ "### Training the multiple linear model on the entire data set", "_____no_output_____" ] ], [ [ "t0 = time.time()\n\n# The optimal multiple linear regression model\nlin_reg = LinearRegression()\nlin_reg.fit(input_data_scaled, output_data)\n\nprint(time.time() - t0)", "114.00159311294556\n" ], [ "# Loss of this optimal multiple linear regression model\nclc_predictions = lin_reg.predict(input_data_scaled)\nlin_mse = mean_squared_error(output_data, clc_predictions)\nprint('The mean squared error of the linear model is %.2f.'%lin_mse) ", "The mean squared error of the linear model is 401.47.\n" ] ], [ [ "### Zero Output Model", "_____no_output_____" ] ], [ [ "np.mean(output_data**2, dtype=np.float64)", "_____no_output_____" ] ], [ [ "### Constant Output Model", "_____no_output_____" ] ], [ [ "mean = np.mean(output_data, dtype=np.float64)\nnp.mean((output_data-mean)**2, dtype=np.float64)", "_____no_output_____" ] ], [ [ "### Randomly initialized neural network", "_____no_output_____" ] ], [ [ "# Create the model\nmodel = Sequential()\n\n# First hidden layer\nmodel.add(Dense(units=64, activation='tanh', input_dim=no_of_features, \n kernel_regularizer=l1_l2(l1=0.004749, l2=0.008732)))\n\n# Second hidden layer\nmodel.add(Dense(units=64, activation=nn.leaky_relu, kernel_regularizer=l1_l2(l1=0.004749, l2=0.008732)))\n# model.add(Dropout(0.221)) # We drop 18% of the hidden nodes\nmodel.add(BatchNormalization())\n\n# Third hidden layer\nmodel.add(Dense(units=64, activation='tanh', kernel_regularizer=l1_l2(l1=0.004749, l2=0.008732)))\n# model.add(Dropout(0.221)) # We drop 18% of the hidden nodes\n\n# Output layer\nmodel.add(Dense(1, activation='linear', kernel_regularizer=l1_l2(l1=0.004749, l2=0.008732)))\nmodel.compile(loss='mse', optimizer=Nadam())", "_____no_output_____" ], [ "# model_fold_3 is implemented in ICON-A\nbatch_size = 2**20\n\nfor i in range(1 + input_data_scaled.shape[0]//batch_size):\n if i == 0:\n clc_predictions = model.predict_on_batch(input_data_scaled[i*batch_size:(i+1)*batch_size])\n else:\n clc_predictions = np.concatenate((clc_predictions, model.predict_on_batch(input_data_scaled[i*batch_size:(i+1)*batch_size])), axis=0)\n K.clear_session()\n gc.collect()", "_____no_output_____" ], [ "lin_mse = mean_squared_error(output_data, clc_predictions[:, 0])\nprint('The mean squared error of the randomly initialized neural network is %.2f.'%lin_mse) ", "The mean squared error of the randomly initialized neural network is 913.91.\n" ] ], [ [ "### Simplified Sundqvist function\n\ninput_data is unscaled", "_____no_output_____" ] ], [ [ "qv = input_data[:, 0]\ntemp = input_data[:, 3]\npres = input_data[:, 4]", "_____no_output_____" ], [ "t0 = time.time()\n\n# 0.001% of the data\nind = np.random.randint(0, samples_total, samples_total//10**5)\n\n# Entries will be in [0, 1]\nsundqvist = []\nfor i in ind:\n sundqvist.append(simple_sundqvist_scheme(qv[i], temp[i], pres[i], ps=101325))\n \ntime.time() - t0", "_____no_output_____" ], [ "np.mean((output_data[ind] - 100*np.array(sundqvist))**2, dtype=np.float64)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d01b8184bc542c0eb04cad0e78eae2d60a5d87cd
21,467
ipynb
Jupyter Notebook
lessons/swc-python/python-05-errors.ipynb
leelasd/2014-07-08-stonybrook
0658e583fa8e59bac9162208524f19b24c21316a
[ "CC-BY-3.0" ]
4
2015-02-06T20:46:23.000Z
2021-11-26T08:27:12.000Z
lessons/swc-python/python-05-errors.ipynb
geocarpentry/2014-01-21-erdc
a16757d0095faca247e110b9e876d834d6f0992d
[ "CC-BY-3.0" ]
1
2016-06-27T23:03:38.000Z
2016-06-27T23:03:38.000Z
lessons/swc-python/python-05-errors.ipynb
geocarpentry/2014-01-21-erdc
a16757d0095faca247e110b9e876d834d6f0992d
[ "CC-BY-3.0" ]
2
2016-03-12T02:28:13.000Z
2017-05-01T20:43:22.000Z
35.838063
568
0.569525
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d01b83413b0fd33db32643cf14706337c3ea7297
3,813
ipynb
Jupyter Notebook
notebooks/BurgosLoad.ipynb
zach-data/rgsnotebooks
e625ed2fe44d78e6f526aee492a752fd385a703d
[ "Apache-2.0" ]
1
2020-10-21T19:58:01.000Z
2020-10-21T19:58:01.000Z
notebooks/BurgosLoad.ipynb
zach-data/rgsnotebooks
e625ed2fe44d78e6f526aee492a752fd385a703d
[ "Apache-2.0" ]
null
null
null
notebooks/BurgosLoad.ipynb
zach-data/rgsnotebooks
e625ed2fe44d78e6f526aee492a752fd385a703d
[ "Apache-2.0" ]
1
2019-08-01T17:18:00.000Z
2019-08-01T17:18:00.000Z
26.296552
125
0.538421
[ [ [ "!git -C /home/ec2-user/SageMaker/burgos pull\n!/home/ec2-user/SageMaker/rgs/miniconda/envs/rgsutils/bin/pip install -e /home/ec2-user/SageMaker/burgos --upgrade", "remote: Enumerating objects: 9, done.\u001b[K\nremote: Counting objects: 100% (9/9), done.\u001b[K\nremote: Compressing objects: 100% (1/1), done.\u001b[K\nremote: Total 5 (delta 4), reused 5 (delta 4), pack-reused 0\u001b[K\nUnpacking objects: 100% (5/5), done.\nFrom https://github.com/zach-data/burgos\n 0555fd7..5fbd382 development -> origin/development\nUpdating 0555fd7..5fbd382\nFast-forward\n burgos/db/_clients.py | 15 \u001b[32m++++++++\u001b[m\u001b[31m-------\u001b[m\n 1 file changed, 8 insertions(+), 7 deletions(-)\nObtaining file:///home/ec2-user/SageMaker/burgos\nInstalling collected packages: burgos\n Found existing installation: burgos 0.0.4\n Uninstalling burgos-0.0.4:\n Successfully uninstalled burgos-0.0.4\n Running setup.py develop for burgos\nSuccessfully installed burgos\n" ], [ "import burgos\nprint(burgos.__version__)\ncontext = burgos.ConfigurationManager()\nredshift = burgos.RedshiftManager(context)", "0.0.4\n" ], [ "redshift.load_table('tpch','10gb','nation')", "\n COPY nation \n FROM 's3://redshift-managed-loads-datasets-us-east-1/dataset=tpch/size=10GB/table=nation/nation.manifest' \n iam_role 'arn:aws:iam::029328890439:role/rgs-5d224842-IamRoleStack-17AR6NN4I0B-RedshiftRole-TLNR44OVSWTQ' \n gzip \n delimiter '|' \n COMPUPDATE OFF \n MANIFEST\n \nRow(tablename='\"tpch_10gb\".\"nation\"', rows=50)\nRow(tablename='\"tpch_10gb\".\"nation\"', rows=280)\n" ], [ "tables = ['nation', 'region', 'part', 'supplier', 'partsupp', 'customer', 'orders', 'lineitem']\nfor table in tables:\nredshift.load_table('tpch','1tb','nation')", "['arn', 'aws', 'sagemaker', 'us-east-1', '029328890439', 'notebook-instance/rgs-5d224842-notebook']\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
d01b90a308219f2aeacb092c9ad5cf549d576beb
7,991
ipynb
Jupyter Notebook
ImageColorizerColab.ipynb
pabenz99/DeOldify
c6f28b9557cba1d38b580ae2bbfef2845103a7b3
[ "MIT" ]
19
2020-07-22T14:38:20.000Z
2021-12-20T02:32:09.000Z
ImageColorizerColab.ipynb
pabenz99/DeOldify
c6f28b9557cba1d38b580ae2bbfef2845103a7b3
[ "MIT" ]
4
2021-03-19T15:22:41.000Z
2022-03-12T00:50:52.000Z
ImageColorizerColab.ipynb
pabenz99/DeOldify
c6f28b9557cba1d38b580ae2bbfef2845103a7b3
[ "MIT" ]
2
2021-01-22T13:29:01.000Z
2021-08-23T10:00:27.000Z
26.636667
565
0.58253
[ [ [ "<a href=\"https://colab.research.google.com/github/jantic/DeOldify/blob/master/ImageColorizerColab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "### **<font color='blue'> Artistic Colorizer </font>**", "_____no_output_____" ], [ "#◢ DeOldify - Colorize your own photos!\n\n####**Credits:**\n\nSpecial thanks to:\n\nMatt Robinson and María Benavente for pioneering the DeOldify image colab notebook. \n\nDana Kelley for doing things, breaking stuff & having an opinion on everything.", "_____no_output_____" ], [ "\n\n---\n\n\n#◢ Verify Correct Runtime Settings\n\n**<font color='#FF000'> IMPORTANT </font>**\n\nIn the \"Runtime\" menu for the notebook window, select \"Change runtime type.\" Ensure that the following are selected:\n* Runtime Type = Python 3\n* Hardware Accelerator = GPU \n", "_____no_output_____" ], [ "#◢ Git clone and install DeOldify", "_____no_output_____" ] ], [ [ "!git clone https://github.com/jantic/DeOldify.git DeOldify ", "_____no_output_____" ], [ "cd DeOldify", "_____no_output_____" ] ], [ [ "#◢ Setup", "_____no_output_____" ] ], [ [ "#NOTE: This must be the first call in order to work properly!\nfrom deoldify import device\nfrom deoldify.device_id import DeviceId\n#choices: CPU, GPU0...GPU7\ndevice.set(device=DeviceId.GPU0)\n\nimport torch\n\nif not torch.cuda.is_available():\n print('GPU not available.')", "_____no_output_____" ], [ "!pip install -r colab_requirements.txt", "_____no_output_____" ], [ "import fastai\nfrom deoldify.visualize import *", "_____no_output_____" ], [ "!mkdir 'models'\n!wget https://www.dropbox.com/s/zkehq1uwahhbc2o/ColorizeArtistic_gen.pth?dl=0 -O ./models/ColorizeArtistic_gen.pth", "_____no_output_____" ], [ "!wget https://media.githubusercontent.com/media/jantic/DeOldify/master/resource_images/watermark.png -O ./resource_images/watermark.png", "_____no_output_____" ], [ "colorizer = get_image_colorizer(artistic=True)", "_____no_output_____" ] ], [ [ "#◢ Instructions", "_____no_output_____" ], [ "### source_url\nType in a url to a direct link of an image. Usually that means they'll end in .png, .jpg, etc. NOTE: If you want to use your own image, upload it first to a site like Imgur. \n\n### render_factor\nThe default value of 35 has been carefully chosen and should work -ok- for most scenarios (but probably won't be the -best-). This determines resolution at which the color portion of the image is rendered. Lower resolution will render faster, and colors also tend to look more vibrant. Older and lower quality images in particular will generally benefit by lowering the render factor. Higher render factors are often better for higher quality images, but the colors may get slightly washed out. \n\n### watermarked\nSelected by default, this places a watermark icon of a palette at the bottom left corner of the image. This is intended to be a standard way to convey to others viewing the image that it is colorized by AI. We want to help promote this as a standard, especially as the technology continues to improve and the distinction between real and fake becomes harder to discern. This palette watermark practice was initiated and lead by the company MyHeritage in the MyHeritage In Color feature (which uses a newer version of DeOldify than what you're using here).\n\n#### How to Download a Copy\nSimply right click on the displayed image and click \"Save image as...\"!\n\n## Pro Tips\n\nYou can evaluate how well the image is rendered at each render_factor by using the code at the bottom (that cell under \"See how well render_factor values perform on a frame here\"). ", "_____no_output_____" ], [ "#◢ Colorize!!", "_____no_output_____" ] ], [ [ "source_url = '' #@param {type:\"string\"}\nrender_factor = 35 #@param {type: \"slider\", min: 7, max: 40}\nwatermarked = True #@param {type:\"boolean\"}\n\nif source_url is not None and source_url !='':\n image_path = colorizer.plot_transformed_image_from_url(url=source_url, render_factor=render_factor, compare=True, watermarked=watermarked)\n show_image_in_notebook(image_path)\nelse:\n print('Provide an image url and try again.')", "_____no_output_____" ] ], [ [ "## See how well render_factor values perform on the image here", "_____no_output_____" ] ], [ [ "for i in range(10,40,2):\n colorizer.plot_transformed_image('test_images/image.png', render_factor=i, display_render_factor=True, figsize=(8,8))", "_____no_output_____" ] ], [ [ "---\n#⚙ Recommended image sources \n* [/r/TheWayWeWere](https://www.reddit.com/r/TheWayWeWere/)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01b91f74e99f8c441db9f9f547dcd3931207254
370,344
ipynb
Jupyter Notebook
M2.859_20211_A9_gbonillas.ipynb
gpbonillas/stackoverflow_2021_wrangling_data
14cd6ca5629a07e0ec01c645b21e370af672da09
[ "MIT" ]
null
null
null
M2.859_20211_A9_gbonillas.ipynb
gpbonillas/stackoverflow_2021_wrangling_data
14cd6ca5629a07e0ec01c645b21e370af672da09
[ "MIT" ]
null
null
null
M2.859_20211_A9_gbonillas.ipynb
gpbonillas/stackoverflow_2021_wrangling_data
14cd6ca5629a07e0ec01c645b21e370af672da09
[ "MIT" ]
null
null
null
35.311213
613
0.41928
[ [ [ "<div style=\"width: 100%; clear: both;\">\n<div style=\"float: left; width: 50%;\">\n<img src=\"http://www.uoc.edu/portal/_resources/common/imatges/marca_UOC/UOC_Masterbrand.jpg\" align=\"left\">\n</div>\n<div style=\"float: right; width: 50%;\">\n<p style=\"margin: 0; padding-top: 22px; text-align:right;\">M2.859 · Visualización de datos · Práctica, Parte 2</p>\n<p style=\"margin: 0; text-align:right;\">2021-1 · Máster universitario en Ciencia de datos (Data science)</p>\n<p style=\"margin: 0; text-align:right; padding-button: 100px;\">Estudios de Informática, Multimedia y Telecomunicación</p>\n</div>\n</div>\n<div style=\"width:100%;\">&nbsp;</div>\n\n\n# A9: Práctica Final (parte 2) - Wrangling data\n\n\nEl [**wrangling data**](https://en.wikipedia.org/wiki/Data_wrangling) es el proceso de transformar y mapear datos de un formulario de datos \"sin procesar\" a otro formato con la intención de hacerlo más apropiado y valioso para una variedad de propósitos posteriores, como el análisis. El objetivo del wrangling data es garantizar la calidad y la utilidad de los datos. Los analistas de datos suelen pasar la mayor parte de su tiempo en el proceso de disputa de datos en comparación con el análisis real de los datos.\n\nEl proceso de wrangling data puede incluir más manipulación, visualización de datos, agregación de datos, entrenamiento de un modelo estadístico, así como muchos otros usos potenciales. El wrangling data normalmente sigue un conjunto de pasos generales que comienzan con la extracción de los datos sin procesar de la fuente de datos, \"removiendo\" los datos sin procesar (por ejemplo, clasificación) o analizando los datos en estructuras de datos predefinidas y, finalmente, depositando el contenido resultante en un sumidero de datos para almacenamiento y uso futuro.\n \nPara ello vamos a necesitar las siguientes librerías:", "_____no_output_____" ] ], [ [ "from six import StringIO\n\nfrom IPython.display import Image \nfrom sklearn import datasets\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\nimport pydotplus\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport pandas as pd\npd.set_option('display.max_columns', None)", "_____no_output_____" ] ], [ [ "# 1. Carga del conjunto de datos (1 punto)\n\nSe ha seleccionado un conjunto de datos desde el portal Stack Overflow Annual Developer Survey, que examina todos los aspectos de la experiencia de los programadores de la comunidad (Stack Overflow), desde la satisfacción profesional y la búsqueda de empleo hasta la educación y las opiniones sobre el software de código abierto; y los resultados se publican en la siguiente URL: https://insights.stackoverflow.com/survey.\n\nEn este portal se encuentran publicados los resultados de los últimos 11 años. Para los fines de la práctica final de esta asignatura se usará el dataset del año 2021, cuyo link de descarga es: https://info.stackoverflowsolutions.com/rs/719-EMH-566/images/stack-overflow-developer-survey-2021.zip.", "_____no_output_____" ] ], [ [ "so2021_df = pd.read_csv('survey_results_public.csv', header=0)\nso2021_df.sample(5)", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Selección de variables:</strong> se realiza la selección de todas las variables del dataset que servirán para responder a todas las cuestiones planteadas en la primera parte de la práctica:\n</div>", "_____no_output_____" ] ], [ [ "so2021_data = so2021_df[['MainBranch', 'Employment', 'Country', 'EdLevel', 'Age1stCode', 'YearsCode', 'YearsCodePro', 'DevType', 'CompTotal', 'LanguageHaveWorkedWith', 'DatabaseHaveWorkedWith', 'PlatformHaveWorkedWith', 'WebframeHaveWorkedWith', 'MiscTechHaveWorkedWith', 'ToolsTechHaveWorkedWith', 'NEWCollabToolsHaveWorkedWith', 'OpSys', 'Age', 'Gender', 'Trans', 'Ethnicity', 'MentalHealth', 'ConvertedCompYearly']]\nso2021_data.head(5)", "_____no_output_____" ], [ "so2021_data.shape", "_____no_output_____" ], [ "so2021_data.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 83439 entries, 0 to 83438\nData columns (total 23 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 MainBranch 83439 non-null object \n 1 Employment 83323 non-null object \n 2 Country 83439 non-null object \n 3 EdLevel 83126 non-null object \n 4 Age1stCode 83243 non-null object \n 5 YearsCode 81641 non-null object \n 6 YearsCodePro 61216 non-null object \n 7 DevType 66484 non-null object \n 8 CompTotal 47183 non-null float64\n 9 LanguageHaveWorkedWith 82357 non-null object \n 10 DatabaseHaveWorkedWith 69546 non-null object \n 11 PlatformHaveWorkedWith 52135 non-null object \n 12 WebframeHaveWorkedWith 61707 non-null object \n 13 MiscTechHaveWorkedWith 47055 non-null object \n 14 ToolsTechHaveWorkedWith 72537 non-null object \n 15 NEWCollabToolsHaveWorkedWith 81234 non-null object \n 16 OpSys 83294 non-null object \n 17 Age 82407 non-null object \n 18 Gender 82286 non-null object \n 19 Trans 80678 non-null object \n 20 Ethnicity 79464 non-null object \n 21 MentalHealth 76920 non-null object \n 22 ConvertedCompYearly 46844 non-null float64\ndtypes: float64(2), object(21)\nmemory usage: 14.6+ MB\n" ], [ "so2021_data.isnull().values.any() #valores perdidos en dataset", "_____no_output_____" ], [ "so2021_data.isnull().any() # valores perdidos por columnas en el dataset", "_____no_output_____" ], [ "data = so2021_data.dropna()", "_____no_output_____" ], [ "data.isnull().any() # valores perdidos por columnas en el dataset", "_____no_output_____" ], [ "data.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 15173 entries, 45 to 83437\nData columns (total 23 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 MainBranch 15173 non-null object \n 1 Employment 15173 non-null object \n 2 Country 15173 non-null object \n 3 EdLevel 15173 non-null object \n 4 Age1stCode 15173 non-null object \n 5 YearsCode 15173 non-null object \n 6 YearsCodePro 15173 non-null object \n 7 DevType 15173 non-null object \n 8 CompTotal 15173 non-null float64\n 9 LanguageHaveWorkedWith 15173 non-null object \n 10 DatabaseHaveWorkedWith 15173 non-null object \n 11 PlatformHaveWorkedWith 15173 non-null object \n 12 WebframeHaveWorkedWith 15173 non-null object \n 13 MiscTechHaveWorkedWith 15173 non-null object \n 14 ToolsTechHaveWorkedWith 15173 non-null object \n 15 NEWCollabToolsHaveWorkedWith 15173 non-null object \n 16 OpSys 15173 non-null object \n 17 Age 15173 non-null object \n 18 Gender 15173 non-null object \n 19 Trans 15173 non-null object \n 20 Ethnicity 15173 non-null object \n 21 MentalHealth 15173 non-null object \n 22 ConvertedCompYearly 15173 non-null float64\ndtypes: float64(2), object(21)\nmemory usage: 2.8+ MB\n" ], [ "data.head()", "_____no_output_____" ], [ "data.to_csv('data.csv', index=False)", "_____no_output_____" ], [ "data_test = data.copy()", "_____no_output_____" ], [ "data_test.to_csv('data_test.csv', index=False)", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable Ethnicity:</strong>.\n</div>", "_____no_output_____" ] ], [ [ "from re import search\n\ndef choose_ethnia(cell_ethnia):\n val_ethnia_exceptions = [\"I don't know\", \"Or, in your own words:\"]\n \n if cell_ethnia == \"I don't know;Or, in your own words:\":\n return val_ethnia_exceptions[0]\n \n if search(\";\", cell_ethnia):\n row_ethnia_values = cell_ethnia.split(';', 5)\n first_val = row_ethnia_values[0]\n\n if first_val not in val_ethnia_exceptions:\n return first_val\n\n if len(row_ethnia_values) > 1:\n if row_ethnia_values[1] not in val_ethnia_exceptions:\n return row_ethnia_values[1]\n\n if len(row_ethnia_values) > 2:\n if row_ethnia_values[2] not in val_ethnia_exceptions:\n return row_ethnia_values[2]\n else:\n return cell_ethnia", "_____no_output_____" ], [ "data_test['Ethnicity'] = data_test['Ethnicity'].apply(choose_ethnia)", "_____no_output_____" ], [ "data_test.drop(index=data_test[data_test['Ethnicity'] == 'Or, in your own words:'].index, inplace=True)", "_____no_output_____" ], [ "data_test.drop(index=data_test[data_test['Ethnicity'] == 'Prefer not to say'].index, inplace=True)", "_____no_output_____" ], [ "data_test['Ethnicity'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test['Ethnicity'] = data_test['Ethnicity'].replace(['Black or of African descent'], 'Negro')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace(['East Asian'], 'Asiatico del este')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace(['Hispanic or Latino/a/x'], 'Latino')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace([\"I don't know\"], 'No Definido')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace(['Indigenous (such as Native American, Pacific Islander, or Indigenous Australian)'], 'Indigena')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace(['Middle Eastern'], 'Medio Oriente')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace(['South Asian'], 'Asiatico del Sur')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace(['Southeast Asian'], 'Asiatico del Sudeste')\ndata_test['Ethnicity'] = data_test['Ethnicity'].replace(['White or of European descent'], 'Blanco o Europeo')", "_____no_output_____" ], [ "data_test['Ethnicity'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test.to_csv('data_test.csv', index=False)", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable Employment:</strong>.\n</div>", "_____no_output_____" ] ], [ [ "data_test['Employment'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test['Employment'] = data_test['Employment'].replace(['Employed full-time'], 'Tiempo completo')\ndata_test['Employment'] = data_test['Employment'].replace(['Employed part-time'], 'Tiempo parcial')\ndata_test['Employment'] = data_test['Employment'].replace(['Independent contractor, freelancer, or self-employed'], 'Independiete')", "_____no_output_____" ], [ "data_test['Employment'].drop_duplicates().sort_values()", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable EdLevel:</strong>.\n</div>", "_____no_output_____" ] ], [ [ "data_test['EdLevel'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test['EdLevel'] = data_test['EdLevel'].replace(['Associate degree (A.A., A.S., etc.)'], 'Grado Asociado')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Bachelor’s degree (B.A., B.S., B.Eng., etc.)'], 'Licenciatura')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Master’s degree (M.A., M.S., M.Eng., MBA, etc.)'], 'Master')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Other doctoral degree (Ph.D., Ed.D., etc.)'], 'Doctorado')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Primary/elementary school'], 'Primaria')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Professional degree (JD, MD, etc.)'], 'Grado Profesional')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Secondary school (e.g. American high school, German Realschule or Gymnasium, etc.)'], 'Secundaria')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Some college/university study without earning a degree'], 'Estudios sin grado')\ndata_test['EdLevel'] = data_test['EdLevel'].replace(['Something else'], 'Otro')", "_____no_output_____" ], [ "data_test['EdLevel'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test.to_csv('data_test.csv', index=False)", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable DevType:</strong>.\n</div>", "_____no_output_____" ] ], [ [ "data_test['DevType'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "from re import search\n\ndef choose_devtype(cell_devtype):\n val_devtype_exceptions = [\"Other (please specify):\"]\n \n if cell_devtype == \"Other (please specify):\":\n return val_devtype_exceptions[0]\n \n if search(\";\", cell_devtype):\n row_devtype_values = cell_devtype.split(';', 10)\n first_val = row_devtype_values[0]\n \n if first_val not in val_devtype_exceptions:\n return first_val\n\n if len(row_devtype_values) > 1:\n if row_devtype_values[1] not in val_devtype_exceptions:\n return row_devtype_values[1] \n\n else:\n return cell_devtype", "_____no_output_____" ], [ "data_test['DevType'] = data_test['DevType'].apply(choose_devtype)", "_____no_output_____" ], [ "data_test['DevType'].head()", "_____no_output_____" ], [ "data_test['DevType'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test['DevType'].value_counts()", "_____no_output_____" ], [ "data_test['DevType'] = data_test['DevType'].replace(['Developer, full-stack'], 'Desarrollador full-stack')\ndata_test['DevType'] = data_test['DevType'].replace(['Developer, front-end'], 'Desarrollador front-end')\ndata_test['DevType'] = data_test['DevType'].replace(['Developer, mobile'], 'Desarrollador móvil')\ndata_test['DevType'] = data_test['DevType'].replace(['Developer, back-end'], 'Desarrollador back-end')\ndata_test['DevType'] = data_test['DevType'].replace(['Developer, desktop or enterprise applications'], 'Desarrollador Escritorio')\ndata_test['DevType'] = data_test['DevType'].replace(['Engineer, data'], 'Ingeniero de datos')\ndata_test['DevType'] = data_test['DevType'].replace(['Data scientist or machine learning specialist'], 'Cientifico de datos')\ndata_test['DevType'] = data_test['DevType'].replace(['Other (please specify):'], 'Otro')\ndata_test['DevType'] = data_test['DevType'].replace(['Engineering manager'], 'Manager de Ingeniería')\ndata_test['DevType'] = data_test['DevType'].replace(['DevOps specialist'], 'Especialista en DevOps')\ndata_test['DevType'] = data_test['DevType'].replace(['Senior Executive (C-Suite, VP, etc.)'], 'Ejecutivo Senior')\ndata_test['DevType'] = data_test['DevType'].replace(['Academic researcher'], 'Investigador Académico')\ndata_test['DevType'] = data_test['DevType'].replace(['Developer, QA or test'], 'Desarrollador de QA o Test')\ndata_test['DevType'] = data_test['DevType'].replace(['Data or business analyst'], 'Analista de datos o negocio')\ndata_test['DevType'] = data_test['DevType'].replace(['Developer, embedded applications or devices'], 'Desarrollador de aplicaciones embebidas')\ndata_test['DevType'] = data_test['DevType'].replace(['System administrator'], 'Administrador de sistemas')\ndata_test['DevType'] = data_test['DevType'].replace(['Engineer, site reliability'], 'Ingeniero de confiabilidad del sitio')\ndata_test['DevType'] = data_test['DevType'].replace(['Product manager'], 'Gerente de producto')\ndata_test['DevType'] = data_test['DevType'].replace(['Database administrator'], 'Administrador de base de datos')\ndata_test['DevType'] = data_test['DevType'].replace(['Student'], 'Estudiante')\ndata_test['DevType'] = data_test['DevType'].replace(['Developer, game or graphics'], 'Desarrollador de juegos o gráfico')\ndata_test['DevType'] = data_test['DevType'].replace(['Scientist'], 'Científico')\ndata_test['DevType'] = data_test['DevType'].replace(['Designer'], 'Diseñador')\ndata_test['DevType'] = data_test['DevType'].replace(['Educator'], 'Educador')\ndata_test['DevType'] = data_test['DevType'].replace(['Marketing or sales professional'], 'Profesional en Marketing o ventas')", "_____no_output_____" ], [ "data_test['DevType'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test['DevType'].value_counts()", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable MainBranch:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['MainBranch'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test['MainBranch'] = data_test['MainBranch'].replace(['I am a developer by profession'], 'Desarrollador Profesional')\ndata_test['MainBranch'] = data_test['MainBranch'].replace(['I am not primarily a developer, but I write code sometimes as part of my work'], 'Desarrollador ocasional')", "_____no_output_____" ], [ "data_test['MainBranch'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test.to_csv('data_test.csv', index=False)", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable Age1stCode:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['Age1stCode'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "data_test['Age1stCode'].value_counts()", "_____no_output_____" ], [ "data_test['Age1stCode'] = data_test['Age1stCode'].replace(['11 - 17 years'], '11-17')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['18 - 24 years'], '18-24')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['25 - 34 years'], '25-34')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['35 - 44 years'], '35-44')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['45 - 54 years'], '45-54')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['5 - 10 years'], '5-10')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['55 - 64 years'], '55-64')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['Older than 64 years'], '> 64')\ndata_test['Age1stCode'] = data_test['Age1stCode'].replace(['Younger than 5 years'], '< 5')", "_____no_output_____" ], [ "data_test['Age1stCode'].value_counts()", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable YearsCode:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['YearsCode'] = data_test['YearsCode'].replace(['More than 50 years'], 50)\ndata_test['YearsCode'] = data_test['YearsCode'].replace(['Less than 1 year'], 1)", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable YearsCodePro:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['YearsCodePro'] = data_test['YearsCodePro'].replace(['More than 50 years'], 50)\ndata_test['YearsCodePro'] = data_test['YearsCodePro'].replace(['Less than 1 year'], 1)", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable OpSys:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['OpSys'].value_counts()", "_____no_output_____" ], [ "data_test['OpSys'] = data_test['OpSys'].replace(['Windows Subsystem for Linux (WSL)'], 'Windows')\ndata_test['OpSys'] = data_test['OpSys'].replace(['Linux-based'], 'Linux')\ndata_test['OpSys'] = data_test['OpSys'].replace(['Other (please specify)'], 'Otro')", "_____no_output_____" ], [ "data_test['OpSys'].value_counts()", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable Age:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['Age'].value_counts()", "_____no_output_____" ], [ "data_test['Age'] = data_test['Age'].replace(['25-34 years old'], '25-34')\ndata_test['Age'] = data_test['Age'].replace(['35-44 years old'], '35-44')\ndata_test['Age'] = data_test['Age'].replace(['18-24 years old'], '18-24')\ndata_test['Age'] = data_test['Age'].replace(['45-54 years old'], '45-54')\ndata_test['Age'] = data_test['Age'].replace(['55-64 years old'], '55-64')\ndata_test['Age'] = data_test['Age'].replace(['Under 18 years old'], '< 18')\ndata_test['Age'] = data_test['Age'].replace(['65 years or older'], '>= 65')\ndata_test['Age'] = data_test['Age'].replace(['Prefer not to say'], 'No definido')", "_____no_output_____" ], [ "data_test['Age'] = data_test['Age'].replace(['25-34 years old'], '25-34')", "_____no_output_____" ], [ "data_test['Age'].value_counts()", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable Gender:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['Gender'].value_counts()", "_____no_output_____" ], [ "data_test['Gender'] = data_test['Gender'].replace(['Man'], 'Hombre')\ndata_test['Gender'] = data_test['Gender'].replace(['Woman'], 'Mujer')\ndata_test['Gender'] = data_test['Gender'].replace(['Non-binary, genderqueer, or gender non-conforming'], 'No binario u otro')\ndata_test['Gender'] = data_test['Gender'].replace(['Man;Non-binary, genderqueer, or gender non-conforming'], 'No binario u otro')\ndata_test['Gender'] = data_test['Gender'].replace(['Man;Or, in your own words:'], 'Hombre')\ndata_test['Gender'] = data_test['Gender'].replace(['Or, in your own words:'], 'No definido')\ndata_test['Gender'] = data_test['Gender'].replace(['Woman;Non-binary, genderqueer, or gender non-conforming'], 'No binario u otro')\ndata_test['Gender'] = data_test['Gender'].replace(['Man;Woman'], 'No definido')\ndata_test['Gender'] = data_test['Gender'].replace(['Man;Woman;Non-binary, genderqueer, or gender non-conforming;Or, in your own words:'], 'No binario u otro')\ndata_test['Gender'] = data_test['Gender'].replace(['Non-binary, genderqueer, or gender non-conforming;Or, in your own words:'], 'No binario u otro')\ndata_test['Gender'] = data_test['Gender'].replace(['Man;Woman;Non-binary, genderqueer, or gender non-conforming'], 'No binario u otro')", "_____no_output_____" ], [ "data_test['Gender'] = data_test['Gender'].replace(['Prefer not to say'], 'No definido')", "_____no_output_____" ], [ "data_test['Gender'].value_counts()", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable Trans:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['Trans'].value_counts()", "_____no_output_____" ], [ "data_test['Trans'] = data_test['Trans'].replace(['Yes'], 'Si')\ndata_test['Trans'] = data_test['Trans'].replace(['Prefer not to say'], 'No definido')\ndata_test['Trans'] = data_test['Trans'].replace(['Or, in your own words:'], 'No definido')", "_____no_output_____" ], [ "data_test['Trans'].value_counts()", "_____no_output_____" ] ], [ [ "<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Variable MentalHealth:</strong>\n</div>", "_____no_output_____" ] ], [ [ "data_test['MentalHealth'].value_counts()", "_____no_output_____" ], [ "from re import search\n\ndef choose_mental_health(cell_mental_health):\n val_mental_health_exceptions = [\"Or, in your own words:\"]\n \n if cell_mental_health == \"Or, in your own words:\":\n return val_mental_health_exceptions[0]\n \n if search(\";\", cell_mental_health):\n row_mental_health_values = cell_mental_health.split(';', 10)\n first_val = row_mental_health_values[0]\n \n return first_val\n else:\n return cell_mental_health", "_____no_output_____" ], [ "data_test['MentalHealth'] = data_test['MentalHealth'].apply(choose_mental_health)", "_____no_output_____" ], [ "data_test['MentalHealth'].value_counts()", "_____no_output_____" ], [ "data_test['MentalHealth'] = data_test['MentalHealth'].replace(['None of the above'], 'Ninguna de las mencionadas')\ndata_test['MentalHealth'] = data_test['MentalHealth'].replace(['I have a concentration and/or memory disorder (e.g. ADHD)'], 'Desorden de concentración o memoria')\ndata_test['MentalHealth'] = data_test['MentalHealth'].replace(['I have a mood or emotional disorder (e.g. depression, bipolar disorder)'], 'Desorden emocional')\ndata_test['MentalHealth'] = data_test['MentalHealth'].replace(['I have an anxiety disorder'], 'Desorden de ansiedad')\ndata_test['MentalHealth'] = data_test['MentalHealth'].replace(['Prefer not to say'], 'No definido')\ndata_test['MentalHealth'] = data_test['MentalHealth'].replace([\"I have autism / an autism spectrum disorder (e.g. Asperger's)\"], 'Tipo de autismo')\ndata_test['MentalHealth'] = data_test['MentalHealth'].replace(['Or, in your own words:'], 'No definido')", "_____no_output_____" ], [ "data_test['MentalHealth'].value_counts()", "_____no_output_____" ] ], [ [ "# 2. Selección de campos para subdatasets\n\nSe seleccionarán los campos adecuados para responder a cada una de las cuestiones que se plantearon en la primera parte de la práctica.", "_____no_output_____" ], [ "### 2.1. Según la autodeterminación de la etnia, ¿Qué etnia tiene un mayor sueldo anual?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_etnia = data_test[['Country', 'Ethnicity', 'ConvertedCompYearly']]\ndata_etnia.head()", "_____no_output_____" ], [ "df_data_etnia = data_etnia.copy()", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_data_etnia['ConvertedCompYearly'], 0.1)\n\nprint(df_data_etnia[mask])", " Country Ethnicity ConvertedCompYearly\n45 Brazil Blanco o Europeo 60480.0\n50 Greece Blanco o Europeo 25944.0\n58 Russian Federation Blanco o Europeo 22644.0\n76 Poland Blanco o Europeo 45564.0\n77 Canada Blanco o Europeo 151263.0\n... ... ... ...\n83425 Finland Blanco o Europeo 19452.0\n83428 Brazil Latino 41232.0\n83431 Pakistan Asiatico del Sudeste 11676.0\n83432 Canada Asiatico del este 80169.0\n83436 United States of America Blanco o Europeo 90000.0\n\n[11611 rows x 3 columns]\n" ], [ "df_data_etnia_no_outliers = df_data_etnia[mask]", "_____no_output_____" ], [ "df_data_etnia_no_outliers = df_data_etnia_no_outliers.copy()", "_____no_output_____" ], [ "df_data_etnia_no_outliers['ConvertedCompYearlyCategorical'] = 'ALTO'\ndf_data_etnia_no_outliers.loc[(df_data_etnia_no_outliers['ConvertedCompYearly'] >= 0) & (df_data_etnia_no_outliers['ConvertedCompYearly'] <= 32747), 'ConvertedCompYearlyCategorical'] = 'BAJO'\ndf_data_etnia_no_outliers.loc[(df_data_etnia_no_outliers['ConvertedCompYearly'] > 32747) & (df_data_etnia_no_outliers['ConvertedCompYearly'] <= 90000), 'ConvertedCompYearlyCategorical'] = 'MEDIO'\n\nprint(df_data_etnia_no_outliers)", " Country Ethnicity ConvertedCompYearly \\\n45 Brazil Blanco o Europeo 60480.0 \n50 Greece Blanco o Europeo 25944.0 \n58 Russian Federation Blanco o Europeo 22644.0 \n76 Poland Blanco o Europeo 45564.0 \n77 Canada Blanco o Europeo 151263.0 \n... ... ... ... \n83425 Finland Blanco o Europeo 19452.0 \n83428 Brazil Latino 41232.0 \n83431 Pakistan Asiatico del Sudeste 11676.0 \n83432 Canada Asiatico del este 80169.0 \n83436 United States of America Blanco o Europeo 90000.0 \n\n ConvertedCompYearlyCategorical \n45 MEDIO \n50 BAJO \n58 BAJO \n76 MEDIO \n77 ALTO \n... ... \n83425 BAJO \n83428 MEDIO \n83431 BAJO \n83432 MEDIO \n83436 MEDIO \n\n[11611 rows x 4 columns]\n" ], [ "df_data_etnia_alto = df_data_etnia_no_outliers[df_data_etnia_no_outliers['ConvertedCompYearlyCategorical'] == 'ALTO']", "_____no_output_____" ], [ "df_data_etnia_alto = df_data_etnia_alto[['Ethnicity', 'ConvertedCompYearlyCategorical']]", "_____no_output_____" ], [ "df_flourish = df_data_etnia_alto['Ethnicity'].value_counts().to_frame('counts').reset_index()", "_____no_output_____" ], [ "df_flourish", "_____no_output_____" ], [ "df_flourish.to_csv('001_df_flourish.csv', index=False)", "_____no_output_____" ], [ "df_data_etnia_alto.to_csv('001_df_data_etnia_alto.csv', index=False)", "_____no_output_____" ], [ "df_data_etnia.to_csv('001_data_etnia_categorical.csv', index=False)", "_____no_output_____" ], [ "data_etnia.to_csv('001_data_etnia.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.2. ¿Cuáles son los porcentajes de programadores que trabajan a tiempo completo, medio tiempo o freelance?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_time_work_dev = data_test[['Country', 'Employment', 'ConvertedCompYearly', 'EdLevel', 'Age']]\ndata_time_work_dev.head()", "_____no_output_____" ], [ "df_flourish_002 = data_time_work_dev['Employment'].value_counts().to_frame('counts').reset_index()", "_____no_output_____" ], [ "df_flourish_002", "_____no_output_____" ], [ "df_flourish_002['counts'] = (df_flourish_002['counts'] * 100 ) / data_time_work_dev.shape[0]", "_____no_output_____" ], [ "df_flourish_002", "_____no_output_____" ], [ "df_flourish_002['counts'] = df_flourish_002['counts'].round(2)", "_____no_output_____" ], [ "df_flourish_002", "_____no_output_____" ], [ "df_flourish_002.to_csv('002_df_flourish.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.3. ¿Cuáles son los países con mayor número de programadores profesionales que son activos en la comunidad Stack Overflow?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_pro_dev_active_so = data_test[['Country', 'Employment', 'MainBranch', 'EdLevel', 'DevType', 'Age']]\ndata_pro_dev_active_so.head()", "_____no_output_____" ], [ "df_flourish_003 = data_pro_dev_active_so['Country'].value_counts().sort_values(ascending=False).head(10)", "_____no_output_____" ], [ "df_flourish_003 = df_flourish_003.to_frame()", "_____no_output_____" ], [ "df_flourish_003 = df_flourish_003.reset_index()\ndf_flourish_003.columns = [\"País\", \"# Programadores Profesionales\"]", "_____no_output_____" ], [ "df_flourish_003.to_csv('003_df_flourish_003.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.4. ¿Cuál es el nivel educativo que mayores ingresos registra entre los encuestados?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_edlevel_income = data_test[['ConvertedCompYearly', 'EdLevel']]\ndata_edlevel_income.head()", "_____no_output_____" ], [ "df_data_edlevel_income = data_edlevel_income.copy()", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_data_edlevel_income['ConvertedCompYearly'], 0.1)\n\nprint(df_data_edlevel_income[mask])", " ConvertedCompYearly EdLevel\n45 60480.0 Licenciatura\n50 25944.0 Licenciatura\n58 22644.0 Grado Profesional\n76 45564.0 Licenciatura\n77 151263.0 Doctorado\n... ... ...\n83425 19452.0 Secundaria\n83428 41232.0 Master\n83431 11676.0 Licenciatura\n83432 80169.0 Licenciatura\n83436 90000.0 Secundaria\n\n[11611 rows x 2 columns]\n" ], [ "df_data_edlevel_income = df_data_edlevel_income[mask]", "_____no_output_____" ], [ "df_data_edlevel_income['ConvertedCompYearlyCategorical'] = 'ALTO'\ndf_data_edlevel_income.loc[(df_data_edlevel_income['ConvertedCompYearly'] >= 0) & (df_data_edlevel_income['ConvertedCompYearly'] <= 32747), 'ConvertedCompYearlyCategorical'] = 'BAJO'\ndf_data_edlevel_income.loc[(df_data_edlevel_income['ConvertedCompYearly'] > 32747) & (df_data_edlevel_income['ConvertedCompYearly'] <= 90000), 'ConvertedCompYearlyCategorical'] = 'MEDIO'\n\nprint(df_data_edlevel_income)", " ConvertedCompYearly EdLevel ConvertedCompYearlyCategorical\n45 60480.0 Licenciatura MEDIO\n50 25944.0 Licenciatura BAJO\n58 22644.0 Grado Profesional BAJO\n76 45564.0 Licenciatura MEDIO\n77 151263.0 Doctorado ALTO\n... ... ... ...\n83425 19452.0 Secundaria BAJO\n83428 41232.0 Master MEDIO\n83431 11676.0 Licenciatura BAJO\n83432 80169.0 Licenciatura MEDIO\n83436 90000.0 Secundaria MEDIO\n\n[11611 rows x 3 columns]\n" ], [ "df_data_edlevel_income = df_data_edlevel_income[df_data_edlevel_income['ConvertedCompYearlyCategorical'] == 'ALTO']", "_____no_output_____" ], [ "df_data_edlevel_income = df_data_edlevel_income[['EdLevel', 'ConvertedCompYearlyCategorical']]", "_____no_output_____" ], [ "df_flourish_004 = df_data_edlevel_income['EdLevel'].value_counts().to_frame('counts').reset_index()", "_____no_output_____" ], [ "df_flourish_004", "_____no_output_____" ], [ "df_flourish_004.to_csv('004_df_flourish.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.5. ¿Existe brecha salarial entre hombres y mujeres u otros géneros?, y de ¿Cuánto es la diferencia? ¿Cuáles son los peores países en cuanto a brecha salarial? ¿Cuáles son los países que han reducido esta brecha salarial entre programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_wage_gap = data_test[['Country', 'ConvertedCompYearly', 'Gender']]\ndata_wage_gap.head()", "_____no_output_____" ], [ "df_data_wage_gap = data_wage_gap.copy()", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_data_wage_gap['ConvertedCompYearly'], 0.1)\n\nprint(df_data_wage_gap[mask])", " Country ConvertedCompYearly Gender\n45 Brazil 60480.0 Hombre\n50 Greece 25944.0 Hombre\n58 Russian Federation 22644.0 Hombre\n76 Poland 45564.0 Hombre\n77 Canada 151263.0 Hombre\n... ... ... ...\n83425 Finland 19452.0 Hombre\n83428 Brazil 41232.0 Hombre\n83431 Pakistan 11676.0 Hombre\n83432 Canada 80169.0 Mujer\n83436 United States of America 90000.0 Hombre\n\n[11611 rows x 3 columns]\n" ], [ "df_data_wage_gap = df_data_wage_gap[mask]", "_____no_output_____" ], [ "df_data_wage_gap['ConvertedCompYearlyCategorical'] = 'ALTO'\ndf_data_wage_gap.loc[(df_data_wage_gap['ConvertedCompYearly'] >= 0) & (df_data_wage_gap['ConvertedCompYearly'] <= 32747), 'ConvertedCompYearlyCategorical'] = 'BAJO'\ndf_data_wage_gap.loc[(df_data_wage_gap['ConvertedCompYearly'] > 32747) & (df_data_wage_gap['ConvertedCompYearly'] <= 90000), 'ConvertedCompYearlyCategorical'] = 'MEDIO'\n\nprint(df_data_wage_gap)", " Country ConvertedCompYearly Gender \\\n45 Brazil 60480.0 Hombre \n50 Greece 25944.0 Hombre \n58 Russian Federation 22644.0 Hombre \n76 Poland 45564.0 Hombre \n77 Canada 151263.0 Hombre \n... ... ... ... \n83425 Finland 19452.0 Hombre \n83428 Brazil 41232.0 Hombre \n83431 Pakistan 11676.0 Hombre \n83432 Canada 80169.0 Mujer \n83436 United States of America 90000.0 Hombre \n\n ConvertedCompYearlyCategorical \n45 MEDIO \n50 BAJO \n58 BAJO \n76 MEDIO \n77 ALTO \n... ... \n83425 BAJO \n83428 MEDIO \n83431 BAJO \n83432 MEDIO \n83436 MEDIO \n\n[11611 rows x 4 columns]\n" ], [ "df_data_wage_gap = df_data_wage_gap[df_data_wage_gap['ConvertedCompYearlyCategorical'].isin(['ALTO', 'MEDIO'])]", "_____no_output_____" ], [ "df_data_wage_gap = df_data_wage_gap[['Country', 'Gender', 'ConvertedCompYearlyCategorical']]", "_____no_output_____" ], [ "df_data_wage_gap.to_csv('005_df_data_wage_gap.csv', index=False)", "_____no_output_____" ], [ "df_data_wage_gap['ConvertedCompYearlyCategorical'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "df_data_wage_gap['Gender'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "df_data_wage_gap['Country'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "df_data_wage_gap1 = df_data_wage_gap.copy()", "_____no_output_____" ], [ "df_flourish_005 = df_data_wage_gap1.groupby(['Country', 'Gender']).size().unstack(fill_value=0).sort_values('Hombre')", "_____no_output_____" ], [ "df_flourish_005 = df_flourish_005.apply(lambda x: pd.concat([x.head(40), x.tail(5)]))", "_____no_output_____" ], [ "df_flourish_005.to_csv('005_flourish_data.csv', index=True)", "_____no_output_____" ] ], [ [ "### 2.6. ¿Cuáles son los ingresos promedios según los rangos de edad? ¿Cuál es el rango de edad con el mejor y peor ingreso?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_age_income = data_test[['ConvertedCompYearly', 'Age']]\ndata_age_income.head()", "_____no_output_____" ], [ "df_data_age_income = data_age_income.copy()", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_data_age_income['ConvertedCompYearly'], 0.1)\n\nprint(df_data_age_income[mask])", " ConvertedCompYearly Age\n45 60480.0 35-44\n50 25944.0 25-34\n58 22644.0 25-34\n76 45564.0 25-34\n77 151263.0 35-44\n... ... ...\n83425 19452.0 18-24\n83428 41232.0 25-34\n83431 11676.0 18-24\n83432 80169.0 18-24\n83436 90000.0 25-34\n\n[11611 rows x 2 columns]\n" ], [ "df_data_age_income = df_data_age_income[mask]", "_____no_output_____" ], [ "df_data_age_income1 = df_data_age_income.copy()", "_____no_output_____" ], [ "df_data_age_income1.to_csv('006_df_data_age_income1.csv', index=False)", "_____no_output_____" ], [ "grouped_df = df_data_age_income1.groupby(\"Age\")\n\naverage_df = grouped_df.mean()", "_____no_output_____" ], [ "average_df", "_____no_output_____" ], [ "df_flourish_006 = average_df.copy()", "_____no_output_____" ], [ "df_flourish_006.to_csv('006_df_flourish_006.csv', index=True)", "_____no_output_____" ] ], [ [ "### 2.7. ¿Cuáles son las tecnologías que permiten tener un mejor ingreso salarial anual?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_techs_best_income1 = data_test[['ConvertedCompYearly', 'LanguageHaveWorkedWith', 'DatabaseHaveWorkedWith', 'PlatformHaveWorkedWith', 'WebframeHaveWorkedWith', 'MiscTechHaveWorkedWith', 'ToolsTechHaveWorkedWith', 'NEWCollabToolsHaveWorkedWith']]\ndata_techs_best_income1.head()", "_____no_output_____" ], [ "data_techs_best_income1['AllTechs'] = data_techs_best_income1['LanguageHaveWorkedWith'].map(str) + ';' + data_techs_best_income1['DatabaseHaveWorkedWith'].map(str) + ';' + data_techs_best_income1['PlatformHaveWorkedWith'].map(str) + ';' + data_techs_best_income1['WebframeHaveWorkedWith'].map(str) + ';' + data_techs_best_income1['MiscTechHaveWorkedWith'].map(str) + ';' + data_techs_best_income1['ToolsTechHaveWorkedWith'].map(str) + ';' + data_techs_best_income1['NEWCollabToolsHaveWorkedWith'].map(str)\nprint (data_techs_best_income1)", " ConvertedCompYearly LanguageHaveWorkedWith \\\n45 60480.0 C#;C++;JavaScript;PowerShell;SQL;TypeScript \n50 25944.0 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type... \n58 22644.0 Bash/Shell;HTML/CSS;JavaScript;Python;SQL \n64 500000.0 HTML/CSS;JavaScript;Python \n76 45564.0 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav... \n... ... ... \n83428 41232.0 Bash/Shell;Node.js;TypeScript \n83431 11676.0 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j... \n83432 80169.0 Ruby \n83436 90000.0 Groovy;Java;Python \n83437 816816.0 Bash/Shell;JavaScript;Node.js;Python \n\n DatabaseHaveWorkedWith \\\n45 Microsoft SQL Server;PostgreSQL;Redis \n50 Couchbase;MariaDB;Microsoft SQL Server;MongoDB... \n58 Oracle \n64 MySQL \n76 Firebase;Microsoft SQL Server;MongoDB;MySQL;Po... \n... ... \n83428 Elasticsearch;MongoDB;PostgreSQL;Redis \n83431 Firebase;MySQL;SQLite \n83432 MySQL;PostgreSQL \n83436 DynamoDB;Elasticsearch;MongoDB;PostgreSQL;Redis \n83437 Cassandra;Elasticsearch;MongoDB;PostgreSQL;Redis \n\n PlatformHaveWorkedWith \\\n45 Heroku;Microsoft Azure \n50 AWS;DigitalOcean;Microsoft Azure \n58 Heroku \n64 AWS \n76 Google Cloud Platform;Microsoft Azure \n... ... \n83428 AWS;Google Cloud Platform \n83431 Google Cloud Platform \n83432 Google Cloud Platform;Heroku \n83436 AWS;Google Cloud Platform \n83437 Heroku \n\n WebframeHaveWorkedWith \\\n45 ASP.NET Core ;React.js \n50 Angular;ASP.NET;ASP.NET Core ;Express;Svelte \n58 Django;FastAPI;Vue.js \n64 Flask \n76 Angular;Angular.js;ASP.NET;ASP.NET Core ;Djang... \n... ... \n83428 React.js \n83431 Flask;jQuery \n83432 Flask;React.js;Ruby on Rails;Vue.js \n83436 FastAPI;Flask \n83437 Django;Express;Flask;React.js \n\n MiscTechHaveWorkedWith \\\n45 .NET Core / .NET 5 \n50 .NET Framework;.NET Core / .NET 5 \n58 NumPy;Pandas;Torch/PyTorch \n64 Pandas \n76 .NET Framework;.NET Core / .NET 5;Apache Spark... \n... ... \n83428 React Native \n83431 Flutter \n83432 NumPy;Pandas;TensorFlow;Torch/PyTorch \n83436 Hadoop;Keras;NumPy;Pandas \n83437 NumPy;Pandas;TensorFlow;Torch/PyTorch \n\n ToolsTechHaveWorkedWith \\\n45 Docker;Git;Kubernetes \n50 Docker;Kubernetes \n58 Docker;Git \n64 Git \n76 Docker;Git;Unity 3D \n... ... \n83428 Docker;Git;Terraform;Yarn \n83431 Git \n83432 Docker;Git;Kubernetes;Yarn \n83436 Ansible;Docker;Git;Terraform \n83437 Ansible;Docker;Git;Terraform \n\n NEWCollabToolsHaveWorkedWith \\\n45 Notepad++;Visual Studio;Visual Studio Code \n50 Notepad++;Visual Studio;Visual Studio Code \n58 IPython/Jupyter;Visual Studio Code \n64 Notepad++;PyCharm;Sublime Text \n76 Android Studio;Eclipse;NetBeans;Notepad++;Visu... \n... ... \n83428 Visual Studio Code;Webstorm \n83431 Android Studio;IntelliJ;IPython/Jupyter;Notepa... \n83432 Atom;IPython/Jupyter;Vim;Visual Studio Code \n83436 Android Studio;Eclipse;IntelliJ;IPython/Jupyte... \n83437 PyCharm;Sublime Text \n\n AllTechs \n45 C#;C++;JavaScript;PowerShell;SQL;TypeScript;Mi... \n50 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type... \n58 Bash/Shell;HTML/CSS;JavaScript;Python;SQL;Orac... \n64 HTML/CSS;JavaScript;Python;MySQL;AWS;Flask;Pan... \n76 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav... \n... ... \n83428 Bash/Shell;Node.js;TypeScript;Elasticsearch;Mo... \n83431 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j... \n83432 Ruby;MySQL;PostgreSQL;Google Cloud Platform;He... \n83436 Groovy;Java;Python;DynamoDB;Elasticsearch;Mong... \n83437 Bash/Shell;JavaScript;Node.js;Python;Cassandra... \n\n[14517 rows x 9 columns]\n" ], [ "df_data_techs_best_income = data_techs_best_income1[['ConvertedCompYearly', 'AllTechs']].copy()", "_____no_output_____" ], [ "df_data_techs_best_income1 = df_data_techs_best_income.copy()", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_data_techs_best_income1['ConvertedCompYearly'], 0.1)\n\nprint(df_data_techs_best_income1[mask])", " ConvertedCompYearly AllTechs\n45 60480.0 C#;C++;JavaScript;PowerShell;SQL;TypeScript;Mi...\n50 25944.0 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type...\n58 22644.0 Bash/Shell;HTML/CSS;JavaScript;Python;SQL;Orac...\n76 45564.0 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav...\n77 151263.0 HTML/CSS;Python;R;DynamoDB;AWS;Flask;Keras;Num...\n... ... ...\n83425 19452.0 HTML/CSS;JavaScript;Node.js;TypeScript;DynamoD...\n83428 41232.0 Bash/Shell;Node.js;TypeScript;Elasticsearch;Mo...\n83431 11676.0 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j...\n83432 80169.0 Ruby;MySQL;PostgreSQL;Google Cloud Platform;He...\n83436 90000.0 Groovy;Java;Python;DynamoDB;Elasticsearch;Mong...\n\n[11611 rows x 2 columns]\n" ], [ "df_data_techs_best_income1 = df_data_techs_best_income1[mask]", "_____no_output_____" ], [ "df_data_techs_best_income1['ConvertedCompYearlyCategorical'] = 'ALTO'\ndf_data_techs_best_income1.loc[(df_data_techs_best_income1['ConvertedCompYearly'] >= 0) & (df_data_techs_best_income1['ConvertedCompYearly'] <= 32747), 'ConvertedCompYearlyCategorical'] = 'BAJO'\ndf_data_techs_best_income1.loc[(df_data_techs_best_income1['ConvertedCompYearly'] > 32747) & (df_data_techs_best_income1['ConvertedCompYearly'] <= 90000), 'ConvertedCompYearlyCategorical'] = 'MEDIO'\n\nprint(df_data_techs_best_income1)", " ConvertedCompYearly AllTechs \\\n45 60480.0 C#;C++;JavaScript;PowerShell;SQL;TypeScript;Mi... \n50 25944.0 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type... \n58 22644.0 Bash/Shell;HTML/CSS;JavaScript;Python;SQL;Orac... \n76 45564.0 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav... \n77 151263.0 HTML/CSS;Python;R;DynamoDB;AWS;Flask;Keras;Num... \n... ... ... \n83425 19452.0 HTML/CSS;JavaScript;Node.js;TypeScript;DynamoD... \n83428 41232.0 Bash/Shell;Node.js;TypeScript;Elasticsearch;Mo... \n83431 11676.0 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j... \n83432 80169.0 Ruby;MySQL;PostgreSQL;Google Cloud Platform;He... \n83436 90000.0 Groovy;Java;Python;DynamoDB;Elasticsearch;Mong... \n\n ConvertedCompYearlyCategorical \n45 MEDIO \n50 BAJO \n58 BAJO \n76 MEDIO \n77 ALTO \n... ... \n83425 BAJO \n83428 MEDIO \n83431 BAJO \n83432 MEDIO \n83436 MEDIO \n\n[11611 rows x 3 columns]\n" ], [ "df_data_techs_best_income1 = df_data_techs_best_income1[df_data_techs_best_income1['ConvertedCompYearlyCategorical'].isin(['ALTO', 'MEDIO'])]", "_____no_output_____" ], [ "df_data_techs_best_income1['AllTechs'] = df_data_techs_best_income1['AllTechs'].str.replace(' ', '')", "_____no_output_____" ], [ "df_data_techs_best_income1['AllTechs'] = df_data_techs_best_income1['AllTechs'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts = df_data_techs_best_income1['AllTechs'].str.split(expand=True).stack().value_counts().rename_axis('Tech').reset_index(name='Count')", "_____no_output_____" ], [ "df_counts.head(10)", "_____no_output_____" ], [ "df_data_techs_best_income_007 = df_counts.head(10)", "_____no_output_____" ], [ "df_data_techs_best_income_007.to_csv('007_df_data_techs_best_income.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.8. ¿Cuántas tecnologías en promedio domina un programador profesional?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_techs_dev_pro1 = data_test[['DevType', 'LanguageHaveWorkedWith', 'DatabaseHaveWorkedWith', 'PlatformHaveWorkedWith', 'WebframeHaveWorkedWith', 'MiscTechHaveWorkedWith', 'ToolsTechHaveWorkedWith', 'NEWCollabToolsHaveWorkedWith']]\ndata_techs_dev_pro1.head()", "_____no_output_____" ], [ "data_techs_dev_pro1['AllTechs'] = data_techs_dev_pro1['LanguageHaveWorkedWith'].map(str) + ';' + data_techs_dev_pro1['DatabaseHaveWorkedWith'].map(str) + ';' + data_techs_dev_pro1['PlatformHaveWorkedWith'].map(str) + ';' + data_techs_dev_pro1['WebframeHaveWorkedWith'].map(str) + ';' + data_techs_dev_pro1['MiscTechHaveWorkedWith'].map(str) + ';' + data_techs_best_income1['ToolsTechHaveWorkedWith'].map(str) + ';' + data_techs_dev_pro1['NEWCollabToolsHaveWorkedWith'].map(str)\nprint (data_techs_dev_pro1)", " DevType \\\n45 Desarrollador Escritorio \n50 Desarrollador full-stack \n58 Desarrollador full-stack \n64 Desarrollador front-end \n76 Desarrollador front-end \n... ... \n83428 Ejecutivo Senior \n83431 Desarrollador móvil \n83432 Desarrollador back-end \n83436 Cientifico de datos \n83437 Desarrollador back-end \n\n LanguageHaveWorkedWith \\\n45 C#;C++;JavaScript;PowerShell;SQL;TypeScript \n50 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type... \n58 Bash/Shell;HTML/CSS;JavaScript;Python;SQL \n64 HTML/CSS;JavaScript;Python \n76 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav... \n... ... \n83428 Bash/Shell;Node.js;TypeScript \n83431 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j... \n83432 Ruby \n83436 Groovy;Java;Python \n83437 Bash/Shell;JavaScript;Node.js;Python \n\n DatabaseHaveWorkedWith \\\n45 Microsoft SQL Server;PostgreSQL;Redis \n50 Couchbase;MariaDB;Microsoft SQL Server;MongoDB... \n58 Oracle \n64 MySQL \n76 Firebase;Microsoft SQL Server;MongoDB;MySQL;Po... \n... ... \n83428 Elasticsearch;MongoDB;PostgreSQL;Redis \n83431 Firebase;MySQL;SQLite \n83432 MySQL;PostgreSQL \n83436 DynamoDB;Elasticsearch;MongoDB;PostgreSQL;Redis \n83437 Cassandra;Elasticsearch;MongoDB;PostgreSQL;Redis \n\n PlatformHaveWorkedWith \\\n45 Heroku;Microsoft Azure \n50 AWS;DigitalOcean;Microsoft Azure \n58 Heroku \n64 AWS \n76 Google Cloud Platform;Microsoft Azure \n... ... \n83428 AWS;Google Cloud Platform \n83431 Google Cloud Platform \n83432 Google Cloud Platform;Heroku \n83436 AWS;Google Cloud Platform \n83437 Heroku \n\n WebframeHaveWorkedWith \\\n45 ASP.NET Core ;React.js \n50 Angular;ASP.NET;ASP.NET Core ;Express;Svelte \n58 Django;FastAPI;Vue.js \n64 Flask \n76 Angular;Angular.js;ASP.NET;ASP.NET Core ;Djang... \n... ... \n83428 React.js \n83431 Flask;jQuery \n83432 Flask;React.js;Ruby on Rails;Vue.js \n83436 FastAPI;Flask \n83437 Django;Express;Flask;React.js \n\n MiscTechHaveWorkedWith \\\n45 .NET Core / .NET 5 \n50 .NET Framework;.NET Core / .NET 5 \n58 NumPy;Pandas;Torch/PyTorch \n64 Pandas \n76 .NET Framework;.NET Core / .NET 5;Apache Spark... \n... ... \n83428 React Native \n83431 Flutter \n83432 NumPy;Pandas;TensorFlow;Torch/PyTorch \n83436 Hadoop;Keras;NumPy;Pandas \n83437 NumPy;Pandas;TensorFlow;Torch/PyTorch \n\n ToolsTechHaveWorkedWith \\\n45 Docker;Git;Kubernetes \n50 Docker;Kubernetes \n58 Docker;Git \n64 Git \n76 Docker;Git;Unity 3D \n... ... \n83428 Docker;Git;Terraform;Yarn \n83431 Git \n83432 Docker;Git;Kubernetes;Yarn \n83436 Ansible;Docker;Git;Terraform \n83437 Ansible;Docker;Git;Terraform \n\n NEWCollabToolsHaveWorkedWith \\\n45 Notepad++;Visual Studio;Visual Studio Code \n50 Notepad++;Visual Studio;Visual Studio Code \n58 IPython/Jupyter;Visual Studio Code \n64 Notepad++;PyCharm;Sublime Text \n76 Android Studio;Eclipse;NetBeans;Notepad++;Visu... \n... ... \n83428 Visual Studio Code;Webstorm \n83431 Android Studio;IntelliJ;IPython/Jupyter;Notepa... \n83432 Atom;IPython/Jupyter;Vim;Visual Studio Code \n83436 Android Studio;Eclipse;IntelliJ;IPython/Jupyte... \n83437 PyCharm;Sublime Text \n\n AllTechs \n45 C#;C++;JavaScript;PowerShell;SQL;TypeScript;Mi... \n50 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type... \n58 Bash/Shell;HTML/CSS;JavaScript;Python;SQL;Orac... \n64 HTML/CSS;JavaScript;Python;MySQL;AWS;Flask;Pan... \n76 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav... \n... ... \n83428 Bash/Shell;Node.js;TypeScript;Elasticsearch;Mo... \n83431 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j... \n83432 Ruby;MySQL;PostgreSQL;Google Cloud Platform;He... \n83436 Groovy;Java;Python;DynamoDB;Elasticsearch;Mong... \n83437 Bash/Shell;JavaScript;Node.js;Python;Cassandra... \n\n[14517 rows x 9 columns]\n" ], [ "df_data_techs_dev_pro = data_techs_dev_pro1[['DevType', 'AllTechs']].copy()", "_____no_output_____" ], [ "df_data_techs_dev_pro = df_data_techs_dev_pro[df_data_techs_dev_pro['DevType'].isin(['Desarrollador full-stack', 'Desarrollador front-end', 'Desarrollador móvil', 'Desarrollador back-end', 'Desarrollador Escritorio', 'Desarrollador de QA o Test', 'Desarrollador de aplicaciones embebidas', 'Administrador de base de datos', 'Desarrollador de juegos o gráfico'])]", "_____no_output_____" ], [ "df_data_techs_dev_pro.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 12832 entries, 45 to 83437\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 DevType 12832 non-null object\n 1 AllTechs 12832 non-null object\ndtypes: object(2)\nmemory usage: 300.8+ KB\n" ], [ "df_data_techs_dev_pro1 = df_data_techs_dev_pro.copy()", "_____no_output_____" ], [ "df_data_techs_dev_pro1.to_csv('008_df_data_techs_dev_pro1.csv', index=True)", "_____no_output_____" ], [ "def convert_row_to_list(lst):\n return lst.split(';')", "_____no_output_____" ], [ "df_data_techs_dev_pro1['ListTechs'] = df_data_techs_dev_pro1['AllTechs'].apply(convert_row_to_list)", "_____no_output_____" ], [ "df_data_techs_dev_pro1['LenListTechs'] = df_data_techs_dev_pro1['ListTechs'].map(len)", "_____no_output_____" ], [ "df_flourish_008 = df_data_techs_dev_pro1[['DevType', 'LenListTechs']].copy()\ndf_flourish_008", "_____no_output_____" ], [ "grouped_df = df_flourish_008.groupby(\"DevType\")\n\naverage_df_008 = round(grouped_df.mean())", "_____no_output_____" ], [ "df_flourish_008 = average_df_008.copy()", "_____no_output_____" ], [ "df_flourish_008.to_csv('008_df_flourish_008.csv', index=True)", "_____no_output_____" ] ], [ [ "### 2.9. ¿En qué rango de edad se inició la mayoría de los programadores en la programación?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_age1stcode_dev_pro1 = data_test[['Age1stCode']]\ndata_age1stcode_dev_pro1.head()", "_____no_output_____" ], [ "data_age1stcode_dev_pro1 = data_age1stcode_dev_pro1['Age1stCode'].value_counts().to_frame('counts').reset_index()", "_____no_output_____" ], [ "data_age1stcode_dev_pro1.to_csv('009_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.10. ¿Cuántos años como programadores se requiere para obtener un ingreso salarial alto?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_yearscode_high_income1 = data_test[['ConvertedCompYearly', 'YearsCode']]\ndata_yearscode_high_income1.head()", "_____no_output_____" ], [ "df_data_yearscode_high_income = data_yearscode_high_income1.copy()", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_data_yearscode_high_income['ConvertedCompYearly'], 0.1)\n\nprint(df_data_yearscode_high_income[mask])", " ConvertedCompYearly YearsCode\n45 60480.0 22\n50 25944.0 12\n58 22644.0 5\n76 45564.0 12\n77 151263.0 10\n... ... ...\n83425 19452.0 5\n83428 41232.0 12\n83431 11676.0 9\n83432 80169.0 5\n83436 90000.0 10\n\n[11611 rows x 2 columns]\n" ], [ "df_data_yearscode_high_income = df_data_yearscode_high_income[mask]", "_____no_output_____" ], [ "df_data_yearscode_high_income['ConvertedCompYearlyCategorical'] = 'ALTO'\n\ndf_data_yearscode_high_income.loc[(df_data_yearscode_high_income['ConvertedCompYearly'] >= 0) & (df_data_yearscode_high_income['ConvertedCompYearly'] <= 32747), 'ConvertedCompYearlyCategorical'] = 'BAJO'\ndf_data_yearscode_high_income.loc[(df_data_yearscode_high_income['ConvertedCompYearly'] > 32747) & (df_data_yearscode_high_income['ConvertedCompYearly'] <= 90000), 'ConvertedCompYearlyCategorical'] = 'MEDIO'\n\nprint(df_data_yearscode_high_income)", " ConvertedCompYearly YearsCode ConvertedCompYearlyCategorical\n45 60480.0 22 MEDIO\n50 25944.0 12 BAJO\n58 22644.0 5 BAJO\n76 45564.0 12 MEDIO\n77 151263.0 10 ALTO\n... ... ... ...\n83425 19452.0 5 BAJO\n83428 41232.0 12 MEDIO\n83431 11676.0 9 BAJO\n83432 80169.0 5 MEDIO\n83436 90000.0 10 MEDIO\n\n[11611 rows x 3 columns]\n" ], [ "df_data_yearscode_high_income.to_csv('010_df_flourish.csv', index=False)", "_____no_output_____" ], [ "df_data_yearscode_high_income['ConvertedCompYearlyCategorical'].value_counts()", "_____no_output_____" ], [ "df_flourish_010 = df_data_yearscode_high_income[['YearsCode', 'ConvertedCompYearlyCategorical']].copy()\n\ndf_flourish_010.head()", "_____no_output_____" ], [ "df_flourish_010['YearsCode'] = pd.to_numeric(df_flourish_010['YearsCode'])", "_____no_output_____" ], [ "df_flourish_010.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 11611 entries, 45 to 83436\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 YearsCode 11611 non-null int64 \n 1 ConvertedCompYearlyCategorical 11611 non-null object\ndtypes: int64(1), object(1)\nmemory usage: 530.2+ KB\n" ], [ "grouped_df_010 = df_flourish_010.groupby(\"ConvertedCompYearlyCategorical\")\n\naverage_df_010 = round(grouped_df_010.mean())", "_____no_output_____" ], [ "average_df_010", "_____no_output_____" ], [ "average_df_010.to_csv('010_flourish_data.csv', index=True)", "_____no_output_____" ] ], [ [ "### 2.11. ¿Cuáles son los perfiles que registran los mejores ingresos?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_profiles_dev_high_income1 = data_test[['ConvertedCompYearly', 'DevType']].copy()\ndata_profiles_dev_high_income1.head()", "_____no_output_____" ], [ "df_data_profiles_dev_high_income = data_profiles_dev_high_income1.copy()", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_data_profiles_dev_high_income['ConvertedCompYearly'], 0.1)\n\nprint(df_data_profiles_dev_high_income[mask])", " ConvertedCompYearly DevType\n45 60480.0 Desarrollador Escritorio\n50 25944.0 Desarrollador full-stack\n58 22644.0 Desarrollador full-stack\n76 45564.0 Desarrollador front-end\n77 151263.0 Cientifico de datos\n... ... ...\n83425 19452.0 Desarrollador full-stack\n83428 41232.0 Ejecutivo Senior\n83431 11676.0 Desarrollador móvil\n83432 80169.0 Desarrollador back-end\n83436 90000.0 Cientifico de datos\n\n[11611 rows x 2 columns]\n" ], [ "df_data_profiles_dev_high_income = df_data_profiles_dev_high_income[mask]", "_____no_output_____" ], [ "df_data_profiles_dev_high_income['ConvertedCompYearlyCategorical'] = 'ALTO'\n\ndf_data_profiles_dev_high_income.loc[(df_data_profiles_dev_high_income['ConvertedCompYearly'] >= 0) & (df_data_profiles_dev_high_income['ConvertedCompYearly'] <= 32747), 'ConvertedCompYearlyCategorical'] = 'BAJO'\ndf_data_profiles_dev_high_income.loc[(df_data_profiles_dev_high_income['ConvertedCompYearly'] > 32747) & (df_data_profiles_dev_high_income['ConvertedCompYearly'] <= 90000), 'ConvertedCompYearlyCategorical'] = 'MEDIO'\n\nprint(df_data_profiles_dev_high_income)", " ConvertedCompYearly DevType \\\n45 60480.0 Desarrollador Escritorio \n50 25944.0 Desarrollador full-stack \n58 22644.0 Desarrollador full-stack \n76 45564.0 Desarrollador front-end \n77 151263.0 Cientifico de datos \n... ... ... \n83425 19452.0 Desarrollador full-stack \n83428 41232.0 Ejecutivo Senior \n83431 11676.0 Desarrollador móvil \n83432 80169.0 Desarrollador back-end \n83436 90000.0 Cientifico de datos \n\n ConvertedCompYearlyCategorical \n45 MEDIO \n50 BAJO \n58 BAJO \n76 MEDIO \n77 ALTO \n... ... \n83425 BAJO \n83428 MEDIO \n83431 BAJO \n83432 MEDIO \n83436 MEDIO \n\n[11611 rows x 3 columns]\n" ], [ "df_data_profiles_dev_high_income['ConvertedCompYearlyCategorical'].value_counts()", "_____no_output_____" ], [ "df_flourish_011 = df_data_profiles_dev_high_income[['DevType', 'ConvertedCompYearlyCategorical']].copy()", "_____no_output_____" ], [ "df_flourish_011 = df_flourish_011[df_flourish_011['ConvertedCompYearlyCategorical'].isin(['ALTO'])]", "_____no_output_____" ], [ "df_flourish_011.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 2892 entries, 77 to 83372\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 DevType 2892 non-null object\n 1 ConvertedCompYearlyCategorical 2892 non-null object\ndtypes: object(2)\nmemory usage: 67.8+ KB\n" ], [ "df_data_flourish_011 = df_flourish_011['DevType'].value_counts().to_frame('counts').reset_index()", "_____no_output_____" ], [ "df_data_flourish_011 = df_data_flourish_011.head(10)", "_____no_output_____" ], [ "df_data_flourish_011", "_____no_output_____" ], [ "df_data_flourish_011.to_csv('011_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.12. ¿Cuáles son las 10 tecnologías más usadas entre los programadores por países?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_10_techs_popular_dev_countries = data_test[['Country', 'LanguageHaveWorkedWith', 'DatabaseHaveWorkedWith', 'PlatformHaveWorkedWith', 'WebframeHaveWorkedWith', 'MiscTechHaveWorkedWith', 'ToolsTechHaveWorkedWith', 'NEWCollabToolsHaveWorkedWith']]\ndata_10_techs_popular_dev_countries.head()", "_____no_output_____" ], [ "data_10_techs_popular_dev_countries['AllTechs'] = data_10_techs_popular_dev_countries['LanguageHaveWorkedWith'].map(str) + ';' + data_10_techs_popular_dev_countries['DatabaseHaveWorkedWith'].map(str) + ';' + data_10_techs_popular_dev_countries['PlatformHaveWorkedWith'].map(str) + ';' + data_10_techs_popular_dev_countries['WebframeHaveWorkedWith'].map(str) + ';' + data_10_techs_popular_dev_countries['MiscTechHaveWorkedWith'].map(str) + ';' + data_10_techs_popular_dev_countries['ToolsTechHaveWorkedWith'].map(str) + ';' + data_10_techs_popular_dev_countries['NEWCollabToolsHaveWorkedWith'].map(str)\nprint (data_10_techs_popular_dev_countries)", " Country \\\n45 Brazil \n50 Greece \n58 Russian Federation \n64 United States of America \n76 Poland \n... ... \n83428 Brazil \n83431 Pakistan \n83432 Canada \n83436 United States of America \n83437 Canada \n\n LanguageHaveWorkedWith \\\n45 C#;C++;JavaScript;PowerShell;SQL;TypeScript \n50 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type... \n58 Bash/Shell;HTML/CSS;JavaScript;Python;SQL \n64 HTML/CSS;JavaScript;Python \n76 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav... \n... ... \n83428 Bash/Shell;Node.js;TypeScript \n83431 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j... \n83432 Ruby \n83436 Groovy;Java;Python \n83437 Bash/Shell;JavaScript;Node.js;Python \n\n DatabaseHaveWorkedWith \\\n45 Microsoft SQL Server;PostgreSQL;Redis \n50 Couchbase;MariaDB;Microsoft SQL Server;MongoDB... \n58 Oracle \n64 MySQL \n76 Firebase;Microsoft SQL Server;MongoDB;MySQL;Po... \n... ... \n83428 Elasticsearch;MongoDB;PostgreSQL;Redis \n83431 Firebase;MySQL;SQLite \n83432 MySQL;PostgreSQL \n83436 DynamoDB;Elasticsearch;MongoDB;PostgreSQL;Redis \n83437 Cassandra;Elasticsearch;MongoDB;PostgreSQL;Redis \n\n PlatformHaveWorkedWith \\\n45 Heroku;Microsoft Azure \n50 AWS;DigitalOcean;Microsoft Azure \n58 Heroku \n64 AWS \n76 Google Cloud Platform;Microsoft Azure \n... ... \n83428 AWS;Google Cloud Platform \n83431 Google Cloud Platform \n83432 Google Cloud Platform;Heroku \n83436 AWS;Google Cloud Platform \n83437 Heroku \n\n WebframeHaveWorkedWith \\\n45 ASP.NET Core ;React.js \n50 Angular;ASP.NET;ASP.NET Core ;Express;Svelte \n58 Django;FastAPI;Vue.js \n64 Flask \n76 Angular;Angular.js;ASP.NET;ASP.NET Core ;Djang... \n... ... \n83428 React.js \n83431 Flask;jQuery \n83432 Flask;React.js;Ruby on Rails;Vue.js \n83436 FastAPI;Flask \n83437 Django;Express;Flask;React.js \n\n MiscTechHaveWorkedWith \\\n45 .NET Core / .NET 5 \n50 .NET Framework;.NET Core / .NET 5 \n58 NumPy;Pandas;Torch/PyTorch \n64 Pandas \n76 .NET Framework;.NET Core / .NET 5;Apache Spark... \n... ... \n83428 React Native \n83431 Flutter \n83432 NumPy;Pandas;TensorFlow;Torch/PyTorch \n83436 Hadoop;Keras;NumPy;Pandas \n83437 NumPy;Pandas;TensorFlow;Torch/PyTorch \n\n ToolsTechHaveWorkedWith \\\n45 Docker;Git;Kubernetes \n50 Docker;Kubernetes \n58 Docker;Git \n64 Git \n76 Docker;Git;Unity 3D \n... ... \n83428 Docker;Git;Terraform;Yarn \n83431 Git \n83432 Docker;Git;Kubernetes;Yarn \n83436 Ansible;Docker;Git;Terraform \n83437 Ansible;Docker;Git;Terraform \n\n NEWCollabToolsHaveWorkedWith \\\n45 Notepad++;Visual Studio;Visual Studio Code \n50 Notepad++;Visual Studio;Visual Studio Code \n58 IPython/Jupyter;Visual Studio Code \n64 Notepad++;PyCharm;Sublime Text \n76 Android Studio;Eclipse;NetBeans;Notepad++;Visu... \n... ... \n83428 Visual Studio Code;Webstorm \n83431 Android Studio;IntelliJ;IPython/Jupyter;Notepa... \n83432 Atom;IPython/Jupyter;Vim;Visual Studio Code \n83436 Android Studio;Eclipse;IntelliJ;IPython/Jupyte... \n83437 PyCharm;Sublime Text \n\n AllTechs \n45 C#;C++;JavaScript;PowerShell;SQL;TypeScript;Mi... \n50 C#;HTML/CSS;JavaScript;Node.js;PowerShell;Type... \n58 Bash/Shell;HTML/CSS;JavaScript;Python;SQL;Orac... \n64 HTML/CSS;JavaScript;Python;MySQL;AWS;Flask;Pan... \n76 Bash/Shell;C#;Dart;Delphi;Go;HTML/CSS;Java;Jav... \n... ... \n83428 Bash/Shell;Node.js;TypeScript;Elasticsearch;Mo... \n83431 C#;Dart;HTML/CSS;Java;JavaScript;Kotlin;Node.j... \n83432 Ruby;MySQL;PostgreSQL;Google Cloud Platform;He... \n83436 Groovy;Java;Python;DynamoDB;Elasticsearch;Mong... \n83437 Bash/Shell;JavaScript;Node.js;Python;Cassandra... \n\n[14517 rows x 9 columns]\n" ], [ "df_data_10_techs_popular_dev_countries = data_10_techs_popular_dev_countries[['Country', 'AllTechs']].copy()", "_____no_output_____" ], [ "df_data_10_techs_popular_dev_countries.head()", "_____no_output_____" ], [ "df_data_10_techs_popular_dev_countries['AllTechs'] = df_data_10_techs_popular_dev_countries['AllTechs'].str.replace(' ', '')", "_____no_output_____" ], [ "df_data_10_techs_popular_dev_countries['AllTechs'] = df_data_10_techs_popular_dev_countries['AllTechs'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts = df_data_10_techs_popular_dev_countries['AllTechs'].str.split(expand=True).stack().value_counts().rename_axis('Tech').reset_index(name='Count')", "_____no_output_____" ], [ "df_counts", "_____no_output_____" ], [ "data_10_techs_popular_dev_countries.to_csv('012_data_10_techs_popular_dev_countries.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.13. ¿Cuáles el sistema operativo más usado entre los encuestados?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_data_so_devs = data_test[['OpSys']].copy()", "_____no_output_____" ], [ "df_data_so_devs.tail()", "_____no_output_____" ], [ "df_data_so_devs['OpSys'].drop_duplicates().sort_values()", "_____no_output_____" ], [ "df_data_so_devs['OpSys'] = df_data_so_devs['OpSys'].replace(['Other (please specify):'], 'Otro')", "_____no_output_____" ], [ "df_data_so_devs['OpSys'].value_counts()", "_____no_output_____" ], [ "df_counts = df_data_so_devs['OpSys'].str.split(expand=True).stack().value_counts().rename_axis('OS').reset_index(name='Count')", "_____no_output_____" ], [ "df_counts", "_____no_output_____" ], [ "df_counts.to_csv('013_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.14. ¿Qué proporción de programadores tiene algún desorden mental por país?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "data_devs_mental_health_countries = data_test[['Country', 'MentalHealth']]\ndata_devs_mental_health_countries.head()", "_____no_output_____" ], [ "data_devs_mental_health_countries['MentalHealth'].value_counts()", "_____no_output_____" ], [ "df_data_devs_mental_health_countries = data_devs_mental_health_countries.copy()", "_____no_output_____" ], [ "df_data_devs_mental_health_countries = df_data_devs_mental_health_countries[df_data_devs_mental_health_countries['MentalHealth'].isin(['Desorden de concentración o memoria', 'Desorden emocional', 'Desorden de ansiedad', 'Tipo de autismo'])]", "_____no_output_____" ], [ "df_data_devs_mental_health_countries.head()", "_____no_output_____" ], [ "df_data_flourish_014 = df_data_devs_mental_health_countries['Country'].value_counts().to_frame('counts').reset_index()", "_____no_output_____" ], [ "df_data_flourish_014 = df_data_flourish_014.head(10)\ndf_data_flourish_014", "_____no_output_____" ], [ "df_data_flourish_014_best_ten = df_data_devs_mental_health_countries[df_data_devs_mental_health_countries['Country'].isin(['United States of America', 'United Kingdom of Great Britain and Northern Ireland', 'Brazil', 'Canada', 'India', 'Germany', 'Australia', 'Netherlands', 'Poland', 'Turkey'])]", "_____no_output_____" ], [ "df = df_data_flourish_014_best_ten.copy()", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df1 = pd.crosstab(df['Country'], df['MentalHealth'])\ndf1", "_____no_output_____" ], [ "(df_data_devs_mental_health_countries.groupby(['Country', 'MentalHealth']).size() \n .sort_values(ascending=False) \n .reset_index(name='count') \n .drop_duplicates(subset='Country'))", "_____no_output_____" ], [ "df_flourish_data_014 = (df_data_devs_mental_health_countries.groupby(['Country', 'MentalHealth']).size() \n .sort_values(ascending=False) \n .reset_index(name='count'))", "_____no_output_____" ], [ "df_flourish_data_014 = df_flourish_data_014.sort_values('Country')", "_____no_output_____" ], [ "df_data_flourish_014.head(10).to_csv('014_flourish_data_014.csv', index=False)", "_____no_output_____" ], [ "df1.to_csv('014_flourish_data_014.csv', index=True)", "_____no_output_____" ] ], [ [ "### 2.15. ¿Cuáles son los países que tienen los mejores sueldos entre los programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_best_incomes_countries = data_test[['Country', 'ConvertedCompYearly']].copy()", "_____no_output_____" ], [ "df_best_incomes_countries", "_____no_output_____" ], [ "def remove_outliers(df, q=0.05):\n upper = df.quantile(1-q)\n lower = df.quantile(q)\n mask = (df < upper) & (df > lower)\n return mask\n\nmask = remove_outliers(df_best_incomes_countries['ConvertedCompYearly'], 0.1)\n\nprint(df_best_incomes_countries[mask])", " Country ConvertedCompYearly\n45 Brazil 60480.0\n50 Greece 25944.0\n58 Russian Federation 22644.0\n76 Poland 45564.0\n77 Canada 151263.0\n... ... ...\n83425 Finland 19452.0\n83428 Brazil 41232.0\n83431 Pakistan 11676.0\n83432 Canada 80169.0\n83436 United States of America 90000.0\n\n[11611 rows x 2 columns]\n" ], [ "df_best_incomes_countries_no_outliers = df_best_incomes_countries[mask]", "_____no_output_____" ], [ "df_best_incomes_countries_no_outliers1 = df_best_incomes_countries_no_outliers.copy()", "_____no_output_____" ], [ "df_best_incomes_countries_no_outliers1['ConvertedCompYearlyCategorical'] = 'ALTO'\ndf_best_incomes_countries_no_outliers1.loc[(df_best_incomes_countries_no_outliers1['ConvertedCompYearly'] >= 0) & (df_best_incomes_countries_no_outliers1['ConvertedCompYearly'] <= 32747), 'ConvertedCompYearlyCategorical'] = 'BAJO'\ndf_best_incomes_countries_no_outliers1.loc[(df_best_incomes_countries_no_outliers1['ConvertedCompYearly'] > 32747) & (df_best_incomes_countries_no_outliers1['ConvertedCompYearly'] <= 90000), 'ConvertedCompYearlyCategorical'] = 'MEDIO'\n\nprint(df_best_incomes_countries_no_outliers1)", " Country ConvertedCompYearly \\\n45 Brazil 60480.0 \n50 Greece 25944.0 \n58 Russian Federation 22644.0 \n76 Poland 45564.0 \n77 Canada 151263.0 \n... ... ... \n83425 Finland 19452.0 \n83428 Brazil 41232.0 \n83431 Pakistan 11676.0 \n83432 Canada 80169.0 \n83436 United States of America 90000.0 \n\n ConvertedCompYearlyCategorical \n45 MEDIO \n50 BAJO \n58 BAJO \n76 MEDIO \n77 ALTO \n... ... \n83425 BAJO \n83428 MEDIO \n83431 BAJO \n83432 MEDIO \n83436 MEDIO \n\n[11611 rows x 3 columns]\n" ], [ "df_best_incomes_countries_no_outliers1['ConvertedCompYearlyCategorical'].value_counts()", "_____no_output_____" ], [ "df_best_incomes_countries_alto = df_best_incomes_countries_no_outliers1[df_best_incomes_countries_no_outliers1['ConvertedCompYearlyCategorical'] == 'ALTO']", "_____no_output_____" ], [ "df_alto = df_best_incomes_countries_alto[['Country', 'ConvertedCompYearlyCategorical']].copy()", "_____no_output_____" ], [ "df_flourish_015 = df_alto['Country'].value_counts().to_frame('counts').reset_index()", "_____no_output_____" ], [ "df_flourish_015.head(10)", "_____no_output_____" ], [ "df_flourish_015.head(10).to_csv('015_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.16. ¿Cuáles son los 10 lenguajes de programación más usados entre los programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_10_prog_languages_devs = data_test[['LanguageHaveWorkedWith']].copy()\ndf_10_prog_languages_devs.head()", "_____no_output_____" ], [ "df_10_prog_languages_devs['LanguageHaveWorkedWith'] = df_10_prog_languages_devs['LanguageHaveWorkedWith'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts_016 = df_10_prog_languages_devs['LanguageHaveWorkedWith'].str.split(expand=True).stack().value_counts().rename_axis('Languages').reset_index(name='Count')", "_____no_output_____" ], [ "df_counts_016.head(10)", "_____no_output_____" ], [ "df_counts_016.head(10).to_csv('016_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.17. ¿Cuáles son las bases de datos más usadas entre los programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_10_databases = data_test[['DatabaseHaveWorkedWith']].copy()\ndf_10_databases.head()", "_____no_output_____" ], [ "df_10_databases['DatabaseHaveWorkedWith'] = df_10_databases['DatabaseHaveWorkedWith'].str.replace(' ', '')", "_____no_output_____" ], [ "df_10_databases['DatabaseHaveWorkedWith'] = df_10_databases['DatabaseHaveWorkedWith'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts_017 = df_10_databases['DatabaseHaveWorkedWith'].str.split(expand=True).stack().value_counts().rename_axis('Databases').reset_index(name='Count')", "_____no_output_____" ], [ "df_counts_017.head(10)", "_____no_output_____" ], [ "df_counts_017.head(10).to_csv('017_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.18. ¿Cuáles son las plataformas más usadas entre los programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_10_platforms = data_test[['PlatformHaveWorkedWith']].copy()\ndf_10_platforms.head()", "_____no_output_____" ], [ "df_10_platforms['PlatformHaveWorkedWith'] = df_10_platforms['PlatformHaveWorkedWith'].str.replace(' ', '')", "_____no_output_____" ], [ "df_10_platforms['PlatformHaveWorkedWith'] = df_10_platforms['PlatformHaveWorkedWith'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts_018 = df_10_platforms['PlatformHaveWorkedWith'].str.split(expand=True).stack().value_counts().rename_axis('Platform').reset_index(name='Count')", "_____no_output_____" ], [ "df_counts_018.head(10)", "_____no_output_____" ], [ "df_counts_018.to_csv('018_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.19. ¿Cuáles son los frameworks web más usados entre los programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_10_web_frameworks = data_test[['WebframeHaveWorkedWith']].copy()\ndf_10_web_frameworks.head()", "_____no_output_____" ], [ "df_10_web_frameworks['WebframeHaveWorkedWith'] = df_10_web_frameworks['WebframeHaveWorkedWith'].str.replace(' ', '')", "_____no_output_____" ], [ "df_10_web_frameworks['WebframeHaveWorkedWith'] = df_10_web_frameworks['WebframeHaveWorkedWith'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts_019 = df_10_web_frameworks['WebframeHaveWorkedWith'].str.split(expand=True).stack().value_counts().rename_axis('Web framework').reset_index(name='Count')", "_____no_output_____" ], [ "df_counts_019.head(10)", "_____no_output_____" ], [ "df_counts_019.to_csv('019_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.20. ¿Cuáles son las herramientas tecnológicas más usadas entre los programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_10_data_misc_techs = data_test[['MiscTechHaveWorkedWith', 'ToolsTechHaveWorkedWith']].copy()\ndf_10_data_misc_techs.head()", "_____no_output_____" ], [ "df_10_data_misc_techs['AllMiscTechs'] = df_10_data_misc_techs['MiscTechHaveWorkedWith'].map(str) + ';' + df_10_data_misc_techs['ToolsTechHaveWorkedWith'].map(str)", "_____no_output_____" ], [ "df_10_data_misc_techs.head()", "_____no_output_____" ], [ "df_10_data_misc_techs['AllMiscTechs'] = df_10_data_misc_techs['AllMiscTechs'].str.replace(' ', '')", "_____no_output_____" ], [ "df_10_data_misc_techs['AllMiscTechs'] = df_10_data_misc_techs['AllMiscTechs'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts_020 = df_10_data_misc_techs['AllMiscTechs'].str.split(expand=True).stack().value_counts().rename_axis('Tecnología').reset_index(name='# Programadores')", "_____no_output_____" ], [ "df_counts_020.head(10)", "_____no_output_____" ], [ "df_counts_020.head(10).to_csv('020_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.21. ¿Cuáles son las herramientas colaborativas más usadas entre programadores?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_10_colab = data_test[['NEWCollabToolsHaveWorkedWith']].copy()\ndf_10_colab.head()", "_____no_output_____" ], [ "df_10_colab['NEWCollabToolsHaveWorkedWith'] = df_10_colab['NEWCollabToolsHaveWorkedWith'].str.replace(' ', '')", "_____no_output_____" ], [ "df_10_colab['NEWCollabToolsHaveWorkedWith'] = df_10_colab['NEWCollabToolsHaveWorkedWith'].str.replace(';', ' ')", "_____no_output_____" ], [ "df_counts_021 = df_10_colab['NEWCollabToolsHaveWorkedWith'].str.split(expand=True).stack().value_counts().rename_axis('Herramienta Colaborativa').reset_index(name='# Programadores')", "_____no_output_____" ], [ "df_counts_021.head(10)", "_____no_output_____" ], [ "df_counts_021.head(10).to_csv('021_flourish_data.csv', index=False)", "_____no_output_____" ] ], [ [ "### 2.22. ¿Cuáles son los países con mayor número de programadores trabajando a tiempo completo?\n\nSe seleccionarán los campos adecuados para responder a esta pregunta", "_____no_output_____" ] ], [ [ "df_fulltime_employment = data_test[['Country', 'Employment']].copy()\ndf_fulltime_employment.head()", "_____no_output_____" ], [ "df_fulltime_employment.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 14517 entries, 45 to 83437\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Country 14517 non-null object\n 1 Employment 14517 non-null object\ndtypes: object(2)\nmemory usage: 856.3+ KB\n" ], [ "df_fulltime_only = df_fulltime_employment[df_fulltime_employment['Employment'] == 'Tiempo completo']", "_____no_output_____" ], [ "df_fulltime_only.head()", "_____no_output_____" ], [ "df_flourish_022 = df_fulltime_only['Country'].value_counts().to_frame('# Programadores').reset_index()", "_____no_output_____" ], [ "df_flourish_022.head(10)", "_____no_output_____" ], [ "df_flourish_022.head(10).to_csv('022_flourish_data.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", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d01b9fc8eb1fa55837cfe74c523542d9280c7a4d
62,274
ipynb
Jupyter Notebook
Analise.ipynb
WeDias/Algoritmos-Ordenacao
a1f3a2669aed0f6c855c56143e9a89def8eaca6a
[ "MIT" ]
null
null
null
Analise.ipynb
WeDias/Algoritmos-Ordenacao
a1f3a2669aed0f6c855c56143e9a89def8eaca6a
[ "MIT" ]
null
null
null
Analise.ipynb
WeDias/Algoritmos-Ordenacao
a1f3a2669aed0f6c855c56143e9a89def8eaca6a
[ "MIT" ]
null
null
null
233.235955
52,256
0.88928
[ [ [ "# This Python file uses the following encoding: utf-8\n\n# Analise.ipynb\n# Github:@WeDias\n\n# MIT License\n#\n# Copyright (c) 2020 Wesley R. Dias\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nfrom time import time\nfrom random import randint\n\n\nclass Analisador:\n \"\"\"Classe criada para obter os tempos de execução\n dos seguintes algoritmos de ordenação:\n 1.Built-in Python\n 2.Quicksort\n 3.Mergesort\n 4.Seleção\n \"\"\"\n _tempo_total = 0\n _resultados = {\n 'nativo': {},\n 'quicksort': {},\n 'mergesort': {},\n 'selecao': {}\n }\n\n # noinspection PyUnusedLocal\n def __init__(self, inicio: int = 2000, fim: int = 22000,\n passo: int = 2000, intervalo: tuple = (0, 20000)):\n \"\"\"Serve para iniciar o processo de obtenção dos tempos de execução de cada algoritmo\n :param inicio: int, número inicial de elementos aleatórios da lista, padrão 2000\n :param fim: int, número final de elementos aleatórios da lista, padrão 22000\n :param passo: int, número de elementos incrementados a cada teste, padrão 2000\n :param intervalo: tuple, intervalo de números aleatórios, padrão (0, 20000)\n \"\"\"\n inicio_exec = time()\n algoritmos = {\n 'nativo': self._nativo,\n 'quicksort': self._quicksort,\n 'mergesort': self._mergesort,\n 'selecao': self._selecao\n }\n for amostra in range(inicio, fim + 1, passo):\n array = [randint(intervalo[0], intervalo[1]) for a in range(amostra)]\n for nome_algo, algoritmo in algoritmos.items():\n self._temporizador(nome_algo, algoritmo, array, amostra)\n self._tempo_total = time() - inicio_exec\n print(f'Tempo total de execução: {self._tempo_total:.2f}s\\n')\n\n def resultado(self) -> dict:\n \"\"\"Serve para retornar um dicionário com os dados de tempo de\n execução de cada algoritmo em cada caso de teste\n :return: dict, dados do tempo de execução de cada algoritmo\n \"\"\"\n return self._resultados\n\n @staticmethod\n def _temporizador(nome_algo: str, algoritmo, array: list, amostra: int) -> None:\n \"\"\"Serve para registrar o tempo gasto para um algoritmo de\n ordenação ser executado e ordenar uma determinada lista\n :param nome_algo: str, nome do algoritmo\n :param algoritmo: function, algoritmo a ser executado\n :param array: list, lista de elementos a ser ordenada\n :param amostra: int, número de elementos da lista\n :return: None\n \"\"\"\n inicio_exec_algo = time()\n algoritmo(array)\n Analisador._resultados[nome_algo][amostra] = round(time() - inicio_exec_algo, 3)\n\n @staticmethod\n def _nativo(array: list) -> list:\n \"\"\"Algoritmo de ordenação Built-in do Python, serve para ordenar listas\n :param array: list, lista de elementos a ser ordenada\n :return: list, lista de elementos ordenados\n \"\"\"\n return sorted(array)\n\n @staticmethod\n def _quicksort(array: list) -> list:\n \"\"\"Algoritmo de ordenação Quicksort, serve para ordenar listas\n :param array: list, lista de elementos a ser ordenada\n :return: list, lista de elementos ordenados\n \"\"\"\n if len(array) <= 1:\n return array\n m = array[0]\n return Analisador._quicksort(\n [x for x in array if x < m]) + \\\n [x for x in array if x == m] + \\\n Analisador._quicksort([x for x in array if x > m])\n\n @staticmethod\n def _selecao(array: list) -> list:\n \"\"\"Algoritmo de ordenação Seleção, serve para ordenar listas\n :param array: list, lista de elementos a ser ordenada\n :return: list, lista de elementos ordenados\n \"\"\"\n r = []\n while array:\n m = min(array)\n r.append(m)\n array.remove(m)\n return r\n\n @staticmethod\n def _mergesort(array: list) -> list:\n \"\"\"Algoritmo de ordenação Mergesort, serve para ordenar listas\n :param array: list, lista de elementos a ser ordenada\n :return: list, lista de elementos ordenados\n \"\"\"\n if len(array) <= 1:\n return array\n else:\n m = len(array) // 2\n e = Analisador._mergesort(array[:m])\n d = Analisador._mergesort(array[m:])\n return Analisador._merge(e, d)\n\n @staticmethod\n def _merge(e:list , d: list) -> list:\n \"\"\"Serve para auxiliar no Mergesort\n :param e: list, Lista da esquerda\n :param d: list, Lista da direita\n :return: list, lista de elementos ordenados\n \"\"\"\n r = []\n i, j = 0, 0\n while i < len(e) and j < len(d):\n if e[i] <= d[j]:\n r.append(e[i])\n i += 1\n else:\n r.append(d[j])\n j += 1\n r += e[i:]\n r += d[j:]\n return r", "_____no_output_____" ], [ "# Obtenção dos dados de execução dos algoritmos\nfrom pandas import DataFrame\n\nanalise = Analisador()\ndf = DataFrame.from_dict(analise.resultado())\nprint(df)", "Tempo total de execução: 30.01s\n\n nativo quicksort mergesort selecao\n2000 0.000 0.008 0.014 0.052\n4000 0.000 0.018 0.028 0.223\n6000 0.000 0.035 0.053 0.479\n8000 0.001 0.044 0.075 0.852\n10000 0.001 0.043 0.092 1.351\n12000 0.002 0.065 0.125 1.976\n14000 0.002 0.059 0.116 2.651\n16000 0.003 0.069 0.137 3.470\n18000 0.003 0.091 0.177 4.422\n20000 0.004 0.127 0.214 5.439\n22000 0.004 0.100 0.191 6.954\n" ], [ "# Geração do gráfico comparativo\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(16, 9))\nplt.plot(df, marker='.')\nplt.title('Comparação entre algoritmos de ordenação', size=16)\nplt.legend(('Nativo (Python)', 'Quicksort', 'Mergesort', 'Seleção'), fontsize=14)\nplt.xlabel('Número de elementos', size=14)\nplt.ylabel('Tempo em segundos', size=14)\nplt.grid()\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
d01ba8eae1796ba6ec774d7a77e646c4ae413757
136,785
ipynb
Jupyter Notebook
PyBer_analysis_code.ipynb
rfwilliams92/Pyber_Ridesharing_Analysis
d8042af2eec8082ce0334c1f127cde4530280737
[ "Apache-2.0" ]
null
null
null
PyBer_analysis_code.ipynb
rfwilliams92/Pyber_Ridesharing_Analysis
d8042af2eec8082ce0334c1f127cde4530280737
[ "Apache-2.0" ]
null
null
null
PyBer_analysis_code.ipynb
rfwilliams92/Pyber_Ridesharing_Analysis
d8042af2eec8082ce0334c1f127cde4530280737
[ "Apache-2.0" ]
null
null
null
87.124204
88,924
0.759784
[ [ [ "# Pyber Analysis", "_____no_output_____" ], [ "### 4.3 Loading and Reading CSV files", "_____no_output_____" ] ], [ [ "# Add Matplotlib inline magic command\n%matplotlib inline\n# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib.dates as mdates\n\n# File to Load (Remember to change these)\ncity_data_to_load = \"Resources/city_data.csv\"\nride_data_to_load = \"Resources/ride_data.csv\"\n\n# Read the City and Ride Data\ncity_data_df = pd.read_csv(city_data_to_load)\nride_data_df = pd.read_csv(ride_data_to_load)", "_____no_output_____" ] ], [ [ "### Merge the DataFrames", "_____no_output_____" ] ], [ [ "# Combine the data into a single dataset\npyber_data_df = pd.merge(ride_data_df, city_data_df, how=\"left\", on=[\"city\", \"city\"])\n\n# Display the data table for preview\npyber_data_df", "_____no_output_____" ] ], [ [ "## Deliverable 1: Get a Summary DataFrame ", "_____no_output_____" ] ], [ [ "# 1. Get the total rides for each city type\ntot_rides_by_type = pyber_data_df.groupby([\"type\"]).count()[\"ride_id\"]\ntot_rides_by_type", "_____no_output_____" ], [ "# 2. Get the total drivers for each city type\ntot_drivers_by_type = city_data_df.groupby([\"type\"]).sum()[\"driver_count\"]\ntot_drivers_by_type", "_____no_output_____" ], [ "# 3. Get the total amount of fares for each city type\ntot_fares_by_type = pyber_data_df.groupby([\"type\"]).sum()[\"fare\"]\ntot_fares_by_type", "_____no_output_____" ], [ "# 4. Get the average fare per ride for each city type. \navg_fare_by_type = round((tot_fares_by_type / tot_rides_by_type), 2)\navg_fare_by_type", "_____no_output_____" ], [ "# 5. Get the average fare per driver for each city type. \navg_fare_per_driver_by_type = round((tot_fares_by_type / tot_drivers_by_type), 2)\navg_fare_per_driver_by_type ", "_____no_output_____" ], [ "# 6. Create a PyBer summary DataFrame. \npyber_summary_df = pd.DataFrame({\n \"Total Rides\": tot_rides_by_type,\n \"Total Drivers\": tot_drivers_by_type,\n \"Total Fares\": tot_fares_by_type,\n \"Average Fare per Ride\": avg_fare_by_type,\n \"Average Fare per Driver\": avg_fare_per_driver_by_type \n })\npyber_summary_df.dtypes", "_____no_output_____" ], [ "# 7. Cleaning up the DataFrame. Delete the index name\npyber_summary_df.index.name = None\npyber_summary_df", "_____no_output_____" ], [ "# 8. Format the columns.\npyber_summary_df['Total Rides'] = pyber_summary_df['Total Rides'].map('{:,}'.format)\npyber_summary_df['Total Drivers'] = pyber_summary_df['Total Drivers'].map('{:,}'.format)\npyber_summary_df['Total Fares'] = pyber_summary_df['Total Fares'].map('${:,}'.format)\npyber_summary_df['Average Fare per Ride'] = pyber_summary_df['Average Fare per Ride'].map('${:,}'.format)\npyber_summary_df['Average Fare per Driver'] = pyber_summary_df['Average Fare per Driver'].map('${:,}'.format)\npyber_summary_df", "_____no_output_____" ] ], [ [ "## Deliverable 2. Create a multiple line plot that shows the total weekly of the fares for each type of city.", "_____no_output_____" ] ], [ [ "# 1. Read the merged DataFrame\npyber_data_df", "_____no_output_____" ], [ "# 2. Using groupby() to create a new DataFrame showing the sum of the fares \n# for each date where the indices are the city type and date.\ntot_fares_by_date_df = pd.DataFrame(pyber_data_df.groupby([\"type\", \"date\"]).sum()[\"fare\"])\ntot_fares_by_date_df", "_____no_output_____" ], [ "# 3. Reset the index on the DataFrame you created in #1. This is needed to use the 'pivot()' function.\n# df = df.reset_index()\ntot_fares_by_date_df = tot_fares_by_date_df.reset_index()\ntot_fares_by_date_df", "_____no_output_____" ], [ "# 4. Create a pivot table with the 'date' as the index, the columns ='type', and values='fare' \n# to get the total fares for each type of city by the date. \npyber_pivot = tot_fares_by_date_df.pivot(index=\"date\", columns=\"type\", values=\"fare\")\npyber_pivot", "_____no_output_____" ], [ "# 5. Create a new DataFrame from the pivot table DataFrame using loc on the given dates, '2019-01-01':'2019-04-29'.\npyber_pivot_df = pyber_pivot.loc['2019-01-01':'2019-04-29']\npyber_pivot_df", "_____no_output_____" ], [ "# 6. Set the \"date\" index to datetime datatype. This is necessary to use the resample() method in Step 8.\npyber_pivot_df.index = pd.to_datetime(pyber_pivot_df.index)", "_____no_output_____" ], [ "# 7. Check that the datatype for the index is datetime using df.info()\npyber_pivot_df.info()", "<class 'pandas.core.frame.DataFrame'>\nDatetimeIndex: 2196 entries, 2019-01-01 00:08:16 to 2019-04-28 19:35:03\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Rural 114 non-null float64\n 1 Suburban 573 non-null float64\n 2 Urban 1509 non-null float64\ndtypes: float64(3)\nmemory usage: 68.6 KB\n" ], [ "# 8. Create a new DataFrame using the \"resample()\" function by week 'W' and get the sum of the fares for each week.\ntot_fares_by_week_df = pyber_pivot_df.resample('W').sum()\ntot_fares_by_week_df", "_____no_output_____" ], [ "# 8. Using the object-oriented interface method, plot the resample DataFrame using the df.plot() function. \n\n# Import the style from Matplotlib.\nfrom matplotlib import style\n# Use the graph style fivethirtyeight.\nstyle.use('fivethirtyeight')\n\nfig, ax = plt.subplots()\ntot_fares_by_week_df.plot(figsize=(20,7), ax=ax)\n\nax.set_title(\"Total Fares by City Type\")\nax.set_ylabel(\"Fares($USD)\")\nax.set_xlabel(\"Month(Weekly Fare Totals)\")\nax.legend(labels=[\"Rural\", \"Suburban\", \"Urban\"],\n loc=\"center\")\n\nplt.savefig(\"analysis/PyBer_fare_summary.png\")\n\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01bc2f452d69abcff0063535d78cb952bf78a44
630,987
ipynb
Jupyter Notebook
examples/all_weather_portfolio.ipynb
gomtinQQ/NDFinance
522bf0486e5f5337c522d0e34b088f386c7c3290
[ "MIT" ]
35
2020-09-26T16:31:45.000Z
2022-01-01T12:12:21.000Z
examples/all_weather_portfolio.ipynb
gomtinQQ/NDFinance
522bf0486e5f5337c522d0e34b088f386c7c3290
[ "MIT" ]
1
2020-09-27T08:54:23.000Z
2020-09-27T08:54:23.000Z
examples/all_weather_portfolio.ipynb
gomtinQQ/NDFinance
522bf0486e5f5337c522d0e34b088f386c7c3290
[ "MIT" ]
8
2020-10-06T23:51:22.000Z
2022-02-16T12:11:10.000Z
1,071.285229
98,896
0.957172
[ [ [ "!pip install ndfinance #install ndfinance", "Requirement already satisfied: ndfinance in /home/bellmanlabs/anaconda3/envs/BellmanFinance/lib/python3.7/site-packages (0.0.2)\n" ], [ "EXPORT_PATH = \"./bt_results/all_weather_portfolio/\"", "_____no_output_____" ] ], [ [ "# Import Packages", "_____no_output_____" ] ], [ [ "from ndfinance.brokers.backtest import *\nfrom ndfinance.core import BacktestEngine\nfrom ndfinance.analysis.backtest import BacktestAnalyzer\nfrom ndfinance.strategies import PeriodicRebalancingStrategy\nfrom ndfinance.visualizers.backtest_visualizer import BasicVisualizer\n%matplotlib inline\nimport matplotlib.pyplot as plt", "2020-10-10 13:22:13,815\tINFO resource_spec.py:212 -- Starting Ray with 15.38 GiB memory available for workers and up to 7.7 GiB for objects. You can adjust these settings with ray.init(memory=<bytes>, object_store_memory=<bytes>).\n2020-10-10 13:22:14,051\tWARNING services.py:923 -- Redis failed to start, retrying now.\n2020-10-10 13:22:14,252\tINFO services.py:1165 -- View the Ray dashboard at \u001b[1m\u001b[32mlocalhost:8265\u001b[39m\u001b[22m\n" ] ], [ [ "# build strategy", "_____no_output_____" ] ], [ [ "class AllWeatherPortfolio(PeriodicRebalancingStrategy):\n def __init__(self, weight_dict, rebalance_period):\n super(AllWeatherPortfolio, self).__init__(rebalance_period)\n self.weight_dict = weight_dict\n \n \n def _logic(self):\n self.broker.order(Rebalance(self.weight_dict.keys(), self.weight_dict.values()))", "_____no_output_____" ] ], [ [ "# set portfolio elements, weights, rebalance period\nyou can adjust and play in your own!", "_____no_output_____" ] ], [ [ "PORTFOLIO = {\n \"GLD\" : 0.05, \n \"SPY\" : 0.5,\n \"SPTL\" : 0.15,\n \"BWZ\" : 0.15,\n \"SPHY\": 0.15,\n}", "_____no_output_____" ], [ "REBALANCE_PERIOD = TimeFrames.day * 365", "_____no_output_____" ] ], [ [ "# Make data provider", "_____no_output_____" ] ], [ [ "dp = BacktestDataProvider()\ndp.add_yf_tickers(*PORTFOLIO.keys())", "_____no_output_____" ] ], [ [ "# Make time indexer", "_____no_output_____" ] ], [ [ "indexer = TimeIndexer(dp.get_shortest_timestamp_seq())\ndp.set_indexer(indexer)\ndp.cut_data()", "_____no_output_____" ] ], [ [ "# Make broker and add assets", "_____no_output_____" ] ], [ [ "brk = BacktestBroker(dp, initial_margin=10000)\n_ = [brk.add_asset(Asset(ticker=ticker)) for ticker in PORTFOLIO.keys()]", "_____no_output_____" ] ], [ [ "# Initialize strategy", "_____no_output_____" ] ], [ [ "strategy = AllWeatherPortfolio(PORTFOLIO, rebalance_period=REBALANCE_PERIOD)", "_____no_output_____" ] ], [ [ "# Initialize backtest engine", "_____no_output_____" ] ], [ [ "engine = BacktestEngine()\nengine.register_broker(brk)\nengine.register_strategy(strategy)", "_____no_output_____" ] ], [ [ "# run", "_____no_output_____" ] ], [ [ "log = engine.run()", "[ENGINE]: 100%|██████████| 2090/2090 [00:00<00:00, 11637.76it/s]\n" ] ], [ [ "# run analysis", "_____no_output_____" ] ], [ [ "analyzer = BacktestAnalyzer(log)\nanalyzer.print()", "\n\n-------------------------------------------------- [BACKTEST RESULT] --------------------------------------------------\nCAGR:10.644\nMDD:19.49\nCAGR_MDD_ratio:0.546\nwin_trade_count:24\nlose_trade_count:11\ntotal_trade_count:75\nwin_rate_percentage:32.0\nlose_rate_percentage:14.667\nsharpe_ratio:0.279\nsortino_ratio:0.361\npnl_ratio_sum:13.677\npnl_ratio:6.269\naverage_realized_pnl:90.262\nmax_realized_pnl:1255.897\nmin_realized_pnl:-232.054\naverage_realized_pnl_percentage:2.427\nmax_realized_pnl_percentage:26.859\nmin_realized_pnl_percentage:-13.873\naverage_realized_pnl_percentage_weighted:0.661\nmax_realized_pnl_percentage_weighted:9.432\nmin_realized_pnl_percentage_weighted:-1.999\naverage_portfolio_value_total:12706.284\nmax_portfolio_value_total:18406.706\nmin_portfolio_value_total:9613.284\naverage_portfolio_value:12706.284\nmax_portfolio_value:18406.706\nmin_portfolio_value:9613.284\naverage_leverage:0.88\nmax_leverage:1.0\nmin_leverage:0.0\naverage_leverage_total:0.88\nmax_leverage_total:1.0\nmin_leverage_total:0.0\naverage_cash_weight_percentage:11.962\nmax_cash_weight_percentage:100.0\nmin_cash_weight_percentage:0.0\naverage_cash_weight_percentage_total:11.962\nmax_cash_weight_percentage_total:100.0\nmin_cash_weight_percentage_total:0.0\naverage_unrealized_pnl_percentage:2.343\nmax_unrealized_pnl_percentage:10.526\nmin_unrealized_pnl_percentage:-11.134\naverage_unrealized_pnl_percentage_total:2.343\nmax_unrealized_pnl_percentage_total:10.526\nmin_unrealized_pnl_percentage_total:-11.134\naverage_1M_pnl_percentage:0.59\nmax_1M_pnl_percentage:8.165\nmin_1M_pnl_percentage:-6.083\naverage_1D_pnl_percentage:0.0\nmax_1D_pnl_percentage:0.0\nmin_1D_pnl_percentage:0.0\naverage_1W_pnl_percentage:0.107\nmax_1W_pnl_percentage:5.255\nmin_1W_pnl_percentage:-9.881\n" ] ], [ [ "# visualize", "_____no_output_____" ] ], [ [ "visualizer = BasicVisualizer()\nvisualizer.plot_log(log)", "_____no_output_____" ] ], [ [ "# Export", "_____no_output_____" ] ], [ [ "visualizer.export(EXPORT_PATH)\nanalyzer.export(EXPORT_PATH)", "\n\n-------------------------------------------------- [EXPORTING FIGURES] --------------------------------------------------\nexporting figure to: ./bt_results/all_weather_portfolio/plot/mdd.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/cagr.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/sharpe.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/sortino.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/portfolio_value.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/portfolio_value_cum_pnl_perc.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/portfolio_value_total.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/portfolio_value_total_cum_pnl_perc.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/realized_pnl_percentage_hist.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/realized_pnl_percentage_weighted_hist.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/1M_pnl_hist.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/1D_pnl_hist.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/1W_pnl_hist.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/1M_pnl_bar.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/1D_pnl_bar.png\nexporting figure to: ./bt_results/all_weather_portfolio/plot/1W_pnl_bar.png\n\n\n-------------------------------------------------- [EXPORTING RESULT/LOG] --------------------------------------------------\nsaving log: ./bt_results/all_weather_portfolio/broker_log.csv\nsaving log: ./bt_results/all_weather_portfolio/portfolio_log.csv\nsaving result to: ./bt_results/all_weather_portfolio/result.json\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01bddbb48f435ddbcc0733496c990b6a5e3c342
89,398
ipynb
Jupyter Notebook
docs/site/tutorials/walkthrough.ipynb
sendilkumarn/swift
60d3c495c96b3de791caf2eb2daa50a0949e7842
[ "CC-BY-4.0" ]
1
2019-10-02T06:13:47.000Z
2019-10-02T06:13:47.000Z
docs/site/tutorials/walkthrough.ipynb
sendilkumarn/swift
60d3c495c96b3de791caf2eb2daa50a0949e7842
[ "CC-BY-4.0" ]
null
null
null
docs/site/tutorials/walkthrough.ipynb
sendilkumarn/swift
60d3c495c96b3de791caf2eb2daa50a0949e7842
[ "CC-BY-4.0" ]
null
null
null
63.583215
24,092
0.756616
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d01be05e6a57e57d501442f897a21f198a28628f
630,092
ipynb
Jupyter Notebook
Parte 1/notebooks/3-descriptive_stats.ipynb
mbs8/IF679-ciencia-de-dados
ee5b44ca6833408bc3aa2808823e83b3f287d866
[ "MIT" ]
null
null
null
Parte 1/notebooks/3-descriptive_stats.ipynb
mbs8/IF679-ciencia-de-dados
ee5b44ca6833408bc3aa2808823e83b3f287d866
[ "MIT" ]
null
null
null
Parte 1/notebooks/3-descriptive_stats.ipynb
mbs8/IF679-ciencia-de-dados
ee5b44ca6833408bc3aa2808823e83b3f287d866
[ "MIT" ]
null
null
null
686.374728
506,640
0.944438
[ [ [ "# Estatísticas descritivas e Visualização de Dados\nEste notebook é responsável por mostrar as estatíscas descritivas da base dados com visualizações.\nSerá analisado o comportamento de algumas características que são cruciais na compra/venda de veículos usados.", "_____no_output_____" ] ], [ [ "from Utils import *\nfrom tqdm import tqdm\nfrom matplotlib import pyplot as plt\nimport seaborn as sns", "_____no_output_____" ], [ "pd.set_option('display.max_colwidth', 100)\nDATASET = \"../datasets/clean_vehicles_2.csv\"\ndf = pd.read_csv(DATASET)\n\ndf.describe()", "_____no_output_____" ] ], [ [ "## Estatísticas Univariadas\nAqui vamos análisar o comportamento de alguns dados em relação a sua distribuição.\n### Ano de fabricação\n\n", "_____no_output_____" ] ], [ [ "##Análise de média, desvio padrão, mediana e moda do Ano de fabricação\nprint(\n\"Ano do veículo:\\n\"\n\"Média: \"+floatStr(df['year'].mean())+\"\\n\"+\n\"Desvio padrão: \"+floatStr(df['year'].std())+\"\\n\"+ \n\"Mediana: \"+floatStr(df['year'].median())+\"\\n\"+\n\"IQR: \"+floatStr(df['year'].describe()[6] - df['year'].describe()[4])+\"\\n\"+\n\"Moda: \"+floatStr(df['year'].mode().loc[0]) \n)", "Ano do veículo:\nMédia: 2010.26\nDesvio padrão: 8.67\nMediana: 2012.0\nIQR: 9.0\nModa: 2017.0\n" ] ], [ [ "Aqui notamos uma mediana maior do que a média. O que nos levar a imaginar que esta grandeza não segue uma distribuição normal.\nIsto indica que deve haver alguns carros muito antigos sendo vendidos, gerando uma caractéristica de assimetria na curva.\n\n\nPara verifcarmos isso, vamos gerar o histograma", "_____no_output_____" ] ], [ [ "##Plotar o histograma da distribuição em relação ao ano de fabricação do veículo\nbars = df[df['year']> 0].year.max() - df[df['year']> 0].year.min()\ndf[df['year']> 0].year.hist(bins = int(bars))", "_____no_output_____" ] ], [ [ "Porém, este plotting não nos dá uma boa visualização. Nesta lista há alguns carros voltados para colecionadores, que não é o perfil que queremos estudar. \nEntão, tomando o ano de 1985 como limiar, analisamos o histograma da distribuição de carros comercializáveis \"para uso normal\".\n\nAgora conseguimos perceber que a maior parte dos carros vendidos são fábricados depois de 2000. ", "_____no_output_____" ] ], [ [ "##Plot do histograma dos anos de fabricação do carro limitando à 1985\nbars = df['year'].max() - 1985\ndf[df['year']> 1985].year.hist(bins = int(bars))\n", "_____no_output_____" ] ], [ [ "### Preço de revenda do veículo", "_____no_output_____" ] ], [ [ "##Análise de estatísticas univariadas dos valores de preço do veículo\nprint(\n\"Preço do veículo:\\n\"\n\"Média: \"+floatStr(df[df['price'] > 0].price.mean())+\"\\n\"+\n\"Desvio padrão: \"+floatStr(df[df['price'] > 0].price.std())+\"\\n\"+ \n\"Mediana: \"+floatStr(df[df['price'] > 0].price.median())+\"\\n\"+\n\"IQR: \"+floatStr(df['price'].describe()[6] - df['price'].describe()[4])+\"\\n\"+\n\"Moda: \"+floatStr(df[df['price'] > 0].price.mode().loc[0]) \n)", "Preço do veículo:\nMédia: 36809.65\nDesvio padrão: 6571953.45\nMediana: 11495.0\nIQR: 13000.0\nModa: 7995\n" ] ], [ [ "Aqui encontramos uma diferença muito grandes nestes dados. O que nos faz pensar que temos uma distribuição muito variada e assimétrica de preços.\n\n\nDevido a esta característica, não conseguiremos ver um histograma com todos os dados. Podemos contornar isto de 2 maneiras:\n\n * Poderíamos usar o log10 para ter uma noção da ordem de grandeza, mas não conseguiríamos extrair muita informação, pois a maioria se encaixariam em log10(x) = 4.\n * Outra alternativa seria plotar um subconjunto dos preços. \nEntão, depois de algumas análises, protaremos apenas valores de 0 a $ 100.000.\n", "_____no_output_____" ] ], [ [ "sns.distplot(df[(df['price'] > 0) & (df['price'] < 100000)].price, bins = 100,norm_hist = False, hist=True, kde=False)", "_____no_output_____" ] ], [ [ "### Leitura atual do Odômetro (Milhas percorrida pelo veículo)", "_____no_output_____" ] ], [ [ "##Análise de estatísticas univariadas dos valores de leitura do Odômetro.\n##Note que estamos descartando valores nulos para fazer esta análise\nprint(\n\"Odômetro do veículo:\\n\"\n\"Média: \"+floatStr(df[df['odometer'] > 0].odometer.mean())+\"\\n\"+\n\"Desvio padrão: \"+floatStr(df[df['odometer'] > 0].odometer.std())+\"\\n\"+ \n\"Mediana: \"+floatStr(df[df['odometer'] > 0].odometer.median())+\"\\n\"+\n\"IQR: \"+floatStr(df['odometer'].describe()[6] - df['odometer'].describe()[4])+\"\\n\"+\n\"Moda: \"+floatStr(df[df['odometer'] > 0].odometer.mode().loc[0]) \n)", "Odômetro do veículo:\nMédia: 99705.09\nDesvio padrão: 111570.94\nMediana: 92200.0\nIQR: 92054.0\nModa: 150000.0\n" ] ], [ [ "Aqui também temos uma grande varidade de valores. Apenas 492 deles estão acima de 800.000 de milhas registradas. Para fim de análise, iremos utilizar este intervalo.\n", "_____no_output_____" ] ], [ [ "sns.distplot(df[(df['odometer'] > 0) & (df['odometer'] < 400000)].odometer, bins = 100,norm_hist = False, hist=True, kde=False)", "_____no_output_____" ] ], [ [ "### Visualização de quantidade de anúncios por fabricantes de veículos\nFaremos uma análise visual para tentar perceber quais as marcas mais populares no mercado de seminovos.", "_____no_output_____" ] ], [ [ "## Plotar a divisão de mercas que são mais anunciadas\nmanufacturers = df['manufacturer'].value_counts().drop(df['manufacturer'].value_counts().index[8]).drop(df['manufacturer'].value_counts().index[13:])\nsns.set()\nplt.figure(figsize=(10,5))\nsns.barplot(x=manufacturers.index, y=manufacturers)\nprint(\"As 3 marcas mais anunciadas (Ford, chevrolet, toyota) equivalem a \"\n +str(round(sum(df['manufacturer'].value_counts().values[0:3])/df['manufacturer'].count()*100,2))\n +\"% deste mercado.\")\n", "As 3 marcas mais anunciadas (Ford, chevrolet, toyota) equivalem a 40.15% deste mercado.\n" ], [ "filter_list = ['ford', 'chevrolet', 'toyota', 'nissan', 'honda']\nfiltereddf = df[df.manufacturer.isin(filter_list)]\n\nax = sns.boxplot(x=\"manufacturer\", y=\"price\", data= filtereddf[filtereddf['price']< 40000])", "_____no_output_____" ] ], [ [ "### Visualização da relação entre preço de carros classificados por tração\n\nAqui podemos comparar como o preço variam de acordo com a tração do veículo \n\n\n * 4wd: 4x4\n * rwd: tração traseira \n * fwd: tração dianteira\n \n \nComparamos a média, mediana e quantidade. Porém, já percebemos de análises anteriores que a mediana nos dá um valor mais razoável, por isto ordenamos baseado nela\n", "_____no_output_____" ] ], [ [ "df[df['drive'] != 'undefined'].groupby(['drive']).agg(['mean','median','count'])['price'].sort_values(by='median', ascending=False)", "_____no_output_____" ] ], [ [ "## Estatísticas Bivariadas\nAqui vamos tentar encontrar se as grandezas numéricas possuem algum tipo de correlação. Primeiro analisaremos o método de spearman, depois de pearson. Em seguida tentaremos utilizar ", "_____no_output_____" ] ], [ [ "##Aplicando-se alguns limitadores para analisar correlações entre as variáveis\ncar = df[(df['odometer']> 0) & (df['odometer']<400000)]\ncar = car[(car['price']>0) & (car['price']<100000)]\ncar = car[car['year']>=1985]\ncar = car.drop(['lat','long'], axis=1)\ncar.cov()", "_____no_output_____" ], [ "car.corr(method='spearman')", "_____no_output_____" ], [ "car.corr(method='pearson')", "_____no_output_____" ], [ "##Relaçãoo de preço x milhas rodadas entre as 3 marcas mais populares\nfilter_list = ['ford', 'chevrolet', 'toyota']\ncar[car['manufacturer'].isin(filter_list)].plot.scatter(x='odometer',y='price')", "*c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*. Please use the *color* keyword-argument or provide a 2-D array with a single row if you intend to specify the same RGB or RGBA value for all points.\n" ], [ "g = sns.FacetGrid(car[car['manufacturer']!='undefined'], col=\"manufacturer\", hue='drive')\ng.map(sns.scatterplot, \"year\", \"price\")\ng.add_legend()\n\n#Clique na imagem pequena para expandir", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d01c0cd630250940fcd3f5a7075f0d09a6e1510a
38,008
ipynb
Jupyter Notebook
src/notebooks/255-percentage-stacked-area-chart.ipynb
nrslt/The-Python-Graph-Gallery
55898de66070ae716c95442466783ee986576e7d
[ "0BSD" ]
null
null
null
src/notebooks/255-percentage-stacked-area-chart.ipynb
nrslt/The-Python-Graph-Gallery
55898de66070ae716c95442466783ee986576e7d
[ "0BSD" ]
null
null
null
src/notebooks/255-percentage-stacked-area-chart.ipynb
nrslt/The-Python-Graph-Gallery
55898de66070ae716c95442466783ee986576e7d
[ "0BSD" ]
null
null
null
348.697248
19,270
0.750079
[ [ [ "Welcome in the introductory template of the python graph gallery. Here is how to proceed to add a new `.ipynb` file that will be converted to a blogpost in the gallery!", "_____no_output_____" ], [ "## Notebook Metadata", "_____no_output_____" ], [ "It is very important to add the following fields to your notebook. It helps building the page later on:\n- **slug**: the URL of the blogPost. It should be exactly the same as the file title. Example: `70-basic-density-plot-with-seaborn`\n- **chartType**: the chart type like density or heatmap. For a complete list see [here](https://github.com/holtzy/The-Python-Graph-Gallery/blob/master/src/util/sectionDescriptions.js), it must be one of the `id` options.\n- **title**: what will be written in big on top of the blogpost! use html syntax there.\n- **description**: what will be written just below the title, centered text.\n- **keyword**: list of keywords related with the blogpost\n- **seoDescription**: a description for the bloppost meta. Should be a bit shorter than the description and must not contain any html syntax.", "_____no_output_____" ], [ "## Add a chart description", "_____no_output_____" ], [ "A chart example always come with some explanation. It must:\n\ncontain keywords\nlink to related pages like the parent page (graph section)\ngive explanations. In depth for complicated charts. High level for beginner level charts", "_____no_output_____" ], [ "## Add a chart", "_____no_output_____" ] ], [ [ "import seaborn as sns, numpy as np\nnp.random.seed(0)\nx = np.random.randn(100)\nax = sns.distplot(x)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
d01c0d484ce04960fdd0338cd0bda4b3fa76f35f
202,676
ipynb
Jupyter Notebook
airbnb-rj-1/Data Treatment.ipynb
reneoctavio/analysis
e46eab42d5c3705e9c1dc9c1112be548153e794a
[ "MIT" ]
1
2021-02-06T19:02:52.000Z
2021-02-06T19:02:52.000Z
airbnb-rj-1/Data Treatment.ipynb
reneoctavio/analysis
e46eab42d5c3705e9c1dc9c1112be548153e794a
[ "MIT" ]
null
null
null
airbnb-rj-1/Data Treatment.ipynb
reneoctavio/analysis
e46eab42d5c3705e9c1dc9c1112be548153e794a
[ "MIT" ]
null
null
null
55.315502
10,004
0.604635
[ [ [ "# Airbnb - Rio de Janeiro\n* Download [data](http://insideairbnb.com/get-the-data.html)\n* We downloaded `listings.csv` from all monthly dates available\n\n## Questions\n1. What was the price and supply behavior before and during the pandemic?\n2. Does a title in English or Portuguese impact the price?\n3. What features correlate with the price? Can we predict a price? Which features matters?", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport glob\nimport re\nimport pendulum\nimport tqdm\n\nimport matplotlib.pyplot as plt\n\nimport langid\nlangid.set_languages(['en','pt'])", "_____no_output_____" ] ], [ [ "### Read files\nRead all 30 files and get their date", "_____no_output_____" ] ], [ [ "files = sorted(glob.glob('data/listings*.csv'))\n\ndf = []\nfor f in files:\n date = pendulum.from_format(re.findall(r\"\\d{4}_\\d{2}_\\d{2}\", f)[0], fmt=\"YYYY_MM_DD\").naive()\n csv = pd.read_csv(f)\n csv[\"date\"] = date\n df.append(csv)\ndf = pd.concat(df)\ndf", "_____no_output_____" ] ], [ [ "### Deal with NaNs\n* Drop `neighbourhood_group` as it is all NaNs;\n* Fill `reviews_per_month` with zeros (if there is no review, then reviews per month are zero)\n* Keep `name` for now\n* Drop `host_name` rows, as there is not any null host_id\n* Keep `last_review` too, as there are rooms with no review", "_____no_output_____" ] ], [ [ "df.isna().any()", "_____no_output_____" ], [ "df = df.drop([\"host_name\", \"neighbourhood_group\"], axis=1)\ndf[\"reviews_per_month\"] = df[\"reviews_per_month\"].fillna(0.)\ndf.head()", "_____no_output_____" ] ], [ [ "### Detect `name` language\n* Clean strings for evaluation\n* Remove common neighbourhoods name in Portuguese from `name` column to diminish misprediction\n* Remove several non-alphanumeric characters\n* Detect language using [langid](https://github.com/saffsd/langid.py)\n* I restricted between pt, en. There are very few rooms listed in other languages.\n* Drop `name` column", "_____no_output_____" ] ], [ [ "import unicodedata", "_____no_output_____" ], [ "stopwords = pd.unique(df[\"neighbourhood\"])\nstopwords = [re.sub(r\"[\\(\\)]\", \"\", x.lower().strip()).split() for x in stopwords]\nstopwords = [x for item in stopwords for x in item]\nstopwords += [unicodedata.normalize(\"NFKD\", x).encode('ASCII', 'ignore').decode() for x in stopwords]\nstopwords += [\"rio\", \"janeiro\", \"copa\", \"arpoador\", \"pepê\", \"pepe\", \"lapa\", \"morro\", \"corcovado\"]\nstopwords = set(stopwords)", "_____no_output_____" ], [ "docs = [re.sub(r\"[\\-\\_\\\\\\/\\,\\;\\:\\!\\+\\’\\%\\&\\d\\*\\#\\\"\\´\\`\\.\\|\\(\\)\\[\\]\\@\\'\\»\\«\\>\\<\\❤️\\…]\", \" \", str(x)) for x in df[\"name\"].tolist()]\ndocs = [\" \".join(x.lower().strip().split()) for x in docs]\ndocs = [\"\".join(e for e in x if (e.isalnum() or \" \")) for x in docs]", "_____no_output_____" ], [ "ndocs = []\nfor doc in tqdm.tqdm(docs):\n ndocs.append(\" \".join([x for x in doc.split() if x not in stopwords]))\ndocs = ndocs", "100%|██████████| 1047691/1047691 [00:01<00:00, 649856.94it/s]\n" ], [ "results = []\nfor d in tqdm.tqdm(docs):\n results.append(langid.classify(d)[0])", "100%|██████████| 1047691/1047691 [01:10<00:00, 14788.52it/s]\n" ], [ "df[\"language\"] = results\n\n# Because we transformed NaNs into string, fill those detection with nans too\ndf.loc[df[\"name\"].isna(), \"language\"] = pd.NA", "_____no_output_____" ] ], [ [ "* Test accuracy, manually label 383 out of 88191 (95% conf. interval, 5% margin of error)", "_____no_output_____" ] ], [ [ "df.loc[~df[\"name\"].isna()].drop_duplicates(\"name\").shape", "_____no_output_____" ], [ "df.loc[~df[\"name\"].isna()].drop_duplicates(\"name\")[[\"name\", \"language\"]].sample(n=383, random_state=42).to_csv(\"lang_pred_1.csv\")", "_____no_output_____" ], [ "lang_pred = pd.read_csv(\"lang_pred.csv\", index_col=0)\nlang_pred.head()", "_____no_output_____" ], [ "overall_accuracy = (lang_pred[\"pred\"] == lang_pred[\"true\"]).sum() / lang_pred.shape[0]\npt_accuracy = (lang_pred[lang_pred[\"true\"] == \"pt\"][\"true\"] == lang_pred[lang_pred[\"true\"] == \"pt\"][\"pred\"]).sum() / lang_pred[lang_pred[\"true\"] == \"pt\"].shape[0]\nen_accuracy = (lang_pred[lang_pred[\"true\"] == \"en\"][\"true\"] == lang_pred[lang_pred[\"true\"] == \"en\"][\"pred\"]).sum() / lang_pred[lang_pred[\"true\"] == \"en\"].shape[0]\nprint(f\"Overall accuracy: {overall_accuracy*100}%\")\nprint(f\"Portuguese accuracy: {pt_accuracy*100}%\")\nprint(f\"English accuracy: {en_accuracy*100}%\")", "Overall accuracy: 92.95039164490862%\nPortuguese accuracy: 92.67241379310344%\nEnglish accuracy: 95.27027027027027%\n" ], [ "df = df.drop(\"name\", axis=1)\ndf.head()", "_____no_output_____" ], [ "df[\"language\"].value_counts()", "_____no_output_____" ] ], [ [ "### Calculate how many times a room appeared\n* There are 30 months of data, and rooms appear multiple times\n* Calculate for a specific date, how many times the same room appeared up to that date", "_____no_output_____" ] ], [ [ "df = df.set_index([\"id\", \"date\"])\ndf[\"appearances\"] = df.groupby([\"id\", \"date\"])[\"host_id\"].count().unstack().cumsum(axis=1).stack()\ndf = df.reset_index()\ndf.head()", "_____no_output_____" ] ], [ [ "### Days since last review\n* Calculate days since last review\n* Then categorize them by the length of the days", "_____no_output_____" ] ], [ [ "df.loc[:, \"last_review\"] = pd.to_datetime(df[\"last_review\"], format=\"%Y/%m/%d\")", "_____no_output_____" ], [ "# For each scraping date, consider the last date to serve as comparision as the maximum date\nlast_date = df.groupby(\"date\")[\"last_review\"].max()\ndf[\"last_date\"] = df.apply(lambda row: last_date.loc[row[\"date\"]], axis=1)", "_____no_output_____" ], [ "df[\"days_last_review\"] = (df[\"last_date\"] - df[\"last_review\"]).dt.days", "_____no_output_____" ], [ "df = df.drop(\"last_date\", axis=1)\ndf.head()", "_____no_output_____" ], [ "df[\"days_last_review\"].describe()", "_____no_output_____" ], [ "def categorize_last_review(days_last_review):\n \"\"\"Transform days since last review into categories\n \n Transform days since last review into one of those categories:\n last_week, last_month, last_half_year, last_year, last_two_years, \n long_time_ago, or never\n\n Args:\n days_last_review (int): Days since the last review\n\n Returns:\n str: A string with the category name. \n \n \"\"\"\n if days_last_review <= 7:\n return \"last_week\"\n elif days_last_review <= 30:\n return \"last_month\"\n elif days_last_review <= 182:\n return \"last_half_year\"\n elif days_last_review <= 365:\n return \"last_year\"\n elif days_last_review <= 730:\n return \"last_two_years\"\n elif days_last_review > 730:\n return \"long_time_ago\"\n else:\n return \"never\"\n \ndf.loc[:, \"last_review\"] = df.apply(lambda row: categorize_last_review(row[\"days_last_review\"]), axis=1)", "_____no_output_____" ], [ "df = df.drop([\"days_last_review\"], axis=1)\ndf.head()", "_____no_output_____" ], [ "df = df.set_index([\"id\", \"date\"])\n\ndf.loc[:, \"appearances\"] = df[\"appearances\"].astype(int)\n\ndf.loc[:, \"host_id\"] = df[\"host_id\"].astype(\"category\")\ndf.loc[:, \"neighbourhood\"] = df[\"neighbourhood\"].astype(\"category\")\ndf.loc[:, \"room_type\"] = df[\"room_type\"].astype(\"category\")\ndf.loc[:, \"last_review\"] = df[\"last_review\"].astype(\"category\")\ndf.loc[:, \"language\"] = df[\"language\"].astype(\"category\")", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df.to_pickle(\"data.pkl\")", "_____no_output_____" ] ], [ [ "### Distributions\n* Check the distribution of features", "_____no_output_____" ] ], [ [ "df = pd.read_pickle(\"data.pkl\")\ndf.head()", "_____no_output_____" ], [ "df[\"latitude\"].hist(bins=250)", "_____no_output_____" ], [ "df[\"longitude\"].hist(bins=250)", "_____no_output_____" ], [ "df[\"price\"].hist(bins=250)", "_____no_output_____" ], [ "df[\"minimum_nights\"].hist(bins=250)", "_____no_output_____" ], [ "df[\"number_of_reviews\"].hist()", "_____no_output_____" ], [ "df[\"reviews_per_month\"].hist(bins=250)", "_____no_output_____" ], [ "df[\"calculated_host_listings_count\"].hist(bins=250)", "_____no_output_____" ], [ "df[\"availability_365\"].hist()", "_____no_output_____" ], [ "df[\"appearances\"].hist(bins=29)", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ] ], [ [ "### Limits\n* We are analising mostly for touristic purpose, so get the short-term rentals only\n* Prices between 10 and 10000 (The luxury Copacabana Palace Penthouse at 8000 for example)\n* Short-term rentals (minimum_nights < 31)\n* Impossibility of more than 31 reviews per month", "_____no_output_____" ] ], [ [ "df = pd.read_pickle(\"data.pkl\")\ntotal_records = len(df)", "_____no_output_____" ], [ "outbound_values = (df[\"price\"] < 10) | (df[\"price\"] > 10000)\ndf = df[~outbound_values]\n\nprint(f\"Removed values {outbound_values.sum()}, {outbound_values.sum()*100/total_records}%\")", "Removed values 5069, 0.48382586086928303%\n" ], [ "long_term = df[\"minimum_nights\"] >= 31\ndf = df[~long_term]\n\nprint(f\"Removed values {long_term.sum()}, {long_term.sum()*100/total_records}%\")", "Removed values 5742, 0.54806235808077%\n" ], [ "reviews_limit = df[\"reviews_per_month\"] > 31\ndf = df[~reviews_limit]\n\nprint(f\"Removed values {reviews_limit.sum()}, {reviews_limit.sum()*100/total_records}%\")", "Removed values 2, 0.00019089597982611286%\n" ] ], [ [ "### Log skewed variables\n* Most numerical values are skewed, so log them", "_____no_output_____" ] ], [ [ "df.describe()", "_____no_output_____" ], [ "# number_of_reviews, reviews_per_month, availability_365 have zeros, thus sum one to all\ndf[\"number_of_reviews\"] = np.log(df[\"number_of_reviews\"] + 1)\ndf[\"reviews_per_month\"] = np.log(df[\"reviews_per_month\"] + 1)\ndf[\"availability_365\"] = np.log(df[\"availability_365\"] + 1)", "_____no_output_____" ], [ "df[\"price\"] = np.log(df[\"price\"])\ndf[\"minimum_nights\"] = np.log(df[\"minimum_nights\"])\ndf[\"calculated_host_listings_count\"] = np.log(df[\"calculated_host_listings_count\"])\ndf[\"appearances\"] = np.log(df[\"appearances\"])", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ] ], [ [ "### Extreme outliers\n* Most outliers are clearly mistyped values (one can check these rooms ids in their website)\n* Remove extreme outliers first from large deviations within the same `id` (eliminate rate jumps of same room)\n* Then remove those from same scraping `date`, `neighbourhood` and `room_type`", "_____no_output_____" ] ], [ [ "df = df.reset_index()", "_____no_output_____" ], [ "q25 = df.groupby([\"id\"])[\"price\"].quantile(0.25)\nq75 = df.groupby([\"id\"])[\"price\"].quantile(0.75)\n\next = q75 + 3 * (q75 - q25)\next = ext[(q75 - q25) > 0.]", "_____no_output_____" ], [ "affected_rows = []\nmultiple_id = df[df[\"id\"].isin(ext.index)]\nfor row in tqdm.tqdm(multiple_id.itertuples(), total=len(multiple_id)):\n if row.price >= ext.loc[row.id]:\n affected_rows.append(row.Index)", "100%|██████████| 1023406/1023406 [00:14<00:00, 70302.71it/s]\n" ], [ "df = df.drop(affected_rows)\nprint(f\"Removed values {len(affected_rows)}, {len(affected_rows)*100/total_records}%\")", "Removed values 21078, 2.0118527313874033%\n" ], [ "# Remove extreme outliers per neighbourhood, room_type and scraping date\nq25 = df.groupby([\"date\", \"neighbourhood\", \"room_type\"])[\"price\"].quantile(0.25)\nq75 = df.groupby([\"date\", \"neighbourhood\", \"room_type\"])[\"price\"].quantile(0.75)\next = q75 + 3 * (q75 - q25)\next", "_____no_output_____" ], [ "affected_rows = []\nfor row in tqdm.tqdm(df.itertuples(), total=len(df)):\n if row.price >= ext.loc[(row.date, row.neighbourhood, row.room_type)]:\n affected_rows.append(row.Index)", "100%|██████████| 1015800/1015800 [01:30<00:00, 11223.94it/s]\n" ], [ "df = df.drop(affected_rows)\nprint(f\"Removed values {len(affected_rows)}, {len(affected_rows)*100/total_records}%\")", "Removed values 3528, 0.3367405084132631%\n" ], [ "df.describe()", "_____no_output_____" ], [ "df[\"price\"].hist()", "_____no_output_____" ], [ "df.to_pickle(\"treated_data.pkl\")", "_____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", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01c1091d8e8d7a085357003c5ec50bd34b206b1
59,548
ipynb
Jupyter Notebook
lecture-04/lab.ipynb
LuxTheDude/modern-ai-course
1cff6515f53354a0c2a6ae783ec116bfc3e06b74
[ "MIT" ]
null
null
null
lecture-04/lab.ipynb
LuxTheDude/modern-ai-course
1cff6515f53354a0c2a6ae783ec116bfc3e06b74
[ "MIT" ]
null
null
null
lecture-04/lab.ipynb
LuxTheDude/modern-ai-course
1cff6515f53354a0c2a6ae783ec116bfc3e06b74
[ "MIT" ]
null
null
null
72.09201
35,020
0.757758
[ [ [ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/real-itu/modern-ai-course/blob/master/lecture-04/lab.ipynb)", "_____no_output_____" ], [ "# Lab 4 - Math\n\n", "_____no_output_____" ], [ "### Stats\n\nYou're given the following dataset:\n\n", "_____no_output_____" ] ], [ [ "import random\r\nrandom.seed(0)\r\nx = [random.gauss(0, 1)**2 for _ in range(20)]\r\nprint(x)", "[0.8868279034128675, 1.9504304025306558, 0.46201173092655257, 0.13727289350107572, 1.0329650747173147, 0.00520129768651921, 0.032111381051647944, 0.6907259056240523, 1.713578821550704, 0.037592456206679545, 0.9865449735727571, 0.418585230265908, 0.11133432341026718, 2.7082355435792898, 0.3123577703699347, 0.26435707416151544, 5.779789763931721, 2.344213906200638, 0.6343578347545124, 4.014607380283022]\n" ] ], [ [ "> Compute the min, max, mean, median, standard deviation and variance of x\n", "_____no_output_____" ] ], [ [ "# Your code here\r\nimport math\r\n# min\r\nmi = min(x)\r\nprint(\"min: \" + str(mi))\r\n\r\n#max\r\nma = max(x)\r\nprint(\"max: \" + str(ma))\r\n\r\n#mean\r\nmean = sum(x)/len(x)\r\nprint(\"mean: \" + str(mean))\r\n\r\n#median \r\nmedian = sorted(x)[int(len(x)/2)]\r\nprint(\"median: \" + str(median))\r\n\r\n#stddv\r\n#variance\r\nlars = 0\r\nfor v in x:\r\n lars += math.pow(v - mean, 2)\r\nvariance = lars / len(x)\r\nstddv = math.sqrt(variance)\r\nprint(\"standard deviation: \" + str(stddv))\r\nprint(\"variance: \" + str(variance))", "min: 0.00520129768651921\nmax: 5.779789763931721\nmean: 1.2261550833868817\nmedian: 0.6907259056240523\nstandard deviation: 1.4717408201314568\nvariance: 2.166021041641213\n" ] ], [ [ "### Vectors\n\nYou're given the two 3 dimensional vectors a and b below.", "_____no_output_____" ] ], [ [ "a = [1, 3, 5]\r\nb = [2, 9, 13]", "_____no_output_____" ] ], [ [ "> Compute\n 1. $a + b$\n 2. $2a-3b$\n 3. $ab$ - the inner product\n\n", "_____no_output_____" ] ], [ [ "# Your code here\r\nfirst = list(map(lambda t: t[0]+t[1], list(zip(a,b))))\r\nprint(first)\r\n\r\nsecond = list(map(lambda t: t[0] - t[1], list(zip(list(map(lambda x: x*2, a)), list(map(lambda x: x*3, b))))))\r\nprint(second)\r\n\r\nthird = sum(list(map(lambda t: t[0] * t[1], list(zip(a,b)))))\r\nprint(third)", "[3, 12, 18]\n[-4, -21, -29]\n94\n" ] ], [ [ "### Gradients", "_____no_output_____" ], [ "Given the function $f(x,y) = 3x^2 + 6y$\r\n\r\n> Compute the partial gradients $\\frac{df}{dx}$ and $\\frac{df}{dy}$", "_____no_output_____" ], [ "Your answer here\r\n\r\n$\\frac{df}{dx} = 6x$\r\n\r\n\r\n$\\frac{df}{dy} = 6$", "_____no_output_____" ], [ "The function above corresponds to the following computational graph", "_____no_output_____" ], [ "![sol (1).png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAqkAAAG5CAYAAACtGK3BAAAAAXNSR0IArs4c6QAABPB0RVh0bXhmaWxlACUzQ214ZmlsZSUyMGhvc3QlM0QlMjJhcHAuZGlhZ3JhbXMubmV0JTIyJTIwbW9kaWZpZWQlM0QlMjIyMDIxLTA5LTA2VDA2JTNBNTMlM0EzNC4zNjlaJTIyJTIwYWdlbnQlM0QlMjI1LjAlMjAoTWFjaW50b3NoJTNCJTIwSW50ZWwlMjBNYWMlMjBPUyUyMFglMjAxMF8xNV83KSUyMEFwcGxlV2ViS2l0JTJGNTM3LjM2JTIwKEtIVE1MJTJDJTIwbGlrZSUyMEdlY2tvKSUyMENocm9tZSUyRjkyLjAuNDUxNS4xNTklMjBTYWZhcmklMkY1MzcuMzYlMjIlMjB2ZXJzaW9uJTNEJTIyMTUuMC4zJTIyJTIwZXRhZyUzRCUyMnF3ZXRIbU15OTBRbE84bFNpQlg0JTIyJTIwdHlwZSUzRCUyMmRldmljZSUyMiUzRSUzQ2RpYWdyYW0lMjBpZCUzRCUyMjZCdm8xaC1aLVVDY3c1QlY4ZHNHJTIyJTNFN1poTGo1c3dFTWMlMkZEZGNLYkI3SmRiTnBlMmhQT1hUMzZBVUhxQnlNSEJPZ243NEdqd1BFaTFUMUVhaVVFOHpmRHp3enZ6RVlCJTJCOU96U2RCeXV3clR5aHprSnMwRG41MkVQSjhGS3BMcDdSYWlYeGZDNm5JRSUyQmcwQ0lmOEJ3WFJCYlhLRTNxZWRKU2NNNW1YVXpIbVJVRmpPZEdJRUx5ZWRqdHlObjFxU1ZKcUNZZVlNRnY5bGljeTAlMkJvR1JZUCUyQm1lWnBacDdzaFZ2ZGNpS21NMHh4emtqQ2F5MzF6dUc5ZzNlQ2M2bnZUczJPc2k1NEppNDZBaDluV3E4TEU3U1F2eklBd1RKa2EzeWppWElWVEM1a3hsTmVFTFlmMUNmQnF5S2gzUVN1c29ZJTJCWHpndmxlZ3A4VHVWc29XOGtVcHlKV1h5eEtDVk5ybDhHZDIlMkZkbE45Q01CNmJtRG0zbWlOVVVqUnZveU4wYWpPSEliMWxobW4lMkZldWNtc2FkVnlJR0NRTkJSS1FVZ2hiWmNmU3UyVkZZVTM2aTZpbXFpNkNNeVB3eW5aMEFYJTJCbTEzNUFDZFFOWmVEOGpzSm9MWVJWTTJ0ZzVZa3loM3VXaXpuSkpEeVhwZmFsVnRVMGpUYzZsNXYlMkJZTjEzR0lCd1hLaVJ0WnBHWmNkVU1BS1JjS0Y3a2dsMlBTZ0drYkZRRlJ2dVQ0UGdQWEZGZzQlMkJxRnklMkZFYVdMdzZYWnI4VmwlMkZXelM1RzkyTTNmTEJyOXRVeHU5dmwwSTFtMENYS2FKeGdqOWFJTUY1dyUyQjkwOEVEYThUclpmZHptR3R6TU12eWtEa3pVQ0hDd0lzTW1VRmE2akVudmJmWFBRVTd6R3VFVkx4czJ6WTdIMnloJTJCSyUyRlhWUzY3OWQlMkJSNWExZHZMTE1kaUdhJTJCUjN0dlgxdWFPOE9MJTJGSFY3dkw4RHJ2JTJGUGVXdkRZWU5aajBSdXVrZDdiYzRQdjN4SGY0SUh2RmRXMWZIYVo5Vmo0eHNvSVYzbjJ2ZDJCJTJGJTJCSFpWNW5ETDh5JTJCYmZRakdPOSUyRkFnJTNEJTNEJTNDJTJGZGlhZ3JhbSUzRSUzQyUyRm14ZmlsZSUzRVBNg+QAACAASURBVHhe7Z0JfFXVtf9XjENLSQELAVuDfQgKaQEZ0iizQgsGHHgVY0FUJkGkRaKgWCxQkVmwPBA0DJWhGmlLS0tMW5Q+Q2QIU7AyCfYZsE8CKuD/UbUM/8/a9mKIIffcm3PvPfuc7/58/KTac/ZZ+7v2uvt39tl77aSzZ8+eFQoEIOBJAlu2bJGSkhLZvXu3HDhwQA4dOiRlZWVy7NgxOXnypJw+fVqSk5OlRo0aUrt2bUlNTZUrr7xSrr76amnWrJm0bNlS2rZt68m2YRQEIAABCECgKgJJiFQ6CAS8Q2D79u1SUFAgr776qqxfv16aNm0qrVq1MoKzcePGkpaWJvXr1zeCVIWpClQVqipYVbgePnxYDh48KPv375ddu3bJjh07ZM+ePdKxY0e56aabpEePHqY+CgQgAAEIQMDrBBCpXvcQ9vmewNtvvy0rVqyQlStXyqlTpyQrK0u6desmnTp1kpSUlGq3/8SJE1JYWChr166V/Px8ufjii6VPnz7Sr18/adKkSbXrpwIIQAACEIBALAggUmNBlToh4IDAn/70J1mwYIERkP3795fs7Gy5/vrrHdxZvUs2btwoeXl5smzZMjPDOmzYMOnevXv1KuVuCEAAAhCAgMsEEKkuA6U6CIQjoLOZM2bMMJ/nhw8fLkOGDAl3S8z+/9zcXJk3b57UqVNHRo8ebWZxKRCAAAQgAAEvEECkesEL2BAIAjt37pTx48ebDVCPPvqo+dzulbJ8+XKZNm2aWfc6ceJEadGihVdMww4IQAACEAgoAURqQB1Ps+NLYMKECTJ9+nSZNGmS5OTkxPfhETxt1qxZMm7cOCOiVVBTIAABCEAAAokigEhNFHmeGwgCult/xIgRJi2UfuJv2LCh59tdWlpqPv1ruqu5c+eSDcDzHsNACEAAAv4kgEj1p19plQcILFq0SAYPHizz5883m5NsK2r3gw8+KLpuddCgQbaZj70QgAAEIGA5AUSq5Q7EfG8S0M/lukFqyZIlVifTLy4uloEDB5oNVbpmlQIBCEAAAhCIFwFEarxI85zAELjnnnvMzn3NfepGntNEg9M8q7rJSzMALF26NNHm8HwIQAACEAgIAURqQBxNM+NDoHfv3uY0KJ1B9Vu577775Pjx47Jq1Sq/NY32QAACEICABwkgUj3oFEyyk4AK1NTUVHnuuefsbIADq4cOHSplZWUIVQesuAQCEIAABKpHAJFaPX7cDQFDQE+M0uNG/TiDWtHFOqN65swZPv3T9yEAAQhAIKYEEKkxxUvlQSCgm6R2794tq1evDkJzTRtvueUWSU9PZzNVYDxOQyEAAQjEnwAiNf7MeaKPCCxcuFDmzJkjRUVFvtgk5dQ1upmqffv28tBDD5Geyik0roMABCAAgYgIIFIjwsXFEPiCwLZt26RNmzaiaZratm0bODTa7szMTNm6dSsJ/wPnfRoMAQhAIPYEEKmxZ8wTfEqgXbt2oummbEzU75ZLNOH/8uXLzUwyBQIQgAAEIOAmAUSqmzSpKzAEJkyYYNah5uXlBabNF2podna2WZ86fvz4wLMAAAQgAAEIuEcAkeoeS2oKCIGSkhLRWdQ9e/ZIWlpaQFp94WaWlpZK06ZNZePGjdKiRYvA8wAABCAAAQi4QwCR6g5HagkQgdtvv106deokOTk5AWp11U2dNWuWFBYWkj+VHgEBCEAAAq4RQKS6hpKKgkBgzZo1MnbsWNm5c2cQmhtRG5s3b25SUmVlZUV0HxdDAAIQgAAEKiOASKVfQCACAjfeeKMMHjzYnGVPOZ+AbqBatGiRrFu3DjQQgAAEIACBahNApFYbIRUEhUBBQYGZRd2+fXtQmhxxO6+77jozm9q9e/eI7+UGCEAAAhCAQHkCiFT6AwQcEtC1qL169TIzqZTKCeTm5kp+fj5rU+kgEIAABCBQbQKI1GojpIIgENi3b585YenIkSNBaG612li3bl3ZsGGDNGnSpFr1cDMEIAABCASbACI12P6n9Q4JaF5UPQpUd7FTqiYwatQoqVWrligzCgQgAAEIQCBaAojUaMlxX6AIaLL6JUuWmGNAKVUT0HypgwYNkrfeegtUEIAABCAAgagJIFKjRseNQSGwbds26du3r0neT3FG4Nprr5WXXnpJWrVq5ewGroIABCAAAQhUIIBIpUtAIAyByZMny9GjR/nUH0FP0U/+qampJhsCBQIQgAAEIBANAURqNNS4J1AEunbtKg8//DBJ6iPwuh56MHv2bFm7dm0Ed3EpBCAAAQhA4AsCiFR6AwTCELjsssvMTGpKSgqsHBLQTWY6k/rJJ584vIPLIAABCEAAAucTQKTSIyBQBYHi4mK5//77SeAfRS/RxP4LFy6Utm3bRnE3t0AAAhCAQNAJIFKD3gNof5UEVGQVFRWZnf2UyAgMGDBAOnToYHb6UyAAAQhAAAKREkCkRkqM6wNFQNeiNmjQQEaPHh2odrvR2OnTp0tZWZnMnDnTjeqoAwIQgAAEAkYAkRowh9PcyAjoUaj33nuv9O7dO7IbY3j1mTNn5Prrr5e///3vZt3nE088IXfeeadcdNFFMXxq5FX/9re/lWXLlnFEauTouAMCEIAABEQEkUo3gEAVBHQ95YIFCzyzrvLs2bMm00BSUpLoTOX69eulS5cu8uyzz8qwYcPMf/dK0fW8w4cPF/1LgQAEIAABCERKAJEaKTGuDxSBhg0bmjWpaWlpnmi3ilQ99UqFn/5vnVVt3ry5mVF97bXXPCVSS0tLpWPHjvLuu+96gh1GQAACEICAXQQQqXb5C2vjTODrX/+6vPfee55KP7V7927RtFiNGjWSnTt3SsuWLeWFF16Qu+++21Of/DUNlYr748ePx9lrPA4CEIAABPxAAJHqBy/ShpgRuPjii+XTTz+V5OTkmD0jmop11nTr1q2yaNEimTdvnvnk7zUbT506JV/96lflX//6VzRN5B4IQAACEAg4AURqwDsAza+agK7x1M/qXivr1q2Tzz77TA4cOCDz58+X3NxcswzAS2tSlZvXhLPX/Ig9sSXQuXNn0VihQAACdhJApNrpN6yOEwGvzqSGmq9C8Ec/+pG8/PLLJt1T3bp140Qm/GNCM6kqpikQiDeB0EuSF18y482C50HAVgKIVFs9h91xIeC1NamnT5+WO+64Q/Q0p/HjxxsG+vfnP/+52Th14403xoWLk4ewJtUJJa6JFQEVp5qWDZEaK8LUC4HYE0Ckxp4xT7CYgNd29//f//2f1KxZ0wjTCRMmmN39miNV16eWlJSIimqvFHb3e8UTwbQDkRpMv9NqfxFApPrLn7TGZQJey5OqolSPGf3lL38p9913n7z55ptmY9fEiRNFDx7wUkJ/8qS63BmpLiICiNSIcHExBDxJAJHqSbdglFcIePHEKR18db3n888/L1dddZVkZWV5SpyGfMeJU17pxcG0A5EaTL/Tan8RQKT6y5+0xmUCerrTFVdcIY888ojLNfu/uhkzZsjhw4dl5syZ/m8sLfQcAUSq51yCQRCImAAiNWJk3BAkAgsXLpQ33nhDFi9eHKRmu9LWAQMGSIcOHczyBAoE4k0AkRpv4jwPAu4TQKS6z5QafURA11Xef//9sn37dh+1Kj5N0QwEKvJ1XS8FAvEmgEiNN3GeBwH3CSBS3WdKjT4joEeQfvDBB2ZXPcUZgY8//ljq1asnn3zyibMbuAoCLhNApLoMlOogkAACiNQEQOeRdhHo2rWr6NpU3aBEcUZgzZo1Mnv2bFm7dq2zG7gKAi4TQKS6DJTqIJAAAojUBEDnkXYRmDx5shw9elRmzZpll+EJtHbUqFGSmpoqY8eOTaAVPDrIBBCpQfY+bfcLAUSqXzxJO2JGYNu2bdK3b1/Zs2dPzJ7ht4qvvfZaeemll6RVq1Z+axrtsYQAItUSR2EmBKoggEile0DAAYH09HRZsmSJZGZmOrg62Jds3LjR7Oh/6623gg2C1ieUACI1ofh5OARcIYBIdQUjlfidgB5DqpuB+OQf3tP6qb9WrVrm2FYKBBJFAJGaKPI8FwLuEUCkuseSmnxMYN++fdK+fXs5cuSIj1vpTtPq1q0rGzZskCZNmrhTIbVAIAoCiNQooHELBDxGAJHqMYdgjncJ6BGpvXr1ksGDB3vXyARblpubK/n5+bJq1aoEW8Ljg04AkRr0HkD7/UAAkeoHL9KGuBAoKCiQxx9/XHQjFaVyArpRaurUqdK9e3cQQSChBBCpCcXPwyHgCgFEqisYqSQoBLp06WJOoNLd/pTzCaxYscKcMLVu3TrQQCDhBBCpCXcBBkCg2gQQqdVGSAVBIqBJ6jX3586dO4PUbEdtbdGihZlF5dADR7i4KMYEEKkxBkz1EIgDAURqHCDzCH8R0LWpnTt3Ft3FTvmcgGY9KCwsZC0qHcIzBBCpnnEFhkAgagKI1KjRcWNQCZSUlEi7du1Mcv+0tLSgYjjX7tLSUmnatKloflSdTaVAwAsEEKle8AI2QKB6BBCp1ePH3QEloHlT9+7da05VCnrJzs6WZs2akRc16B3BY+1HpHrMIZgDgSgIIFKjgMYtEFACOpt67733ytChQwMLZMGCBbJs2TIpKioKLAMa7k0CiFRv+gWrIBAJAURqJLS4FgLlCGgqqjZt2khxcbG0bds2cGy2bNkiGRkZJiWXpp6iQMBLBBCpXvIGtkAgOgKI1Oi4cRcEDAFNuTRnzhx54403pGbNmoGhokfE6kzyyJEjOdwgMF63q6GIVLv8hbUQqIwAIpV+AYFqEhgzZozZRLV69epq1mTP7bfeeqtZhzpt2jR7jMbSQBFApAbK3TTWpwQQqT51LM2KL4H+/fvLJZdcIosXL47vgxPwtAEDBsjp06dl6dKlCXg6j4SAMwKIVGecuAoCXiaASPWyd7DNKgKaP7VBgwaim4n8WnSTWFlZGflQ/epgH7ULkeojZ9KUwBJApAbW9TQ8FgRUqF5++eW+nFHVGdRjx44hUGPRcajTdQKIVNeRUiEE4k4AkRp35DzQ7wT00//x48dFz7JPSUmxvrm6Sapfv35Sq1Ytk26KAgEbCCBSbfASNkKgagKIVHoIBGJAQDdTFRQUmBlVm9NTaZqpgQMHys0338wmqRj0E6qMHQFEauzYUjME4kUAkRov0jwncAQ0PdWQIUNk/vz5MmzYMOvar2trH3jgAcnNzSXNlHXew2BEKn0AAvYTQKTa70Na4GECmuh+xIgR0rBhQ5kxY4akpaV52NrPTTt48KCMHj1aSktLZe7cudK6dWvP24yBEKhIAJFKn4CA/QQQqfb7kBZYQGD8+PEyc+ZMmTRpkowaNcqzFs+aNUueeOIJI1InTJjgWTsxDALhCCBSwxHi/4eA9wkgUr3vIyz0CYGSkhJRsfrOO+/IY489Jn379vVMy3STlybmb9SokUycOFFatmzpGdswBALREECkRkONeyDgLQKIVG/5A2sCQGDNmjXm0/+JEydk+PDhCV3vqetm582bZ3bu6+xpz549A+ABmhgEAojUIHiZNvqdACLV7x6mfZ4loLv/dXNSUVGRaNqq7OxsyczMjLm9mzZtkry8PJNOqn379mZTV48ePWL+XB4AgXgSQKTGkzbPgkBsCCBSY8OVWiHgmMC+fftMTtWVK1fKmTNnJCsrS7p16yadOnWSmjVrOq7nQhdqntPCwkJZu3at5Ofny0UXXSR9+vQxuU+vueaaatdPBRDwIgFEqhe9gk0QiIwAIjUyXlwNgZgS0GwAOsP66quvyvr16yU9PV1atWolzZo1k8aNG5vsAPXr15fatWtLjRo1JDk5WU6fPi0nT540p0EdPnzY7M7fv3+/7Nq1S3bs2GH+dujQQbp27WpmTNmtH1MXUrlHCCBSPeIIzIBANQggUqsBj1shEGsCxcXFohuudu/eLQcOHJBDhw5JWVmZEaQqTFWgqlBVwarCNTU1Va688kq5+uqrjbDVDVAZGRmxNpP6IeA5AohUz7kEgyAQMQFEasTIuAECEIAABLxOAJHqdQ9hHwTCE0CkhmfEFRCAAAQgYBkBRKplDsNcCFRCAJFKt4AABCAAAd8RQKT6zqU0KIAEEKkBdDpNhgAEIOB3AohUv3uY9gWBACI1CF6mjRCAAAQCRgCRGjCH01xfEkCk+tKtNAoCEIBAsAkgUoPtf1rvDwKIVH/4kVZAAAIQgEA5AohUugME7CeASLXfh7QAAhCAAAQqEECk0iUgYD8BRKr9PqQFEIAABCCASKUPQMB3BBCpvnMpDYIABCAAAWZS6QMQsJ8AItV+H9ICCEAAAhBgJpU+AAHfEUCk+s6lNAgCEIAABJhJpQ9AwH4CiFT7fUgLIAABCECAmVT6AAR8RwCR6juX0iAIQAACEGAmlT4AAfsJIFLt9yEtgAAEIAABZlLpAxDwHQFEqu9cSoMgAAEIQICZVPoABOwngEi134e0AAIQgAAEmEmlD0DAdwQQqb5zKQ2CAAQgAAFmUukDELCfACLVfh/SAghAAAIQYCaVPgAB3xFApPrOpTQIAhCAAASYSaUPQMB+AohU+31ICyAAAQhAgJlU+gAEfEcAkeo7l9IgCEAAAhBgJpU+AAH7CSBS7fchLYAABCAAAWZS6QMQ8B0BRKrvXEqDIAABCECAmVT6AATsJ4BItd+HtAACEIAABJhJpQ9AwHcEEKm+cykNggAEIAABZlLpAxCwnwAi1X4f0gIIQAACEGAmlT4AAd8RQKT6zqU0CAIQgAAEmEmlD0DAfgKIVPt9SAsgAAEIQICZVPoABHxHAJHqO5fSIAhAAAIQYCaVPgAB+wkgUu33IS2AAAQgAAFmUukDEPAdAUSq71xKgyAAAQgEk8DTTz8t48aNk2nTpsmPf/xjueiii0RnVH/xi1/IY489JpMnT5ZRo0YFEw6thoCFBBCpFjoNkyEAAQhA4MsETpw4IXXr1pWLL75YatSoIR988IF84xvfkJMnT8rp06fl6NGjkpKSAjoIQMASAohUSxyFmRCAAAQgEJ6AzpjOnj1bPvvss3MXX3rppZKTkyNTpkwJXwFXQAACniGASPWMKzAEAhCAAASqS0BnU1NTU+XTTz89V9Vll10mR44cYRa1unC5HwJxJoBIjTNwHgcBCEAAArElUH42lVnU2LKmdgjEkgAiNZZ0qRsCEIAABOJOoPxsKrOoccfPAyHgGgFEqmsoqQgCEIAABLxCQGdTZ82aJQ8//DBrUb3iFOyAQIQEEKkRAuNyCEAAAhDwPgGdTR0wYID88pe/ZC2q992FhRColEDCRWpxcbGUlJTI7t275cCBA3Lo0CEpKyuTY8eOnUsbkpycbNKJ1K5d2yyIT0tLk0aNGkmzZs2kZcuWkpGRgXsh4EsCxIcv3UqjXCJAfLgEkmp8ScAP8RF3kbpt2zYpKCiQ1157TQoLCyU9PV2uu+4687dx48ZGgNavX98IUhWmKlA1v53muVPhevjwYTl48KDs379fdu3aJTt27DACt0OHDnLTTTdJjx49pHXr1r7scDTK/wSID//7mBZGT4D4iJ4dd/qfgB/jIy4i9e2335YVK1bIyy+/bARnVlaWdOvWTTp16uTKZ5iPP/5YXn/9dVm7dq3k5+ebRM59+vSRfv36SZMmTfzfM2mh1QSID6vdh/ExJkB8xBgw1VtNwO/xEVORqjOmCxYskPXr10v//v3lrrvukszMzJh3iI0bN0peXp4sW7ZMOnbsKMOGDZPu3bvH/Lk8AAKRECA+IqHFtUEjQHwEzeO0NxICQYmPmIjUNWvWyMyZM83n+eHDh8uQIUMiYe/qtbm5ufLss8+a5QOPPPKI9OzZ09X6qQwCkRIgPiIlxvVBIkB8BMnbtDVSAkGLD1dFqm6AGj9+vLzzzjvy6KOPms/tXim63GDq1Klm3evEiROlRYsWXjENOwJCgPgIiKNpZlQEiI+osHFTQAgENT5cE6kTJkyQGTNmyJNPPmnOSPZq0bx548aNkzFjxojaTIFAPAgQH/GgzDNsJUB82Oo57I4HgSDHR7VFqu4mGzFihDRs2NCIVN2d7/VSWloqo0ePNumu5s6dK61atfK6ydhnKQHiw1LHYXZcCBAfccHMQywlQHyIVEukLly40Kw3nT9/vtmcZFvRTV0PPPCA6LrVwYMH22Y+9nqcgF/iQ9sxaNAgj9PGPNsI+CU+GD9s63l22OuX+Kju+BG1SNXP5bq7bPHixdK2bVs7vF6JlZrsduDAgSYt1rRp06xtB4Z7iwDx4S1/YI23CBAf3vIH1niLAPHxhT+iEqmaTur48eMm92lKSoq3vBuFNXp8nm7yqlOnjixdujSKGrgFAl8QID7oDRC4MAHig94BAeLDaR+IWKTefvvtRswtWbLE6TOsuU7Peda0WatWrbLGZgz1FgHiw1v+wBpvESA+vOUPrPEWAeLjy/6ISKQqwAYNGpgE/X4tQ4cOlbKyMoSqXx0cw3b17t1bUlNT5bnnnovhUxJbNfGRWP42P534sNl72B5rAuirygk7Fqn6iUaPG/XjDGpFNDqjqse38uk/1mHpn/qJD//4kpa4T4D4cJ8pNfqHAPFxYV86Eqm6iHfPnj2yevVq//SKMC255ZZbJD09nc1UgfF49A0lPqJnx53+J0B8+N/HtDB6AsRH1ezCilRNHzBnzhwpKiryxSYpp11JN1O1b99eRo4cSXoqp9ACeF3Q4+Ohhx4iPVUA+73TJgc9Phg/nPaUYF4X9PhwMn5UKVI1kWybNm1E0zTZnGYq2u6v7f7e974nyoGE/9FS9O99xEexZGZmytatW4kP/3bzqFtGfDB+RN15AnAj8eFs/KhSpLZr107uueceKxP1u9XHdZPYsmXLzEwyBQLlCRAfYg7yWL58OfFBaHyJAPEhZpMx4wfBURkB4sPZ+HFBkapnxe7evVvy8vIC38Oys7OlWbNmokwoEFACxMcX/UDjQ9dvjx8/ns4BAUOA+Dg/Phg/CIzyBPS3cu/evfLSSy8FHky48aNSkVpSUiI33HCDgZiWlhZ4iKWlpdK0aVPZuHGjtGjRIvA8gg5A40PfgnUzIfEhQnwEPSLObz/xcT4P4oP4KE+A+IgsPioVqZrPrmPHjpKTk0Pv+jeBWbNmSWFhIflT6RGi+ew6depEfJTrC8QHgREiQHx8uS8QH8RH+fjo3LmzjBo1CigO9NWXROqaNWtk7NixsnPnTgBWINC8eXOZOnWq9OzZEzYBJUB8XNjxGh/Tpk2TrKysgPYOmk18VB0fjB/BjhHiI/Lx40si9cYbbzQpl/Qse8r5BFasWCGaMmLdunWgCSgB4uPCjtcNVIsWLSI+Ahob2mzi48LOZ/wIcGD8u+ldunSRIUOGoK8q6QoXGj/OE6kFBQVmFnX79u30pgsQ0FRU+jbcvXt3GAWMAPER3uHXXXedmU0lPsKz8tsVxEd4jzJ+hGfk1ys0Ph5//HGT0pJSOYHKxo/zRKquJerVqxfJ66voQbm5uZKfn8/a1ABGGfER3unER3hGfr2C+AjvWeIjPCO/XkF8hPdsZfFxTqTu27fPnLB05MiR8DUF/Iq6devKhg0bpEmTJgEnEZzmEx/OfU18OGfllyuJD+eeJD6cs/LLlcSHc09WjI9zIlXz2ulRoLoLkVI1Ad2VV6tWLfKmBqijEB/OnU18OGfllyuJD+eeJD6cs/LLlZoX9eOPP0ZfOXBoxfg4J1I1GfeSJUvMMYeUqglovtRBgwbJW2+9BaqAECA+nDua+HDOyi9XEh/OPUl8OGfllyuJD+eerBgfRqTqQt6+ffua5OQUZwSuvfZaefHFF6V169bObuAqawkQH5G7TuNDT1PRjSIUfxMgPiL3L+NH5MxsvWPr1q1mNz/6yrkHy48fRqROnjxZjh49ylS0c4YmEW+9evXMbj2KvwkQH5H7V+MjNTXVZAuh+JsA8RG5fxk/Imdm6x1PPfWUfPDBB+irCBxYfvwwIrVbt25GdJGk3jlFTco7e/ZsWbt2rfObuNJKAl27dpWHH36YJPUReI/4iACW5ZcSH5E7kPiInJmtdxAfkXtO4+OZZ56Rv/zlL2JE6mWXXWZmUlNSUiKvLaB36CJonUn95JNPAkogOM0mPiL3tW7C1JlU4iNydrbdQXxE7jHGj8iZ2XjH2bNn5Stf+YqZSa1Zs6aNTUiIzeXHj6TNmzefvf/++0ngH4UrdL3d888/LxkZGVHczS02ECguLhY/x8eZM2eMGy666CLX3aGJmfWEtrZt27peNxV6g4Df4yOWlBk/YknXG3Vv3rxZhg0bRgL/KNwRGj+ScnNzzxYVFZmd/ZTICAwYMMDkltVjZCn+JKAiy6/xoUdY/vWvfzUCdefOnfKd73zHVSdqfHTo0MFkwqD4k4Cf4yPWHmP8iDXhxNevyek1p/rixYujMkYnEfS3+etf/7o0atQoqjoudJPO8mr9SUlJMZmkqK6x9913n3Ts2FGScnJyzjZo0EBGjx5d3ToDd/+MGTPk/fffl6effjpwbQ9Kg3Utqh/j4/Tp00ZAvvHGG+YFddmyZfLqq6+6+mM1ffp0KSsrk5kzZwaluwSunbGIDx04dQDVlycdQGNd9FnxeE7FdjB+xNqzia8/JydHvvnNb8ojjzwSsTHaL5OTk2X48OGiM7IqdvXf3Sqa2/i//uu/5KOPPpJTp065+tvvho2h8SPptttuO3vvvfdK79693ag3UHWsWrVKli5dyhGpPva6HmXn1/jQHyn9Rz/Zfu973zv3Vu2WO3/7298a8atxQvEngVjER0gwPvHEE/Lzn/88JuBUCF966aVSv359uf766+WXv/xl3PdkMH7ExLWeqlTjQ2cE9W+kRU//1P75u9/9zkwk/OY3v3FdSP7sZz+TN998U/S32umLmqYWzM7Odnx9pO0OXR8aP5LatGlzdsGCBawbi4Lkli1bzHoT/Uuxk4DOguua0wttGtT1lH6P+uAgswAAIABJREFUD/3sr4v6//CHP7jqRBW/Ogugfyl2EkhEfKiA1Bkjzb8aqzy7OtD++te/NrmuNU2atvNf//qXXHzxxXFzFONH3FDH7EHh4qNNmzZm34r+jbRo/xwzZozs37/fCEKnItLpc3Sm9s477xT9/dffaadFha1ObsRiH0N5G0LjR1JaWppZk5qWlubURq77N4GDBw+aNamlpaUwsZTAV7/6VTODqJ9lNOdtRbHasGFDsybVr/Ghb8Qvv/yy6Od/t390NC50TdG7775rae/A7ETEh87s/OhHP5KSkhJXP2+W96Z+HdETA1Uo6svZrbfeagZePb4yXoXxI16kY/eccPGh44Z+pr/yyisdG7Fu3TrRWVSdSdTMGaoxrrnmGunSpYvjOpxcqL/5V199tUk/quPf3//+d9HxLlwZMWKEzJkzx/F4oePrQw89JNquvLw80dO3nJTQ+JGUkpJy9r333ov7p46qjNS3Bw3gFStWmLVJ+oOlM1r6371UNI3It771LdF0CRQ7CfziF7+Qxx577Nynbg1WnVkJiVVdsO61+HCLtK5D1/Wi+mOlP4S6PtXNt3WNC/2RPn78uFsmU0+cCSQiPnTmadOmTaL5JXU9uA7Obr9AaZ//n//5HzNI62yYrhnUE4H0pBstOu7ov7/wwgtmAP/nP/8pV111lav0GT9cxZmQysLFh44j//u//xtR+intl4sWLZLCwkLp1KmT/N///Z/ccsstXxKp2kcre6m65JJLpFatWmazlf6j/1tjqWLR/t2sWTNjm+4duPvuu2XSpEnmv1VVtC7NXxouJtU+fRHU00znzZtnxlH9q+1yUkLjR1JycvLZTz/9NGZvrE6MqXjN3r17pWnTpmYdhtqmg6n+tyuuuCKa6mJ2j/7Q6ZuOLjqm2EvgG9/4hnz44YemAbpOTYWavl3+9Kc/ldq1a5s+6OaCdX2z1GTFNWrUMJ9awgV7tGT1Oc8995z893//t0yZMkXq1Klj3oB1FkkHXP33Y8eOnas+tNMz2udVvE/jQmca9DMqxV4C8YwPHdh017u+MKkA0Fmof/zjH6K7pCu+QOlGv/Klsg1Qmqu3efPmlcLXGVv9pKovak8++aQRo1o0DvTZ+pvQq1cvs6RLfwdee+01V1/iGD/sjYnyllcVHyoQ9fcv0t947YM6+6pLzXSW/0JF1zXrmKXCVMeoymJA4+amm276UhX6cqaCUevQa/RFTcekiRMnntfPQ2kKQxXoxIN+HSvfpsqWI2jc6iSevujdc889Zm3uf/zHfzj+WhEaP3TrpObz91xvmTp1quhxe1pUfffv399zNqpBbs48ebKBATVKg15/HHSxupvx8c4775iUZTrw6eyMBrC+Leunxorlb3/7mxw+fDjsQKw/QBX7odqclZVl3pB1bY+mgdIfjSZNmsjJkydNSpSK7XK7L4d2p7rJL6Dd0XPNjlV86ID47W9/W371q1+Z7BOrV682L4v66b/iQF9dkarxpdlZ9IVRZ5x0rZ0O9MuXLzdHWOpSAI2JBx980PB/9tlnXfeD2zHnuoFUGBWBUHzoJ/uKIs9JhfqpW1MC6iSCmxMk5Z+tX6h1GYGKUrVRX8hUVOs67VDRJQAqLnXWX7MA6IubznDqMq7yRV8s9Z9Q0d98/fKt68qdzLpWxiQ0fnhyJlUN1oH0a1/7mnmbUId5MZh5E3YSbt6/pm7duuZEEC3lZ1J1jarONro1k6o/BD/4wQ/Mj4Gu0dH+oxs1NENEZS9hOoiqyCxfKntTruwtWQdY/cyyb98+k1pKjz7evn27eW7nzp3ND1OsCzOpsSYcn/rjFR/aGk21k5mZab5O6eCskxWaJkeXf0U6G+WUjg6kurFFv9jp83Tpi35e1fjXmNX264xrZXHm9BmVXcf4UR163rm3qvjQGfhoZlJ1n4DO5q9fv/6C2kfHgsomNypOCmjcVLxOr1G79ehRHXtUDOvSmkcfffRLY0PF+nQJgy7hqhiP5TWaxs1tt91mTuWMNkfsuZlUL65J1e6n8PTNVhW8/kD88Ic/9E6v/LclrCnynEsiNkh/CHQNqg4YGmQq4nRw0pkVLW6uSdV+3KdPH/OpRBeoq5D8/ve/b4SkBrPbJSRoVaTqj4/OqMbzZY81qW57NP71xTM+tHX6PP1ypsu7tOh6VB3o9ZNkxUFRx4dwRWejdHNg+aKxfscdd4ieaKNr+kIvi7r0Rmd9dDZJxbJu8Ni9e7f5qxMl+hVEX/DcKowfbpFMXD3h4iOaNanaGn1h+n//7/+Z2fsL/WaHkvE7aX3F2VgVkRpb+pVA40M//esGQl3SEu5lUD/hh3tp1Po1tvRYbM0HrCX0RU83T4Vb96rXn1uT6sXd/QcOHJDGjRubTz66uFfXZeiPxeWXX+7EH3G7ht2ZcUMdswfpmkkdpEK7+0PiNPRAN3f3T5s2zbxVal/WHwLdIKKfGkNrgir+GOnbtM6mhiv6I1PZaVH6I6b/qEDVt3l98dN/14FYZ3RjXdjdH2vCsa8/nvGhrVm7dq1Jh6MvbqG9CbpuTj/9Vywat+FKZafp6ACqQlTX4OlAGpq91c/8+gm0Xbt2JqOHDuz6gqdfJPSTZ0FBgVl24FZh/HCLZOLqCRcf0ezu1/6pL0xDhw41fS9WRZe06GEcGiMqpvVzfjiBqrZoTu2NGzeGvVbHNhW/+nXyz3/+sxl79IQ6pycQntvd78U8qTqA6qCqql6V+He/+13jNG2glwp57rzkjehs0SAaMmTIuZnTirW4mSdVczPqRqbQWjpN8KyzObqBQxOXt27d+rzHh07eCdeyytYs6Yud7hDVgfc///M/zcYpXWOrs1JHjx6NSz5I8qSG85z3//94xofSCOVI1ZlO/fKg+xI0+4abXwB0sNT40CUvKlI1i4xu6HjqqadMNgqdodW40aU4OqOl68f1nkOHDpmNIG4Vxg+3SCaunnDxEWme1NAXPU3ir/3D7YwSFUlpvOnLkk7GOI0xzSuu8eNE0Gr9OkOr46ievOX0GWrnuTypnDgVfQfXGTDd+KInQlD8ScDNE3X0M78uJdAfHk1LokGrA59uoFIB6yTonVLW2SFdyK7LCHSRu77sqUAeOXKkGZzdfNaFbOLEKafesvc6N+MjREEHNt2wqEu8YtVPQy+AW7duNWmndCYp9Cz9/1Qs6MufDqo6q6pZAnSTiZuF8cNNmt6sS9dl6u+wkxOnNF2TZqL44x//aP6ZO3duzPp/dWipnZV9uatOnZXde+7EqZycnLN+PJvcbWCV1cfZy/GgnNhn6OcQTX0WzdnLlVkeSvMUOps8tPMzFoNxqG4daN9++22TE7Kyz5+xIqzxodkJNMUPxZ8E3I4Pf1KqvFWMH/73ti4j08kIJ+OH/l7rpkFNGaibdXXTbpDL9OnTzcbhpNzcXHPilOYkpURGQN+QdCeophSi+JOALjHRnI3R7lD0JxVnrdL40LWETtcgOauVq7xEgPiI3huMH9Gzs+VOze+ruX4jGT8qy+BiS3vdtDM0fiRt3rz5rK4x0PQ0lMgI6LnSuvklIyMjshu52hoCui6G+IjOXbreVkWMrkei+JMA8RG9Xxk/omdny5267ErXNGuaM0pkBELjR5Jm8tdTkzRPpB6PRXFGQNOHaJ4xnZan+JsA8RG5fzU+dD2sroWl+JsA8RG5fxk/Imdm4x06K6rxoUnw0VfOPVh+/DAiVc9i1bVFekINxRkBTa8we/ZskzKF4m8CxEfk/iU+Imdm6x3ER+SeIz4iZ2brHcRH5J4rHx9GpGqaD01Lo3mzKM4I6NnuOlOku7Up/iZAfETuX40P3RGtByVQ/E2A+Ijcv4wfkTOz9Q5NbaZfqtFXzj1YfvwwIlXXS2jSWE2cT3FGQNOW6Bm3FXNbOrubq2wiQHxE7i2ND02rpevuKP4mQHxE7l/Gj8iZ2XqHpjnr168f+ioCB5YfP4xI1Xv16Dfd4a8pEChVE9i0aZPJfbZr1y5QBYQA8eHc0Xoaie7o13x6lGAQID6c+5nxwzkrv1ypx4BqTnU9rYlSNYGK48c5kaonb+hiVaakw3chnYrWY/UmTJgQ/mKu8AUB4sO5G4kP56z8ciXx4dyTxIdzVn65kvhw7smK8XFOpOpZyZrz88iRI85rC+iVuqtfc581adIkoASC12ziw7nPiQ/nrPxyJfHh3JPEh3NWfrmS+HDuyYrxcU6kahV6dFevXr1ITl8FT03OqzvPOArVeafzy5XER3hPanzk5+eLHvlICRYB4iO8vxk/wjPy6xV6ROott9yCvgqjryqOH+eJ1IKCArNbncSzF6aoG0GmTJkiPXr08Gss0a4LECA+wncNjY+pU6dK9+7dw1/MFb4iQHyEdyfjR3hGfr3ilVdekZ/+9KfoqyocXFl8nCdS9d4uXbqYE3Z0tz/lfAIrVqwwJ+isW7cONAElQHxc2PHER0CDolyziQ/igyi4MAHiI/L4+JJI1U/Zmttw586d9LUKBFq0aGFmUXv27AmbgBIgPi7seI0PnUXlUJCABoeIWQrF+FG5/xk/ghsXoZb/8Y9/NLOpJSUlwHCor74kUvU+XVvUuXNn0V1WlM8JaNaD119/nbWodAjio5I+oPFRWFjIWlTig/i4QHwwfhAc6KvK+0BV40elIlVVfrt27Uzy2bS0tMD3rIMHD0rTpk3ljTfekJYtWwaeR9ABEB/n94DS0lITH5rfTmeLKMEmQHyc73/Gj2DHQ8XW79ixw2RSQl99TkbjQ5P3X2j8qFSk6o2a12vv3r3m1Jigl7vuussMwuRFDXpP+KL9xMcXLLKzs0WTVRMfxEeIAPHxRV9g/CAuKhIgPpyPHxcUqVqFzqbee++9MnTo0MD2sgULFsjSpUvNLCoFAuUJEB8iGh/Lli2ToqIiOgcEziNAfHweH4wfBEZlBG644Qa57777Aq+vwo0fVYpUTUXVpk0bKS4ulrZt2waup23ZskUyMjJEz95t3bp14NpPg6smQHx8Hh/KQVOHUCBQngDxwfhBRFyYgOoK/f1UfaU6K2glpK/CjR9VilSFpimX5syZY2YSa9asGRiOekSsrhv5yU9+QvLdwHg98oYGOT50pmzkyJHER+TdJjB3BDk+GD8C082jbqge7jB37lzzJSpo+srp+BFWpCr9MWPGmEW+q1evjtoZtt146623mnWo06dPt8107I0zgaDGh65DnTZtWpxp8zjbCAQ1Phg/bOupibFX40P3//z+979PjAEJeKrqK6fjhyORqm3o37+/XHLJJbJ48eIENCm+jxwwYICcOnXKrLWjQMAJgaDFx+nTp81aOwoEnBAIWnwwfjjpFVwTInD33XfLpZdeGhh9Fcn44VikKkzNn9qgQQOzGNyvZdiwYfL++++TD9WvDo5hu4IQH7qJsqysjHyoMexHfq06CPHB+OHX3hv7dgUhPqIZPyISqSGhevnll/tS8esM6kcffYRAjX08+vYJ+kPj5/g4duwYAtW3vTf2DfN7fDB+xL4P+fkJfo+PaMaPiEVq6NP/8ePHRc/qTklJsb7P6Capfv36Sa1atfjEb703E98A/bRJfCTeD1jgTQLEhzf9glXeIEB8nO+HqESqVqGLfQsKCsyMqs3pqTQNwsCBA6VHjx5skvJGjPrCCr/Fx80338wmKV/0TG80wm/xwfjhjX7lFyv8Fh/VGT+iFqnaGTS9yJAhQ2T+/Pmia3FsK7q29oEHHhBNAzF48GDbzMdejxMgPjzuIMxLKAHiI6H4ebjHCRAfnzuoWiJVK9BErCNGjJCGDRvKjBkzJC0tzeOu//ys2NGjR4ueOa45ykjU73mXWWsg8WGt6zA8DgSIjzhA5hHWEiA+XBCpIe/rWbQzZ86USZMmyahRozzbKWbPni3jxo0zIpWzxj3rJt8ZZkt8zJo1S5544gniw3c90NsNsiU+GD+83Y/8ap0t8RGL8aPaM6nlO0VJSYkozHfeeUcee+wx6du3r2f6jG7y0sTjjRo1kokTJ0rLli09YxuGBIMA8REMP9PK6AgQH9Fx465gEAhqfLgqUkNdZc2aNebT/4kTJ2T48OEJXe+p6zrmzZtndu7r7GnPnj2D0aNppWcJEB+edQ2GeYAA8eEBJ2CCZwkELT5iIlJD3tXd/7o5Sc+l1bQK2dnZkpmZGXPnb9q0SfLy8kw6KT0/WTd16e5LCgS8RID48JI3sMVrBIgPr3kEe7xEICjxEVORGnLovn37TE7VlStXypkzZyQrK0u6desmnTp1kpo1a1bb75rntLCwUNauXSv5+fly0UUXSZ8+fUzu02uuuaba9VMBBGJJgPiIJV3qtp0A8WG7B7E/lgT8Hh9xEanlHaS71fQN4NVXX5X169dLenq6tGrVSpo1ayaNGzc22QHq168vtWvXlho1akhycrLoOa8nT54UPa3g8OHDZnf+/v37ZdeuXbJjxw7zt0OHDtK1a1czY8pu/ViGBHXHkgDxEUu61G07AeLDdg9ifywJ+DE+4i5SKzqouLhYdEHw7t275cCBA3Lo0CFzNrgKUhWmKlBVqKpgVeGampoqV155pVx99dVG2OoGqIyMjFj6nbohkDACxEfC0PNgCwgQHxY4CRMTRsAP8ZFwkZow7/FgCEAAAhCAAAQgEEACukxywIABsmTJEk8fb49IDWDnpMkQgAAEIAABCASXwNixY+Xpp5+Whx9+WKZMmeJZEIhUz7oGwyAAAQhAAAIQgIC7BHQWtV69evLpp5/KZZddJkeOHPHsbCoi1V3fUxsEIAABCEAAAhDwLAGdRdXToT777DO59NJLJScnx7OzqYhUz3YjDIMABCAAAQhAAALuEdBDlnQDus6ihoqXZ1MRqe75npogAAEIQAACEICAZwmUn0UNGenl2VREqme7EoZBAAIQgAAEIAABdwjoLGrdunVNWs+vfe1r8uGHH0qdOnXkn//8p5w6dUo++OADz61NRaS643tqgQAEIAABCEAAAp4loLv5x40bJ1OnTpWRI0ea0zn1FNBnnnlGdIb1qaeeMutTvVQQqV7yBrZAAAIQgAAEIACBOBAIidQ4PCrqRyBSo0bHjRCAAAQgAAEIQMBOAohUO/2G1RCAAAQgAAEIQMDXBBCpvnYvjYMABCAAAQhAAAJ2EkCk2uk3rIYABCAAAQhAAAK+JoBI9bV7aRwEIAABCEAAAhCwkwAi1U6/YTUEIAABCEAAAhDwNQFEqq/dS+MgAAEIQAACEICAnQQQqXb6DashAAEIQAACEICArwkgUn3tXhoHAQhAAAIQgAAE7CSASLXTb1gNAQhAAAIQgAAEfE0Akepr99I4CEAAAhCAAAQgYCcBRKqdfsNqCEAAAhCAAAQg4GsCiFRfu5fGQQACEIAABCAAATsJIFLt9BtWQwACEIAABCAAAV8TQKT62r00DgIQgAAEIAABCNhJAJFqp9+wGgIQgAAEIAABCPiaACLV1+6lcRCAAAQgAAEIQMBOAohUO/2G1RCAAAQgAAEIQMDXBBCpvnYvjYMABCAAAQhAAAJ2EkCk2uk3rIYABCAAAQhAAAK+JoBI9bV7aRwEIAABCEAAAhCwkwAi1U6/YTUEIAABCEAAAhDwNQFEqq/dS+MgAAEIQAACEICAnQQQqXb6DashAAEIQAACEICArwkgUn3tXhoHAQhAAAIQgAAE7CSASLXTb1gNAQhAAAIQgAAEfE0Akepr99I4CEAAAhCAAAQgYCcBRKqdfsNqCEAAAhCAAAQg4GsCiFRfu5fGQQACEIAABCAAATsJIFLt9BtWQwACEIAABCAAAV8TQKQ6cO+WLVukpKREdu/eLQcOHJBDhw5JWVmZHDt2TE6ePCmnT5+W5ORkqVGjhtSuXVtSU1PlyiuvlKuvvlqaNWsmLVu2lLZt2zp4EpdAwD4CxId9PsNiCEAAAjYQQKRW4qXt27fLK6+8Iq+99pqsX79emjZtKq1atZL09HQjPNPS0qR+/fpGkKowVYGqQlUFqwrXw4cPy8GDB2X//v1G2Gp9e/bskQ4dOkjXrl2lR48epj4KBGwkQHzY6DVshgAEIGAfAUTqv3329ttvy4oVK2TlypVy6tQpycrKkm7dukmnTp0kJSWl2p49ceKEFBYWytq1ayU/P18uvvhi6dOnj/Tr10+aNGlS7fqpAAKxJEB8xJIudUMAAhCAQGUEAi9SCwoK5LnnnjMCsn///pKdnS3XX399zHvLxo0bJS8vT5YtWyYdO3aUYcOGSffu3WP+XB4AgUgI/OlPf5IFCxYQH5FA41oIQAACEHCFQGBF6po1a2TmzJnm8/zw4cNlyJAhrgCNppLc3FyZN2+e1KlTR0aPHm1mcSkQSCQB4iOR9Hk2BCAAAQgogcCJ1J07d8r48ePNBqhHH33UfG73Slm+fLlMmzZNGjduLBMnTpQWLVp4xTTsCAgB4iMgjqaZEIAABCwgECiROmHCBJk+fbpMmjRJcnJyPOueWbNmybhx44yIVkFNgUA8CBAf8aDMMyAAAQhAwCmBQIjUbdu2yY9//GOTFko/8evufK+X0tJS8+lf013NnTuXbABed5jF9ulu/REjRpj4mDFjhjRs2NDzrSE+PO8iDIQABCBQbQK+F6kLFy40603nz59vNifZVtTuBx98UHTd6qBBg2wzH3s9ToD48LiDMA8CEIBAgAn4WqTq53LNd7p48WKrk+kXFxfLwIEDzYYqXbNKgYAbBDQ+NB3akiVLiA83gFIHBCAAAQi4SsC3IlXTSR0/ftzkPnUjz6mr1KOoTPOs6iYvzQCwdOnSKGrgFgh8QYD4oDdAAAIQgIDXCfhSpPbu3ducBqUzRH4r9913nxHfq1at8lvTaE+cCBAfcQLNYyAAAQhAoFoEfCdSdQBOTU01Cfr9WoYOHSplZWUIVb86OIbtIj5iCJeqIQABCEDAVQK+Eqn6CVOPG/XjDGpFr+uM6pkzZ/j072o4+Lsy4sPf/qV1EIAABPxGwDcidcyYMbJnzx5ZvXq133x0wfbccsstkp6ezmaqwHg8+obqJqndu3cTH9Ej5E4IQAACEIgzAV+IVE2jM2fOHCkqKvLFJimnfUA3U7Vv314eeugh0lM5hRbA64gP4iOA3Z4mQwACPiBgvUjVRP1t2rQRTdPUtm1bH7gksiZouzMzM2Xr1q0k/I8MXSCuJj6Ij0B0dBoJAQj4koD1IrVdu3Zyzz33WJmo360epQn/ly9fbmaSKRAoT4D4EHOQB/FBXEAAAhCwj4DVIlXPGtd1dnl5efaRd9ni7OxsadasmSgTCgSUAPHxRT/Q+ND12+PHj6dzQAACEICAJQSsFaklJSVyww03yN69eyUtLc0S3LEzU88yb9q0qWzcuFFatGgRuwdRsxUEND50FlU3ExIfIsSHFd0WIyEAAQicR8Bakar5Hjt27Cg5OTm49N8EZs2aJYWFheRPpUfI7bffLp06dSI+yvUF4oPAgAAEIGAXAStF6po1a2Ts2LGyc+dOu2jHwdrmzZublFRZWVlxeBqP8CIB4uPCXiE+vNhjsQkCEIBA5QSsFKk33nijDB482JxlTzmfwIoVK0RTDq1btw40ASVAfFzY8bqBatGiRcRHQGODZkMAAnYRsE6kFhQUmFnU7du320U6jta2atVKpk6dKt27d4/jU3mUFwgQH+G9cN1115mvDcRHeFZcAQEIQCCRBKwTqbrWrlevXmYmlVI5gdzcXMnPz2dtagA7CPER3unER3hGXAEBCEDACwSsEqn79u0zJywdOXLEC+w8bUPdunVlw4YN0qRJE0/biXHuESA+nLMkPpyz4koIQAACiSJglUjVvI96FKju0qVUTWDUqFFSq1Yt8qYGqKMQH86dTXw4Z8WVEIAABBJFwCqRqsm4lyxZYo4BpVRNQPOlDho0SN566y1QBYQA8eHc0cSHc1ZcCQEIQCBRBKwRqXoGed++fU1ycoozAtdee628+OKL0rp1a2c3cJW1BIiPyF2n8fHSSy+JbjSkQAACEICA9whYI1InT54sR48e5VN/BH1IP2nWq1dPHn/88Qju4lIbCRAfkXtN4yM1NdVkC6FAAAIQgID3CFgjUrt16yY6qPTs2dN7FD1qkSZ1nz17tqxdu9ajFmKWWwS6du0qDz/8MIc4RACU+IgAFpdCAAIQSAABa0TqZZddZmZSU1JSEoDJzkd+/PHHZib1k08+sbMBWO2YAPHhGNW5C3UTps6kEh+Rs+MOCEAAAvEgYIVI3bx589n777+fBP5R9Ahdb/f8889LRkZGFHdziw0EiouLxQ/xcfbsWUlKSoorck3srye0tW3bNq7P5WEQgAAEIBCegBUiNTc392xRUZHZ2U+JjMCAAQNMblkOP4iMm01Xq8iyNT5UmP7+97+XmTNnmpRpzzzzTFxz+2p8dOjQwWTCoEAAAhCAgLcIWCFSc3JyzjZo0EBGjx7tLXoWWDNjxgx5//335emnn7bAWkyMhoCuRbU1PqZPn25m+lWcvvDCC3LNNdfIU089FQ2GqO7R55eVlRmRTIEABCAAAW8RsEKk3nbbbWfvvfde6d27t7foWWDNqlWrZOnSpRyRaoGvojVRj0K1MT40nZx+bte/3/72t81xx/q5/w9/+EO0KCK+77e//a0sW7aM+IiYHDdAAAIQiD0BK0RqmzZtzi5YsMBT68bOnDkjf/3rX41NX//61895auXKldKnT5/Ye87hE7Zs2SLDhg0T/Uuxk4DOguua0wttGtQ+GIv40E/x2s9/85vfyB133CH6Y+Fm+dnPfiavv/66vPbaa6ba0HrU0F99vv5T/rlbt26VNm3auGaGrucdPny46F8KBCAAAQh4i4AVIjUtLc2sSU1LS/MEPf08qKmwNDel/vPqq6+agVRnLO+77z4zsHulHDx40KxJLS0t9YpJ2BEhga9+9aumT+Xk5JictxXFasOGDc2aVDfjQ8VhXl6eLFq0SL7xjW+Y2U6ox+O/AAAgAElEQVQ9MKCiUHXa1yvep/Xry9PevXuN6NSjjn/wgx/IK6+8Yp6h9Wp7/vGPf8iHH34oderUMWJWU9E5faYTzBoXHTt2lHfffdfJ5VwDAQhAAAJxJGCFSE1JSTn73nvveSb9VLt27WTgwIGSnJxs/p4+fdrMAunmJE2TpRtBvFI0DdW3vvUt0XQ7FDsJ/OIXv5DHHnvMiDPtZypWNQF9SKzqTL6b8aECcsKECfLnP/9Z3njjDVm8eLHp2zt37pTmzZufg6jXjR8/3sx2VlX0R2bixInnXaJtufnmm+Wzzz4zL3cqSIcOHSpf+cpXjGDVJQy6VCWUH/m2224za1fz8/Pld7/7nWuO1LjQZx8/fty1OqkIAhCAAATcIWCFSE1OTj776aefGlHohaKDtw6eOpt61VVXmU+tKlS/+c1vmoTqY8aM8YKZxga1S3Nonjp1yjM2YUjkBHQ2U2cUtVx66aVGrOrhFj/96U+ldu3a4mZ8/OUvfzGzmnpkaHZ2thGhmzdvlszMTEeGO0klpdd06dLFzJquW7fO1KtxpEsAdPZUN099//vfN18Bdu3aJU2bNpUf/vCH5q9+vXCraFzoTPW//vUvt6qkHghAAAIQcImAFSJVRMfJqmdrXOLhuBoVf3Xr1pVf//rXoqf96Fo5XRuoMz06Q+SlooIm3vknvdR+v9hSMQYuueQSufXWW82aUTfjQ1NajRs3zojFcOtQnXx6V9sqvmCGRKr2SxWp+ldPRlNhqstnbrrpJpk3b57Z1LRhwwbTPp3xnDt3rqsbKCuzzS/9hXZAAAIQsJ1A586dz01keLUtSV6bSVVQIVGq6Z3q168vubm58vOf/1zefvtt88nSK4WZVK94onp26AvRBx988KWZVF2jqus13ZxJ1c/vKhD1U39IXFY2O1qdz/3akEcffVQ2bdp0TqTOmTPHJNbfvn27Eceaw1TFq+ZH3r9/v8mfGoq36tH84m5mUt0iST0QgAAEgkkgyWtrUtUNoc+fb775phEJuk5QP6trrkcvzVqyJtX+oNE1qboGNbT2+aGHHjIbqEJZJdxek6piWJezqGBs3bq1+dyua1L137/zne+4BlTboymoXnzxRfnud79rsmJontRJkyaZGNJ1qNo2nU3VNbLLly83L4FuxhdrUl1zJxVBAAIQCCSBJK/t7lcvhDaX6EzQn/70J+OY5557zqQK8lJhd7+XvBGdLbpmUgVdaHd/+ZRnWmMsdverMNQE97pZ6p577jGbmXRdrJtFlwqo+HzyySfNOltd/6qzpzfeeKN5jO64V8GqywEOHTpkMmfMnz/fVZHK7n43PUpdEIAABIJHIMlreVLfeustGTFihEnRU69ePZN8fMqUKWY39IVyWSbKbeRJTRR5956reVKHDBlyXj7e8rXHMk9qxTyl7rXqi5rKr2sNrYFVYapfKx555JFz61E1B7EeYepmIU+qmzSpCwIQgEDwCCR57cQpzdeoO5F1F7/uCtaUVBs3bnS8+zmeLtQ0ProEwc20PfG0n2eFJ2DriVNVtUzzsmqWgQcffFDuvPNOs6FKhXq4jVzhaZ1/BSdORUqM6yEAAQhAoDyBpJycnLNeOptcZ370GEpdI6cllKrHi26bMWOG2Wyis3EUfxLQtGdXXHGFmXX0S9ENTRpjurRBU09pBg0316KGOGl8HD582CxtoEAAAhCAAAQiJZCUm5trTpzSXb5eKqG0P7EYPN1qp67x01yTuvGF4k8CuqEplHTfTy0MHV4Qy/jS+NAlBIMGDfITOtoCAQhAAAJxIpC0efPms7ohSVPTUCIj0KpVK3NST0ZGRmQ3crU1BHRdJfERnbs0u4CKfF3XS4EABCAAAQhESiBJM/lreidNjVOzZs1I7w/s9Zp+SvNrag5Nir8JEB+R+1fjQzc+fvLJJ5HfzB0QgAAEIAABETEiVdek6dq7rKwsoDgksGbNGpk9e7Y5yYfibwLER+T+JT4iZ8YdEIAABCBwPgEjUvW87qNHj5p8jRRnBPRsd50p0sTvFH8TID4i96/GR2pqqjkogQIBCEAAAhCIhoARqdu2bZO+ffuKpqahOCNw7bXXmtN89NQgir8JEB+R+1fjQzNz6LptCgQgAAEIQCAaAkak6o3p6elmh39mZmY09QTqHj0JS3cu65GWlGAQID6c+1nzGuuOfj2YgwIBCEAAAhCIlsA5kTp+/HjRzQ588g+PUj9l1qpVyxw7SQkGAeLDuZ+JD+esuBICEIAABC5M4JxI3bdvn8n5eeTIEXiFIaC7+jds2CBNmjSBVUAIEB/OHU18OGfFlRCAAAQg4ECk6iV6BGSvXr1ITl9Fj8nNzRXducxRqMELK+IjvM81PvLz80WPDKZAAAIQgAAEqkPg3EyqVlJQUGB2q+tGEUrlBHQjyJQpU6RHjx4gChgB4iO8wzU+pk6dKt27dw9/MVdAAAIQgAAEqiBwnkjV67p06WJO2NHd/pTzCaxYscKcoLNu3TrQBJQA8XFhxxMfAQ0Kmg0BCEAgRgS+JFL1U7bmNty5c2eMHmlvtS1atDCzqD179rS3EVheLQLEx4XxaXzoLCqHglSri3EzBCAAAQj8m8CXRKr+d11717lzZ9FdupTPCWjWg9dff521qHQI4qOSPqDxUVhYyFpU4gMCEIAABFwjUKlILSkpkXbt2pnk/mlpaa49zNaKDh48KE2bNpU33nhDWrZsaWszsNslAsTH+SBLS0tNfGh+VJ1NpUAAAhCAAATcIFCpSNWKNS/k3r17zakxQS933XWXGYTJixr0nvBF+4mPL1hkZ2dLs2bNiA/CAwIQgAAEXCVwQZGqT9HZ1HvvvVeGDh3q6kNtqmzBggWydOlSM4tKgUB5AsSHiMbHsmXLpKioiM4BAQhAAAIQcJVAlSJVU1G1adNGiouLpW3btq4+2IbKtmzZIhkZGbJ161Zp3bq1DSZjYxwJEB+fx4dy0NRTFAhAAAIQgICbBKoUqfogTbk0Z84cM5NYs2ZNN5/t6br0iFg9gesnP/kJhxt42lOJNS7I8aEzySNHjiQ+EtsFeToEIAAB3xIIK1K15WPGjDGbqFavXu1bEBUbduutt5p1qNOnTw9Mm2lodASCGh+6DnXatGnRQeMuCEAAAhCAQBgCjkSq1tG/f3+55JJLZPHixb6HOmDAADl16pRZa0eBgBMCQYuP06dPm7XaFAhAAAIQgECsCDgWqWqA5k9t0KCB2Szh1zJs2DB5//33yYfqVwfHsF1BiA/dRFlWVkY+1Bj2I6qGAAQgAIHPCUQkUkNC9fLLL/fljKrOoH700UcIVKIjagIqVP0cH8eOHUOgRt07uBECEIAABCIhELFI1cr10+bx48dFz+pOSUmJ5HmevFY3SfXr109q1arFJ35Pesguo4gPu/yFtRCAAAQg4E0CUYlUbYpuFikoKDAzqjanp9I0UwMHDpQePXqwScqbfdRKq/wWHzfffDObpKzsiRgNAQhAwF4CUYtUbbKm3xkyZIjMnz9fdC2nbUXX1j7wwAOSm5tLGh3bnGeBvcSHBU7CRAhAAAIQ8CyBaolUbZUm8h4xYoQ0bNhQZsyYIWlpaZ5tbMiwgwcPyujRo0XPHJ87dy6J+j3vMXsNJD7s9R2WQwACEIBAYglUW6SGzNezzGfOnCmTJk2SUaNGJbZVVTx99uzZMm7cOCNSJ0yY4Fk7McxfBGyJj1mzZskTTzxBfPir+9EaCEAAAlYScE2kautLSkpEB+N33nlHHnvsMenbt69noOgmL0083qhRI5k4caK0bNnSM7ZhSDAIEB/B8DOthAAEIAABdwi4KlJDJq1Zs8Z8+j9x4oQMHz48oes9dV3gvHnzzM59nT3t2bOnO+SoBQJREiA+ogTHbRCAAAQgECgCMRGpIYK6+183JxUVFZm0VdnZ2ZKZmRlzwJs2bZK8vDyTTqp9+/ZmU5fu3qdAwEsEiA8veQNbIAABCEDAawRiKlJDjd23b5/Jqbpy5Uo5c+aMZGVlSbdu3aRTp05Ss2bNajPRPKeFhYWydu1ayc/Pl4suukj69Oljcp9ec8011a6fCiAQSwLERyzpUjcEIAABCNhKIC4itTwc3e2sM0ivvvqqrF+/XtLT06VVq1bSrFkzady4sckOUL9+faldu7bUqFFDkpOTRc8JP3nypOhpN4cPHxbdnb9//37ZtWuX7Nixw/zt0KGDdO3a1cyYtm7d2lZ/YHfACRAfAe8ANB8CEIAABM4RiLtIrci+uLjYbLjavXu3HDhwQA4dOmTOBldBqsJUBaoKVRWsKlxTU1PlyiuvlKuvvtoIW90AlZGRgUsh4EsCxIcv3UqjIAABCEDAAYGEi1QHNnIJBCBQCQFd5jJgwABZsmSJL44nxskQgAAEIACB8gQQqfQHCFhKYOzYsfL000/Lww8/LFOmTLG0FZgNAQhAAAIQqJwAIpWeAQELCegsar169eTTTz+Vyy67TI4cOcJsqoV+xGQIQAACELgwAUQqvQMCFhLQWVQ9Heqzzz6TSy+9VHJycphNtdCPmAwBCEAAAohU+gAEfENAD8nQDYQ6ixoqzKb6xr00BAIQgAAE/k2AmVS6AgQsI1B+FjVkOrOpljkRcyEAAQhAICwBRGpYRFwAAe8Q0FnUunXrmrRsX/va1+TDDz+UOnXqyD//+U85deqUfPDBB6xN9Y67sAQCEIAABKpBAJFaDXjcCoF4E9Dd/OPGjZOpU6fKyJEjzelqeorbM888IzrD+tRTT5n1qRQIQAACEICA7QQQqbZ7EPsDTSAkUgMNgcZDAAIQgIAvCSBSfelWGhUUAojUoHiadkIAAhAIHgFEavB8Tot9RACR6iNn0hQIQAACEDiPACKVDgEBiwkgUi12HqZDAAIQgECVBBCpdBAIWEwAkWqx8zAdAhCAAAQQqfQBCPiVACLVr56lXRCAAAQgwEwqfQACFhNApFrsPEyHAAQgAAFmUukDEPArAUSqXz1LuyAAAQhAgJlU+gAELCaASLXYeZgOAQhAAALMpNIHIOBXAohUv3qWdkEAAhCAADOp9AEIWEwAkWqx8zAdAhCAAASYSaUPQMCvBBCpfvUs7YIABCAAAWZS6QMQsJgAItVi52E6BCAAAQgwk0ofgIBfCSBS/epZ2gUBCEAAAsyk0gcgYDEBRKrFzsN0CEAAAhBgJpU+AAG/EkCk+tWztAsCEIAABJhJpQ9AwGICiFSLnYfpEIAABCDATCp9AAJ+JYBI9atnaRcEIAABCDCTSh+AgMUEEKkWOw/TIQABCECAmVT6AAT8SgCR6lfP0i4IQAACEGAmlT4AAYsJIFItdh6mQwACEIAAM6n0AQj4lQAi1a+epV0QgAAEIMBMKn0AAhYTQKRa7DxMhwAEIAABZlLpAxDwKwFEql89S7sgAAEIQICZVPoABCwmgEi12HmYDgEIQAACzKTSByDgVwKIVL96lnZBAAIQgAAzqfQBCFhMAJFqsfMwHQIQgAAEmEmlD0DArwQQqX71LO2CAAQgAAFmUukDELCYACLVYudhOgQgAAEIMJNKH4CAXwkgUv3qWdoFAQhAAALMpNIHIGAxAUSqxc7DdAhAAAIQ8PZManFxsZSUlMju3bvlwIEDcujQISkrK5Njx47JyZMn5fTp05KcnCw1atSQ2rVrS2pqqqSlpUmjRo2kWbNm0rJlS8nIyMDNEAgkAURqIN1OoyEAAQgEgkDcZ1K3bdsmBQUF8tprr0lhYaGkp6fLddddZ/42btzYCND69esbQarCVAWqClUVrCpcDx8+LAcPHpT9+/fLrl27ZMeOHUbgdujQQW666Sbp0aOHtG7dOhDOo5EQQKTSByAAAQhAwK8E4iJS3377bVmxYoW8/PLLRnBmZWVJt27dpFOnTpKSklJtth9//LG8/vrrsnbtWsnPz5eLL75Y+vTpI/369ZMmTZpUu34qgIBXCSBSveoZ7IIABCAAgeoSiKlI1RnTBQsWyPr166V///5y1113SWZmZnVtDnv/xo0bJS8vT5YtWyYdO3aUYcOGSffu3cPexwUQsI0AItU2j2EvBCAAAQg4JRATkbpmzRqZOXOm+Tw/fPhwGTJkiFN7XL8uNzdXnn32WbN84JFHHpGePXu6/gwqhECiCCBSE0We50IAAhCAQKwJuCpSdQPU+PHj5Z133pFHH33UfG73StHlBlOnTjXrXidOnCgtWrTwimnYAYGoCSBSo0bHjRCAAAQg4HECronUCRMmyIwZM+TJJ5+UnJwczzZ71qxZMm7cOBkzZoyozRQI2EwAkWqz97AdAhCAAASqIlBtkaq79UeMGCENGzY0IlV353u9lJaWyujRo026q7lz50qrVq28bjL2QaBSAohUOgYEIAABCPiVQLVE6sKFC8160/nz55vNSbYV3dT1wAMPiK5bHTx4sG3mYy8EBJFKJ4AABCAAAb8SiFqk6udy3b2/ePFiadu2rbV89DCBgQMHmrRY06ZNs7YdGB5MAojUYPqdVkMAAhAIAoGoRKqmkzp+/LjJfepGntNEgz5x4oTZ5FWnTh1ZunRpos3h+RBwTACR6hgVF0IAAhCAgGUEIhapt99+uxFzS5Yssayp4c0dMGCASZu1atWq8BdzBQQ8QACR6gEnYAIEIAABCMSEQEQiVQVqgwYNTIJ+v5ahQ4dKWVkZQtWvDvZZuxCpPnMozYEABCAAgXMEHItU/cSvx436cQa1Yn/QGVU9vpVP/0SK1wkgUr3uIeyDAAQgAIFoCTgSqbpJas+ePbJ69epon2Pdfbfccoukp6ezmco6zwXLYERqsPxNayEAAQgEiUBYkapppubMmSNFRUW+2CTl1Lm6map9+/YycuRI0lM5hcZ1cSeASI07ch4IAQhAAAJxIlClSNVE/W3atBFN02RzmqloWWq7v/e974lyIOF/tBS5L5YEEKmxpEvdEIAABCCQSAJVitR27drJPffcY2Wifreg6iaxZcuWmZlkCgS8RgCR6jWPYA8EIAABCLhF4IIiVc+13717t+Tl5bn1LGvryc7OlmbNmokyoUDASwQQqV7yBrZAAAIQgICbBCoVqSUlJXLDDTfI3r17JS0tzc3nWVlXaWmpNG3aVDZu3CgtWrSwsg0Y7U8CiFR/+pVWQQACEICASKUitXfv3tKxY0fJycmB0b8JzJo1SwoLC8mfSo/wFAFEqqfcgTEQgAAEIOAigS+J1DVr1sjYsWNl586dLj7GH1U1b95cpk6dKj179vRHg2iF9QQQqda7kAZAAAIQgMAFCHxJpN54440m5ZKeZU85n8CKFStEU3KtW7cONBDwBAFEqifcgBEQgAAEIBADAueJ1IKCAjOLun379hg8yh9VaioqnU3t3r27PxpEK6wmgEi12n0YDwEIQAACVRA4T6Tefvvt0qtXL5LXVwEsNzdX8vPzWZtKWHmCACLVE27ACAhAAAIQiAGBcyJ137595oSlI0eOxOAx/qqybt26smHDBmnSpIm/GkZrrCOASLXOZRgMAQhAAAIOCZwTqZoDVI8C1V3slKoJjBo1SmrVqkXeVDpKwgkgUhPuAgyAAAQgAIEYETgnUtPT02XJkiWSmZkZo0f5p1rNlzpo0CB56623/NMoWmIlAUSqlW7DaAhAAAIQcEDAiFQ9m75v376yZ88eB7dwiRK49tpr5cUXX5TWrVsDBAIJI4BITRh6HgwBCEAAAjEmYETq5MmT5ejRo3zqjwC2fvKvV6+ePP744xHcxaUQcJcAItVdntQGAQhAAALeIWBEardu3URFF0nqnTtGDz2YPXu2rF271vlNXAkBlwkgUl0GSnUQgAAEIOAZAkakXnbZZWYmNSUlxTOGed2Qjz/+2MykfvLJJ143Fft8TACR6mPn0jQIQAACASeQtHnz5rP3338/Cfyj6Aia2P/555+XjIyMKO7mFghUnwAitfoMqQECEIAABLxJICk3N/dsUVGR2dlPiYzAgAEDTG5ZPUaWAoFEEECkJoI6z4QABCAAgXgQSMrJyTnboEEDGT16dDyeF9Uzzp49K0lJSVHdG8ubZsyYIe+//748/fTTsXwMdUPgggQQqXQOCEAAAhDwK4Gk22677ey9994rvXv39lQbz5w5I3PnzpXly5eLDsQjRoyQu+++21M2rlq1SpYuXcoRqZ7ySrCMQaQGy9+0FgIQgECQCCS1adPm7IIFC6Rt27aeabcK1DvuuEOaN29u/uoRpHPmzJE333zTUzOqW7ZskWHDhon+pUAgEQQQqYmgzjMhAAEIQCAeBJLS0tLMmtS0tLR4PC/sM/TT/tChQ+Xdd9+VV155xcyiTpw4Uf7xj3/Ic889F/b+eF5w8OBBsya1tLQ0no/lWRA4RwCRSmeAAAQgAAG/EkhKSUk5+95773km/dSJEyekVq1a8rOf/cz8s2nTJjOj6sX0WJqG6lvf+paozRQIJIIAIjUR1HkmBCAAAQjEg0BScnLy2U8//VSSk5Pj8bywz9i7d680bdpUnnjiCbniiitE/33Hjh1GsN50001h74/nBadPnxbNMXvq1Kl4PpZnQYCZVPoABCAAAQj4noBumdd8/p5p6GuvvSZdu3YVTe+0ePFiY9f48eNl4cKF8vbbb0uNGjU8Y6sa4sWsA54ChDExJdClSxdZt25dTJ9B5RCAAAQgAIFEEPDcTOqBAwekcePGsmjRIhk4cKBhkpeXJ3fddZfZOPXd7343EZwqfSYzqZ5xBYZAAAIQgAAEIOAzAp5bk6qfzi+55JLzROqKFStM+qm1a9eaWVavFNakesUT2AEBCEAAAhCAgN8IeG53v6af0hnUq666yuzq16Kf+9esWSObN282u/29Utjd7xVPYAcEIAABCEAAAn4j4Mk8qbpR6gc/+IHceeedZlb1b3/7m4waNUqysrI8xZ88qZ5yB8ZAAAIQgAAEIOAjAp4+cWrlypXSrl07k+bJSzOoIf/riVMvvPCC/O53v/NRl6ApEIAABCAAAQhAIPEEknJycs42aNBARo8enXhrLLNgxowZ8v7778vTTz9tmeWYCwEIQAACEIAABLxNICk3N9ecOLVkyRJvW+pB6zRNlp44NXjwYA9ah0kQgAAEIAABCEDAXgJJmzdvPnv//ffL9u3b7W1Fgixv1aqVPP/885KRkZEgC3gsBCAAAQhAAAIQ8CeBJM3kr6cmffDBB1KzZk1/tjIGrdL0U3Xr1hU9rYsCAQhAAAIQgAAEIOAuASNSNffoww8/7Lnd8+421d3aNCXW7NmzTe5WCgQgAAEIQAACEICAuwSMSJ08ebIcPXpUZs2a5W7tPq5NU2LVq1dPHn/8cR+3kqZBAAIQgAAEIACBxBAwInXbtm3St29f2bNnT2KssPCp1157rbz44ovSunVrC63HZAhAAAIQgAAEIOBtAkakqonp6elmh39mZqa3LfaAdZs2bRLd2b9r1y4PWIMJEIAABCAAAQhAwH8EzolUPXpUNwPxyT+8k/VTf61atWTChAnhL+YKCEAAAhCAAAQgAIGICZwTqfv27TM5P48cORJxJUG7QXf1b9iwQZo0aRK0ptNeCEAAAhCAAAQgEBcC50SqPu3222+XXr16kZy+CvS5ubmiO/s5CjUu/ZOHQAACEIAABCAQUALnidSCggKzW103UlEqJ6AJ/KdMmSI9evQAEQQgAAEIQAACEIBAjAicJ1L1GV26dBE9gUp3+1POJ7BixQpZuHChrFu3DjQQgAAEIAABCEAAAjEk8CWRqp+yx44dKzt37ozhY+2sukWLFmYWtWfPnnY2AKshAAEIQAACEICAJQS+JFLVbl2b2rlzZ9Fd7JTPCWjWg9dff521qHQICEAAAhCAAAQgEAcClYrUkpISadeunUnun5aWFgczvP2IgwcPStOmTeWNN96Qli1bettYrIMABCAAAQhAAAI+IFCpSNV2ad7UvXv3yksvveSDZlavCXfddZcRqeRFrR5H7oYABCAAAQhAAAJOCVxQpGoFOpt6zz33yLBhw5zW57vrFixYIEuXLjWzqBQIQAACEIAABCAAgfgQqFKkaiqqNm3aSHFxsbRt2zY+FnnoKVu2bJGMjAzZunWrtG7d2kOWYQoEIAABCEAAAhDwN4EqRao2XVMuzZkzR4qKiiQlJcXfNMq1To+I1RO4fvKTn3C4QWC8TkMhAAEIQAACEPAKgbAiVQ0dM2aM2US1evVqr9gdcztuvfVWsw51+vTpMX8WD4AABCAAAQhAAAIQOJ+AI5Gqt/Tv318uueQSWbx4se8ZDhgwQE6dOiXLli3zfVtpIAQgAAEIQAACEPAiAcciVY3X/KkNGjQQ3Uzk16KbxN5//33yofrVwbQLAhCAAAQgAAErCEQkUkNC9fLLL/fljKrOoH700UcIVCu6LkZCAAIQgAAEIOBnAhGLVIWhn/6PHz8uv/rVr6RmzZrW89FNUv369ZNatWrxid96b9IACEAAAhCAAAT8QCAqkaoN181UBQUFsmTJEpOmytaiaaYGDhwoPXr0YJOUrU7EbghAAAIQgAAEfEcgapGqJDQ91ZAhQ8wa1aFDh1oHR+1+4IEHJDc3lzRT1nkPgyEAAQhAAAIQ8DOBaolUBaMJ/0eMGCENGzaUGTNmSFpamud5HTx4UEaPHi2lpaUyd+5cEvV73mMYCAEIQAACEIBA0AhUW6SGgI0fP15mzpwpkyZNklGjRnmW4+zZs2XcuHFGpE6YMMGzdmIYBCAAAQhAAAIQCDIB10SqQiwpKREVq++884489thj0rdvX8+wXbFihUybNk0aNWokEydOlJYtW3rGNgyBAAQgAAEIQAACEDifgKsiNVT1H//4RzOreuLECRk+fHhC13vqutl58+aZnfs6e9qzZ0/6AAQgAAEIQAACEICAxwnERKSG2qy7/3VzUlFRkUlblZ2dLZmZmTFHsmnTJsnLyzPppNq3by+aoF9371MgAAEIQAACEIAABOwgECnyJc0AAAENSURBVFORGkKwb98+0c/tK1eulDNnzkhWVpZ069ZNOnXq5EqeVc1z+vrrr8urr74q+fn5ctFFF8mdd95plhtcc801dngCKyEAAQhAAAIQgAAEzhGIi0gtz1uzAegMqwrK9evXS3p6ulx33XXmb+PGjU12gPr160vt2rWlRo0akpycLKdPn5aTJ0/KsWPH5PDhw6K78/fv3y+7du2SHTt2mL8dO3aUm266ycyYtm7dGhdDAAIQgAAEIAABCFhMIO4itSKr4uJis+Fq9+7dcuDAATl06JCUlZUZQarCVAWqClUVrCpcU1NT5corr5Srr75amjVrZjZAZWRkWOwCTIcABCAAAQhAAAIQqEjg/wOzX8Uhbh50FQAAAABJRU5ErkJggg==)", "_____no_output_____" ], [ "> Denote each arrow with the corresponding partial gradient, e.g. $\\frac{df}{dc} = 1$ between $f$ and $c$, and use the generalized chain rule on graphs to compute the gradients $\\frac{df}{dc}$, $\\frac{df}{db}$, $\\frac{df}{da}$, $\\frac{df}{dx}$, $\\frac{df}{dy}$.", "_____no_output_____" ], [ "Your answer here\r\n\r\n$\\frac{df}{dc} = 1$\r\n\r\n$\\frac{dc}{d6} = y$\r\n\r\n$\\frac{dc}{dy} = 6$\r\n\r\n\r\n$\\frac{df}{db} = 1$\r\n\r\n$\\frac{db}{d3} = a$\r\n\r\n$\\frac{db}{da} = 3$\r\n\r\n$\\frac{da}{dx} = 2x$\r\n\r\n----------------------------------\r\n\r\n$\\frac{df}{da} = \\frac{df}{db} * \\frac{db}{da} = 1 * 3 = 3$\r\n\r\n$\\frac{df}{dx} = \\frac{df}{db} * \\frac{db}{da} * \\frac{da}{dx} = 1 * 3 * 2x = 6x$\r\n\r\n$\\frac{df}{dy} = \\frac{df}{dc} * \\frac{dc}{dy} = 1 * 6 = 6$", "_____no_output_____" ], [ "### Autodiff\n\nThis exercise is quite hard. It's OK if you don't finish it, but you should try your best!", "_____no_output_____" ], [ "You are given the following function (pseudo-code):", "_____no_output_____" ] ], [ [ "def parents_grads(node):\r\n \"\"\" \r\n returns parents of node and the gradients of node w.r.t each parent\r\n e.g. in the example graph above parents_grads(f) would return: [(b, df/db), (c, df/dc)]\r\n \"\"\"", "_____no_output_____" ] ], [ [ "> Complete the `backprop` method below to create a recursive algorithm such that calling `backward(node)` computes the gradient of `node` w.r.t. every (upstream - to the left) node in the computational graph. Every node has a `node.grad` attribute that is initialized to `0.0`, it's numerical gradient. The algorithm should modify this property directly, it should not return anything. Assume the gradients from `parents_grads` can be treated like real numbers, so you can e.g. multiply and add them.", "_____no_output_____" ] ], [ [ "def backprop(node, df_dnode):\r\n node.grad += df_dnode\r\n # Your code here\r\n parents = parents_grads(node)\r\n for parent, grad in parents:\r\n backprop(parent, grad + df_dnode) \r\n\r\n\r\ndef backward(node):\r\n \"\"\"\r\n Computes the gradient of every (upstream) node in the computational graph w.r.t. node.\r\n \"\"\"\r\n backprop(node, 1.0) # The gradient of a node w.r.t. itself is 1 by definition.", "_____no_output_____" ] ], [ [ "Ok, now let's try to actually make it work! We'll define a class `Node` which contains the node value, gradient and parents and their gradients", "_____no_output_____" ] ], [ [ "from typing import Sequence, Tuple\r\n\r\nclass Node:\r\n def __init__(self, value: float, parents_grads: Sequence[Tuple['Node', float]]):\r\n self.value = value\r\n self.grad = 0.0\r\n self.parents_grads = parents_grads \r\n \r\n def __repr__(self):\r\n return \"Node(value=%.4f, grad=%.4f)\"%(self.value, self.grad)", "_____no_output_____" ] ], [ [ "So far no magic. We still havn't defined how we get the `parents_grads`, but we'll get there. Now move the `backprop` and `grad` function into the class, and modify it so it works with the class. ", "_____no_output_____" ] ], [ [ "# Your code here\r\nfrom typing import Sequence, Tuple\r\n\r\nclass Node:\r\n def __init__(self, value: float, parents_grads: Sequence[Tuple['Node', float]]):\r\n self.value = value\r\n self.grad = 0.0\r\n self.parents_grads = parents_grads \r\n \r\n def __repr__(self):\r\n return \"Node(value=%.4f, grad=%.4f)\"%(self.value, self.grad)\r\n\r\n def backprop(self, df_dnode):\r\n self.grad += df_dnode\r\n # Your code here\r\n for parent, grad in self.parents_grads:\r\n parent.backprop(grad * df_dnode) \r\n\r\n\r\n def backward(self):\r\n \"\"\"\r\n Computes the gradient of every (upstream) node in the computational graph w.r.t. node.\r\n \"\"\"\r\n self.backprop(1.0) # The gradient of a node w.r.t. itself is 1 by definition.", "_____no_output_____" ] ], [ [ "Now let's create a simple graph: $y = x^2$, and compute it for $x=2$. We'll set the parent_grads directly based on our knowledge that $\\frac{dx^2}{dx}=2x$", "_____no_output_____" ] ], [ [ "x = Node(2.0, [])\r\ny = Node(x.value**2, parents_grads=[(x, 2*x.value)])", "_____no_output_____" ] ], [ [ "And print the two nodes", "_____no_output_____" ] ], [ [ "print(\"x\", x, \"y\", y)", "x Node(value=2.0000, grad=0.0000) y Node(value=4.0000, grad=0.0000)\n" ] ], [ [ "> Verify that the `y.backward()` call below computes the correct gradients", "_____no_output_____" ] ], [ [ "y.backward()\r\nprint(\"x\", x, \"y\", y)", "x Node(value=2.0000, grad=4.0000) y Node(value=4.0000, grad=1.0000)\n" ] ], [ [ "$\\frac{dy}{dx}$ should be 4 and $\\frac{dy}{dy}$ should be 1", "_____no_output_____" ], [ "Ok, so it seems to work, but it's not very easy to use, since you have to define all the `parents_grads` whenever you're creating new nodes. **Here's the trick.** We can make a function `square(node:Node)->Node` which can square any Node. See below", "_____no_output_____" ] ], [ [ "def square(node: Node) -> Node:\r\n return Node(node.value**2, [(node, 2*node.value)])", "_____no_output_____" ] ], [ [ "Let's verify that it works", "_____no_output_____" ] ], [ [ "x = Node(3.0, [])\r\ny = square(x)\r\nprint(\"x\", x, \"y\", y)\r\ny.backward()\r\nprint(\"x\", x, \"y\", y)", "x Node(value=3.0000, grad=0.0000) y Node(value=9.0000, grad=0.0000)\nx Node(value=3.0000, grad=6.0000) y Node(value=9.0000, grad=1.0000)\n" ] ], [ [ "Now we're getting somewhere. These calls to square can of course be chained", "_____no_output_____" ] ], [ [ "x = Node(3.0, [])\r\ny = square(x)\r\nz = square(y)\r\nprint(\"x\", x, \"y\", y, \"z\", z)\r\nz.backward()\r\nprint(\"x\", x, \"y\", y,\"z\", z)", "x Node(value=3.0000, grad=0.0000) y Node(value=9.0000, grad=0.0000) z Node(value=81.0000, grad=0.0000)\nx Node(value=3.0000, grad=108.0000) y Node(value=9.0000, grad=18.0000) z Node(value=81.0000, grad=1.0000)\n" ] ], [ [ "> Compute the $\\frac{dz}{dx}$ gradient by hand and verify that it's correct", "_____no_output_____" ], [ "Your answer here\r\n\r\n$\\frac{dz}{dx} = \\frac{dz}{dy} * \\frac{dy}{dx} = 2y * 2x = 2 (x^2) * 2x = 2 * 3^2 * 2 * 3 = 108$", "_____no_output_____" ], [ "Similarly we can create functions like this for all the common operators, plus, minus, multiplication, etc. With enough base operators like this we can create any computation we want, and compute the gradients automatically with `.backward()`\n\n> Finish the plus function below and verify that it works", "_____no_output_____" ] ], [ [ "def plus(a: Node, b:Node)->Node:\r\n \"\"\"\r\n Computes a+b\r\n \"\"\"\r\n # Your code here\r\n return Node(a.value + b.value, [(a, 1), (b, 1)])", "_____no_output_____" ], [ "x = Node(4.0, [])\r\ny = Node(5.0, [])\r\nz = plus(x, y)\r\nprint(\"x\", x, \"y\", y, \"z\", z)\r\nz.backward()\r\nprint(\"x\", x, \"y\", y,\"z\", z)", "x Node(value=4.0000, grad=0.0000) y Node(value=5.0000, grad=0.0000) z Node(value=9.0000, grad=0.0000)\nx Node(value=4.0000, grad=1.0000) y Node(value=5.0000, grad=1.0000) z Node(value=9.0000, grad=1.0000)\n" ] ], [ [ "> Finish the multiply function below and verify that it works:", "_____no_output_____" ] ], [ [ "def multiply(a: Node, b:Node)->Node:\r\n \"\"\"\r\n Computes a*b\r\n \"\"\"\r\n # Your code hre\r\n return Node(a.value*b.value, [(a,b.value),(b,a.value)])", "_____no_output_____" ], [ "x = Node(4.0, [])\r\ny = Node(5.0, [])\r\nz = multiply(x, y)\r\nprint(\"x\", x, \"y\", y, \"z\", z)\r\nz.backward()\r\nprint(\"x\", x, \"y\", y,\"z\", z)", "x Node(value=4.0000, grad=0.0000) y Node(value=5.0000, grad=0.0000) z Node(value=20.0000, grad=0.0000)\nx Node(value=4.0000, grad=5.0000) y Node(value=5.0000, grad=4.0000) z Node(value=20.0000, grad=1.0000)\n" ] ], [ [ "We'll stop here, but with just a few more functions we could compute a lot of common computations, and get their gradients automatically!\n\nThis is super nice, but it's kind of annoying having to write `plus(a,b)`. Wouldn't it be nice if we could just write `a+b`? With python operator overloading we can! If we define the `__add__` method on `Node`, this will be executed instead of the regular plus operation when we add something to a `Node`. \n\n> Modify the `Node` class so that it overload the plus, `__add__(self, other)`, and multiplication, `__mul__(self, other)`, operators and run the code below to verify that it works.", "_____no_output_____" ] ], [ [ "# Your code here\r\nclass Node:\r\n def __init__(self, value: float, parents_grads: Sequence[Tuple['Node', float]]):\r\n self.value = value\r\n self.grad = 0.0\r\n self.parents_grads = parents_grads \r\n \r\n def __repr__(self):\r\n return \"Node(value=%.4f, grad=%.4f)\"%(self.value, self.grad)\r\n\r\n def backprop(self, df_dnode):\r\n self.grad += df_dnode\r\n # Your code here\r\n for parent, grad in self.parents_grads:\r\n parent.backprop(grad * df_dnode) \r\n\r\n\r\n def backward(self):\r\n \"\"\"\r\n Computes the gradient of every (upstream) node in the computational graph w.r.t. node.\r\n \"\"\"\r\n self.backprop(1.0) # The gradient of a node w.r.t. itself is 1 by definition.\r\n \r\n def __add__(self, other):\r\n return Node(self.value + other.value, [(self, 1), (other, 1)])\r\n\r\n def __mul__(self, other):\r\n return Node(self.value * other.value, [(self, other.value), (other, self.value)])", "_____no_output_____" ], [ "a = Node(2.0, [])\r\nb = Node(3.0, [])\r\nc = Node(4.0, [])\r\nd = a*b + c # Behold the magic of operator overloading!\r\nprint(\"a\", a, \"b\", b, \"c\", c, \"d\", d)\r\nd.backward()\r\nprint(\"a\", a, \"b\", b, \"c\", c, \"d\", d)", "a Node(value=2.0000, grad=0.0000) b Node(value=3.0000, grad=0.0000) c Node(value=4.0000, grad=0.0000) d Node(value=10.0000, grad=0.0000)\na Node(value=2.0000, grad=3.0000) b Node(value=3.0000, grad=2.0000) c Node(value=4.0000, grad=1.0000) d Node(value=10.0000, grad=1.0000)\n" ] ], [ [ "Congratulations, you've made your own tiny library for autodiff! That's really an awesome achievement!\n\nNow, I wouldn't recommend using your library for anything other than a tool to understand the inner workings of autodiff. Extremely good libraries already exist, which has a lot of functions defined and are super-duper optimized and can even run on specialized hardware like GPUs. Some of those libraries are [PyTorch](https://pytorch.org/), [Tensorflow](https://www.tensorflow.org/) and [Jax](https://github.com/google/jax). ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d01c2ae951cdb9cfcf5c9931964ebb57061b8551
29,172
ipynb
Jupyter Notebook
notebooks/Experimental/Ishan/ADP Demo/Old Versions/DataFrame to NumPy.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
null
null
null
notebooks/Experimental/Ishan/ADP Demo/Old Versions/DataFrame to NumPy.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
null
null
null
notebooks/Experimental/Ishan/ADP Demo/Old Versions/DataFrame to NumPy.ipynb
Noob-can-Compile/PySyft
156cf93489b16dd0205b0058d4d23d56b3a91ab8
[ "Apache-2.0" ]
null
null
null
32.269912
237
0.437783
[ [ [ "import syft as sy\nimport numpy as np\nfrom syft.core.adp.entity import DataSubject", "_____no_output_____" ] ], [ [ "## To Do\n\nDownload a dataset from Domain\n\nConvert all string columns to unique integers ---> could use hashes\n", "_____no_output_____" ] ], [ [ "domain_node = sy.login(email=\"[email protected]\", password=\"changethis\", port=8081)", "Connecting to http://localhost:8081... done! \t Logging into adp... done!\n" ], [ "domain_node.store.pandas", "_____no_output_____" ], [ "import pandas as pd", "_____no_output_____" ], [ "canada = pd.read_csv(\"../../trade_demo/datasets/ca - feb 2021.csv\")", "/Users/ishanmishra/PycharmProjects/PySyft/.tox/syft.jupyter/lib/python3.9/site-packages/IPython/core/interactiveshell.py:3441: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False.\n exec(code_obj, self.user_global_ns, self.user_ns)\n" ], [ "canada.head()", "_____no_output_____" ], [ "import hashlib", "_____no_output_____" ], [ "hashlib.algorithms_available", "_____no_output_____" ], [ "test_string = \"February 2021\"\nhashlib.md5(test_string.encode(\"utf-8\"))", "<md5 _hashlib.HASH object @ 0x143f50f10>\n" ], [ "int(hashlib.sha256(test_string.encode(\"utf-8\")).hexdigest(), 16) % 10**8", "_____no_output_____" ], [ "def convert_string(s: str, digits: int=15):\n \"\"\"Maps a string to a unique hash using SHA, converts it to a hash or an int\"\"\"\n if to_int:\n return int(hashlib.sha256(s.encode(\"utf-8\")).hexdigest(), 16) % 10**digits\n else:\n return hashlib.sha256(s.encode(\"utf-8\")).hexdigest()", "_____no_output_____" ], [ "convert_string(\"Canada\", to_int=False)", "_____no_output_____" ], [ "convert_string(\"Canada\", to_int=True, digits=10)", "_____no_output_____" ], [ "convert_string(\"Canada\", to_int=True, digits=260)", "_____no_output_____" ], [ "canada.columns", "_____no_output_____" ], [ "#domain_node.load_dataset(canada)\ncanada.shape", "_____no_output_____" ], [ "domain_node.datasets.pandas", "_____no_output_____" ], [ "canada['Trade Flow']", "_____no_output_____" ], [ "domain_node.store.pandas", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01c420196f060f43a8738a0f3fe2e3f7f90bb4f
449,830
ipynb
Jupyter Notebook
Oreilly_Natural Language Processing with Python/ch01.ipynb
db12138/Online_Courses_and_Materials
6a113056f4fd2667556942b3bcc9608bdf9c2968
[ "MIT" ]
1
2019-12-25T12:42:30.000Z
2019-12-25T12:42:30.000Z
Oreilly_Natural Language Processing with Python/.ipynb_checkpoints/ch01-checkpoint.ipynb
db12138/Online_Courses_and_Materials
6a113056f4fd2667556942b3bcc9608bdf9c2968
[ "MIT" ]
null
null
null
Oreilly_Natural Language Processing with Python/.ipynb_checkpoints/ch01-checkpoint.ipynb
db12138/Online_Courses_and_Materials
6a113056f4fd2667556942b3bcc9608bdf9c2968
[ "MIT" ]
3
2019-07-29T04:47:06.000Z
2021-02-22T23:20:30.000Z
161.229391
315,289
0.559113
[ [ [ "from nltk.book import *", "*** Introductory Examples for the NLTK Book ***\nLoading text1, ..., text9 and sent1, ..., sent9\nType the name of the text or sentence to view it.\nType: 'texts()' or 'sents()' to list the materials.\ntext1: Moby Dick by Herman Melville 1851\ntext2: Sense and Sensibility by Jane Austen 1811\ntext3: The Book of Genesis\ntext4: Inaugural Address Corpus\ntext5: Chat Corpus\ntext6: Monty Python and the Holy Grail\ntext7: Wall Street Journal\ntext8: Personals Corpus\ntext9: The Man Who Was Thursday by G . K . Chesterton 1908\n" ], [ "text1", "_____no_output_____" ], [ "text1.concordance(\"monstrous\") # use to search for word 'monstrous'", "Displaying 11 of 11 matches:\nong the former , one was of a most monstrous size . ... This came towards us , \nON OF THE PSALMS . \" Touching that monstrous bulk of the whale or ork we have r\nll over with a heathenish array of monstrous clubs and spears . Some were thick\nd as you gazed , and wondered what monstrous cannibal and savage could ever hav\nthat has survived the flood ; most monstrous and most mountainous ! That Himmal\nthey might scout at Moby Dick as a monstrous fable , or still worse and more de\nth of Radney .'\" CHAPTER 55 Of the Monstrous Pictures of Whales . I shall ere l\ning Scenes . In connexion with the monstrous pictures of whales , I am strongly\nere to enter upon those still more monstrous stories of them which are to be fo\nght have been rummaged out of this monstrous cabinet there is no telling . But \nof Whale - Bones ; for Whales of a monstrous size are oftentimes cast up dead u\n" ], [ "text1.similar(\"monstrous\")", "true contemptible christian abundant few part mean careful puzzled\nmystifying passing curious loving wise doleful gamesome singular\ndelightfully perilous fearless\n" ], [ "text2.similar(\"monstrous\")", "very so exceedingly heartily a as good great extremely remarkably\nsweet vast amazingly\n" ], [ "text2.common_contexts(['monstrous','very'])", "a_pretty am_glad a_lucky is_pretty be_glad\n" ], [ "%matplotlib inline\nimport seaborn as sns", "_____no_output_____" ], [ "text4.dispersion_plot(['citizens','democracy','freedom','duties','America'])", "_____no_output_____" ], [ "text4", "_____no_output_____" ], [ "#text3.generate('day')", "_____no_output_____" ], [ "len(text3)", "_____no_output_____" ], [ "sorted(set(text3))", "_____no_output_____" ], [ "len(set(text3)) # this calculates the amonut of used words in the text3", "_____no_output_____" ], [ "from __future__ import division", "_____no_output_____" ], [ "len(text3)/len(set(text3)) # the average used time of each word", "_____no_output_____" ], [ "text3.count(\"smote\") # to calculate how many used times of 'smote'", "_____no_output_____" ], [ "text2[len(text2)-20:]", "_____no_output_____" ], [ "sent = ['word1', 'word2', 'word3', 'word4', 'word5',\\\n 'word6', 'word7', 'word8', 'word9', 'word10']\n#Now modify the sent list content\nsent[0] = 'First'\nsent[9] = 'Last'\nsent[1:9] = ['Second','Third']\nsent", "_____no_output_____" ], [ "sent[9] # size of sent will automatically reshaped \\\n #into (1,4) after you modify its values", "_____no_output_____" ], [ "len(set(text5))", "_____no_output_____" ], [ "'a' * 2", "_____no_output_____" ], [ "'a' * 'a'", "_____no_output_____" ], [ "saying = ['After', 'all', 'is', 'said', 'and', 'done',\\\n 'more', 'is', 'said', 'than', 'done']\ntokens = set(saying) # choose each word once\ntokens = sorted(tokens) # then sorted the word list via alphabet order\n#tokens\ntokens[-2:]", "_____no_output_____" ], [ "fdist1 = FreqDist(text1)\nfdist1.items()", "_____no_output_____" ], [ "fdist1.plot(50, cumulative=True)", "_____no_output_____" ], [ "fdist1.hapaxes()", "_____no_output_____" ], [ "V = set(text1)\nlong_words = [w for w in V if len(w) > 15]\nsorted(long_words)", "_____no_output_____" ], [ "fdist5 = FreqDist(text5)\nsorted([w for w in set(text5) if len(w)>7 and fdist5[w] > 7])", "_____no_output_____" ], [ "text4.collocations() #print the most frequent bigrams(two words) from the text", "United States; fellow citizens; four years; years ago; Federal\nGovernment; General Government; American people; Vice President; Old\nWorld; Almighty God; Fellow citizens; Chief Magistrate; Chief Justice;\nGod bless; every citizen; Indian tribes; public debt; one another;\nforeign nations; political parties\n" ], [ "text8.collocations() # not so make sense....", "would like; medium build; social drinker; quiet nights; non smoker;\nlong term; age open; Would like; easy going; financially secure; fun\ntimes; similar interests; Age open; weekends away; poss rship; well\npresented; never married; single mum; permanent relationship; slim\nbuild\n" ], [ "fdist = FreqDist([len(w) for w in text1])", "_____no_output_____" ], [ "fdist.plot();fdist.plot(cumulative = True)", "_____no_output_____" ], [ "sent7", "_____no_output_____" ], [ "from nltk.book import *\nbabelize_shell()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01c4ba72ec897fb463bc2949269425437eda8aa
6,957
ipynb
Jupyter Notebook
Assignments/HW_3/Pyspark.ipynb
soundreaper/DS-2.3-Data-Science-in-Production
e1cafb9188ab0c141688d8a34a5ad56b76a903ae
[ "MIT" ]
null
null
null
Assignments/HW_3/Pyspark.ipynb
soundreaper/DS-2.3-Data-Science-in-Production
e1cafb9188ab0c141688d8a34a5ad56b76a903ae
[ "MIT" ]
null
null
null
Assignments/HW_3/Pyspark.ipynb
soundreaper/DS-2.3-Data-Science-in-Production
e1cafb9188ab0c141688d8a34a5ad56b76a903ae
[ "MIT" ]
null
null
null
31.479638
223
0.393848
[ [ [ "from pyspark import SparkContext\nsc = SparkContext()\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession \\\n .builder \\\n .appName(\"Python Spark regression example\") \\\n .config(\"spark.some.config.option\", \"some-value\") \\\n .getOrCreate()", "_____no_output_____" ], [ "df = spark.read.csv('titanic.csv',header=True, inferSchema = True)", "_____no_output_____" ], [ "df.show()", "+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n|PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked|\n+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n| 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0| A/5 21171| 7.25| null| S|\n| 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C|\n| 3| 1| 3|Heikkinen, Miss. ...|female|26.0| 0| 0|STON/O2. 3101282| 7.925| null| S|\n| 4| 1| 1|Futrelle, Mrs. Ja...|female|35.0| 1| 0| 113803| 53.1| C123| S|\n| 5| 0| 3|Allen, Mr. Willia...| male|35.0| 0| 0| 373450| 8.05| null| S|\n| 6| 0| 3| Moran, Mr. James| male|null| 0| 0| 330877| 8.4583| null| Q|\n| 7| 0| 1|McCarthy, Mr. Tim...| male|54.0| 0| 0| 17463|51.8625| E46| S|\n| 8| 0| 3|Palsson, Master. ...| male| 2.0| 3| 1| 349909| 21.075| null| S|\n| 9| 1| 3|Johnson, Mrs. Osc...|female|27.0| 0| 2| 347742|11.1333| null| S|\n| 10| 1| 2|Nasser, Mrs. Nich...|female|14.0| 1| 0| 237736|30.0708| null| C|\n| 11| 1| 3|Sandstrom, Miss. ...|female| 4.0| 1| 1| PP 9549| 16.7| G6| S|\n| 12| 1| 1|Bonnell, Miss. El...|female|58.0| 0| 0| 113783| 26.55| C103| S|\n| 13| 0| 3|Saundercock, Mr. ...| male|20.0| 0| 0| A/5. 2151| 8.05| null| S|\n| 14| 0| 3|Andersson, Mr. An...| male|39.0| 1| 5| 347082| 31.275| null| S|\n| 15| 0| 3|Vestrom, Miss. Hu...|female|14.0| 0| 0| 350406| 7.8542| null| S|\n| 16| 1| 2|Hewlett, Mrs. (Ma...|female|55.0| 0| 0| 248706| 16.0| null| S|\n| 17| 0| 3|Rice, Master. Eugene| male| 2.0| 4| 1| 382652| 29.125| null| Q|\n| 18| 1| 2|Williams, Mr. Cha...| male|null| 0| 0| 244373| 13.0| null| S|\n| 19| 0| 3|Vander Planke, Mr...|female|31.0| 1| 0| 345763| 18.0| null| S|\n| 20| 1| 3|Masselmani, Mrs. ...|female|null| 0| 0| 2649| 7.225| null| C|\n+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\nonly showing top 20 rows\n\n" ], [ "df.describe()", "_____no_output_____" ], [ "# Shape of the DateFrame\nprint((df.count(), len(df.columns)))", "(891, 12)\n" ], [ "df.dtypes", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "# Number of Male Passengers and Number of Female Passengers\nprint(df.filter(df['Sex'] == 'male').count())\nprint(df.filter(df['Sex'] == 'female').count())", "577\n314\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01c4ff48f9bfe6bf4b4a154a5751bedc04acbcc
3,978
ipynb
Jupyter Notebook
day8/warm-up-day-8-ex2-solution.ipynb
btardio/dataviz_warmups
6eca22f9a722766941ddbf203a5d5a3044c09a48
[ "MIT" ]
null
null
null
day8/warm-up-day-8-ex2-solution.ipynb
btardio/dataviz_warmups
6eca22f9a722766941ddbf203a5d5a3044c09a48
[ "MIT" ]
null
null
null
day8/warm-up-day-8-ex2-solution.ipynb
btardio/dataviz_warmups
6eca22f9a722766941ddbf203a5d5a3044c09a48
[ "MIT" ]
null
null
null
26.171053
112
0.418552
[ [ [ "import pandas as pd\nfrom IPython.display import display, HTML\n\ndf = pd.DataFrame({\"sku\": ['325','436','772'], \"price\": ['$100', '$124', '$99'] } )\n\n# remove/replace the dollar sign\ndf['price'] = df['price'].str.replace('$', '')\n\n# convert from str to int, raise an error if it can't convert\ndf['price'] = pd.to_numeric(df['price'], errors='raise')\n\n# assign df the view returned with only the rows from the price column with \n# price greater than 100\ndf = df.loc[ df['price'] >= 100 ]\n\n# rename the column headers\ndf = df.rename({'sku': 'Product #Ref', 'price': 'Retail Price'}, axis=1)\n\n# convert the price column back to string\ndf['Retail Price'] = df['Retail Price'].astype(str)\n\n# add a dollar sign in front of the price\ndf['Retail Price'] = '$' + df['Retail Price']\n\ndf", "_____no_output_____" ], [ "display( HTML('<h1>Table Showing products with prices of $100 or more.</h1>' + df.to_html()) )", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
d01c63fe42b19ef4d662aa29cf0722aba1e75a90
34,594
ipynb
Jupyter Notebook
openmdao/docs/openmdao_book/features/core_features/working_with_components/distributed_components.ipynb
markleader/OpenMDAO
0579ea9fa976706a18d56f167a171d474b5f993e
[ "Apache-2.0" ]
null
null
null
openmdao/docs/openmdao_book/features/core_features/working_with_components/distributed_components.ipynb
markleader/OpenMDAO
0579ea9fa976706a18d56f167a171d474b5f993e
[ "Apache-2.0" ]
null
null
null
openmdao/docs/openmdao_book/features/core_features/working_with_components/distributed_components.ipynb
markleader/OpenMDAO
0579ea9fa976706a18d56f167a171d474b5f993e
[ "Apache-2.0" ]
null
null
null
38.695749
905
0.566775
[ [ [ "%pylab inline\nfrom ipyparallel import Client, error\ncluster=Client(profile=\"mpi\")\nview=cluster[:]\nview.block=True\n\ntry:\n from openmdao.utils.notebook_utils import notebook_mode\nexcept ImportError:\n !python -m pip install openmdao[notebooks]", "_____no_output_____" ] ], [ [ "```{note}\nThis feature requires MPI, and may not be able to be run on Colab.\n```", "_____no_output_____" ], [ "# Distributed Variables\n\nAt times when you need to perform a computation using large input arrays, you may want to perform that computation in multiple processes, where each process operates on some subset of the input values. This may be done purely for performance reasons, or it may be necessary because the entire input will not fit in the memory of a single machine. In any case, this can be accomplished in OpenMDAO by declaring those inputs and outputs as distributed. By definition, a variable is distributed if each process contains only a part of the whole variable. Conversely, when a variable is not distributed (i.e., serial), each process contains a copy of the entire variable. A component that has at least one distributed variable can also be called a distributed component.\n\nWe’ve already seen that by using [src_indices](connect-with-src-indices), we can connect an input to only a subset of an output variable. By giving different values for src_indices in each MPI process, we can distribute computations on a distributed output across the processes. All of the scenarios that involve connecting distributed and serial variables are detailed in [Connections involving distributed variables](../working_with_groups/dist_serial.ipynb).", "_____no_output_____" ], [ "\n## Example: Simple Component with Distributed Input and Output\n\nThe following example shows how to create a simple component, *SimpleDistrib*, that takes a distributed variable as an input and computes a distributed output. The calculation is divided across the available processes, but the details of that division are not contained in the component. In fact, the input is sized based on it's connected source using the \"shape_by_conn\" argument.", "_____no_output_____" ] ], [ [ "%%px \n\nimport numpy as np\n\nimport openmdao.api as om\n\n\nclass SimpleDistrib(om.ExplicitComponent):\n\n def setup(self):\n\n # Distributed Input\n self.add_input('in_dist', shape_by_conn=True, distributed=True)\n\n # Distributed Output\n self.add_output('out_dist', copy_shape='in_dist', distributed=True)\n\n def compute(self, inputs, outputs):\n x = inputs['in_dist']\n\n # \"Computationally Intensive\" operation that we wish to parallelize.\n f_x = x**2 - 2.0*x + 4.0\n\n outputs['out_dist'] = f_x", "_____no_output_____" ] ], [ [ "In the next part of the example, we take the `SimpleDistrib` component, place it into a model, and run it. Suppose the vector of data we want to process has 7 elements. We have 4 processors available for computation, so if we distribute them as evenly as we can, 3 procs can handle 2 elements each, and the 4th processor can pick up the last one. OpenMDAO's utilities includes the `evenly_distrib_idxs` function which computes the sizes and offsets for all ranks. The sizes are used to determine how much of the array to allocate on any specific rank. The offsets are used to figure out where the local portion of the array starts, and in this example, is used to set the initial value properly. In this case, the initial value for the full distributed input \"in_dist\" is a vector of 7 values between 3.0 and 9.0, and each processor has a 1 or 2 element piece of it.", "_____no_output_____" ] ], [ [ "%%px\n\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\nfrom openmdao.utils.mpi import MPI\n\nsize = 7\n\nif MPI:\n comm = MPI.COMM_WORLD\n rank = comm.rank\n sizes, offsets = evenly_distrib_idxs(comm.size, size)\nelse:\n # When running in serial, the entire variable is on rank 0.\n rank = 0\n sizes = {rank : size}\n offsets = {rank : 0}\n\nprob = om.Problem()\nmodel = prob.model\n\n# Create a distributed source for the distributed input.\nivc = om.IndepVarComp()\nivc.add_output('x_dist', np.zeros(sizes[rank]), distributed=True)\n\nmodel.add_subsystem(\"indep\", ivc)\nmodel.add_subsystem(\"D1\", SimpleDistrib())\n\nmodel.connect('indep.x_dist', 'D1.in_dist')\n\nprob.setup()\n\n# Set initial values of distributed variable.\nx_dist_init = 3.0 + np.arange(size)[offsets[rank]:offsets[rank] + sizes[rank]]\nprob.set_val('indep.x_dist', x_dist_init)\n\nprob.run_model()\n\n# Values on each rank.\nfor var in ['indep.x_dist', 'D1.out_dist']:\n print(var, prob.get_val(var))\n \n# Full gathered values.\nfor var in ['indep.x_dist', 'D1.out_dist']:\n print(var, prob.get_val(var, get_remote=True))\nprint('')", "_____no_output_____" ], [ "%%px\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(prob.get_val(var, get_remote=True), np.array([7., 12., 19., 28., 39., 52., 67.]))", "_____no_output_____" ] ], [ [ "Note that we created a connection source 'x_dist' that passes its value to 'D1.in_dist'. OpenMDAO requires a source for non-constant inputs, and usually creates one automatically as an output of a component referred to as an 'Auto-IVC'. However, the automatic creation is not supported for distributed variables. We must manually create an `IndepVarComp` and connect it to our input. \n\nWhen using distributed variables, OpenMDAO can't always size the component inputs based on the shape of the connected source. In this example, the component determines its own split using `evenly_distrib_idxs`. This requires that the component know the full vector size, which is passed in via the option 'vec_size'.", "_____no_output_____" ] ], [ [ "%%px\n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\nfrom openmdao.utils.mpi import MPI\n\nclass SimpleDistrib(om.ExplicitComponent):\n\n def initialize(self):\n self.options.declare('vec_size', types=int, default=1,\n desc=\"Total size of vector.\")\n\n def setup(self):\n comm = self.comm\n rank = comm.rank\n\n size = self.options['vec_size']\n sizes, _ = evenly_distrib_idxs(comm.size, size)\n mysize = sizes[rank]\n\n # Distributed Input\n self.add_input('in_dist', np.ones(mysize, float), distributed=True)\n\n # Distributed Output\n self.add_output('out_dist', np.ones(mysize, float), distributed=True)\n\n def compute(self, inputs, outputs):\n x = inputs['in_dist']\n\n # \"Computationally Intensive\" operation that we wish to parallelize.\n f_x = x**2 - 2.0*x + 4.0\n\n outputs['out_dist'] = f_x\n\n\nsize = 7\n\nif MPI:\n comm = MPI.COMM_WORLD\n rank = comm.rank\n sizes, offsets = evenly_distrib_idxs(comm.size, size)\nelse:\n # When running in serial, the entire variable is on rank 0.\n rank = 0\n sizes = {rank : size}\n offsets = {rank : 0}\n\nprob = om.Problem()\nmodel = prob.model\n\n# Create a distributed source for the distributed input.\nivc = om.IndepVarComp()\nivc.add_output('x_dist', np.zeros(sizes[rank]), distributed=True)\n\nmodel.add_subsystem(\"indep\", ivc)\nmodel.add_subsystem(\"D1\", SimpleDistrib(vec_size=size))\n\nmodel.connect('indep.x_dist', 'D1.in_dist')\n\nprob.setup()\n\n# Set initial values of distributed variable.\nx_dist_init = 3.0 + np.arange(size)[offsets[rank]:offsets[rank] + sizes[rank]]\nprob.set_val('indep.x_dist', x_dist_init)\n\nprob.run_model()\n\n# Values on each rank.\nfor var in ['indep.x_dist', 'D1.out_dist']:\n print(var, prob.get_val(var))\n\n# Full gathered values.\nfor var in ['indep.x_dist', 'D1.out_dist']:\n print(var, prob.get_val(var, get_remote=True))\nprint('')", "_____no_output_____" ], [ "%%px\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(prob.get_val(var, get_remote=True), np.array([7., 12., 19., 28., 39., 52., 67.]))", "_____no_output_____" ] ], [ [ "\n## Example: Distributed I/O and a Serial Input\n\nOpenMDAO supports both serial and distributed I/O on the same component, so in this example, we expand the problem to include a serial input. In this case, the serial input also has a vector width of 7, but those values will be the same on each processor. This serial input is included in the computation by taking the vector sum and adding it to the distributed output.", "_____no_output_____" ] ], [ [ "%%px \n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\nfrom openmdao.utils.mpi import MPI\n\n\nclass MixedDistrib1(om.ExplicitComponent):\n\n def setup(self):\n\n # Distributed Input\n self.add_input('in_dist', shape_by_conn=True, distributed=True)\n\n # Serial Input\n self.add_input('in_serial', shape_by_conn=True)\n\n # Distributed Output\n self.add_output('out_dist', copy_shape='in_dist', distributed=True)\n\n def compute(self, inputs, outputs):\n x = inputs['in_dist']\n y = inputs['in_serial']\n\n # \"Computationally Intensive\" operation that we wish to parallelize.\n f_x = x**2 - 2.0*x + 4.0\n\n # This operation is repeated on all procs.\n f_y = y ** 0.5\n \n outputs['out_dist'] = f_x + np.sum(f_y)\n \nsize = 7\n\nif MPI:\n comm = MPI.COMM_WORLD\n rank = comm.rank\n sizes, offsets = evenly_distrib_idxs(comm.size, size)\nelse:\n # When running in serial, the entire variable is on rank 0.\n rank = 0\n sizes = {rank : size}\n offsets = {rank : 0}\n\nprob = om.Problem()\nmodel = prob.model\n\n# Create a distributed source for the distributed input.\nivc = om.IndepVarComp()\nivc.add_output('x_dist', np.zeros(sizes[rank]), distributed=True)\nivc.add_output('x_serial', np.zeros(size))\n\nmodel.add_subsystem(\"indep\", ivc)\nmodel.add_subsystem(\"D1\", MixedDistrib1())\n\nmodel.connect('indep.x_dist', 'D1.in_dist')\nmodel.connect('indep.x_serial', 'D1.in_serial')\n\nprob.setup()\n\n# Set initial values of distributed variable.\nx_dist_init = 3.0 + np.arange(size)[offsets[rank]:offsets[rank] + sizes[rank]]\nprob.set_val('indep.x_dist', x_dist_init)\n\n# Set initial values of serial variable.\nx_serial_init = 1.0 + 2.0*np.arange(size)\nprob.set_val('indep.x_serial', x_serial_init)\n\nprob.run_model()\n\n# Values on each rank.\nfor var in ['indep.x_dist', 'indep.x_serial', 'D1.out_dist']:\n print(var, prob.get_val(var))\n \n# Full gathered values.\nfor var in ['indep.x_dist', 'indep.x_serial', 'D1.out_dist']:\n print(var, prob.get_val(var, get_remote=True))\nprint('')", "_____no_output_____" ], [ "%%px\n\nassert_near_equal(prob.get_val(var, get_remote=True), np.array([24.53604616, 29.53604616, 36.53604616, 45.53604616, 56.53604616, 69.53604616, 84.53604616]), 1e-6)", "_____no_output_____" ] ], [ [ "## Example: Distributed I/O and a Serial Ouput\n\nYou can also create a component with a serial output and distributed outputs and inputs. This situation tends to be more tricky and usually requires you to performe some MPI operations in your component's `run` method. If the serial output is only a function of the serial inputs, then you can handle that variable just like you do on any other component. However, this example extends the previous component to include a serial output that is a function of both the serial and distributed inputs. In this case, it's a function of the sum of the square root of each element in the full distributed vector. Since the data is not all on any local processor, we use an MPI operation, in this case `Allreduce`, to make a summation across the distributed vector, and gather the answer back to each processor. The MPI operation and your implementation will vary, but consider this to be a general example.", "_____no_output_____" ] ], [ [ "%%px\n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\nfrom openmdao.utils.mpi import MPI\n\n\nclass MixedDistrib2(om.ExplicitComponent):\n\n def setup(self):\n\n # Distributed Input\n self.add_input('in_dist', shape_by_conn=True, distributed=True)\n\n # Serial Input\n self.add_input('in_serial', shape_by_conn=True)\n\n # Distributed Output\n self.add_output('out_dist', copy_shape='in_dist', distributed=True)\n \n # Serial Output\n self.add_output('out_serial', copy_shape='in_serial')\n\n def compute(self, inputs, outputs):\n x = inputs['in_dist']\n y = inputs['in_serial']\n\n # \"Computationally Intensive\" operation that we wish to parallelize.\n f_x = x**2 - 2.0*x + 4.0\n\n # These operations are repeated on all procs.\n f_y = y ** 0.5\n g_y = y**2 + 3.0*y - 5.0\n \n # Compute square root of our portion of the distributed input.\n g_x = x ** 0.5\n \n # Distributed output\n outputs['out_dist'] = f_x + np.sum(f_y)\n \n # Serial output\n if MPI and comm.size > 1:\n\n # We need to gather the summed values to compute the total sum over all procs.\n local_sum = np.array(np.sum(g_x))\n total_sum = local_sum.copy()\n self.comm.Allreduce(local_sum, total_sum, op=MPI.SUM)\n \n outputs['out_serial'] = g_y + total_sum\n else:\n # Recommended to make sure your code can run in serial too, for testing.\n outputs['out_serial'] = g_y + np.sum(g_x)\n \nsize = 7\n\nif MPI:\n comm = MPI.COMM_WORLD\n rank = comm.rank\n sizes, offsets = evenly_distrib_idxs(comm.size, size)\nelse:\n # When running in serial, the entire variable is on rank 0.\n rank = 0\n sizes = {rank : size}\n offsets = {rank : 0}\n\nprob = om.Problem()\nmodel = prob.model\n\n# Create a distributed source for the distributed input.\nivc = om.IndepVarComp()\nivc.add_output('x_dist', np.zeros(sizes[rank]), distributed=True)\nivc.add_output('x_serial', np.zeros(size))\n\nmodel.add_subsystem(\"indep\", ivc)\nmodel.add_subsystem(\"D1\", MixedDistrib2())\n\nmodel.connect('indep.x_dist', 'D1.in_dist')\nmodel.connect('indep.x_serial', 'D1.in_serial')\n\nprob.setup()\n\n# Set initial values of distributed variable.\nx_dist_init = 3.0 + np.arange(size)[offsets[rank]:offsets[rank] + sizes[rank]]\nprob.set_val('indep.x_dist', x_dist_init)\n\n# Set initial values of serial variable.\nx_serial_init = 1.0 + 2.0*np.arange(size)\nprob.set_val('indep.x_serial', x_serial_init)\n\nprob.run_model()\n\n# Values on each rank.\nfor var in ['indep.x_dist', 'indep.x_serial', 'D1.out_dist', 'D1.out_serial']:\n print(var, prob.get_val(var))\n \n# Full gathered values.\nfor var in ['indep.x_dist', 'indep.x_serial', 'D1.out_dist', 'D1.out_serial']:\n print(var, prob.get_val(var, get_remote=True))\nprint('')", "_____no_output_____" ], [ "%%px\n\nassert_near_equal(prob.get_val(var, get_remote=True), np.array([15.89178696, 29.89178696, 51.89178696, 81.89178696, 119.89178696, 165.89178696, 219.89178696]), 1e-6)", "_____no_output_____" ] ], [ [ "```{note}\nIn this example, we introduce a new component called an [IndepVarComp](indepvarcomp.ipynb). If you used OpenMDAO prior to version 3.2, then you are familiar with this component. It is used to define an independent variable.\n\nYou usually do not have to define these because OpenMDAO defines and uses them automatically for all unconnected inputs in your model. This automatically-created `IndepVarComp` is called an Auto-IVC.\n\nHowever, when we define a distributed input, we often use the “src_indices” attribute to determine the allocation of that input to the processors that the component sees. For some sets of these indices, it isn’t possible to easily determine the full size of the corresponding independent variable, and the *IndepVarComp* cannot be created automatically. So, for unconnected inputs on a distributed component, you must manually create one, as we did in this example.\n```\n\n# Derivatives with Distributed Variables\n\nIn the following examples, we show how to add analytic derivatives to the distributed examples given above. In most cases it is straighforward, but when you have a serial output and a distributed input, the [matrix-free](matrix-free-api) format is required.\n\n## Derivatives: Distributed I/O and a Serial Input\n\nIn this example, we have a distributed input, a distributed output, and a serial input. The derivative of 'out_dist' with respect to 'in_dict' has a diagonal Jacobian, so we use sparse declaration and each processor gives `declare_partials` the local number of rows and columns. The derivatives are verified against complex step using `check_totals` since our component is complex-safe.", "_____no_output_____" ] ], [ [ "%%px \n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\nfrom openmdao.utils.mpi import MPI\n\n\nclass MixedDistrib1(om.ExplicitComponent):\n\n def setup(self):\n\n # Distributed Input\n self.add_input('in_dist', shape_by_conn=True, distributed=True)\n\n # Serial Input\n self.add_input('in_serial', shape_by_conn=True)\n\n # Distributed Output\n self.add_output('out_dist', copy_shape='in_dist', distributed=True)\n\n def setup_partials(self):\n meta = self.get_io_metadata(metadata_keys=['shape'])\n local_size = meta['in_dist']['shape'][0]\n\n row_col_d = np.arange(local_size)\n\n self.declare_partials('out_dist', 'in_dist', rows=row_col_d, cols=row_col_d)\n self.declare_partials('out_dist', 'in_serial')\n\n def compute(self, inputs, outputs):\n x = inputs['in_dist']\n y = inputs['in_serial']\n\n # \"Computationally Intensive\" operation that we wish to parallelize.\n f_x = x**2 - 2.0*x + 4.0\n\n # This operation is repeated on all procs.\n f_y = y ** 0.5\n\n outputs['out_dist'] = f_x + np.sum(f_y)\n\n def compute_partials(self, inputs, partials):\n x = inputs['in_dist']\n y = inputs['in_serial']\n size = len(y)\n local_size = len(x)\n\n partials['out_dist', 'in_dist'] = 2.0 * x - 2.0\n\n df_dy = 0.5 / y ** 0.5\n partials['out_dist', 'in_serial'] = np.tile(df_dy, local_size).reshape((local_size, size))\n\n\nsize = 7\n\nif MPI:\n comm = MPI.COMM_WORLD\n rank = comm.rank\n sizes, offsets = evenly_distrib_idxs(comm.size, size)\nelse:\n # When running in serial, the entire variable is on rank 0.\n rank = 0\n sizes = {rank : size}\n offsets = {rank : 0}\n\nprob = om.Problem()\nmodel = prob.model\n\n# Create a distributed source for the distributed input.\nivc = om.IndepVarComp()\nivc.add_output('x_dist', np.zeros(sizes[rank]), distributed=True)\nivc.add_output('x_serial', np.zeros(size))\n\nmodel.add_subsystem(\"indep\", ivc)\nmodel.add_subsystem(\"D1\", MixedDistrib1())\n\nmodel.connect('indep.x_dist', 'D1.in_dist')\nmodel.connect('indep.x_serial', 'D1.in_serial')\n\nmodel.add_design_var('indep.x_serial')\nmodel.add_design_var('indep.x_dist')\nmodel.add_objective('D1.out_dist')\n\nprob.setup(force_alloc_complex=True)\n\n# Set initial values of distributed variable.\nx_dist_init = 3.0 + np.arange(size)[offsets[rank]:offsets[rank] + sizes[rank]]\nprob.set_val('indep.x_dist', x_dist_init)\n\n# Set initial values of serial variable.\nx_serial_init = 1.0 + 2.0*np.arange(size)\nprob.set_val('indep.x_serial', x_serial_init)\n\nprob.run_model()\n\nif rank > 0:\n prob.check_totals(method='cs', out_stream=None)\nelse:\n prob.check_totals(method='cs')\n", "_____no_output_____" ], [ "%%px\n\ntotals = prob.check_totals(method='cs', out_stream=None)\nfor key, val in totals.items():\n assert_near_equal(val['rel error'][0], 0.0, 1e-6)", "_____no_output_____" ] ], [ [ "## Derivatives: Distributed I/O and a Serial Output\n\nIf you have a component with distributed inputs and a serial output, then the standard `compute_partials` API will not work for specifying the derivatives. You will need to use the matrix-free API with `compute_jacvec_product`, which is described in the feature document for [ExplicitComponent](explicit_component.ipynb)\n\nComputing the matrix-vector product for the derivative of the serial output with respect to a distributed input will require you to use MPI operations to gather the required parts of the Jacobian to all processors. The following example shows how to implement derivatives on the earlier `MixedDistrib2` component.", "_____no_output_____" ] ], [ [ "%%px\n\n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\nfrom openmdao.utils.mpi import MPI\n\n\nclass MixedDistrib2(om.ExplicitComponent):\n\n def setup(self):\n\n # Distributed Input\n self.add_input('in_dist', shape_by_conn=True, distributed=True)\n\n # Serial Input\n self.add_input('in_serial', shape_by_conn=True)\n\n # Distributed Output\n self.add_output('out_dist', copy_shape='in_dist', distributed=True)\n\n # Serial Output\n self.add_output('out_serial', copy_shape='in_serial')\n\n def compute(self, inputs, outputs):\n x = inputs['in_dist']\n y = inputs['in_serial']\n\n # \"Computationally Intensive\" operation that we wish to parallelize.\n f_x = x**2 - 2.0*x + 4.0\n\n # These operations are repeated on all procs.\n f_y = y ** 0.5\n g_y = y**2 + 3.0*y - 5.0\n\n # Compute square root of our portion of the distributed input.\n g_x = x ** 0.5\n\n # Distributed output\n outputs['out_dist'] = f_x + np.sum(f_y)\n\n # Serial output\n if MPI and comm.size > 1:\n\n # We need to gather the summed values to compute the total sum over all procs.\n local_sum = np.array(np.sum(g_x))\n total_sum = local_sum.copy()\n self.comm.Allreduce(local_sum, total_sum, op=MPI.SUM)\n outputs['out_serial'] = g_y + total_sum\n else:\n # Recommended to make sure your code can run in serial too, for testing.\n outputs['out_serial'] = g_y + np.sum(g_x)\n\n def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode):\n x = inputs['in_dist']\n y = inputs['in_serial']\n\n df_dx = 2.0 * x - 2.0\n df_dy = 0.5 / y ** 0.5\n dg_dx = 0.5 / x ** 0.5\n dg_dy = 2.0 * y + 3.0\n\n local_size = len(x)\n size = len(y)\n\n if mode == 'fwd':\n if 'out_dist' in d_outputs:\n if 'in_dist' in d_inputs:\n d_outputs['out_dist'] += df_dx * d_inputs['in_dist']\n if 'in_serial' in d_inputs:\n d_outputs['out_dist'] += np.tile(df_dy, local_size).reshape((local_size, size)).dot(d_inputs['in_serial'])\n if 'out_serial' in d_outputs:\n if 'in_dist' in d_inputs:\n if MPI and comm.size > 1:\n deriv = np.tile(dg_dx, size).reshape((size, local_size)).dot(d_inputs['in_dist'])\n deriv_sum = np.zeros(deriv.size)\n self.comm.Allreduce(deriv, deriv_sum, op=MPI.SUM)\n d_outputs['out_serial'] += deriv_sum\n else:\n # Recommended to make sure your code can run in serial too, for testing.\n d_outputs['out_serial'] += np.tile(dg_dx, local_size).reshape((local_size, size)).dot(d_inputs['in_dist'])\n if 'in_serial' in d_inputs:\n d_outputs['out_serial'] += dg_dy * d_inputs['in_serial']\n\n else:\n if 'out_dist' in d_outputs:\n if 'in_dist' in d_inputs:\n d_inputs['in_dist'] += df_dx * d_outputs['out_dist']\n if 'in_serial' in d_inputs:\n d_inputs['in_serial'] += np.tile(df_dy, local_size).reshape((local_size, size)).dot(d_outputs['out_dist'])\n if 'out_serial' in d_outputs:\n if 'out_serial' in d_outputs:\n if 'in_dist' in d_inputs:\n if MPI and comm.size > 1:\n deriv = np.tile(dg_dx, size).reshape((size, local_size)).dot(d_outputs['out_serial'])\n deriv_sum = np.zeros(deriv.size)\n self.comm.Allreduce(deriv, deriv_sum, op=MPI.SUM)\n d_inputs['in_dist'] += deriv_sum\n else:\n # Recommended to make sure your code can run in serial too, for testing.\n d_inputs['in_dist'] += np.tile(dg_dx, local_size).reshape((local_size, size)).dot(d_outputs['out_serial']) \n if 'in_serial' in d_inputs:\n d_inputs['in_serial'] += dg_dy * d_outputs['out_serial']\n\n\nsize = 7\n\nif MPI:\n comm = MPI.COMM_WORLD\n rank = comm.rank\n sizes, offsets = evenly_distrib_idxs(comm.size, size)\nelse:\n # When running in serial, the entire variable is on rank 0.\n rank = 0\n sizes = {rank : size}\n offsets = {rank : 0}\n\nprob = om.Problem()\nmodel = prob.model\n\n# Create a distributed source for the distributed input.\nivc = om.IndepVarComp()\nivc.add_output('x_dist', np.zeros(sizes[rank]), distributed=True)\nivc.add_output('x_serial', np.zeros(size))\n\nmodel.add_subsystem(\"indep\", ivc)\nmodel.add_subsystem(\"D1\", MixedDistrib2())\n\nmodel.connect('indep.x_dist', 'D1.in_dist')\nmodel.connect('indep.x_serial', 'D1.in_serial')\n\nmodel.add_design_var('indep.x_serial')\nmodel.add_design_var('indep.x_dist')\nmodel.add_constraint('D1.out_dist', lower=0.0)\nmodel.add_constraint('D1.out_serial', lower=0.0)\n\nprob.setup(force_alloc_complex=True)\n\n# Set initial values of distributed variable.\nx_dist_init = 3.0 + np.arange(size)[offsets[rank]:offsets[rank] + sizes[rank]]\nprob.set_val('indep.x_dist', x_dist_init)\n\n# Set initial values of serial variable.\nx_serial_init = 1.0 + 2.0*np.arange(size)\nprob.set_val('indep.x_serial', x_serial_init)\n\nprob.run_model()\n\nif rank > 0:\n prob.check_totals(method='cs', out_stream=None)\nelse:\n prob.check_totals(method='cs')", "_____no_output_____" ], [ "%%px\n\ntotals = prob.check_totals(method='cs', out_stream=None)\nfor key, val in totals.items():\n assert_near_equal(val['rel error'][0], 0.0, 1e-6)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d01c8207d079ae3a9fe28c732018862ee4168d48
55,037
ipynb
Jupyter Notebook
module4-logistic-regression/LS_DS_214.ipynb
cedro-gasque/DS-Unit-2-Linear-Models
48f654d5b9b6954bbd7ebd523c0f9479ce1b8ac1
[ "MIT" ]
null
null
null
module4-logistic-regression/LS_DS_214.ipynb
cedro-gasque/DS-Unit-2-Linear-Models
48f654d5b9b6954bbd7ebd523c0f9479ce1b8ac1
[ "MIT" ]
null
null
null
module4-logistic-regression/LS_DS_214.ipynb
cedro-gasque/DS-Unit-2-Linear-Models
48f654d5b9b6954bbd7ebd523c0f9479ce1b8ac1
[ "MIT" ]
null
null
null
40.98064
11,600
0.64711
[ [ [ "Lambda School Data Science\n\n*Unit 2, Sprint 1, Module 4*\n\n---\n\n# Logistic Regression\n- do train/validate/test split\n- begin with baselines for classification\n- express and explain the intuition and interpretation of Logistic Regression\n- use sklearn.linear_model.LogisticRegression to fit and interpret Logistic Regression models\n\nLogistic regression is the baseline for classification models, as well as a handy way to predict probabilities (since those too live in the unit interval). While relatively simple, it is also the foundation for more sophisticated classification techniques such as neural networks (many of which can effectively be thought of as networks of logistic models).", "_____no_output_____" ], [ "### Setup\n\nRun the code cell below. You can work locally (follow the [local setup instructions](https://lambdaschool.github.io/ds/unit2/local/)) or on Colab.\n\nLibraries:\n- category_encoders\n- numpy\n- pandas\n- scikit-learn", "_____no_output_____" ] ], [ [ "%%capture\nimport sys\n\n# If you're on Colab:\nif 'google.colab' in sys.modules:\n DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Linear-Models/master/data/'\n !pip install category_encoders==2.*\n\n# If you're working locally:\nelse:\n DATA_PATH = '../data/'", "_____no_output_____" ] ], [ [ "# Do train/validate/test split", "_____no_output_____" ], [ "## Overview", "_____no_output_____" ], [ "### Predict Titanic survival 🚢\n\nKaggle is a platform for machine learning competitions. [Kaggle has used the Titanic dataset](https://www.kaggle.com/c/titanic/data) for their most popular \"getting started\" competition. \n\nKaggle splits the data into train and test sets for participants. Let's load both:", "_____no_output_____" ] ], [ [ "import pandas as pd\ntrain = pd.read_csv(DATA_PATH+'titanic/train.csv')\ntest = pd.read_csv(DATA_PATH+'titanic/test.csv')", "_____no_output_____" ] ], [ [ "Notice that the train set has one more column than the test set:", "_____no_output_____" ] ], [ [ "train.shape, test.shape", "_____no_output_____" ] ], [ [ "Which column is in train but not test? The target!", "_____no_output_____" ] ], [ [ "set(train.columns) - set(test.columns)", "_____no_output_____" ] ], [ [ "### Why doesn't Kaggle give you the target for the test set?\n\n#### Rachel Thomas, [How (and why) to create a good validation set](https://www.fast.ai/2017/11/13/validation-sets/)\n\n> One great thing about Kaggle competitions is that they force you to think about validation sets more rigorously (in order to do well). For those who are new to Kaggle, it is a platform that hosts machine learning competitions. Kaggle typically breaks the data into two sets you can download:\n>\n> 1. a **training set**, which includes the _independent variables,_ as well as the _dependent variable_ (what you are trying to predict).\n>\n> 2. a **test set**, which just has the _independent variables._ You will make predictions for the test set, which you can submit to Kaggle and get back a score of how well you did.\n>\n> This is the basic idea needed to get started with machine learning, but to do well, there is a bit more complexity to understand. **You will want to create your own training and validation sets (by splitting the Kaggle “training” data). You will just use your smaller training set (a subset of Kaggle’s training data) for building your model, and you can evaluate it on your validation set (also a subset of Kaggle’s training data) before you submit to Kaggle.**\n>\n> The most important reason for this is that Kaggle has split the test data into two sets: for the public and private leaderboards. The score you see on the public leaderboard is just for a subset of your predictions (and you don’t know which subset!). How your predictions fare on the private leaderboard won’t be revealed until the end of the competition. The reason this is important is that you could end up overfitting to the public leaderboard and you wouldn’t realize it until the very end when you did poorly on the private leaderboard. Using a good validation set can prevent this. You can check if your validation set is any good by seeing if your model has similar scores on it to compared with on the Kaggle test set. ...\n>\n> Understanding these distinctions is not just useful for Kaggle. In any predictive machine learning project, you want your model to be able to perform well on new data.", "_____no_output_____" ], [ "### 2-way train/test split is not enough\n\n#### Hastie, Tibshirani, and Friedman, [The Elements of Statistical Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/), Chapter 7: Model Assessment and Selection\n\n> If we are in a data-rich situation, the best approach is to randomly divide the dataset into three parts: a training set, a validation set, and a test set. The training set is used to fit the models; the validation set is used to estimate prediction error for model selection; the test set is used for assessment of the generalization error of the final chosen model. Ideally, the test set should be kept in a \"vault,\" and be brought out only at the end of the data analysis. Suppose instead that we use the test-set repeatedly, choosing the model with the smallest test-set error. Then the test set error of the final chosen model will underestimate the true test error, sometimes substantially.\n\n#### Andreas Mueller and Sarah Guido, [Introduction to Machine Learning with Python](https://books.google.com/books?id=1-4lDQAAQBAJ&pg=PA270)\n\n> The distinction between the training set, validation set, and test set is fundamentally important to applying machine learning methods in practice. Any choices made based on the test set accuracy \"leak\" information from the test set into the model. Therefore, it is important to keep a separate test set, which is only used for the final evaluation. It is good practice to do all exploratory analysis and model selection using the combination of a training and a validation set, and reserve the test set for a final evaluation - this is even true for exploratory visualization. Strictly speaking, evaluating more than one model on the test set and choosing the better of the two will result in an overly optimistic estimate of how accurate the model is.\n\n#### Hadley Wickham, [R for Data Science](https://r4ds.had.co.nz/model-intro.html#hypothesis-generation-vs.hypothesis-confirmation)\n\n> There is a pair of ideas that you must understand in order to do inference correctly:\n>\n> 1. Each observation can either be used for exploration or confirmation, not both.\n>\n> 2. You can use an observation as many times as you like for exploration, but you can only use it once for confirmation. As soon as you use an observation twice, you’ve switched from confirmation to exploration.\n>\n> This is necessary because to confirm a hypothesis you must use data independent of the data that you used to generate the hypothesis. Otherwise you will be over optimistic. There is absolutely nothing wrong with exploration, but you should never sell an exploratory analysis as a confirmatory analysis because it is fundamentally misleading.\n>\n> If you are serious about doing an confirmatory analysis, one approach is to split your data into three pieces before you begin the analysis.\n\n\n#### Sebastian Raschka, [Model Evaluation](https://sebastianraschka.com/blog/2018/model-evaluation-selection-part4.html)\n\n> Since “a picture is worth a thousand words,” I want to conclude with a figure (shown below) that summarizes my personal recommendations ...\n\n<img src=\"https://sebastianraschka.com/images/blog/2018/model-evaluation-selection-part4/model-eval-conclusions.jpg\" width=\"600\">\n\nUsually, we want to do **\"Model selection (hyperparameter optimization) _and_ performance estimation.\"** (The green box in the diagram.)\n\nTherefore, we usually do **\"3-way holdout method (train/validation/test split)\"** or **\"cross-validation with independent test set.\"**", "_____no_output_____" ], [ "### What's the difference between Training, Validation, and Testing sets?\n\n#### Brandon Rohrer, [Training, Validation, and Testing Data Sets](https://end-to-end-machine-learning.teachable.com/blog/146320/training-validation-testing-data-sets)\n\n> The validation set is for adjusting a model's hyperparameters. The testing data set is the ultimate judge of model performance.\n>\n> Testing data is what you hold out until very last. You only run your model on it once. You don’t make any changes or adjustments to your model after that. ...", "_____no_output_____" ], [ "## Follow Along\n\n> You will want to create your own training and validation sets (by splitting the Kaggle “training” data).\n\nDo this, using the [sklearn.model_selection.train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function:", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "train.shape, test.shape", "_____no_output_____" ], [ "train, val = train_test_split(train, random_state=28)", "_____no_output_____" ], [ "train.shape, val.shape, test.shape", "_____no_output_____" ] ], [ [ "## Challenge", "_____no_output_____" ], [ "For your assignment, you'll do a 3-way train/validate/test split.\n\nThen next sprint, you'll begin to participate in a private Kaggle challenge, just for your cohort! \n\nYou will be provided with data split into 2 sets: training and test. You will create your own training and validation sets, by splitting the Kaggle \"training\" data, so you'll end up with 3 sets total.", "_____no_output_____" ], [ "# Begin with baselines for classification", "_____no_output_____" ], [ "## Overview", "_____no_output_____" ], [ "We'll begin with the **majority class baseline.**\n\n[Will Koehrsen](https://twitter.com/koehrsen_will/status/1088863527778111488)\n\n> A baseline for classification can be the most common class in the training dataset.\n\n[*Data Science for Business*](https://books.google.com/books?id=4ZctAAAAQBAJ&pg=PT276), Chapter 7.3: Evaluation, Baseline Performance, and Implications for Investments in Data\n\n> For classification tasks, one good baseline is the _majority classifier,_ a naive classifier that always chooses the majority class of the training dataset (see Note: Base rate in Holdout Data and Fitting Graphs). This may seem like advice so obvious it can be passed over quickly, but it is worth spending an extra moment here. There are many cases where smart, analytical people have been tripped up in skipping over this basic comparison. For example, an analyst may see a classification accuracy of 94% from her classifier and conclude that it is doing fairly well—when in fact only 6% of the instances are positive. So, the simple majority prediction classifier also would have an accuracy of 94%. ", "_____no_output_____" ], [ "## Follow Along", "_____no_output_____" ], [ "Determine majority class", "_____no_output_____" ] ], [ [ "target = 'Survived'\ny_train = train[target]\ny_train.value_counts()", "_____no_output_____" ] ], [ [ "What if we guessed the majority class for every prediction?", "_____no_output_____" ] ], [ [ "y_pred = y_train.apply(lambda x : 0)", "_____no_output_____" ] ], [ [ "#### Use a classification metric: accuracy\n\n[Classification metrics are different from regression metrics!](https://scikit-learn.org/stable/modules/model_evaluation.html)\n- Don't use _regression_ metrics to evaluate _classification_ tasks.\n- Don't use _classification_ metrics to evaluate _regression_ tasks.\n\n[Accuracy](https://scikit-learn.org/stable/modules/model_evaluation.html#accuracy-score) is a common metric for classification. Accuracy is the [\"proportion of correct classifications\"](https://en.wikipedia.org/wiki/Confusion_matrix): the number of correct predictions divided by the total number of predictions.", "_____no_output_____" ], [ "What is the baseline accuracy if we guessed the majority class for every prediction?", "_____no_output_____" ] ], [ [ "from sklearn.metrics import accuracy_score", "_____no_output_____" ], [ "accuracy_score(y_train, y_pred)", "_____no_output_____" ], [ "train[target].value_counts(normalize=True)", "_____no_output_____" ], [ "y_val = val[target]\ny_val\ny_pred = [0] * len(y_val)\naccuracy_score(y_val, y_pred)", "_____no_output_____" ] ], [ [ "## Challenge", "_____no_output_____" ], [ "In your assignment, your Sprint Challenge, and your upcoming Kaggle challenge, you'll begin with the majority class baseline. How quickly can you beat this baseline?", "_____no_output_____" ], [ "# Express and explain the intuition and interpretation of Logistic Regression\n", "_____no_output_____" ], [ "## Overview\n\nTo help us get an intuition for *Logistic* Regression, let's start by trying *Linear* Regression instead, and see what happens...", "_____no_output_____" ], [ "## Follow Along", "_____no_output_____" ], [ "### Linear Regression?", "_____no_output_____" ] ], [ [ "train.describe()", "_____no_output_____" ], [ "# 1. Import estimator class\nfrom sklearn.linear_model import LinearRegression\n\n# 2. Instantiate this class\nlinear_reg = LinearRegression()\n\n# 3. Arrange X feature matrices (already did y target vectors)\nfeatures = ['Pclass', 'Age', 'Fare']\nX_train = train[features]\nX_val = val[features]\n\n# Impute missing values\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer()\nX_train_imputed = imputer.fit_transform(X_train)\nX_val_imputed = imputer.transform(X_val)\n\n# 4. Fit the model\nlinear_reg.fit(X_train_imputed, y_train)\n\n# 5. Apply the model to new data.\n# The predictions look like this ...\nlinear_reg.predict(X_val_imputed)", "_____no_output_____" ], [ "# Get coefficients\npd.Series(linear_reg.coef_, features)", "_____no_output_____" ], [ "test_case = [[1, 5, 500]] # 1st class, 5-year old, Rich\nlinear_reg.predict(test_case)", "_____no_output_____" ] ], [ [ "### Logistic Regression!", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression\n\nlog_reg = LogisticRegression(solver='lbfgs')\nlog_reg.fit(X_train_imputed, y_train)\nprint('Validation Accuracy', log_reg.score(X_val_imputed, y_val))", "Validation Accuracy 0.7219730941704036\n" ], [ "# The predictions look like this\nlog_reg.predict(X_val_imputed)", "_____no_output_____" ], [ "log_reg.predict(test_case)", "_____no_output_____" ], [ "log_reg.predict_proba(test_case)", "_____no_output_____" ], [ "# What's the math?\nlog_reg.coef_", "_____no_output_____" ], [ "log_reg.intercept_", "_____no_output_____" ], [ "# The logistic sigmoid \"squishing\" function, implemented to accept numpy arrays\nimport numpy as np\n\ndef sigmoid(x):\n return 1 / (1 + np.e**(-x))", "_____no_output_____" ], [ "sigmoid(log_reg.intercept_ + np.dot(log_reg.coef_, np.transpose(test_case)))", "_____no_output_____" ], [ "log_reg.coef_", "_____no_output_____" ], [ "test_case", "_____no_output_____" ], [ "sigmoid()", "_____no_output_____" ] ], [ [ "So, clearly a more appropriate model in this situation! For more on the math, [see this Wikipedia example](https://en.wikipedia.org/wiki/Logistic_regression#Probability_of_passing_an_exam_versus_hours_of_study).", "_____no_output_____" ], [ "# Use sklearn.linear_model.LogisticRegression to fit and interpret Logistic Regression models", "_____no_output_____" ], [ "## Overview\n\nNow that we have more intuition and interpretation of Logistic Regression, let's use it within a realistic, complete scikit-learn workflow, with more features and transformations.", "_____no_output_____" ], [ "## Follow Along\n\nSelect these features: `['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']`\n\n(Why shouldn't we include the `Name` or `Ticket` features? What would happen here?) \n\nFit this sequence of transformers & estimator:\n\n- [category_encoders.one_hot.OneHotEncoder](https://contrib.scikit-learn.org/categorical-encoding/onehot.html)\n- [sklearn.impute.SimpleImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html)\n- [sklearn.preprocessing.StandardScaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html)\n- [sklearn.linear_model.LogisticRegressionCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegressionCV.html)\n\nGet validation accuracy.", "_____no_output_____" ] ], [ [ "features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']\ntarget = 'Survived'\n\nX_train = train[features]\ny_train = train[target]\nX_val = val[features]\ny_val = val[target]\n\nX_train.shape, y_train.shape, X_val.shape, y_val.shape", "_____no_output_____" ], [ "import category_encoders as ce\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegressionCV", "_____no_output_____" ], [ "encoder = ce.OneHotEncoder(use_cat_names=True)\nX_train_encoded = encoder.fit_transform(X_train)", "_____no_output_____" ], [ "X_val_encoded = encoder.transform(X_val)", "_____no_output_____" ], [ "imputer = SimpleImputer(strategy='mean')\nX_train_imputed = imputer.fit_transform(X_train_encoded)\nX_val_imputed = imputer.transform(X_val_encoded)", "_____no_output_____" ], [ "scaler = StandardScaler()\nX_train_scaled = scaler.fit_transform(X_train_imputed)\nX_val_scaled = scaler.transform(X_val_imputed)", "_____no_output_____" ], [ "model = LogisticRegressionCV()\nmodel.fit(X_train_scaled, y_train)", "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_split.py:1978: FutureWarning: The default value of cv will change from 3 to 5 in version 0.22. Specify it explicitly to silence this warning.\n warnings.warn(CV_WARNING, FutureWarning)\n" ], [ "y_pred = model.predict(X_val_scaled)\naccuracy_score(y_val, y_pred)", "_____no_output_____" ], [ "print('Validation Accuracy:', model.score(X_val_scaled, y_val))", "Validation Accuracy: 0.7802690582959642\n" ] ], [ [ "Plot coefficients:", "_____no_output_____" ] ], [ [ "%matplotlib inline\ncoefficients = pd.Series(model.coef_[0], X_train_encoded.columns)\ncoefficients.sort_values().plot.barh();", "_____no_output_____" ] ], [ [ "Generate [Kaggle](https://www.kaggle.com/c/titanic) submission:", "_____no_output_____" ], [ "## Challenge\n\nYou'll use Logistic Regression for your assignment, your Sprint Challenge, and optionally for your first model in our Kaggle challenge!", "_____no_output_____" ], [ "# Review\n\nFor your assignment, you'll use a [**dataset of 400+ burrito reviews**](https://srcole.github.io/100burritos/). How accurately can you predict whether a burrito is rated 'Great'?\n\n> We have developed a 10-dimensional system for rating the burritos in San Diego. ... Generate models for what makes a burrito great and investigate correlations in its dimensions.\n\n- Do train/validate/test split. Train on reviews from 2016 & earlier. Validate on 2017. Test on 2018 & later.\n- Begin with baselines for classification.\n- Use scikit-learn for logistic regression.\n- Get your model's validation accuracy. (Multiple times if you try multiple iterations.)\n- Get your model's test accuracy. (One time, at the end.)\n- Commit your notebook to your fork of the GitHub repo.\n- Watch Aaron's [video #1](https://www.youtube.com/watch?v=pREaWFli-5I) (12 minutes) & [video #2](https://www.youtube.com/watch?v=bDQgVt4hFgY) (9 minutes) to learn about the mathematics of Logistic Regression.", "_____no_output_____" ], [ "# Sources\n- Brandon Rohrer, [Training, Validation, and Testing Data Sets](https://end-to-end-machine-learning.teachable.com/blog/146320/training-validation-testing-data-sets)\n- Hadley Wickham, [R for Data Science](https://r4ds.had.co.nz/model-intro.html#hypothesis-generation-vs.hypothesis-confirmation), Hypothesis generation vs. hypothesis confirmation\n- Hastie, Tibshirani, and Friedman, [The Elements of Statistical Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/), Chapter 7: Model Assessment and Selection\n- Mueller and Guido, [Introduction to Machine Learning with Python](https://books.google.com/books?id=1-4lDQAAQBAJ&pg=PA270), Chapter 5.2.2: The Danger of Overfitting the Parameters and the Validation Set\n- Provost and Fawcett, [Data Science for Business](https://books.google.com/books?id=4ZctAAAAQBAJ&pg=PT276), Chapter 7.3: Evaluation, Baseline Performance, and Implications for Investments in Data\n- Rachel Thomas, [How (and why) to create a good validation set](https://www.fast.ai/2017/11/13/validation-sets/)\n- Sebastian Raschka, [Model Evaluation](https://sebastianraschka.com/blog/2018/model-evaluation-selection-part4.html)\n- Will Koehrsen, [\"A baseline for classification can be the most common class in the training dataset.\"](https://twitter.com/koehrsen_will/status/1088863527778111488)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
d01c905782e7d69d6d47044c0533a30eec32d7d8
7,432
ipynb
Jupyter Notebook
torchbenchmark/models/pytorch_struct/notebooks/Unsupervised_CFG.ipynb
ramiro050/benchmark
0fdd791d7b23b66a2f74e16349efc3add2b66aef
[ "BSD-3-Clause" ]
1,063
2019-08-29T09:56:44.000Z
2022-03-30T03:35:39.000Z
torchbenchmark/models/pytorch_struct/notebooks/Unsupervised_CFG.ipynb
ramiro050/benchmark
0fdd791d7b23b66a2f74e16349efc3add2b66aef
[ "BSD-3-Clause" ]
72
2019-08-29T14:24:01.000Z
2022-02-11T18:24:40.000Z
torchbenchmark/models/pytorch_struct/notebooks/Unsupervised_CFG.ipynb
ramiro050/benchmark
0fdd791d7b23b66a2f74e16349efc3add2b66aef
[ "BSD-3-Clause" ]
84
2019-09-01T04:10:20.000Z
2022-03-22T04:51:37.000Z
30.089069
250
0.427207
[ [ [ "<a href=\"https://colab.research.google.com/github/harvardnlp/pytorch-struct/blob/master/notebooks/Unsupervised_CFG.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!pip install -qqq torchtext -qqq pytorch-transformers dgl\n!pip install -qqqU git+https://github.com/harvardnlp/pytorch-struct", " Building wheel for torch-struct (setup.py) ... \u001b[?25l\u001b[?25hdone\n" ], [ "import torchtext\nimport torch\nfrom torch_struct import SentCFG\nfrom torch_struct.networks import NeuralCFG\nimport torch_struct.data", "_____no_output_____" ], [ "# Download and the load default data.\nWORD = torchtext.data.Field(include_lengths=True)\nUD_TAG = torchtext.data.Field(init_token=\"<bos>\", eos_token=\"<eos>\", include_lengths=True)\n\n# Download and the load default data.\ntrain, val, test = torchtext.datasets.UDPOS.splits(\n fields=(('word', WORD), ('udtag', UD_TAG), (None, None)), \n filter_pred=lambda ex: 5 < len(ex.word) < 30\n)\n\nWORD.build_vocab(train.word, min_freq=3)\nUD_TAG.build_vocab(train.udtag)\ntrain_iter = torch_struct.data.TokenBucket(train, \n batch_size=200,\n device=\"cuda:0\")\n", "_____no_output_____" ], [ "H = 256\nT = 30\nNT = 30\nmodel = NeuralCFG(len(WORD.vocab), T, NT, H)\nmodel.cuda()\nopt = torch.optim.Adam(model.parameters(), lr=0.001, betas=[0.75, 0.999])", "_____no_output_____" ], [ "def train():\n #model.train()\n losses = []\n for epoch in range(10):\n for i, ex in enumerate(train_iter):\n opt.zero_grad()\n words, lengths = ex.word \n N, batch = words.shape\n words = words.long()\n params = model(words.cuda().transpose(0, 1))\n dist = SentCFG(params, lengths=lengths)\n loss = dist.partition.mean()\n (-loss).backward()\n losses.append(loss.detach())\n torch.nn.utils.clip_grad_norm_(model.parameters(), 3.0)\n opt.step()\n\n if i % 100 == 1: \n print(-torch.tensor(losses).mean(), words.shape)\n losses = []", "_____no_output_____" ], [ "train()", "tensor(52.3219) torch.Size([29, 18])\n" ], [ "for i, ex in enumerate(train_iter):\n opt.zero_grad()\n words, lengths = ex.word \n\n N, batch = words.shape\n words = words.long()\n params = terms(words.transpose(0, 1)), rules(batch), roots(batch)\n\n tree = CKY(MaxSemiring).marginals(params, lengths=lengths, _autograd=True)\n print(tree)\n break", "_____no_output_____" ], [ "def split(spans):\n batch, N = spans.shape[:2]\n splits = []\n for b in range(batch):\n cover = spans[b].nonzero()\n left = {i: [] for i in range(N)}\n right = {i: [] for i in range(N)}\n batch_split = {}\n for i in range(cover.shape[0]):\n i, j, A = cover[i].tolist()\n left[i].append((A, j, j - i + 1))\n right[j].append((A, i, j - i + 1))\n for i in range(cover.shape[0]):\n i, j, A = cover[i].tolist()\n B = None\n for B_p, k, a_span in left[i]:\n for C_p, k_2, b_span in right[j]:\n if k_2 == k + 1 and a_span + b_span == j - i + 1:\n B, C = B_p, C_p\n k_final = k\n break\n if j > i:\n batch_split[(i, j)] =k\n splits.append(batch_split)\n return splits ", "_____no_output_____" ], [ "splits = split(spans)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01c95a1d871718d1fb4562d08b7d73418180b99
25,230
ipynb
Jupyter Notebook
LearningOnMarkedData/week2/sklearn.linear_model_part2.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
e82e772df2f4aec162cb34ac6127df10d14a625a
[ "MIT" ]
null
null
null
LearningOnMarkedData/week2/sklearn.linear_model_part2.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
e82e772df2f4aec162cb34ac6127df10d14a625a
[ "MIT" ]
null
null
null
LearningOnMarkedData/week2/sklearn.linear_model_part2.ipynb
ishatserka/MachineLearningAndDataAnalysisCoursera
e82e772df2f4aec162cb34ac6127df10d14a625a
[ "MIT" ]
null
null
null
50.159046
11,056
0.752517
[ [ [ "# Sklearn", "_____no_output_____" ], [ "## sklearn.linear_model", "_____no_output_____" ] ], [ [ "from matplotlib.colors import ListedColormap\nfrom sklearn import cross_validation, datasets, linear_model, metrics\n\nimport numpy as np", "D:\\Education\\GitHub\\Coursera\\MachineLearningAndDataAnalysisCoursera\\venv\\lib\\site-packages\\sklearn\\cross_validation.py:41: 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" ], [ "%pylab inline", "Populating the interactive namespace from numpy and matplotlib\n" ] ], [ [ "### Линейная регрессия", "_____no_output_____" ], [ "#### Генерация данных", "_____no_output_____" ] ], [ [ "data, target, coef = datasets.make_regression(n_features = 2, n_informative = 1, n_targets = 1, \n noise = 5., coef = True, random_state = 2)", "_____no_output_____" ], [ "pylab.scatter(list(map(lambda x:x[0], data)), target, color='r')\npylab.scatter(list(map(lambda x:x[1], data)), target, color='b')", "_____no_output_____" ], [ "train_data, test_data, train_labels, test_labels = cross_validation.train_test_split(data, target, \n test_size = 0.3)", "_____no_output_____" ] ], [ [ "#### LinearRegression", "_____no_output_____" ] ], [ [ "linear_regressor = linear_model.LinearRegression()\nlinear_regressor.fit(train_data, train_labels)\npredictions = linear_regressor.predict(test_data)", "_____no_output_____" ], [ "print(test_labels)", "[-36.69728864 -91.477377 11.96165156 -0.74051877 24.47584129\n 12.42286854 -57.46293828 28.15553021 -10.27758354 -80.80239408\n 22.2276832 64.70214251 -22.33224966 -84.32102748 -44.51417742\n -18.57607726 -76.75213382 -18.86438755 -40.84204295 -63.4056294\n -35.32062686 -10.06708677 21.20540389 78.24817537 -24.77820218\n -26.87743177 -12.0017312 64.19559505 -16.79027112 -71.3715844 ]\n" ], [ "print(predictions)", "[-27.37351175 -93.7792872 12.92330013 0.89313596 22.43864415\n 5.91564656 -54.96106527 22.07112775 -8.09116828 -78.72050659\n 18.40889843 67.58130785 -29.40807671 -82.64062439 -55.06907019\n -25.93566194 -69.15559338 -18.53616803 -47.76985106 -59.5373645\n -43.0530469 -9.24228731 15.45126983 65.6471009 -26.49152707\n -28.21874519 -8.03490249 69.06852394 -15.19504878 -72.42753591]\n" ], [ "metrics.mean_absolute_error(test_labels, predictions)", "_____no_output_____" ], [ "linear_scoring = cross_validation.cross_val_score(linear_regressor, data, target, scoring = 'mean_absolute_error', \n cv=10)\nprint('mean: {}, std: {}'.format(linear_scoring.mean(), linear_scoring.std()))", "mean: -4.070071498779696, std: 1.07371044928902\n" ], [ "scorer = metrics.make_scorer(metrics.mean_absolute_error, greater_is_better=True)", "_____no_output_____" ], [ "linear_scoring = cross_validation.cross_val_score(linear_regressor, data, target, scoring=scorer, \n cv = 10)\nprint('mean: {}, std: {}'.format(linear_scoring.mean(), linear_scoring.std()))", "mean: 4.070071498779696, std: 1.07371044928902\n" ], [ "coef", "_____no_output_____" ], [ "linear_regressor.coef_", "_____no_output_____" ], [ "# в лекции не указано, что в уравнении обученной модели также участвует свободный член\nlinear_regressor.intercept_", "_____no_output_____" ], [ "print(\"y = {:.2f}*x1 + {:.2f}*x2\".format(coef[0], coef[1]))", "y = 38.08*x1 + 0.00*x2\n" ], [ "print(\"y = {:.2f}*x1 + {:.2f}*x2 + {:.2f}\".format(linear_regressor.coef_[0], \n linear_regressor.coef_[1], \n linear_regressor.intercept_))", "y = 38.15*x1 + -0.16*x2 + -0.88\n" ] ], [ [ "#### Lasso", "_____no_output_____" ] ], [ [ "lasso_regressor = linear_model.Lasso(random_state = 3)\nlasso_regressor.fit(train_data, train_labels)\nlasso_predictions = lasso_regressor.predict(test_data)", "_____no_output_____" ], [ "lasso_scoring = cross_validation.cross_val_score(lasso_regressor, data, target, scoring = scorer, cv = 10)\nprint('mean: {}, std: {}'.format(lasso_scoring.mean(), lasso_scoring.std()))", "mean: 4.1544782466663985, std: 1.0170354384993352\n" ], [ "print(lasso_regressor.coef_)", "[37.31062919 -0. ]\n" ], [ "print(\"y = {:.2f}*x1 + {:.2f}*x2\".format(coef[0], coef[1]))", "y = 38.08*x1 + 0.00*x2\n" ], [ "print(\"y = {:.2f}*x1 + {:.2f}*x2\".format(lasso_regressor.coef_[0], lasso_regressor.coef_[1]))", "y = 37.31*x1 + -0.00*x2\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d01c96edb67ed28e04de97fd908f6ded461990c4
58,737
ipynb
Jupyter Notebook
Atividade 04.ipynb
Lucas-Otavio/MS211K-2s21
3828461e8fba2d30fce3fc4e45189b11a8007635
[ "MIT" ]
null
null
null
Atividade 04.ipynb
Lucas-Otavio/MS211K-2s21
3828461e8fba2d30fce3fc4e45189b11a8007635
[ "MIT" ]
null
null
null
Atividade 04.ipynb
Lucas-Otavio/MS211K-2s21
3828461e8fba2d30fce3fc4e45189b11a8007635
[ "MIT" ]
null
null
null
51.478528
13,094
0.568483
[ [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nimport functools\nimport time", "_____no_output_____" ] ], [ [ "# Questão 1", "_____no_output_____" ], [ "Resolva o sistema linear $Ax = b$ em que\n\n\n$\nA =\n\\begin{bmatrix}\n9. & −4. & 1. & 0. & 0. & 0. & 0. \\\\\n−4. & 6. & −4. & 1. & 0. & 0. & 0. \\\\\n1. & −4. & 6. & −4. & 1. & 0. & 0. \\\\\n0. & 1. & −4. & 6. & −4. & 1. & 0. \\\\\n\\vdots & \\ddots & \\ddots & \\ddots & \\ddots & \\ddots & \\vdots \\\\\n0. & 0. & 1. & −4. & 6. & −4. & 1. \\\\\n0. & 0. & 0. & 1. & −4. & 5. & −2. \\\\\n0. & 0. & 0. & 0. & 1. & −2. & 1.\n\\end{bmatrix} \\in R^{\\; 200 \\times 200}\n$\n\n\n\ne \n\n$\nb =\n\\begin{bmatrix}\n1 \\\\\n1\\\\\n1\\\\\n1\\\\\n\\vdots\\\\\n1\\\\\n1\\\\\n1\\\\\n\\end{bmatrix} \\in\nR^{\\; 200}\n$\n\nusando o método da Eliminação de Gauss (com pivoteamento parcial) e os métodos iterativos de Gauss-Jacobi e Gauss-Seidel, se possível. Compare o desempenho dos métodos para a resolução do sistema linear em termos do tempo de execução.", "_____no_output_____" ] ], [ [ "def timer(f):\n @functools.wraps(f)\n def wrapper_timer(*args, **kwargs):\n tempo_inicio = time.perf_counter()\n retorno = f(*args, **kwargs)\n tempo_fim = time.perf_counter()\n tempo_exec = tempo_fim - tempo_inicio\n print(f\"Tempo de Execução: {tempo_exec:0.4f} segundos\")\n return retorno\n return wrapper_timer", "_____no_output_____" ], [ "def FatoracaoLUPivot(A):\n U = np.copy(A)\n n = A.shape[0]\n L = np.zeros_like(A)\n P = np.eye(n)\n\n m = 0\n\n for j in range(n):\n\n #Pivoteamento Parcial\n\n k = np.argmax(np.abs(U[j:,j])) + j\n U[j], U[k] = np.copy(U[k]), np.copy(U[j])\n P[j], P[k] = np.copy(P[k]), np.copy(P[j])\n\n L[j], L[k] = np.copy(L[k]), np.copy(L[j])\n\n m += 1\n\n for i in range(j + 1, n):\n L[i][j] = U[i][j]/U[j][j]\n for k in range(j + 1, n):\n U[i][k] -= L[i][j] * U[j][k]\n U[i][j] = 0\n m += 1\n L += np.eye(n)\n return L, U, P", "_____no_output_____" ], [ "def SubstituicaoRegressiva(U, c): # U triangular superior\n x = np.copy(c)\n n = U.shape[0]\n\n for i in range(n-1, -1, -1):\n for j in range(i + 1, n):\n x[i] -= (U[i,j] * x[j])\n x[i] /= U[i,i]\n return x", "_____no_output_____" ], [ "def SubstituicaoDireta(U, c): #U triangular inferior\n x = np.copy(c)\n n = U.shape[0]\n\n for i in range(n):\n for j in range(i):\n x[i] -= (U[i,j] * x[j])\n x[i] /= U[i,i]\n return x", "_____no_output_____" ], [ "@timer\ndef EliminacaoGaussLUPivot(A, b):\n L, U, P = FatoracaoLUPivot(A)\n # Resolver Ly = b e Ux = y\n y = SubstituicaoDireta(L, b)\n x = SubstituicaoRegressiva(U, y)\n\n return P, x", "_____no_output_____" ], [ "def buildA():\n A = np.zeros((200, 200))\n A[0,0:3] = np.array([9, -4, 1])\n A[1,0:4] = np.array([-4, 6, -4, 1])\n A[198,196:200] = np.array([1, -4, 5, -2])\n A[199,197:200] = np.array([1, -2, 1])\n\n for i in range(2, 198):\n A[i, i-2:i+3] = np.array([1, -4, 6, -4, 1])\n \n return A", "_____no_output_____" ], [ "A = buildA()\nA", "_____no_output_____" ], [ "b = np.ones((200,1))\nb", "_____no_output_____" ] ], [ [ "## Solução por Eliminação de Gauss com Pivoteamento Parcial", "_____no_output_____" ] ], [ [ "P, x = EliminacaoGaussLUPivot(A, b)", "Tempo de Execução: 4.0179 segundos\n" ], [ "x", "_____no_output_____" ], [ "print(np.max(np.abs(P @ A @ x - b)))", "2.384185791015625e-07\n" ] ], [ [ "## Método Gauss-Jacobi", "_____no_output_____" ] ], [ [ "@timer\ndef GaussJacobi(A, b):\n n = A.shape[0]\n x_history = list()\n x_old = np.zeros(n)\n x_new = np.zeros(n)\n k_limite = 200\n k = 0\n tau = 1E-4\n Dr = 1\n\n while (k < k_limite and Dr > tau):\n for i in range(n):\n soma = 0\n for j in range(n):\n if (i == j):\n continue\n soma += A[i,j]*x_old[j]\n x_new[i] = (b[i] - soma) / A[i,i]\n \n k += 1\n Dr = np.max(np.abs(x_new - x_old)) / np.max(np.abs(x_new))\n x_history.append(x_old)\n x_old = np.copy(x_new)\n \n return x_history, x_new", "_____no_output_____" ], [ "history, x = GaussJacobi(A, b)", "Tempo de Execução: 4.8295 segundos\n" ], [ "erros = []\nfor i in range(len(history)):\n erro = np.max(np.abs(A @ history[i] - b))\n if (erro != np.inf):\n erros.append(erro)", "_____no_output_____" ], [ "plt.semilogy(erros)", "_____no_output_____" ] ], [ [ "## Método Gauss-Seidel", "_____no_output_____" ] ], [ [ "@timer\ndef GaussSeidel(A, b, k_limite=200):\n n = A.shape[0]\n x_history = list()\n x_old = np.zeros(n)\n x_new = np.zeros(n)\n k = 0\n tau = 1E-4\n Dr = 1\n\n while (k < k_limite and Dr > tau):\n for i in range(n):\n soma = 0\n for j in range(n):\n if (i == j):\n continue\n soma += A[i,j]*x_new[j]\n x_new[i] = (b[i] - soma) / A[i,i]\n \n \n Dr = np.max(np.abs(x_new - x_old)) / np.max(np.abs(x_new))\n x_history.append(x_old)\n x_old = np.copy(x_new)\n k += 1\n\n if (Dr > tau):\n print(\"NÃO CONVERGIU!\")\n \n return x_history, x_new", "_____no_output_____" ], [ "history, x = GaussSeidel(A, b)", "NÃO CONVERGIU!\nTempo de Execução: 4.7215 segundos\n" ], [ "print(np.max(np.abs(A @ x - b)))", "1.4693583616174237\n" ], [ "erros = []\nfor i in range(len(history)):\n erro = np.max(np.abs(A @ history[i] - b))\n if (erro != np.inf):\n erros.append(erro)", "_____no_output_____" ], [ "plt.semilogy(erros)", "_____no_output_____" ] ], [ [ "## Análise dos Resultados", "_____no_output_____" ], [ "Além de reutilizar as funções criadas para a Eliminação de Gauss com Pivoteamento Parcial, escrevi rotinas para implementar os métodos de Gauss-Jacobi e Gauss-Seidel. \n\nAinda, criei uma função decoradora `timer` para envolver as rotinas de cada método de resolução de sistemas lineares para contabilizar e imprimir o respectivo tempo de execução.\n\nAo longo da análise, considerei o erro absoluto máximo como a componente de maior diferença, em módulo, entre $Ax$ e $b$.\n\nO método de Eliminação de Gauss demorou $4,0178$ segundos e obteve a resposta correta, com erro absoluto máximo de aproximadamente $2,4E-7$.\n\nO método de Gauss-Jacobi executou em $4,8295$ segundos e divergiu, com erro crescente a cada iteração.\n\nO método de Gauss-Seidel executou em $4,7215$ segundos e apresentou uma condição peculiar. O resultado não divergiu, mas converge lentamente $-$ de forma que $200$ iterações não foram suficientes para obter a resposta correta e o erro absoluto máximo da última iteração permaneceu próximo de $1,5$.\n\nPortanto, o método de melhor performance no caso analisado foi a Eliminação de Gauss com Pivoteamento Parcial, pois ela obteve a melhor resposta e executou em menos tempo.", "_____no_output_____" ], [ "# Questão 2", "_____no_output_____" ], [ "Determine valores de $\\beta$ que garantem a convergência dos métodos de Gauss-Jacobi e Gauss-Seidel quando\naplicados para resolução do sistema linear $Ax = b$ em que\n\n\n$A =\n\\begin{bmatrix}\n−10 & 2 \\\\\n\\beta & 5\n\\end{bmatrix}$\ne\n$b =\n\\begin{bmatrix}\n1 \\\\\n1\n\\end{bmatrix}$", "_____no_output_____" ], [ "## Gauss-Jacobi\n\n#### $i=1$:\n\n$\\sum_{j \\ne i} |a_{ij}| = |a_{12}| = 2 < 10 = |a_{11}|$\n\n#### $i=2$:\n\n$\\sum_{j \\ne i} |a_{ij}| = |a_{21}| = \\beta < 5 = |a_{22}|$\n\nLogo, a matriz é diagonalmente estritamente crescente para $\\beta < 5$ e o conjunto de matrizes que satisfazem essa condição garante a convergência do Método de Gauss-Jacobi.", "_____no_output_____" ], [ "## Gauss-Seidel\n\n### Critério das Linhas\n\nConforme vimos no critério de convergência para Gauss-Jacobi, a matriz é diagonalmente estritalmente crescente $-$ e, consequentemente o método de Gauss-Seidel converge $-$ para $\\beta < 5$.\n\n### Critério de Sassenfeld\n\n#### $i=1$:\n\n$\\beta_1 = \\frac{1}{|a_{11}|} \\left( \\sum_{j = 2}^2 |a_{1j}|\\right) = \\frac{|a_{12}|}{|a_{11}|} = \\frac{2}{10} = \\frac{1}{5} < 1$\n\n#### $i=2$:\n\n$\\beta_2 = \\frac{1}{|a_{22}|} \\left( \\sum_{j = 1}^1 |a_{2j}| \\beta_j\\right) = \\frac{|a_{21}| \\beta_1}{|a_{22}|} = \\frac{\\beta \\times (1/5)}{5} = \\frac{\\beta}{25} < 1 \\iff \\beta < 25$\n\nDessa forma, como os dois critérios são independentemente suficientes para determinar a convergência do método, realizei a união dos intervalos de $\\beta$.\n\nPortanto, valores de $\\beta$ no intervalo $\\beta < 25$ garantem a convergência de Gauss-Seidel.", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d01cb1c614ee40ff3c971557d478e9fdce9bea13
3,179
ipynb
Jupyter Notebook
01_hello.ipynb
hannesloots/nbdev-tutorial
dd8bf2fc49de3486cc6cfa82d9d796a784e11eb0
[ "Apache-2.0" ]
null
null
null
01_hello.ipynb
hannesloots/nbdev-tutorial
dd8bf2fc49de3486cc6cfa82d9d796a784e11eb0
[ "Apache-2.0" ]
null
null
null
01_hello.ipynb
hannesloots/nbdev-tutorial
dd8bf2fc49de3486cc6cfa82d9d796a784e11eb0
[ "Apache-2.0" ]
null
null
null
20.914474
243
0.4838
[ [ [ "# default_exp core", "_____no_output_____" ] ], [ [ "# hello\n\n> API details.\n", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.showdoc import *\nfrom nbdev_tutorial.core import *\n%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "#export\nclass HelloSayer:\n \"Say hello to `to` using `say_hello`\"\n def __init__(self, to): self.to = to\n\n def say(self):\n \"Do the saying\"\n return say_hello(self.to)", "_____no_output_____" ], [ "show_doc(HelloSayer)", "_____no_output_____" ], [ "Card(suit=2, rank=11)", "_____no_output_____" ], [ "show_doc(Card)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d01cb914daa5ad93073bced2405a42b2fc714568
50,284
ipynb
Jupyter Notebook
Assignment9- Dynamic.ipynb
bblank70/MSDS432
f4cc8f42d1dfef8e5c42e92b9e356b43c2584052
[ "MIT" ]
1
2021-04-28T04:35:21.000Z
2021-04-28T04:35:21.000Z
Assignment9- Dynamic.ipynb
bblank70/MSDS432
f4cc8f42d1dfef8e5c42e92b9e356b43c2584052
[ "MIT" ]
null
null
null
Assignment9- Dynamic.ipynb
bblank70/MSDS432
f4cc8f42d1dfef8e5c42e92b9e356b43c2584052
[ "MIT" ]
null
null
null
159.126582
28,643
0.679441
[ [ [ "# Assignment 9: Implement Dynamic Programming\n\nIn this exercise, we will begin to explore the concept of dynamic programming and how it related to various object containers with respect to computational complexity. ", "_____no_output_____" ], [ "## Deliverables:\n\n \n\n 1) Choose and implement a Dynamic Programming algorithm in Python, make sure you are using a Dynamic Programming solution (not another one).\n\n 2) Use the algorithm to solve a range of scenarios. \n \n 3) Explain what is being done in the implementation. That is, write up a walk through of the algorithm and explain how it is a Dynamic Programming solution.\n\n\n\n \n### Prepare an executive summary of your results, referring to the table and figures you have generated. Explain how your results relate to big O notation. Describe your results in language that management can understand. This summary should be included as text paragraphs in the Jupyter notebook. Explain how the algorithm works and why it is a useful to data engineers.", "_____no_output_____" ], [ "# A. The Dynamic programming problem: Longest Increasing Sequence\n\n\n### The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. ", "_____no_output_____" ], [ "# A. Setup: Library imports and Algorithm", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport time\n#import itertools\n\nimport random\nimport matplotlib.pyplot as plt\n#import networkx as nx\n#import pydot\n#from networkx.drawing.nx_pydot import graphviz_layout\n\n#from collections import deque\n", "_____no_output_____" ], [ "# Dynamic Programming Approach of Finding LIS by reducing the problem to longest common Subsequence\n \ndef lis(a):\n n=len(a) #get the length of the list\n \n b=sorted(list(set(a))) #removes duplicates, and sorts list\n m=len(b) #gets the length of the truncated and sorted list\n \n dp=[[-1 for i in range(m+1)] for j in range(n+1)] #instantiates a list of lists filled with -1 columns are indicies of the sorted array; rows the original array\n \n for i in range(n+1): # for every column in the table at each row:\n \n for j in range(m+1):\n if i==0 or j==0: #if at first element in either a row or column set the table row,index to zero\n dp[i][j]=0 \n elif a[i-1]==b[j-1]: #else if the sorted array value matches the original array:\n dp[i][j]=1+dp[i-1][j-1]#sets dp[i][j] to 1+prveious cell of the dyanmic table\n else:\n dp[i][j]=max(dp[i-1][j],dp[i][j-1]) #else record the max of the row or column for that cell in the cell\n return dp[-1][-1] # This will return the max running sequence.\n \n# Driver program to test above function\narr1 = [10, 22, 9, 33, 21, 50, 41, 60]\nlen_arr1 = len(arr1)\nprint(\"Longest increaseing sequence has a length of:\", lis(arr1))\n# addtional comments included from the original code contributed by Dheeraj Khatri (https://www.geeksforgeeks.org/longest-increasing-subsequence-dp-3/) \n\n\ndef Container(arr, fun): ### I'm glad I was able to reuse this from assignment 3 and 4. Useful function.\n objects = [] #instantiates an empty list to collect the returns\n times = [] #instantiates an empty list to collect times for each computation\n for t in arr:\n start= time.perf_counter() #collects the start time\n obj = fun(t) # applies the function to the arr object\n end = time.perf_counter() # collects end time\n duration = (end-start)* 1E3 #converts to milliseconds\n objects.append(obj)# adds the returns of the functions to the objects list\n times.append(duration) # adds the duration for computation to list\n return objects, times\n\n\n", "Longest increaseing sequence has a length of: 5\n" ] ], [ [ "# B. Test Array Generation", "_____no_output_____" ] ], [ [ "RANDOM_SEED = 300\n\nnp.random.seed(RANDOM_SEED) \narr100 = list(np.random.randint(low=1, high= 5000, size=100))\n\nnp.random.seed(RANDOM_SEED) \narr200 = list(np.random.randint(low=1, high= 5000, size=200))\n\n\nnp.random.seed(RANDOM_SEED) \narr400 = list(np.random.randint(low=1, high= 5000, size=400))\n\n\nnp.random.seed(RANDOM_SEED) \narr600 = list(np.random.randint(low=1, high= 5000, size=600))\n\nnp.random.seed(RANDOM_SEED) \narr800 = list(np.random.randint(low=1, high= 5000, size=800))\n\nprint(len(arr100), len(arr200), len(arr400), len(arr600), len(arr800))\n\n\n\n", "100 200 400 600 800\n" ], [ "arr_list = [arr100, arr200, arr400, arr600, arr800]\n\nmetrics = Container(arr_list, lis)", "_____no_output_____" ] ], [ [ "### Table1. Performance Summary", "_____no_output_____" ] ], [ [ "summary = {\n 'ArraySize' : [len(arr100), len(arr200), len(arr400), len(arr600), len(arr800)], \n 'SequenceLength' : [metrics[0][0],metrics[0][1], metrics[0][2], metrics[0][3], metrics[0][4]],\n 'Time(ms)' : [metrics[1][0],metrics[1][1], metrics[1][2], metrics[1][3], metrics[1][4]]\n}\n\ndf =pd.DataFrame(summary)\ndf", "_____no_output_____" ] ], [ [ "### Figure 1. Performance", "_____no_output_____" ] ], [ [ "sns.scatterplot(data=df, x='Time(ms)', y='ArraySize')\n", "_____no_output_____" ] ], [ [ "# Discussion\n\n Explain what is being done in the implementation. That is, write up a walk through of the algorithm and explain how it is a Dynamic Programming solution.\n", "_____no_output_____" ], [ "The dyanamic programming problem above finds the length of the longest incrementing sequence of values in a list. The defined function makes a sorted copy of the list containing only unique values and also creates a dynamic table (in the form of a list of lists) using a nested list comprehension. This table contains the incidices of the sorted array as columns and the indicies of the original array as rows. To begin, the table is instantiated with values of -1. The value of zero indicies are set to zero in the dynamic table and if a given index in the original array is found to be increasing the dyanamic table is incremented. until all positions are assessed. The funciton then returns the maximum value of the increments which will be the length of the longest running sequence. This is a dynamic progromming problem because the solution builds on a smaller subset problems. \n\nDyanmic programming is an important concept for developers and engineers. Functions and programs that use dynamic programming help solve problems which present themselves as factorial time complexity in a more efficient way. At face value, it appears that this problem of the longest incrementing sequence will have to compare all values in a given array to all previous values in the array. Dyanmic programming allows for a shortcut in a sense. We can compare the given array with a sorted version of that array and at the intersection of the sorted and unsorted arrays we can determine if we need to make an additon to our incrementing sequence tally. \n\nShown above in table and figure 1 is the time required for the algorithm to tally the longest running sequence for various array sizes. Because the algorithm utilizes a nested for loop it is the expeictation that the time will grow as a function of the square of the original array length. This is confirmed when inspecting the scatterplot in figure 1. Thus, the developed algorithm in big O notation is O(n^2) time complexity which is much more efficient than factorial time.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d01cd77ba332fa91753a0feffde5081248ce2787
84,173
ipynb
Jupyter Notebook
Chapter3/2019-03-03_AS_JJ_Chapter3-Part1.ipynb
alexanu/research
31118d143f8720e4668a6d6ad7e5168fc2c244c5
[ "MIT" ]
null
null
null
Chapter3/2019-03-03_AS_JJ_Chapter3-Part1.ipynb
alexanu/research
31118d143f8720e4668a6d6ad7e5168fc2c244c5
[ "MIT" ]
null
null
null
Chapter3/2019-03-03_AS_JJ_Chapter3-Part1.ipynb
alexanu/research
31118d143f8720e4668a6d6ad7e5168fc2c244c5
[ "MIT" ]
null
null
null
132.139717
65,472
0.853599
[ [ [ "# Chapter 3 Questions", "_____no_output_____" ], [ "#### 3.1 Form dollar bars for E-mini S&P 500 futures:\n1. Apply a symmetric CUSUM filter (Chapter 2, Section 2.5.2.1) where the threshold is the standard deviation of daily returns (Snippet 3.1).\n2. Use Snippet 3.4 on a pandas series t1, where numDays=1.\n3. On those sampled features, apply the triple-barrier method, where ptSl=[1,1] and t1 is the series you created in point 1.b.\n4. Apply getBins to generate the labels.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport timeit\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, classification_report, confusion_matrix\n\nfrom mlfinlab.corefns.core_functions import CoreFunctions\nfrom mlfinlab.fracdiff.fracdiff import frac_diff_ffd\n\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "# Read in data\ndata = pd.read_csv('official_data/dollar_bars.csv', nrows=40000)\ndata.index = pd.to_datetime(data['date_time'])\ndata = data.drop('date_time', axis=1)", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ] ], [ [ "**Apply a symmetric CUSUM filter (Chapter 2, Section 2.5.2.1) where the threshold is the standard deviation of daily returns (Snippet 3.1).**", "_____no_output_____" ] ], [ [ "# Compute daily volatility\nvol = CoreFunctions.get_daily_vol(close=data['close'], lookback=50)", "Calculating daily volatility for dynamic thresholds\n" ], [ "vol.plot(figsize=(14, 7), title='Volatility as caclulated by de Prado')\nplt.show()", "_____no_output_____" ], [ "# Apply Symmetric CUSUM Filter and get timestamps for events\n# Note: Only the CUSUM filter needs a point estimate for volatility\ncusum_events = CoreFunctions.get_t_events(data['close'], threshold=vol.mean())", " 1%|▏ | 592/39998 [00:00<00:06, 5912.41it/s]" ] ], [ [ "**Use Snippet 3.4 on a pandas series t1, where numDays=1.**", "_____no_output_____" ] ], [ [ "# Compute vertical barrier\nvertical_barriers = CoreFunctions.add_vertical_barrier(cusum_events, data['close'])\nvertical_barriers.head()", "_____no_output_____" ] ], [ [ "**On those sampled features, apply the triple-barrier method, where ptSl=[1,1] and t1 is the series you created in point 1.b.**", "_____no_output_____" ] ], [ [ "triple_barrier_events = CoreFunctions.get_events(close=data['close'],\n t_events=cusum_events,\n pt_sl=[1, 1],\n target=vol,\n min_ret=0.01,\n num_threads=1,\n vertical_barrier_times=vertical_barriers,\n side=None)", "/home/ariadne/Desktop/Research Project/research/2019-03-03_AS_JJ_Chapter3/mlfinlab/corefns/core_functions.py:205: FutureWarning: \nPassing list-likes to .loc or [] with any missing label will raise\nKeyError in the future, you can use .reindex() as an alternative.\n\nSee the documentation here:\nhttps://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike\n target = target.loc[t_events]\n" ], [ "triple_barrier_events.head()", "_____no_output_____" ], [ "labels = CoreFunctions.get_bins(triple_barrier_events, data['close'])", "_____no_output_____" ], [ "labels.head()", "_____no_output_____" ], [ "labels['bin'].value_counts()", "_____no_output_____" ] ], [ [ "---\n#### 3.2 From exercise 1, use Snippet 3.8 to drop rare labels.", "_____no_output_____" ] ], [ [ "clean_labels = CoreFunctions.drop_labels(labels)", "_____no_output_____" ], [ "print(labels.shape)\nprint(clean_labels.shape)", "(660, 3)\n(660, 3)\n" ] ], [ [ "---\n#### 3.3 Adjust the getBins function (Snippet 3.5) to return a 0 whenever the vertical barrier is the one touched first.\nThis change was made inside the module CoreFunctions.", "_____no_output_____" ], [ "---\n#### 3.4 Develop a trend-following strategy based on a popular technical analysis statistic (e.g., crossing moving averages). For each observation, themodel suggests a side, but not a size of the bet.\n\n1. Derive meta-labels for pt_sl = [1,2] and t1 where num_days=1. Use as trgt the daily standard deviation as computed by Snippet 3.1.\n2. Train a random forest to decide whether to trade or not. Note: The decision is whether to trade or not, {0,1}, since the underllying model (the crossing moveing average has decided the side{-1, 1})", "_____no_output_____" ] ], [ [ "# This question is answered in the notebook: 2019-03-06_JJ_Trend-Following-Question", "_____no_output_____" ] ], [ [ "----\n#### 3.5 Develop a mean-reverting strategy based on Bollinger bands. For each observation, the model suggests a side, but not a size of the bet.\n\n* (a) Derive meta-labels for ptSl = [0, 2] and t1 where numDays = 1. Use as trgt the daily standard deviation as computed by Snippet 3.1.\n* (b) Train a random forest to decide whether to trade or not. Use as features: volatility, seial correlation, and teh crossinmg moving averages.\n* (c) What is teh accuracy of prediction from the primary model? (i.e. if the secondary model does not filter the bets) What are the precision, recall and FI-scores?\n* (d) What is teh accuracy of prediction from the primary model? What are the precision, recall and FI-scores?\n", "_____no_output_____" ] ], [ [ "# This question is answered in the notebook: 2019-03-07_BBand-Question", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01cda216e47949ae138309845e953ec1737118e
7,871
ipynb
Jupyter Notebook
Sesion 5/A-Presentacion.ipynb
ochoadavid/TallerDePython
d98a83e3697af138dff2644355722d59977291e2
[ "CNRI-Python", "CECILL-B" ]
2
2017-07-05T15:30:23.000Z
2017-07-05T17:57:11.000Z
Sesion 5/A-Presentacion.ipynb
ochoadavid/TallerDePython
d98a83e3697af138dff2644355722d59977291e2
[ "CNRI-Python", "CECILL-B" ]
1
2017-08-02T16:18:49.000Z
2017-08-02T16:27:21.000Z
Sesion 5/A-Presentacion.ipynb
ochoadavid/TallerDePython
d98a83e3697af138dff2644355722d59977291e2
[ "CNRI-Python", "CECILL-B" ]
null
null
null
25.227564
497
0.597002
[ [ [ "![Python Logo](img/Python_logo.png)", "_____no_output_____" ], [ "# If I have seen further it is by standing on the shoulders of Giants\n(Newton??)", "_____no_output_____" ], [ "![Python Logo](img/python-loc.png)\n(https://www.openhub.net/)", "_____no_output_____" ], [ "![Python Logo](img/numpy-loc.png)\n(https://www.openhub.net/)", "_____no_output_____" ], [ "![Python Logo](img/scipy-loc.png)\n(https://www.openhub.net/)", "_____no_output_____" ], [ "![Python Logo](img/pandas-loc.png)\n(https://www.openhub.net/)", "_____no_output_____" ], [ "![Python Logo](img/resumen-loc.png)\n(https://www.openhub.net/)", "_____no_output_____" ], [ "### Pero, ¿qué es lo que hace fuertes a estos proyectos?", "_____no_output_____" ], [ "![Like a programmer](img/like-a-programmer.jpeg)\n(https://medium.com/@sailorhg/coding-like-a-girl-595b90791cce)", "_____no_output_____" ], [ "![Guido](img/pycon-guido.jpg)", "_____no_output_____" ], [ "## Codigo de conducta", "_____no_output_____" ], [ "### PyCon 2016 Code Of Conduct\nHarassment includes offensive communication related to gender, sexual orientation, disability, physical appearance, body size, race, religion, sexual images in public spaces, deliberate intimidation, stalking, following, harassing photography or recording, sustained disruption of talks or other events, inappropriate physical contact, and unwelcome sexual attention.", "_____no_output_____" ], [ "Participants asked to stop any harassing behavior are expected to comply immediately.", "_____no_output_____" ], [ "Exhibitors in the expo hall, sponsor or vendor booths, or similar activities are also subject to the anti-harassment policy. In particular, exhibitors should not use sexualized images, activities, or other material. Booth staff (including volunteers) should not use sexualized clothing/uniforms/costumes, or otherwise create a sexualized environment.", "_____no_output_____" ], [ "Be careful in the words that you choose. Remember that sexist, racist, and other exclusionary jokes can be offensive to those around you. Excessive swearing and offensive jokes are not appropriate for PyCon.", "_____no_output_____" ], [ "If a participant engages in behavior that violates this code of conduct, the conference organizers may take any action they deem appropriate, including warning the offender or expulsion from the conference with no refund.", "_____no_output_____" ], [ "## Políticas de inclusión", "_____no_output_____" ], [ "![python software fundation](img/psf-logo.png)\n\n__The mission of the Python Software Foundation is to promote, protect, and advance the Python programming language, and to support and facilitate the growth of a diverse and international community of Python programmers.__\n\nThe Python Software Foundation (PSF) is a 501(c)(3) non-profit corporation that holds the intellectual property rights behind the Python programming language. We manage the open source licensing for Python version 2.1 and later and own and protect the trademarks associated with Python. We also run the North American PyCon conference annually, support other Python conferences around the world, and fund Python related development with our grants program and by funding special projects.\n\n(https://www.python.org/psf/)", "_____no_output_____" ], [ "![django girls logo](img/django-girls-logo.png)\n\n__We inspire women to fall in love with programming.__\n\n_Django Girls organize free Python and Django workshops, create open sourced online tutorials and curate amazing first experiences with technology._\n\n(https://djangogirls.org/)", "_____no_output_____" ], [ "![tshirt](img/django-girls-tshirt.png)", "_____no_output_____" ], [ "![pyladies logo](img/pyladies-logo.png)\n\nWe are an international mentorship group with a focus on helping more women become active participants and leaders in the Python open-source community. Our mission is to promote, educate and advance a diverse Python community through outreach, education, conferences, events and social gatherings.\n\nPyLadies also aims to provide a friendly support network for women and a bridge to the larger Python world. Anyone with an interest in Python is encouraged to participate!\n\n(http://www.pyladies.com/)", "_____no_output_____" ], [ "![Like a programmer](img/inclusion-in-numbers.png)\n(https://www.slideshare.net/fmasanori/import-community-62142823)", "_____no_output_____" ], [ "# ¡Gracias!\n\n<center>David Manuel Ochoa González<br>\ncorreos: ochoadavid at gmail.com - dochoa at iteso.mx<br>\ngithub: https://github.com/ochoadavid<br>\nmaterial de apoyo en: https://github.com/ochoadavid/TallerDePython</center>", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d01cee6ba5eb9a9e920816cc971048bcf937d8db
3,635
ipynb
Jupyter Notebook
playbook/tactics/initial-access/T1566.ipynb
haresudhan/The-AtomicPlaybook
447b1d6bca7c3750c5a58112634f6bac31aff436
[ "MIT" ]
8
2021-05-25T15:25:31.000Z
2021-11-08T07:14:45.000Z
playbook/tactics/initial-access/T1566.ipynb
haresudhan/The-AtomicPlaybook
447b1d6bca7c3750c5a58112634f6bac31aff436
[ "MIT" ]
1
2021-08-23T17:38:02.000Z
2021-10-12T06:58:19.000Z
playbook/tactics/initial-access/T1566.ipynb
haresudhan/The-AtomicPlaybook
447b1d6bca7c3750c5a58112634f6bac31aff436
[ "MIT" ]
2
2021-05-29T20:24:24.000Z
2021-08-05T23:44:12.000Z
69.903846
1,207
0.748831
[ [ [ "# T1566 - Phishing\nAdversaries may send phishing messages to elicit sensitive information and/or gain access to victim systems. All forms of phishing are electronically delivered social engineering. Phishing can be targeted, known as spearphishing. In spearphishing, a specific individual, company, or industry will be targeted by the adversary. More generally, adversaries can conduct non-targeted phishing, such as in mass malware spam campaigns.\n\nAdversaries may send victim’s emails containing malicious attachments or links, typically to execute malicious code on victim systems or to gather credentials for use of [Valid Accounts](https://attack.mitre.org/techniques/T1078). Phishing may also be conducted via third-party services, like social media platforms.", "_____no_output_____" ], [ "## Atomic Tests:\nCurrently, no tests are available for this technique.", "_____no_output_____" ], [ "## Detection\nNetwork intrusion detection systems and email gateways can be used to detect phishing with malicious attachments in transit. Detonation chambers may also be used to identify malicious attachments. Solutions can be signature and behavior based, but adversaries may construct attachments in a way to avoid these systems.\n\nURL inspection within email (including expanding shortened links) can help detect links leading to known malicious sites. Detonation chambers can be used to detect these links and either automatically go to these sites to determine if they're potentially malicious, or wait and capture the content if a user visits the link.\n\nBecause most common third-party services used for phishing via service leverage TLS encryption, SSL/TLS inspection is generally required to detect the initial communication/delivery. With SSL/TLS inspection intrusion detection signatures or other security gateway appliances may be able to detect malware.\n\nAnti-virus can potentially detect malicious documents and files that are downloaded on the user's computer. Many possible detections of follow-on behavior may take place once [User Execution](https://attack.mitre.org/techniques/T1204) occurs.", "_____no_output_____" ], [ "## Shield Active Defense\n### Email Manipulation \n Modify the flow or contents of email. \n\n Email flow manipulation includes changing which mail appliances process mail flows, to which systems they forward mail, or moving mail after it arrives in an inbox. Email content manipulation includes altering the contents of an email message.\n#### Opportunity\nA phishing email can be detected and blocked from arriving at the intended recipient. \n#### Use Case\nA defender can intercept emails that are detected as suspicious or malicious by email detection tools and prevent deliver to the intended target. \n#### Procedures\nModify the destination of inbound email to facilitate the collection of inbound spearphishing messages.\nModify the contents of an email message to maintain continuity when it is used for adversary engagement purposes.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ] ]
d01cf1854f015816501bb09ad26c4f7ce1d516c2
22,170
ipynb
Jupyter Notebook
Prasant_Kumar/Assignments/F9.ipynb
ks1320/Traffic-Surveillance-System
fa1eb2a3a3d494c798fa2eeb0528ef48b1978332
[ "MIT" ]
null
null
null
Prasant_Kumar/Assignments/F9.ipynb
ks1320/Traffic-Surveillance-System
fa1eb2a3a3d494c798fa2eeb0528ef48b1978332
[ "MIT" ]
null
null
null
Prasant_Kumar/Assignments/F9.ipynb
ks1320/Traffic-Surveillance-System
fa1eb2a3a3d494c798fa2eeb0528ef48b1978332
[ "MIT" ]
1
2021-09-29T08:21:56.000Z
2021-09-29T08:21:56.000Z
22,170
22,170
0.5682
[ [ [ "# Import Libraries", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms", "_____no_output_____" ] ], [ [ "## Data Transformations\n\nWe first start with defining our data transformations. We need to think what our data is and how can we augment it to correct represent images which it might not see otherwise. \n", "_____no_output_____" ] ], [ [ "# Train Phase transformations\ntrain_transforms = transforms.Compose([\n # transforms.Resize((28, 28)),\n # transforms.ColorJitter(brightness=0.10, contrast=0.1, saturation=0.10, hue=0.1),\n transforms.RandomRotation((-7.0, 7.0), fill=(1,)),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,)) # The mean and std have to be sequences (e.g., tuples), therefore you should add a comma after the values. \n # Note the difference between (0.1307) and (0.1307,)\n ])\n\n# Test Phase transformations\ntest_transforms = transforms.Compose([\n # transforms.Resize((28, 28)),\n # transforms.ColorJitter(brightness=0.10, contrast=0.1, saturation=0.10, hue=0.1),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n", "_____no_output_____" ] ], [ [ "# Dataset and Creating Train/Test Split", "_____no_output_____" ] ], [ [ "train = datasets.MNIST('./data', train=True, download=True, transform=train_transforms)\ntest = datasets.MNIST('./data', train=False, download=True, transform=test_transforms)", "_____no_output_____" ] ], [ [ "# Dataloader Arguments & Test/Train Dataloaders\n", "_____no_output_____" ] ], [ [ "SEED = 1\n\n# CUDA?\ncuda = torch.cuda.is_available()\nprint(\"CUDA Available?\", cuda)\n\n# For reproducibility\ntorch.manual_seed(SEED)\n\nif cuda:\n torch.cuda.manual_seed(SEED)\n\n# dataloader arguments - something you'll fetch these from cmdprmt\ndataloader_args = dict(shuffle=True, batch_size=128, num_workers=4, pin_memory=True) if cuda else dict(shuffle=True, batch_size=64)\n\n# train dataloader\ntrain_loader = torch.utils.data.DataLoader(train, **dataloader_args)\n\n# test dataloader\ntest_loader = torch.utils.data.DataLoader(test, **dataloader_args)", "CUDA Available? True\n" ] ], [ [ "# The model\nLet's start with the model we first saw", "_____no_output_____" ] ], [ [ "import torch.nn.functional as F\ndropout_value = 0.1\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n # Input Block\n self.convblock1 = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=16, kernel_size=(3, 3), padding=0, bias=False),\n nn.ReLU(),\n nn.BatchNorm2d(16),\n nn.Dropout(dropout_value)\n ) # output_size = 26\n\n # CONVOLUTION BLOCK 1\n self.convblock2 = nn.Sequential(\n nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3), padding=0, bias=False),\n nn.ReLU(),\n nn.BatchNorm2d(32),\n nn.Dropout(dropout_value)\n ) # output_size = 24\n\n # TRANSITION BLOCK 1\n self.convblock3 = nn.Sequential(\n nn.Conv2d(in_channels=32, out_channels=10, kernel_size=(1, 1), padding=0, bias=False),\n ) # output_size = 24\n self.pool1 = nn.MaxPool2d(2, 2) # output_size = 12\n\n # CONVOLUTION BLOCK 2\n self.convblock4 = nn.Sequential(\n nn.Conv2d(in_channels=10, out_channels=16, kernel_size=(3, 3), padding=0, bias=False),\n nn.ReLU(), \n nn.BatchNorm2d(16),\n nn.Dropout(dropout_value)\n ) # output_size = 10\n self.convblock5 = nn.Sequential(\n nn.Conv2d(in_channels=16, out_channels=16, kernel_size=(3, 3), padding=0, bias=False),\n nn.ReLU(), \n nn.BatchNorm2d(16),\n nn.Dropout(dropout_value)\n ) # output_size = 8\n self.convblock6 = nn.Sequential(\n nn.Conv2d(in_channels=16, out_channels=16, kernel_size=(3, 3), padding=0, bias=False),\n nn.ReLU(), \n nn.BatchNorm2d(16),\n nn.Dropout(dropout_value)\n ) # output_size = 6\n self.convblock7 = nn.Sequential(\n nn.Conv2d(in_channels=16, out_channels=16, kernel_size=(3, 3), padding=1, bias=False),\n nn.ReLU(), \n nn.BatchNorm2d(16),\n nn.Dropout(dropout_value)\n ) # output_size = 6\n \n # OUTPUT BLOCK\n self.gap = nn.Sequential(\n nn.AvgPool2d(kernel_size=6)\n ) # output_size = 1\n\n self.convblock8 = nn.Sequential(\n nn.Conv2d(in_channels=16, out_channels=10, kernel_size=(1, 1), padding=0, bias=False),\n # nn.BatchNorm2d(10),\n # nn.ReLU(),\n # nn.Dropout(dropout_value)\n ) \n\n\n self.dropout = nn.Dropout(dropout_value)\n\n def forward(self, x):\n x = self.convblock1(x)\n x = self.convblock2(x)\n x = self.convblock3(x)\n x = self.pool1(x)\n x = self.convblock4(x)\n x = self.convblock5(x)\n x = self.convblock6(x)\n x = self.convblock7(x)\n x = self.gap(x) \n x = self.convblock8(x)\n\n x = x.view(-1, 10)\n return F.log_softmax(x, dim=-1)", "_____no_output_____" ] ], [ [ "# Model Params\nCan't emphasize on how important viewing Model Summary is. \nUnfortunately, there is no in-built model visualizer, so we have to take external help", "_____no_output_____" ] ], [ [ "!pip install torchsummary\nfrom torchsummary import summary\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nprint(device)\nmodel = Net().to(device)\nsummary(model, input_size=(1, 28, 28))", "Requirement already satisfied: torchsummary in /usr/local/lib/python3.6/dist-packages (1.5.1)\ncuda\n----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 16, 26, 26] 144\n ReLU-2 [-1, 16, 26, 26] 0\n BatchNorm2d-3 [-1, 16, 26, 26] 32\n Dropout-4 [-1, 16, 26, 26] 0\n Conv2d-5 [-1, 32, 24, 24] 4,608\n ReLU-6 [-1, 32, 24, 24] 0\n BatchNorm2d-7 [-1, 32, 24, 24] 64\n Dropout-8 [-1, 32, 24, 24] 0\n Conv2d-9 [-1, 10, 24, 24] 320\n MaxPool2d-10 [-1, 10, 12, 12] 0\n Conv2d-11 [-1, 16, 10, 10] 1,440\n ReLU-12 [-1, 16, 10, 10] 0\n BatchNorm2d-13 [-1, 16, 10, 10] 32\n Dropout-14 [-1, 16, 10, 10] 0\n Conv2d-15 [-1, 16, 8, 8] 2,304\n ReLU-16 [-1, 16, 8, 8] 0\n BatchNorm2d-17 [-1, 16, 8, 8] 32\n Dropout-18 [-1, 16, 8, 8] 0\n Conv2d-19 [-1, 16, 6, 6] 2,304\n ReLU-20 [-1, 16, 6, 6] 0\n BatchNorm2d-21 [-1, 16, 6, 6] 32\n Dropout-22 [-1, 16, 6, 6] 0\n Conv2d-23 [-1, 16, 6, 6] 2,304\n ReLU-24 [-1, 16, 6, 6] 0\n BatchNorm2d-25 [-1, 16, 6, 6] 32\n Dropout-26 [-1, 16, 6, 6] 0\n AvgPool2d-27 [-1, 16, 1, 1] 0\n Conv2d-28 [-1, 10, 1, 1] 160\n================================================================\nTotal params: 13,808\nTrainable params: 13,808\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.00\nForward/backward pass size (MB): 1.06\nParams size (MB): 0.05\nEstimated Total Size (MB): 1.12\n----------------------------------------------------------------\n" ] ], [ [ "# Training and Testing\n\nAll right, so we have 24M params, and that's too many, we know that. But the purpose of this notebook is to set things right for our future experiments. \n\nLooking at logs can be boring, so we'll introduce **tqdm** progressbar to get cooler logs. \n\nLet's write train and test functions", "_____no_output_____" ] ], [ [ "from tqdm import tqdm\n\ntrain_losses = []\ntest_losses = []\ntrain_acc = []\ntest_acc = []\n\ndef train(model, device, train_loader, optimizer, epoch):\n model.train()\n pbar = tqdm(train_loader)\n correct = 0\n processed = 0\n for batch_idx, (data, target) in enumerate(pbar):\n # get samples\n data, target = data.to(device), target.to(device)\n\n # Init\n optimizer.zero_grad()\n # In PyTorch, we need to set the gradients to zero before starting to do backpropragation because PyTorch accumulates the gradients on subsequent backward passes. \n # Because of this, when you start your training loop, ideally you should zero out the gradients so that you do the parameter update correctly.\n\n # Predict\n y_pred = model(data)\n\n # Calculate loss\n loss = F.nll_loss(y_pred, target)\n train_losses.append(loss)\n\n # Backpropagation\n loss.backward()\n optimizer.step()\n\n # Update pbar-tqdm\n \n pred = y_pred.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n processed += len(data)\n\n pbar.set_description(desc= f'Loss={loss.item()} Batch_id={batch_idx} Accuracy={100*correct/processed:0.2f}')\n train_acc.append(100*correct/processed)\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n test_losses.append(test_loss)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n \n test_acc.append(100. * correct / len(test_loader.dataset))", "_____no_output_____" ], [ "from torch.optim.lr_scheduler import StepLR\n\nmodel = Net().to(device)\noptimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n# scheduler = StepLR(optimizer, step_size=6, gamma=0.1)\n\n\nEPOCHS = 20\nfor epoch in range(EPOCHS):\n print(\"EPOCH:\", epoch)\n train(model, device, train_loader, optimizer, epoch)\n # scheduler.step()\n test(model, device, test_loader)", "\r 0%| | 0/469 [00:00<?, ?it/s]" ] ] ]
[ "markdown", "code", "markdown", "code", "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" ] ]
d01cf7bf4e3d0c654802b8ae6666044d8efef035
9,198
ipynb
Jupyter Notebook
specialized/specialized_form_parser.ipynb
jlehga1/documentai-notebooks
65a3335a70b829b817abf94ae40edcbde2f593d6
[ "Apache-2.0" ]
null
null
null
specialized/specialized_form_parser.ipynb
jlehga1/documentai-notebooks
65a3335a70b829b817abf94ae40edcbde2f593d6
[ "Apache-2.0" ]
null
null
null
specialized/specialized_form_parser.ipynb
jlehga1/documentai-notebooks
65a3335a70b829b817abf94ae40edcbde2f593d6
[ "Apache-2.0" ]
null
null
null
30.55814
209
0.56708
[ [ [ "# Document AI Specialized Parser with HITL\nThis notebook shows you how to use Document AI's specialized parsers ex. Invoice, Receipt, W2, W9, etc. and also shows Human in the Loop (HITL) output for supported parsers.", "_____no_output_____" ] ], [ [ "# Install necessary Python libraries and restart your kernel after.\n!python -m pip install -r ../requirements.txt", "_____no_output_____" ], [ "from google.cloud import documentai_v1beta3 as documentai\nfrom PIL import Image, ImageDraw\n\nimport os\nimport pandas as pd", "_____no_output_____" ] ], [ [ "## Set your processor variables ", "_____no_output_____" ] ], [ [ "# TODO(developer): Fill these variables with your values before running the sample\nPROJECT_ID = \"YOUR_PROJECT_ID_HERE\"\nLOCATION = \"us\" # Format is 'us' or 'eu'\nPROCESSOR_ID = \"PROCESSOR_ID\" # Create processor in Cloud Console\nPDF_PATH = \"../resources/procurement/invoices/invoice.pdf\" # Update to path of target document", "_____no_output_____" ] ], [ [ "The following code calls the synchronous API and parses the form fields and values.", "_____no_output_____" ] ], [ [ "def process_document_sample():\n # Instantiates a client\n client_options = {\"api_endpoint\": \"{}-documentai.googleapis.com\".format(LOCATION)}\n client = documentai.DocumentProcessorServiceClient(client_options=client_options)\n\n # The full resource name of the processor, e.g.:\n # projects/project-id/locations/location/processor/processor-id\n # You must create new processors in the Cloud Console first\n name = f\"projects/{PROJECT_ID}/locations/{LOCATION}/processors/{PROCESSOR_ID}\"\n\n with open(PDF_PATH, \"rb\") as image:\n image_content = image.read()\n\n # Read the file into memory\n document = {\"content\": image_content, \"mime_type\": \"application/pdf\"}\n\n # Configure the process request\n request = {\"name\": name, \"document\": document}\n\n # Recognizes text entities in the PDF document\n result = client.process_document(request=request)\n document = result.document\n entities = document.entities\n print(\"Document processing complete.\\n\\n\")\n\n # For a full list of Document object attributes, please reference this page: https://googleapis.dev/python/documentai/latest/_modules/google/cloud/documentai_v1beta3/types/document.html#Document \n types = []\n values = []\n confidence = []\n \n # Grab each key/value pair and their corresponding confidence scores.\n for entity in entities:\n types.append(entity.type_)\n values.append(entity.mention_text)\n confidence.append(round(entity.confidence,4))\n \n # Create a Pandas Dataframe to print the values in tabular format. \n df = pd.DataFrame({'Type': types, 'Value': values, 'Confidence': confidence})\n display(df)\n \n if result.human_review_operation:\n print (\"Triggered HITL long running operation: {}\".format(result.human_review_operation))\n\n return document\n\n\ndef get_text(doc_element: dict, document: dict):\n \"\"\"\n Document AI identifies form fields by their offsets\n in document text. This function converts offsets\n to text snippets.\n \"\"\"\n response = \"\"\n # If a text segment spans several lines, it will\n # be stored in different text segments.\n for segment in doc_element.text_anchor.text_segments:\n start_index = (\n int(segment.start_index)\n if segment in doc_element.text_anchor.text_segments\n else 0\n )\n end_index = int(segment.end_index)\n response += document.text[start_index:end_index]\n return response", "_____no_output_____" ], [ "doc = process_document_sample()", "_____no_output_____" ] ], [ [ "## Draw the bounding boxes\nWe will now use the spatial data returned by the processor to mark our values on the invoice pdf file that we first converted into a jpg.", "_____no_output_____" ] ], [ [ "JPG_PATH = \"../resources/procurement/invoices/invoice.jpg\" # Update to path of a jpg of your sample document.", "_____no_output_____" ], [ "document_image = Image.open(JPG_PATH)\ndraw = ImageDraw.Draw(document_image)\nfor entity in doc.entities:\n # Draw the bounding box around the entities\n vertices = []\n for vertex in entity.page_anchor.page_refs[0].bounding_poly.normalized_vertices:\n vertices.append({'x': vertex.x * document_image.size[0], 'y': vertex.y * document_image.size[1]})\n draw.polygon([\n vertices[0]['x'], vertices[0]['y'],\n vertices[1]['x'], vertices[1]['y'],\n vertices[2]['x'], vertices[2]['y'],\n vertices[3]['x'], vertices[3]['y']], outline='blue')\ndocument_image", "_____no_output_____" ] ], [ [ "# Human in the loop (HITL) Operation", "_____no_output_____" ], [ "**Only complete this section if a HITL Operation is triggered.** </br>", "_____no_output_____" ] ], [ [ "lro = \"LONG_RUNNING_OPERATION\" # LRO printed in the previous cell ex. projects/660199673046/locations/us/operations/174674963333130330", "_____no_output_____" ], [ "client = documentai.DocumentProcessorServiceClient()\noperation = client._transport.operations_client.get_operation(lro)\nif operation.done:\n print(\"HITL location: {} \".format(str(operation.response.value)[5:-1]))\nelse:\n print('Waiting on human review.')", "_____no_output_____" ], [ "!gsutil cp \"HITL_LOCATION\" response.json # Location printed above ex. gs://gcs_bucket/receipt-output/174674963333130330/data-00001-of-00001.json", "_____no_output_____" ], [ "with open(\"response.json\", \"r\") as file:\n import json\n entities = {}\n data = json.load(file)\n for entity in data['entities']:\n if 'mentionText' in entity:\n entities[entity['type']] = entity['mentionText']\n else:\n entities[entity['type']] = \"\"\n \n for t in entities:\n print(\"{} : {}\\n \".format(t, entities[t]))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
d01cf8c6bf936fff0602867d3e1718978f9bce0c
802,964
ipynb
Jupyter Notebook
performance_on_random.ipynb
ninextycode/finalYearProjectNMF
59edf5ae9bcc56a0a0d557fc92e10a6316da864f
[ "MIT" ]
null
null
null
performance_on_random.ipynb
ninextycode/finalYearProjectNMF
59edf5ae9bcc56a0a0d557fc92e10a6316da864f
[ "MIT" ]
null
null
null
performance_on_random.ipynb
ninextycode/finalYearProjectNMF
59edf5ae9bcc56a0a0d557fc92e10a6316da864f
[ "MIT" ]
null
null
null
148.641984
153,831
0.829009
[ [ [ "Notebook which focuses on the randomly generated data sets and the performance comparison of algorithms on it", "_____no_output_____" ] ], [ [ "from IPython.core.display import display, HTML\ndisplay(HTML('<style>.container {width:100% !important;}</style>'))", "_____no_output_____" ], [ "%matplotlib notebook\nimport matplotlib.pyplot as plt \nimport numpy as np\nimport torch\nfrom itertools import product, chain\n\nimport nmf.mult\nimport nmf.pgrad\nimport nmf.nesterov\n\nimport nmf_torch.mult\nimport nmf_torch.pgrad\nimport nmf_torch.nesterov\nimport nmf_torch.norms\n\nimport matplotlib\nimport pickle\n\nfrom performance.performance_eval_func import get_random_lowrank_matrix, get_time_ratio,\\\n compare_performance, plot_errors_dict,\\\n torch_algo_wrapper,\\\n plot_ratios_gpu_algo, plot_ratios_cpu_gpu, plot_ratios_cpu_algo,\\\n plot_errors_dict, errors_at_time_t_over_inner_dim\n ", "_____no_output_____" ], [ "algo_dict_to_test = {\n \"mult\": nmf.mult.factorize_Fnorm,\n \"pgrad\": nmf.pgrad.factorize_Fnorm_subproblems,\n \"nesterov\": nmf.nesterov.factorize_Fnorm,\n\n \"mult_torch\": torch_algo_wrapper(nmf_torch.mult.factorize_Fnorm, \n device=\"cuda\"),\n \"pgrad_torch\": torch_algo_wrapper(nmf_torch.pgrad.factorize_Fnorm_subproblems, \n device=\"cuda\"),\n \"nesterov_torch\": torch_algo_wrapper(nmf_torch.nesterov.factorize_Fnorm, \n device=\"cuda\")\n}", "_____no_output_____" ], [ "f, ax = plt.subplots()\nplot_errors_dict(errors_over_r_random, ax, log=True, x_lbl=\"Inner dim\", title=\"site3\")\n\nf, ax = plt.subplots()\nplot_errors_dict(errors_over_r_random, ax, log=False, x_lbl=\"Inner dim\", title=\"site3\")", "_____no_output_____" ], [ "shapes = [(5 * a, a) for a in [30, 100, 300, 1000, 3000]]\nshapes", "_____no_output_____" ], [ "inner_dims_small = [sh[1] // 10 for sh in shapes]\ninner_dims_small", "_____no_output_____" ], [ "inner_dims_big = [8 * sh[1] // 10 for sh in shapes]\ninner_dims_big", "_____no_output_____" ], [ "shapes_all = shapes + shapes\ninner_dims = inner_dims_small + inner_dims_big", "_____no_output_____" ], [ "times = [5, 25, 200, 1200, 8000]\ntimes = times + [t * 2 for t in times]", "_____no_output_____" ], [ "print(len(shapes_all))", "10\n" ], [ "errors_dict = pickle.load(open(\"random_data_errors_dict.pkl\",\"rb\"))", "_____no_output_____" ], [ "del errors_dict[(3, (150, 30))]", "_____no_output_____" ], [ "errors_dict = {}", "_____no_output_____" ], [ "for inner_dim, shape, t in zip(inner_dims, shapes_all, times):\n print((inner_dim, shape))\n if (inner_dim, shape) in errors_dict.keys():\n continue\n \n V = get_random_lowrank_matrix(shape[0], inner_dim, shape[1]) + np.random.rand(*shape) * 0.1\n\n W_init = np.random.rand(shape[0], inner_dim)\n H_init = np.random.rand(inner_dim, shape[1])\n\n errors = compare_performance(V=V, inner_dim=inner_dim, time_limit=t,\n W_init=W_init, H_init=H_init, \n algo_dict_to_test=algo_dict_to_test)\n errors_dict[(inner_dim, shape)] = errors\n pickle.dump(errors_dict, open(\"random_data_errors_dict.pkl\",\"wb\"))", "(3, (150, 30))\nStarting mult\nStarting pgrad\nStarting nesterov\nStarting mult_torch\nStarting pgrad_torch\nStarting nesterov_torch\n(10, (500, 100))\n(30, (1500, 300))\n(100, (5000, 1000))\n(300, (15000, 3000))\n(24, (150, 30))\n(80, (500, 100))\n(240, (1500, 300))\n(800, (5000, 1000))\n(2400, (15000, 3000))\n" ], [ "pickle.dump(errors_dict, open(\"random_data_errors_dict.pkl\",\"wb\"))", "_____no_output_____" ], [ "keys = zip(inner_dims, shapes_all)\nkeys = sorted(keys, key=lambda k: k[0])\nkeys = sorted(keys, key=lambda k: k[1][0])", "_____no_output_____" ], [ "keys", "_____no_output_____" ], [ "for k in keys:\n r, shape = k\n M = np.random.rand(shape[0], r) @ np.random.rand(r, shape[1])\n\n errros_dict_particular_data = errors_dict[k]\n\n f, axes = plt.subplots(3, 2, figsize=(8, 7), dpi=100, gridspec_kw=dict(hspace=0.45, top=0.92, bottom=0.08, \n left=0.08, right=0.99))\n f.suptitle(\"Comparison, time ratio for {}, {:.2f}KB, {:.2f}MB\".format(k, M.nbytes / 2**10, M.nbytes / 2**20))\n\n plot_errors_dict(errros_dict_particular_data, axes[0, 0], log=True, title=\"Objective function\", x_lbl=\"time [s]\")\n\n plot_ratios_cpu_gpu(errros_dict_particular_data, axes[0, 1])\n plot_ratios_cpu_algo(errros_dict_particular_data, axes[1:, 0], selected_algs=[\"mult\", \"pgrad\", \"nesterov\"])\n plot_ratios_gpu_algo(errros_dict_particular_data, axes[1:, 1],\n selected_algs=[\"mult_torch\", \"pgrad_torch\", \"nesterov_torch\"])", "_____no_output_____" ], [ "font = {'family' : 'normal',\n 'weight' : 'normal',\n 'size' : 14}\n\nmatplotlib.rc('font', **font)", "_____no_output_____" ], [ "figsize = (9, 10)\n\ngridspec_kw = dict(wspace=0.4, hspace=0.9,\n top=0.85,\n bottom=0.1,\n left=0.1, right=0.95)", "_____no_output_____" ], [ "plt.close(\"all\")\n\n\nf, axes1 = plt.subplots(3, 2, figsize=figsize, dpi=100, \n gridspec_kw=gridspec_kw)\nf.suptitle(\"Ratio between time required\\nto reach particular cost function value on CPU and on GPU\")\n\nf, axes2 = plt.subplots(3, 2, figsize=figsize, dpi=100, \n gridspec_kw=gridspec_kw)\nf.suptitle(\"Ratio between time required\\nto reach particular cost function value on CPU and on GPU\")\n\naxes1[0,0].get_shared_y_axes().join(*axes1[0, :], *axes1[1, :], *axes1[2, :])\naxes2[0,0].get_shared_y_axes().join(*axes2[0, :], *axes2[1, :], *axes2[2, :])\n\naxes1[2,1].set_axis_off()\naxes2[2,1].set_axis_off()\n\naxes1 = list(axes1.ravel()) \naxes2 = list(axes2.ravel())\n\n\nlegend_is = False\nfor k, a in zip(keys, chain.from_iterable(zip(axes1, axes2))):\n print(a)\n r, shape = k\n plot_ratios_cpu_gpu(errors_dict[k], a)\n \n M = np.random.rand(shape[0], r) @ np.random.rand(r, shape[1])\n kb = M.nbytes / 2**10 \n mb = M.nbytes / 2**20\n \n if mb < 1:\n size = \"{:.1f}KB\".format(kb) \n else:\n size = \"{:.1f}MB\".format(mb) \n \n a.set_title(\"Factorization of size {}\\nmat. dim. {}, {}\".format(k[0], k[1], size))\n \n if legend_is:\n a.get_legend().remove()\n else:\n legend_is = True", "_____no_output_____" ], [ "plt.close(\"all\")\n\nf, axes1 = plt.subplots(3, 2, figsize=figsize, dpi=100, \n gridspec_kw=gridspec_kw)\n\nf.suptitle(\"Ratio between time required to reach a particular\"+\n \"cost \\n function value for multiplicative algorithms and gradient algorithms\")\n\n\nf, axes2 = plt.subplots(3, 2, figsize=figsize, dpi=100, \n gridspec_kw=gridspec_kw)\n\n\nf.suptitle(\"Ratio between time required to reach a particular cost \\n function value for projecitve and Nesterov gradient algorithms\")\n\n\naxes1 = list(axes1.ravel())\naxes2 = list(axes2.ravel())\n\naxes1[-1].set_axis_off()\naxes2[-1].set_axis_off()\n\n\n# axes1[0].get_shared_y_axes().join(*axes1)\naxes2[0].get_shared_y_axes().join(*axes2)\n\nprint(keys)\nprint(len(axes1))\nprint(len(axes2))\n\nlegend_is = False\nfor k, a1, a2 in zip(keys[::2], axes1, axes2):\n r, shape = k\n \n if r != 0.1 * shape[1]:\n print(k)\n continue\n \n plot_ratios_gpu_algo(errors_dict[k], [a1, a2],\n selected_algs=[\"mult_torch\", \n \"pgrad_torch\",\n \"nesterov_torch\"])\n \n M = np.random.rand(shape[0], r) @ np.random.rand(r, shape[1])\n kb = M.nbytes / 2**10 \n mb = M.nbytes / 2**20\n \n if mb < 1:\n size = \"{:.2f}KB\".format(kb) \n else:\n size = \"{:.2f}MB\".format(mb) \n \n a1.set_title(\"factorization of size {}\\nmat. shape {} {}\".format(k[0], k[1], size))\n a2.set_title(\"factorization of size {}\\nmat. shape {} {}\".format(k[0], k[1], size))\n \n if legend_is:\n a1.get_legend().remove()\n a2.get_legend().remove()\n else:\n legend_is = True", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01cfd70d27f1dcaaa1fae90c597dab9c977fa3c
11,234
ipynb
Jupyter Notebook
doc/auto_tutorials/plot_02-FOOOF.ipynb
varman-m/eeg_notebooks_doc
12230719637c8087b020e8d5feeb20520a4da74d
[ "Apache-2.0" ]
1
2020-11-05T21:30:07.000Z
2020-11-05T21:30:07.000Z
doc/auto_tutorials/plot_02-FOOOF.ipynb
varman-m/eeg_notebooks_doc
12230719637c8087b020e8d5feeb20520a4da74d
[ "Apache-2.0" ]
null
null
null
doc/auto_tutorials/plot_02-FOOOF.ipynb
varman-m/eeg_notebooks_doc
12230719637c8087b020e8d5feeb20520a4da74d
[ "Apache-2.0" ]
null
null
null
49.707965
1,148
0.616699
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\n02: Fitting Power Spectrum Models\n=================================\n\nIntroduction to the module, beginning with the FOOOF object.\n", "_____no_output_____" ] ], [ [ "# Import the FOOOF object\nfrom fooof import FOOOF\n\n# Import utility to download and load example data\nfrom fooof.utils.download import load_fooof_data", "_____no_output_____" ], [ "# Download examples data files needed for this example\nfreqs = load_fooof_data('freqs.npy', folder='data')\nspectrum = load_fooof_data('spectrum.npy', folder='data')", "_____no_output_____" ] ], [ [ "FOOOF Object\n------------\n\nAt the core of the module, which is object oriented, is the :class:`~fooof.FOOOF` object,\nwhich holds relevant data and settings as attributes, and contains methods to run the\nalgorithm to parameterize neural power spectra.\n\nThe organization is similar to sklearn:\n\n- A model object is initialized, with relevant settings\n- The model is used to fit the data\n- Results can be extracted from the object\n\n\n", "_____no_output_____" ], [ "Calculating Power Spectra\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe :class:`~fooof.FOOOF` object fits models to power spectra. The module itself does not\ncompute power spectra, and so computing power spectra needs to be done prior to using\nthe FOOOF module.\n\nThe model is broadly agnostic to exactly how power spectra are computed. Common\nmethods, such as Welch's method, can be used to compute the spectrum.\n\nIf you need a module in Python that has functionality for computing power spectra, try\n`NeuroDSP <https://neurodsp-tools.github.io/neurodsp/>`_.\n\nNote that FOOOF objects require frequency and power values passed in as inputs to\nbe in linear spacing. Passing in non-linear spaced data (such logged values) may\nproduce erroneous results.\n\n\n", "_____no_output_____" ], [ "Fitting an Example Power Spectrum\n---------------------------------\n\nThe following example demonstrates fitting a power spectrum model to a single power spectrum.\n\n\n", "_____no_output_____" ] ], [ [ "# Initialize a FOOOF object\nfm = FOOOF()\n\n# Set the frequency range to fit the model\nfreq_range = [2, 40]\n\n# Report: fit the model, print the resulting parameters, and plot the reconstruction\nfm.report(freqs, spectrum, freq_range)", "_____no_output_____" ] ], [ [ "Fitting Models with 'Report'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe above method 'report', is a convenience method that calls a series of methods:\n\n- :meth:`~fooof.FOOOF.fit`: fits the power spectrum model\n- :meth:`~fooof.FOOOF.print_results`: prints out the results\n- :meth:`~fooof.FOOOF.plot`: plots to data and model fit\n\nEach of these methods can also be called individually.\n\n\n", "_____no_output_____" ] ], [ [ "# Alternatively, just fit the model with FOOOF.fit() (without printing anything)\nfm.fit(freqs, spectrum, freq_range)\n\n# After fitting, plotting and parameter fitting can be called independently:\n# fm.print_results()\n# fm.plot()", "_____no_output_____" ] ], [ [ "Model Parameters\n~~~~~~~~~~~~~~~~\n\nOnce the power spectrum model has been calculated, the model fit parameters are stored\nas object attributes that can be accessed after fitting.\n\nFollowing the sklearn convention, attributes that are fit as a result of\nthe model have a trailing underscore, for example:\n\n- ``aperiodic_params_``\n- ``peak_params_``\n- ``error_``\n- ``r2_``\n- ``n_peaks_``\n\n\n", "_____no_output_____" ], [ "Access model fit parameters from FOOOF object, after fitting:\n\n\n", "_____no_output_____" ] ], [ [ "# Aperiodic parameters\nprint('Aperiodic parameters: \\n', fm.aperiodic_params_, '\\n')\n\n# Peak parameters\nprint('Peak parameters: \\n', fm.peak_params_, '\\n')\n\n# Goodness of fit measures\nprint('Goodness of fit:')\nprint(' Error - ', fm.error_)\nprint(' R^2 - ', fm.r_squared_, '\\n')\n\n# Check how many peaks were fit\nprint('Number of fit peaks: \\n', fm.n_peaks_)", "_____no_output_____" ] ], [ [ "Selecting Parameters\n~~~~~~~~~~~~~~~~~~~~\n\nYou can also select parameters using the :meth:`~fooof.FOOOF.get_params`\nmethod, which can be used to specify which parameters you want to extract.\n\n\n", "_____no_output_____" ] ], [ [ "# Extract a model parameter with `get_params`\nerr = fm.get_params('error')\n\n# Extract parameters, indicating sub-selections of parameter\nexp = fm.get_params('aperiodic_params', 'exponent')\ncfs = fm.get_params('peak_params', 'CF')\n\n# Print out a custom parameter report\ntemplate = (\"With an error level of {error:1.2f}, FOOOF fit an exponent \"\n \"of {exponent:1.2f} and peaks of {cfs:s} Hz.\")\nprint(template.format(error=err, exponent=exp,\n cfs=' & '.join(map(str, [round(cf, 2) for cf in cfs]))))", "_____no_output_____" ] ], [ [ "For a full description of how you can access data with :meth:`~fooof.FOOOF.get_params`,\ncheck the method's documentation.\n\nAs a reminder, you can access the documentation for a function using '?' in a\nJupyter notebook (ex: `fm.get_params?`), or more generally with the `help` function\nin general Python (ex: `help(get_params)`).\n\n\n", "_____no_output_____" ], [ "Notes on Interpreting Peak Parameters\n-------------------------------------\n\nPeak parameters are labeled as:\n\n- CF: center frequency of the extracted peak\n- PW: power of the peak, over and above the aperiodic component\n- BW: bandwidth of the extracted peak\n\nNote that the peak parameters that are returned are not exactly the same as the\nparameters of the Gaussians used internally to fit the peaks.\n\nSpecifically:\n\n- CF is the exact same as mean parameter of the Gaussian\n- PW is the height of the model fit above the aperiodic component [1],\n which is not necessarily the same as the Gaussian height\n- BW is 2 * the standard deviation of the Gaussian [2]\n\n[1] Since the Gaussians are fit together, if any Gaussians overlap,\nthan the actual height of the fit at a given point can only be assessed\nwhen considering all Gaussians. To be better able to interpret heights\nfor single peak fits, we re-define the peak height as above, and label it\nas 'power', as the units of the input data are expected to be units of power.\n\n[2] Gaussian standard deviation is '1 sided', where as the returned BW is '2 sided'.\n\n\n", "_____no_output_____" ], [ "The underlying gaussian parameters are also available from the FOOOF object,\nin the ``gaussian_params_`` attribute.\n\n\n", "_____no_output_____" ] ], [ [ "# Compare the 'peak_params_' to the underlying gaussian parameters\nprint(' Peak Parameters \\t Gaussian Parameters')\nfor peak, gauss in zip(fm.peak_params_, fm.gaussian_params_):\n print('{:5.2f} {:5.2f} {:5.2f} \\t {:5.2f} {:5.2f} {:5.2f}'.format(*peak, *gauss))", "_____no_output_____" ] ], [ [ "FOOOFResults\n~~~~~~~~~~~~\n\nThere is also a convenience method to return all model fit results:\n:func:`~fooof.FOOOF.get_results`.\n\nThis method returns all the model fit parameters, including the underlying Gaussian\nparameters, collected together into a FOOOFResults object.\n\nThe FOOOFResults object, which in Python terms is a named tuple, is a standard data\nobject used with FOOOF to organize and collect parameter data.\n\n\n", "_____no_output_____" ] ], [ [ "# Grab each model fit result with `get_results` to gather all results together\n# Note that this returns a FOOOFResult object\nfres = fm.get_results()\n\n# You can also unpack all fit parameters when using `get_results`\nap_params, peak_params, r_squared, fit_error, gauss_params = fm.get_results()", "_____no_output_____" ], [ "# Print out the FOOOFResults\nprint(fres, '\\n')\n\n# From FOOOFResults, you can access the different results\nprint('Aperiodic Parameters: \\n', fres.aperiodic_params)\n\n# Check the r^2 and error of the model fit\nprint('R-squared: \\n {:5.4f}'.format(fm.r_squared_))\nprint('Fit error: \\n {:5.4f}'.format(fm.error_))", "_____no_output_____" ] ], [ [ "Conclusion\n----------\n\nIn this tutorial, we have explored the basics of the :class:`~fooof.FOOOF` object,\nfitting power spectrum models, and extracting parameters.\n\nBefore we move on to controlling the fit procedure, and interpreting the results,\nin the next tutorial, we will first explore how this model is actually fit.\n\n\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d01d01d80a35e57154554dd399c3d8f781043c10
124,777
ipynb
Jupyter Notebook
Section-08-Discretisation/08.01-Equal-width-discretisation.ipynb
cym3509/FeatureEngineering
8237dbdec803f5bf91543466cff011108fb2c935
[ "BSD-3-Clause" ]
1
2020-07-27T14:00:50.000Z
2020-07-27T14:00:50.000Z
Section-08-Discretisation/08.01-Equal-width-discretisation.ipynb
cym3509/FeatureEngineering
8237dbdec803f5bf91543466cff011108fb2c935
[ "BSD-3-Clause" ]
null
null
null
Section-08-Discretisation/08.01-Equal-width-discretisation.ipynb
cym3509/FeatureEngineering
8237dbdec803f5bf91543466cff011108fb2c935
[ "BSD-3-Clause" ]
null
null
null
89.253934
19,392
0.815607
[ [ [ "## Discretisation\n\nDiscretisation is the process of transforming continuous variables into discrete variables by creating a set of contiguous intervals that span the range of the variable's values. Discretisation is also called **binning**, where bin is an alternative name for interval.\n\n\n### Discretisation helps handle outliers and may improve value spread in skewed variables\n\nDiscretisation helps handle outliers by placing these values into the lower or higher intervals, together with the remaining inlier values of the distribution. Thus, these outlier observations no longer differ from the rest of the values at the tails of the distribution, as they are now all together in the same interval / bucket. In addition, by creating appropriate bins or intervals, discretisation can help spread the values of a skewed variable across a set of bins with equal number of observations.\n\n\n### Discretisation approaches\n\nThere are several approaches to transform continuous variables into discrete ones. Discretisation methods fall into 2 categories: **supervised and unsupervised**. Unsupervised methods do not use any information, other than the variable distribution, to create the contiguous bins in which the values will be placed. Supervised methods typically use target information in order to create the bins or intervals.\n\n\n#### Unsupervised discretisation methods\n\n- Equal width discretisation\n- Equal frequency discretisation\n- K-means discretisation\n\n#### Supervised discretisation methods\n\n- Discretisation using decision trees\n\n\nIn this lecture, I will describe **equal width discretisation**.\n\n\n## Equal width discretisation\n\nEqual width discretisation divides the scope of possible values into N bins of the same width.The width is determined by the range of values in the variable and the number of bins we wish to use to divide the variable:\n\nwidth = (max value - min value) / N\n\nwhere N is the number of bins or intervals.\n\nFor example if the values of the variable vary between 0 and 100, we create 5 bins like this: width = (100-0) / 5 = 20. The bins thus are 0-20, 20-40, 40-60, 80-100. The first and final bins (0-20 and 80-100) can be expanded to accommodate outliers (that is, values under 0 or greater than 100 would be placed in those bins as well).\n\nThere is no rule of thumb to define N, that is something to determine experimentally.\n\n## In this demo\n\nWe will learn how to perform equal width binning using the Titanic dataset with\n\n- pandas and NumPy\n- Feature-engine\n- Scikit-learn", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.preprocessing import KBinsDiscretizer\n\nfrom feature_engine.discretisers import EqualWidthDiscretiser", "_____no_output_____" ], [ "# load the numerical variables of the Titanic Dataset\n\ndata = pd.read_csv('../titanic.csv',\n usecols=['age', 'fare', 'survived'])\n\ndata.head()", "_____no_output_____" ], [ "# Let's separate into train and test set\n\nX_train, X_test, y_train, y_test = train_test_split(\n data[['age', 'fare']],\n data['survived'],\n test_size=0.3,\n random_state=0)\n\nX_train.shape, X_test.shape", "_____no_output_____" ] ], [ [ "The variables Age and fare contain missing data, that I will fill by extracting a random sample of the variable.", "_____no_output_____" ] ], [ [ "def impute_na(data, variable):\n\n df = data.copy()\n\n # random sampling\n df[variable + '_random'] = df[variable]\n\n # extract the random sample to fill the na\n random_sample = X_train[variable].dropna().sample(\n df[variable].isnull().sum(), random_state=0)\n\n # pandas needs to have the same index in order to merge datasets\n random_sample.index = df[df[variable].isnull()].index\n df.loc[df[variable].isnull(), variable + '_random'] = random_sample\n\n return df[variable + '_random']", "_____no_output_____" ], [ "# replace NA in both train and test sets\n\nX_train['age'] = impute_na(data, 'age')\nX_test['age'] = impute_na(data, 'age')\n\nX_train['fare'] = impute_na(data, 'fare')\nX_test['fare'] = impute_na(data, 'fare')", "_____no_output_____" ], [ "# let's explore the distribution of age\n\ndata[['age', 'fare']].hist(bins=30, figsize=(8,4))\nplt.show()", "_____no_output_____" ] ], [ [ "## Equal width discretisation with pandas and NumPy\n\nFirst we need to determine the intervals' edges or limits.", "_____no_output_____" ] ], [ [ "# let's capture the range of the variable age\n\nage_range = X_train['age'].max() - X_train['age'].min()\n\nage_range", "_____no_output_____" ], [ "# let's divide the range into 10 equal width bins\n\nage_range / 10", "_____no_output_____" ] ], [ [ "The range or width of our intervals will be 7 years.", "_____no_output_____" ] ], [ [ "# now let's capture the lower and upper boundaries\n\nmin_value = int(np.floor( X_train['age'].min()))\nmax_value = int(np.ceil( X_train['age'].max()))\n\n# let's round the bin width\ninter_value = int(np.round(age_range / 10))\n\nmin_value, max_value, inter_value", "_____no_output_____" ], [ "# let's capture the interval limits, so we can pass them to the pandas cut \n# function to generate the bins\n\nintervals = [i for i in range(min_value, max_value+inter_value, inter_value)]\n\nintervals", "_____no_output_____" ], [ "# let's make labels to label the different bins\n\nlabels = ['Bin_' + str(i) for i in range(1, len(intervals))]\n\nlabels", "_____no_output_____" ], [ "# create binned age / discretise age\n\n# create one column with labels\nX_train['Age_disc_labels'] = pd.cut(x=X_train['age'],\n bins=intervals,\n labels=labels,\n include_lowest=True)\n\n# and one with bin boundaries\nX_train['Age_disc'] = pd.cut(x=X_train['age'],\n bins=intervals,\n include_lowest=True)\n\nX_train.head(10)", "_____no_output_____" ] ], [ [ "We can see in the above output how by discretising using equal width, we placed each Age observation within one interval / bin. For example, age=13 was placed in the 7-14 interval, whereas age 30 was placed into the 28-35 interval.\n\nWhen performing equal width discretisation, we guarantee that the intervals are all of the same lenght, however there won't necessarily be the same number of observations in each of the intervals. See below:", "_____no_output_____" ] ], [ [ "X_train.groupby('Age_disc')['age'].count()", "_____no_output_____" ], [ "X_train.groupby('Age_disc')['age'].count().plot.bar()\nplt.xticks(rotation=45)\nplt.ylabel('Number of observations per bin')", "_____no_output_____" ] ], [ [ "The majority of people on the Titanic were between 14-42 years of age.\n\nNow, we can discretise Age in the test set, using the same interval boundaries that we calculated for the train set:", "_____no_output_____" ] ], [ [ "X_test['Age_disc_labels'] = pd.cut(x=X_test['age'],\n bins=intervals,\n labels=labels,\n include_lowest=True)\n\nX_test['Age_disc'] = pd.cut(x=X_test['age'],\n bins=intervals,\n include_lowest=True)\n\nX_test.head()", "_____no_output_____" ], [ "# if the distributions in train and test set are similar, we should expect similar propotion of\n# observations in the different intervals in the train and test set\n# let's see that below\n\nt1 = X_train.groupby(['Age_disc'])['age'].count() / len(X_train)\nt2 = X_test.groupby(['Age_disc'])['age'].count() / len(X_test)\n\ntmp = pd.concat([t1, t2], axis=1)\ntmp.columns = ['train', 'test']\ntmp.plot.bar()\nplt.xticks(rotation=45)\nplt.ylabel('Number of observations per bin')", "_____no_output_____" ] ], [ [ "## Equal width discretisation with Feature-Engine", "_____no_output_____" ] ], [ [ "# Let's separate into train and test set\n\nX_train, X_test, y_train, y_test = train_test_split(\n data[['age', 'fare']],\n data['survived'],\n test_size=0.3,\n random_state=0)\n\nX_train.shape, X_test.shape", "_____no_output_____" ], [ "# replace NA in both train and test sets\n\nX_train['age'] = impute_na(data, 'age')\nX_test['age'] = impute_na(data, 'age')\n\nX_train['fare'] = impute_na(data, 'fare')\nX_test['fare'] = impute_na(data, 'fare')", "_____no_output_____" ], [ "# with feature engine we can automate the process for many variables\n# in one line of code\n\ndisc = EqualWidthDiscretiser(bins=10, variables = ['age', 'fare'])\n\ndisc.fit(X_train)", "_____no_output_____" ], [ "# in the binner dict, we can see the limits of the intervals. For age\n# the value increases aproximately 7 years from one bin to the next.\n\n# for fare it increases in around 50 dollars from one interval to the \n# next, but it increases always the same value, aka, same width.\n\ndisc.binner_dict_", "_____no_output_____" ], [ "# transform train and text\n\ntrain_t = disc.transform(X_train)\ntest_t = disc.transform(X_test)", "_____no_output_____" ], [ "train_t.head()", "_____no_output_____" ], [ "t1 = train_t.groupby(['age'])['age'].count() / len(train_t)\nt2 = test_t.groupby(['age'])['age'].count() / len(test_t)\n\ntmp = pd.concat([t1, t2], axis=1)\ntmp.columns = ['train', 'test']\ntmp.plot.bar()\nplt.xticks(rotation=0)\nplt.ylabel('Number of observations per bin')", "_____no_output_____" ], [ "t1 = train_t.groupby(['fare'])['fare'].count() / len(train_t)\nt2 = test_t.groupby(['fare'])['fare'].count() / len(test_t)\n\ntmp = pd.concat([t1, t2], axis=1)\ntmp.columns = ['train', 'test']\ntmp.plot.bar()\nplt.xticks(rotation=0)\nplt.ylabel('Number of observations per bin')", "_____no_output_____" ] ], [ [ "We can see quite clearly, that equal width discretisation does not improve the value spread. The original variable Fare was skewed, and the discrete variable is also skewed.\n\n## Equal width discretisation with Scikit-learn", "_____no_output_____" ] ], [ [ "# Let's separate into train and test set\n\nX_train, X_test, y_train, y_test = train_test_split(\n data[['age', 'fare']],\n data['survived'],\n test_size=0.3,\n random_state=0)\n\nX_train.shape, X_test.shape", "_____no_output_____" ], [ "# replace NA in both train and test sets\n\nX_train['age'] = impute_na(data, 'age')\nX_test['age'] = impute_na(data, 'age')\n\nX_train['fare'] = impute_na(data, 'fare')\nX_test['fare'] = impute_na(data, 'fare')", "_____no_output_____" ], [ "disc = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform')\n\ndisc.fit(X_train[['age', 'fare']])", "_____no_output_____" ], [ "disc.bin_edges_", "_____no_output_____" ], [ "train_t = disc.transform(X_train[['age', 'fare']])\n\ntrain_t = pd.DataFrame(train_t, columns = ['age', 'fare'])\n\ntrain_t.head()", "_____no_output_____" ], [ "test_t = disc.transform(X_test[['age', 'fare']])\n\ntest_t = pd.DataFrame(test_t, columns = ['age', 'fare'])", "_____no_output_____" ], [ "t1 = train_t.groupby(['age'])['age'].count() / len(train_t)\nt2 = test_t.groupby(['age'])['age'].count() / len(test_t)\n\ntmp = pd.concat([t1, t2], axis=1)\ntmp.columns = ['train', 'test']\ntmp.plot.bar()\nplt.xticks(rotation=0)\nplt.ylabel('Number of observations per bin')", "_____no_output_____" ], [ "t1 = train_t.groupby(['fare'])['fare'].count() / len(train_t)\nt2 = test_t.groupby(['fare'])['fare'].count() / len(test_t)\n\ntmp = pd.concat([t1, t2], axis=1)\ntmp.columns = ['train', 'test']\ntmp.plot.bar()\nplt.xticks(rotation=0)\nplt.ylabel('Number of observations per bin')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01d2ecd4bd595fb0947f289dd35fb299c66a89f
18,244
ipynb
Jupyter Notebook
homework/hw0/hw0.ipynb
aare1981/mcis6273_f21_datamining
0bc0843712a05f05b9fae0b25a43391f11ba4f5c
[ "CC0-1.0" ]
1
2021-08-31T23:49:23.000Z
2021-08-31T23:49:23.000Z
homework/hw0/hw0.ipynb
aare1981/mcis6273_f21_datamining
0bc0843712a05f05b9fae0b25a43391f11ba4f5c
[ "CC0-1.0" ]
null
null
null
homework/hw0/hw0.ipynb
aare1981/mcis6273_f21_datamining
0bc0843712a05f05b9fae0b25a43391f11ba4f5c
[ "CC0-1.0" ]
18
2021-08-22T20:43:46.000Z
2021-12-15T08:19:44.000Z
18,244
18,244
0.718209
[ [ [ "# MCIS6273 Data Mining (Prof. Maull) / Fall 2021 / HW0\n\n**This assignment is worth up to 20 POINTS to your grade total if you complete it on time.**\n\n| Points <br/>Possible | Due Date | Time Commitment <br/>(estimated) |\n|:---------------:|:--------:|:---------------:|\n| 20 | Wednesday, Sep 1 @ Midnight | _up to_ 20 hours |\n\n\n* **GRADING:** Grading will be aligned with the completeness of the objectives.\n\n* **INDEPENDENT WORK:** Copying, cheating, plagiarism and academic dishonesty _are not tolerated_ by University or course policy. Please see the syllabus for the full departmental and University statement on the academic code of honor.\n\n## OBJECTIVES\n* Familiarize yourself with the JupyterLab environment, Markdown and Python\n\n* Familiarize yourself with Github and basic git\n\n* Explore JupyterHub Linux console integrating what you learned in the prior parts of this homework\n\n* Listen to the Talk Python['Podcast'] from June 25, 2021: A Path to Data Science Interview with Sanyam Bhutani\n\n* Explore Python for data munging and analysis, with an introduction to CSV and Pandas\n\n## WHAT TO TURN IN\nYou are being encouraged to turn the assignment in using the provided\nJupyter Notebook. To do so, make a directory in your Lab environment called\n`homework/hw0`. Put all of your files in that directory. Then zip that directory,\nrename it with your name as the first part of the filename (e.g. `maull_hw0_files.zip`), then\ndownload it to your local machine, then upload the `.zip` to Blackboard.\n\nIf you do not know how to do this, please ask, or visit one of the many tutorials out there\non the basics of using zip in Linux.\n\nIf you choose not to use the provided notebook, you will still need to turn in a\n`.ipynb` Jupyter Notebook and corresponding files according to the instructions in\nthis homework.\n\n\n## ASSIGNMENT TASKS\n### (0%) Familiarize yourself with the JupyterLab environment, Markdown and Python \n\nAs stated in the course announcement [Jupyter (https://jupyter.org)](https://jupyter.org) is the\ncore platform we will be using in this course and\nis a popular platform for data scientists around the world. We have a JupyterLab\nsetup for this course so that we can operate in a cloud-hosted environment, free from\nsome of the resource constraints of running Jupyter on your local machine (though you are free to set\nit up on your own and seek my advice if you desire).\n\nYou have been given the information about the Jupyter environment we have setup for our course, and\nthe underlying Python environment will be using is the [Anaconda (https://anaconda.com)](https://anaconda.com)\ndistribution. It is not necessary for this assignment, but you are free to look at the multitude\nof packages installed with Anaconda, though we will not use the majority of them explicitly.\n\nAs you will soon find out, Notebooks are an incredibly effective way to mix code with narrative\nand you can create cells that are entirely code or entirely Markdown. Markdown (MD or `md`) is\na highly readable text format that allows for easy documentation of text files, while allowing\nfor HTML-based rendering of the text in a way that is style-independent.\n\nWe will be using Markdown frequently in this course, and you will learn that there are many different\n\"flavors\" or Markdown. We will only be using the basic flavor, but you will benefit from exploring\nthe \"Github flavored\" Markdown, though you will not be responsible for using it in this course -- only the\n\"basic\" flavor. Please refer to the original course announcement about Markdown.\n\n&#167; **THERE IS NOTHING TO TURN IN FOR THIS PART.** Play with and become familiar with the basic functions of\nthe Lab environment given to you online in the course Blackboard.\n\n\n&#167; **PLEASE _CREATE A MARKDOWN DOCUMENT_ CALLED `semester_goals.md` WITH 3 SENTENCES/FRAGMENTS THAT\nANSWER THE FOLLOWING QUESTION:**\n\n* **What do you wish to accomplish this semester in Data Mining?**\n\nRead the documentation for basic Markdown [here](https://www.markdownguide.org/basic-syntax). \nTurn in the text `.md` file *not* the processed `.html`. In whatever you turn in, \nyou must show the use of *ALL* the following:\n\n* headings (one level is fine),\n* bullets,\n* bold and italics\n\nAgain, the content of your document needs to address the question above and it should live\nin the top level directory of your assignment submission. This part will be graded but no\npoints are awarded for your answer.\n\n\n\n### (0%) Familiarize yourself with Github and basic git \n\n[Github (https://github.com)](https://github.com) is the _de facto_ platform for open source software in the world based\non the very popular [git (https://git-scm.org)](https://git-scm.org) version control system. Git has a sophisticated set\nof tools for version control based on the concept of local repositories for fast commits and remote\nrepositories only when collaboration and remote synchronization is necessary. Github enhances git by providing\ntools and online hosting of public and private repositories to encourage and promote sharing and collaboration.\nGithub hosts some of the world's most widely used open source software.\n\n**If you are already familiar with git and Github, then this part will be very easy!**\n\n&#167; **CREATE A PUBLIC GITHUB REPO NAMED `\"mcis6273-F21-datamining\"` AND PLACE A README.MD FILE IN IT.**\nCreate your first file called\n`README.md` at the top level of the repository. You can put whatever text you like in the file \n(If you like, use something like [lorem ipsum](https://lipsum.com/)\nto generate random sentences to place in the file.).\nPlease include the link to **your** Github repository that now includes the minimal `README.md`. \nYou don't have to have anything elaborate in that file or the repo. \n\n\n\n### (0%) Explore JupyterHub Linux console integrating what you learned in the prior parts of this homework \n\nThe Linux console in JupyterLab is a great way to perform command-line tasks and is an essential tool\nfor basic scripting that is part of a data scientist's toolkit. Open a console in the lab environment\nand familiarize yourself with your files and basic commands using git as indicated below.\n\n1. In a new JupyterLab command line console, run the `git clone` command to clone the new\n repository you created in the prior part.\n You will want to read the documentation on this \n command (try here [https://www.git-scm.com/docs/git-clone](https://www.git-scm.com/docs/git-clone) to get a good\n start).\n2. Within the same console, modify your `README.md` file, check it in and push it back to your repository, using\n `git push`. Read the [documentation about `git push`](https://git-scm.com/docs/git-push).\n3. The commands `wget` and `curl` are useful for grabbing data and files from remote resources off the web.\n Read the documentation on each of these commands by typing `man wget` or `man curl` in the terminal.\n Make sure you pipe the output to a file or use the proper flags to do so.\n\n&#167; **THERE IS NOTHING TO TURN IN FOR THIS PART.**\n\n\n\n### (30%) Listen to the Talk Python['Podcast'] from June 25, 2021: A Path to Data Science Interview with Sanyam Bhutani \n\nData science is one of the most important and \"hot\" disciplines today\nand there is a lot going on from data engineering to modeling and\nanalysis.\n\nBhutani is one of the top [Kaggle]() leaders and in this interview\nshares his experience from computer science to data science, \ndocumenting some of the lessons he learned along the way.\n\nPlease listen to this one hour podcast and answer some of the questions below.\nYou can listen to it from one of the two links below:\n\n* [Talk Python['Podcast'] landing page](https://talkpython.fm/episodes/transcript/322/a-path-into-data-science)\n* [direct link to mp3 file](https://downloads.talkpython.fm/podcasts/talkpython/322-starting-in-data-sci.mp3)\n\n&#167; **PLEASE ANSWER THE FOLLOWING QUESTIONS AFTER LISTENING TO THE PODCAST:**\n\n1. List 3 things that you learned from this podcast?\n\n2. What is your reaction to the podcast? Pick at least one point Sanyam brought up in the interview that you agree with and list your reason why.\n\n3. After listening to the podcast, do you think you are more interested or less interested in a career in Data Science?\n\n\n\n### (70%) Explore Python for data munging and analysis, with an introduction to CSV and Pandas \n\n\nPython's strengths shine when tasked with data munging and analysis. As we will learn throughout\nthe course, there are a number of excellent data sources for open data of all kinds now\navailable for the public. These open data sources are heralding the new era of transparency\nfrom all levels from small municipal data to big government data, from transportation, to science,\nto education.\n\nTo warm up to such datasets, we will be working with an interesting\ndataset from the US Fish and Wildlife Service (FWS). This is a \nwater quality data set taken from a managed national refuge in\nVirginia called Back Bay National Wildlife Refuge, which was \nestablished in 1938. As a function of being managed by the FWS, \nwater quality samples are taken regularly from the marshes within \nthe refuge.\n\nYou can (and should) learn a little more about Back Bay from\nthis link, since it has an interesting history, features and wildlife.\n\n* [https://www.fws.gov/refuge/Back_Bay/about.html](https://www.fws.gov/refuge/Back_Bay/about.html)\n\n\nThe data we will be looking at can be found as a direct download \nfrom data.gov, the US data repository where many datasets from\na variety of sources can be found -- mostly related to the \nmultitude of US government agencies.\n\nThe dataset is a small water quality dataset with several decades\nof water quality data from Back Bay. We will be warming up\nto this dataset with a basic investigation into the shape, content\nand context of the data contained therein.\n\n\nIn this part of the assignment, we will make use of Python libraries to pull the data from the\nendpoint and use [Pandas](https://pandas.pydata.org) to plot the data. The raw CSV data is\nreadily imported into Pandas from the following URL:\n\n* [FWS Water Quality Data 12/20/2020](https://catalog.data.gov/dataset/water-quality-data/resource/f4d736fd-ade9-4e3f-b8e0-ae7fd98b2f87)\n\nPlease take a look at the page, on it you will notice a link \nto the raw CSV file:\n\n* [https://ecos.fws.gov/ServCat/DownloadFile/173741?Reference=117348](https://ecos.fws.gov/ServCat/DownloadFile/173741?Reference=117348)\n\nWe are going to explore this dataset to learn a bit more about the \nwater quality characteristics of Bay Bay over the past couple decades\nor so.\n\n&#167; **WRITE THE CODE IN YOUR NOTEBOOK TO LOAD AND RESHAPE THE COMPLETE CSV WATER QUALITY DATASET**:\n\nYou will need to perform the following steps:\n\n1. **use [`pandas.read_csv()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) method to load the dataset** into a Pandas DataFrame;\n2. **clean the data so that the range of years is restricted to the 20 year period from 1999 to 2018**\n5. **store the entire dataset back into a new CSV** file called `back_bay_1998-2018_clean.csv`.\n\n**HINTS:** _Here are some a code hints you might like to study and use to craft a solution:_\n\n* study [`pandas.DataFrame.query()]`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html?highlight=query#pandas.DataFrame.query) to learn how to filter and query year ranges\n* study [`pandas.DataFrame.groupby()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html?highlight=groupby#pandas.DataFrame.groupby) to understand how to group data\n\n\n&#167; **USE PANDAS TO LOAD THE CSV DATA TO A DATAFRAME AND ANSWER THE FOLLOWING QUESTIONS:**\n\n1. How many and what are the names of the columns in this dataset?\n2. What is the mean `Dissolved Oxygen (mg/L)` over the entire dataset?\n3. Which year were the highest number of `AirTemp (C)` data points collected?\n4. Which year were the least number of `AirTemp (C)` data points collected?\n\n\nTo answer these questions, you'll need to dive further into Pandas, which is\nthe standard tool in the Python data science stack for loading, manipulating,\ntransforming, analyzing and preparing data as input to other tools such as\n[Numpy (http://www.numpy.org/)](http://www.numpy.org/), \n[SciKitLearn (http://scikit-learn.org/stable/index.html)](http://scikit-learn.org/stable/index.html), \n[NLTK (http://www.nltk.org/)](http://www.nltk.org/) and others.\n\nFor this assignment, you will only need to learn how to load and select data using Pandas.\n\n* **LOADING DATA**\nThe core data structure in Pandas is the `DataFrame`. You will need to visit\nthe Pandas documentation [(https://pandas.pydata.org/pandas-docs/stable/reference/)](https://pandas.pydata.org/pandas-docs/stable/reference/)\nto learn more about the library, but to help you along with a hint, read the\ndocumentation on the [`pandas.read_csv()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) method.\n\n* **SELECTING DATA**\nThe [tutorial here on indexing and selecting](http://pandas.pydata.org/pandas-docs/stable/indexing.html)\nshould be of great use in understanding how to index and select subsets of\nthe data to answer the questions.\n\n* **GROUPING DATA** You may use [`DataFrame.value_counts()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.value_counts.html?highlight=value_counts#pandas.DataFrame.value_counts) or [`DataFrame.groupby()`](https://pandas.pydata.org/pandas-docs/stable/reference/groupby.html) to group\nthe data you need for these questons. You will also find [`DataFrame.groupby()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html?highlight=groupby#pandas.DataFrame.groupby) and [`DataFrame.describe()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html?highlight=describe#pandas.DataFrame.describe) very useful.\n\n**CODE HINTS**\n\nHere is example code that should give you clues about the structure\nof your code for this part.\n\n```python\n import pandas as pd\n\n df = pd.read_csv('your_json_file.csv')\n\n # code for question 1 ... and so on\n```\n\n\n&#167; **EXPLORING WATER SALINITY IN THE DATA**\n\nThe Back Bay refuge is on the eastern coast of Virginia and to\nthe east is the Atlantic Ocean. Salinity is a measure of\nthe salt concentration of water, and you can learn a little more\nabout salinity in water [here](https://www.usgs.gov/special-topic/water-science-school/science/saline-water-and-salinity?qt-science_center_objects=0#qt-science_center_objects).\n\nYou will notice that there is a `Site_Id` variable in the data, which \nwe will find refers to the five sampling locations (see the [documentation here](https://ecos.fws.gov/ServCat/Reference/Profile/117348))\nof (1) the Bay, (2) D-Pool (fishing pond), (3) C-Pool, (4) B-Pool and (5) A-Pool.\n\nThe ppt in Salinity is the percent salinity, and so 1 ppt is equivalent to 10000 ppm salinity. Use this information to answer \nthe following questions.\n\n1. Which sampling location has the highest mean ppt? What is the equivalent ppm?\n2. When looking at the mean ppt, which location would you infer is furthest from the influence of ocean water inflows? \n (Assume that higher salinity correlates to closer proximity to the ocean.)\n3. Dig a little deeper into #2, and write why there may be some uncertainty in your answer? (hint: certainty is improved by consistency in data)\n4. Use the data to determine the correlation between `Salinity (ppt)` and `pH (standard units)`. Use the [DataFrame.corr()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.corr.html?highlight=correlate). You just need to report the correlation value. \n\n\n\n", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
d01d3202613c335f8a421ca0202969c9eeb156b4
156,400
ipynb
Jupyter Notebook
day5/02-NN.ipynb
JanaLasser/data-science-course
5086982e47bfa3fb98dde005c8af9327079d22b8
[ "CC-BY-4.0" ]
5
2017-11-13T15:14:58.000Z
2021-06-11T10:50:26.000Z
day5/02-NN.ipynb
JanaLasser/data-science-course
5086982e47bfa3fb98dde005c8af9327079d22b8
[ "CC-BY-4.0" ]
null
null
null
day5/02-NN.ipynb
JanaLasser/data-science-course
5086982e47bfa3fb98dde005c8af9327079d22b8
[ "CC-BY-4.0" ]
4
2017-07-19T13:21:11.000Z
2019-09-28T15:32:17.000Z
108.989547
68,100
0.872717
[ [ [ "## Obligatory imports", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sklearn\nimport matplotlib\n%matplotlib inline\nmatplotlib.rcParams['figure.figsize'] = (12,8)\nmatplotlib.rcParams['font.size']=20\nmatplotlib.rcParams['lines.linewidth']=4\nmatplotlib.rcParams['xtick.major.size'] = 10\nmatplotlib.rcParams['ytick.major.size'] = 10\nmatplotlib.rcParams['xtick.major.width'] = 2\nmatplotlib.rcParams['ytick.major.width'] = 2", "_____no_output_____" ] ], [ [ "# We use the MNIST Dataset again", "_____no_output_____" ] ], [ [ "import IPython\nurl = 'http://yann.lecun.com/exdb/mnist/'\niframe = '<iframe src=' + url + ' width=80% height=400px></iframe>'\nIPython.display.HTML(iframe)", "_____no_output_____" ] ], [ [ "## Fetch the data", "_____no_output_____" ] ], [ [ "from sklearn.datasets import fetch_mldata", "_____no_output_____" ], [ "mnist = fetch_mldata('MNIST original', data_home='../day4/data/')", "_____no_output_____" ], [ "allimages = mnist.data\nallimages.shape", "_____no_output_____" ], [ "all_image_labels = mnist.target\nset(all_image_labels)", "_____no_output_____" ] ], [ [ "## check out the data", "_____no_output_____" ] ], [ [ "digit1 = mnist.data[0,:].reshape(28,-1) # arr.reshape(4, -1) is equivalent to arr.reshape(4, 7), is arr has size 28", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(1.5, 1.5))\nax.imshow(digit1, vmin=0, vmax=1)", "_____no_output_____" ] ], [ [ "# Theoretical background\n**Warning: math ahead**\n<img src=\"images/logreg_schematics.svg\" alt=\"logreg-schematics\" style=\"width: 50%;\"/>", "_____no_output_____" ], [ "## Taking logistic regression a step further: neural networks\n<img src=\"images/mlp_schematics.svg\" alt=\"nn-schematics\" style=\"width: 50%;\"/>", "_____no_output_____" ], [ "### How (artificial) neural networks predict a label from features?\n* The *input layer* has **dimention = number of features.**\n* For each training example, each feature value is \"fed\" into the input layer. \n* Each \"neuron\" in the hidden layer receives a weighted sum of the features: the weight is initialized to a random value in the beginning, and the network \"learns\" from the datasetsand tunes these weights. Each hidden neuron, based on its input, and an \"activation function\", e.g.: the logistic function\n![actfunc](https://upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Activation_tanh.svg/320px-Activation_tanh.svg.png)\n* The output is again, a weighted sum of the values at each hidden neuron. \n* There can be *more than one hidden layer*, in which case the output of the first hidden layer becomes the input of the second hidden layer. \n\n### Regularization\nLike Logistic regression and SVM, neural networks also can be improved with regularization.\nFot scikit-learn, the relevant tunable parameter is `alpha` (as opposed to `gamma` for LR and SVM). \nFurthermore, it has default value 0.0001, unlike gamma, for which it is 1. ", "_____no_output_____" ], [ "### Separate the data into training data and test data", "_____no_output_____" ] ], [ [ "len(allimages)", "_____no_output_____" ] ], [ [ "### Sample the data, 70000 is too many images to handle on a single PC", "_____no_output_____" ] ], [ [ "len(allimages)", "_____no_output_____" ], [ "size_desired_dataset = 2000", "_____no_output_____" ], [ "sample_idx = np.random.choice(len(allimages), size_desired_dataset)\nimages = allimages[sample_idx, :]\nimage_labels = all_image_labels[sample_idx]", "_____no_output_____" ], [ "set(image_labels)", "_____no_output_____" ], [ "image_labels.shape", "_____no_output_____" ] ], [ [ "### Partition into training and test set *randomly*", "_____no_output_____" ], [ "**As a rule of thumb, 80/20 split between training/test dataset is often recommended.**\nSee below for cross validation and how that changes this thumbrule.\n", "_____no_output_____" ] ], [ [ "from scipy.stats import itemfreq", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "training_data, test_data, training_labels, test_labels = train_test_split(images, image_labels, train_size=0.8)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/model_selection/_split.py:2026: FutureWarning: From version 0.21, test_size will always complement train_size unless both are specified.\n FutureWarning)\n" ] ], [ [ "** Importance of normalization** \nIf Feature A is in the range [0,1] and Feature B is in [10000,50000], SVM (in fact, most of the classifiers) will suffer inaccuracy.\nThe solution is to *normalize* (AKA \"feature scaling\") each feature to the same interval e.g. [0,1] or [-1, 1].\n\n**scipy provides a standard function for this:**", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n# Fit only to the training data: IMPORTANT\nscaler.fit(training_data)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ], [ "from sklearn.neural_network import MLPClassifier", "_____no_output_____" ], [ "clf = MLPClassifier(hidden_layer_sizes=(50,), max_iter = 5000)\nclf.fit(scaler.transform(training_data), training_labels)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ], [ "clf.score(scaler.transform(training_data), training_labels), clf.score(scaler.transform(test_data), test_labels)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ] ], [ [ "### Visualize the hidden layer:", "_____no_output_____" ] ], [ [ "# source: \n# \n#http://scikit-learn.org/stable/auto_examples/neural_networks/plot_mnist_filters.html\nfig, axes = plt.subplots(4, 4, figsize=(15,15))\n# use global min / max to ensure all weights are shown on the same scale\nvmin, vmax = clf.coefs_[0].min(), clf.coefs_[0].max()\nfor coef, ax in zip(clf.coefs_[0].T, axes.ravel()):\n ax.matshow(coef.reshape(28, 28), cmap=plt.cm.gray, vmin=.5 * vmin,\n vmax=.5 * vmax)\n ax.set_xticks(())\n ax.set_yticks(())\n\nplt.show()", "_____no_output_____" ] ], [ [ "Not bad, but is it better than Logistic regression? Check out with Learning curves:", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import learning_curve\nimport pandas as pd", "_____no_output_____" ], [ "curve = learning_curve(clf, scaler.transform(images), image_labels)\ntrain_sizes, train_scores, test_scores = curve\n\ntrain_scores = pd.DataFrame(train_scores)\ntrain_scores.loc[:,'train_size'] = train_sizes\ntest_scores = pd.DataFrame(test_scores)\ntest_scores.loc[:,'train_size'] = train_sizes\n\ntrain_scores = pd.melt(train_scores, id_vars=['train_size'], value_name = 'CrossVal score')\ntest_scores = pd.melt(test_scores, id_vars=['train_size'], value_name = 'CrossVal score')", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ], [ "matplotlib.rcParams['figure.figsize'] = (12,8)\nsns.tsplot(train_scores, time = 'train_size', unit='variable', value = 'CrossVal score')\nsns.tsplot(test_scores, time = 'train_size', unit='variable', value = 'CrossVal score', color='g')\nplt.ylim(0,1.1)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/seaborn/timeseries.py:183: UserWarning: The tsplot function is deprecated and will be removed or replaced (in a substantially altered version) in a future release.\n warnings.warn(msg, UserWarning)\n" ] ], [ [ "Not really, we can try to improve it with parameter space search.", "_____no_output_____" ], [ "## Parameter space search with `GridSearchCV`", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import GridSearchCV", "_____no_output_____" ], [ "clr = MLPClassifier()", "_____no_output_____" ], [ "clf = GridSearchCV(clr, {'alpha':np.logspace(-8, -1, 2)})", "_____no_output_____" ], [ "clf.fit(scaler.transform(images), image_labels)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ], [ "clf.best_params_", "_____no_output_____" ], [ "clf.best_score_", "_____no_output_____" ], [ "nn_tuned = clf.best_estimator_\nnn_tuned.fit(scaler.transform(training_data), training_labels)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ], [ "curve = learning_curve(nn_tuned, scaler.transform(images), image_labels)\ntrain_sizes, train_scores, test_scores = curve\n\ntrain_scores = pd.DataFrame(train_scores)\ntrain_scores.loc[:,'train_size'] = train_sizes\ntest_scores = pd.DataFrame(test_scores)\ntest_scores.loc[:,'train_size'] = train_sizes\n\ntrain_scores = pd.melt(train_scores, id_vars=['train_size'], value_name = 'CrossVal score')\ntest_scores = pd.melt(test_scores, id_vars=['train_size'], value_name = 'CrossVal score')", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/neural_network/multilayer_perceptron.py:564: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/neural_network/multilayer_perceptron.py:564: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/neural_network/multilayer_perceptron.py:564: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/neural_network/multilayer_perceptron.py:564: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/neural_network/multilayer_perceptron.py:564: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/neural_network/multilayer_perceptron.py:564: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n" ], [ "matplotlib.rcParams['figure.figsize'] = (12,8)\nsns.tsplot(train_scores, time = 'train_size', unit='variable', value = 'CrossVal score')\nsns.tsplot(test_scores, time = 'train_size', unit='variable', value = 'CrossVal score', color='g')\nplt.ylim(0,1.1)\n\nplt.legend()", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/seaborn/timeseries.py:183: UserWarning: The tsplot function is deprecated and will be removed or replaced (in a substantially altered version) in a future release.\n warnings.warn(msg, UserWarning)\nNo handles with labels found to put in legend.\n" ] ], [ [ "The increase in accuracy is miniscule.", "_____no_output_____" ], [ "## Multi layered NN's", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import StandardScaler \nscaler = StandardScaler() \nscaler.fit(images)\n\nimages_normed = scaler.transform(images)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ], [ "clr = MLPClassifier(hidden_layer_sizes=(25,25))\nclf = GridSearchCV(clr, {'alpha':np.logspace(-80, -1, 3)})\nclf.fit(images_normed, image_labels)\nclf.best_score_", "_____no_output_____" ], [ "clf.best_params_", "_____no_output_____" ], [ "nn_tuned = clf.best_estimator_\nnn_tuned.fit(scaler.transform(training_data), training_labels)", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/sklearn/utils/validation.py:475: DataConversionWarning: Data with input dtype uint8 was converted to float64 by StandardScaler.\n warnings.warn(msg, DataConversionWarning)\n" ], [ "curve = learning_curve(nn_tuned, images_normed, image_labels)\ntrain_sizes, train_scores, test_scores = curve\n\ntrain_scores = pd.DataFrame(train_scores)\ntrain_scores.loc[:,'train_size'] = train_sizes\ntest_scores = pd.DataFrame(test_scores)\ntest_scores.loc[:,'train_size'] = train_sizes\n\ntrain_scores = pd.melt(train_scores, id_vars=['train_size'], value_name = 'CrossVal score')\ntest_scores = pd.melt(test_scores, id_vars=['train_size'], value_name = 'CrossVal score')", "_____no_output_____" ], [ "matplotlib.rcParams['figure.figsize'] = (12, 8)\nsns.tsplot(train_scores, time = 'train_size', unit='variable', value = 'CrossVal score')\nsns.tsplot(test_scores, time = 'train_size', unit='variable', value = 'CrossVal score', color='g')\nplt.ylim(0,1.1)\n\nplt.legend()", "/home/dmanik/venvs/teaching/lib/python3.5/site-packages/seaborn/timeseries.py:183: UserWarning: The tsplot function is deprecated and will be removed or replaced (in a substantially altered version) in a future release.\n warnings.warn(msg, UserWarning)\nNo handles with labels found to put in legend.\n" ] ], [ [ "Hmm... multi-hidden layer NN's seem to be much harder to tune.\nMaybe we need to try with wider range of parameters for Gridsearch?", "_____no_output_____" ], [ "Finding optimum parameters for advanced classifiers is not always so straightforward, and quite often the most time consuming part. This so-called **Hyperparameter optimization** is a topic in itself, and has numerous approaches and libraries. \n\n* [http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html](http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html)\n* [Practical Bayesian Optimization of Machine Learning Algorithms](https://dash.harvard.edu/handle/1/11708816)", "_____no_output_____" ], [ "**sklearn's neural network functionality is rather limited.** More advanced toolboxes for neural networks:\n* [keras](https://keras.io/)\n* [tensorflow](https://www.tensorflow.org/)\n* [Theano](http://deeplearning.net/software/theano/)", "_____no_output_____" ], [ "# Exercise\n\n## iris dataset\nTrain a neural network on the `iris` dataset and run cross validation. Do not forget to normalize the featurs. \nCompare the results against LogisticRegression.\n\nUse Grid search to tune the NN further.", "_____no_output_____" ], [ "## Further reading\n* http://www.ritchieng.com/applying-machine-learning/\n ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d01d3a0b353c2e8a697c4054b6b41299ea9d0b82
2,120
ipynb
Jupyter Notebook
Sklearn/1.6 Data Split/.ipynb_checkpoints/1.6.1.1 train_test_split-checkpoint.ipynb
120180163/Sklearn-Library
96f3dbcac9797066ce4e8938fe39b7ce00b89596
[ "Apache-2.0" ]
1
2021-08-28T11:03:28.000Z
2021-08-28T11:03:28.000Z
Sklearn/1.6 Data Split/1.6.1.1 train_test_split.ipynb
120180163/Sklearn-Library
96f3dbcac9797066ce4e8938fe39b7ce00b89596
[ "Apache-2.0" ]
null
null
null
Sklearn/1.6 Data Split/1.6.1.1 train_test_split.ipynb
120180163/Sklearn-Library
96f3dbcac9797066ce4e8938fe39b7ce00b89596
[ "Apache-2.0" ]
null
null
null
22.553191
115
0.470283
[ [ [ "#Import Libraries\nfrom sklearn.model_selection import train_test_split\n#----------------------------------------------------\n\n#Splitting data\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=44, shuffle =True)\n\n#Splitted Data\nprint('X_train shape is ' , X_train.shape)\nprint('X_test shape is ' , X_test.shape)\nprint('y_train shape is ' , y_train.shape)\nprint('y_test shape is ' , y_test.shape)", "_____no_output_____" ], [ "import numpy as np\nfrom sklearn.model_selection import train_test_split\n\nX, y = np.arange(10).reshape((5, 2)), range(5)\n\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state=40, shuffle = True)\n\n\nprint(X_train)\nprint('<<<<<<>>>>>>>')\nprint(y_train)\nprint('<<<<<<>>>>>>>')\nprint(X_test)\nprint('<<<<<<>>>>>>>')\nprint(y_test)", "[[0 1]\n [2 3]\n [8 9]\n [6 7]]\n<<<<<<>>>>>>>\n[0, 1, 4, 3]\n<<<<<<>>>>>>>\n[[4 5]]\n<<<<<<>>>>>>>\n[2]\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
d01d3b492a4f59193788b65055f9bf9557e1948e
931,614
ipynb
Jupyter Notebook
numerical5.ipynb
fatginger1024/NumericalMethods
c4886d60da6fef8da9d0350bbc808cbd163d4623
[ "MIT" ]
null
null
null
numerical5.ipynb
fatginger1024/NumericalMethods
c4886d60da6fef8da9d0350bbc808cbd163d4623
[ "MIT" ]
null
null
null
numerical5.ipynb
fatginger1024/NumericalMethods
c4886d60da6fef8da9d0350bbc808cbd163d4623
[ "MIT" ]
null
null
null
735.291239
139,344
0.935494
[ [ [ "<center> <h1>Numerical Methods -- Assignment 5</h1> </center>", "_____no_output_____" ], [ "## Problem1 -- Energy density", "_____no_output_____" ], [ "The matter and radiation density of the universe at redshift $z$ is\n$$\\Omega_m(z) = \\Omega_{m,0}(1+z)^3$$\n$$\\Omega_r(z) = \\Omega_{r,0}(1+z)^4$$\nwhere $\\Omega_{m,0}=0.315$ and $\\Omega_r = 9.28656 \\times 10^{-5}$", "_____no_output_____" ], [ "### (a) Plot", "_____no_output_____" ] ], [ [ "%config InlineBackend.figure_format = 'retina' \nimport matplotlib.pyplot as plt\nimport numpy as np\n\nz = np.linspace(-1000,4000,10000)\nO_m0 = 0.315\nO_r0 = 9.28656e-5\nO_m = O_m0*np.power(z+1,3)\nO_r = O_r0*np.power(z+1,4)\n#define where the roots are\nx1 = -1; x2 = O_m0/O_r0\ny1 = O_m0*np.power(x1+1,3)\ny2 = O_m0*np.power(x2+1,3)\nx = np.array([x1,x2])\ny = np.array([y1,y2])\n#plot the results\nplt.figure(figsize=(8,8))\nplt.plot(z,O_m,'-',label=\"matter density\")\nplt.plot(z,O_r,'-',label=\"radiation density\")\nplt.plot(x,y,'h',label=r\"$z_{eq}$\")\nplt.xlabel(\"redshift(z)\")\nplt.ylabel(\"energy density\")\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "### (b) Analytical solution", "_____no_output_____" ], [ "An analytical solution can be found by equating the two equations. Since $z$ denotes for the redshift and it has a physical meaning, so it must take a real value for it to have a meaning. Thus\n\\begin{align*}\n\\Omega_m(z) &= \\Omega_r(z)\\\\\n\\Omega_{m,0}(1+z)^3 &= \\Omega_{r,0}(1+z)^4\\\\\n(1+z)^3(0.315-9.28656 \\times 10^{-5} z)&=0\\\\\n(1+z)^3 &= 0\\\\\nor \\ (0.315-9.28656 \\times 10^{-5} (z+1))&=0\\\\\n\\end{align*}\n$z_1 = -1$ or $z_2 = 3391.0$", "_____no_output_____" ], [ "### (c) Bisection method", "_____no_output_____" ], [ "The bisection method in mathematics is a root-finding method that repeatedly bisects an interval and then selects a subinterval in which a root must lie for further processing. It is a very simple and robust method, but it is also relatively slow. scipy.optimize.bisect calculates the roots for a given function, but for it to work $f(a)$ and $f(b)$ must take different signs (so that there exists a root $\\in [a,b]$).", "_____no_output_____" ] ], [ [ "from scipy.optimize import bisect\n\ndef f(z):\n O_m0 = 0.315\n O_r0 = 9.28656e-5\n O_m = O_m0*np.power(z+1,3)\n O_r = O_r0*np.power(z+1,4)\n return O_m -O_r\nz1 = bisect(f,-1000,0,xtol=1e-10)\nz2 = bisect(f,0,4000,xtol=1e-10)\nprint \"The roots are found to be:\",z1,z2", "The roots are found to be: -1.00000000003 3390.9987595\n" ] ], [ [ "### (d) Secant method", "_____no_output_____" ], [ "The $\\textit{secant method}$ uses secant lines to find the root. A secant line is a straight line that intersects two points of a curve. In the secant method, a line is drawn between two points on the continuous function such that it extends and intersects the $x$ axis. A secant line $y$ is drawn from $f(b)$ to $f(a)$ and intersects at point $c$ on the $x$ axis such that\n$$y = \\frac{f(b)-f(a)}{b-a}(c-b)+f(b)$$\nThe solution is therefore\n$$c = b-f(b)\\frac{b-a}{f(b)-f(a)}$$", "_____no_output_____" ] ], [ [ "\ndef secant(f, x0, x1, eps):\n f_x0 = f(x0)\n f_x1 = f(x1)\n iteration_counter = 0\n while abs(f_x1) > eps and iteration_counter < 100:\n try:\n denominator = float(f_x1 - f_x0)/(x1 - x0)\n x = x1 - float(f_x1)/denominator\n except ZeroDivisionError:\n print \"Error! - denominator zero for x = \", x\n sys.exit(1) # Abort with error\n x0 = x1\n x1 = x\n f_x0 = f_x1\n f_x1 = f(x1)\n iteration_counter += 1\n # Here, either a solution is found, or too many iterations\n if abs(f_x1) > eps:\n iteration_counter = -1\n return x, iteration_counter\n#find the roots in the nearby region, with an accuracy of 1e-10\nz1 = secant(f,-10,-0.5,1e-10)[0]\nz2 = secant(f,3000,4000,1e-10)[0]\n\nprint \"The roots are found to be:\",z1,z2\n", "The roots are found to be: -0.999466618551 3390.9987595\n" ] ], [ [ "### (e) Newton-Raphson method", "_____no_output_____" ], [ "In numerical methods, $\\textit{Newton-Raphson method}$ is a method for finding successively better approximations to the roots of a real-valued function. The algorithm is as follows:\n* Starting with a function $f$ defined over the real number $x$, the function's derivative $f'$, and an initial guess $x_0$ for a root of the fucntion $f$, then a better approximation $x_1$ is:\n$$x_1 = x_0 -\\frac{f(x_0)}{f'(x_0)}$$\n* The process is then repeated as\n$$x_{n+1} = x_n-\\frac{f(x_n)}{f'(x_n)}$$\nuntil a sufficiently satisfactory value is reached.", "_____no_output_____" ] ], [ [ "def fprime(z):\n O_m0 = 0.315\n O_r0 = 9.28656e-5\n O_m = O_m0*np.power(z+1,2)\n O_r = O_r0*np.power(z+1,3)\n return 3*O_m -4*O_r\n\ndef Newton(f, dfdx, x, eps):\n f_value = f(x)\n iteration_counter = 0\n while abs(f_value) > eps and iteration_counter < 100:\n try:\n x = x - float(f_value)/dfdx(x)\n except ZeroDivisionError:\n print \"Error! - derivative zero for x = \", x\n sys.exit(1) # Abort with error\n\n f_value = f(x)\n iteration_counter += 1\n\n # Here, either a solution is found, or too many iterations\n if abs(f_value) > eps:\n iteration_counter = -1\n return x, iteration_counter\n\nz1 = Newton(f,fprime,0,1e-10)[0]\nz2 = Newton(f,fprime,3000,1e-10)[0]\nprint \"The roots are found to be:\",z1,z2\n ", "The roots are found to be: -0.9993234602 3390.9987595\n" ] ], [ [ "Now, change the initial guess far from the values obtained from (b). And test how the three algorithms perform respectively.", "_____no_output_____" ] ], [ [ "#test how the bisection method perform\nimport time\nstart1 = time.time()\nz1 = bisect(f,-1000,1000,xtol=1e-10)\nend1 = time.time()\nstart2 = time.time()\nz2 = bisect(f,3000,10000,xtol=1e-10)\nend2 = time.time()\nerr1 = abs((z1-(-1))/(-1))\nerr2 = abs((z2-(O_m0/O_r0-1))/(O_m0/O_r0-1))\nprint \"The roots are found to be:\",z1,z2\nprint \"With a deviation of:\",err1,err2\nprint \"Time used are:\",end1-start1,end2-start2", "The roots are found to be: -1.00000000003 3390.9987595\nWith a deviation of: 3.31965566147e-11 1.11306528845e-14\nTime used are: 0.00043797492981 0.000349998474121\n" ], [ "#test how the secant method perform\nstart1 = time.time()\nz1 = secant(f,-1000,1000,1e-10)[0]\nend1 = time.time()\nstart2 = time.time()\nz2 = secant(f,3000,10000,1e-10)[0]\nend2 = time.time()\nerr1 = abs((z1-(-1))/(-1))\nerr2 = abs((z2-(O_m0/O_r0-1))/(O_m0/O_r0-1))\nprint \"The roots are found to be:\",z1,z2\nprint \"With a deviation of:\",err1,err2\nprint \"Time used are:\",end1-start1,end2-start2\nprint \"Roots found after\",secant(f,-10,-0.5,1e-10)[1],\"and\",secant(f,3000,4000,1e-10)[1],\"loops\"\n", "The roots are found to be: -0.999414972528 3390.9987595\nWith a deviation of: 0.000585027471743 0.0\nTime used are: 0.000823020935059 0.000194072723389\nRoots found after 25 and 8 loops\n" ], [ "#test how the newton-Raphson method perform\nstart1 = time.time()\nz1 = Newton(f,fprime,-1000,1e-10)[0]\nend1 = time.time()\nstart2 = time.time()\nz2 = Newton(f,fprime,10000,1e-10)[0]\nend2 = time.time()\nerr1 = abs((z1-(-1))/(-1))\nerr2 = abs((z2-(O_m0/O_r0-1))/(O_m0/O_r0-1))\nprint \"The roots are found to be:\",z1,z2\nprint \"With a deviation of:\",err1,err2\nprint \"Time used are:\",end1-start1,end2-start2\nprint \"Roots found after\",Newton(f,fprime,0,1e-10)[1],\"and\",Newton(f,fprime,3000,1e-10)[1],\"loops\"", "The roots are found to be: -1.00051824126 3390.9987595\nWith a deviation of: 0.000518241260632 0.0\nTime used are: 0.000991821289062 0.000278949737549\nRoots found after 18 and 7 loops\n" ] ], [ [ "It is not difficult to find out that tested with the function given, bisection method is the fastest and the most reliable method in finding the first root; however, in determining the second root, both the secant method and Newton's method showed better performance, with zero deviation from the actual value, and a much faster run time. But in general, when dealing with more complicated calculations, bisection method is relatively slow. But within a given tolerance Newton's method and secant method may probably show better performance.", "_____no_output_____" ], [ "## Problem 2 -- Potential", "_____no_output_____" ], [ "$\\textit{Navarro-Frenk-White}$ and $\\textit{Hernquist}$ potential can be expressed as the following equations:\n$$\\Phi_{NFW}(r) = \\Phi_0\\frac{r_s}{r}\\,ln(1+r/r_s)$$\n$$\\Phi_{Hernquist}(r) = -\\Phi_0\\,\\frac{1}{2(1+r/r_s)}$$\nwith $\\Phi_0 = 1.659 \\times 10^4 \\ km^2/s^2$ and $r_s = 15.61 \\ kpc$.\nThe apocentre and pericentre can be found by solving the following equation:\n\\begin{align*}\nE_{tot} &= \\frac{1}{2}\\left(v_t^2+v_r^2\\right)+\\Phi\\\\\n\\end{align*}\nwhere $L = J_r=rv_r$ is the angular momentum in the radial direction, and $E_{tot}$ is the total energy of the elliptical orbit and can be found by $(r,v_t,v_r)$ of a given star.\nDefine the residue function\n$$R\\equiv E_{tot} - \\frac{1}{2}\\left(\\frac{L}{r}\\right)^2-\\Phi$$\nso that the percenter and apocenter can be found when $R=0$.\nThen, the radial action $J_r$ is defined as $\\textit{(Jason L. Sanders,2015)}$\n$$J_r = \\frac{1}{\\pi}\\int_{r_p}^{r_a}dr\\sqrt{2E-2\\Phi-\\frac{L^2}{r^2}}$$\nwhere $r_p$ is the pericentric radius and $r_a$ is the apocentric radius.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import newton\nfrom scipy.integrate import quad\nfrom math import * \n\nr = np.array([7.80500, 15.6100,31.2200,78.0500,156.100]) #r in kpc\nvt = np.array([139.234,125.304,94.6439,84.5818,62.8640]) # vt in km/s\nvr = np.array([-15.4704,53.7018,-283.932,-44.5818,157.160]) # vr in km/s\n#NFW profile potential\ndef NFW(r):\n phi0 = 1.659e4\n rs = 15.61\n ratio = rs/r\n return -phi0*ratio*np.log(1+1/ratio)\n#Hernquist profile potential\ndef H(r):\n phi0 = 1.659e4\n rs = 15.61\n ratio = r/rs\n return -phi0/(2*(1+ratio))\n#1st derivative of Hernquist profile potential\ndef H_d(r):\n phi0 = 1.659e4\n rs = 15.61\n ratio = r/rs\n return phi0*0.5/rs*((1+ratio)**(-2)) \n#1st derivative of NFW profile potential\ndef NFW_d(r):\n phi0 = 1.659e4\n rs = 15.61\n ratio = rs/r\n return -phi0*rs*((-1/r**2)*np.log(1+1/ratio)+1/(r*rs)*(1+1/ratio)**(-1))\n#total energy, NFW profile\ndef E_NFW(r,vt,vr):\n E = 0.5*(vt**2+vr**2)+NFW(r)\n return E\n#total energy, Hernquist profile\ndef E_H(r,vt,vr):\n E = 0.5*(vt**2+vr**2)+H(r)\n return E\n#Residue function\ndef Re(r,Energy,momentum,p):\n return Energy - 0.5*(momentum/r)**2-p\n\n#Residue function for NFW profile\ndef R_NFW(r,Energy,momentum):\n return Energy - 0.5*(momentum/r)**2-NFW(r)\n#Residue function for Hernquist profile\ndef R_H(r,Energy,momentum):\n return Energy - 0.5*(momentum/r)**2-H(r)\n#derivative of residue of NFW profile\ndef R_dNFW(r,Energy,momentum):\n return Energy*0+momentum**2*r**(-3)-NFW_d(r)\n#derivative of residue of Hernquist profile\ndef R_dH(r,Energy,momentum):\n return Energy*0+momentum**2*r**(-3)-H_d(r)\n\n#second derivative of residue of Hernquist profile, come handy if the \n#calculated value for pericentre for Hernquist profile is too far off\n#from the value calculated for NFW profile\ndef R_ddH(r,Energy,momentum):\n phi0 = 1.659e4\n rs = 15.61\n ratio = r/rs\n return Energy*0-3*momentum**2*r**(-4)+phi0*0.5/rs**2*((1+ratio)**(-3)) \n#function that defines the radial action\ndef r_actionNFW(r,Energy,momentum):\n return np.sqrt(2*(Energy-NFW(r))-(momentum/r)**2)/pi\ndef r_actionH(r,Energy,momentum):\n return np.sqrt(2*(Energy-H(r))-(momentum/r)**2)/pi\n\nR1 = np.linspace(7,400,1000)\nR2 = np.linspace(10,500,1000)\nR3 = np.linspace(7,600,1000)\nR4 = np.linspace(50,800,1000)\nR5 = np.linspace(50,1500,1000)\nMomentum = r*vt\nEnergy_nfw = E_NFW(r,vt,vr)\nEnergy_h = E_H(r,vt,vr)\n#plot results for 5 stars\n#1st star\ni = 0\nR_nfw = Re(R1,Energy_nfw[i],Momentum[i],NFW(R1))\nR_h = Re(R1,Energy_h[i],Momentum[i],H(R1))\nplt.figure(figsize=(15,10))\nplt.plot(R1,R_nfw,ls='-',label=\"NFW\",color='#9370db',lw=2)\nplt.plot(R1,R_h,ls='--',label=\"Hernquist\",color='salmon',alpha=0.75,lw=2)\nplt.rc('xtick', labelsize=15) # fontsize of the tick labels\nplt.rc('ytick', labelsize=15)\nplt.axhline(y=0,color='#b22222',lw=3)\nplt.title(r\"1st star, $R= E_{tot} - \\frac{1}{2}\\left(\\frac{L}{r}\\right)^2-\\Phi$\",fontsize=20)\nplt.xlabel(\"r(kpc)\",fontsize=15)\nplt.ylabel(\"Residue\",fontsize=15)\nz1 = newton(R_NFW,10,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\nz2 = newton(R_NFW,100,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\ne1 = R_NFW(z1,Energy_nfw[i],Momentum[i])\ne2 = R_NFW(z2,Energy_nfw[i],Momentum[i])\nprint \"The pericentre and apocentre are found to be:\",z1,\"kpc\",\"and\",z2,\"kpc\",\"for the NFW profile\"\nplt.plot(z1,e1,marker='d',label='pericentre-NFW')\nplt.plot(z2,e2,marker='d',label='apocentre-NFW')\nz3 = newton(R_H,10,args=(Energy_h[i],Momentum[i]),fprime=R_dH)\ne3 = Re(z1,Energy_h[i],Momentum[i],H(z1))\nprint \"The pericentre is found to be:\",z3,\"kpc\",\"for the Hernquist profile\"\nplt.plot(z1,e1,marker='o',label='pericentre-H')\nplt.legend(fontsize=15)\nplt.show()\n\nJ_NFW = quad(r_actionNFW,z1,z2,args=(Energy_nfw[i],Momentum[i]))\nprint \"The radial action for NFW profile is:\",J_NFW[0],\"km/s kpc\"\nJ_H = quad(r_actionH,z3,np.inf,args=(Energy_h[i],Momentum[i]))\nprint \"The radial action for Hernquist profile is:\",J_H[0],\"km/s kpc\"", "The pericentre and apocentre are found to be: 7.75067639682 kpc and 178.316271432 kpc for the NFW profile\nThe pericentre is found to be: 7.75234061029 kpc for the Hernquist profile\n" ], [ "#2nd star\ni = 1\nR_nfw = Re(R2,Energy_nfw[i],Momentum[i],NFW(R2))\nR_h = Re(R2,Energy_h[i],Momentum[i],H(R2))\nplt.figure(figsize=(15,10))\nplt.plot(R2,R_nfw,ls='-',label=\"NFW\",color='#9370db',lw=2)\nplt.plot(R2,R_h,ls='--',label=\"Hernquist\",color='salmon',alpha=0.75,lw=2)\nplt.rc('xtick', labelsize=15) # fontsize of the tick labels\nplt.rc('ytick', labelsize=15)\nplt.axhline(y=0,color='#b22222',lw=3)\nplt.title(r\"2nd star, $R= E_{tot} - \\frac{1}{2}\\left(\\frac{L}{r}\\right)^2-\\Phi$\",fontsize=20)\nplt.xlabel(\"r(kpc)\",fontsize=15)\nplt.ylabel(\"Residue\",fontsize=15)\nz1 = newton(R_NFW,10,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\nz2 = newton(R_NFW,400,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\ne1 = R_NFW(z1,Energy_nfw[i],Momentum[i])\ne2 = R_NFW(z2,Energy_nfw[i],Momentum[i])\nprint \"The pericentre and apocentre are found to be:\",z1,\"kpc\",\"and\",z2,\"kpc\",\"for the NFW profile\"\nplt.plot(z1,e1,marker='d',label='pericentre-NFW')\nplt.plot(z2,e2,marker='d',label='apocentre-NFW')\nz3 = newton(R_H,10,args=(Energy_h[i],Momentum[i]),fprime=R_dH)\ne3 = Re(z1,Energy_h[i],Momentum[i],H(z1))\nprint \"The pericentre is found to be:\",z3,\"kpc\",\"for the Hernquist profile\"\nplt.plot(z3,e3,marker='o',label='pericentre-H')\nplt.legend(fontsize=15)\nplt.show()\n\nJ_NFW = quad(r_actionNFW,z1,z2,args=(Energy_nfw[i],Momentum[i]))\nprint \"The radial action for NFW profile is:\",J_NFW[0],\"km/s kpc\"\nJ_H = quad(r_actionH,z3,np.inf,args=(Energy_h[i],Momentum[i]))\nprint \"The radial action for Hernquist profile is:\",J_H[0],\"km/s kpc\"", "The pericentre and apocentre are found to be: 14.1075227275 kpc and 375.764622203 kpc for the NFW profile\nThe pericentre is found to be: 14.1986051415 kpc for the Hernquist profile\n" ], [ "#3rd star\ni = 2\nR_nfw = Re(R3,Energy_nfw[i],Momentum[i],NFW(R3))\nR_h = Re(R3,Energy_h[i],Momentum[i],H(R3))\nplt.figure(figsize=(15,10))\nplt.plot(R3,R_nfw,ls='-',label=\"NFW\",color='#9370db',lw=2)\nplt.plot(R3,R_h,ls='--',label=\"Hernquist\",color='salmon',alpha=0.75,lw=2)\nplt.rc('xtick', labelsize=15) # fontsize of the tick labels\nplt.rc('ytick', labelsize=15)\nplt.axhline(y=0,color='#b22222',lw=3)\nplt.title(r\"3rd star, $R= E_{tot} - \\frac{1}{2}\\left(\\frac{L}{r}\\right)^2-\\Phi$\",fontsize=20)\nplt.xlabel(\"r(kpc)\",fontsize=15)\nplt.ylabel(\"Residue\",fontsize=15)\nz1 = newton(R_NFW,10,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\ne1 = R_NFW(z1,Energy_nfw[i],Momentum[i])\nprint \"The pericentre is found to be:\",z1,\"kpc\",\"for the NFW profile\"\nplt.plot(z1,e1,marker='d',label='pericentre-NFW')\nz2 = newton(R_H,10,args=(Energy_h[i],Momentum[i]),fprime=R_dH,fprime2=R_ddH)\ne2 = R_H(z2,Energy_h[i],Momentum[i])\nprint \"The pericentre is found to be:\",z2,\"kpc\",\"for the Hernquist profile\"\nplt.plot(z2,e2,marker='o',label='pericentre-H')\nplt.legend(fontsize=15)\nplt.show()\n\nJ_NFW = quad(r_actionNFW,z1,np.inf,args=(Energy_nfw[i],Momentum[i]))\nprint \"The radial action for NFW profile is:\",J_NFW[0],\"km/s kpc\"\nJ_H = quad(r_actionH,z2,np.inf,args=(Energy_h[i],Momentum[i]))\nprint \"The radial action for Hernquist profile is:\",J_H[0],\"km/s kpc\"", "The pericentre is found to be: 9.47357617853 kpc for the NFW profile\nThe pericentre is found to be: 9.62166037758 kpc for the Hernquist profile\n" ], [ "#4th star\ni = 3\nR_nfw = Re(R4,Energy_nfw[i],Momentum[i],NFW(R4))\nR_h = Re(R4,Energy_h[i],Momentum[i],H(R4))\nplt.figure(figsize=(15,10))\nplt.plot(R4,R_nfw,ls='-',label=\"NFW\",color='#9370db',lw=2)\nplt.plot(R4,R_h,ls='--',label=\"Hernquist\",color='salmon',alpha=0.75,lw=2)\nplt.rc('xtick', labelsize=15) # fontsize of the tick labels\nplt.rc('ytick', labelsize=15)\nplt.axhline(y=0,color='#b22222',lw=3)\nplt.title(r\"4th star, $R= E_{tot} - \\frac{1}{2}\\left(\\frac{L}{r}\\right)^2-\\Phi$\",fontsize=20)\nplt.xlabel(\"r(kpc)\",fontsize=15)\nplt.ylabel(\"Residue\",fontsize=15)\nz1 = newton(R_NFW,10,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\nz2 = newton(R_NFW,400,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\ne1 = R_NFW(z1,Energy_nfw[i],Momentum[i])\ne2 = R_NFW(z2,Energy_nfw[i],Momentum[i])\nprint \"The pericentre and apocentre are found to be:\",z1,\"kpc\",\"and\",z2,\"kpc\",\"for the NFW profile\"\nplt.plot(z1,e1,marker='d',label='pericentre-NFW')\nplt.plot(z2,e2,marker='d',label='apocentre-NFW')\nz3 = newton(R_H,50,args=(Energy_h[i],Momentum[i]),fprime=R_dH,fprime2=R_ddH)\ne3 = R_H(z3,Energy_h[i],Momentum[i])\nprint \"The pericentre is found to be:\",z3,\"kpc\",\"for the Hernquist profile\"\nplt.plot(z1,e1,marker='o',label='pericentre-H')\nplt.legend(fontsize=15)\nplt.show()\n\nJ_NFW = quad(r_actionNFW,z1,z2,args=(Energy_nfw[i],Momentum[i]))\nprint \"The radial action for NFW profile is:\",J_NFW[0],\"km/s kpc\"\nJ_H = quad(r_actionH,z3,np.inf,args=(Energy_h[i],Momentum[i]))\nprint \"The radial action for Hernquist profile is:\",J_H[0],\"km/s kpc\"", "The pericentre and apocentre are found to be: 64.9161691596 kpc and 697.429352749 kpc for the NFW profile\nThe pericentre is found to be: 67.7971003933 kpc for the Hernquist profile\n" ], [ "#5th star\ni = 4\nR_nfw = Re(R5,Energy_nfw[i],Momentum[i],NFW(R5))\nR_h = Re(R5,Energy_h[i],Momentum[i],H(R5))\nplt.figure(figsize=(15,10))\nplt.plot(R5,R_nfw,ls='-',label=\"NFW\",color='#9370db',lw=2)\nplt.plot(R5,R_h,ls='--',label=\"Hernquist\",color='salmon',alpha=0.75,lw=2)\nplt.rc('xtick', labelsize=15) # fontsize of the tick labels\nplt.rc('ytick', labelsize=15)\nplt.axhline(y=0,color='#b22222',lw=3)\nplt.title(r\"5th star, $R= E_{tot} - \\frac{1}{2}\\left(\\frac{L}{r}\\right)^2-\\Phi$\",fontsize=20)\nplt.xlabel(\"r(kpc)\",fontsize=15)\nplt.ylabel(\"Residue\",fontsize=15)\nz1 = newton(R_NFW,10,args=(Energy_nfw[i],Momentum[i]),fprime=R_dNFW)\ne1 = R_NFW(z1,Energy_nfw[i],Momentum[i])\nprint \"The pericentre is found to be:\",z1,\"kpc\",\"for the NFW profile\"\nplt.plot(z1,e1,marker='d',label='pericentre-NFW')\nz2 = newton(R_H,50,args=(Energy_h[i],Momentum[i]),fprime=R_dH,fprime2=R_ddH)\ne2 = R_H(z2,Energy_h[i],Momentum[i])\nprint \"The pericentre is found to be:\",z2,\"kpc\",\"for the Hernquist profile\"\nplt.plot(z1,e1,marker='o',label='pericentre-H')\nplt.legend(fontsize=15)\nplt.show()\n\nJ_NFW = quad(r_actionNFW,z1,np.inf,args=(Energy_nfw[i],Momentum[i]))\nprint \"The radial action for NFW profile is:\",J_NFW[0],\"km/s kpc\"\nJ_H = quad(r_actionH,z2,np.inf,args=(Energy_h[i],Momentum[i]))\nprint \"The radial action for Hernquist profile is:\",J_H[0],\"km/s kpc\"", "The pericentre is found to be: 52.2586723359 kpc for the NFW profile\nThe pericentre is found to be: 55.9497763757 kpc for the Hernquist profile\n" ] ], [ [ "The table below lists all the parameters of the five stars.", "_____no_output_____" ], [ "<img src=\"Desktop/table.png\">", "_____no_output_____" ], [ "## Problem 3 -- System of equations", "_____no_output_____" ], [ "$$f(x,y) = x^2+y^2-50=0$$\n$$g(x,y) = x \\times y -25 = 0$$", "_____no_output_____" ], [ "### (a) Analytical solution", "_____no_output_____" ], [ "First $f(x,y)-2g(x,y)$,we find:\n\\begin{align*}\nx^2+y^2-2xy &=0\\\\\n(x-y)^2 &= 0\\\\\nx&=y\n\\end{align*}\nThen $f(x,y)+2g(x,y)$,we find:\n\\begin{align*}\nx^2+y^2+2xy &=100\\\\\n(x+y)^2 &= 100\\\\\nx,y = 5,5 \\ &or -5,-5\n\\end{align*}", "_____no_output_____" ], [ "### (b) Newton's method", "_____no_output_____" ], [ "Newton-Raphson method can also be applied to solve multivariate systems. The algorithm is simply as follows:\n* Suppose we have an N-D multivariate system of the form:\n\\begin{cases}\nf_1(x_1,...,x_N)=f_1(\\mathbf{x})=0\\\\\nf_2(x_1,...,x_N)=f_2(\\mathbf{x})=0\\\\\n...... \\\\\nf_N(x_1,...,x_N)=f_N(\\mathbf{x})=0\\\\\n\\end{cases}\nwhere we have defined \n$$\\mathbf{x}=[x_1,...,x_N]^T$$\nDefine a vector function\n$$\\mathbf{f}(\\mathbf{x})=[f_1(\\mathbf{x}),...,f_N(\\mathbf{x})]^T$$\nSo that the equation system above can be written as\n$$\\mathbf{f}(\\mathbf{x})=\\mathbf{0}$$\n* $\\mathbf{J}_{\\mathbf{f}}(\\mathbf{x})$ is the $\\textit{Jacobian matrix}$ over the function vector $\\mathbf{f}(\\mathbf{x})$ \n$$\\mathbf{J}_{\\mathbf{f}}(\\mathbf{x})=\\begin{bmatrix}\n\\frac{\\partial f_1}{\\partial x_1} & \\dots & \\frac{\\partial f_1}{\\partial x_N} \\\\\n\\vdots & \\ddots & \\vdots \\\\\n\\frac{\\partial f_N}{\\partial x_1} & \\dots & \\frac{\\partial f_N}{\\partial x_N}\n\\end{bmatrix}$$\n* If all equations are linear we have\n$$\\mathbf{f}(\\mathbf{x}+\\delta \\mathbf{x})=\\mathbf{f}(\\mathbf{x})+\\mathbf{J}(\\mathbf{x})\\delta\\mathbf{x}$$\n* by assuming $\\mathbf{f}(\\mathbf{x}+\\delta \\mathbf{x})=0$, we can find the roots as $\\mathbf{x}+\\delta \\mathbf{x}$, where\n$$\\delta \\mathbf{x} = -\\mathbf{J}(\\mathbf{x})^{-1}\\mathbf{f}(\\mathbf{x})$$\n* The approximation can be improved iteratively\n$$\\mathbf{x}_{n+1} = \\mathbf{x}_n +\\delta \\mathbf{x}_n = \\mathbf{x}_n-\\mathbf{J}(\\mathbf{x}_n)^{-1}\\mathbf{f}(\\mathbf{x}_n)$$", "_____no_output_____" ] ], [ [ "from scipy.optimize import fsolve\nimport numpy as np\n\nf1 = lambda x: [x[0]**2+x[1]**2-50,x[0]*x[1]-25]\n#the Jacobian needed to implement Newton's method\nfd = lambda x: np.array([[2*x[0],2*x[1]],[x[1],x[0]]]).reshape(2,2)\n#define the domain where we want to find the solution (x,y)\na = np.linspace(-10,10,100)\nb = a\n#for every point (a,b), pass on to fsolve and append the result \n#then round the result and see how many pairs of solutions there are\ni = 0\nresult = np.array([[5,5]])\n#print result\nfor a,b in zip(a,b):\n x = fsolve(f1,[a,b],fprime=fd)\n x = np.round(x)\n result = np.append(result,[x],axis=0)\n\nprint \"The sets of solutions are found to be:\",np.unique(result,axis=0)\n", "The sets of solutions are found to be: [[-5. -5.]\n [ 5. 5.]]\n" ] ], [ [ "From above we learn that the solutions are indeed left with $(x,y) = (5,5)$ or $(x,y) = (-5,-5)$ ", "_____no_output_____" ], [ "### (c) Convergence", "_____no_output_____" ] ], [ [ "%config InlineBackend.figure_format = 'retina' \nimport numpy as np\nfrom scipy.optimize import fsolve\n\nimport matplotlib.pyplot as plt\n\ndef f(x, y):\n return x**2+y**2-50;\n\ndef g(x, y):\n return x*y-25\n\nx = np.linspace(-6, 6, 500)\n\[email protected]\ndef fy(x):\n x0 = 0.0\n def tmp(y):\n return f(x, y)\n y1, = fsolve(tmp, x0)\n return y1\n\[email protected]\ndef gy(x):\n x0 = 0.0\n def tmp(y):\n return g(x, y)\n y1, = fsolve(tmp, x0)\n return y1\n\n\nplt.plot(x, fy(x), x, gy(x))\nplt.xlabel('x')\nplt.ylabel('y')\nplt.rc('xtick', labelsize=10) # fontsize of the tick labels\nplt.rc('ytick', labelsize=10)\nplt.legend(['fy', 'gy'])\nplt.show()\n#print fy(x)", "_____no_output_____" ], [ "i =1\nI = np.array([])\nF = np.array([])\nG = np.array([])\nX_std = np.array([])\nY_std = np.array([])\nwhile i<50:\n x_result = fsolve(f1,[-100,-100],maxfev=i)\n f_result = f(x_result[0],x_result[1])\n g_result = g(x_result[0],x_result[1])\n x1_std = abs(x_result[0]+5.0)\n x2_std = abs(x_result[1]+5.0)\n F = np.append(F,f_result)\n G = np.append(G,g_result)\n I = np.append(I,i)\n X_std = np.append(X_std,x1_std)\n Y_std = np.append(Y_std,x2_std)\n i+=1\nxtol = 1.49012e-08\nplt.loglog(I,np.abs(F),I,np.abs(G))\nplt.title(\"converge of f and g\")\nplt.xlabel(\"iterations\")\nplt.ylabel(\"function values\")\nplt.legend(['f','g'])\nplt.show()", "_____no_output_____" ], [ "plt.loglog(I,X_std,I,Y_std)\nplt.axhline(y=xtol,color='#b22222',lw=3)\nplt.title(r\"$converge \\ of \\ \\Delta_x \\ and \\ \\Delta_y$\")\nplt.xlabel(\"iterations\")\nplt.ylabel(\"Deviation values\")\nplt.legend([r'$\\Delta x$',r'$\\Delta y$','tolerance'])\nplt.show()", "_____no_output_____" ] ], [ [ "### (d) Maximum iterations", "_____no_output_____" ], [ "Now also apply the Jacobian. The jacobian of the system of equation is simply as follows\n$$\\mathbf{J} = \\begin{bmatrix}\n\\frac{\\partial f}{\\partial x} & \\frac{\\partial f}{\\partial y} \\\\\n\\frac{\\partial g}{\\partial x} & \\frac{\\partial g}{\\partial y}\n\\end{bmatrix}$$\n\n$$=\\begin{bmatrix}\n2x & 2y \\\\\ny & x\n\\end{bmatrix}$$", "_____no_output_____" ] ], [ [ "fd = lambda x: np.array([[2*x[0],2*x[1]],[x[1],x[0]]]).reshape(2,2)\n\n\ni =1\nI = np.array([])\nF = np.array([])\nG = np.array([])\nX_std = np.array([])\nY_std = np.array([])\nwhile i<50:\n x_result = fsolve(f1,[-100,-100],fprime=fd,maxfev=i)\n f_result = f(x_result[0],x_result[1])\n g_result = g(x_result[0],x_result[1])\n x1_std = abs(x_result[0]+5.0)\n x2_std = abs(x_result[1]+5.0)\n F = np.append(F,f_result)\n G = np.append(G,g_result)\n I = np.append(I,i)\n X_std = np.append(X_std,x1_std)\n Y_std = np.append(Y_std,x2_std)\n i+=1\nxtol = 1.49012e-08\nplt.loglog(I,np.abs(F),I,np.abs(G))\nplt.title(\"converge of f and g\")\nplt.xlabel(\"iterations\")\nplt.ylabel(\"function values\")\nplt.legend(['f','g'])\nplt.show()", "_____no_output_____" ], [ "plt.loglog(I,X_std,I,Y_std)\nplt.axhline(y=xtol,color='#b22222',lw=3)\nplt.title(r\"$converge \\ of \\ \\Delta_x \\ and \\ \\Delta_y$\")\nplt.xlabel(\"iterations\")\nplt.ylabel(\"Deviation values\")\nplt.legend([r'$\\Delta x$',r'$\\Delta y$','tolerance'])\nplt.show()", "_____no_output_____" ] ], [ [ "Now that we have applied the Jacobian and it can be seen directly from the two plots above that they both drop more quickly to zero, and f and g (also $\\Delta x$ and $\\Delta y$) started to converge more quickly in the case when the Jacobian is applied, and is approaching the tolerance much faster ($\\Delta x$ and $\\Delta y$). This happens because when the comupter is trying to build up the Jacobian, it needs multiple sets of solutions to estimate the partial derivatives, and the derivatives are all just calculated from $\\frac{f(x+\\Delta x)}{\\Delta x}$ and its accuracy will only increase with the cumulation of sets of solutions. But in the case of the Jacobian is applied, the function for the first derivative is then already known, so even if we start very far off we can still have an exponential increase in accuracy (the increase in accuracy in the case without Jacobian is also exponential but much slower, approximately 10 times slower).", "_____no_output_____" ] ] ]
[ "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", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d01d3e308754b00f4b5b92d3d5404db84eb447db
117,434
ipynb
Jupyter Notebook
section_robot/ideal_robot9.ipynb
MasahiroOgawa/LNPR_BOOK_CODES
112e9ce1b1312d77651c5958d44dbcd2ba225c19
[ "MIT" ]
148
2019-03-27T00:20:16.000Z
2022-03-30T22:34:11.000Z
section_robot/ideal_robot9.ipynb
MasahiroOgawa/LNPR_BOOK_CODES
112e9ce1b1312d77651c5958d44dbcd2ba225c19
[ "MIT" ]
3
2018-11-07T04:33:13.000Z
2018-12-31T01:35:16.000Z
section_robot/ideal_robot9.ipynb
MasahiroOgawa/LNPR_BOOK_CODES
112e9ce1b1312d77651c5958d44dbcd2ba225c19
[ "MIT" ]
116
2019-04-18T08:35:53.000Z
2022-03-24T05:17:46.000Z
110.47413
72,767
0.778488
[ [ [ "import matplotlib\nmatplotlib.use('nbagg')\nimport matplotlib.animation as anm\nimport matplotlib.pyplot as plt\nimport math\nimport matplotlib.patches as patches\nimport numpy as np", "_____no_output_____" ], [ "class World: ### fig:world_init_add_timespan (1-5行目)\n def __init__(self, time_span, time_interval, debug=False):\n self.objects = [] \n self.debug = debug\n self.time_span = time_span # 追加\n self.time_interval = time_interval # 追加\n \n def append(self,obj): # オブジェクトを登録するための関数\n self.objects.append(obj)\n \n def draw(self): ### fig:world_draw_with_timesapn (1, 10, 21-26, 28-34行目)\n fig = plt.figure(figsize=(4,4)) # 8x8 inchの図を準備\n ax = fig.add_subplot(111) # サブプロットを準備\n ax.set_aspect('equal') # 縦横比を座標の値と一致させる\n ax.set_xlim(-5,5) # X軸を-5m x 5mの範囲で描画\n ax.set_ylim(-5,5) # Y軸も同様に\n ax.set_xlabel(\"X\",fontsize=10) # X軸にラベルを表示\n ax.set_ylabel(\"Y\",fontsize=10) # 同じくY軸に\n \n elems = []\n \n if self.debug: \n for i in range(int(self.time_span/self.time_interval)): self.one_step(i, elems, ax) \n else:\n self.ani = anm.FuncAnimation(fig, self.one_step, fargs=(elems, ax),\n frames=int(self.time_span/self.time_interval)+1, interval=int(self.time_interval*1000), repeat=False)\n plt.show()\n \n def one_step(self, i, elems, ax):\n while elems: elems.pop().remove()\n time_str = \"t = %.2f[s]\" % (self.time_interval*i) # 時刻として表示する文字列\n elems.append(ax.text(-4.4, 4.5, time_str, fontsize=10))\n for obj in self.objects:\n obj.draw(ax, elems)\n if hasattr(obj, \"one_step\"): obj.one_step(self.time_interval) # 変更", "_____no_output_____" ], [ "class IdealRobot: ### fig:robot_camera(1,2,8,28-29行目,49-53行目)\n def __init__(self, pose, agent=None, sensor=None, color=\"black\"): # 引数を追加\n self.pose = pose \n self.r = 0.2 \n self.color = color \n self.agent = agent\n self.poses = [pose]\n self.sensor = sensor # 追加\n \n def draw(self, ax, elems):\n x, y, theta = self.pose \n xn = x + self.r * math.cos(theta) \n yn = y + self.r * math.sin(theta)\n elems += ax.plot([x,xn], [y,yn], color=self.color)\n c = patches.Circle(xy=(x, y), radius=self.r, fill=False, color=self.color) \n elems.append(ax.add_patch(c)) \n self.poses.append(self.pose)\n elems += ax.plot([e[0] for e in self.poses], [e[1] for e in self.poses], linewidth=0.5, color=\"black\")\n if self.sensor and len(self.poses) > 1: #追加\n self.sensor.draw(ax, elems, self.poses[-2]) #追加\n \n @classmethod \n def state_transition(self, nu, omega, time, pose):\n t0 = pose[2]\n if math.fabs(omega) < 1e-10:\n return pose + np.array( [nu*math.cos(t0), \n nu*math.sin(t0),\n omega ] ) * time\n else:\n return pose + np.array( [nu/omega*(math.sin(t0 + omega*time) - math.sin(t0)), \n nu/omega*(-math.cos(t0 + omega*time) + math.cos(t0)),\n omega*time ] )\n\n def one_step(self, time_interval):\n if not self.agent: return\n obs = self.sensor.data(self.pose) if self.sensor else None #追加\n nu, omega = self.agent.decision(obs) #引数追加\n self.pose = self.state_transition(nu, omega, time_interval, self.pose)", "_____no_output_____" ], [ "class Agent:\n def __init__(self, nu, omega):\n self.nu = nu\n self.omega = omega\n \n def decision(self, observation=None):\n return self.nu, self.omega", "_____no_output_____" ], [ "class Landmark:\n def __init__(self, x, y):\n self.pos = np.array([x, y]).T\n self.id = None\n \n def draw(self, ax, elems):\n c = ax.scatter(self.pos[0], self.pos[1], s=100, marker=\"*\", label=\"landmarks\", color=\"orange\")\n elems.append(c)\n elems.append(ax.text(self.pos[0], self.pos[1], \"id:\" + str(self.id), fontsize=10))", "_____no_output_____" ], [ "class Map:\n def __init__(self): # 空のランドマークのリストを準備\n self.landmarks = []\n \n def append_landmark(self, landmark): # ランドマークを追加\n landmark.id = len(self.landmarks) # 追加するランドマークにIDを与える\n self.landmarks.append(landmark)\n\n def draw(self, ax, elems): # 描画(Landmarkのdrawを順に呼び出し)\n for lm in self.landmarks: lm.draw(ax, elems)", "_____no_output_____" ], [ "class IdealCamera: ### fig:camera2(1-4行目、6, 12-13行目, 26-32行目)\n def __init__(self, env_map):\n self.map = env_map\n self.lastdata = [] # 追加\n \n def data(self, cam_pose):\n observed = []\n for lm in self.map.landmarks:\n z = self.observation_function(cam_pose, lm.pos)\n observed.append((z, lm.id))\n \n self.lastdata = observed # 追加\n return observed \n \n @classmethod\n def observation_function(cls, cam_pose, obj_pos):\n diff = obj_pos - cam_pose[0:2]\n phi = math.atan2(diff[1], diff[0]) - cam_pose[2]\n while phi >= np.pi: phi -= 2*np.pi\n while phi < -np.pi: phi += 2*np.pi\n return np.array( [np.hypot(*diff), phi ] ).T\n \n def draw(self, ax, elems, cam_pose): # 追加 ###camera2_1\n for lm in self.lastdata:\n x, y, theta = cam_pose\n distance, direction = lm[0][0], lm[0][1]\n lx = x + distance * math.cos(direction + theta)\n ly = y + distance * math.sin(direction + theta)\n elems += ax.plot([x,lx], [y,ly], color=\"pink\")", "_____no_output_____" ], [ "world = World(10, 0.1, debug=False) ### fig:sensor_drawing (10-19行目)\n\n### 地図を生成して3つランドマークを追加 ###\nm = Map() \nm.append_landmark(Landmark(2,-2))\nm.append_landmark(Landmark(-1,-3))\nm.append_landmark(Landmark(3,3))\nworld.append(m) \n\n### ロボットを作る ###\nstraight = Agent(0.2, 0.0) \ncircling = Agent(0.2, 10.0/180*math.pi) \nrobot1 = IdealRobot( np.array([ 2, 3, math.pi/6]).T, sensor=IdealCamera(m), agent=straight ) # 引数にcameraを追加、整理\nrobot2 = IdealRobot( np.array([-2, -1, math.pi/5*6]).T, sensor=IdealCamera(m), agent=circling, color=\"red\") # robot3は消しました\nworld.append(robot1)\nworld.append(robot2)\n\n### アニメーション実行 ###\nworld.draw()", "_____no_output_____" ], [ "cam = IdealCamera(m) \np = cam.data(robot2.pose)\nprint(p)", "[(array([4.12310563, 2.26829546]), 0), (array([2.23606798, 1.40612541]), 1), (array([ 6.40312424, -3.09517024]), 2)]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01d40501e6590f9215cd4495f85628327d3ee02
244,997
ipynb
Jupyter Notebook
code/data_EDA.ipynb
ArwaSheraky/Montreal-Collisions
e7fce87778a73ce9b7d6f5c0c8871d70d6fcb11c
[ "MIT" ]
1
2021-06-03T15:16:54.000Z
2021-06-03T15:16:54.000Z
code/data_EDA.ipynb
ArwaSheraky/Montreal-Collisions
e7fce87778a73ce9b7d6f5c0c8871d70d6fcb11c
[ "MIT" ]
null
null
null
code/data_EDA.ipynb
ArwaSheraky/Montreal-Collisions
e7fce87778a73ce9b7d6f5c0c8871d70d6fcb11c
[ "MIT" ]
null
null
null
125.382293
47,176
0.811426
[ [ [ "# Exploratory Data Analysis", "_____no_output_____" ] ], [ [ "from pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.sql import functions as F", "_____no_output_____" ], [ "spark = SparkSession.builder.master('local[1]').appName(\"Jupyter\").getOrCreate()\nsc = spark.sparkContext", "_____no_output_____" ], [ "#test if this works\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt \nimport scipy\nimport datetime\n\n# the more advanced python visualization library\nimport seaborn as sns\n\n# apply style to all the charts\nsns.set_style('whitegrid')\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)", "_____no_output_____" ], [ "# create sparksession\n\nspark = SparkSession \\\n .builder \\\n .appName(\"Pysparkexample\") \\\n .config(\"spark.some.config.option\", \"some-value\") \\\n .getOrCreate()", "_____no_output_____" ] ], [ [ "# Load Data", "_____no_output_____" ] ], [ [ "#collisions = spark.read.csv('data/accidents.csv', header='true', inferSchema = True)\n#collisions.show(2)\n\ndf_new = spark.read.csv('data/accidents_new.csv', header='true', inferSchema = True)", "_____no_output_____" ] ], [ [ "# Data Perspective\n_____", "_____no_output_____" ], [ "* One variable\n * Numeric variables:\n * continuous\n * discrete\n * Categorical variables:\n * ordinal\n * nominal\n\n* Multiple variables:\n * Numeric x Numeric\n * Categorical x Numeric\n * Categorical x Categorical\n____________________", "_____no_output_____" ], [ "# Overview", "_____no_output_____" ] ], [ [ "print('The total number of rows : ', df_new.count(),\n '\\nThe total number of columns :', len(df_new.columns))", "The total number of rows : 128647 \nThe total number of columns : 40\n" ] ], [ [ "# Data Schema\nPrint the data schema for our dataset - SAAQ Accident Information", "_____no_output_____" ] ], [ [ "df_new.printSchema()", "root\n |-- ID: string (nullable = true)\n |-- DATE: timestamp (nullable = true)\n |-- WEEK_DAY: string (nullable = true)\n |-- REG: string (nullable = true)\n |-- MUNCP: string (nullable = true)\n |-- STREET: string (nullable = true)\n |-- TYPE_ACCDN: integer (nullable = true)\n |-- SURFACE: integer (nullable = true)\n |-- LIGHT: integer (nullable = true)\n |-- STR_ASPCT: integer (nullable = true)\n |-- STR_CONFIG: integer (nullable = true)\n |-- METEO: integer (nullable = true)\n |-- GRAVITE: string (nullable = true)\n |-- NB_VEH_IMPLIQUES_ACCDN: integer (nullable = true)\n |-- NB_VICTIMES_TOTAL: integer (nullable = true)\n |-- NB_MORTS: integer (nullable = true)\n |-- NB_BLESSES_GRAVES: integer (nullable = true)\n |-- NB_BLESS_LEGERS: integer (nullable = true)\n |-- NB_DECES_PIETON: integer (nullable = true)\n |-- NB_BLESSES_PIETON: integer (nullable = true)\n |-- NB_VICTIMES_PIETON: integer (nullable = true)\n |-- NB_DECES_MOTO: integer (nullable = true)\n |-- NB_BLESSES_MOTO: integer (nullable = true)\n |-- NB_VICTIMES_MOTO: integer (nullable = true)\n |-- NB_DECES_VELO: integer (nullable = true)\n |-- NB_BLESSES_VELO: integer (nullable = true)\n |-- NB_VICTIMES_VELO: integer (nullable = true)\n |-- nb_automobile_camion_leger: integer (nullable = true)\n |-- nb_camionLourd_tractRoutier: integer (nullable = true)\n |-- nb_outil_equipement: integer (nullable = true)\n |-- nb_tous_autobus_minibus: integer (nullable = true)\n |-- nb_bicyclette: integer (nullable = true)\n |-- nb_cyclomoteur: integer (nullable = true)\n |-- nb_motocyclette: integer (nullable = true)\n |-- nb_taxi: integer (nullable = true)\n |-- nb_urgence: integer (nullable = true)\n |-- nb_motoneige: integer (nullable = true)\n |-- nb_VHR: integer (nullable = true)\n |-- nb_autres_types: integer (nullable = true)\n |-- nb_veh_non_precise: integer (nullable = true)\n\n" ], [ "# Create temporary table query with SQL\n\ndf_new.createOrReplaceTempView('AccidentData')\naccidents_limit_10 = spark.sql(\n'''\nSELECT * FROM AccidentData\nLIMIT 10\n'''\n).toPandas()\n\naccidents_limit_10", "_____no_output_____" ] ], [ [ "# One Variable\n__________", "_____no_output_____" ], [ "## a. Numeric - Data Totals\nTotals for various accident records", "_____no_output_____" ] ], [ [ "from pyspark.sql import functions as func\n\n#df_new.agg(func.sum(\"NB_BLESSES_VELO\").alias('Velo'),func.sum(\"NB_VICTIMES_MOTO\"),func.sum(\"NB_VEH_IMPLIQUES_ACCDN\")).show()\n\ndf_new.agg(func.sum(\"NB_VEH_IMPLIQUES_ACCDN\").alias('Ttl Cars In Accidents')).show()\ndf_new.agg(func.sum(\"NB_VICTIMES_TOTAL\").alias('Ttl Victims')).show()\ndf_new.agg(func.sum(\"NB_MORTS\").alias('Ttl Deaths')).show()\ndf_new.agg(func.sum(\"NB_BLESSES_GRAVES\").alias('Ttl Severe Injuries')).show()\ndf_new.agg(func.sum(\"NB_BLESS_LEGERS\").alias('Ttl Light Injuries')).show()\ndf_new.agg(func.sum(\"NB_DECES_PIETON\").alias('Ttl Pedestrian Deaths')).show()\ndf_new.agg(func.sum(\"NB_BLESSES_PIETON\").alias('Ttl Pedestrian Injuries')).show()\ndf_new.agg(func.sum(\"NB_VICTIMES_PIETON\").alias('Ttl Pedestrian Victims')).show()\ndf_new.agg(func.sum(\"NB_DECES_MOTO\").alias('Ttl Moto Deaths')).show()\ndf_new.agg(func.sum(\"NB_BLESSES_MOTO\").alias('Ttl Moto Injuries')).show()\ndf_new.agg(func.sum(\"NB_VICTIMES_MOTO\").alias('Ttl Moto Victims')).show()\ndf_new.agg(func.sum(\"NB_DECES_VELO\").alias('Ttl Bike Deaths')).show()\ndf_new.agg(func.sum(\"NB_BLESSES_VELO\").alias('Ttl Bike Injuries')).show()\ndf_new.agg(func.sum(\"NB_VICTIMES_VELO\").alias('Ttl Bike Victims')).show()\ndf_new.agg(func.sum(\"nb_automobile_camion_leger\").alias('Ttl Car - Light Trucks')).show()\ndf_new.agg(func.sum(\"nb_camionLourd_tractRoutier\").alias('Ttl Heavy Truck - Tractor')).show()\ndf_new.agg(func.sum(\"nb_outil_equipement\").alias('Ttl Equipment - Tools')).show()\ndf_new.agg(func.sum(\"nb_tous_autobus_minibus\").alias('Ttl Bus')).show()\ndf_new.agg(func.sum(\"nb_bicyclette\").alias('Ttl Bikes')).show()\ndf_new.agg(func.sum(\"nb_cyclomoteur\").alias('Ttl Motorized Bike')).show()\ndf_new.agg(func.sum(\"nb_motocyclette\").alias('Ttl Motorcycle')).show()\ndf_new.agg(func.sum(\"nb_taxi\").alias('Ttl Taxi')).show()\ndf_new.agg(func.sum(\"nb_urgence\").alias('Ttl Emergency')).show()\ndf_new.agg(func.sum(\"nb_motoneige\").alias('Ttl Snowmobile')).show()\ndf_new.agg(func.sum(\"nb_VHR\").alias('Ttl Motorhome')).show()\ndf_new.agg(func.sum(\"nb_autres_types\").alias('Ttl Other Types')).show()\ndf_new.agg(func.sum(\"nb_veh_non_precise\").alias('Ttl Non Specified Vehicles')).show()", "+---------------------+\n|Ttl Cars In Accidents|\n+---------------------+\n| 251681|\n+---------------------+\n\n+-----------+\n|Ttl Victims|\n+-----------+\n| 39532|\n+-----------+\n\n+----------+\n|Ttl Deaths|\n+----------+\n| 170|\n+----------+\n\n+-------------------+\n|Ttl Severe Injuries|\n+-------------------+\n| 1339|\n+-------------------+\n\n+------------------+\n|Ttl Light Injuries|\n+------------------+\n| 38023|\n+------------------+\n\n+---------------------+\n|Ttl Pedestrian Deaths|\n+---------------------+\n| 97|\n+---------------------+\n\n+-----------------------+\n|Ttl Pedestrian Injuries|\n+-----------------------+\n| 7255|\n+-----------------------+\n\n+----------------------+\n|Ttl Pedestrian Victims|\n+----------------------+\n| 7352|\n+----------------------+\n\n+---------------+\n|Ttl Moto Deaths|\n+---------------+\n| 11|\n+---------------+\n\n+-----------------+\n|Ttl Moto Injuries|\n+-----------------+\n| 1159|\n+-----------------+\n\n+----------------+\n|Ttl Moto Victims|\n+----------------+\n| 1170|\n+----------------+\n\n+---------------+\n|Ttl Bike Deaths|\n+---------------+\n| 24|\n+---------------+\n\n+-----------------+\n|Ttl Bike Injuries|\n+-----------------+\n| 4447|\n+-----------------+\n\n+----------------+\n|Ttl Bike Victims|\n+----------------+\n| 4471|\n+----------------+\n\n+----------------------+\n|Ttl Car - Light Trucks|\n+----------------------+\n| 196290|\n+----------------------+\n\n+-------------------------+\n|Ttl Heavy Truck - Tractor|\n+-------------------------+\n| 13762|\n+-------------------------+\n\n+---------------------+\n|Ttl Equipment - Tools|\n+---------------------+\n| 1789|\n+---------------------+\n\n+-------+\n|Ttl Bus|\n+-------+\n| 3664|\n+-------+\n\n+---------+\n|Ttl Bikes|\n+---------+\n| 5861|\n+---------+\n\n+------------------+\n|Ttl Motorized Bike|\n+------------------+\n| 884|\n+------------------+\n\n+--------------+\n|Ttl Motorcycle|\n+--------------+\n| 1933|\n+--------------+\n\n+--------+\n|Ttl Taxi|\n+--------+\n| 5104|\n+--------+\n\n+-------------+\n|Ttl Emergency|\n+-------------+\n| 4167|\n+-------------+\n\n+--------------+\n|Ttl Snowmobile|\n+--------------+\n| 5|\n+--------------+\n\n+-------------+\n|Ttl Motorhome|\n+-------------+\n| 7|\n+-------------+\n\n+---------------+\n|Ttl Other Types|\n+---------------+\n| 694|\n+---------------+\n\n+--------------------------+\n|Ttl Non Specified Vehicles|\n+--------------------------+\n| 17521|\n+--------------------------+\n\n" ], [ "df_totals = pd.DataFrame(columns=['Attr','Total'])\n\n#df_totals.append({'Attr':'NB_VEH_IMPLIQUES_ACCDN','Total':df_new.agg(func.sum(\"NB_VEH_IMPLIQUES_ACCDN\"))},ignore_index=True)\n#df_totals", "_____no_output_____" ] ], [ [ "## b. Categorical", "_____no_output_____" ], [ "### GRAVITE - severity of the accident", "_____no_output_____" ] ], [ [ "gravite_levels = spark.sql(\n'''\nSELECT GRAVITE, COUNT(*) as Total FROM AccidentData\nGROUP BY GRAVITE\nORDER BY Total DESC\n'''\n).toPandas()\n\ngravite_levels", "_____no_output_____" ], [ "# Pie Chart\n\nfig,ax = plt.subplots(1,1,figsize=(12,6))\n\nwedges, texts, autotexts = ax.pie(gravite_levels['Total'], radius=2, #labeldistance=2, pctdistance=1.1,\n autopct='%1.2f%%', startangle=90)\n\n\nax.legend(wedges, gravite_levels['GRAVITE'],\n title=\"GRAVITE\",\n loc=\"center left\",\n bbox_to_anchor=(1, 0, 0.5, 1))\n\nplt.setp(autotexts, size=12, weight=\"bold\")\nax.axis('equal') \nplt.tight_layout()\n\nplt.savefig('figures/gravite_levels.png')\nplt.show()", "_____no_output_____" ] ], [ [ "### METEO - Weather Conditions", "_____no_output_____" ] ], [ [ "meteo_conditions = spark.sql(\n'''\nSELECT METEO, COUNT(*) as Total FROM AccidentData\nGROUP BY METEO\nORDER BY Total DESC\n'''\n).toPandas()\n\nmeteo_conditions['METEO'] = meteo_conditions['METEO'].replace( {11:'Clear',12:'Overcast: cloudy/dark',13:'Fog/mist',\n 14:'Rain/bruine',15:'Heavy rain',16:'Strong wind',\n 17:'Snow/storm',18:'Blowing snow/blizzard',\n 19:'Ice',99:'Other..'})\n\nmeteo_conditions", "_____no_output_____" ], [ "fig,ax = plt.subplots(1,1,figsize=(10,6))\n\nplt.bar(meteo_conditions['METEO'], meteo_conditions['Total'],\n align='center', alpha=0.7, width=0.7, color='purple')\n\nplt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')\nfig.tight_layout()\n\nplt.savefig('figures/meteo_conditions.png')\nplt.show()", "_____no_output_____" ] ], [ [ "# Multiple Variables\n____________\n## Numeric X Categorical", "_____no_output_____" ], [ "### 1. Accident Victims by Municipality", "_____no_output_____" ] ], [ [ "victims_by_municipality = spark.sql(\n'''\nSELECT MUNCP, SUM(NB_VICTIMES_TOTAL) as Total FROM AccidentData\nGROUP BY MUNCP\nORDER BY Total DESC\n\n'''\n).toPandas()\n\nvictims_by_municipality", "_____no_output_____" ], [ "fig,ax = plt.subplots(1,1,figsize=(10,6))\n\nvictims_by_municipality.plot(x = 'MUNCP', y = 'Total', kind = 'barh', color = 'C0', ax = ax, legend = False)\n\nax.set_xlabel('Total Victims', size = 16)\nax.set_ylabel('Municipality', size = 16)\n\nplt.savefig('figures/victims_by_municipality.png')\nplt.show()", "_____no_output_____" ], [ "\nvictims_by_region = spark.sql(\n'''\nSELECT MUNCP, SUM(NB_VICTIMES_TOTAL) as Total FROM AccidentData\nGROUP BY MUNCP\n\n'''\n).toPandas()\n\nplt.figure(figsize = (10,6))\nsns.distplot(np.log(victims_by_region['Total']))\n\nplt.title('Total Victims Histogram by Region', size = 16)\nplt.ylabel('Density', size = 16)\nplt.xlabel('Log Total', size = 16)\n\nplt.savefig('figures/distplot.png')\nplt.show()", "_____no_output_____" ] ], [ [ "### 2. Total Collisions by Day of Week", "_____no_output_____" ] ], [ [ "collisions_by_day = spark.sql(\n'''\nSELECT WEEK_DAY, COUNT(WEEK_DAY) as Number_of_Collisions FROM AccidentData\nGROUP BY WEEK_DAY\nORDER BY Number_of_Collisions DESC\n\n'''\n).toPandas()\n\ncollisions_by_day", "_____no_output_____" ], [ "fig,ax = plt.subplots(1,1,figsize=(10,6))\n\ncollisions_by_day.plot(x = 'WEEK_DAY', y = 'Number_of_Collisions', kind = 'barh', color = 'C0', ax = ax, legend = False)\n\nax.set_xlabel('Number_of_Collisions', size = 16)\nax.set_ylabel('WEEK_DAY', size = 16)\n\nplt.savefig('figures/collisions_by_day.png')\nplt.show()", "_____no_output_____" ] ], [ [ "#### \"VE\", Friday has the highest number of collisions.", "_____no_output_____" ], [ "### 3. Top 10 Accidents by street", "_____no_output_____" ] ], [ [ "accidents_by_street = spark.sql(\n'''\nSELECT STREET, COUNT(STREET) as Number_of_Accidents FROM AccidentData\nGROUP BY STREET\nORDER BY Number_of_Accidents DESC\nLIMIT 10\n'''\n).toPandas()", "_____no_output_____" ], [ "fig,ax = plt.subplots(1,1,figsize=(10,6))\n\n#accidents_by_street.plot(x = 'STREET', y = 'Number_of_Accidents', kind = 'barh', color = 'C0', ax = ax, legend = False)\nsns.barplot(x=accidents_by_street['Number_of_Accidents'], y=accidents_by_street['STREET'], orient='h')\n\nax.set_xlabel('Number of Accidents', size = 16)\nax.set_ylabel('Street', size = 16)\n\nplt.savefig('figures/accidents_by_street.png')\nplt.show()", "_____no_output_____" ] ], [ [ "## Numeric X Numeric", "_____no_output_____" ], [ "### Correlation Heatmap\nIllustrates the corellation between numeric variables of the dataset.", "_____no_output_____" ] ], [ [ "plot_df = spark.sql(\n'''\nSELECT METEO, SURFACE, LIGHT, TYPE_ACCDN, \nNB_MORTS, NB_BLESSES_GRAVES, NB_VEH_IMPLIQUES_ACCDN, NB_VICTIMES_TOTAL\nFROM AccidentData\n\n'''\n).toPandas()\n\n\ncorrmat = plot_df.corr()\nf, ax = plt.subplots(figsize=(10, 7))\nsns.heatmap(corrmat, vmax=.8, square=True)\nplt.savefig('figures/heatmap.png')\nplt.show()\n", "_____no_output_____" ] ], [ [ "## Categorical X Categorical", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
d01d433ec289320ffcaeac58cd9c3744bb09a26f
104,392
ipynb
Jupyter Notebook
notebooks/ExpW EDA.ipynb
StefanieStoppel/InferFace
89b3a47d49d24cb5e67d7a11d114f8f1711a7785
[ "MIT" ]
null
null
null
notebooks/ExpW EDA.ipynb
StefanieStoppel/InferFace
89b3a47d49d24cb5e67d7a11d114f8f1711a7785
[ "MIT" ]
null
null
null
notebooks/ExpW EDA.ipynb
StefanieStoppel/InferFace
89b3a47d49d24cb5e67d7a11d114f8f1711a7785
[ "MIT" ]
null
null
null
44.065851
20,488
0.624483
[ [ [ "import pandas as pd\nimport os\nimport csv\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "data_dir = '/home/steffi/dev/data/ExpW/ExpwCleaned'\nlabels_csv = '/home/steffi/dev/data/ExpW/labels_clean.csv'", "_____no_output_____" ], [ "expw = pd.read_csv(labels_csv, delimiter=',')", "_____no_output_____" ], [ "expw.head()", "_____no_output_____" ], [ "expressions = expw.iloc[:, 2:]", "_____no_output_____" ], [ "expression_mapping = {\n 0: \"angry\",\n 1: \"disgust\",\n 2: \"fear\",\n 3: \"happy\",\n 4: \"sad\",\n 5: \"surprise\",\n 6: \"neutral\"\n}", "_____no_output_____" ] ], [ [ "## Hist plot for all values (even though 0 is actually useless)", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(figsize=(10,10))\nax.hist(expressions, alpha=0.5, label=expressions.columns)\nax.legend()", "_____no_output_____" ] ], [ [ "#### Filter out all values that are equal to 0", "_____no_output_____" ] ], [ [ "expressions.value_counts(sort=True)", "_____no_output_____" ] ], [ [ "#### ===> columns contempt, unkown and NF can be dropped ", "_____no_output_____" ] ], [ [ "expressions_drop = expressions.drop(columns=[\"unknown\", \"contempt\", \"NF\"])", "_____no_output_____" ], [ "exp_nan = expressions_drop.replace(0, np.NaN)", "_____no_output_____" ], [ "exp_stacked = exp_nan.stack(dropna=True)", "_____no_output_____" ], [ "exp_unstacked = exp_stacked.reset_index(level=1)\nexpressions_single = exp_unstacked.rename(columns={\"level_1\": \"expression\"}).drop(columns=[0])", "_____no_output_____" ], [ "expressions_single.head()", "_____no_output_____" ] ], [ [ "### Append expressions to expw", "_____no_output_____" ] ], [ [ "expw[\"expression\"] = expressions_single[\"expression\"]", "_____no_output_____" ], [ "expw.head()", "_____no_output_____" ] ], [ [ "### Remove unnecessary columns", "_____no_output_____" ] ], [ [ "expw_minimal = expw.drop(expw.columns[1:-1], axis=1)", "_____no_output_____" ], [ "expw_minimal.loc[:, \"Image name\"] = data_dir + \"/\" + expw_minimal[\"Image name\"].astype(str)", "_____no_output_____" ], [ "expw_minimal.shape", "_____no_output_____" ] ], [ [ "### Histogram of expression distribution", "_____no_output_____" ] ], [ [ "x_ticks = [f\"{idx} = {expr}, count: {count}\" for idx, (expr, count) in enumerate(zip(list(expressions_single.value_counts().index.get_level_values(0)), expressions_single.value_counts().values))]", "_____no_output_____" ], [ "x_ticks", "_____no_output_____" ], [ "ax = expressions_single.value_counts().plot(kind='barh')\nax.set_yticklabels(x_ticks)", "_____no_output_____" ] ], [ [ "### Create a csv file with all absolute image paths for annotating with FairFace", "_____no_output_____" ] ], [ [ "col_name = \"img_path\"", "_____no_output_____" ], [ "image_names = expw[[\"Image name\"]]", "_____no_output_____" ], [ "image_names.head()", "_____no_output_____" ], [ "image_names.rename(columns={\"Image name\": \"img_path\"}, inplace=True)", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/frame.py:4296: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return super().rename(\n" ], [ "image_names.loc[:, \"img_path\"] = data_dir + \"/\" + image_names[\"img_path\"].astype(str)", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/indexing.py:1783: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self.obj[item_labels[indexer[info_axis]]] = value\n" ], [ "save_path = \"/home/steffi/dev/independent_study/FairFace/expw_image_paths.csv\"", "_____no_output_____" ], [ "image_names.to_csv(save_path, index=False)", "_____no_output_____" ] ], [ [ "### Filter only img_paths which contain \"black\", \"African\", \"chinese\", \"asian\"", "_____no_output_____" ] ], [ [ "black = image_names.loc[image_names.img_path.str.contains('(black)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "african = image_names.loc[image_names.img_path.str.contains('(African)'), :]", "_____no_output_____" ], [ "asian = image_names.loc[image_names.img_path.str.contains('(asian)'), :]", "_____no_output_____" ], [ "chinese = image_names.loc[image_names.img_path.str.contains('(chinese)'), :]", "_____no_output_____" ], [ "filtered = pd.concat([black, african, asian, chinese])", "_____no_output_____" ] ], [ [ "### Filter and save subgroups", "_____no_output_____" ], [ "##### Anger", "_____no_output_____" ] ], [ [ "black_angry_annoyed = black.loc[image_names.img_path.str.contains('(angry)|(annoyed)'), :]", "_____no_output_____" ], [ "black_angry_annoyed.to_csv(\"/home/steffi/dev/independent_study/FairFace/black_angry_annoyed.csv\", index=False)", "_____no_output_____" ], [ "black_angry_annoyed.head()", "_____no_output_____" ], [ "african_angry_annoyed = african.loc[image_names.img_path.str.contains('(angry)|(annoyed)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "african_angry_annoyed.to_csv(\"/home/steffi/dev/independent_study/FairFace/african_angry_annoyed.csv\", index=False)", "_____no_output_____" ], [ "african_angry_annoyed.shape", "_____no_output_____" ], [ "asian_angry_annoyed = asian.loc[image_names.img_path.str.contains('(angry)|(annoyed)'), :]", "_____no_output_____" ], [ "asian_angry_annoyed", "_____no_output_____" ], [ "asian_angry_annoyed.to_csv(\"/home/steffi/dev/independent_study/FairFace/asian_angry_annoyed.csv\", index=False)", "_____no_output_____" ], [ "chinese_angry_annoyed = chinese.loc[image_names.img_path.str.contains('(angry)|(annoyed)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "chinese_angry_annoyed.head()", "_____no_output_____" ], [ "chinese_angry_annoyed.to_csv(\"/home/steffi/dev/independent_study/FairFace/chinese_angry_annoyed.csv\", index=False)", "_____no_output_____" ] ], [ [ "##### Surprise", "_____no_output_____" ] ], [ [ "black_awe_astound_amazed = black.loc[image_names.img_path.str.contains('(awe)|(astound)|(amazed)'), :]", "_____no_output_____" ], [ "black_awe_astound_amazed", "_____no_output_____" ], [ "black_awe_astound_amazed.to_csv(\"/home/steffi/dev/independent_study/FairFace/black_awe_astound_amazed.csv\", index=False)", "_____no_output_____" ], [ "african_awe = african.loc[image_names.img_path.str.contains('(awe)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "african_awe", "_____no_output_____" ], [ "african_awe.to_csv(\"/home/steffi/dev/independent_study/FairFace/african_awe.csv\", index=False)", "_____no_output_____" ], [ "asian_astound = asian.loc[image_names.img_path.str.contains('(astound)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "asian_astound.to_csv(\"/home/steffi/dev/independent_study/FairFace/asian_astound.csv\", index=False)", "_____no_output_____" ], [ "asian_astound", "_____no_output_____" ], [ "chinese_astound = chinese.loc[image_names.img_path.str.contains('(astound)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "chinese_astound.to_csv(\"/home/steffi/dev/independent_study/FairFace/chinese_astound.csv\", index=False)", "_____no_output_____" ], [ "chinese_astound", "_____no_output_____" ] ], [ [ "#### Fear", "_____no_output_____" ] ], [ [ "black_fear = black.loc[image_names.img_path.str.contains('(fear)|(frightened)|(anxious)|(shocked)'), :]", "_____no_output_____" ], [ "black_fear.shape", "_____no_output_____" ], [ "african_fear = african.loc[image_names.img_path.str.contains('(fear)|(frightened)|(anxious)|(shocked)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "black_african_fear = pd.concat([african_fear, black_fear])", "_____no_output_____" ], [ "black_african_fear.shape", "_____no_output_____" ], [ "black_african_fear.to_csv(\"/home/steffi/dev/independent_study/FairFace/black_african_fear.csv\", index=False)", "_____no_output_____" ] ], [ [ "#### Disgust", "_____no_output_____" ] ], [ [ "black_disgust = black.loc[image_names.img_path.str.contains('(distaste)|(disgust)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "african_digsust = african.loc[image_names.img_path.str.contains('(distaste)|(disgust)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "african_digsust.shape", "_____no_output_____" ], [ "black_african_disgust = pd.concat([black_disgust, african_digsust])", "_____no_output_____" ], [ "pd.set_option('display.max_colwidth', -1)", "<ipython-input-55-0891b765a168>:1: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.\n pd.set_option('display.max_colwidth', -1)\n" ], [ "black_african_disgust", "_____no_output_____" ], [ "black_african_disgust.to_csv(\"/home/steffi/dev/independent_study/FairFace/black_african_disgust.csv\", index=False)", "_____no_output_____" ], [ "disgust_all = image_names.loc[image_names.img_path.str.contains('(distaste)|(disgust)'), :]", "/home/steffi/.conda/envs/InferFace/lib/python3.8/site-packages/pandas/core/strings.py:2001: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.\n return func(self, *args, **kwargs)\n" ], [ "disgust_all.shape", "_____no_output_____" ], [ "disgust_all", "_____no_output_____" ] ], [ [ "#### Saving all filtered to csv", "_____no_output_____" ] ], [ [ "filtered_save_path = \"/home/steffi/dev/independent_study/FairFace/filtered_expw_image_paths.csv\"", "_____no_output_____" ], [ "filtered.to_csv(filtered_save_path, index=False)", "_____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" ]
[ [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d01d481ca18df942215713f7c61655461a08c8ef
8,595
ipynb
Jupyter Notebook
example/evaluation_with_executable.ipynb
birolkuyumcu/fastext_gui
dfe3d418e2313d0775e65be3b7b7ec3be818b55d
[ "MIT" ]
6
2019-12-01T19:14:02.000Z
2022-02-19T10:02:17.000Z
example/evaluation_with_executable.ipynb
birolkuyumcu/fasttext_gui
dfe3d418e2313d0775e65be3b7b7ec3be818b55d
[ "MIT" ]
null
null
null
example/evaluation_with_executable.ipynb
birolkuyumcu/fasttext_gui
dfe3d418e2313d0775e65be3b7b7ec3be818b55d
[ "MIT" ]
null
null
null
29.434932
117
0.444095
[ [ [ "import pandas as pd\nimport numpy as np\nimport random\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix, classification_report\n%matplotlib inline", "_____no_output_____" ], [ "!fasttext", "usage: fasttext <command> <args>\n\nThe commands supported by fasttext are:\n\n supervised train a supervised classifier\n quantize quantize a model to reduce the memory usage\n test evaluate a supervised classifier\n predict predict most likely labels\n predict-prob predict most likely labels with probabilities\n skipgram train a skipgram model\n cbow train a cbow model\n print-word-vectors print word vectors given a trained model\n print-sentence-vectors print sentence vectors given a trained model\n print-ngrams print ngrams given a trained model and word\n nn query for nearest neighbors\n analogies query for analogies\n dump dump arguments,dictionary,input/output vectors\n\n" ], [ "def fasttext_predict_prob(model_file_name,query_list,encoding='utf-8'):\n cmd = 'fastText.exe'\n fp = open('temp.txt','wt',encoding=encoding)\n fp.writelines([x+'\\n' for x in query_list])\n fp.close()\n commands = ' predict-prob '+model_file_name+' '+'temp.txt '+str(1)\n print('Executing : ' ,cmd+commands)\n out = os.popen(cmd+commands).read()\n out = out.splitlines()\n return [item.split(' ') for item in out]", "_____no_output_____" ], [ "fp = open('dbpedia_csv/classes.txt','rt')\nclass_names = fp.readlines()\nfp.close()\nclass_names = [x.strip() for x in class_names]\nclass_names", "_____no_output_____" ], [ "fp = open('dbpedia.test','rt',encoding='utf-8')\nlines = fp.readlines()\nfp.close()", "_____no_output_____" ], [ "labels = []\nqlist = []\nfor line in lines:\n i = line.index(',')\n labels.append(line[:i])\n qlist.append(line[i+1:].strip())", "_____no_output_____" ], [ "labels = [x.split('__')[-1].strip() for x in labels]", "_____no_output_____" ], [ "out = fasttext_predict_prob('models/dbpedia_1.bin',qlist)", "Executing : fastText.exe predict-prob models/dbpedia_1.bin temp.txt 1\n" ], [ "predicted = [x[0] for x in out]\npredicted = [x.split('__')[-1].strip() for x in predicted]", "_____no_output_____" ], [ "y_true = [class_names.index(x) for x in labels]\ny_pred = [class_names.index(x) for x in predicted]", "_____no_output_____" ], [ "cm = confusion_matrix(labels, predicted, labels=class_names)\nprint (\"Confusion matrix \\n\",cm)", "Confusion matrix \n [[4767 39 8 4 14 34 50 3 2 0 7 12 9 51]\n [ 33 4924 0 0 5 1 30 1 1 0 0 0 2 3]\n [ 18 3 4772 13 84 0 8 1 0 0 0 27 17 57]\n [ 3 1 18 4960 14 0 0 1 0 2 0 0 1 0]\n [ 5 3 47 10 4923 2 4 0 2 1 0 0 1 2]\n [ 24 1 0 0 4 4957 8 1 0 0 2 0 1 2]\n [ 46 25 1 0 6 7 4880 21 7 2 0 1 1 3]\n [ 2 1 0 0 1 0 14 4973 9 0 0 0 0 0]\n [ 0 0 1 0 1 0 8 11 4978 0 0 0 0 1]\n [ 2 0 0 0 0 1 0 6 0 4940 50 0 0 1]\n [ 11 1 0 0 0 0 1 0 0 8 4978 0 0 1]\n [ 1 0 10 1 0 0 1 0 0 0 0 4956 19 12]\n [ 5 1 3 1 1 2 1 1 0 0 1 14 4937 33]\n [ 36 4 15 2 8 3 4 1 1 0 3 5 36 4882]]\n" ], [ "print (\" Classification Report \\n\",classification_report(y_true, y_pred, target_names=class_names,digits=3))", " Classification Report \n precision recall f1-score support\n\n Company 0.962 0.953 0.958 5000\nEducationalInstitution 0.984 0.985 0.985 5000\n Artist 0.979 0.954 0.966 5000\n Athlete 0.994 0.992 0.993 5000\n OfficeHolder 0.973 0.985 0.979 5000\n MeanOfTransportation 0.990 0.991 0.991 5000\n Building 0.974 0.976 0.975 5000\n NaturalPlace 0.991 0.995 0.993 5000\n Village 0.996 0.996 0.996 5000\n Animal 0.997 0.988 0.993 5000\n Plant 0.988 0.996 0.992 5000\n Album 0.988 0.991 0.990 5000\n Film 0.983 0.987 0.985 5000\n WrittenWork 0.967 0.976 0.972 5000\n\n accuracy 0.983 70000\n macro avg 0.983 0.983 0.983 70000\n weighted avg 0.983 0.983 0.983 70000\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01d5402657e153fe23430e75c236d684d82137f
80,885
ipynb
Jupyter Notebook
MVA/TMVA_tutorial_classification_tmva_app.py.nbconvert.ipynb
LailinXu/hepstat-tutorial
201b21c980bb29a9b81608b832475b3c356c8523
[ "CC-BY-4.0" ]
null
null
null
MVA/TMVA_tutorial_classification_tmva_app.py.nbconvert.ipynb
LailinXu/hepstat-tutorial
201b21c980bb29a9b81608b832475b3c356c8523
[ "CC-BY-4.0" ]
null
null
null
MVA/TMVA_tutorial_classification_tmva_app.py.nbconvert.ipynb
LailinXu/hepstat-tutorial
201b21c980bb29a9b81608b832475b3c356c8523
[ "CC-BY-4.0" ]
null
null
null
93.834107
19,200
0.836088
[ [ [ "# T M V A_Tutorial_Classification_Tmva_App\nTMVA example, for classification\n with following objectives:\n * Apply a BDT with TMVA\n\n\n\n\n**Author:** Lailin XU \n<i><small>This notebook tutorial was automatically generated with <a href= \"https://github.com/root-project/root/blob/master/documentation/doxygen/converttonotebook.py\">ROOTBOOK-izer</a> from the macro found in the ROOT repository on Tuesday, April 27, 2021 at 01:21 AM.</small></i>", "_____no_output_____" ] ], [ [ "from ROOT import TMVA, TFile, TTree, TCut, TH1F, TCanvas, gROOT, TLegend\nfrom subprocess import call\nfrom os.path import isfile\nfrom array import array\n \ngROOT.SetStyle(\"ATLAS\")", "Welcome to JupyROOT 6.22/07\n" ] ], [ [ "Setup TMVA", "_____no_output_____" ] ], [ [ "TMVA.Tools.Instance()", "_____no_output_____" ] ], [ [ "Reader. One reader for each application.", "_____no_output_____" ] ], [ [ "reader = TMVA.Reader(\"Color:!Silent\")\nreader_S = TMVA.Reader(\"Color:!Silent\")\nreader_B = TMVA.Reader(\"Color:!Silent\")\n ", "_____no_output_____" ] ], [ [ "Inputs\n=============\nLoad data\nAn unknown sample", "_____no_output_____" ] ], [ [ "trfile = \"Zp2TeV_ttbar.root\"\ndata = TFile.Open(trfile)\ntree = data.Get('tree')", "_____no_output_____" ] ], [ [ "Known signal", "_____no_output_____" ] ], [ [ "trfile_S = \"Zp1TeV_ttbar.root\"\ndata_S = TFile.Open(trfile_S)\ntree_S = data_S.Get('tree')", "_____no_output_____" ] ], [ [ "Known background", "_____no_output_____" ] ], [ [ "trfile_B = \"SM_ttbar.root\"\ndata_B = TFile.Open(trfile_B)\ntree_B = data_B.Get('tree')\n ", "_____no_output_____" ] ], [ [ "Set input variables. Do this for each reader", "_____no_output_____" ] ], [ [ "branches = {}\nfor branch in tree.GetListOfBranches():\n branchName = branch.GetName()\n branches[branchName] = array('f', [-999])\n tree.SetBranchAddress(branchName, branches[branchName])\n if branchName not in [\"mtt_truth\", \"weight\", \"nlep\", \"njets\"]:\n reader.AddVariable(branchName, branches[branchName])\n\nbranches_S = {}\nfor branch in tree_S.GetListOfBranches():\n branchName = branch.GetName()\n branches_S[branchName] = array('f', [-999])\n tree_S.SetBranchAddress(branchName, branches_S[branchName])\n if branchName not in [\"mtt_truth\", \"weight\", \"nlep\", \"njets\"]:\n reader_S.AddVariable(branchName, branches_S[branchName])\n\nbranches_B = {}\nfor branch in tree_B.GetListOfBranches():\n branchName = branch.GetName()\n branches_B[branchName] = array('f', [-999])\n tree_B.SetBranchAddress(branchName, branches_B[branchName])\n if branchName not in [\"mtt_truth\", \"weight\", \"nlep\", \"njets\"]:\n reader_B.AddVariable(branchName, branches_B[branchName])\n ", "_____no_output_____" ] ], [ [ "Book method(s)\n=============\nBDT", "_____no_output_____" ] ], [ [ "methodName1 = \"BDT\"\nweightfile = 'dataset/weights/TMVAClassification_{0}.weights.xml'.format(methodName1)\nreader.BookMVA( methodName1, weightfile )\nreader_S.BookMVA( methodName1, weightfile )\nreader_B.BookMVA( methodName1, weightfile )", "_____no_output_____" ] ], [ [ "BDTG", "_____no_output_____" ] ], [ [ "methodName2 = \"BDTG\"\nweightfile = 'dataset/weights/TMVAClassification_{0}.weights.xml'.format(methodName2)\nreader.BookMVA( methodName2, weightfile )\nreader_S.BookMVA( methodName2, weightfile )\nreader_B.BookMVA( methodName2, weightfile )", "_____no_output_____" ] ], [ [ "Loop events for evaluation\n================", "_____no_output_____" ], [ "Book histograms", "_____no_output_____" ] ], [ [ "nbins, xmin, xmax=20, -1, 1", "_____no_output_____" ] ], [ [ "Signal", "_____no_output_____" ] ], [ [ "tag = \"S\"\nhname=\"BDT_{0}\".format(tag)\nh1 = TH1F(hname, hname, nbins, xmin, xmax)\nh1.Sumw2()\nhname=\"BDTG_{0}\".format(tag)\nh2 = TH1F(hname, hname, nbins, xmin, xmax)\nh2.Sumw2()\n\nnevents = tree_S.GetEntries()\nfor i in range(nevents):\n tree_S.GetEntry(i)\n\n BDT = reader_S.EvaluateMVA(methodName1)\n BDTG = reader_S.EvaluateMVA(methodName2)\n h1.Fill(BDT)\n h2.Fill(BDTG)", "_____no_output_____" ] ], [ [ "Background", "_____no_output_____" ] ], [ [ "tag = \"B\"\nhname=\"BDT_{0}\".format(tag)\nh3 = TH1F(hname, hname, nbins, xmin, xmax)\nh3.Sumw2()\nhname=\"BDTG_{0}\".format(tag)\nh4 = TH1F(hname, hname, nbins, xmin, xmax)\nh4.Sumw2()\n\nnevents = tree_B.GetEntries()\nfor i in range(nevents):\n tree_B.GetEntry(i)\n\n BDT = reader_B.EvaluateMVA(methodName1)\n BDTG = reader_B.EvaluateMVA(methodName2)\n h3.Fill(BDT)\n h4.Fill(BDTG)", "_____no_output_____" ] ], [ [ "New sample", "_____no_output_____" ] ], [ [ "tag = \"N\"\nhname=\"BDT_{0}\".format(tag)\nh5 = TH1F(hname, hname, nbins, xmin, xmax)\nh5.Sumw2()\nhname=\"BDTG_{0}\".format(tag)\nh6 = TH1F(hname, hname, nbins, xmin, xmax)\nh6.Sumw2()\n\nnevents = tree.GetEntries()\nfor i in range(nevents):\n tree.GetEntry(i)\n\n BDT = reader.EvaluateMVA(methodName1)\n BDTG = reader.EvaluateMVA(methodName2)\n h5.Fill(BDT)\n h6.Fill(BDTG)", "_____no_output_____" ] ], [ [ "Helper function to normalize hists", "_____no_output_____" ] ], [ [ "def norm_hists(h):\n\n h_new = h.Clone()\n hname = h.GetName() + \"_normalized\"\n h_new.SetName(hname)\n h_new.SetTitle(hname)\n ntot = h.Integral()\n if ntot!=0:\n h_new.Scale(1./ntot)\n\n return h_new", "_____no_output_____" ] ], [ [ "Plotting", "_____no_output_____" ] ], [ [ "myc = TCanvas(\"c\", \"c\", 800, 600)\nmyc.SetFillColor(0)\nmyc.cd()", "_____no_output_____" ] ], [ [ "Compare the performance for BDT", "_____no_output_____" ] ], [ [ "nh1 = norm_hists(h1)\nnh1.GetXaxis().SetTitle(\"BDT\")\nnh1.GetYaxis().SetTitle(\"A.U.\")\nnh1.Draw(\"hist\")\nnh3 = norm_hists(h3)\nnh3.SetLineColor(2)\nnh3.SetMarkerColor(2)\nnh3.Draw(\"same hist\")\nnh5 = norm_hists(h5)\nnh5.SetLineColor(4)\nnh5.SetMarkerColor(4)\nnh5.Draw(\"same\")\n\nymin = 0\nymax = max(nh1.GetMaximum(), nh3.GetMaximum(), nh5.GetMaximum())\nnh1.GetYaxis().SetRangeUser(ymin, ymax*1.5)", "_____no_output_____" ] ], [ [ "Draw legends", "_____no_output_____" ] ], [ [ "lIy = 0.92\nlg = TLegend(0.60, lIy-0.25, 0.85, lIy)\nlg.SetBorderSize(0)\nlg.SetFillStyle(0)\nlg.SetTextFont(42)\nlg.SetTextSize(0.04)\nlg.AddEntry(nh1, \"Signal 1 TeV\", \"l\")\nlg.AddEntry(nh3, \"Background\", \"l\")\nlg.AddEntry(nh5, \"Signal 2 TeV\", \"l\")\nlg.Draw()\n\nmyc.Draw()\nmyc.SaveAs(\"TMVA_tutorial_cla_app_1.png\")", "Info in <TCanvas::Print>: png file TMVA_tutorial_cla_app_1.png has been created\n" ] ], [ [ "Compare the performance for BDTG", "_____no_output_____" ] ], [ [ "nh1 = norm_hists(h2)\nnh1.GetXaxis().SetTitle(\"BDTG\")\nnh1.GetYaxis().SetTitle(\"A.U.\")\nnh1.Draw(\"hist\")\nnh3 = norm_hists(h4)\nnh3.SetLineColor(2)\nnh3.SetMarkerColor(2)\nnh3.Draw(\"same hist\")\nnh5 = norm_hists(h6)\nnh5.SetLineColor(4)\nnh5.SetMarkerColor(4)\nnh5.Draw(\"same\")\n\nymin = 0\nymax = max(nh1.GetMaximum(), nh3.GetMaximum(), nh5.GetMaximum())\nnh1.GetYaxis().SetRangeUser(ymin, ymax*1.5)", "_____no_output_____" ] ], [ [ "Draw legends", "_____no_output_____" ] ], [ [ "lIy = 0.92\nlg = TLegend(0.60, lIy-0.25, 0.85, lIy)\nlg.SetBorderSize(0)\nlg.SetFillStyle(0)\nlg.SetTextFont(42)\nlg.SetTextSize(0.04)\nlg.AddEntry(nh1, \"Signal 1 TeV\", \"l\")\nlg.AddEntry(nh3, \"Background\", \"l\")\nlg.AddEntry(nh5, \"Signal 2 TeV\", \"l\")\nlg.Draw()\n\nmyc.Draw()\nmyc.SaveAs(\"TMVA_tutorial_cla_app_2.png\")", "Info in <TCanvas::Print>: png file TMVA_tutorial_cla_app_2.png has been created\n" ] ], [ [ "Draw all canvases ", "_____no_output_____" ] ], [ [ "from ROOT import gROOT \ngROOT.GetListOfCanvases().Draw()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01d5f17068470cbe68f754f1a6bf67b4efcaded
780,607
ipynb
Jupyter Notebook
20201120/20201116/empirical/.ipynb_checkpoints/DataProcessing-checkpoint.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
20201120/20201116/empirical/.ipynb_checkpoints/DataProcessing-checkpoint.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
20201120/20201116/empirical/.ipynb_checkpoints/DataProcessing-checkpoint.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
567.714182
388,636
0.94107
[ [ [ "# Data Processing ", "_____no_output_____" ] ], [ [ "%pylab inline\nmatplotlib.rcParams['figure.figsize'] = [20, 10]\nimport pandas as pd\nimport numpy as np\nimport warnings\nwarnings.filterwarnings(\"ignore\")", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "# All variables we concern about\ncolumnNames1 = [\"releaseNum\", \"1968ID\", \"personNumber\", \"gender\", \"marriage\", \"familyNumber\", \"sequenceNum\", \n \"relationToHead\", \"age\", 'employmentStatus', \"education\", \"nonHeadlaborIncome\"]\n\ncolumnNames2 = [\"releaseNum\", \"1968ID\", \"personNumber\", \"gender\", \"marriage\", \"familyNumber\", \"sequenceNum\", \n \"relationToHead\", \"age\", 'employmentStatus', \"education\"]\n\nFcolumnNames1999_2001 = ['releaseNum', 'familyID', 'composition', 'headCount', 'ageHead', 'maritalStatus', 'employmentStatus', \n 'liquidWealth', 'race', 'industry' ,'geoCode','incomeHead', \"incomeWife\", \n 'foodCost', 'houseCost', 'transCost', 'educationCost', 'childCost', 'healthCost', 'education', \n 'participation', 'investmentAmount', 'annuityIRA', 'wealthWithoutHomeEquity', \"wealthWithHomeEquity\"]\n\nFcolumnNames2003_2007 = ['releaseNum', 'familyID', 'composition', 'headCount', 'ageHead', 'maritalStatus', 'employmentStatus', \n 'liquidWealth', 'race', 'industry', 'incomeHead', \"incomeWife\", \n 'foodCost', 'houseCost', 'transCost', 'educationCost', 'childCost', 'healthCost', 'geoCode', 'education', \n 'participation', 'investmentAmount', 'annuityIRA', 'wealthWithoutHomeEquity', \"wealthWithHomeEquity\"]\n\nFcolumnNames2019 = ['releaseNum', 'familyID', 'composition', 'headCount', 'ageHead', 'maritalStatus', 'employmentStatus', \n 'liquidWealth', 'race', 'industry' ,'incomeHead', 'incomeWife', \n 'participation', 'investmentAmount', 'annuityIRA', 'wealthWithoutHomeEquity', 'wealthWithHomeEquity',\n 'foodCost', 'houseCost', 'transCost', 'educationCost', 'childCost', 'healthCost', 'geoCode', 'education']\n# The timeline we care about\nyears = [1999, 2001, 2003, 2005, 2007, 2009, 2011, 2013, 2015, 2017]\n\n# The function used to complile all years data into one dataFrame, \n# the input \"features\" is a list of features.\ndef compile_data_with_features(features, years):\n df = pd.DataFrame()\n # Loading the data through years\n for year in years:\n df_sub = pd.read_excel(\"individual/\" + str(year) + \".xlsx\")\n if year >= 2005:\n df_sub.columns = columnNames1\n df_sub['year'] = year\n df = pd.concat([df, df_sub[['year'] + features + [\"nonHeadlaborIncome\"]]])\n else:\n df_sub.columns = columnNames2\n df_sub['year'] = year\n df = pd.concat([df, df_sub[['year'] + features]])\n df = df.reset_index(drop = True)\n return df\n\ndef Fcompile_data_with_features(features, years):\n df = pd.DataFrame()\n # Loading the data through years\n for year in years:\n df_sub = pd.read_excel(\"family/\" + str(year) + \".xlsx\")\n if year >= 1999 and year <= 2001:\n df_sub.columns = FcolumnNames1999_2001\n elif year >= 2003 and year <= 2007:\n df_sub.columns = FcolumnNames2003_2007\n else:\n df_sub.columns = FcolumnNames2019\n df_sub['year'] = year\n df = pd.concat([df, df_sub[['familyID','year'] + features]])\n df = df.reset_index(drop = True)\n return df\n\n# The function is used to drop the values we do not like in the dataFrame, \n# the input \"features\" and \"values\" are both list\ndef drop_values(features, values, df): \n for feature in features:\n for value in values:\n df = df[df[feature] != value]\n df = df.reset_index(drop = True)\n return df", "_____no_output_____" ] ], [ [ "### Individual Data", "_____no_output_____" ] ], [ [ "Idf = compile_data_with_features([\"1968ID\", \"personNumber\", \"familyNumber\",\"gender\", \"marriage\", \n \"age\", 'employmentStatus', \"education\", \"relationToHead\"], years)\nIdf[\"ID\"] = Idf[\"1968ID\"]* 1000 + Idf[\"personNumber\"]\n# pick out the head in the individual\ndf_head = Idf[Idf[\"relationToHead\"] == 10]\ndf_head = df_head.reset_index(drop = True)\n# compile individuals with all 10 years data.\ncompleteIndividualData = []\nfor ID, value in df_head.groupby(\"ID\"):\n if len(value) == len(years):\n completeIndividualData.append(value)\nprint(\"Number of heads with complete data: \", len(completeIndividualData))", "Number of heads with complete data: 3074\n" ], [ "# prepare the combined dataset and set up dummy variables for qualitative data\ndf = Fcompile_data_with_features(['composition', 'headCount', 'ageHead', 'maritalStatus', 'employmentStatus', \n 'liquidWealth', 'race', 'industry' ,'geoCode','incomeHead', \"incomeWife\", \n 'foodCost', 'houseCost', 'transCost', 'educationCost', 'childCost', \n 'healthCost', 'education', 'participation', 'investmentAmount', 'annuityIRA', \n 'wealthWithoutHomeEquity', \"wealthWithHomeEquity\"], years)", "_____no_output_____" ] ], [ [ "### Family Data", "_____no_output_____" ] ], [ [ "# prepare the combined dataset and set up dummy variables for qualitative data\ndf = Fcompile_data_with_features(['composition', 'headCount', 'ageHead', 'maritalStatus', 'employmentStatus', \n 'liquidWealth', 'race', 'industry' ,'geoCode','incomeHead', \"incomeWife\", \n 'foodCost', 'houseCost', 'transCost', 'educationCost', 'childCost', \n 'healthCost', 'education', 'participation', 'investmentAmount', 'annuityIRA', \n 'wealthWithoutHomeEquity', \"wealthWithHomeEquity\"], years)\n\ndf = drop_values([\"ageHead\"],[999], df)\ndf = drop_values([\"maritalStatus\"],[8,9], df)\ndf = drop_values([\"employmentStatus\"],[0, 22, 98, 99], df)\ndf = drop_values([\"liquidWealth\"],[999999998,999999999], df)\ndf = drop_values([\"race\"],[0,8,9], df)\ndf = drop_values([\"industry\"],[999,0], df)\ndf = drop_values([\"education\"],[99,0], df)\ndf[\"totalExpense\"] = df[['foodCost', 'houseCost', 'transCost', \n 'educationCost', 'childCost', 'healthCost']].sum(axis = 1)\ndf[\"laborIncome\"] = df[\"incomeHead\"] + df[\"incomeWife\"]\ndf[\"costPerPerson\"] = df[\"totalExpense\"]/df[\"headCount\"]\n\n\n\nmaritalStatus = [\"Married\", \"neverMarried\", \"Widowed\", \"Divorced\", \"Separated\"]\nemploymentStatus = [\"Working\", \"temporalLeave\", \"unemployed\", \"retired\", \"disabled\", \"keepHouse\", \"student\", \"other\"]\nrace = [\"White\", \"Black\",\"AmericanIndian\",\"Asian\",\"Latino\",\"otherBW\",\"otherRace\"]\n# Education\n# < 8th grade: middle school\n# >= 8 and < 12: high scho0l\n# >=12 and < 15: college\n# >= 15 post graduate\neducation = [\"middleSchool\", \"highSchool\", \"college\", \"postGraduate\"]\n# Industry\n# < 400 manufacturing\n# >= 400 and < 500 publicUtility\n# >= 500 and < 680 retail \n# >= 680 and < 720 finance\n# >= 720 and < 900 service\n# >= 900 otherIndustry\nindustry = [\"manufacturing\", \"publicUtility\", \"retail\", \"finance\", \"service\", \"otherIndustry\"]\ndata = []\nfor i in range(len(df)):\n dataCollect = []\n # marital status\n dataCollect.append(maritalStatus[int(df.iloc[i][\"maritalStatus\"]-1)])\n # employment\n dataCollect.append(employmentStatus[int(df.iloc[i][\"employmentStatus\"]-1)])\n # race\n dataCollect.append(race[int(df.iloc[i][\"race\"] - 1)])\n # Education variable \n if df.iloc[i][\"education\"] < 8:\n dataCollect.append(education[0])\n elif df.iloc[i][\"education\"] >= 8 and df.iloc[i][\"education\"] < 12:\n dataCollect.append(education[1])\n elif df.iloc[i][\"education\"] >= 12 and df.iloc[i][\"education\"] < 15:\n dataCollect.append(education[2])\n else:\n dataCollect.append(education[3])\n # industry variable \n if df.iloc[i][\"industry\"] < 400:\n dataCollect.append(industry[0])\n elif df.iloc[i][\"industry\"] >= 400 and df.iloc[i][\"industry\"] < 500:\n dataCollect.append(industry[1])\n elif df.iloc[i][\"industry\"] >= 500 and df.iloc[i][\"industry\"] < 680:\n dataCollect.append(industry[2])\n elif df.iloc[i][\"industry\"] >= 680 and df.iloc[i][\"industry\"] < 720:\n dataCollect.append(industry[3])\n elif df.iloc[i][\"industry\"] >= 720 and df.iloc[i][\"industry\"] < 900:\n dataCollect.append(industry[4])\n else:\n dataCollect.append(industry[5])\n data.append(dataCollect)\n# Categorical dataFrame\ndf_cat = pd.DataFrame(data, columns = [\"maritalStatus\", \"employmentStatus\", \"race\", \"education\", \"industry\"])", "_____no_output_____" ], [ "Fdf = pd.concat([df[[\"familyID\", \"year\",'composition', 'headCount', 'ageHead', 'liquidWealth', 'laborIncome', \n \"costPerPerson\",\"totalExpense\", 'participation', 'investmentAmount', 'annuityIRA', \n 'wealthWithoutHomeEquity', \"wealthWithHomeEquity\"]], \n df_cat[[\"maritalStatus\", \"employmentStatus\", \"education\",\"race\", \"industry\"]]], axis=1)\n# Adjust for inflation. \nyears = [1999, 2001, 2003, 2005, 2007, 2009, 2011, 2013, 2015, 2017]\nvalues_at2020 = np.array([1.55, 1.46, 1.40, 1.32, 1.24, 1.20, 1.15, 1.11, 1.09, 1.05])\nvalues_at2005 = values_at2020/1.32\nvalues_at2005\nquantVariables = ['annuityIRA', 'investmentAmount', 'liquidWealth', 'laborIncome', 'costPerPerson','costPerPerson',\n 'totalExpense', 'wealthWithoutHomeEquity', 'wealthWithHomeEquity']\nfor i in range(len(Fdf)):\n for variable in quantVariables:\n Fdf.at[i, variable] = round(Fdf.at[i, variable] * values_at2005[years.index(Fdf.at[i,\"year\"])], 2)", "_____no_output_____" ] ], [ [ "### Link Family Data with Individual Head Data", "_____no_output_____" ] ], [ [ "completeFamilyData = []\nfor individual in completeIndividualData:\n idf = pd.DataFrame()\n for i in range(len(individual)): \n idf = pd.concat([idf, Fdf[(Fdf.year == individual.iloc[i].year)&\n (Fdf.familyID == individual.iloc[i].familyNumber)]])\n completeFamilyData.append(idf.set_index(\"year\", drop = True))", "_____no_output_____" ], [ "FamilyData = [f for f in completeFamilyData if len(f) == len(years)]\nlen(FamilyData)", "_____no_output_____" ], [ "# skilled definition with college and postGraduate\nskilled_index = []\nfor i in range(1973):\n if \"postGraduate\" in FamilyData[i].education.values or \"college\" in FamilyData[i].education.values:\n skilled_index.append(i)\nlen(skilled_index)", "_____no_output_____" ], [ "# skilled definition with postGraduate\nskilled_index = []\nfor i in range(1973):\n if \"postGraduate\" in FamilyData[i].education.values:\n skilled_index.append(i)\nlen(skilled_index)", "_____no_output_____" ], [ "# working in the finance industry\nfinance_index = []\nfor i in range(1973):\n if \"finance\" in FamilyData[i].industry.values:\n finance_index.append(i)\nlen(finance_index)", "_____no_output_____" ], [ "a = FamilyData[randint(0, 1973)]\na", "_____no_output_____" ] ], [ [ "# Individual plot", "_____no_output_____" ] ], [ [ "def inFeaturePlot(FamilyData, feature, n):\n plt.figure()\n for i in range(n[0],n[1]):\n FamilyData[i][feature].plot(marker='o')\n plt.show()\n\ndef plotFeatureVsAge(FamilyData, feature, n):\n plt.figure()\n for i in range(n[0],n[1]):\n plt.plot(FamilyData[i].ageHead, FamilyData[i][feature], marker = 'o')\n plt.show()", "_____no_output_____" ], [ "inFeaturePlot(FamilyData,\"laborIncome\" , [1,100])", "_____no_output_____" ] ], [ [ "# Average variable plot", "_____no_output_____" ] ], [ [ "def plotFeature(FamilyData, feature):\n df = FamilyData[0][feature] * 0\n for i in range(len(FamilyData)):\n df = df + FamilyData[i][feature]\n df = df/len(FamilyData)\n df.plot(marker='o')\n print(df)", "_____no_output_____" ], [ "# laborIncome\nplotFeature(FamilyData, \"laborIncome\")", "year\n1999 58515.849468\n2001 62096.450076\n2003 61631.421186\n2005 62050.746072\n2007 60616.224024\n2009 61723.606183\n2011 55187.245819\n2013 55558.055246\n2015 51013.996452\n2017 48526.321338\nName: laborIncome, dtype: float64\n" ], [ "# laborIncome\nplotFeature(FamilyData, \"investmentAmount\")", "year\n1999 44860.393310\n2001 62282.585910\n2003 58126.453117\n2005 55852.234668\n2007 62082.949823\n2009 50626.348201\n2011 56326.484034\n2013 72089.909782\n2015 74328.152053\n2017 85350.660922\nName: investmentAmount, dtype: float64\n" ], [ "# Expenditure\nplotFeature(FamilyData, \"totalExpense\")", "year\n1999 32567.763675\n2001 34693.636589\n2003 34174.804709\n2005 40804.406837\n2007 41616.631510\n2009 39253.224445\n2011 38401.690223\n2013 37231.670071\n2015 36753.446087\n2017 35466.241521\nName: totalExpense, dtype: float64\n" ], [ "# wealthWithoutHomeEquity\nplotFeature(FamilyData, \"wealthWithoutHomeEquity\")", "year\n1999 189996.335023\n2001 209022.036493\n2003 215746.606690\n2005 240508.410542\n2007 294690.792701\n2009 265977.239736\n2011 264675.113533\n2013 263506.552458\n2015 319621.413077\n2017 325448.128738\nName: wealthWithoutHomeEquity, dtype: float64\n" ], [ "# wealthWithHomeEquity\nplotFeature(FamilyData, \"wealthWithHomeEquity\")", "year\n1999 249291.759757\n2001 280795.618855\n2003 299767.171313\n2005 348341.237202\n2007 414308.082108\n2009 361313.661936\n2011 357152.367968\n2013 354735.116067\n2015 423869.457172\n2017 440618.187532\nName: wealthWithHomeEquity, dtype: float64\n" ], [ "plotFeature(FamilyData, \"annuityIRA\")", "year\n1999 31462.509377\n2001 34869.478459\n2003 31720.994932\n2005 40220.458186\n2007 50619.510897\n2009 41815.880892\n2011 62674.657881\n2013 65190.544349\n2015 78211.521034\n2017 84070.374050\nName: annuityIRA, dtype: float64\n" ] ], [ [ "## Compare The Distribution Over Age", "_____no_output_____" ] ], [ [ "df = Fdf[(Fdf[\"ageHead\"]>=20) & (Fdf[\"ageHead\"]<=80)]\ndf[['liquidWealth', 'laborIncome', 'costPerPerson', 'totalExpense','investmentAmount', 'annuityIRA',\n 'wealthWithoutHomeEquity', 'wealthWithHomeEquity']] = df[['liquidWealth', 'laborIncome', 'costPerPerson', 'totalExpense','investmentAmount', 'annuityIRA',\n 'wealthWithoutHomeEquity', 'wealthWithHomeEquity']]/1000\ndf.shape", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "ww = df.groupby(\"ageHead\")[\"liquidWealth\"].mean()\nnn = df.groupby(\"ageHead\")[\"annuityIRA\"].mean()\ncc = df.groupby(\"ageHead\")[\"totalExpense\"].mean()\nkk = df.groupby(\"ageHead\")[\"investmentAmount\"].mean()\nytyt = df.groupby(\"ageHead\")[\"laborIncome\"].mean()", "_____no_output_____" ], [ "plt.figure(figsize = [14,8])\nplt.plot(ww, label = \"wealth\")\nplt.plot(cc, label = \"Consumption\")\nplt.plot(kk, label = \"Stock\")\nplt.legend()", "_____no_output_____" ], [ "plt.plot(nn, label = \"IRA\")", "_____no_output_____" ], [ "np.save('nn',nn)", "_____no_output_____" ] ] ]
[ "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", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d01d73a62806e2bbe3b3507f32e3b7de8fa211a0
5,615
ipynb
Jupyter Notebook
Colab Notebooks/competition/valuelabs_ml_hiring_challenge.ipynb
ankschoubey/notes
e8f86e90ceb93282073c1760bedcfbb8ad35a1df
[ "MIT" ]
3
2018-04-17T08:47:07.000Z
2020-02-13T18:39:16.000Z
Colab Notebooks/competition/valuelabs_ml_hiring_challenge.ipynb
ankschoubey/notes
e8f86e90ceb93282073c1760bedcfbb8ad35a1df
[ "MIT" ]
null
null
null
Colab Notebooks/competition/valuelabs_ml_hiring_challenge.ipynb
ankschoubey/notes
e8f86e90ceb93282073c1760bedcfbb8ad35a1df
[ "MIT" ]
null
null
null
5,615
5,615
0.648976
[ [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "_____no_output_____" ], [ "from fastai import *\nfrom fastai.datasets import *\nfrom fastai.text import *\nimport pandas as pd\nfrom tqdm import tqdm", "_____no_output_____" ] ], [ [ "# Data", "_____no_output_____" ] ], [ [ "path = Path('/content/drive/My Drive/Archieve/ValueLabs'); path.ls()", "_____no_output_____" ], [ "train_df = pd.read_csv(path/'Train.csv'); train_df.head()", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "bs = 24", "_____no_output_____" ] ], [ [ "# LM", "_____no_output_____" ] ], [ [ "data_lm = (TextList\n .from_df(train_df,cols=['question', 'answer_text', 'distractor'])\n .split_by_rand_pct(0.1)\n .label_for_lm()\n .databunch(bs=bs)\n )", "_____no_output_____" ], [ "data_lm.save(path/'lm.pkl')", "_____no_output_____" ], [ "data_lm = load_data(path, 'lm.pkl', bs=bs)\ndata_lm.show_batch()", "_____no_output_____" ], [ "learn = language_model_learner(data_lm, AWD_LSTM, drop_mult=0.3)", "_____no_output_____" ], [ "learn.lr_find()", "_____no_output_____" ], [ "learn.recorder.plot(skip_end=10)", "_____no_output_____" ], [ "learn.fit_one_cycle(1, 1e-2, moms=(0.8,0.7))", "_____no_output_____" ], [ "learn.save(path/'fit_head')", "_____no_output_____" ], [ "learn.load(path/'fit_head')", "_____no_output_____" ], [ "#@title Default title text\nvariable_name = \"hello\" #@param {type:\"string\"}", "_____no_output_____" ], [ "learn.fit_one_cycle(10, 1e-3, moms=(0.8,0.7))", "_____no_output_____" ], [ "learn.save(path/'fine_tuned')", "_____no_output_____" ], [ "learn.load(path/'fine_tuned')", "_____no_output_____" ], [ "learn.predict(\"hi what is the problem\",20)", "_____no_output_____" ], [ "test_df = pd.read_csv(path/'Test.csv');test_df.head()", "_____no_output_____" ], [ "combined = test_df['question']+test_df['answer_text']", "_____no_output_____" ], [ "combined.head()\ncombined.shape", "_____no_output_____" ], [ "output = []\nfor index, value in combined.iteritems():\n if index % 100 == 0: print(index)\n output.append(learn.predict(value))", "_____no_output_____" ], [ "import pickle", "_____no_output_____" ], [ "with open(path/'output_list','w') as f:\n pickle.dumps(output, f)", "_____no_output_____" ], [ "output[:5]", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01d810ce7ea79cc82ee3af11c4f2cbea93e89fe
622,772
ipynb
Jupyter Notebook
Notebooks/RadarCOVID-Report/Daily/RadarCOVID-Report-2020-11-07.ipynb
pvieito/Radar-STATS
9ff991a4db776259bc749a823ee6f0b0c0d38108
[ "Apache-2.0" ]
9
2020-10-14T16:58:32.000Z
2021-10-05T12:01:56.000Z
Notebooks/RadarCOVID-Report/Daily/RadarCOVID-Report-2020-11-07.ipynb
pvieito/Radar-STATS
9ff991a4db776259bc749a823ee6f0b0c0d38108
[ "Apache-2.0" ]
3
2020-10-08T04:48:35.000Z
2020-10-10T20:46:58.000Z
Notebooks/RadarCOVID-Report/Daily/RadarCOVID-Report-2020-11-07.ipynb
Radar-STATS/Radar-STATS
61d8b3529f6bbf4576d799e340feec5b183338a3
[ "Apache-2.0" ]
3
2020-09-27T07:39:26.000Z
2020-10-02T07:48:56.000Z
88.161382
167,380
0.750548
[ [ [ "# RadarCOVID-Report", "_____no_output_____" ], [ "## Data Extraction", "_____no_output_____" ] ], [ [ "import datetime\nimport json\nimport logging\nimport os\nimport shutil\nimport tempfile\nimport textwrap\nimport uuid\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker\nimport numpy as np\nimport pandas as pd\nimport retry\nimport seaborn as sns\n\n%matplotlib inline", "_____no_output_____" ], [ "current_working_directory = os.environ.get(\"PWD\")\nif current_working_directory:\n os.chdir(current_working_directory)\n\nsns.set()\nmatplotlib.rcParams[\"figure.figsize\"] = (15, 6)\n\nextraction_datetime = datetime.datetime.utcnow()\nextraction_date = extraction_datetime.strftime(\"%Y-%m-%d\")\nextraction_previous_datetime = extraction_datetime - datetime.timedelta(days=1)\nextraction_previous_date = extraction_previous_datetime.strftime(\"%Y-%m-%d\")\nextraction_date_with_hour = datetime.datetime.utcnow().strftime(\"%Y-%m-%d@%H\")\ncurrent_hour = datetime.datetime.utcnow().hour\nare_today_results_partial = current_hour != 23", "_____no_output_____" ] ], [ [ "### Constants", "_____no_output_____" ] ], [ [ "from Modules.ExposureNotification import exposure_notification_io\n\nspain_region_country_code = \"ES\"\ngermany_region_country_code = \"DE\"\n\ndefault_backend_identifier = spain_region_country_code\n\nbackend_generation_days = 7 * 2\ndaily_summary_days = 7 * 4 * 3\ndaily_plot_days = 7 * 4\ntek_dumps_load_limit = daily_summary_days + 1", "_____no_output_____" ] ], [ [ "### Parameters", "_____no_output_____" ] ], [ [ "environment_backend_identifier = os.environ.get(\"RADARCOVID_REPORT__BACKEND_IDENTIFIER\")\nif environment_backend_identifier:\n report_backend_identifier = environment_backend_identifier\nelse:\n report_backend_identifier = default_backend_identifier\nreport_backend_identifier", "_____no_output_____" ], [ "environment_enable_multi_backend_download = \\\n os.environ.get(\"RADARCOVID_REPORT__ENABLE_MULTI_BACKEND_DOWNLOAD\")\nif environment_enable_multi_backend_download:\n report_backend_identifiers = None\nelse:\n report_backend_identifiers = [report_backend_identifier]\n\nreport_backend_identifiers", "_____no_output_____" ], [ "environment_invalid_shared_diagnoses_dates = \\\n os.environ.get(\"RADARCOVID_REPORT__INVALID_SHARED_DIAGNOSES_DATES\")\nif environment_invalid_shared_diagnoses_dates:\n invalid_shared_diagnoses_dates = environment_invalid_shared_diagnoses_dates.split(\",\")\nelse:\n invalid_shared_diagnoses_dates = []\n\ninvalid_shared_diagnoses_dates", "_____no_output_____" ] ], [ [ "### COVID-19 Cases", "_____no_output_____" ] ], [ [ "report_backend_client = \\\n exposure_notification_io.get_backend_client_with_identifier(\n backend_identifier=report_backend_identifier)", "_____no_output_____" ], [ "@retry.retry(tries=10, delay=10, backoff=1.1, jitter=(0, 10))\ndef download_cases_dataframe_from_ecdc():\n return pd.read_csv(\n \"https://opendata.ecdc.europa.eu/covid19/casedistribution/csv/data.csv\")\n\nconfirmed_df_ = download_cases_dataframe_from_ecdc()", "_____no_output_____" ], [ "confirmed_df = confirmed_df_.copy()\nconfirmed_df = confirmed_df[[\"dateRep\", \"cases\", \"geoId\"]]\nconfirmed_df.rename(\n columns={\n \"dateRep\":\"sample_date\",\n \"cases\": \"new_cases\",\n \"geoId\": \"country_code\",\n },\n inplace=True)\nconfirmed_df[\"sample_date\"] = pd.to_datetime(confirmed_df.sample_date, dayfirst=True)\nconfirmed_df[\"sample_date\"] = confirmed_df.sample_date.dt.strftime(\"%Y-%m-%d\")\nconfirmed_df.sort_values(\"sample_date\", inplace=True)\nconfirmed_df.tail()", "_____no_output_____" ], [ "def sort_source_regions_for_display(source_regions: list) -> list:\n if report_backend_identifier in source_regions:\n source_regions = [report_backend_identifier] + \\\n list(sorted(set(source_regions).difference([report_backend_identifier])))\n else:\n source_regions = list(sorted(source_regions))\n return source_regions", "_____no_output_____" ], [ "confirmed_days = pd.date_range(\n start=confirmed_df.iloc[0].sample_date,\n end=extraction_datetime)\nsource_regions_at_date_df = pd.DataFrame(data=confirmed_days, columns=[\"sample_date\"])\nsource_regions_at_date_df[\"source_regions_at_date\"] = \\\n source_regions_at_date_df.sample_date.apply(\n lambda x: report_backend_client.source_regions_for_date(date=x))\nsource_regions_at_date_df.sort_values(\"sample_date\", inplace=True)\nsource_regions_at_date_df[\"_source_regions_group\"] = source_regions_at_date_df. \\\n source_regions_at_date.apply(lambda x: \",\".join(sort_source_regions_for_display(x)))\nsource_regions_at_date_df[\"sample_date_string\"] = \\\n source_regions_at_date_df.sample_date.dt.strftime(\"%Y-%m-%d\")\nsource_regions_at_date_df.tail()", "_____no_output_____" ], [ "source_regions_for_summary_df = \\\n source_regions_at_date_df[[\"sample_date\", \"_source_regions_group\"]].copy()\nsource_regions_for_summary_df.rename(columns={\"_source_regions_group\": \"source_regions\"}, inplace=True)\nsource_regions_for_summary_df.head()", "_____no_output_____" ], [ "confirmed_output_columns = [\"sample_date\", \"new_cases\", \"covid_cases\"]\nconfirmed_output_df = pd.DataFrame(columns=confirmed_output_columns)\n\nfor source_regions_group, source_regions_group_series in \\\n source_regions_at_date_df.groupby(\"_source_regions_group\"):\n source_regions_set = set(source_regions_group.split(\",\"))\n confirmed_source_regions_set_df = \\\n confirmed_df[confirmed_df.country_code.isin(source_regions_set)].copy()\n confirmed_source_regions_group_df = \\\n confirmed_source_regions_set_df.groupby(\"sample_date\").new_cases.sum() \\\n .reset_index().sort_values(\"sample_date\")\n confirmed_source_regions_group_df[\"covid_cases\"] = \\\n confirmed_source_regions_group_df.new_cases.rolling(7, min_periods=0).mean().round()\n confirmed_source_regions_group_df = \\\n confirmed_source_regions_group_df[confirmed_output_columns]\n confirmed_source_regions_group_df.fillna(method=\"ffill\", inplace=True)\n confirmed_source_regions_group_df = \\\n confirmed_source_regions_group_df[\n confirmed_source_regions_group_df.sample_date.isin(\n source_regions_group_series.sample_date_string)]\n confirmed_output_df = confirmed_output_df.append(confirmed_source_regions_group_df)\n\nconfirmed_df = confirmed_output_df.copy()\nconfirmed_df.tail()", "_____no_output_____" ], [ "confirmed_df.rename(columns={\"sample_date\": \"sample_date_string\"}, inplace=True)\nconfirmed_df.sort_values(\"sample_date_string\", inplace=True)\nconfirmed_df.tail()", "_____no_output_____" ], [ "confirmed_df[[\"new_cases\", \"covid_cases\"]].plot()", "_____no_output_____" ] ], [ [ "### Extract API TEKs", "_____no_output_____" ] ], [ [ "raw_zip_path_prefix = \"Data/TEKs/Raw/\"\nfail_on_error_backend_identifiers = [report_backend_identifier]\nmulti_backend_exposure_keys_df = \\\n exposure_notification_io.download_exposure_keys_from_backends(\n backend_identifiers=report_backend_identifiers,\n generation_days=backend_generation_days,\n fail_on_error_backend_identifiers=fail_on_error_backend_identifiers,\n save_raw_zip_path_prefix=raw_zip_path_prefix)\nmulti_backend_exposure_keys_df[\"region\"] = multi_backend_exposure_keys_df[\"backend_identifier\"]\nmulti_backend_exposure_keys_df.rename(\n columns={\n \"generation_datetime\": \"sample_datetime\",\n \"generation_date_string\": \"sample_date_string\",\n },\n inplace=True)\nmulti_backend_exposure_keys_df.head()", "WARNING:root:NoKeysFoundException(\"No exposure keys found on endpoint 'https://radarcovidpre.covid19.gob.es/dp3t/v1/gaen/exposed/1604707200000' (parameters: {'generation_date': '2020-11-07', 'endpoint_identifier_components': ['2020-11-07'], 'backend_identifier': 'ES@PRE', 'server_endpoint_url': 'https://radarcovidpre.covid19.gob.es/dp3t'}).\")\n" ], [ "early_teks_df = multi_backend_exposure_keys_df[\n multi_backend_exposure_keys_df.rolling_period < 144].copy()\nearly_teks_df[\"rolling_period_in_hours\"] = early_teks_df.rolling_period / 6\nearly_teks_df[early_teks_df.sample_date_string != extraction_date] \\\n .rolling_period_in_hours.hist(bins=list(range(24)))", "_____no_output_____" ], [ "early_teks_df[early_teks_df.sample_date_string == extraction_date] \\\n .rolling_period_in_hours.hist(bins=list(range(24)))", "_____no_output_____" ], [ "multi_backend_exposure_keys_df = multi_backend_exposure_keys_df[[\n \"sample_date_string\", \"region\", \"key_data\"]]\nmulti_backend_exposure_keys_df.head()", "_____no_output_____" ], [ "active_regions = \\\n multi_backend_exposure_keys_df.groupby(\"region\").key_data.nunique().sort_values().index.unique().tolist()\nactive_regions", "_____no_output_____" ], [ "multi_backend_summary_df = multi_backend_exposure_keys_df.groupby(\n [\"sample_date_string\", \"region\"]).key_data.nunique().reset_index() \\\n .pivot(index=\"sample_date_string\", columns=\"region\") \\\n .sort_index(ascending=False)\nmulti_backend_summary_df.rename(\n columns={\"key_data\": \"shared_teks_by_generation_date\"},\n inplace=True)\nmulti_backend_summary_df.rename_axis(\"sample_date\", inplace=True)\nmulti_backend_summary_df = multi_backend_summary_df.fillna(0).astype(int)\nmulti_backend_summary_df = multi_backend_summary_df.head(backend_generation_days)\nmulti_backend_summary_df.head()", "_____no_output_____" ], [ "def compute_keys_cross_sharing(x):\n teks_x = x.key_data_x.item()\n common_teks = set(teks_x).intersection(x.key_data_y.item())\n common_teks_fraction = len(common_teks) / len(teks_x)\n return pd.Series(dict(\n common_teks=common_teks,\n common_teks_fraction=common_teks_fraction,\n ))\n\nmulti_backend_exposure_keys_by_region_df = \\\n multi_backend_exposure_keys_df.groupby(\"region\").key_data.unique().reset_index()\nmulti_backend_exposure_keys_by_region_df[\"_merge\"] = True\nmulti_backend_exposure_keys_by_region_combination_df = \\\n multi_backend_exposure_keys_by_region_df.merge(\n multi_backend_exposure_keys_by_region_df, on=\"_merge\")\nmulti_backend_exposure_keys_by_region_combination_df.drop(\n columns=[\"_merge\"], inplace=True)\nif multi_backend_exposure_keys_by_region_combination_df.region_x.nunique() > 1:\n multi_backend_exposure_keys_by_region_combination_df = \\\n multi_backend_exposure_keys_by_region_combination_df[\n multi_backend_exposure_keys_by_region_combination_df.region_x !=\n multi_backend_exposure_keys_by_region_combination_df.region_y]\nmulti_backend_exposure_keys_cross_sharing_df = \\\n multi_backend_exposure_keys_by_region_combination_df \\\n .groupby([\"region_x\", \"region_y\"]) \\\n .apply(compute_keys_cross_sharing) \\\n .reset_index()\nmulti_backend_cross_sharing_summary_df = \\\n multi_backend_exposure_keys_cross_sharing_df.pivot_table(\n values=[\"common_teks_fraction\"],\n columns=\"region_x\",\n index=\"region_y\",\n aggfunc=lambda x: x.item())\nmulti_backend_cross_sharing_summary_df", "<ipython-input-22-4e21708c19d8>:2: FutureWarning: `item` has been deprecated and will be removed in a future version\n teks_x = x.key_data_x.item()\n<ipython-input-22-4e21708c19d8>:3: FutureWarning: `item` has been deprecated and will be removed in a future version\n common_teks = set(teks_x).intersection(x.key_data_y.item())\n" ], [ "multi_backend_without_active_region_exposure_keys_df = \\\n multi_backend_exposure_keys_df[multi_backend_exposure_keys_df.region != report_backend_identifier]\nmulti_backend_without_active_region = \\\n multi_backend_without_active_region_exposure_keys_df.groupby(\"region\").key_data.nunique().sort_values().index.unique().tolist()\nmulti_backend_without_active_region", "_____no_output_____" ], [ "exposure_keys_summary_df = multi_backend_exposure_keys_df[\n multi_backend_exposure_keys_df.region == report_backend_identifier]\nexposure_keys_summary_df.drop(columns=[\"region\"], inplace=True)\nexposure_keys_summary_df = \\\n exposure_keys_summary_df.groupby([\"sample_date_string\"]).key_data.nunique().to_frame()\nexposure_keys_summary_df = \\\n exposure_keys_summary_df.reset_index().set_index(\"sample_date_string\")\nexposure_keys_summary_df.sort_index(ascending=False, inplace=True)\nexposure_keys_summary_df.rename(columns={\"key_data\": \"shared_teks_by_generation_date\"}, inplace=True)\nexposure_keys_summary_df.head()", "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/pandas/core/frame.py:4110: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return super().drop(\n" ] ], [ [ "### Dump API TEKs", "_____no_output_____" ] ], [ [ "tek_list_df = multi_backend_exposure_keys_df[\n [\"sample_date_string\", \"region\", \"key_data\"]].copy()\ntek_list_df[\"key_data\"] = tek_list_df[\"key_data\"].apply(str)\ntek_list_df.rename(columns={\n \"sample_date_string\": \"sample_date\",\n \"key_data\": \"tek_list\"}, inplace=True)\ntek_list_df = tek_list_df.groupby(\n [\"sample_date\", \"region\"]).tek_list.unique().reset_index()\ntek_list_df[\"extraction_date\"] = extraction_date\ntek_list_df[\"extraction_date_with_hour\"] = extraction_date_with_hour\n\ntek_list_path_prefix = \"Data/TEKs/\"\ntek_list_current_path = tek_list_path_prefix + f\"/Current/RadarCOVID-TEKs.json\"\ntek_list_daily_path = tek_list_path_prefix + f\"Daily/RadarCOVID-TEKs-{extraction_date}.json\"\ntek_list_hourly_path = tek_list_path_prefix + f\"Hourly/RadarCOVID-TEKs-{extraction_date_with_hour}.json\"\n\nfor path in [tek_list_current_path, tek_list_daily_path, tek_list_hourly_path]:\n os.makedirs(os.path.dirname(path), exist_ok=True)\n\ntek_list_df.drop(columns=[\"extraction_date\", \"extraction_date_with_hour\"]).to_json(\n tek_list_current_path,\n lines=True, orient=\"records\")\ntek_list_df.drop(columns=[\"extraction_date_with_hour\"]).to_json(\n tek_list_daily_path,\n lines=True, orient=\"records\")\ntek_list_df.to_json(\n tek_list_hourly_path,\n lines=True, orient=\"records\")\ntek_list_df.head()", "_____no_output_____" ] ], [ [ "### Load TEK Dumps", "_____no_output_____" ] ], [ [ "import glob\n\ndef load_extracted_teks(mode, region=None, limit=None) -> pd.DataFrame:\n extracted_teks_df = pd.DataFrame(columns=[\"region\"])\n file_paths = list(reversed(sorted(glob.glob(tek_list_path_prefix + mode + \"/RadarCOVID-TEKs-*.json\"))))\n if limit:\n file_paths = file_paths[:limit]\n for file_path in file_paths:\n logging.info(f\"Loading TEKs from '{file_path}'...\")\n iteration_extracted_teks_df = pd.read_json(file_path, lines=True)\n extracted_teks_df = extracted_teks_df.append(\n iteration_extracted_teks_df, sort=False)\n extracted_teks_df[\"region\"] = \\\n extracted_teks_df.region.fillna(spain_region_country_code).copy()\n if region:\n extracted_teks_df = \\\n extracted_teks_df[extracted_teks_df.region == region]\n return extracted_teks_df", "_____no_output_____" ], [ "daily_extracted_teks_df = load_extracted_teks(\n mode=\"Daily\",\n region=report_backend_identifier,\n limit=tek_dumps_load_limit)\ndaily_extracted_teks_df.head()", "_____no_output_____" ], [ "exposure_keys_summary_df_ = daily_extracted_teks_df \\\n .sort_values(\"extraction_date\", ascending=False) \\\n .groupby(\"sample_date\").tek_list.first() \\\n .to_frame()\nexposure_keys_summary_df_.index.name = \"sample_date_string\"\nexposure_keys_summary_df_[\"tek_list\"] = \\\n exposure_keys_summary_df_.tek_list.apply(len)\nexposure_keys_summary_df_ = exposure_keys_summary_df_ \\\n .rename(columns={\"tek_list\": \"shared_teks_by_generation_date\"}) \\\n .sort_index(ascending=False)\nexposure_keys_summary_df = exposure_keys_summary_df_\nexposure_keys_summary_df.head()", "_____no_output_____" ] ], [ [ "### Daily New TEKs", "_____no_output_____" ] ], [ [ "tek_list_df = daily_extracted_teks_df.groupby(\"extraction_date\").tek_list.apply(\n lambda x: set(sum(x, []))).reset_index()\ntek_list_df = tek_list_df.set_index(\"extraction_date\").sort_index(ascending=True)\ntek_list_df.head()", "_____no_output_____" ], [ "def compute_teks_by_generation_and_upload_date(date):\n day_new_teks_set_df = tek_list_df.copy().diff()\n try:\n day_new_teks_set = day_new_teks_set_df[\n day_new_teks_set_df.index == date].tek_list.item()\n except ValueError:\n day_new_teks_set = None\n if pd.isna(day_new_teks_set):\n day_new_teks_set = set()\n day_new_teks_df = daily_extracted_teks_df[\n daily_extracted_teks_df.extraction_date == date].copy()\n day_new_teks_df[\"shared_teks\"] = \\\n day_new_teks_df.tek_list.apply(lambda x: set(x).intersection(day_new_teks_set))\n day_new_teks_df[\"shared_teks\"] = \\\n day_new_teks_df.shared_teks.apply(len)\n day_new_teks_df[\"upload_date\"] = date\n day_new_teks_df.rename(columns={\"sample_date\": \"generation_date\"}, inplace=True)\n day_new_teks_df = day_new_teks_df[\n [\"upload_date\", \"generation_date\", \"shared_teks\"]]\n day_new_teks_df[\"generation_to_upload_days\"] = \\\n (pd.to_datetime(day_new_teks_df.upload_date) -\n pd.to_datetime(day_new_teks_df.generation_date)).dt.days\n day_new_teks_df = day_new_teks_df[day_new_teks_df.shared_teks > 0]\n return day_new_teks_df\n\nshared_teks_generation_to_upload_df = pd.DataFrame()\nfor upload_date in daily_extracted_teks_df.extraction_date.unique():\n shared_teks_generation_to_upload_df = \\\n shared_teks_generation_to_upload_df.append(\n compute_teks_by_generation_and_upload_date(date=upload_date))\nshared_teks_generation_to_upload_df \\\n .sort_values([\"upload_date\", \"generation_date\"], ascending=False, inplace=True)\nshared_teks_generation_to_upload_df.tail()", "<ipython-input-30-827222b35590>:4: FutureWarning: `item` has been deprecated and will be removed in a future version\n day_new_teks_set = day_new_teks_set_df[\n" ], [ "today_new_teks_df = \\\n shared_teks_generation_to_upload_df[\n shared_teks_generation_to_upload_df.upload_date == extraction_date].copy()\ntoday_new_teks_df.tail()", "_____no_output_____" ], [ "if not today_new_teks_df.empty:\n today_new_teks_df.set_index(\"generation_to_upload_days\") \\\n .sort_index().shared_teks.plot.bar()", "_____no_output_____" ], [ "generation_to_upload_period_pivot_df = \\\n shared_teks_generation_to_upload_df[\n [\"upload_date\", \"generation_to_upload_days\", \"shared_teks\"]] \\\n .pivot(index=\"upload_date\", columns=\"generation_to_upload_days\") \\\n .sort_index(ascending=False).fillna(0).astype(int) \\\n .droplevel(level=0, axis=1)\ngeneration_to_upload_period_pivot_df.head()", "_____no_output_____" ], [ "new_tek_df = tek_list_df.diff().tek_list.apply(\n lambda x: len(x) if not pd.isna(x) else None).to_frame().reset_index()\nnew_tek_df.rename(columns={\n \"tek_list\": \"shared_teks_by_upload_date\",\n \"extraction_date\": \"sample_date_string\",}, inplace=True)\nnew_tek_df.tail()", "_____no_output_____" ], [ "shared_teks_uploaded_on_generation_date_df = shared_teks_generation_to_upload_df[\n shared_teks_generation_to_upload_df.generation_to_upload_days == 0] \\\n [[\"upload_date\", \"shared_teks\"]].rename(\n columns={\n \"upload_date\": \"sample_date_string\",\n \"shared_teks\": \"shared_teks_uploaded_on_generation_date\",\n })\nshared_teks_uploaded_on_generation_date_df.head()", "_____no_output_____" ], [ "estimated_shared_diagnoses_df = shared_teks_generation_to_upload_df \\\n .groupby([\"upload_date\"]).shared_teks.max().reset_index() \\\n .sort_values([\"upload_date\"], ascending=False) \\\n .rename(columns={\n \"upload_date\": \"sample_date_string\",\n \"shared_teks\": \"shared_diagnoses\",\n })\ninvalid_shared_diagnoses_dates_mask = \\\n estimated_shared_diagnoses_df.sample_date_string.isin(invalid_shared_diagnoses_dates)\nestimated_shared_diagnoses_df[invalid_shared_diagnoses_dates_mask] = 0\nestimated_shared_diagnoses_df.head()", "_____no_output_____" ] ], [ [ "### Hourly New TEKs", "_____no_output_____" ] ], [ [ "hourly_extracted_teks_df = load_extracted_teks(\n mode=\"Hourly\", region=report_backend_identifier, limit=25)\nhourly_extracted_teks_df.head()", "_____no_output_____" ], [ "hourly_new_tek_count_df = hourly_extracted_teks_df \\\n .groupby(\"extraction_date_with_hour\").tek_list. \\\n apply(lambda x: set(sum(x, []))).reset_index().copy()\nhourly_new_tek_count_df = hourly_new_tek_count_df.set_index(\"extraction_date_with_hour\") \\\n .sort_index(ascending=True)\n\nhourly_new_tek_count_df[\"new_tek_list\"] = hourly_new_tek_count_df.tek_list.diff()\nhourly_new_tek_count_df[\"new_tek_count\"] = hourly_new_tek_count_df.new_tek_list.apply(\n lambda x: len(x) if not pd.isna(x) else 0)\nhourly_new_tek_count_df.rename(columns={\n \"new_tek_count\": \"shared_teks_by_upload_date\"}, inplace=True)\nhourly_new_tek_count_df = hourly_new_tek_count_df.reset_index()[[\n \"extraction_date_with_hour\", \"shared_teks_by_upload_date\"]]\nhourly_new_tek_count_df.head()", "_____no_output_____" ], [ "hourly_summary_df = hourly_new_tek_count_df.copy()\nhourly_summary_df.set_index(\"extraction_date_with_hour\", inplace=True)\nhourly_summary_df = hourly_summary_df.fillna(0).astype(int).reset_index()\nhourly_summary_df[\"datetime_utc\"] = pd.to_datetime(\n hourly_summary_df.extraction_date_with_hour, format=\"%Y-%m-%d@%H\")\nhourly_summary_df.set_index(\"datetime_utc\", inplace=True)\nhourly_summary_df = hourly_summary_df.tail(-1)\nhourly_summary_df.head()", "_____no_output_____" ] ], [ [ "### Data Merge", "_____no_output_____" ] ], [ [ "result_summary_df = exposure_keys_summary_df.merge(\n new_tek_df, on=[\"sample_date_string\"], how=\"outer\")\nresult_summary_df.head()", "_____no_output_____" ], [ "result_summary_df = result_summary_df.merge(\n shared_teks_uploaded_on_generation_date_df, on=[\"sample_date_string\"], how=\"outer\")\nresult_summary_df.head()", "_____no_output_____" ], [ "result_summary_df = result_summary_df.merge(\n estimated_shared_diagnoses_df, on=[\"sample_date_string\"], how=\"outer\")\nresult_summary_df.head()", "_____no_output_____" ], [ "result_summary_df = confirmed_df.tail(daily_summary_days).merge(\n result_summary_df, on=[\"sample_date_string\"], how=\"left\")\nresult_summary_df.head()", "_____no_output_____" ], [ "result_summary_df[\"sample_date\"] = pd.to_datetime(result_summary_df.sample_date_string)\nresult_summary_df = result_summary_df.merge(source_regions_for_summary_df, how=\"left\")\nresult_summary_df.set_index([\"sample_date\", \"source_regions\"], inplace=True)\nresult_summary_df.drop(columns=[\"sample_date_string\"], inplace=True)\nresult_summary_df.sort_index(ascending=False, inplace=True)\nresult_summary_df.head()", "_____no_output_____" ], [ "with pd.option_context(\"mode.use_inf_as_na\", True):\n result_summary_df = result_summary_df.fillna(0).astype(int)\n result_summary_df[\"teks_per_shared_diagnosis\"] = \\\n (result_summary_df.shared_teks_by_upload_date / result_summary_df.shared_diagnoses).fillna(0)\n result_summary_df[\"shared_diagnoses_per_covid_case\"] = \\\n (result_summary_df.shared_diagnoses / result_summary_df.covid_cases).fillna(0)\n\nresult_summary_df.head(daily_plot_days)", "_____no_output_____" ], [ "weekly_result_summary_df = result_summary_df \\\n .sort_index(ascending=True).fillna(0).rolling(7).agg({\n \"covid_cases\": \"sum\",\n \"shared_teks_by_generation_date\": \"sum\",\n \"shared_teks_by_upload_date\": \"sum\",\n \"shared_diagnoses\": \"sum\"\n}).sort_index(ascending=False)\n\nwith pd.option_context(\"mode.use_inf_as_na\", True):\n weekly_result_summary_df = weekly_result_summary_df.fillna(0).astype(int)\n weekly_result_summary_df[\"teks_per_shared_diagnosis\"] = \\\n (weekly_result_summary_df.shared_teks_by_upload_date / weekly_result_summary_df.shared_diagnoses).fillna(0)\n weekly_result_summary_df[\"shared_diagnoses_per_covid_case\"] = \\\n (weekly_result_summary_df.shared_diagnoses / weekly_result_summary_df.covid_cases).fillna(0)\n\nweekly_result_summary_df.head()", "_____no_output_____" ], [ "last_7_days_summary = weekly_result_summary_df.to_dict(orient=\"records\")[1]\nlast_7_days_summary", "_____no_output_____" ] ], [ [ "## Report Results", "_____no_output_____" ] ], [ [ "display_column_name_mapping = {\n \"sample_date\": \"Sample\\u00A0Date\\u00A0(UTC)\",\n \"source_regions\": \"Source Countries\",\n \"datetime_utc\": \"Timestamp (UTC)\",\n \"upload_date\": \"Upload Date (UTC)\",\n \"generation_to_upload_days\": \"Generation to Upload Period in Days\",\n \"region\": \"Backend\",\n \"region_x\": \"Backend\\u00A0(A)\",\n \"region_y\": \"Backend\\u00A0(B)\",\n \"common_teks\": \"Common TEKs Shared Between Backends\",\n \"common_teks_fraction\": \"Fraction of TEKs in Backend (A) Available in Backend (B)\",\n \"covid_cases\": \"COVID-19 Cases in Source Countries (7-day Rolling Average)\",\n \"shared_teks_by_generation_date\": \"Shared TEKs by Generation Date\",\n \"shared_teks_by_upload_date\": \"Shared TEKs by Upload Date\",\n \"shared_diagnoses\": \"Shared Diagnoses (Estimation)\",\n \"teks_per_shared_diagnosis\": \"TEKs Uploaded per Shared Diagnosis\",\n \"shared_diagnoses_per_covid_case\": \"Usage Ratio (Fraction of Cases in Source Countries Which Shared Diagnosis)\",\n \"shared_teks_uploaded_on_generation_date\": \"Shared TEKs Uploaded on Generation Date\",\n}", "_____no_output_____" ], [ "summary_columns = [\n \"covid_cases\",\n \"shared_teks_by_generation_date\",\n \"shared_teks_by_upload_date\",\n \"shared_teks_uploaded_on_generation_date\",\n \"shared_diagnoses\",\n \"teks_per_shared_diagnosis\",\n \"shared_diagnoses_per_covid_case\",\n]", "_____no_output_____" ] ], [ [ "### Daily Summary Table", "_____no_output_____" ] ], [ [ "result_summary_df_ = result_summary_df.copy()\nresult_summary_df = result_summary_df[summary_columns]\nresult_summary_with_display_names_df = result_summary_df \\\n .rename_axis(index=display_column_name_mapping) \\\n .rename(columns=display_column_name_mapping)\nresult_summary_with_display_names_df", "_____no_output_____" ] ], [ [ "### Daily Summary Plots", "_____no_output_____" ] ], [ [ "result_plot_summary_df = result_summary_df.head(daily_plot_days)[summary_columns] \\\n .droplevel(level=[\"source_regions\"]) \\\n .rename_axis(index=display_column_name_mapping) \\\n .rename(columns=display_column_name_mapping)\nsummary_ax_list = result_plot_summary_df.sort_index(ascending=True).plot.bar(\n title=f\"Daily Summary\",\n rot=45, subplots=True, figsize=(15, 22), legend=False)\nax_ = summary_ax_list[-1]\nax_.get_figure().tight_layout()\nax_.get_figure().subplots_adjust(top=0.95)\nax_.yaxis.set_major_formatter(matplotlib.ticker.PercentFormatter(1.0))\n_ = ax_.set_xticklabels(sorted(result_plot_summary_df.index.strftime(\"%Y-%m-%d\").tolist()))", "_____no_output_____" ] ], [ [ "### Daily Generation to Upload Period Table", "_____no_output_____" ] ], [ [ "display_generation_to_upload_period_pivot_df = \\\n generation_to_upload_period_pivot_df \\\n .head(backend_generation_days)\ndisplay_generation_to_upload_period_pivot_df \\\n .head(backend_generation_days) \\\n .rename_axis(columns=display_column_name_mapping) \\\n .rename_axis(index=display_column_name_mapping)", "_____no_output_____" ], [ "fig, generation_to_upload_period_pivot_table_ax = plt.subplots(\n figsize=(12, 1 + 0.6 * len(display_generation_to_upload_period_pivot_df)))\ngeneration_to_upload_period_pivot_table_ax.set_title(\n \"Shared TEKs Generation to Upload Period Table\")\nsns.heatmap(\n data=display_generation_to_upload_period_pivot_df\n .rename_axis(columns=display_column_name_mapping)\n .rename_axis(index=display_column_name_mapping),\n fmt=\".0f\",\n annot=True,\n ax=generation_to_upload_period_pivot_table_ax)\ngeneration_to_upload_period_pivot_table_ax.get_figure().tight_layout()", "_____no_output_____" ] ], [ [ "### Hourly Summary Plots ", "_____no_output_____" ] ], [ [ "hourly_summary_ax_list = hourly_summary_df \\\n .rename_axis(index=display_column_name_mapping) \\\n .rename(columns=display_column_name_mapping) \\\n .plot.bar(\n title=f\"Last 24h Summary\",\n rot=45, subplots=True, legend=False)\nax_ = hourly_summary_ax_list[-1]\nax_.get_figure().tight_layout()\nax_.get_figure().subplots_adjust(top=0.9)\n_ = ax_.set_xticklabels(sorted(hourly_summary_df.index.strftime(\"%Y-%m-%d@%H\").tolist()))", "_____no_output_____" ] ], [ [ "### Publish Results", "_____no_output_____" ] ], [ [ "def get_temporary_image_path() -> str:\n return os.path.join(tempfile.gettempdir(), str(uuid.uuid4()) + \".png\")\n\ndef save_temporary_plot_image(ax):\n if isinstance(ax, np.ndarray):\n ax = ax[0]\n media_path = get_temporary_image_path()\n ax.get_figure().savefig(media_path)\n return media_path\n\ndef save_temporary_dataframe_image(df):\n import dataframe_image as dfi\n media_path = get_temporary_image_path()\n dfi.export(df, media_path)\n return media_path", "_____no_output_____" ], [ "github_repository = os.environ.get(\"GITHUB_REPOSITORY\")\nif github_repository is None:\n github_repository = \"pvieito/Radar-STATS\"\n\ngithub_project_base_url = \"https://github.com/\" + github_repository\n\ndisplay_formatters = {\n display_column_name_mapping[\"teks_per_shared_diagnosis\"]: lambda x: f\"{x:.2f}\",\n display_column_name_mapping[\"shared_diagnoses_per_covid_case\"]: lambda x: f\"{x:.2%}\",\n}\ndaily_summary_table_html = result_summary_with_display_names_df \\\n .head(daily_plot_days) \\\n .rename_axis(index=display_column_name_mapping) \\\n .rename(columns=display_column_name_mapping) \\\n .to_html(formatters=display_formatters)\nmulti_backend_summary_table_html = multi_backend_summary_df \\\n .head(daily_plot_days) \\\n .rename_axis(columns=display_column_name_mapping) \\\n .rename(columns=display_column_name_mapping) \\\n .rename_axis(index=display_column_name_mapping) \\\n .to_html(formatters=display_formatters)\n\ndef format_multi_backend_cross_sharing_fraction(x):\n if pd.isna(x):\n return \"-\"\n elif round(x * 100, 1) == 0:\n return \"\"\n else:\n return f\"{x:.1%}\"\n\nmulti_backend_cross_sharing_summary_table_html = multi_backend_cross_sharing_summary_df \\\n .rename_axis(columns=display_column_name_mapping) \\\n .rename(columns=display_column_name_mapping) \\\n .rename_axis(index=display_column_name_mapping) \\\n .to_html(\n classes=\"table-center\",\n formatters=display_formatters,\n float_format=format_multi_backend_cross_sharing_fraction)\nmulti_backend_cross_sharing_summary_table_html = \\\n multi_backend_cross_sharing_summary_table_html \\\n .replace(\"<tr>\",\"<tr style=\\\"text-align: center;\\\">\")\n\nextraction_date_result_summary_df = \\\n result_summary_df[result_summary_df.index.get_level_values(\"sample_date\") == extraction_date]\nextraction_date_result_hourly_summary_df = \\\n hourly_summary_df[hourly_summary_df.extraction_date_with_hour == extraction_date_with_hour]\n\ncovid_cases = \\\n extraction_date_result_summary_df.covid_cases.sum()\nshared_teks_by_generation_date = \\\n extraction_date_result_summary_df.shared_teks_by_generation_date.sum()\nshared_teks_by_upload_date = \\\n extraction_date_result_summary_df.shared_teks_by_upload_date.sum()\nshared_diagnoses = \\\n extraction_date_result_summary_df.shared_diagnoses.sum()\nteks_per_shared_diagnosis = \\\n extraction_date_result_summary_df.teks_per_shared_diagnosis.sum()\nshared_diagnoses_per_covid_case = \\\n extraction_date_result_summary_df.shared_diagnoses_per_covid_case.sum()\n\nshared_teks_by_upload_date_last_hour = \\\n extraction_date_result_hourly_summary_df.shared_teks_by_upload_date.sum().astype(int)\n\nreport_source_regions = extraction_date_result_summary_df.index \\\n .get_level_values(\"source_regions\").item().split(\",\")\n\ndisplay_source_regions = \", \".join(report_source_regions)\nif len(report_source_regions) == 1:\n display_brief_source_regions = report_source_regions[0]\nelse:\n display_brief_source_regions = f\"{len(report_source_regions)} 🇪🇺\"", "<ipython-input-56-300f594104ba>:64: FutureWarning: `item` has been deprecated and will be removed in a future version\n report_source_regions = extraction_date_result_summary_df.index \\\n" ], [ "summary_plots_image_path = save_temporary_plot_image(\n ax=summary_ax_list)\nsummary_table_image_path = save_temporary_dataframe_image(\n df=result_summary_with_display_names_df)\nhourly_summary_plots_image_path = save_temporary_plot_image(\n ax=hourly_summary_ax_list)\nmulti_backend_summary_table_image_path = save_temporary_dataframe_image(\n df=multi_backend_summary_df)\ngeneration_to_upload_period_pivot_table_image_path = save_temporary_plot_image(\n ax=generation_to_upload_period_pivot_table_ax)", "_____no_output_____" ] ], [ [ "### Save Results", "_____no_output_____" ] ], [ [ "report_resources_path_prefix = \"Data/Resources/Current/RadarCOVID-Report-\"\nresult_summary_df.to_csv(\n report_resources_path_prefix + \"Summary-Table.csv\")\nresult_summary_df.to_html(\n report_resources_path_prefix + \"Summary-Table.html\")\nhourly_summary_df.to_csv(\n report_resources_path_prefix + \"Hourly-Summary-Table.csv\")\nmulti_backend_summary_df.to_csv(\n report_resources_path_prefix + \"Multi-Backend-Summary-Table.csv\")\nmulti_backend_cross_sharing_summary_df.to_csv(\n report_resources_path_prefix + \"Multi-Backend-Cross-Sharing-Summary-Table.csv\")\ngeneration_to_upload_period_pivot_df.to_csv(\n report_resources_path_prefix + \"Generation-Upload-Period-Table.csv\")\n_ = shutil.copyfile(\n summary_plots_image_path,\n report_resources_path_prefix + \"Summary-Plots.png\")\n_ = shutil.copyfile(\n summary_table_image_path,\n report_resources_path_prefix + \"Summary-Table.png\")\n_ = shutil.copyfile(\n hourly_summary_plots_image_path,\n report_resources_path_prefix + \"Hourly-Summary-Plots.png\")\n_ = shutil.copyfile(\n multi_backend_summary_table_image_path,\n report_resources_path_prefix + \"Multi-Backend-Summary-Table.png\")\n_ = shutil.copyfile(\n generation_to_upload_period_pivot_table_image_path,\n report_resources_path_prefix + \"Generation-Upload-Period-Table.png\")", "_____no_output_____" ] ], [ [ "### Publish Results as JSON", "_____no_output_____" ] ], [ [ "summary_results_api_df = result_summary_df.reset_index()\nsummary_results_api_df[\"sample_date_string\"] = \\\n summary_results_api_df[\"sample_date\"].dt.strftime(\"%Y-%m-%d\")\nsummary_results_api_df[\"source_regions\"] = \\\n summary_results_api_df[\"source_regions\"].apply(lambda x: x.split(\",\"))\n\ntoday_summary_results_api_df = \\\n summary_results_api_df.to_dict(orient=\"records\")[0]\n\nsummary_results = dict(\n backend_identifier=report_backend_identifier,\n source_regions=report_source_regions,\n extraction_datetime=extraction_datetime,\n extraction_date=extraction_date,\n extraction_date_with_hour=extraction_date_with_hour,\n last_hour=dict(\n shared_teks_by_upload_date=shared_teks_by_upload_date_last_hour,\n shared_diagnoses=0,\n ),\n today=today_summary_results_api_df,\n last_7_days=last_7_days_summary,\n daily_results=summary_results_api_df.to_dict(orient=\"records\"))\nsummary_results = \\\n json.loads(pd.Series([summary_results]).to_json(orient=\"records\"))[0]\n\nwith open(report_resources_path_prefix + \"Summary-Results.json\", \"w\") as f:\n json.dump(summary_results, f, indent=4)", "_____no_output_____" ] ], [ [ "### Publish on README", "_____no_output_____" ] ], [ [ "with open(\"Data/Templates/README.md\", \"r\") as f:\n readme_contents = f.read()\n\nreadme_contents = readme_contents.format(\n extraction_date_with_hour=extraction_date_with_hour,\n github_project_base_url=github_project_base_url,\n daily_summary_table_html=daily_summary_table_html,\n multi_backend_summary_table_html=multi_backend_summary_table_html,\n multi_backend_cross_sharing_summary_table_html=multi_backend_cross_sharing_summary_table_html,\n display_source_regions=display_source_regions)\n\nwith open(\"README.md\", \"w\") as f:\n f.write(readme_contents)", "_____no_output_____" ] ], [ [ "### Publish on Twitter", "_____no_output_____" ] ], [ [ "enable_share_to_twitter = os.environ.get(\"RADARCOVID_REPORT__ENABLE_PUBLISH_ON_TWITTER\")\ngithub_event_name = os.environ.get(\"GITHUB_EVENT_NAME\")\n\nif enable_share_to_twitter and github_event_name == \"schedule\" and \\\n (shared_teks_by_upload_date_last_hour or not are_today_results_partial):\n import tweepy\n\n twitter_api_auth_keys = os.environ[\"RADARCOVID_REPORT__TWITTER_API_AUTH_KEYS\"]\n twitter_api_auth_keys = twitter_api_auth_keys.split(\":\")\n auth = tweepy.OAuthHandler(twitter_api_auth_keys[0], twitter_api_auth_keys[1])\n auth.set_access_token(twitter_api_auth_keys[2], twitter_api_auth_keys[3])\n\n api = tweepy.API(auth)\n\n summary_plots_media = api.media_upload(summary_plots_image_path)\n summary_table_media = api.media_upload(summary_table_image_path)\n generation_to_upload_period_pivot_table_image_media = api.media_upload(generation_to_upload_period_pivot_table_image_path)\n media_ids = [\n summary_plots_media.media_id,\n summary_table_media.media_id,\n generation_to_upload_period_pivot_table_image_media.media_id,\n ]\n\n if are_today_results_partial:\n today_addendum = \" (Partial)\"\n else:\n today_addendum = \"\"\n\n status = textwrap.dedent(f\"\"\"\n #RadarCOVID – {extraction_date_with_hour}\n\n Source Countries: {display_brief_source_regions}\n\n Today{today_addendum}:\n - Uploaded TEKs: {shared_teks_by_upload_date:.0f} ({shared_teks_by_upload_date_last_hour:+d} last hour)\n - Shared Diagnoses: ≤{shared_diagnoses:.0f}\n - Usage Ratio: ≤{shared_diagnoses_per_covid_case:.2%}\n\n Last 7 Days:\n - Shared Diagnoses: ≤{last_7_days_summary[\"shared_diagnoses\"]:.0f}\n - Usage Ratio: ≤{last_7_days_summary[\"shared_diagnoses_per_covid_case\"]:.2%}\n\n Info: {github_project_base_url}#documentation\n \"\"\")\n status = status.encode(encoding=\"utf-8\")\n api.update_status(status=status, media_ids=media_ids)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01d9263b00a168712a3e8e33cb4609a3d2f239f
4,683
ipynb
Jupyter Notebook
notebooks/custom-conversions.ipynb
openscm/openscm-units
fcada9ec83e155e4b80f120d2294053a42f1e8e7
[ "BSD-3-Clause" ]
4
2020-10-30T10:50:29.000Z
2021-11-03T22:14:27.000Z
docs/source/notebooks/custom-conversions.ipynb
openscm-project/openscm-units
f97fac6c1ac00dd507e23d55949d8d45b07bf9a8
[ "BSD-3-Clause" ]
33
2020-03-26T05:36:55.000Z
2022-02-08T09:28:25.000Z
docs/source/notebooks/custom-conversions.ipynb
openscm-project/openscm-units
f97fac6c1ac00dd507e23d55949d8d45b07bf9a8
[ "BSD-3-Clause" ]
4
2020-11-04T10:07:25.000Z
2021-08-04T07:54:37.000Z
24.777778
266
0.465941
[ [ [ "# Custom conversions\n\nHere we show how custom conversions can be passed to OpenSCM-Units' `ScmUnitRegistry`.", "_____no_output_____" ] ], [ [ "# NBVAL_IGNORE_OUTPUT\nimport traceback\n\nimport pandas as pd\n\nfrom openscm_units import ScmUnitRegistry", "_____no_output_____" ] ], [ [ "## Custom conversions DataFrame\n\nOn initialisation, a `pd.DataFrame` can be provided which contains the custom conversions. This `pd.DataFrame` should be formatted as shown below, with an index that contains the different species and columns which contain the conversion for different metrics.", "_____no_output_____" ] ], [ [ "metric_conversions_custom = pd.DataFrame([\n {\n \"Species\": \"CH4\",\n \"Custom1\": 20,\n \"Custom2\": 25,\n },\n {\n \"Species\": \"N2O\",\n \"Custom1\": 341,\n \"Custom2\": 300,\n },\n]).set_index(\"Species\")\nmetric_conversions_custom", "_____no_output_____" ] ], [ [ "With such a `pd.DataFrame`, we can use custom conversions in our unit registry as shown.", "_____no_output_____" ] ], [ [ "# initialise the unit registry with custom conversions\nunit_registry = ScmUnitRegistry(metric_conversions=metric_conversions_custom)\n# add standard conversions before moving on\nunit_registry.add_standards()\n\n# start with e.g. N2O\nnitrous_oxide = unit_registry(\"N2O\")\ndisplay(f\"N2O: {nitrous_oxide}\")\n\n# our unit registry allows us to make conversions using the \n# conversion factors we previously defined\nwith unit_registry.context(\"Custom1\"):\n display(f\"N2O in CO2-equivalent: {nitrous_oxide.to('CO2')}\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01d9edfd0691244266b87d31df294699f62f5a1
20,862
ipynb
Jupyter Notebook
playground-tmqa-1.ipynb
RomainClaret/mse.thesis.code
11837100c438d376a90392018ed69fff067c8ddf
[ "MIT" ]
2
2020-12-07T23:35:49.000Z
2021-05-02T14:57:50.000Z
playground-tmqa-1.ipynb
RomainClaret/mse.thesis.code
11837100c438d376a90392018ed69fff067c8ddf
[ "MIT" ]
null
null
null
playground-tmqa-1.ipynb
RomainClaret/mse.thesis.code
11837100c438d376a90392018ed69fff067c8ddf
[ "MIT" ]
null
null
null
112.16129
8,170
0.62041
[ [ [ "import tmqa12 as tmqa1", "_____no_output_____" ], [ "answer = tmqa1.answer_question(\"Who is the wife of Barack Obama?\", verbose=True)\n\nprint(\"\")\nprint(answer)\nprint(\"\")\n \nif answer: \n print(\"Answer:\",tmqa1.get_wd_label(answer[0][0]), \"(\"+str(answer[0][0])+\")\")\n print(\"Paths:\",[[tmqa1.get_wd_label(e) for e in row] for row in answer[1:]])", "-> q_nlp: Who is the wife of Barack Obama?\n-> q_themes: ([(Barack Obama, ['Q47513588', 'Q76', 'Q13202704', 'Q47513588', 'Q76', 'Q13202704', 'Q47513588', 'Q76', 'Q13202704', 'Q76']), (The Wife, ['Q19102288', 'Q16205566', 'Q23936005', 'Q3273509'])], [the wife, the wife, barack obama, the wife])\n-> q_themes_enhanced: [('The Wife', ['Q19102288', 'Q16205566', 'Q23936005', 'Q3273509']), ('wife', ['P26', 'Q188830', 'Q24039104']), ('Wife', ['Q11447160', 'Q7999459', 'Q28318271', 'Q7774795', 'Q7999457']), ('Barack Obama', ['Q47513588', 'Q76', 'Q13202704']), ('Barack', ['Q18643532', 'Q76', 'Q37011990', 'Q380650']), ('Obama', ['Q223850', 'Q15259951', 'Q33687029', 'Q76', 'Q18355807'])]\n-> q_predicates: [(is, ['P31', 'P433', 'P131'])]\n-> q_focused_parts: [(is, ['Q189', 'Q294'])]\n-> Building the graph with k_deep 50 ... (could be long)\n--> 305 nodes and 304 edges\n-> predicates_dict: {'P2842': 1, 'P580': 4, 'P26': 5, 'P279': 2, 'P1476': 4, 'P805': 2, 'P1343': 2, 'P527': 2, 'P460': 4, 'P1013': 4, 'P1889': 3, 'http://www.w3.org/2002/07/owl#sameAs': 2, 'P155': 4, 'P585': 2, 'P166': 1, 'P1552': 1, 'P1533': 1, 'P407': 2, 'P1686': 1, 'P1411': 1, 'P361': 1, 'P571': 1, 'P1429': 1, 'P25': 1, 'P108': 3, 'P582': 2, 'P106': 4, 'P19': 2, 'P31': 20, 'P1245': 1, 'P22': 1, 'P1424': 1, 'P282': 2, 'P734': 1, 'P1039': 3, 'P3373': 2, 'P136': 4, 'P1299': 1, 'P276': 2, 'P102': 1, 'P1038': 2, 'P461': 1, 'P17': 1, 'P495': 2, 'P1225': 1, 'P21': 1, 'P272': 1, 'P171': 2, 'P462': 1, 'P161': 1, 'P18': 1, 'P195': 2, 'P217': 2, 'P2959': 1, 'P2676': 2, 'P1657': 1, 'P1705': 1, 'P3834': 1, 'P1319': 1, 'P570': 1, 'P1562': 1, 'P243': 2, 'P162': 1, 'P1545': 1, 'P179': 1, 'P1258': 2, 'P105': 1, 'P364': 1, 'P1006': 2, 'P2581': 2, 'P1003': 1, 'P123': 1, 'P646': 2, 'P1014': 2, 'P170': 1, 'P227': 2, 'P131': 1}\n-> paths_keywords: (['is', 'wife', 'barack obama', 'the wife', 'iceland', 'icelandic language'], {'spouse': [spouse, ['P26']], 'wife': [spouse, ['P26']]}, [Who])\n-> Computing possible paths... (could be long)\n--> len(path_nodes): 3594\n-> Filtering paths... (could be long)\n--> len(paths_nodes_filtered): 845\n-> Computing hypothesises...\n--> hypothesises: [['Q13133', 1322.0332404641126], ['Q157084', 450.76978892943373], ['Q18531596', 34.619210543955575], ['Q3155966', 17.075340204616296], ['Q766106', 15.781747038102182], ['Q10703919', 7.563230523356064], ['Q18643532', 4.2906634691330856e-05], ['Q37011990', 4.484738372623802e-11]]\n-> Computing golden paths...\n--> len(golden_paths): 5\n--> len(cleared_golden_paths): 3\n->\tRunning time is 252.94s\n\n[['Q13133', 'Q157084', 'Q18531596', 'Q3155966', 'Q766106', 'Q10703919', 'Q18643532', 'Q37011990'], ['Q13133', 'P26', 'Q76', 'P31', 'Q5', 'P31', 'Q24039104', 'P21', 'Q6581072', 'P1552', 'Q188830', 'P26', 'Q18531596'], ['Q13133', 'P26', 'Q76', 'P31', 'Q5', 'P31', 'Q24039104', 'P21', 'Q6581072', 'P1552', 'Q188830', 'P279', 'Q1196129']]\n\nAnswer: Michelle Obama (Q13133)\nPaths: [['Michelle Obama', 'spouse', 'Barack Obama', 'instance of', 'human', 'instance of', 'wife', 'sex or gender', 'female', 'has quality', 'wife', 'spouse', 'Billy Strachan'], ['Michelle Obama', 'spouse', 'Barack Obama', 'instance of', 'human', 'instance of', 'wife', 'sex or gender', 'female', 'has quality', 'wife', 'subclass of', 'spouse']]\n" ], [ "questions = (\n \"Which actor voiced the Unicorn in The Last Unicorn?\",\n \"what city was alex golfis born in\",\n \"what was the cause of death of yves klein\",\n \"Who is the president of the United States?\",\n \"When was produced the first Matrix movie?\",\n \"Who made the soundtrack of the The Last Unicorn movie?\",\n \"Who is the author of Le Petit Prince?\",\n \"how is called the rabbit in Alice in Wonderland?\",\n \"what's akbar tandjung's ethnicity\"\n )\n\nfor question in questions:\n print(\"Question:\",question)\n answer = tmqa1.answer_question(question)\n if answer: \n print(\"Answer:\",tmqa1.get_wd_label(answer[0][0]), \"(\"+str(answer[0][0])+\")\")\n print(\"Paths:\",[[tmqa1.get_wd_label(e) for e in row] for row in answer[1:]])\n else:\n print(\"I don't know\")\n print(\"\\n\")", "Question: Which actor voiced the Unicorn in The Last Unicorn?\nAnswer: Mia Farrow (Q202725)\nPaths: [['Mia Farrow', 'voice actor', 'The Last Unicorn', 'character role', 'The Unicorn', 'instance of', 'unicorn in a fictional work', 'different from', 'Unicorn', 'named after', 'Unicorn'], ['Mia Farrow', 'voice actor', 'The Last Unicorn', 'character role', 'The Unicorn', 'of', 'The Last Unicorn'], ['Mia Farrow', 'voice actor', 'The Last Unicorn', 'character role', 'The Unicorn', 'instance of', 'unicorn in a fictional work', 'different from', 'Unicorn', 'depicts', 'unicorn'], ['Mia Farrow', 'voice actor', 'The Last Unicorn', 'character role', 'The Unicorn', 'instance of', 'unicorn in a fictional work', 'subclass of', 'unicorn'], ['Mia Farrow', 'voice actor', 'The Last Unicorn', 'character role', 'The Unicorn', 'instance of', 'unicorn in a fictional work', 'different from', 'Unicorn', 'described by source', 'Paulys Realenzyklopädie der klassischen Altertumswissenschaft', 'described by source', 'Actor', 'has part', 'Actor'], ['Mia Farrow', 'voice actor', 'The Last Unicorn', 'character role', 'The Unicorn', 'instance of', 'unicorn in a fictional work', 'different from', 'Unicorn', 'described by source', 'Paulys Realenzyklopädie der klassischen Altertumswissenschaft', 'described by source', 'Actor', 'has part', 'Actor']]\n\n\nQuestion: what city was alex golfis born in\nAnswer: The City (Q18148906)\nPaths: [['The City', 'country of origin', 'United States of America', 'country', 'Alex', 'point in time', ''], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Glen Cove'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Saratoga Springs'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Syracuse'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Yonkers'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Canandaigua'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Geneva'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Glens Falls'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Rye'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Salamanca (city), New York'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Norwich'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Cohoes'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Watervliet'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Tonawanda (city), New York'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Cortland'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Batavia'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Fulton'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Binghamton'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Ithaca'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Auburn'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Utica'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Schenectady'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Long Beach'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Buffalo'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Farrukhabad'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'White Plains'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Amsterdam'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Corning'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Troy'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Sherrill'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Beacon'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Dunkirk'], ['The City', 'country of origin', 'United States of America', 'country', 'city', 'instance of', 'Elmira'], ['list of cities in New York', 'is a list of', 'city', 'country', 'United States of America', 'country of origin', 'The City', 'instance of', 'film'], ['town of the United States', 'instance of', 'Alex', 'country', 'United States of America', 'country of origin', 'The City', 'instance of', 'film'], ['city of the United States', 'subclass of', 'city', 'country', 'United States of America', 'country of origin', 'The City', 'instance of', 'film'], ['', 'point in time', 'Alex', 'country', 'United States of America', 'country of origin', 'The City'], ['Glen Cove', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Saratoga Springs', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Syracuse', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Yonkers', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Canandaigua', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Geneva', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Glens Falls', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Rye', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Salamanca (city), New York', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Norwich', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Cohoes', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Watervliet', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Tonawanda (city), New York', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Cortland', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Batavia', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Fulton', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Binghamton', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Ithaca', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Auburn', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Utica', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Schenectady', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Long Beach', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Buffalo', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Farrukhabad', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['White Plains', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Amsterdam', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Corning', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Troy', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Sherrill', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Beacon', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Dunkirk', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['Elmira', 'instance of', 'city', 'country', 'United States of America', 'country of origin', 'The City'], ['film', 'instance of', 'The City', 'country of origin', 'United States of America', 'country', 'city', 'is a list of', 'list of cities in New York'], ['film', 'instance of', 'The City', 'country of origin', 'United States of America', 'country', 'Alex', 'instance of', 'town of the United States'], ['film', 'instance of', 'The City', 'country of origin', 'United States of America', 'country', 'city', 'subclass of', 'city of the United States']]\n\n\nQuestion: what was the cause of death of yves klein\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
d01da1941442457dcf8bdf6456201f8ffd6e3870
331,625
ipynb
Jupyter Notebook
PotencialEletrico/Quest10Graph.ipynb
BrunoZimmer/TeoriaEletromagnetica
e035c5ff72eb82930fb7b640d2cd65a2ce3fc9a4
[ "MIT" ]
4
2021-04-08T18:42:24.000Z
2021-12-01T05:10:25.000Z
PotencialEletrico/Quest10Graph.ipynb
BrunoZimmer/TeoriaEletromagnetica
e035c5ff72eb82930fb7b640d2cd65a2ce3fc9a4
[ "MIT" ]
null
null
null
PotencialEletrico/Quest10Graph.ipynb
BrunoZimmer/TeoriaEletromagnetica
e035c5ff72eb82930fb7b640d2cd65a2ce3fc9a4
[ "MIT" ]
null
null
null
1,305.610236
174,203
0.82729
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nimport seaborn as sns\n", "_____no_output_____" ], [ "%matplotlib inline\nrcParams['figure.figsize'] = 10, 8\nsns.set_style('whitegrid')", "_____no_output_____" ], [ "num = 50\nxv = np.linspace(-500,400,num)\nyv = np.linspace(-500,400,num)\n\nX,Y = np.meshgrid(xv,yv)\n\n\n# frist X,Y\n\n\na = 8.2\nintervalo = 10\nvalor = 100\nke = 1/(4*np.pi*8.85418e-12)\n\nV = np.zeros((num,num))\nprint(V)\n# v = np.zeros((2,10)) \nkl = 1e-12\n\n# x -> i\n# y -> j\n# x = a + intervalo/2 \ni = j = 0\nfor xi in xv:\n for yj in yv:\n x = a + intervalo/2 \n for k in range(100):\n #print(k,x)\n # calcula o valor da carga do intevalor de linha\n Q = ( (kl*x) / ((x**2) + (a**2)) ) * intervalo # pL * dx\n d = np.sqrt((x-xi)**2 + yj**2)\n if d<0.01:\n d == 0.01\n V[j][i] += ke*(Q/d)\n x = x + intervalo\n # print(i,j) \n j += 1 \n i += 1 \n j = 0 \n \nfig = plt.figure()\nax = plt.axes(projection='3d')\nax.plot_wireframe(X, Y, V, color='black') \nplt.show()\n\nprint(V[0][0])\nprint(V[0][1])\n", "[[0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n ...\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]]\n" ], [ "num = 50\nxv = np.linspace(-500,400,num)\nyv = np.linspace(-500,400,num)\n\n\ni = j = 0\nfor xi in xv:\n \n i += 1 \nprint(i)\n\nprint(\"50 ou\", (900/50))", "50\n50 ou %d 18.0\n" ], [ "%% Descobrir o E1 - Campo eletrico dentro do cilindro\n%tem que ser por gauss pq é um fio infinito\n \n\n%% Variaveis Dadas\nclc\nclear all\nclose all\n\n%% variaveis do problema\ne0 = 8.854*10^-12;\nkc = 8.8*10^-12;\na = 10;\n\nconst=1/(4*pi*e0); %Constante\n\n%% Variaveis Criadas\n\npasse = 1;\nlimites = 20;\n%Onde o campo sera medido:\nx= -limites:passe:limites; %vetor na coordenada x onde será calculado E\ny= -limites:passe:limites; %vetor na coordenada z onde será calculado E\nz= -limites:passe:limites; %vetor na coordenada z onde será calculado E\n\n%Gerador do campo:\nxl= a:passe:(5*limites); % variação da coordenada x onde está a carga \n% yl= -passe:passe:passe; % variação da coordenada y onde está a carga \n\ndL = passe; %tamanho de cada segmento\n\n%inicializa o campo elétrico:\nV(:,:,:) = zeros (length(x),length(y),length(z)); \n\n%% Desenvolvimento\nfor i = 1:length(x)% varre a coordenada x onde E será calculado\n disp(i)\n for j = 1: length(y) % varre a coordenada y onde E será calculado\n for k = 1: length(z) % varre a coordenada z onde E será calculado\n\n for m = 1:length(xl) % varre a coordenada x da carga\n% #for n = 1:length(yl) % varre a coordenada y da carga\n \n r = [x(i),y(j),z(k)]; %vetor posição apontando para onde estamos calculando E\n rl= [xl(m),0,0];% vetor posição apontando para a carga\n\n if ((r-rl)*(r-rl)'>0.00000001)\n V(i,j,k) = V(i,j,k) + const*((((kc.*xl(m))/(xl(m).^2 + a^2)).*dL)/(sqrt((r-rl)*(r-rl)'))');\n\n Q = ke/sqrt((x-xi)**2 + yj**2)*( (kl*x) / ((x**2) + (a**2)) ) * intervalo # pL * dx\n \n end \n \n% # end \n \n end\n end\n end\nend\n%% Grafico\n% xd = linspace(-limites,limites);\n% yd = linspace(-limites,limites);\n% zd = linspace(-limites,limites);\n% [X,Y] = meshgrid(xd,yd);\n% \n% figure(1)\n% surf(x,y,V(:,:,0));\n% xlabel('x')\n% ylabel('y')\n% zlabel('z')\n% axis([-5 20 -20 20 -inf inf])\n% grid on\n% colormap(jet(20))\n% colorbar\n%% prof\n[X,Z] = meshgrid(x,z);\nfigure\n[C,h] = contour(x,z,squeeze(V(:,3,:)),20);%faz o gráfico das curvas de nível para o potencial\nset(h,'ShowText','on','TextStep',get(h,'LevelStep'))\nxlabel('eixo x (m)')\nylabel('eixo z (m)')\n\n\n\n%% Print resultado\nmax = int64(length(x));\nV0 = V(max/2,max/2);\nVinf = 0;\ndisp(0-V0)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
d01da5fd4d09f03b097fd3644de18d4b79b432d6
4,499
ipynb
Jupyter Notebook
testing/loss.ipynb
kamildar/cyclegan
e3ab1d7987aff9080ef9063d0005bfc97f80c32c
[ "MIT" ]
1
2019-01-02T07:43:28.000Z
2019-01-02T07:43:28.000Z
testing/loss.ipynb
kamildar/cyclegan
e3ab1d7987aff9080ef9063d0005bfc97f80c32c
[ "MIT" ]
null
null
null
testing/loss.ipynb
kamildar/cyclegan
e3ab1d7987aff9080ef9063d0005bfc97f80c32c
[ "MIT" ]
null
null
null
25.134078
102
0.512781
[ [ [ "import sys\nsys.path.append(\"../\")", "_____no_output_____" ], [ "from loss import compute_loss\nimport networks as net\nfrom data_sampler import data_sampler\n\nimport functools\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F", "_____no_output_____" ], [ "train_pull = pd.read_csv(\"../../../data/fashion_mnisit/train_pull.csv\", header=None).values\ntrain_top = pd.read_csv(\"../../../data/fashion_mnisit/train_top.csv\", header=None).values\n# test_pull = pd.read_csv(\"../../data/fashion_mnisit/test_pull.csv\", header=None).values\n# test_top = pd.read_csv(\"../../data/fashion_mnisit/test_top.csv\", header=None).values", "_____no_output_____" ], [ "input_nc = 1\noutput_nc = 1\ndiscr_filters = 8\nmax_power = 8\nn_layers = 3\nnorm_lay = nn.BatchNorm2d\nstart_size = 28\ngen_filters = 16\ndropout = None\nn_blocks = 1", "_____no_output_____" ], [ "discr_a = net.Discrimanator(input_nc=input_nc,\n discr_filters=discr_filters,\n max_power=max_power,\n n_layers=n_layers,\n norm_lay=norm_lay,\n start_size=start_size)\n\ndiscr_b = net.Discrimanator(input_nc=input_nc,\n discr_filters=discr_filters,\n max_power=max_power,\n n_layers=n_layers,\n norm_lay=norm_lay,\n start_size=start_size)\n\ngener_a = net.ResnetGenerator(\n input_nc = input_nc,\n output_nc = output_nc,\n gen_filters = gen_filters,\n norm_lay = norm_lay,\n dropout = dropout,\n n_blocks = n_blocks\n)\n\ngener_b = net.ResnetGenerator(\n input_nc = input_nc,\n output_nc = output_nc,\n gen_filters = gen_filters,\n norm_lay = norm_lay,\n dropout = dropout,\n n_blocks = n_blocks\n)", "_____no_output_____" ], [ "batch_a, batch_b = data_sampler(10, train_pull, train_top)\nbatch_a = batch_a.view(-1, 1, 28, 28).float()\nbatch_b = batch_b.view(-1, 1, 28, 28).float()", "_____no_output_____" ], [ "compute_loss(\n gener_a = gener_a,\n gener_b = gener_b,\n discr_a = discr_a,\n discr_b = discr_b,\n batch_a = batch_a,\n batch_b = batch_b,\n alpha = 10\n)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d01db1aa74ee13756b8c810f9f2241d779b941cf
50,197
ipynb
Jupyter Notebook
plot_noise_results.ipynb
Seanny123/rnn-comparison
fab64ed929e8a5838d5e82a3697e5c1bab92c664
[ "MIT" ]
6
2016-11-05T16:05:45.000Z
2020-07-27T13:28:05.000Z
plot_noise_results.ipynb
Seanny123/rnn-comparison
fab64ed929e8a5838d5e82a3697e5c1bab92c664
[ "MIT" ]
null
null
null
plot_noise_results.ipynb
Seanny123/rnn-comparison
fab64ed929e8a5838d5e82a3697e5c1bab92c664
[ "MIT" ]
1
2019-11-19T05:21:40.000Z
2019-11-19T05:21:40.000Z
193.065385
22,492
0.904297
[ [ [ "import seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline", "_____no_output_____" ], [ "aa = pd.read_hdf('results/noise_type_exp_res_06_27_12.h5')\nbb = pd.read_hdf('results/noise_type_exp_res_08_13_53.h5')\ndf = pd.concat((aa, bb))\ndf.reset_index()\nprint(\"Done reading\")", "Done reading\n" ], [ "df.columns", "_____no_output_____" ], [ "df['n_classes'].unique()", "_____no_output_____" ], [ "df['noise type'].unique()", "_____no_output_____" ], [ "ff = sns.barplot(x=\"noise type\", y=\"accuracy\", hue=\"approach\", data=df)\nff.set_xlabel(\"Noise Type\")\nff.set_ylabel(\"Mean Accuracy\")\nff.set_title(\"Effect of Noise Type on Classifier Accuracy\")\nff.set_xticklabels(\n [\"Add White\\nNoise Signal\", \"Add Shot\\nNoise\", \"Insert\\nOffset\", \"Filter with\\nLow Pass\", \"Add White\\nNoise\"]\n)\nleg = ff.legend(title=\"Approach\", frameon=True, fancybox=True, shadow=True, framealpha=1, loc=\"upper left\")\nfl = leg.get_frame()\nfl.set_facecolor('white')\nfl.set_edgecolor('black')\n\nfig = ff.get_figure()\nfig.subplots_adjust(bottom=0.15)\nfig.savefig(\"noise_type.pdf\", format=\"pdf\")", "_____no_output_____" ], [ "type(ff)", "_____no_output_____" ] ], [ [ "Interesting to note that the loss of high-frequency information had almost no effect on the SVM classifier.\nAlso interesting that shot noise was more harmful to the vRNN than to SNN methods.\nNot surprising that additive white noise had the greatest effect on accuracy for all classification methods.", "_____no_output_____" ] ], [ [ "mf1 = pd.read_hdf('results/whitenoise_mag_exp_res_11_03_42.h5')\nmf2 = pd.read_hdf('results/whitenoise_mag_exp_res_10_35_19.h5')\nmf = pd.concat((mf1, mf2))", "_____no_output_____" ], [ "mf.columns\nmf_filt = mf[mf['noise magnitude'] < 0.15]", "_____no_output_____" ], [ "ff = sns.lmplot(\"noise magnitude\", \"accuracy\", hue=\"approach\", data=mf_filt, x_estimator=np.mean,\n scatter_kws={\"alpha\": 0.5}, fit_reg=False, legend=False)\n\nax = ff.axes[0][0]\nax.set_title(\"Effect of White Noise Magnitude on Accuracy\")\nax.set_xlabel(\"Noise Magnitude\")\nax.set_ylabel(\"Accuracy\")\nleg = ax.legend(title=\"Approach\", bbox_to_anchor=(1, 0.6), frameon=True, fancybox=True, shadow=True, framealpha=1)\nfl = leg.get_frame()\nfl.set_facecolor('white')\nfl.set_edgecolor('black')\nax.set_xlim((0.0, 0.11))\n\nff.fig.savefig(\"noise_mag.pdf\", format=\"pdf\")", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d01dc121ea4c1d3b4d87f32afbecb9e480d3d004
80,578
ipynb
Jupyter Notebook
01_rl_introduction__markov_decision_process/2_tower_of_hanoi_intro.ipynb
loftiskg/rl-course
27cd62fbb9573a535acc56279ab5786f20549b6d
[ "Apache-2.0" ]
null
null
null
01_rl_introduction__markov_decision_process/2_tower_of_hanoi_intro.ipynb
loftiskg/rl-course
27cd62fbb9573a535acc56279ab5786f20549b6d
[ "Apache-2.0" ]
null
null
null
01_rl_introduction__markov_decision_process/2_tower_of_hanoi_intro.ipynb
loftiskg/rl-course
27cd62fbb9573a535acc56279ab5786f20549b6d
[ "Apache-2.0" ]
null
null
null
103.040921
38,377
0.859403
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Tower-of-Hanoi\" data-toc-modified-id=\"Tower-of-Hanoi-1\">Tower of Hanoi</a></span></li><li><span><a href=\"#Learning-Outcomes\" data-toc-modified-id=\"Learning-Outcomes-2\">Learning Outcomes</a></span></li><li><span><a href=\"#Demo:-How-to-Play-Tower-of-Hanoi\" data-toc-modified-id=\"Demo:-How-to-Play-Tower-of-Hanoi-3\">Demo: How to Play Tower of Hanoi</a></span></li><li><span><a href=\"#Definitions\" data-toc-modified-id=\"Definitions-4\">Definitions</a></span></li><li><span><a href=\"#Demo:-How-to-Play-Tower-of-Hanoi\" data-toc-modified-id=\"Demo:-How-to-Play-Tower-of-Hanoi-5\">Demo: How to Play Tower of Hanoi</a></span></li><li><span><a href=\"#Student-Activity\" data-toc-modified-id=\"Student-Activity-6\">Student Activity</a></span></li><li><span><a href=\"#Reflection\" data-toc-modified-id=\"Reflection-7\">Reflection</a></span></li><li><span><a href=\"#Did-any-group-derive-formula-for-minimum-number-of-moves?\" data-toc-modified-id=\"Did-any-group-derive-formula-for-minimum-number-of-moves?-8\">Did any group derive formula for minimum number of moves?</a></span></li><li><span><a href=\"#Questions?\" data-toc-modified-id=\"Questions?-9\">Questions?</a></span></li><li><span><a href=\"#-Tower-of-Hanoi-as-RL-problem\" data-toc-modified-id=\"-Tower-of-Hanoi-as-RL-problem-10\"> Tower of Hanoi as RL problem</a></span></li><li><span><a href=\"#-Tower-of-Hanoi-Solutions\" data-toc-modified-id=\"-Tower-of-Hanoi-Solutions-11\"> Tower of Hanoi Solutions</a></span></li><li><span><a href=\"#Greedy-Tower-of-Hanoi\" data-toc-modified-id=\"Greedy-Tower-of-Hanoi-12\">Greedy Tower of Hanoi</a></span></li><li><span><a href=\"#-Tower-of-Hanoi-Solutions\" data-toc-modified-id=\"-Tower-of-Hanoi-Solutions-13\"> Tower of Hanoi Solutions</a></span></li><li><span><a href=\"#THERE-MUST-BE-A-BETTER-WAY!\" data-toc-modified-id=\"THERE-MUST-BE-A-BETTER-WAY!-14\">THERE MUST BE A BETTER WAY!</a></span></li><li><span><a href=\"#RECURSION\" data-toc-modified-id=\"RECURSION-15\">RECURSION</a></span></li><li><span><a href=\"#2-Requirements-for-Recursion\" data-toc-modified-id=\"2-Requirements-for-Recursion-16\">2 Requirements for Recursion</a></span></li><li><span><a href=\"#Think,-Pair,-&amp;-Share\" data-toc-modified-id=\"Think,-Pair,-&amp;-Share-17\">Think, Pair, &amp; Share</a></span></li><li><span><a href=\"#Recursion-Steps-to-Solve-Tower-of-Hanoi\" data-toc-modified-id=\"Recursion-Steps-to-Solve-Tower-of-Hanoi-18\">Recursion Steps to Solve Tower of Hanoi</a></span></li><li><span><a href=\"#Illustrated-Recursive-Steps-to-Solve-Tower-of-Hanoi\" data-toc-modified-id=\"Illustrated-Recursive-Steps-to-Solve-Tower-of-Hanoi-19\">Illustrated Recursive Steps to Solve Tower of Hanoi</a></span></li><li><span><a href=\"#Check-for-understanding\" data-toc-modified-id=\"Check-for-understanding-20\">Check for understanding</a></span></li><li><span><a href=\"#Check-for-understanding\" data-toc-modified-id=\"Check-for-understanding-21\">Check for understanding</a></span></li><li><span><a href=\"#Check-for-understanding\" data-toc-modified-id=\"Check-for-understanding-22\">Check for understanding</a></span></li><li><span><a href=\"#Takeaways\" data-toc-modified-id=\"Takeaways-23\">Takeaways</a></span></li><li><span><a href=\"#Bonus-Material\" data-toc-modified-id=\"Bonus-Material-24\">Bonus Material</a></span></li><li><span><a href=\"#Dynamic-Programming\" data-toc-modified-id=\"Dynamic-Programming-25\">Dynamic Programming</a></span></li><li><span><a href=\"#What-would-Dynamic-Programming-look-like-for-Tower-of-Hanoi?\" data-toc-modified-id=\"What-would-Dynamic-Programming-look-like-for-Tower-of-Hanoi?-26\">What would Dynamic Programming look like for Tower of Hanoi?</a></span></li><li><span><a href=\"#Tower-of-Hanoi-for-Final-Project\" data-toc-modified-id=\"Tower-of-Hanoi-for-Final-Project-27\">Tower of Hanoi for Final Project</a></span></li><li><span><a href=\"#Further-Study\" data-toc-modified-id=\"Further-Study-28\">Further Study</a></span></li></ul></div>", "_____no_output_____" ], [ "<center><h2>Tower of Hanoi</h2></center>\n\n<center><img src=\"images/tower_of_hanoi.jpg\" width=\"75%\"/></center>", "_____no_output_____" ], [ "<center><h2>Learning Outcomes</h2></center>\n\n__By the end of this session, you should be able to__:\n\n- Solve Tower of Hanoi by hand.\n- Explain how to Tower of Hanoi with recursion in your words.", "_____no_output_____" ], [ "<center><h2>Demo: How to Play Tower of Hanoi</h2></center>\n\n<center><img src=\"images/tower_of_hanoi.jpg\" width=\"35%\"/></center>\n\nThe Goal: Move all disks from start to finish.\n\nRules: \n\n1. Only one disk may be moved at a time.\n2. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.\n3. No disk may be placed on top of a smaller disk.", "_____no_output_____" ], [ "__My nephew enjoys the Tower of Hanoi.__\n\n", "_____no_output_____" ], [ "Definitions\n-----\n\n- Rod: The vertical shaft\n- Disks: The items on the rod", "_____no_output_____" ], [ "<center><h2>Demo: How to Play Tower of Hanoi</h2></center>\n\n1) Solve with 1 Disc", "_____no_output_____" ], [ "2) Solve with 2 Discs", "_____no_output_____" ], [ "<center><img src=\"http://hangaroundtheweb.com/wp-content/uploads/2018/07/write-down-english.jpg\" width=\"20%\"/></center>", "_____no_output_____" ], [ "> If you can’t write it down in English, you can’t code it. \n> — Peter Halpern", "_____no_output_____" ], [ "<center><h2>Student Activity</h2></center>\n\nIn small groups, solve Tower of Hanoi: \nhttps://www.mathsisfun.com/games/towerofhanoi-flash.html\n\nRecord the minimal number of steps for each number of discs:\n\n1. 3 discs\n1. 4 discs\n1. 5 discs\n1. 6 discs\n\nIf someone has never solved the puzzle, they should lead. If you have solved it, only give hints when the team is stuck.", "_____no_output_____" ], [ "<center><h2>Reflection</h2></center>\n\nHow difficult was each version? \n\nHow many more steps were needed for each increase in disk? \nCould you write a formula to model the minimum of numbers as number of disks increase?", "_____no_output_____" ] ], [ [ "reset -fs", "_____no_output_____" ], [ "from IPython.display import YouTubeVideo\n\n# 3 rings\nYouTubeVideo('S4HOSbrS4bY')", "_____no_output_____" ], [ "# 6 rings\nYouTubeVideo('iFV821yY7Ns')", "_____no_output_____" ] ], [ [ "<center><h2>Did any group derive formula for minimum number of moves?</h2></center>", "_____no_output_____" ] ], [ [ "# Calculate the optimal number of moves\n\nprint(f\"{'# disks':>7} | {'# moves':>10}\")\n \nfor n_disks in range(1, 21): \n n_moves = (2 ** n_disks)-1\n print(f\"{n_disks:>7} {n_moves:>10,}\")", "# disks | # moves\n 1 1\n 2 3\n 3 7\n 4 15\n 5 31\n 6 63\n 7 127\n 8 255\n 9 511\n 10 1,023\n 11 2,047\n 12 4,095\n 13 8,191\n 14 16,383\n 15 32,767\n 16 65,535\n 17 131,071\n 18 262,143\n 19 524,287\n 20 1,048,575\n" ] ], [ [ "<center><h2>Questions?</h2></center>", "_____no_output_____" ], [ "<center><h2> Tower of Hanoi as RL problem</h2></center>\n\nElements of Reinforcement Learning Problem:\n\n1. Is it sequential?\n1. What is the environment? What are the parameters?\n1. Who is the agent?\n1. What are the states?\n1. What are the rewards?", "_____no_output_____" ], [ "1. Sequential - Yes! By definition moves are one-at-a-time\n1. Environment - The number of rods and disks.\n1. Agent - The mover of disks. You right now. The function you are about to write.\n1. State - Location of disks on rods at a given step\n1. Rewards:\n 1. End - All disks on last rod\n 1. Intermediate - Disks closer to solution state", "_____no_output_____" ], [ "<center><h2> Tower of Hanoi Solutions</h2></center>\n\nWhat would a greedy approach look like?\n\nWould it solve the problem?", "_____no_output_____" ], [ "By greedy, I mean an agent can only move directly towards the goal (of course must follow the rules of the game)", "_____no_output_____" ], [ "<center><h2>Greedy Tower of Hanoi</h2></center>\n\n1. Move the smallest disk to the end.\n2. Move the next disk to the middle.\n3. Then get stuck!", "_____no_output_____" ], [ "<center><h2> Tower of Hanoi Solutions</h2></center>\n\nWhat would a random approach look like?\n\nWould it solve the problem?", "_____no_output_____" ], [ "Find all valid moves, select one.\n\nYes, it would solve. It would take a looooong time.", "_____no_output_____" ], [ "<center><h2>THERE MUST BE A BETTER WAY!</h2></center>", "_____no_output_____" ], [ "<center><h2>RECURSION</h2></center>", "_____no_output_____" ], [ "<center><h2>2 Requirements for Recursion</h2></center>\n\n1. Must have a base case\n1. Move towards the base case by calling the function itself", "_____no_output_____" ], [ "<center><h2>Think, Pair, & Share</h2></center>\n\nHow does the 2 requirements of recursion apply to Tower of Hanoi?\n\nWhat is the base case?\n\nHow can we move towards base case?\n\nHow can we generalize to any number of discs?", "_____no_output_____" ], [ "<center><h2>Recursion Steps to Solve Tower of Hanoi</h2></center>\n\n1. Base case: Move the largest disk to rightmost tower. \n2. Move towards the base case by defining:\n - `from_rod`\n - `to_rod`\n - `aux_rod`\n3. Call the function: Solving the same problem with one less disk.", "_____no_output_____" ], [ "<center><h2>Illustrated Recursive Steps to Solve Tower of Hanoi</h2></center>\n\n<center><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Tower_of_Hanoi_recursion_SMIL.svg/512px-Tower_of_Hanoi_recursion_SMIL.svg.png\" width=\"75%\"/></center>", "_____no_output_____" ], [ "<center><h2>Check for understanding</h2></center>\n\nIs the recursion solution deterministic or schocastic?", "_____no_output_____" ], [ "Deterministic - Every time its plays, it will always play the same", "_____no_output_____" ], [ "<center><h2>Check for understanding</h2></center>\n\nDoes recursion solution learn? Will it get better the more it plays?", "_____no_output_____" ], [ "No - It does not learn.", "_____no_output_____" ], [ "<center><h2>Check for understanding</h2></center>\n\nIs the recursive solution optimal?", "_____no_output_____" ], [ "Yes - It will always play the minum number of moves.", "_____no_output_____" ], [ "<center><h2>Takeaways</h2></center>\n\n- Tower of Hanoi is a game to test the cognitive abilities, most often of small children.\n- Tower of Hanoi has the elements of Reinforcement Learning:\n 1. Sequential \n 1. Environment\n 1. Agent\n 1. State\n 1. Rewards\n- Recursion is a deterministic, non-learning, and optimal solution for Tower of Hanoi.", "_____no_output_____" ], [ " ", "_____no_output_____" ], [ "-----\nBonus Material\n-----", "_____no_output_____" ], [ "<center><h2>Dynamic Programming</h2></center>\n\nWhat is it?", "_____no_output_____" ], [ "Look up previous solutions (rather than re-compute them) to overlapping subproblems.\n\nRequires a cache to store solutions.", "_____no_output_____" ], [ "<center><h2>What would Dynamic Programming look like for Tower of Hanoi?</h2></center>", "_____no_output_____" ], [ "Track optimal solutions to subproblems. \n\nUse those solutions instead of recomputing them.", "_____no_output_____" ], [ "However, the recursive solution is optimal for Tower of Hanoi so there is no reason to add dynamic programming.", "_____no_output_____" ], [ "Tower of Hanoi for Final Project\n------\n\nIf you are interesting in extending Tower of Hanoi as your Final Projects, here ideas to consider:\n\n- Frame it as Markov decision process (MDP)\n- Can you make it stochastic?\n- How can you reformulate the problem that a learned solution would perform better than a deterministic solution?", "_____no_output_____" ], [ "Further Study\n------\n\n- [Q-learning for Tower of Hanoi](https://github.com/khpeek/Q-learning-Hanoi)\n- [RL take for Tower of Hanoi](https://kenandeen.wordpress.com/2015/08/22/tower-of-hanoi-reinforcement-learning/)", "_____no_output_____" ], [ " ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d01dc55c8219cd36a3553dc8854b04b04f3d08b0
25,863
ipynb
Jupyter Notebook
thesis_code/auto_detection.ipynb
hhodac/keras-yolo3
bd9f1595d271c4c5d340796b352b0254c9e63322
[ "MIT" ]
null
null
null
thesis_code/auto_detection.ipynb
hhodac/keras-yolo3
bd9f1595d271c4c5d340796b352b0254c9e63322
[ "MIT" ]
null
null
null
thesis_code/auto_detection.ipynb
hhodac/keras-yolo3
bd9f1595d271c4c5d340796b352b0254c9e63322
[ "MIT" ]
null
null
null
49.641075
3,403
0.536017
[ [ [ "# Auto detection to main + 4 cropped images\n**Pipeline:**\n\n1. Load cropped image csv file\n2. Apply prediction\n3. Save prediction result back to csv file\n* pred_value\n* pred_cat\n* pred_bbox", "_____no_output_____" ] ], [ [ "# Import libraries\n%matplotlib inline\nfrom pycocotools.coco import COCO\nfrom keras.models import load_model\n# from utils.utils import *\n# from utils.bbox import *\n# from utils.image import load_image_pixels\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nimport numpy as np\nimport pandas as pd\nimport skimage.io as io\nimport matplotlib.pyplot as plt\nimport pylab\nimport torchvision.transforms.functional as TF\nimport PIL\nimport os\nimport json \nfrom urllib.request import urlretrieve\npylab.rcParams['figure.figsize'] = (8.0, 10.0)", "Using TensorFlow backend.\n" ], [ "# Define image directory\nprojectDir=os.getcwd()\ndataDir='.'\ndataType='val2017'\nimageDir='{}/images/'.format(dataDir)\nannFile='{}/images/{}_selected/annotations/instances_{}.json'.format(dataDir,dataType,dataType)", "_____no_output_____" ] ], [ [ "## Utilities", "_____no_output_____" ] ], [ [ "class BoundBox:\n def __init__(self, xmin, ymin, xmax, ymax, objness = None, classes = None):\n self.xmin = xmin\n self.ymin = ymin\n self.xmax = xmax\n self.ymax = ymax\n self.objness = objness\n self.classes = classes\n self.label = -1\n self.score = -1\n\n def get_label(self):\n if self.label == -1:\n self.label = np.argmax(self.classes)\n\n return self.label\n\n def get_score(self):\n if self.score == -1:\n self.score = self.classes[self.get_label()]\n\n return self.score\n\ndef _sigmoid(x):\n return 1. / (1. + np.exp(-x))\n\ndef decode_netout(netout, anchors, obj_thresh, net_h, net_w):\n grid_h, grid_w = netout.shape[:2]\n nb_box = 3\n netout = netout.reshape((grid_h, grid_w, nb_box, -1))\n nb_class = netout.shape[-1] - 5\n boxes = []\n netout[..., :2] = _sigmoid(netout[..., :2])\n netout[..., 4:] = _sigmoid(netout[..., 4:])\n netout[..., 5:] = netout[..., 4][..., np.newaxis] * netout[..., 5:]\n netout[..., 5:] *= netout[..., 5:] > obj_thresh\n\n for i in range(grid_h*grid_w):\n row = i // grid_w\n col = i % grid_w\n for b in range(nb_box):\n # 4th element is objectness score\n objectness = netout[int(row)][int(col)][b][4]\n if(objectness.all() <= obj_thresh): continue\n # first 4 elements are x, y, w, and h\n x, y, w, h = netout[int(row)][int(col)][b][:4]\n x = (col + x) / grid_w # center position, unit: image width\n y = (row + y) / grid_h # center position, unit: image height\n w = anchors[2 * b + 0] * np.exp(w) / net_w # unit: image width\n h = anchors[2 * b + 1] * np.exp(h) / net_h # unit: image height\n # last elements are class probabilities\n classes = netout[int(row)][col][b][5:]\n box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, objectness, classes)\n boxes.append(box)\n return boxes\n\ndef correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w):\n new_w, new_h = net_w, net_h\n for i in range(len(boxes)):\n x_offset, x_scale = (net_w - new_w)/2./net_w, float(new_w)/net_w\n y_offset, y_scale = (net_h - new_h)/2./net_h, float(new_h)/net_h\n boxes[i].xmin = int((boxes[i].xmin - x_offset) / x_scale * image_w)\n boxes[i].xmax = int((boxes[i].xmax - x_offset) / x_scale * image_w)\n boxes[i].ymin = int((boxes[i].ymin - y_offset) / y_scale * image_h)\n boxes[i].ymax = int((boxes[i].ymax - y_offset) / y_scale * image_h)\n\ndef _interval_overlap(interval_a, interval_b):\n x1, x2 = interval_a\n x3, x4 = interval_b\n if x3 < x1:\n if x4 < x1:\n return 0\n else:\n return min(x2,x4) - x1\n else:\n if x2 < x3:\n return 0\n else:\n return min(x2,x4) - x3\n\ndef bbox_iou(box1, box2):\n intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax])\n intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax])\n intersect = intersect_w * intersect_h\n w1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin\n w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin\n union = w1*h1 + w2*h2 - intersect\n return float(intersect) / union\n\ndef do_nms(boxes, nms_thresh):\n if len(boxes) > 0:\n nb_class = len(boxes[0].classes)\n else:\n return\n for c in range(nb_class):\n sorted_indices = np.argsort([-box.classes[c] for box in boxes])\n for i in range(len(sorted_indices)):\n index_i = sorted_indices[i]\n if boxes[index_i].classes[c] == 0: continue\n for j in range(i+1, len(sorted_indices)):\n index_j = sorted_indices[j]\n if bbox_iou(boxes[index_i], boxes[index_j]) >= nms_thresh:\n boxes[index_j].classes[c] = 0\n\n# load and prepare an image\ndef load_image_pixels(filename, shape):\n # load the image to get its shape\n image = load_img(filename)\n width, height = image.size\n # load the image with the required size\n image = load_img(filename, target_size=shape)\n # convert to numpy array\n image = img_to_array(image)\n # scale pixel values to [0, 1]\n image = image.astype('float32')\n image /= 255.0\n # add a dimension so that we have one sample\n image = np.expand_dims(image, 0)\n return image, width, height\n\n# get all of the results above a threshold\ndef get_boxes(boxes, labels, thresh):\n v_boxes, v_labels, v_scores = list(), list(), list()\n # enumerate all boxes\n for box in boxes:\n # enumerate all possible labels\n for i in range(len(labels)):\n # check if the threshold for this label is high enough\n if box.classes[i] > thresh:\n v_boxes.append(box)\n v_labels.append(labels[i])\n v_scores.append(box.classes[i]*100)\n # don't break, many labels may trigger for one box\n return v_boxes, v_labels, v_scores\n\n# draw all results\ndef draw_boxes(filename, v_boxes, v_labels, v_scores):\n # load the image\n data = plt.imread(filename)\n # plot the image\n plt.imshow(data)\n # get the context for drawing boxes\n ax = plt.gca()\n # plot each box\n for i in range(len(v_boxes)):\n box = v_boxes[i]\n # get coordinates\n y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax\n # calculate width and height of the box\n width, height = x2 - x1, y2 - y1\n # create the shape\n rect = plt.Rectangle((x1, y1), width, height, fill=False, color='white')\n # draw the box\n ax.add_patch(rect)\n # draw text and score in top left corner\n label = \"%s (%.3f)\" % (v_labels[i], v_scores[i])\n plt.text(x1, y1, label, color='white')\n # show the plot\n plt.show()", "_____no_output_____" ] ], [ [ "## Load model", "_____no_output_____" ] ], [ [ "# load yolov3 model\nmodel = load_model('yolov3_model.h5')\n# define the expected input shape for the model\ninput_w, input_h = 416, 416\n# define the anchors\nanchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]]\n# define the probability threshold for detected objects\nclass_threshold = 0.6\n# define the labels\nlabels = [\"person\", \"bicycle\", \"car\", \"motorbike\", \"airplane\", \"bus\", \"train\", \"truck\",\n \"boat\", \"traffic light\", \"fire hydrant\", \"stop sign\", \"parking meter\", \"bench\",\n \"bird\", \"cat\", \"dog\", \"horse\", \"sheep\", \"cow\", \"elephant\", \"bear\", \"zebra\", \"giraffe\",\n \"backpack\", \"umbrella\", \"handbag\", \"tie\", \"suitcase\", \"frisbee\", \"skis\", \"snowboard\",\n \"sports ball\", \"kite\", \"baseball bat\", \"baseball glove\", \"skateboard\", \"surfboard\",\n \"tennis racket\", \"bottle\", \"wine glass\", \"cup\", \"fork\", \"knife\", \"spoon\", \"bowl\", \"banana\",\n \"apple\", \"sandwich\", \"orange\", \"broccoli\", \"carrot\", \"hot dog\", \"pizza\", \"donut\", \"cake\",\n \"chair\", \"couch\", \"pottedplant\", \"bed\", \"diningtable\", \"toilet\", \"tvmonitor\", \"laptop\", \"mouse\",\n \"remote\", \"keyboard\", \"cell phone\", \"microwave\", \"oven\", \"toaster\", \"sink\", \"refrigerator\",\n \"book\", \"clock\", \"vase\", \"scissors\", \"teddy bear\", \"hair drier\", \"toothbrush\"]", "WARNING:tensorflow:From /Users/haiho/PycharmProjects/yolov3_huynhngocanh/venv/lib/python3.5/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\n" ] ], [ [ "## Gather & concatenate all csv files", "_____no_output_____" ] ], [ [ "all_files = []\ncat = 'book'\nfor subdir, dirs, files in os.walk(os.path.join(imageDir,cat)):\n for filename in files:\n filepath = subdir + os.sep + filename\n if filepath.endswith(\".csv\"):\n all_files.append(filepath)\n print(filepath)", "./images/book/529148/1139919.csv\n./images/book/344621/1139063.csv\n./images/book/112798/1985721.csv\n./images/book/385719/1139451.csv\n./images/book/389315/1652379.csv\n./images/book/368684/1145116.csv\n./images/book/506933/1147645.csv\n./images/book/166478/1138070.csv\n./images/book/206579/1986194.csv\n./images/book/96001/1137334.csv\n./images/book/167159/1137818.csv\n./images/book/551439/1140019.csv\n./images/book/16958/1144744.csv\n./images/book/458255/1141588.csv\n./images/book/172617/1140850.csv\n./images/book/334399/1648816.csv\n./images/book/14038/2197005.csv\n./images/book/250901/1986136.csv\n./images/book/25603/1144688.csv\n./images/book/172595/1139612.csv\n./images/book/421923/1137283.csv\n./images/book/222299/1648151.csv\n./images/book/413247/1139762.csv\n./images/book/398377/1138534.csv\n./images/book/509699/1141405.csv\n./images/book/415741/1648882.csv\n./images/book/472678/1648320.csv\n./images/book/575187/1145126.csv\n./images/book/55528/1647877.csv\n./images/book/467176/908400467176.csv\n./images/book/573094/1985088.csv\n./images/book/539883/1138176.csv\n./images/book/553664/1138185.csv\n./images/book/540280/1650976.csv\n./images/book/115870/1141268.csv\n./images/book/479248/1662457.csv\n./images/book/340175/908400340175.csv\n./images/book/400082/1143266.csv\n./images/book/632/1987085.csv\n./images/book/416343/1985126.csv\n./images/book/93353/1137053.csv\n./images/book/71226/1138892.csv\n./images/book/213086/1654376.csv\n./images/book/416451/1658919.csv\n./images/book/194724/1137084.csv\n./images/book/455301/1138815.csv\n./images/book/176232/2143009.csv\n./images/book/24610/1144582.csv\n./images/book/455937/1138668.csv\n./images/book/154705/1649151.csv\n./images/book/123633/1146234.csv\n./images/book/45229/1650257.csv\n./images/book/147518/1985748.csv\n./images/book/136915/1987277.csv\n./images/book/215778/1140731.csv\n./images/book/387098/1983947.csv\n./images/book/134882/1146908.csv\n./images/book/466125/1985068.csv\n./images/book/451308/1984216.csv\n./images/book/58111/1141657.csv\n./images/book/482319/1147472.csv\n./images/book/104666/1140282.csv\n./images/book/121586/1139801.csv\n./images/book/179898/1650038.csv\n./images/book/214224/1654951.csv\n./images/book/473219/1139961.csv\n./images/book/316666/1989379.csv\n./images/book/77396/1136959.csv\n./images/book/547336/1146671.csv\n./images/book/89648/1651552.csv\n./images/book/125129/1983875.csv\n./images/book/36936/2141551.csv\n./images/book/480936/1653080.csv\n./images/book/309938/1139039.csv\n./images/book/323202/1649362.csv\n./images/book/84674/1137165.csv\n./images/book/535253/1985407.csv\n./images/book/255165/1142550.csv\n./images/book/384527/1144024.csv\n./images/book/128148/908400128148.csv\n./images/book/125062/1648577.csv\n./images/book/476810/1147902.csv\n./images/book/567886/1137471.csv\n./images/book/379441/1662278.csv\n./images/book/135872/1138037.csv\n./images/book/179392/1655523.csv\n./images/book/199771/1143506.csv\n./images/book/507575/1140358.csv\n./images/book/39477/1140893.csv\n./images/book/31248/1143403.csv\n./images/book/542776/2196961.csv\n./images/book/308430/1648499.csv\n./images/book/317999/1137617.csv\n./images/book/316015/1657179.csv\n./images/book/262227/1648770.csv\n./images/book/200839/1984132.csv\n./images/book/97994/1142182.csv\n./images/book/205514/1138665.csv\n./images/book/565877/1648063.csv\n./images/book/529568/2141653.csv\n" ], [ "li = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\ndf_images = pd.concat(li, axis=0, ignore_index=True)\ndf_images.head()", "_____no_output_____" ] ], [ [ "## Apply prediction to multiple images", "_____no_output_____" ] ], [ [ "df_pred = pd.DataFrame(columns=['pred','pred_cat','pred_bbox'])\niou_threshold = 0.5\nfor idx, item in df_images.iterrows():\n file_path = os.path.join(item['path'], item['filename'])\n image, image_w, image_h = load_image_pixels(file_path, (input_w, input_h))\n yhat = model.predict(image)\n boxes = list()\n for i in range(len(yhat)):\n # decode the output of the network\n boxes += decode_netout(yhat[i][0], anchors[i], class_threshold, input_h, input_w)\n # correct the sizes of the bounding boxes for the shape of the image\n correct_yolo_boxes(boxes, image_h, image_w, input_h, input_w)\n # suppress non-maximal boxes\n do_nms(boxes, 0.5)\n # get the details of the detected objects\n v_boxes, v_labels, v_scores = get_boxes(boxes, labels, class_threshold)\n \n ##########\n # summarize what we found\n # for i in range(len(v_boxes)):\n # print(v_labels[i], v_scores[i])\n # draw what we found\n # draw_boxes(file_path, v_boxes, v_labels, v_scores)\n\n ##########\n boxes = item['bbox'].lstrip(\"[\")\n boxes = boxes.rstrip(\"]\")\n boxes = boxes.strip()\n x, y, w, h = list(map(int,boxes.split(\",\")))\n _box = BoundBox(x, y, x+w, y+h)\n is_detected = False\n for i, box in enumerate(v_boxes): # y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax\n # print(bbox_iou(box, _box))\n # print(bbox_iou(_box, box))\n iou = bbox_iou(box, _box)\n if iou > iou_threshold:\n df_pred = df_pred.append({\n 'pred': v_scores[i],\n 'pred_cat': v_labels[i],\n 'pred_bbox': [box.xmin, box.ymin, box.xmax-box.xmin, box.ymax-box.ymin]\n }, ignore_index=True)\n is_detected=True\n break\n if not is_detected:\n df_pred = df_pred.append({\n 'pred': np.nan,\n 'pred_cat': np.nan,\n 'pred_bbox': np.nan\n }, ignore_index=True)", "_____no_output_____" ], [ "df = pd.concat([df_images, df_pred], axis=1)\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 500 entries, 0 to 499\nData columns (total 9 columns):\nbbox 500 non-null object\ncategory 500 non-null object\nfilename 500 non-null object\nheight 500 non-null int64\npath 500 non-null object\nwidth 500 non-null int64\npred 56 non-null float64\npred_cat 56 non-null object\npred_bbox 56 non-null object\ndtypes: float64(1), int64(2), object(6)\nmemory usage: 35.3+ KB\n" ], [ "df.head()", "_____no_output_____" ], [ "df.to_csv(imageDir+cat+\"/prediction_results.csv\", index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d01dc94860ba7cd3912d213a050f30213666f5f4
18,280
ipynb
Jupyter Notebook
paper_experiments_work_log/speaker_recognition.ipynb
cgnorthcutt/EgoCom-Dataset
4f17ea5447e6990071dbab4936cc3e713551a3f4
[ "MIT" ]
36
2020-11-05T20:30:18.000Z
2021-12-07T04:35:35.000Z
paper_experiments_work_log/speaker_recognition.ipynb
cgnorthcutt/EgoCom-Dataset
4f17ea5447e6990071dbab4936cc3e713551a3f4
[ "MIT" ]
2
2020-11-07T21:39:41.000Z
2020-11-07T21:45:06.000Z
paper_experiments_work_log/speaker_recognition.ipynb
cgnorthcutt/EgoCom-Dataset
4f17ea5447e6990071dbab4936cc3e713551a3f4
[ "MIT" ]
5
2020-11-07T20:46:15.000Z
2021-11-06T14:05:46.000Z
38.083333
1,177
0.580963
[ [ [ "from egocom import audio\nfrom egocom.multi_array_alignment import gaussian_kernel\nfrom egocom.transcription import async_srt_format_timestamp\nfrom scipy.io import wavfile\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom egocom.transcription import write_subtitles", "_____no_output_____" ], [ "def gaussian_smoothing(arr, samplerate = 44100, window_size = 0.1):\n '''Returns a locally-normalized array by dividing each point by a the \n sum of the points around it, with greater emphasis on the points \n nearest (using a Guassian convolution)\n \n Parameters\n ----------\n arr : np.array\n samplerate : int\n window_size : float (in seconds)\n \n Returns\n -------\n A Guassian smoothing of the input arr'''\n \n kern = gaussian_kernel(kernel_length=int(samplerate * window_size), nsigma=3)\n return np.convolve(arr, kern, 'same')", "_____no_output_____" ], [ "# Tests for audio.avg_pool_1d\n\ndef test_exact_recoverability(\n arr = range(10),\n pool_size = 4,\n weights = [0.2,0.3,0.3,0.2],\n): \n '''Verify that downsampled signal can be fully recovered exactly.'''\n complete_result = audio.avg_pool_1d(range(10), pool_size, filler = True, weights = weights)\n downsampled_result = audio.avg_pool_1d(range(10), pool_size, filler = False, weights = weights)\n # Try to recover filled_pooled_mags using the downsampled pooled_mags\n upsampled_result = audio.upsample_1d(downsampled_result, len(arr), pool_size)\n assert(np.all(upsampled_result == complete_result))\n \n \ndef test_example(\n arr = range(10),\n pool_size = 4,\n weights = [0.2,0.3,0.3,0.2],\n):\n '''Verify that avg_pool_1d produces the result we expect.'''\n result = audio.avg_pool_1d(range(10), pool_size, weights = weights)\n expected = np.array([1.5, 1.5, 1.5, 1.5, 5.5, 5.5, 5.5, 5.5, 8.5, 8.5])\n assert(np.all(result - expected < 1e-6))\n \ntest_exact_recoverability()\ntest_example()", "_____no_output_____" ] ], [ [ "# Generate speaker labels from max raw audio magnitudes", "_____no_output_____" ] ], [ [ "data_dir = '/Users/cgn/Dropbox (Facebook)/EGOCOM/raw_audio/wav/'\n\nfn_dict = {}\nfor fn in sorted(os.listdir(data_dir)):\n key = fn[9:23] + fn[32:37] if 'part' in fn else fn[9:21]\n fn_dict[key] = fn_dict[key] + [fn] if key in fn_dict else [fn]", "_____no_output_____" ], [ "samplerate = 44100\nwindow = 1 # Averages signals with windows of N seconds.\nwindow_length = int(samplerate * window)\n\nlabels = {}\nfor key in list(fn_dict.keys()):\n print(key, end = \" | \")\n fns = fn_dict[key]\n wavs = [wavfile.read(data_dir + fn)[1] for fn in fns]\n duration = min(len(w) for w in wavs)\n wavs = np.stack([w[:duration] for w in wavs])\n \n # Only use the magnitudes of both left and right for each audio wav.\n mags = abs(wavs).sum(axis = 2) \n\n # DOWNSAMPLED (POOLED) Discretized/Fast (no overlap) gaussian smoothing with one-second time window.\n kwargs = {\n 'pool_size': window_length, \n 'weights': gaussian_kernel(kernel_length=window_length),\n 'filler': False,\n }\n pooled_mags = np.apply_along_axis(audio.avg_pool_1d, 1, mags, **kwargs) \n\n # Create noisy speaker labels\n threshold = np.percentile(pooled_mags, 10, axis = 1)\n no_one_speaking = (pooled_mags > np.expand_dims(threshold, axis = 1)).sum(axis = 0) == 0\n speaker_labels = np.argmax(pooled_mags, axis = 0)\n speaker_labels[no_one_speaking] = -1\n \n # User 1-based indexing for speaker labels (ie increase by 1)\n speaker_labels = [z if z < 0 else z + 1 for z in speaker_labels]\n \n # Store results\n labels[key] = speaker_labels", "day_1__con_1__part1 | day_1__con_1__part2 | day_1__con_1__part3 | day_1__con_1__part4 | day_1__con_1__part5 | day_1__con_2__part1 | day_1__con_2__part2 | day_1__con_2__part3 | day_1__con_2__part4 | day_1__con_2__part5 | day_1__con_3__part1 | day_1__con_3__part2 | day_1__con_3__part3 | day_1__con_3__part4 | day_1__con_4__part1 | day_1__con_4__part2 | day_1__con_4__part3 | day_1__con_4__part4 | day_1__con_5__part1 | day_1__con_5__part2 | day_1__con_5__part3 | day_1__con_5__part4 | day_1__con_5__part5 | day_2__con_1__part1 | day_2__con_1__part2 | day_2__con_1__part3 | day_2__con_1__part4 | day_2__con_1__part5 | day_2__con_2__part1 | day_2__con_2__part2 | day_2__con_2__part3 | day_2__con_2__part4 | day_2__con_3 | day_2__con_4 | day_2__con_5 | day_2__con_6 | day_2__con_7 | day_3__con_1 | day_3__con_2 | day_3__con_3 | day_3__con_4 | day_3__con_5 | day_3__con_6 | day_4__con_1 | day_4__con_2 | day_4__con_3 | day_4__con_4 | day_4__con_5 | day_4__con_6 | day_5__con_1 | day_5__con_2 | day_5__con_3 | day_5__con_4 | day_5__con_5 | day_5__con_6 | day_5__con_7 | day_5__con_8 | day_6__con_1 | day_6__con_2 | day_6__con_3 | day_6__con_4 | day_6__con_5 | day_6__con_6 | " ], [ "# Write result to file\nloc = '/Users/cgn/Dropbox (Facebook)/EGOCOM/raw_audio_speaker_labels_{}.json'.format(str(window))\ndef default(o):\n if isinstance(o, np.int64): return int(o) \n raise TypeError\n \nimport json\nwith open(loc, 'w') as fp:\n json.dump(labels, fp, default = default)\nfp.close()", "_____no_output_____" ], [ "# Read result into a dict\nimport json\nwith open(loc, 'r') as fp:\n labels = json.load(fp)\nfp.close()", "_____no_output_____" ] ], [ [ "## Generate ground truth speaker labels", "_____no_output_____" ] ], [ [ "def create_gt_speaker_labels(\n df_times_speaker,\n duration_in_seconds,\n time_window_seconds = 0.5,\n):\n stack = rev_times[::-1]\n stack_time = stack.pop()\n label_times = np.arange(0, duration_in_seconds, time_window_seconds)\n result = [-1] * len(label_times)\n\n for i, t in enumerate(label_times):\n while stack_time['endTime'] > t and stack_time['endTime'] <= t + time_window_seconds:\n result[i] = stack_time['speaker']\n if len(stack) == 0:\n break\n stack_time = stack.pop()\n \n return result", "_____no_output_____" ], [ "df = pd.read_csv(\"/Users/cgn/Dropbox (Facebook)/EGOCOM/ground_truth_transcriptions.csv\")[\n [\"key\", \"endTime\", \"speaker\", ]\n].dropna()", "_____no_output_____" ], [ "gt_speaker_labels = {}\nfor key, sdf in df.groupby('key'):\n print(key, end = \" | \")\n wavs = [wavfile.read(data_dir + fn)[1] for fn in fn_dict[key]]\n duration = min(len(w) for w in wavs)\n DL = sdf[[\"endTime\", \"speaker\"]].to_dict('list')\n rev_times = [dict(zip(DL,t)) for t in zip(*DL.values())]\n duration_in_seconds = np.ceil(duration / float(samplerate))\n gt_speaker_labels[key] = create_gt_speaker_labels(rev_times, duration_in_seconds, window)", "day_1__con_1__part1 | day_1__con_1__part2 | day_1__con_1__part3 | day_1__con_1__part4 | day_1__con_1__part5 | day_1__con_2__part1 | day_1__con_2__part2 | day_1__con_2__part3 | day_1__con_2__part4 | day_1__con_2__part5 | day_1__con_3__part1 | day_1__con_3__part2 | day_1__con_3__part3 | day_1__con_3__part4 | day_1__con_4__part1 | day_1__con_4__part2 | day_1__con_4__part3 | day_1__con_4__part4 | day_1__con_5__part1 | day_1__con_5__part2 | day_1__con_5__part3 | day_1__con_5__part4 | day_1__con_5__part5 | day_2__con_1__part1 | day_2__con_1__part2 | day_2__con_1__part3 | day_2__con_1__part4 | day_2__con_1__part5 | day_2__con_2__part1 | day_2__con_2__part2 | day_2__con_2__part3 | day_2__con_2__part4 | day_2__con_3 | day_2__con_4 | day_2__con_5 | day_2__con_6 | day_2__con_7 | day_3__con_1 | day_3__con_2 | day_3__con_3 | day_3__con_4 | day_3__con_5 | day_3__con_6 | day_4__con_1 | day_4__con_2 | day_4__con_3 | day_4__con_4 | day_4__con_5 | day_4__con_6 | day_5__con_1 | day_5__con_2 | day_5__con_3 | day_5__con_4 | day_5__con_5 | day_5__con_6 | day_5__con_7 | day_5__con_8 | day_6__con_1 | day_6__con_2 | day_6__con_3 | day_6__con_4 | day_6__con_5 | day_6__con_6 | " ], [ "# Write result to file\nloc = '/Users/cgn/Dropbox (Facebook)/EGOCOM/rev_ground_truth_speaker_labels_{}.json'.format(str(window))\nwith open(loc, 'w') as fp:\n json.dump(gt_speaker_labels, fp, default = default)\nfp.close()", "_____no_output_____" ], [ "# Read result into a dict\nwith open(loc, 'r') as fp:\n gt_speaker_labels = json.load(fp)\nfp.close()", "_____no_output_____" ], [ "scores = []\nfor key in labels.keys():\n true = gt_speaker_labels[key]\n pred = labels[key]\n if len(true) > len(pred):\n true = true[:-1]\n# diff = round(accuracy_score(true[:-1], pred) - accuracy_score(true[1:], pred), 3)\n# scores.append(diff)\n# print(key, accuracy_score(true[1:], pred), accuracy_score(true[:-1], pred), diff)\n score = accuracy_score(true, pred)\n scores.append(score)\n print(key, np.round(score, 3))", "day_1__con_1__part1 0.724\nday_1__con_1__part2 0.763\nday_1__con_1__part3 0.702\nday_1__con_1__part4 0.773\nday_1__con_1__part5 0.867\nday_1__con_2__part1 0.68\nday_1__con_2__part2 0.742\nday_1__con_2__part3 0.792\nday_1__con_2__part4 0.869\nday_1__con_2__part5 0.85\nday_1__con_3__part1 0.822\nday_1__con_3__part2 0.735\nday_1__con_3__part3 0.758\nday_1__con_3__part4 0.867\nday_1__con_4__part1 0.859\nday_1__con_4__part2 0.833\nday_1__con_4__part3 0.77\nday_1__con_4__part4 0.72\nday_1__con_5__part1 0.666\nday_1__con_5__part2 0.607\nday_1__con_5__part3 0.637\nday_1__con_5__part4 0.67\nday_1__con_5__part5 0.6\nday_2__con_1__part1 0.699\nday_2__con_1__part2 0.743\nday_2__con_1__part3 0.723\nday_2__con_1__part4 0.68\nday_2__con_1__part5 0.714\nday_2__con_2__part1 0.715\nday_2__con_2__part2 0.68\nday_2__con_2__part3 0.677\nday_2__con_2__part4 0.633\nday_2__con_3 0.623\nday_2__con_4 0.754\nday_2__con_5 0.842\nday_2__con_6 0.728\nday_2__con_7 0.663\nday_3__con_1 0.868\nday_3__con_2 0.787\nday_3__con_3 0.769\nday_3__con_4 0.793\nday_3__con_5 0.685\nday_3__con_6 0.741\nday_4__con_1 0.784\nday_4__con_2 0.669\nday_4__con_3 0.736\nday_4__con_4 0.777\nday_4__con_5 0.423\nday_4__con_6 0.708\nday_5__con_1 0.731\nday_5__con_2 0.693\nday_5__con_3 0.731\nday_5__con_4 0.723\nday_5__con_5 0.727\nday_5__con_6 0.783\nday_5__con_7 0.682\nday_5__con_8 0.612\nday_6__con_1 0.78\nday_6__con_2 0.686\nday_6__con_3 0.678\nday_6__con_4 0.558\nday_6__con_5 0.636\nday_6__con_6 0.598\n" ], [ "print('Average accuracy:', str(np.round(np.mean(scores), 3)* 100) + '%')", "Average accuracy: 72.3%\n" ], [ "loc = '/Users/cgn/Dropbox (Facebook)/EGOCOM/subtitles/'\nfor key in labels.keys():\n gt = gt_speaker_labels[key]\n est = labels[key]\n with open(loc + \"speaker_\" + key + '.srt', 'w') as f:\n print(key, end = \" | \")\n for t, s_est in enumerate(est):\n s_gt = gt[t]\n print(t + 1, file = f)\n print(async_srt_format_timestamp(t*window), end = \"\", file = f)\n print(' --> ', end = '', file = f)\n print(async_srt_format_timestamp(t*window+window), file = f)\n print('Rev.com Speaker:', end = \" \", file = f)\n if s_gt == -1:\n print('No one is speaking', file = f)\n elif s_gt == 1:\n print('Curtis', file = f)\n else:\n print('Speaker ' + str(s_gt), file = f)\n print('MaxMag Speaker:', end = \" \", file = f)\n if s_est == -1:\n print('No one is speaking', file = f)\n elif s_est == 1:\n print('Curtis', file = f)\n else:\n print('Speaker ' + str(s_est), file = f)\n print(file = f)", "day_1__con_1__part1 | day_1__con_1__part2 | day_1__con_1__part3 | day_1__con_1__part4 | day_1__con_1__part5 | day_1__con_2__part1 | day_1__con_2__part2 | day_1__con_2__part3 | day_1__con_2__part4 | day_1__con_2__part5 | day_1__con_3__part1 | day_1__con_3__part2 | day_1__con_3__part3 | day_1__con_3__part4 | day_1__con_4__part1 | day_1__con_4__part2 | day_1__con_4__part3 | day_1__con_4__part4 | day_1__con_5__part1 | day_1__con_5__part2 | day_1__con_5__part3 | day_1__con_5__part4 | day_1__con_5__part5 | day_2__con_1__part1 | day_2__con_1__part2 | day_2__con_1__part3 | day_2__con_1__part4 | day_2__con_1__part5 | day_2__con_2__part1 | day_2__con_2__part2 | day_2__con_2__part3 | day_2__con_2__part4 | day_2__con_3 | day_2__con_4 | day_2__con_5 | day_2__con_6 | day_2__con_7 | day_3__con_1 | day_3__con_2 | day_3__con_3 | day_3__con_4 | day_3__con_5 | day_3__con_6 | day_4__con_1 | day_4__con_2 | day_4__con_3 | day_4__con_4 | day_4__con_5 | day_4__con_6 | day_5__con_1 | day_5__con_2 | day_5__con_3 | day_5__con_4 | day_5__con_5 | day_5__con_6 | day_5__con_7 | day_5__con_8 | day_6__con_1 | day_6__con_2 | day_6__con_3 | day_6__con_4 | day_6__con_5 | day_6__con_6 | " ] ], [ [ "## Generate subtitles", "_____no_output_____" ] ], [ [ "for key in labels.keys():\n gt = labels[key]\n with open(\"subtitles/est_\" + key + '.srt', 'w') as f:\n for t, s in enumerate(gt):\n print(t + 1, file = f)\n print(async_srt_format_timestamp(t*window), end = \"\", file = f)\n print(' --> ', end = '', file = f)\n print(async_srt_format_timestamp(t*window+window), file = f)\n print('Max mag of wavs speaker id', file = f)\n if s == -1:\n print('No one is speaking', file = f)\n elif s == 1:\n print('Curtis', file = f)\n else:\n print('Speaker ' + str(s), file = f)\n print(file = f)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d01dd1d7ec7f0b13e20998a703611cf0fd94532e
20,954
ipynb
Jupyter Notebook
wandb/run-20211017_221447-2snzs8gh/tmp/code/_session_history.ipynb
Programmer-RD-AI/Intel-Image-Classification-V2
4be91f82c5ec699d6ea91ca068167a72d4e63723
[ "Apache-2.0" ]
null
null
null
wandb/run-20211017_221447-2snzs8gh/tmp/code/_session_history.ipynb
Programmer-RD-AI/Intel-Image-Classification-V2
4be91f82c5ec699d6ea91ca068167a72d4e63723
[ "Apache-2.0" ]
null
null
null
wandb/run-20211017_221447-2snzs8gh/tmp/code/_session_history.ipynb
Programmer-RD-AI/Intel-Image-Classification-V2
4be91f82c5ec699d6ea91ca068167a72d4e63723
[ "Apache-2.0" ]
null
null
null
33.796774
269
0.525198
[ [ [ "from torchvision.models import *\nimport wandb\nfrom sklearn.model_selection import train_test_split\nimport os,cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.nn import *\nimport torch,torchvision\nfrom tqdm import tqdm\ndevice = 'cuda'\nPROJECT_NAME = 'Intel-Image-Classification-V2'", "_____no_output_____" ], [ "def load_data():\n data = []\n labels = {}\n labels_r = {}\n idx = 0\n for label in os.listdir('./data/'):\n idx += 1\n labels[label] = idx\n labels_r[idx] = label\n for folder in os.listdir('./data/'):\n for file in os.listdir(f'./data/{folder}/')[:1000]:\n img = cv2.imread(f'./data/{folder}/{file}')\n img = cv2.resize(img,(56,56))\n img = img / 255.0\n data.append([\n img,\n np.eye(labels[foder],len(labels))[labels[folder]-1]\n ])\n X = []\n y = []\n for d in data:\n X.append(d[0])\n y.append(d[1])\n X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,shuffle=False)\n X_train = torch.from_numpy(np.array(X_train)).to(device).view(-1,3,56,56).float()\n y_train = torch.from_numpy(np.array(y_train)).to(device).float()\n X_test = torch.from_numpy(np.array(X_test)).to(device).view(-1,3,56,56).float()\n y_test = torch.from_numpy(np.array(y_test)).to(device).float()\n return X,y,X_train,X_test,y_train,y_test,labels,labels_r,idx,data", "_____no_output_____" ], [ "X,y,X_train,X_test,y_train,y_test,labels,labels_r,idx,data = load_data()", "_____no_output_____" ], [ "def load_data():\n data = []\n labels = {}\n labels_r = {}\n idx = 0\n for label in os.listdir('./data/'):\n idx += 1\n labels[label] = idx\n labels_r[idx] = label\n for folder in os.listdir('./data/'):\n for file in os.listdir(f'./data/{folder}/')[:1000]:\n img = cv2.imread(f'./data/{folder}/{file}')\n img = cv2.resize(img,(56,56))\n img = img / 255.0\n data.append([\n img,\n np.eye(labels[labels_r],len(labels))[labels[folder]-1]\n ])\n X = []\n y = []\n for d in data:\n X.append(d[0])\n y.append(d[1])\n X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,shuffle=False)\n X_train = torch.from_numpy(np.array(X_train)).to(device).view(-1,3,56,56).float()\n y_train = torch.from_numpy(np.array(y_train)).to(device).float()\n X_test = torch.from_numpy(np.array(X_test)).to(device).view(-1,3,56,56).float()\n y_test = torch.from_numpy(np.array(y_test)).to(device).float()\n return X,y,X_train,X_test,y_train,y_test,labels,labels_r,idx,data", "_____no_output_____" ], [ "def load_data():\n data = []\n labels = {}\n labels_r = {}\n idx = 0\n for label in os.listdir('./data/'):\n idx += 1\n labels[label] = idx\n labels_r[idx] = label\n for folder in os.listdir('./data/'):\n for file in os.listdir(f'./data/{folder}/')[:1000]:\n img = cv2.imread(f'./data/{folder}/{file}')\n img = cv2.resize(img,(56,56))\n img = img / 255.0\n data.append([\n img,\n np.eye(labels[folder],len(labels))[labels[folder]-1]\n ])\n X = []\n y = []\n for d in data:\n X.append(d[0])\n y.append(d[1])\n X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,shuffle=False)\n X_train = torch.from_numpy(np.array(X_train)).to(device).view(-1,3,56,56).float()\n y_train = torch.from_numpy(np.array(y_train)).to(device).float()\n X_test = torch.from_numpy(np.array(X_test)).to(device).view(-1,3,56,56).float()\n y_test = torch.from_numpy(np.array(y_test)).to(device).float()\n return X,y,X_train,X_test,y_train,y_test,labels,labels_r,idx,data", "_____no_output_____" ], [ "X,y,X_train,X_test,y_train,y_test,labels,labels_r,idx,data = load_data()", "_____no_output_____" ], [ "torch.save(X_train,'X_train.pt')\ntorch.save(y_train,'y_train.pt')\ntorch.save(X_test,'X_test.pt')\ntorch.save(y_test,'y_test.pt')\ntorch.save(labels_r,'labels_r.pt')\ntorch.save(labels,'labels.pt')\ntorch.save(X_train,'X_train.pth')\ntorch.save(y_train,'y_train.pth')\ntorch.save(X_test,'X_test.pth')\ntorch.save(y_test,'y_test.pth')\ntorch.save(labels_r,'labels_r.pth')\ntorch.save(labels,'labels.pth')", "_____no_output_____" ], [ "def get_loss(model,X,y,criterion):\n preds = model(X)\n loss = criterion(preds,y)\n return loss.item()", "_____no_output_____" ], [ "def get_acuracy(model,X,y):\n preds = model(X)\n correct = 0\n total = 0\n for pred,yb in tqdm(zip(preds,y)):\n pred = int(torch.argmax(pred))\n yb = int(torch.argmax(yb))\n if pred == yb:\n correct += 1\n total += 1\n acc = round(correct/total,3)*100\n return acc", "_____no_output_____" ], [ "model = resnet18().to(device)\nmodel.fc = Linear(512,len(labels))\ncriterion = MSELoss()\noptimizer = Adam(model.parameters(),lr=0.001)\nepochs = 100\nbathc_size = 32", "_____no_output_____" ], [ "model = resnet18().to(device)\nmodel.fc = Linear(512,len(labels))\ncriterion = MSELoss()\noptimizer = optim.Adam(model.parameters(),lr=0.001)\nepochs = 100\nbathc_size = 32", "_____no_output_____" ], [ "model = resnet18().to(device)\nmodel.fc = Linear(512,len(labels))\ncriterion = MSELoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=0.001)\nepochs = 100\nbathc_size = 32", "_____no_output_____" ], [ "wandb.init(project=PROJECT_NAME,name='baseline-TL')\nfor _ in tqdm(range(epochs)):\n for i in range(0,len(X_train),batch_size):\n X_batch = X_train[i:i+batch_size]\n y_batch = y_train[i:i+batch_size]\n model.to(device)\n preds = model(X_batch)\n loss = criterion(preds,y_batch)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n model.eval()\n torch.cuda.empty_cache()\n wandb.log({'Loss':(get_loss(model,X_train,y_train,criterion)+get_loss(model,X_batch,y_batch,criterion))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val Loss':get_loss(model,X_test,y_test,criterion)})\n torch.cuda.empty_cache()\n wandb.log({'Acc':(get_accuracy(model,X_train,y_train)+get_accuracy(model,X_batch,y_batch))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val ACC':get_accuracy(model,X_test,y_test)})\n torch.cuda.empty_cache()\n model.train()\nwandb.finish()", "_____no_output_____" ], [ "model = resnet18().to(device)\nmodel.fc = Linear(512,len(labels))\ncriterion = MSELoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=0.001)\nepochs = 100\nbatch_size = 32", "_____no_output_____" ], [ "wandb.init(project=PROJECT_NAME,name='baseline-TL')\nfor _ in tqdm(range(epochs)):\n for i in range(0,len(X_train),batch_size):\n X_batch = X_train[i:i+batch_size]\n y_batch = y_train[i:i+batch_size]\n model.to(device)\n preds = model(X_batch)\n loss = criterion(preds,y_batch)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n model.eval()\n torch.cuda.empty_cache()\n wandb.log({'Loss':(get_loss(model,X_train,y_train,criterion)+get_loss(model,X_batch,y_batch,criterion))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val Loss':get_loss(model,X_test,y_test,criterion)})\n torch.cuda.empty_cache()\n wandb.log({'Acc':(get_accuracy(model,X_train,y_train)+get_accuracy(model,X_batch,y_batch))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val ACC':get_accuracy(model,X_test,y_test)})\n torch.cuda.empty_cache()\n model.train()\nwandb.finish()", "_____no_output_____" ], [ "def get_accuracy(model,X,y):\n preds = model(X)\n correct = 0\n total = 0\n for pred,yb in tqdm(zip(preds,y)):\n pred = int(torch.argmax(pred))\n yb = int(torch.argmax(yb))\n if pred == yb:\n correct += 1\n total += 1\n acc = round(correct/total,3)*100\n return acc", "_____no_output_____" ], [ "model = resnet18().to(device)\nmodel.fc = Linear(512,len(labels))\ncriterion = MSELoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=0.001)\nepochs = 100\nbatch_size = 32", "_____no_output_____" ], [ "wandb.init(project=PROJECT_NAME,name='baseline-TL')\nfor _ in tqdm(range(epochs)):\n for i in range(0,len(X_train),batch_size):\n X_batch = X_train[i:i+batch_size]\n y_batch = y_train[i:i+batch_size]\n model.to(device)\n preds = model(X_batch)\n loss = criterion(preds,y_batch)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n model.eval()\n torch.cuda.empty_cache()\n wandb.log({'Loss':(get_loss(model,X_train,y_train,criterion)+get_loss(model,X_batch,y_batch,criterion))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val Loss':get_loss(model,X_test,y_test,criterion)})\n torch.cuda.empty_cache()\n wandb.log({'Acc':(get_accuracy(model,X_train,y_train)+get_accuracy(model,X_batch,y_batch))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val ACC':get_accuracy(model,X_test,y_test)})\n torch.cuda.empty_cache()\n model.train()\nwandb.finish()", "_____no_output_____" ], [ "class Model(Module):\n def __init__(self):\n super().__init__()\n self.max_pool2d = MaxPool2d((2,2),(2,2))\n self.activation = ReLU()\n self.conv1 = Conv2d(3,7,(5,5))\n self.conv2 = Conv2d(7,14,(5,5))\n self.conv2bn = BatchNorm2d(14)\n self.conv3 = Conv2d(14,21,(5,5))\n self.linear1 = Linear(21*5*5,256)\n self.linear2 = Linear(256,512)\n self.linear2bn = BatchNorm1d(512)\n self.linear3 = Linear(512,256)\n self.output = Linear(256,len(labels))\n \n def forward(self,X):\n preds = self.max_pool2d(self.activation(self.conv1(X)))\n preds = self.max_pool2d(self.activation(self.conv2bn(self.conv2(preds))))\n preds = self.max_pool2d(self.activation(self.conv3(preds)))\n preds = preds.view(-1,21*5*5)\n preds = self.activation(self.linear1(preds))\n preds = self.activation(self.linear2bn(self.linear2(preds)))\n preds = self.activation(self.linear3(preds))\n preds = self.output(preds)\n return preds", "_____no_output_____" ], [ "model = Model().to(device)\ncriterion = MSELoss()\noptimizer = Adam(model.parameters(),lr=0.001)\nepochs = 100\nbathc_size = 32", "_____no_output_____" ], [ "model = Model().to(device)\ncriterion = MSELoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=0.001)\nepochs = 100\nbathc_size = 32", "_____no_output_____" ], [ "wandb.init(project=PROJECT_NAME,name='baseline-CNN')\nfor _ in tqdm(range(epochs)):\n for i in range(0,len(X_train),batch_size):\n X_batch = X_train[i:i+batch_size]\n y_batch = y_train[i:i+batch_size]\n model.to(device)\n preds = model(X_batch)\n loss = criterion(preds,y_batch)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n model.eval()\n torch.cuda.empty_cache()\n wandb.log({'Loss':(get_loss(model,X_train,y_train,criterion)+get_loss(model,X_batch,y_batch,criterion))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val Loss':get_loss(model,X_test,y_test,criterion)})\n torch.cuda.empty_cache()\n wandb.log({'Acc':(get_accuracy(model,X_train,y_train)+get_accuracy(model,X_batch,y_batch))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val ACC':get_accuracy(model,X_test,y_test)})\n torch.cuda.empty_cache()\n model.train()\nwandb.finish()", "_____no_output_____" ], [ "class Model(Module):\n def __init__(self):\n super().__init__()\n self.max_pool2d = MaxPool2d((2,2),(2,2))\n self.activation = ReLU()\n self.conv1 = Conv2d(3,7,(5,5))\n self.conv2 = Conv2d(7,14,(5,5))\n self.conv2bn = BatchNorm2d(14)\n self.conv3 = Conv2d(14,21,(5,5))\n self.linear1 = Linear(21*5*5,256)\n self.linear2 = Linear(256,512)\n self.linear2bn = BatchNorm1d(512)\n self.linear3 = Linear(512,256)\n self.output = Linear(256,len(labels))\n \n def forward(self,X):\n preds = self.max_pool2d(self.activation(self.conv1(X)))\n preds = self.max_pool2d(self.activation(self.conv2bn(self.conv2(preds))))\n preds = self.max_pool2d(self.activation(self.conv3(preds)))\n preds = preds.view(-1,21*3*3)\n preds = self.activation(self.linear1(preds))\n preds = self.activation(self.linear2bn(self.linear2(preds)))\n preds = self.activation(self.linear3(preds))\n preds = self.output(preds)\n return preds", "_____no_output_____" ], [ "model = Model().to(device)\ncriterion = MSELoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=0.001)\nepochs = 100\nbathc_size = 32", "_____no_output_____" ], [ "wandb.init(project=PROJECT_NAME,name='baseline-CNN')\nfor _ in tqdm(range(epochs)):\n for i in range(0,len(X_train),batch_size):\n X_batch = X_train[i:i+batch_size]\n y_batch = y_train[i:i+batch_size]\n model.to(device)\n preds = model(X_batch)\n loss = criterion(preds,y_batch)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n model.eval()\n torch.cuda.empty_cache()\n wandb.log({'Loss':(get_loss(model,X_train,y_train,criterion)+get_loss(model,X_batch,y_batch,criterion))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val Loss':get_loss(model,X_test,y_test,criterion)})\n torch.cuda.empty_cache()\n wandb.log({'Acc':(get_accuracy(model,X_train,y_train)+get_accuracy(model,X_batch,y_batch))/2})\n torch.cuda.empty_cache()\n wandb.log({'Val ACC':get_accuracy(model,X_test,y_test)})\n torch.cuda.empty_cache()\n model.train()\nwandb.finish()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01dd734a7b260548c7256481f87b1f8679f5428
44,557
ipynb
Jupyter Notebook
Artificial-Int.ipynb
danielordonezg/Machine-Learning-Algorithms
d1364852a4f5833b809cf0043cdcc0e04496c3ab
[ "MIT" ]
null
null
null
Artificial-Int.ipynb
danielordonezg/Machine-Learning-Algorithms
d1364852a4f5833b809cf0043cdcc0e04496c3ab
[ "MIT" ]
null
null
null
Artificial-Int.ipynb
danielordonezg/Machine-Learning-Algorithms
d1364852a4f5833b809cf0043cdcc0e04496c3ab
[ "MIT" ]
null
null
null
55.69625
7,086
0.582871
[ [ [ "Caníbales y misioneros\nmediante búsqueda primero en anchura.", "_____no_output_____" ] ], [ [ "from copy import deepcopy\nfrom collections import deque\nimport sys\n\n# (m, c, b) hace referencia a el número de misioneros, canibales y el bote\nclass Estado(object):\n def __init__(self, misioneros, canibales, bote):\n self.misioneros = misioneros\n self.canibales = canibales\n self.bote = bote\n #se establecen los movimientos que estos tendran \n def siguientes(self):\n if self.bote == 1:\n signo = -1\n direction = \"Ida\"\n else:\n signo = 1\n direction = \"Vuelta\"\n for m in range(3):\n for c in range(3):\n nuevo_Estado = Estado(self.misioneros+signo*m, self.canibales+signo*c, self.bote+signo*1);\n if m+c >= 1 and m+c <= 2 and nuevo_Estado.validar(): # comprobar si la acción y el estado resultante son válidos\n accion = \" %d misioneros y %d canibales %s. %r\" % ( m, c, direction, nuevo_Estado) \n yield accion, nuevo_Estado\n \n def validar(self):\n # validacion inicial\n if self.misioneros < 0 or self.canibales < 0 or self.misioneros > 3 or self.canibales > 3 or (self.bote != 0 and self.bote != 1):\n return False \n # luego verifica si los misioneros superan en número a los canibales\n\n # más canibales que misioneros en la orilla original\n if self.canibales > self.misioneros and self.misioneros > 0: \n return False\n # más canibales que misioneros en otra orilla\n if self.canibales < self.misioneros and self.misioneros < 3: \n return False\n return True\n\n# valida estado objetivo\n def estado_final(self):\n return self.canibales == 0 and self.misioneros == 0 and self.bote == 0\n\n\n# funcion para devolver los estados en los que se encuentra\n def __repr__(self):\n return \"< Estado (%d, %d, %d) >\" % (self.misioneros, self.canibales, self.bote)\n\n\n# clase nodo\nclass Nodo(object): #se crea la clase nodo para hacer la relacion con sus adyacencias \n def __init__(self, nodo_pariente, estado, accion, profundidad):\n self.nodo_pariente = nodo_pariente\n self.estado = estado\n self.accion = accion\n self.profundidad = profundidad\n \n\n# metodo expandir\n#Busca lo nodos adyacentes \n def expandir(self):\n for (accion, estado_sig) in self.estado.siguientes():\n nodo_sig = Nodo(\n nodo_pariente=self,\n estado=estado_sig,\n accion=accion,\n profundidad=self.profundidad + 1)\n yield nodo_sig\n \n\n# funcion para guardar y devolver la solucion del problema\n def devolver_solucion(self):\n solucion = []\n nodo = self\n while nodo.nodo_pariente is not None:\n solucion.append(nodo.accion)\n nodo = nodo.nodo_pariente\n solucion.reverse()\n return solucion\n\n\n# metodo BFS - busqueda por anchura\n\ndef BFS(Estado_inicial):\n nodo_inicial = Nodo(\n nodo_pariente=None,\n estado=Estado_inicial,\n accion=None,\n profundidad=0) # Se establece la conexion con los nodos hijos\n \n cola = deque([nodo_inicial]) #se crea la cola\n profundidad_maxima = -1\n while True:\n if not cola:\n return None\n nodo = cola.popleft() \n if nodo.profundidad > profundidad_maxima: #se defienen los nuevos nodos \n profundidad_maxima = nodo.profundidad\n if nodo.estado.estado_final():\n solucion = nodo.devolver_solucion()\n return solucion\n cola.extend(nodo.expandir())\n\n\ndef main(): #Caso prueba \n Estado_inicial = Estado(3,3,1)\n solucion = BFS(Estado_inicial)\n if solucion is None:\n print(\"no tiene solucion\")\n else:\n for pasos in solucion:\n print(\"%s\" % pasos)\n\n\nif __name__ == \"__main__\":\n main()", " 0 misioneros y 2 canibales Ida. < Estado (3, 1, 0) >\n 0 misioneros y 1 canibales Vuelta. < Estado (3, 2, 1) >\n 0 misioneros y 2 canibales Ida. < Estado (3, 0, 0) >\n 0 misioneros y 1 canibales Vuelta. < Estado (3, 1, 1) >\n 2 misioneros y 0 canibales Ida. < Estado (1, 1, 0) >\n 1 misioneros y 1 canibales Vuelta. < Estado (2, 2, 1) >\n 2 misioneros y 0 canibales Ida. < Estado (0, 2, 0) >\n 0 misioneros y 1 canibales Vuelta. < Estado (0, 3, 1) >\n 0 misioneros y 2 canibales Ida. < Estado (0, 1, 0) >\n 0 misioneros y 1 canibales Vuelta. < Estado (0, 2, 1) >\n 0 misioneros y 2 canibales Ida. < Estado (0, 0, 0) >\n" ] ], [ [ "Función en Python que reciba un grafo, un nodo inicial y un nodo final y devuelva la ruta del nodo inicial al nodo final utilizando búsqueda primero en profundidad. Se deben crear las clases Grafo y Nodo con sus respectivos métodos y atributos. La función debe retornar None en caso de que no haya ninguna ruta posible.\n", "_____no_output_____" ] ], [ [ "class Enlace:\n #pendientes\n def __init__(self, a=None, b=None):\n self.a = a\n self.b = b\n\n def __eq__(self, other):\n return self.a == other.a and self.b == other.b\n\n def __str__(self):\n return \"(\" + str(self.a) + \",\" + str(self.b) + \")\"\n\n def __repr__(self):\n return self.__str__()\n\nclass Nodo:\n\n def __init__(self, padre=None, nombre=\"\"):\n self.padre = padre\n self.nombre = nombre\n\n def __eq__(self, other):\n return self.nombre == other.nombre\n\n def __str__(self):\n return self.nombre\n\n def __repr__(self):\n return self.__str__()\n\nclass Grafo: #se crea el grafo con los nodos y enlaces entre si \n def __init__(self, nodos=[], enlaces=[]):\n self.nodos = nodos\n self.enlaces = enlaces\n\n def __str__(self):\n return \"Nodos : \" + str(self.nodos) + \" Enlaces : \" + str(self.enlaces)\n\n def __repr__(self):\n return self.__str__()\n\ndef hallarRuta(grafo, nodoInicial, nodoFinal): #Se halla el recorrido final del grafo \n actual = nodoInicial\n p=[actual]\n estadoFinal = nodoFinal\n \n visitados = [actual]\n rutaFinal=[]\n\n while len(p) > 0: # se verifica que el grafo no este vacio, que a este llegen los nodos adyacentes\n if (actual!=estadoFinal):\n siguiente = generar_siguiente(actual, grafo, visitados)\n if siguiente != Nodo(nombre=\"\"):\n p.append(siguiente)\n actual = p[len(p)-1]\n visitados.append(actual)#se toma cómo agrega a la \"ruta\" de visitados el nodo en el que nos hallamos\n else:\n p.pop()\n actual = p[len(p)-1]\n else:\n while len(p) > 0:\n \n rutaFinal.insert(0,p.pop())#finalmente se le insertan todos todos los visitados a rutaFinal \n break\n \n print(\"La ruta final es\")\n print(rutaFinal)\n\n\ndef generar_siguiente(actual, grafo, visitados):# una ves visitado uno de los nodos, pasa al siguiente nodo, al siguiente hijo\n #comprueba si este nodo ya fue visitado o no\n for i in range(len(grafo.enlaces)):\n if actual.nombre == grafo.enlaces[i].a:\n\n nodoSiguiente = Nodo(padre=actual.nombre, nombre=grafo.enlaces[i].b)\n if nodoSiguiente not in visitados:\n \n return nodoSiguiente\n break\n return Nodo(nombre=\"\")\n\n#EJEMPLO\n#acontinuación se definen las adyacencia del grafo a consultar el recorrrido\nnodos = [Nodo(nombre=\"A\"),Nodo(nombre=\"B\"),Nodo(nombre=\"C\"),Nodo(nombre=\"D\"),Nodo(nombre=\"F\"),Nodo(nombre=\"E\")]\nE1 = Enlace(a = \"A\", b = \"C\" )\nE2 = Enlace(a = \"A\", b = \"D\" )\nE3 = Enlace(a = \"A\", b = \"F\" )\nE4 = Enlace(a = \"B\", b = \"E\" )\nE5 = Enlace(a = \"C\", b = \"F\" )\nE6 = Enlace(a = \"D\", b = \"E\" )\nE7 = Enlace(a = \"E\", b = \"F\" )\nenlaces = [E1,E2,E3,E4,E5,E6,E7]\ngrafo = Grafo(nodos=nodos,enlaces=enlaces)\nnodoA = Nodo(nombre=\"A\")\nnodoB = Nodo(nombre=\"F\")\n\nruta = hallarRuta(grafo, nodoA, nodoB)\n\nprint(ruta)", "La ruta final es\n[A, C, F]\nNone\n" ] ], [ [ "\nDesarrollar un programa en Python que solucione el problema del rompecabezas des-\nlizante para 8 números utilizando búsqueda en anchura . El programa debe leer el\n\nestado inicial desde un archivo. Algunas configuraciones no tienen solución.", "_____no_output_____" ] ], [ [ "class Estados():\n def __init__(self,Mat,Npadre=None):\n self.Npadre=Npadre\n self.Mat=Mat\n \n #Mat=[[0 1 2],[3 4 5],[6 7 8]]\n \n def BuscZ(self): #Buscar el 0 dentro de la matriz\n itera=0\n Pos=[]\n for y,i in enumerate(self.Mat):\n if 0 in i:\n itera+=1\n Pos.append(y)\n Pos.append(i.index(0))\n#Funcion Busca 0\n return Pos\n#prueba=Estados([[1,2,0],[3,4,5],[6,7,8]])\n#prueba.BuscZ()\n\n\n#Buscar Hijos- Movimientos\n def BuscaH():\n #arriba\n \n #abajo\n\n #derecha\n\n #izquierda", "_____no_output_____" ] ], [ [ "\nDesarrollar un programa en Python que encuentre la ruta de salida en un laberinto representado por una matriz de 0 y 1. Un 0 significa que se puede pasar por esa casilla un 1 representa que hay pared en dicha casilla y 2 que es la salida. El programa debe leer la configuración del laberinto desde un archivo, solicitar al usuario el estado inicial y dibujar el laberinto con la ruta de salida. Se debe utilizar búsqueda primero en profundidad.\n", "_____no_output_____" ] ], [ [ "\n#creacion de ambiente\nfrom IPython.display import display\nimport ipywidgets as widgets\nimport time\nimport random\n\n# se crea el tablero\nclass Tablero:\n def __init__(self, tamanoCelda=(40, 40), nCeldas=(5,5)): #dimensiones del tablero\n self.out = widgets.HTML()\n display(self.out)\n self.tamanoCelda = tamanoCelda\n self.nCeldas = nCeldas\n\n def dibujar(self, agente , trashes, obstaculos,pila=[]):\n \n tablero = \"<h1 style='color:green'>Encuentra la salida </h1>\"\n tablero+=\"<br>\"\n tablero += \"<table border='1' >{}</table>\"\n \n filas = \"\"\n for i in range(self.nCeldas[0]):\n s = \"\"\n for j in range(self.nCeldas[1]):\n \n agenteaux = Agente(x = j, y = i)\n \n if agente == agenteaux:\n contenido = \\\n \"<span style='font-size:{tamanoEmoticon}px;'>{emoticon}</span>\".\\\n format(tamanoEmoticon=agente.tamanoEmoticon, emoticon=agente.emoticon)\n\n elif agenteaux in trashes:\n index = trashes.index(agenteaux)\n contenido = \\\n \"<span style='font-size:{tamanoEmoticon}px;'>{emoticon}</span>\".\\\n format(tamanoEmoticon=trashes[index].tamanoEmoticon, emoticon=trashes[index].emoticon)\n elif agenteaux in obstaculos:\n index = obstaculos.index(agenteaux)\n contenido = \\\n \"<span style='font-size:{tamanoEmoticon}px;'>{emoticon}</span>\".\\\n format(tamanoEmoticon=obstaculos[index].tamanoEmoticon, emoticon=obstaculos[index].emoticon)\n elif Nodo(x=j,y=i) in pila:\n contenido = \\\n \"<span style='font-size:{tamanoEmoticon}px;'>{emoticon}</span>\".\\\n format(tamanoEmoticon=30, emoticon=\"👣\")\n \n else:\n contenido=\"\"\n \n \n s += \"<td style='height:{alto}px;width:{ancho}px'>{contenido}</td>\".\\\n format(alto=self.tamanoCelda[0], ancho=self.tamanoCelda[1], \n contenido=contenido)\n filas += \"<tr>{}</tr>\".format(s)\n tablero = tablero.format(filas)\n \n self.out.value=tablero\n return trashes\n\n#Agente\n#se crea la clase agente y los movimientos que este tendra\nclass Agente:\n def __init__(self, x=2, y=2, emoticon=\"🧍‍♂️\", tamanoEmoticon=30): #estado inicial del agente \n self.x = x\n self.y = y\n self.emoticon = emoticon\n self.tamanoEmoticon = tamanoEmoticon\n\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n\n def __str__(self):\n return \"(\"+str(self.x)+\",\"+str(self.y)+\",\"+self.emoticon+\")\"\n\n def __repr__(self):\n return self.__str__()\n#se definen los movimientos que tendra el agente \n#movimientos en \"X\" y en \"Y\" respectivamente\n\n def Abajo(self): # movimiento hacia abajo\n self.y += 1\n\n def Arriba(self): #movimiento hacia arriba\n self.y -= 1\n\n def Derecha(self): #movimiento hacia la derecha \n self.x += 1\n\n def Izquierda(self): #Movimiento hacia la izquierda\n self.x -= 1\n\nclass Nodo: # se define la clase nodo \n\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n \n def __eq__(self, other):\n return self.x == other.x and self.y==other.y\n\n def __str__(self):\n return str(\"(posX: \"+str(self.x)+\", posY: \"+str(self.y)+\")\")\n\n def __repr__(self):\n return self.__str__()\n\ndef generar_siguiente(actual, visitados): #se comprueba si la posicion ya fue visitado o no, si ya lo fue busca otro nodo\n posx=int(actual.x)\n posy=int(actual.y)\n if posy < len(nombres)-1:\n #Movimiento hacia abajo\n Abajo=int(arreglo[posy+1][posx])\n if Abajo==0 or Abajo==2:\n Siguiente=Nodo(x=posx,y=posy+1)\n if Siguiente not in visitados:\n return Siguiente\n #Movimiento hacia la derecha \n if posx < len(nombres)-1 :\n Derecha=int(arreglo[posy][posx+1])\n if Derecha==0 or Derecha==2:\n Siguiente=Nodo(x=posx+1,y=posy)\n if Siguiente not in visitados:\n return Siguiente\n if posy > 0 :\n #MOVIMIENTO HACIA ARRIBA, MIENTRAS QUE NI SE SAlGA SE LAS DIMENSIONES \n Arriba=int(arreglo[posy-1][posx])\n if Arriba==0 or Arriba==2:\n Siguiente=Nodo(x=posx,y=posy-1)\n if Siguiente not in visitados:\n return Siguiente\n if posx>0:\n #MOVIMIENTO HACIA LA IZQUIERDA, HASTA EL BORDE DEL ESCENARIO \n Izq=int(arreglo[posy][posx-1])\n if Izq==0 or Izq==2:\n Siguiente=Nodo(x=posx-1,y=posy)\n if Siguiente not in visitados:\n return Siguiente\n\n\n return Nodo(x=-1,y=-1)\n\ndef HallarRuta(agente , elementos): # SE DEFINE LA FUNCION, LA CUAL NOS AYUDARA A BUSCAR LA SALIDA DEL LABERINTO\n escenario=elementos[0]\n # print(arreglo)\n for i in range(len(arreglo)):# se recorre \n nombres.append(i)\n \n #rSE RECORRE TODO EL GRAFO PARA SABER EL NODO FINAL \n\n estadoFinal=Nodo() \n for i in range(len(nombres)):\n arreglito=arreglo[i]\n for j in range(len(arreglito)):\n if int(arreglito[j])==2:\n estadoFinal=Nodo(x=i,y=j)\n \n actual = Nodo(x=agente.x,y=agente.y)\n visitados = [actual]\n pila=[actual]\n\n while len(pila)!=0 and actual != estadoFinal: # MIENTRAS LA PILA EN LA QUE SE ALMACENAN LOS NO CONSULTADOS NO SEA 0\n \n#Se busca el siguiente nodo, ignorando los ya visitados\n\n siguienteNodo=generar_siguiente(actual,visitados)\n if siguienteNodo != Nodo(x=-1,y=-1):\n pila.append(siguienteNodo)# el nodo actual pasa a ser visitado \n actual=siguienteNodo # se busca un nuevo nodo \n agente.x=int(actual.x)\n agente.y=int(actual.y)\n visitados.append(actual)\n else:\n pila.pop()\n actual=pila[len(pila)-1]\n agente.x=int(actual.x)\n agente.y=int(actual.y)\n\n escenario.dibujar(agente, elementos[1], elementos[2],pila) # se dibuja el escenario \n time.sleep(1) # tiempo de retraso\n\n\n#Importar para leer archivo csv\nfrom google.colab import files\nfiles.upload()\nimport csv, operator\n\ndef obtenerArregloArchivo():\n Trashes=[]\n Obstaculos=[]\n cont=0\n with open('EscenarioPunto#4.csv') as csvarchivo:\n entrada = csv.reader(csvarchivo)\n arreglo= []\n for reg in entrada:\n arreglo.append(reg)\n if cont == 0:\n cantfilas = len(reg)\n for i in range(len(reg)):\n if len(reg) == 1:\n agente.energia = int(reg[0])\n else:\n if reg[i] == '1':\n Obstaculos.append(Agente(x=i , y=cont , emoticon=\"⛓️\" ))\n if reg[i] == '2':\n Trashes.append(Agente(x=i , y=cont , emoticon=\"🥇\" ))\n cont+=1\n escenario = Tablero(nCeldas=(cont,cantfilas)) \n elementos = [escenario , Trashes, Obstaculos, agente, arreglo]\n \n return elementos\n \n \n#crearEscenarioArchivo()\n\n#Posicion inicil del agente \nposx = input(\" X: \")\nposy = input(\" Y: \")\n\nnombres=[]\nagente = Agente(x=int(posx), y = int(posy))\nelementos = obtenerArregloArchivo()\narreglo=elementos[4]\nruta = HallarRuta(agente , elementos)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d01de31667004b09c034530f5731917cb7ee4526
3,621
ipynb
Jupyter Notebook
Prelim_Exam.ipynb
MishcaGestoso/Linear-Algebra-58019
4fe7b7d1c6d832958b545b6e2936a6a05deec671
[ "Apache-2.0" ]
1
2021-10-16T04:10:28.000Z
2021-10-16T04:10:28.000Z
Prelim_Exam.ipynb
MishcaGestoso/Linear-Algebra-58019
4fe7b7d1c6d832958b545b6e2936a6a05deec671
[ "Apache-2.0" ]
null
null
null
Prelim_Exam.ipynb
MishcaGestoso/Linear-Algebra-58019
4fe7b7d1c6d832958b545b6e2936a6a05deec671
[ "Apache-2.0" ]
null
null
null
23.36129
242
0.418117
[ [ [ "<a href=\"https://colab.research.google.com/github/MishcaGestoso/Linear-Algebra-58019/blob/main/Prelim_Exam.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "###Prelim Exam", "_____no_output_____" ], [ "Question 1.\nA 4 x 4 matrix whose diagonal elements are all one (1's)", "_____no_output_____" ] ], [ [ "import numpy as np\nA = np.array([1,1,1,1,])\nC = np.diag(A)\nprint (C)", "[[1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]]\n" ] ], [ [ "Question 2. doubles all the values of each element.", "_____no_output_____" ] ], [ [ "import numpy as np\nA = np.array([1, 1, 1, 1])\nB = np.diag(A)\nprint (C*2) #To double the value of array C\n", "[[2 0 0 0]\n [0 2 0 0]\n [0 0 2 0]\n [0 0 0 2]]\n" ] ], [ [ "Question 3. The cross-product of matrices, A = [2,7,4] and B = [3,9,8]\n\n", "_____no_output_____" ] ], [ [ "import numpy as np\nA = np.array([2, 7, 4])\nB = np.array([3, 9, 8])\n#To compute the cross of arrays A and B\ncross = np.cross(A,B)\nprint(cross)", "[20 -4 -3]\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01df7a244afec4c7e856b922568a390cbb7c5c5
6,399
ipynb
Jupyter Notebook
Config.ipynb
rcaudill/SkyScan
eb7ab338b11e9aaedc821880a44ee4468ebcad8a
[ "Apache-2.0" ]
223
2021-01-12T23:19:05.000Z
2022-03-19T14:25:24.000Z
Config.ipynb
rcaudill/SkyScan
eb7ab338b11e9aaedc821880a44ee4468ebcad8a
[ "Apache-2.0" ]
16
2021-01-22T19:35:46.000Z
2022-01-28T03:57:04.000Z
Config.ipynb
rcaudill/SkyScan
eb7ab338b11e9aaedc821880a44ee4468ebcad8a
[ "Apache-2.0" ]
18
2020-12-18T02:41:30.000Z
2022-02-24T18:01:09.000Z
22.452632
231
0.544148
[ [ [ "# SkyScan Config\nMake temporary changes to a running SkyScan instance. It will revert back to the values in the environment file when restart.", "_____no_output_____" ] ], [ [ "broker=\"192.168.1.47\" # update with the IP for the Raspberry PI", "_____no_output_____" ], [ "!pip install paho-mqtt", "Requirement already satisfied: paho-mqtt in /Users/lberndt/opt/anaconda3/lib/python3.8/site-packages (1.5.0)\r\n" ], [ "import paho.mqtt.client as mqtt\nimport json", "_____no_output_____" ], [ "client = mqtt.Client(\"notebook-config\")", "_____no_output_____" ] ], [ [ "## Camera Zoom\nThis is how much the camera is zoomed in. It is an Int number between 0-9999 (max)", "_____no_output_____" ] ], [ [ "client.connect(broker)\ndata = {}\ndata['cameraZoom'] = 9999 # Update this Value\njson_data = json.dumps(data)\nclient.publish(\"skyscan/config/json\",json_data)", "_____no_output_____" ] ], [ [ "## Camera Delay\nFloat value for the number of seconds to wait after sending the camera move API command, before sending the take picture API command.", "_____no_output_____" ] ], [ [ "client.connect(broker)\ndata = {}\ndata['cameraDelay'] = 0.25 # Update this Value\njson_data = json.dumps(data)\nclient.publish(\"skyscan/config/json\",json_data)", "_____no_output_____" ] ], [ [ "## Camera Move Speed\nThis is how fast the camea will move. It is an Int number between 0-99 (max)", "_____no_output_____" ] ], [ [ "client.connect(broker)\ndata = {}\ndata['cameraMoveSpeed'] = 99 # Update this Value\njson_data = json.dumps(data)\nclient.publish(\"skyscan/config/json\",json_data)", "_____no_output_____" ] ], [ [ "## Camera Lead\nThis is how far the tracker should move the center point in front of the currently tracked plane. It is a float, and is measured in seconds, example: 0.25 . It is based on the planes current heading and how fast it is going. ", "_____no_output_____" ] ], [ [ "client.connect(broker)\ndata = {}\ndata['cameraLead'] = 0.45 # Update this Value\njson_data = json.dumps(data)\nclient.publish(\"skyscan/config/json\",json_data)", "_____no_output_____" ] ], [ [ "## Camera Bearing\nThis is a float to correct the cameras heading to help it better align with True North. It can be from -180 to 180. ", "_____no_output_____" ] ], [ [ "client.connect(broker)\ndata = {}\ndata['cameraBearing'] = -2 # Update this Value\njson_data = json.dumps(data)\nclient.publish(\"skyscan/config/json\",json_data)", "_____no_output_____" ] ], [ [ "## Minimum Elevation\nThe minimum elevation above the horizon which the Tracker will follow an airplane. Int value between 0-90 degrees.", "_____no_output_____" ] ], [ [ "client.connect(broker)\ndata = {}\ndata['minElevation'] = 45 # Update this Value\njson_data = json.dumps(data)\nclient.publish(\"skyscan/config/json\",json_data)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01dfbe54c1534021e20fc222cb015a111a629ab
95,369
ipynb
Jupyter Notebook
analyze_stock_growth_per_industry.ipynb
pritishyuvraj/profit-from-stock
b66d1988c4fd209687900f04015b0ddef0f4b35b
[ "MIT" ]
null
null
null
analyze_stock_growth_per_industry.ipynb
pritishyuvraj/profit-from-stock
b66d1988c4fd209687900f04015b0ddef0f4b35b
[ "MIT" ]
null
null
null
analyze_stock_growth_per_industry.ipynb
pritishyuvraj/profit-from-stock
b66d1988c4fd209687900f04015b0ddef0f4b35b
[ "MIT" ]
null
null
null
40.825771
98
0.397886
[ [ [ "import pandas as pd \nfrom pprint import pprint ", "_____no_output_____" ], [ "database_location = \"/Users/pyuvraj/CCPP/data_for_profit_from_stock/stock_per_category\"\ndatabase_name = \"all_stocks_data_with_ranking.csv\"", "_____no_output_____" ], [ "database = pd.read_csv(database_location + \"/\" + database_name)", "_____no_output_____" ], [ "list(database)", "_____no_output_____" ], [ "del database['Unnamed: 0']", "_____no_output_____" ], [ "print(database)", " Symbol Name Last Sale \\\n0 A Agilent Technologies Inc. Common Stock $155.70 \n1 AA Alcoa Corporation Common Stock $40.71 \n2 AAL American Airlines Group Inc. Common Stock $21.02 \n3 AAMC Altisource Asset Management Corp Com $15.64 \n4 AAME Atlantic American Corporation Common Stock $4.53 \n... ... ... ... \n3690 ZNH China Southern Airlines Company Limited Common... $25.78 \n3691 ZSAN Zosano Pharma Corporation Common Stock $0.7736 \n3692 ZTR Virtus Total Return Fund Inc. $9.84 \n3693 ZUO Zuora Inc. Class A Common Stock $16.18 \n3694 ZYNE Zynerba Pharmaceuticals Inc. Common Stock $4.44 \n\n Net Change % Change Market Cap Country IPO Year Volume \\\n0 0.6600 0.426% 4.724611e+10 United States 1999.0 1209255 \n1 1.9600 5.058% 7.607321e+09 NaN 2016.0 6141478 \n2 0.1100 0.526% 1.360956e+10 United States NaN 28254416 \n3 0.6000 3.989% 3.203571e+07 United States NaN 9312 \n4 0.2900 6.84% 9.248349e+07 United States NaN 28547 \n... ... ... ... ... ... ... \n3690 0.2800 1.098% 7.903819e+09 China 1997.0 13875 \n3691 0.0235 3.133% 8.256507e+07 United States 2015.0 658697 \n3692 0.1200 1.235% 2.426802e+08 United States 1988.0 85161 \n3693 -0.2900 -1.761% 1.978814e+09 NaN 2018.0 1646779 \n3694 -0.0900 -1.987% 1.831568e+08 United States 2015.0 332826 \n\n Sector Industry stock_name stock_growth \n0 Capital Goods Electrical Products A 68.540905 \n1 Basic Industries Aluminum AA -12.964433 \n2 Transportation Air Freight/Delivery Services AAL -40.173583 \n3 Finance Investment Managers AAMC 175.465860 \n4 Finance Life Insurance AAME -54.365260 \n... ... ... ... ... \n3690 Transportation Air Freight/Delivery Services ZNH 1.850460 \n3691 Health Care Major Pharmaceuticals ZSAN -209.998420 \n3692 Finance Investment Managers ZTR -14.345879 \n3693 Technology EDP Services ZUO 159.067875 \n3694 Health Care Major Pharmaceuticals ZYNE -33.255809 \n\n[3695 rows x 13 columns]\n" ], [ "g = database.groupby(['Industry'])", "_____no_output_____" ], [ "dir(g.Industry)", "_____no_output_____" ], [ "database.sort_values(['stock_growth'], ascending=True).groupby(['Sector']).head(3)\n", "_____no_output_____" ], [ "pprint(set(database['Industry']))", "{'Accident &Health Insurance',\n 'Advertising',\n 'Aerospace',\n 'Agricultural Chemicals',\n 'Air Freight/Delivery Services',\n 'Aluminum',\n 'Apparel',\n 'Assisted Living Services',\n 'Auto Manufacturing',\n 'Auto Parts:O.E.M.',\n 'Automotive Aftermarket',\n 'Banks',\n 'Beverages (Production/Distribution)',\n 'Biotechnology: Biological Products (No Diagnostic Substances)',\n 'Biotechnology: Commercial Physical & Biological Resarch',\n 'Biotechnology: Electromedical & Electrotherapeutic Apparatus',\n 'Biotechnology: In Vitro & In Vivo Diagnostic Substances',\n 'Biotechnology: Laboratory Analytical Instruments',\n 'Books',\n 'Broadcasting',\n 'Building Materials',\n 'Building Products',\n 'Building operators',\n 'Business Services',\n 'Catalog/Specialty Distribution',\n 'Clothing/Shoe/Accessory Stores',\n 'Coal Mining',\n 'Commercial Banks',\n 'Computer Communications Equipment',\n 'Computer Manufacturing',\n 'Computer Software: Prepackaged Software',\n 'Computer Software: Programming Data Processing',\n 'Computer peripheral equipment',\n 'Construction/Ag Equipment/Trucks',\n 'Consumer Electronics/Appliances',\n 'Consumer Electronics/Video Chains',\n 'Consumer Specialties',\n 'Containers/Packaging',\n 'Department/Specialty Retail Stores',\n 'Diversified Commercial Services',\n 'Diversified Financial Services',\n 'Diversified Manufacture',\n 'EDP Peripherals',\n 'EDP Services',\n 'Electric Utilities: Central',\n 'Electrical Products',\n 'Electronic Components',\n 'Electronics Distribution',\n 'Engineering & Construction',\n 'Environmental Services',\n 'Farming/Seeds/Milling',\n 'Finance Companies',\n 'Finance/Investors Services',\n 'Finance: Consumer Services',\n 'Fluid Controls',\n 'Food Chains',\n 'Food Distributors',\n 'Forest Products',\n 'Home Furnishings',\n 'Homebuilding',\n 'Hospital/Nursing Management',\n 'Hotels/Resorts',\n 'Industrial Machinery/Components',\n 'Industrial Specialties',\n 'Integrated oil Companies',\n 'Internet and Information Services',\n 'Investment Bankers/Brokers/Service',\n 'Investment Managers',\n 'Life Insurance',\n 'Major Banks',\n 'Major Chemicals',\n 'Major Pharmaceuticals',\n 'Managed Health Care',\n 'Marine Transportation',\n 'Meat/Poultry/Fish',\n 'Medical Electronics',\n 'Medical Specialities',\n 'Medical/Dental Instruments',\n 'Medical/Nursing Services',\n 'Metal Fabrications',\n 'Military/Government/Technical',\n 'Mining & Quarrying of Nonmetallic Minerals (No Fuels)',\n 'Motor Vehicles',\n 'Movies/Entertainment',\n 'Multi-Sector Companies',\n 'Natural Gas Distribution',\n 'Newspapers/Magazines',\n 'Office Equipment/Supplies/Services',\n 'Oil & Gas Production',\n 'Oil Refining/Marketing',\n 'Oil/Gas Transmission',\n 'Oilfield Services/Equipment',\n 'Ophthalmic Goods',\n 'Ordnance And Accessories',\n 'Other Consumer Services',\n 'Other Metals and Minerals',\n 'Other Pharmaceuticals',\n 'Other Specialty Stores',\n 'Package Goods/Cosmetics',\n 'Packaged Foods',\n 'Paints/Coatings',\n 'Paper',\n 'Plastic Products',\n 'Pollution Control Equipment',\n 'Power Generation',\n 'Precious Metals',\n 'Professional Services',\n 'Property-Casualty Insurers',\n 'Publishing',\n 'RETAIL: Building Materials',\n 'Radio And Television Broadcasting And Communications Equipment',\n 'Railroads',\n 'Real Estate',\n 'Real Estate Investment Trusts',\n 'Recreational Products/Toys',\n 'Rental/Leasing Companies',\n 'Restaurants',\n 'Retail: Computer Software & Peripheral Equipment',\n 'Savings Institutions',\n 'Semiconductors',\n 'Service to the Health Industry',\n 'Services-Misc. Amusement & Recreation',\n 'Shoe Manufacturing',\n 'Specialty Chemicals',\n 'Specialty Foods',\n 'Specialty Insurers',\n 'Steel/Iron Ore',\n 'Telecommunications Equipment',\n 'Television Services',\n 'Textiles',\n 'Tobacco',\n 'Tools/Hardware',\n 'Transportation Services',\n 'Trucking Freight/Courier Services',\n 'Trusts Except Educational Religious and Charitable',\n 'Water Supply',\n 'Wholesale Distributors'}\n" ], [ "growth_per_Industry = database.groupby('Industry').mean()", "_____no_output_____" ], [ "growth_per_Industry.sort_values(by=['stock_growth'], ascending=False).head(10)", "_____no_output_____" ], [ "database.sort_values(['stock_growth'], ascending=False).head(40)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01e0bcc5c2930017cf0606210fb5aef017b0313
758,159
ipynb
Jupyter Notebook
docs/tutorials/coeval_cubes.ipynb
daviesje/21cmFAST
f36885a813ace72f34c881d80473208d06e3829a
[ "MIT" ]
28
2019-10-02T08:48:13.000Z
2022-03-10T08:02:28.000Z
docs/tutorials/coeval_cubes.ipynb
daviesje/21cmFAST
f36885a813ace72f34c881d80473208d06e3829a
[ "MIT" ]
232
2019-06-13T22:36:21.000Z
2022-03-30T15:45:06.000Z
docs/tutorials/coeval_cubes.ipynb
daviesje/21cmFAST
f36885a813ace72f34c881d80473208d06e3829a
[ "MIT" ]
21
2019-06-14T16:53:26.000Z
2022-03-29T19:50:17.000Z
478.032156
173,848
0.941742
[ [ [ "# Running and Plotting Coeval Cubes", "_____no_output_____" ], [ "The aim of this tutorial is to introduce you to how `21cmFAST` does the most basic operations: producing single coeval cubes, and visually verifying them. It is a great place to get started with `21cmFAST`.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport os\n# We change the default level of the logger so that\n# we can see what's happening with caching.\nimport logging, sys, os\nlogger = logging.getLogger('21cmFAST')\nlogger.setLevel(logging.INFO)\n\nimport py21cmfast as p21c\n\n# For plotting the cubes, we use the plotting submodule:\nfrom py21cmfast import plotting\n\n# For interacting with the cache\nfrom py21cmfast import cache_tools\n\n", "_____no_output_____" ], [ "print(f\"Using 21cmFAST version {p21c.__version__}\")", "Using 21cmFAST version 3.0.2\n" ] ], [ [ "Clear the cache so that we get the same results for the notebook every time (don't worry about this for now). Also, set the default output directory to `_cache/`:", "_____no_output_____" ] ], [ [ "if not os.path.exists('_cache'):\n os.mkdir('_cache')\n \np21c.config['direc'] = '_cache'\ncache_tools.clear_cache(direc=\"_cache\")", "2020-10-02 09:51:10,651 | INFO | Removed 0 files from cache.\n" ] ], [ [ "## Basic Usage", "_____no_output_____" ], [ "The simplest (and typically most efficient) way to produce a coeval cube is simply to use the `run_coeval` method. This consistently performs all steps of the calculation, re-using any data that it can without re-computation or increased memory overhead.", "_____no_output_____" ] ], [ [ "coeval8, coeval9, coeval10 = p21c.run_coeval(\n redshift = [8.0, 9.0, 10.0],\n user_params = {\"HII_DIM\": 100, \"BOX_LEN\": 100, \"USE_INTERPOLATION_TABLES\": True},\n cosmo_params = p21c.CosmoParams(SIGMA_8=0.8),\n astro_params = p21c.AstroParams({\"HII_EFF_FACTOR\":20.0}),\n random_seed=12345\n)", "_____no_output_____" ] ], [ [ "There are a number of possible inputs for `run_coeval`, which you can check out either in the [API reference](../reference/py21cmfast.html) or by calling `help(p21c.run_coeval)`. Notably, the `redshift` must be given: it can be a single number, or a list of numbers, defining the redshift at which the output coeval cubes will be defined. \n\nOther params we've given here are `user_params`, `cosmo_params` and `astro_params`. These are all used for defining input parameters into the backend C code (there's also another possible input of this kind; `flag_options`). These can be given either as a dictionary (as `user_params` has been), or directly as a relevant object (like `cosmo_params` and `astro_params`). If creating the object directly, the parameters can be passed individually or via a single dictionary. So there's a lot of flexibility there! Nevertheless we *encourage* you to use the basic dictionary. The other ways of passing the information are there so we can use pre-defined objects later on. For more information about these \"input structs\", see the [API docs](../reference/_autosummary/py21cmfast.inputs.html).\n\nWe've also given a `direc` option: this is the directory in which to search for cached data (and also where cached data should be written). Throughout this notebook we're going to set this directly to the `_cache` folder, which allows us to manage it directly. By default, the cache location is set in the global configuration in `~/.21cmfast/config.yml`. You'll learn more about caching further on in this tutorial. \n\nFinally, we've given a random seed. This sets all the random phases for the simulation, and ensures that we can exactly reproduce the same results on every run. \n\nThe output of `run_coeval` is a list of `Coeval` instances, one for each input redshift (it's just a single object if a single redshift was passed, not a list). They store *everything* related to that simulation, so that it can be completely compared to other simulations. \n\nFor example, the input parameters:", "_____no_output_____" ] ], [ [ "print(\"Random Seed: \", coeval8.random_seed)\nprint(\"Redshift: \", coeval8.redshift)\nprint(coeval8.user_params)", "Random Seed: 12345\nRedshift: 8.0\nUserParams(BOX_LEN:100, DIM:300, HII_DIM:100, HMF:1, POWER_SPECTRUM:0, USE_FFTW_WISDOM:False, USE_RELATIVE_VELOCITIES:False)\n" ] ], [ [ "This is where the utility of being able to pass a *class instance* for the parameters arises: we could run another iteration of coeval cubes, with the same user parameters, simply by doing `p21c.run_coeval(user_params=coeval8.user_params, ...)`.\n\nAlso in the `Coeval` instance are the various outputs from the different steps of the computation. You'll see more about what these steps are further on in the tutorial. But for now, we show that various boxes are available:", "_____no_output_____" ] ], [ [ "print(coeval8.hires_density.shape)\nprint(coeval8.brightness_temp.shape)", "(300, 300, 300)\n(100, 100, 100)\n" ] ], [ [ "Along with these, full instances of the output from each step are available as attributes that end with \"struct\". These instances themselves contain the `numpy` arrays of the data cubes, and some other attributes that make them easier to work with:", "_____no_output_____" ] ], [ [ "coeval8.brightness_temp_struct.global_Tb", "_____no_output_____" ] ], [ [ "By default, each of the components of the cube are cached to disk (in our `_cache/` folder) as we run it. However, the `Coeval` cube itself is _not_ written to disk by default. Writing it to disk incurs some redundancy, since that data probably already exists in the cache directory in seperate files. \n\nLet's save to disk. The save method by default writes in the current directory (not the cache!):", "_____no_output_____" ] ], [ [ "filename = coeval8.save(direc='_cache')", "_____no_output_____" ] ], [ [ "The filename of the saved file is returned:", "_____no_output_____" ] ], [ [ "print(os.path.basename(filename))", "Coeval_z8.0_a3c7dea665420ae9c872ba2fab1b3d7d_r12345.h5\n" ] ], [ [ "Such files can be read in:", "_____no_output_____" ] ], [ [ "new_coeval8 = p21c.Coeval.read(filename, direc='.')", "_____no_output_____" ] ], [ [ "Some convenient plotting functions exist in the `plotting` module. These can work directly on `Coeval` objects, or any of the output structs (as we'll see further on in the tutorial). By default the `coeval_sliceplot` function will plot the `brightness_temp`, using the standard traditional colormap:", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(1,3, figsize=(14,4))\nfor i, (coeval, redshift) in enumerate(zip([coeval8, coeval9, coeval10], [8,9,10])):\n plotting.coeval_sliceplot(coeval, ax=ax[i], fig=fig);\n plt.title(\"z = %s\"%redshift)\nplt.tight_layout()", "_____no_output_____" ] ], [ [ "Any 3D field can be plotted, by setting the `kind` argument. For example, we could alternatively have plotted the dark matter density cubes perturbed to each redshift:", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(1,3, figsize=(14,4))\nfor i, (coeval, redshift) in enumerate(zip([coeval8, coeval9, coeval10], [8,9,10])):\n plotting.coeval_sliceplot(coeval, kind='density', ax=ax[i], fig=fig);\n plt.title(\"z = %s\"%redshift)\nplt.tight_layout()", "_____no_output_____" ] ], [ [ "To see more options for the plotting routines, see the [API Documentation](../reference/_autosummary/py21cmfast.plotting.html).", "_____no_output_____" ], [ "`Coeval` instances are not cached themselves -- they are containers for data that is itself cached (i.e. each of the `_struct` attributes of `Coeval`). See the [api docs](../reference/_autosummary/py21cmfast.outputs.html) for more detailed information on these. \n\nYou can see the filename of each of these structs (or the filename it would have if it were cached -- you can opt to *not* write out any given dataset):", "_____no_output_____" ] ], [ [ "coeval8.init_struct.filename", "_____no_output_____" ] ], [ [ "You can also write the struct anywhere you'd like on the filesystem. This will not be able to be automatically used as a cache, but it could be useful for sharing files with colleagues.", "_____no_output_____" ] ], [ [ "coeval8.init_struct.save(fname='my_init_struct.h5')", "_____no_output_____" ] ], [ [ "This brief example covers most of the basic usage of `21cmFAST` (at least with `Coeval` objects -- there are also `Lightcone` objects for which there is a separate tutorial). \n\nFor the rest of the tutorial, we'll cover a more advanced usage, in which each step of the calculation is done independently.", "_____no_output_____" ], [ "## Advanced Step-by-Step Usage", "_____no_output_____" ], [ "Most users most of the time will want to use the high-level `run_coeval` function from the previous section. However, there are several independent steps when computing the brightness temperature field, and these can be performed one-by-one, adding any other effects between them if desired. This means that the new `21cmFAST` is much more flexible. In this section, we'll go through in more detail how to use the lower-level methods.\n\nEach step in the chain will receive a number of input-parameter classes which define how the calculation should run. These are the `user_params`, `cosmo_params`, `astro_params` and `flag_options` that we saw in the previous section.\n\nConversely, each step is performed by running a function which will return a single object. Every major function returns an object of the same fundamental class (an ``OutputStruct``) which has various methods for reading/writing the data, and ensuring that it's in the right state to receive/pass to and from C.\nThese are the objects stored as `init_box_struct` etc. in the `Coeval` class.\n\nAs we move through each step, we'll outline some extra details, hints and tips about using these inputs and outputs.", "_____no_output_____" ], [ "### Initial Conditions", "_____no_output_____" ], [ "The first step is to get the initial conditions, which defines the *cosmological* density field before any redshift evolution is applied.", "_____no_output_____" ] ], [ [ "initial_conditions = p21c.initial_conditions(\n user_params = {\"HII_DIM\": 100, \"BOX_LEN\": 100},\n cosmo_params = p21c.CosmoParams(SIGMA_8=0.8),\n random_seed=54321\n)", "_____no_output_____" ] ], [ [ "We've already come across all these parameters as inputs to the `run_coeval` function. Indeed, most of the steps have very similar interfaces, and are able to take a random seed and parameters for where to look for the cache. We use a different seed than in the previous section so that all our boxes are \"fresh\" (we'll show how the caching works in a later section).\n\nThese initial conditions have 100 cells per side, and a box length of 100 Mpc. Note again that they can either be passed as a dictionary containing the input parameters, or an actual instance of the class. While the former is the suggested way, one benefit of the latter is that it can be queried for the relevant parameters (by using ``help`` or a post-fixed ``?``), or even queried for defaults:", "_____no_output_____" ] ], [ [ "p21c.CosmoParams._defaults_", "_____no_output_____" ] ], [ [ "(these defaults correspond to the Planck15 cosmology contained in Astropy).", "_____no_output_____" ], [ "So what is in the ``initial_conditions`` object? It is what we call an ``OutputStruct``, and we have seen it before, as the `init_box_struct` attribute of `Coeval`. It contains a number of arrays specifying the density and velocity fields of our initial conditions, as well as the defining parameters. For example, we can easily show the cosmology parameters that are used (note the non-default $\\sigma_8$ that we passed):", "_____no_output_____" ] ], [ [ "initial_conditions.cosmo_params", "_____no_output_____" ] ], [ [ "A handy tip is that the ``CosmoParams`` class also has a reference to a corresponding Astropy cosmology, which can be used more broadly:", "_____no_output_____" ] ], [ [ "initial_conditions.cosmo_params.cosmo", "_____no_output_____" ] ], [ [ "Merely printing the initial conditions object gives a useful representation of its dependent parameters:", "_____no_output_____" ] ], [ [ "print(initial_conditions)", "InitialConditions(UserParams(BOX_LEN:100, DIM:300, HII_DIM:100, HMF:1, POWER_SPECTRUM:0, USE_FFTW_WISDOM:False, USE_RELATIVE_VELOCITIES:False);\n\tCosmoParams(OMb:0.04897468161869667, OMm:0.30964144154550644, POWER_INDEX:0.9665, SIGMA_8:0.8, hlittle:0.6766);\n\trandom_seed:54321)\n" ] ], [ [ "(side-note: the string representation of the object is used to uniquely define it in order to save it to the cache... which we'll explore soon!).\n\nTo see which arrays are defined in the object, access the ``fieldnames`` (this is true for *all* `OutputStruct` objects):", "_____no_output_____" ] ], [ [ "initial_conditions.fieldnames", "_____no_output_____" ] ], [ [ "The `coeval_sliceplot` function also works on `OutputStruct` objects (as well as the `Coeval` object as we've already seen). It takes the object, and a specific field name. By default, the field it plots is the _first_ field in `fieldnames` (for any `OutputStruct`).", "_____no_output_____" ] ], [ [ "plotting.coeval_sliceplot(initial_conditions, \"hires_density\");", "_____no_output_____" ] ], [ [ "### Perturbed Field", "_____no_output_____" ], [ "After obtaining the initial conditions, we need to *perturb* the field to a given redshift (i.e. the redshift we care about). This step clearly requires the results of the previous step, which we can easily just pass in. Let's do that:", "_____no_output_____" ] ], [ [ "perturbed_field = p21c.perturb_field(\n redshift = 8.0,\n init_boxes = initial_conditions\n)", "_____no_output_____" ] ], [ [ "Note that we didn't need to pass in any input parameters, because they are all contained in the `initial_conditions` object itself. The random seed is also taken from this object.\n\nAgain, the output is an `OutputStruct`, so we can view its fields:", "_____no_output_____" ] ], [ [ "perturbed_field.fieldnames", "_____no_output_____" ] ], [ [ "This time, it has only density and velocity (the velocity direction is chosen without loss of generality). Let's view the perturbed density field:", "_____no_output_____" ] ], [ [ "plotting.coeval_sliceplot(perturbed_field, \"density\");", "_____no_output_____" ] ], [ [ "It is clear here that the density used is the *low*-res density, but the overall structure of the field looks very similar.", "_____no_output_____" ], [ "### Ionization Field", "_____no_output_____" ], [ "Next, we need to ionize the box. This is where things get a little more tricky. In the simplest case (which, let's be clear, is what we're going to do here) the ionization occurs at the *saturated limit*, which means we can safely ignore the contribution of the spin temperature. This means we can directly calculate the ionization on the density/velocity fields that we already have. A few more parameters are needed here, and so two more \"input parameter dictionaries\" are available, ``astro_params`` and ``flag_options``. Again, a reminder that their parameters can be viewed by using eg. `help(p21c.AstroParams)`, or by looking at the [API docs](../reference/_autosummary/py21cmfast.inputs.html).", "_____no_output_____" ], [ "For now, let's leave everything as default. In that case, we can just do:", "_____no_output_____" ] ], [ [ "ionized_field = p21c.ionize_box(\n perturbed_field = perturbed_field\n)", "2020-02-29 15:10:43,902 | INFO | Existing init_boxes found and read in (seed=54321).\n" ] ], [ [ "That was easy! All the information required by ``ionize_box`` was given directly by the ``perturbed_field`` object. If we had _also_ passed a redshift explicitly, this redshift would be checked against that from the ``perturbed_field`` and an error raised if they were incompatible:", "_____no_output_____" ], [ "Let's see the fieldnames:", "_____no_output_____" ] ], [ [ "ionized_field.fieldnames", "_____no_output_____" ] ], [ [ "Here the ``first_box`` field is actually just a flag to tell the C code whether this has been *evolved* or not. Here, it hasn't been, it's the \"first box\" of an evolutionary chain. Let's plot the neutral fraction:", "_____no_output_____" ] ], [ [ "plotting.coeval_sliceplot(ionized_field, \"xH_box\");", "_____no_output_____" ] ], [ [ "### Brightness Temperature", "_____no_output_____" ], [ "Now we can use what we have to get the brightness temperature:", "_____no_output_____" ] ], [ [ "brightness_temp = p21c.brightness_temperature(ionized_box=ionized_field, perturbed_field=perturbed_field)", "_____no_output_____" ] ], [ [ "This has only a single field, ``brightness_temp``:", "_____no_output_____" ] ], [ [ "plotting.coeval_sliceplot(brightness_temp);", "_____no_output_____" ] ], [ [ "### The Problem", "_____no_output_____" ], [ "And there you have it -- you've computed each of the four steps (there's actually another, `spin_temperature`, that you require if you don't assume the saturated limit) individually. \n\nHowever, some problems quickly arise. What if you want the `perturb_field`, but don't care about the initial conditions? We know how to get the full `Coeval` object in one go, but it would seem that the sub-boxes have to _each_ be computed as the input to the next. \n\nA perhaps more interesting problem is that some quantities require *evolution*: i.e. a whole bunch of simulations at a string of redshifts must be performed in order to obtain the current redshift. This is true when not in the saturated limit, for example. That means you'd have to manually compute each redshift in turn, and pass it to the computation at the next redshift. While this is definitely possible, it becomes difficult to set up manually when all you care about is the box at the final redshift.\n\n`py21cmfast` solves this by making each of the functions recursive: if `perturb_field` is not passed the `init_boxes` that it needs, it will go and compute them, based on the parameters that you've passed it. If the previous `spin_temp` box required for the current redshift is not passed -- it will be computed (and if it doesn't have a previous `spin_temp` *it* will be computed, and so on).\n\nThat's all good, but what if you now want to compute another `perturb_field`, with the same fundamental parameters (but at a different redshift)? Since you didn't ever see the `init_boxes`, they'll have to be computed all over again. That's where the automatic caching comes in, which is where we turn now...", "_____no_output_____" ], [ "## Using the Automatic Cache", "_____no_output_____" ], [ "To solve all this, ``21cmFAST`` uses an on-disk caching mechanism, where all boxes are saved in HDF5 format in a default location. The cache allows for reading in previously-calculated boxes automatically if they match the parameters that are input. The functions used at every step (in the previous section) will try to use a cached box instead of calculating a new one, unless its explicitly asked *not* to. \n\nThus, we could do this:", "_____no_output_____" ] ], [ [ "perturbed_field = p21c.perturb_field(\n redshift = 8.0,\n user_params = {\"HII_DIM\": 100, \"BOX_LEN\": 100},\n cosmo_params = p21c.CosmoParams(SIGMA_8=0.8),\n)\nplotting.coeval_sliceplot(perturbed_field, \"density\");", "2020-02-29 15:10:45,367 | INFO | Existing z=8.0 perturb_field boxes found and read in (seed=12345).\n" ] ], [ [ "Note that here we pass exactly the same parameters as were used in the previous section. It gives a message that the full box was found in the cache and immediately returns. However, if we change the redshift:", "_____no_output_____" ] ], [ [ "perturbed_field = p21c.perturb_field(\n redshift = 7.0,\n user_params = {\"HII_DIM\": 100, \"BOX_LEN\": 100},\n cosmo_params = p21c.CosmoParams(SIGMA_8=0.8),\n)\nplotting.coeval_sliceplot(perturbed_field, \"density\");", "2020-02-29 15:10:45,748 | INFO | Existing init_boxes found and read in (seed=12345).\n" ] ], [ [ "Now it finds the initial conditions, but it must compute the perturbed field at the new redshift. If we had changed the initial parameters as well, it would have to calculate everything:", "_____no_output_____" ] ], [ [ "perturbed_field = p21c.perturb_field(\n redshift = 8.0,\n user_params = {\"HII_DIM\": 50, \"BOX_LEN\": 100},\n cosmo_params = p21c.CosmoParams(SIGMA_8=0.8),\n)\n\nplotting.coeval_sliceplot(perturbed_field, \"density\");", "_____no_output_____" ] ], [ [ "This shows that we don't need to perform the *previous* step to do any of the steps, they will be calculated automatically.\n\nNow, let's get an ionized box, but this time we won't assume the saturated limit, so we need to use the spin temperature. We can do this directly in the ``ionize_box`` function, but let's do it explicitly. We will use the auto-generation of the initial conditions and perturbed field. However, the spin temperature is an *evolved* field, i.e. to compute the field at $z$, we need to know the field at $z+\\Delta z$. This continues up to some redshift, labelled ``z_heat_max``, above which the spin temperature can be defined directly from the perturbed field. \n\nThus, one option is to pass to the function a *previous* spin temperature box, to evolve to *this* redshift. However, we don't have a previous spin temperature box yet. Of course, the function itself will go and calculate that box if it's not given (or read it from cache if it's been calculated before!). When it tries to do that, it will go to the one before, and so on until it reaches ``z_heat_max``, at which point it will calculate it directly. \n\nTo facilitate this recursive progression up the redshift ladder, there is a parameter, ``z_step_factor``, which is a multiplicate factor that determines the previous redshift at each step. \n\nWe can also pass the dependent boxes explicitly, which provides the parameters necessary.\n\n**WARNING: THIS IS THE MOST TIME-CONSUMING STEP OF THE CALCULATION!**", "_____no_output_____" ] ], [ [ "spin_temp = p21c.spin_temperature(\n perturbed_field = perturbed_field,\n zprime_step_factor=1.05,\n)", "2020-02-29 15:11:38,347 | INFO | Existing init_boxes found and read in (seed=521414794440).\n" ], [ "plotting.coeval_sliceplot(spin_temp, \"Ts_box\");", "_____no_output_____" ] ], [ [ "Let's note here that each of the functions accepts a few of the same arguments that modifies how the boxes are cached. There is a ``write`` argument, which if set to ``False``, will disable writing that box to cache (and it is passed through the recursive heirarchy). There is also ``regenerate``, which if ``True``, forces this box and all its predecessors to be re-calculated even if they exist in the cache. Then there is ``direc``, which we have seen before.\n\nFinally note that by default, ``random_seed`` is set to ``None``. If this is the case, then any cached dataset matching all other parameters will be read in, and the ``random_seed`` will be set based on the file read in. If it is set to an integer number, then the cached dataset must also match the seed. If it is ``None``, and no matching dataset is found, a random seed will be autogenerated.", "_____no_output_____" ], [ "Now if we calculate the ionized box, ensuring that it uses the spin temperature, then it will also need to be evolved. However, due to the fact that we cached each of the spin temperature steps, these should be read in accordingly:", "_____no_output_____" ] ], [ [ "ionized_box = p21c.ionize_box(\n spin_temp = spin_temp,\n zprime_step_factor=1.05,\n)", "2020-02-29 15:12:55,794 | INFO | Existing init_boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,814 | INFO | Existing z=34.2811622461279 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,827 | INFO | Existing z=34.2811622461279 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,865 | INFO | Existing z=32.60110690107419 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,880 | INFO | Existing z=32.60110690107419 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,906 | INFO | Existing z=31.00105419149923 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,919 | INFO | Existing z=31.00105419149923 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,948 | INFO | Existing z=29.4771944680945 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,963 | INFO | Existing z=29.4771944680945 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:55,991 | INFO | Existing z=28.02589949342333 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,005 | INFO | Existing z=28.02589949342333 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,033 | INFO | Existing z=26.643713803260315 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,051 | INFO | Existing z=26.643713803260315 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,079 | INFO | Existing z=25.32734647929554 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,094 | INFO | Existing z=25.32734647929554 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,127 | INFO | Existing z=24.073663313614798 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,141 | INFO | Existing z=24.073663313614798 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,168 | INFO | Existing z=22.879679346299806 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,182 | INFO | Existing z=22.879679346299806 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,205 | INFO | Existing z=21.742551758380767 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,219 | INFO | Existing z=21.742551758380767 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,403 | INFO | Existing z=20.659573103219778 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,418 | INFO | Existing z=20.659573103219778 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,620 | INFO | Existing z=19.62816486020931 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,635 | INFO | Existing z=19.62816486020931 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,784 | INFO | Existing z=18.645871295437438 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,793 | INFO | Existing z=18.645871295437438 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,931 | INFO | Existing z=17.71035361470232 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:56,941 | INFO | Existing z=17.71035361470232 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,085 | INFO | Existing z=16.81938439495459 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,095 | INFO | Existing z=16.81938439495459 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,243 | INFO | Existing z=15.970842280909132 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,254 | INFO | Existing z=15.970842280909132 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,399 | INFO | Existing z=15.162706934199171 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,408 | INFO | Existing z=15.162706934199171 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,544 | INFO | Existing z=14.393054223046828 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,554 | INFO | Existing z=14.393054223046828 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,691 | INFO | Existing z=13.66005164099698 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,700 | INFO | Existing z=13.66005164099698 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,832 | INFO | Existing z=12.961953943806646 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,840 | INFO | Existing z=12.961953943806646 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,970 | INFO | Existing z=12.297098994101567 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:57,978 | INFO | Existing z=12.297098994101567 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,106 | INFO | Existing z=11.663903803906255 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,114 | INFO | Existing z=11.663903803906255 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,244 | INFO | Existing z=11.060860765625003 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,254 | INFO | Existing z=11.060860765625003 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,394 | INFO | Existing z=10.486534062500002 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,402 | INFO | Existing z=10.486534062500002 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,529 | INFO | Existing z=9.939556250000003 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,538 | INFO | Existing z=9.939556250000003 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,674 | INFO | Existing z=9.418625000000002 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,682 | INFO | Existing z=9.418625000000002 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,810 | INFO | Existing z=8.922500000000001 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,819 | INFO | Existing z=8.922500000000001 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,947 | INFO | Existing z=8.450000000000001 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:12:58,956 | INFO | Existing z=8.450000000000001 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:12:59,086 | INFO | Existing z=8.0 perturb_field boxes found and read in (seed=521414794440).\n" ], [ " plotting.coeval_sliceplot(ionized_box, \"xH_box\");", "_____no_output_____" ] ], [ [ "Great! So again, we can just get the brightness temp:", "_____no_output_____" ] ], [ [ "brightness_temp = p21c.brightness_temperature(\n ionized_box = ionized_box,\n perturbed_field = perturbed_field,\n spin_temp = spin_temp\n)", "_____no_output_____" ] ], [ [ "Now lets plot our brightness temperature, which has been evolved from high redshift with spin temperature fluctuations:", "_____no_output_____" ] ], [ [ "plotting.coeval_sliceplot(brightness_temp);", "_____no_output_____" ] ], [ [ "We can also check what the result would have been if we had limited the maximum redshift of heating. Note that this *recalculates* all previous spin temperature and ionized boxes, because they depend on both ``z_heat_max`` and ``zprime_step_factor``.", "_____no_output_____" ] ], [ [ "ionized_box = p21c.ionize_box(\n spin_temp = spin_temp,\n zprime_step_factor=1.05,\n z_heat_max = 20.0\n)\n\nbrightness_temp = p21c.brightness_temperature(\n ionized_box = ionized_box,\n perturbed_field = perturbed_field,\n spin_temp = spin_temp\n)\n\nplotting.coeval_sliceplot(brightness_temp);", "2020-02-29 15:13:08,824 | INFO | Existing init_boxes found and read in (seed=521414794440).\n2020-02-29 15:13:08,840 | INFO | Existing z=19.62816486020931 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:11,438 | INFO | Existing z=18.645871295437438 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:11,447 | INFO | Existing z=19.62816486020931 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:14,041 | INFO | Existing z=17.71035361470232 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:14,050 | INFO | Existing z=18.645871295437438 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:16,667 | INFO | Existing z=16.81938439495459 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:16,675 | INFO | Existing z=17.71035361470232 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:19,213 | INFO | Existing z=15.970842280909132 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:19,222 | INFO | Existing z=16.81938439495459 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:21,756 | INFO | Existing z=15.162706934199171 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:21,764 | INFO | Existing z=15.970842280909132 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:24,409 | INFO | Existing z=14.393054223046828 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:24,417 | INFO | Existing z=15.162706934199171 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:26,938 | INFO | Existing z=13.66005164099698 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:26,947 | INFO | Existing z=14.393054223046828 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:29,504 | INFO | Existing z=12.961953943806646 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:29,517 | INFO | Existing z=13.66005164099698 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:32,163 | INFO | Existing z=12.297098994101567 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:32,171 | INFO | Existing z=12.961953943806646 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:34,704 | INFO | Existing z=11.663903803906255 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:34,712 | INFO | Existing z=12.297098994101567 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:37,257 | INFO | Existing z=11.060860765625003 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:37,266 | INFO | Existing z=11.663903803906255 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:39,809 | INFO | Existing z=10.486534062500002 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:39,817 | INFO | Existing z=11.060860765625003 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:42,378 | INFO | Existing z=9.939556250000003 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:42,387 | INFO | Existing z=10.486534062500002 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:44,941 | INFO | Existing z=9.418625000000002 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:44,950 | INFO | Existing z=9.939556250000003 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:47,518 | INFO | Existing z=8.922500000000001 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:47,528 | INFO | Existing z=9.418625000000002 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:50,077 | INFO | Existing z=8.450000000000001 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:50,086 | INFO | Existing z=8.922500000000001 spin_temp boxes found and read in (seed=521414794440).\n2020-02-29 15:13:52,626 | INFO | Existing z=8.0 perturb_field boxes found and read in (seed=521414794440).\n2020-02-29 15:13:52,762 | INFO | Existing brightness_temp box found and read in (seed=521414794440).\n" ] ], [ [ "As we can see, it's very similar!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01e0e9c38c4dcb5840092c91e5628c4c1c1ca50
21,380
ipynb
Jupyter Notebook
Chapter06/Exercise06.03/Exercise06_03.ipynb
PacktWorkshops/The-Reinforcement-Learning-Workshop
04e8c72bc9e46d66846b748c074b26a1b724fae0
[ "MIT" ]
24
2020-04-08T01:57:02.000Z
2022-03-24T18:36:14.000Z
Exercise03/Exercise03.ipynb
Develop-Packt/Introduction-to-Monte-Carlo-Methods
1c48eb08be8b4d27cea57462816c4a1894090dcb
[ "MIT" ]
10
2020-03-24T19:49:14.000Z
2022-03-12T00:33:01.000Z
Chapter06/Exercise06.03/Exercise06_03.ipynb
PacktWorkshops/The-Reinforcement-Learning-Workshop
04e8c72bc9e46d66846b748c074b26a1b724fae0
[ "MIT" ]
32
2020-04-08T12:07:11.000Z
2022-03-25T15:49:10.000Z
46.077586
131
0.427315
[ [ [ "import gym\nimport numpy as np\nfrom collections import defaultdict\nfrom functools import partial ", "_____no_output_____" ], [ "env = gym.make('Blackjack-v0')", "_____no_output_____" ], [ "def policy_blackjack_game(state):\n player_score, dealer_score, usable_ace = state \n if (player_score >= 17):\n return 0 # don't take any cards, stick\n else:\n return 1 # take additional cards, hit", "_____no_output_____" ], [ "def generate_blackjack_episode():\n \n #initalizing the value of episode, states, actions, rewards\n episode = []\n states = []\n actions = []\n rewards = []\n \n #starting the environment\n state = env.reset()\n \n #settng the state value to player_score, dealer_score and usable_ace\n player_score, dealer_score, usable_ace = state\n\n while (True): \n \n #finding the action by passing on the state\n action = policy_blackjack_game(state) \n next_state, reward, done, info = env.step(action)\n \n #creating a list of episodes, states, actions, rewards\n episode.append((state, action, reward))\n states.append(state)\n actions.append(action)\n rewards.append(reward)\n if done:\n break\n state = next_state\n \n return episode, states, actions, rewards ", "_____no_output_____" ], [ "def black_jack_every_visit_prediction(policy, env, num_episodes):\n \n #initializing the value of total_rewards, number of states, and value_function\n total_rewards = 0\n num_states = defaultdict(float)\n value_function = defaultdict(float)\n \n for k in range (0, num_episodes):\n episode, states, actions, rewards = generate_blackjack_episode() \n total_rewards = 0\n for i in range(len(states)-1, -1,-1):\n current_state = states[i]\n #finding the sum of rewards\n total_rewards += rewards[i]\n #all the state values of every visit are considered\n #increasing the count of states by 1\n num_states[current_state] += 1\n \n #finding the value_function by incremental method\n value_function[current_state] += (total_rewards - value_function[current_state]) / (num_states[current_state])\n \n return value_function", "_____no_output_____" ], [ "black_jack_every_visit_prediction(policy_blackjack_game, env, 10000)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
d01e148f28e0cb9ff1e75d406b58f4bf1dce06c6
758,029
ipynb
Jupyter Notebook
NOMADS/GFS_850mb_temperature_advection.ipynb
HumphreysCarter/Model-Data
3a118e23f9e33de84035ca894cbf75737a05c656
[ "BSD-3-Clause" ]
null
null
null
NOMADS/GFS_850mb_temperature_advection.ipynb
HumphreysCarter/Model-Data
3a118e23f9e33de84035ca894cbf75737a05c656
[ "BSD-3-Clause" ]
null
null
null
NOMADS/GFS_850mb_temperature_advection.ipynb
HumphreysCarter/Model-Data
3a118e23f9e33de84035ca894cbf75737a05c656
[ "BSD-3-Clause" ]
null
null
null
1,306.946552
726,704
0.950312
[ [ [ "import numpy as np\nimport xarray as xr\nimport scipy.ndimage as ndimage\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nimport matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport metpy.calc as mpcalc\nfrom metpy.units import units\nfrom datetime import datetime", "/usr/lib/python3/dist-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.26.2) or chardet (3.0.4) doesn't match a supported version!\n RequestsDependencyWarning)\n" ], [ "# Get dataset from NOMADS Server\nds = xr.open_dataset('http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs20201121/gfs_0p25_1hr_12z')\n\n# Select desired vars\nds = ds[['hgtprs', 'tmpprs', 'ugrdprs', 'vgrdprs']]\n\n# Select time\nds = ds.sel(time=ds.time[0])\n\n# Select level\nds = ds.sel(lev=850)\n\n# Select lat/lon slice\nds = ds.sel(lon=slice(220, 310), lat=slice(15, 65))\n\nds", "_____no_output_____" ], [ "# Calcualte dx and dy \ndx, dy = mpcalc.lat_lon_grid_deltas(ds.lon.values, ds.lat.values)\n\n# Set calculation units \nT, u, v = ds.tmpprs.values * units('K'), ds.ugrdprs.values * units('m/s'), ds.vgrdprs.values * units('m/s')\n\n# Calculate temperature advection\nT_adv = mpcalc.advection(scalar=T, wind=[u, v], deltas=(dx, dy), dim_order='yx')\n\n# Smooth data\nz = ndimage.gaussian_filter(ds.hgtprs, sigma=3, order=0)\nT_adv = ndimage.gaussian_filter(T_adv, sigma=3, order=0) * units('K / s')\n\n# Set plot units\nu = u.to('kt')\nv = v.to('kt')\nT = T.to('degC')\nT_adv = T_adv.to('degC/hr') * 3", "_____no_output_____" ], [ "# Set Projection of Data\ndatacrs = ccrs.PlateCarree()\n\n# Set Projection of Plot\nplotcrs = ccrs.LambertConformal(central_latitude=[30, 60], central_longitude=-100)\n\n# Create new figure\nfig = plt.figure(figsize=(15, 12.5))\ngs = gridspec.GridSpec(2, 1, height_ratios=[1, .02], bottom=.07, top=.99, hspace=0.01, wspace=0.01)\n\n# Add the map and set the extent\nax = plt.subplot(gs[0], projection=plotcrs)\nax.set_extent([235, 290, 20, 55])\n\n# Add state/country boundaries to plot\ncountry_borders=cfeature.NaturalEarthFeature(category='cultural', name='admin_0_countries', scale='10m', facecolor='none')\nax.add_feature(country_borders, edgecolor='black', linewidth=1.0)\nstate_borders=cfeature.NaturalEarthFeature(category='cultural', name='admin_1_states_provinces_lakes', scale='10m', facecolor='none')\nax.add_feature(state_borders, edgecolor='black', linewidth=0.5)\n\n# Plot Height Contours\nclev = np.arange(900, 3000, 30)\ncs = ax.contour(ds.lon, ds.lat, z, clev, colors='black', linewidths=2, transform=datacrs)\nplt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True)\n\n# Plot Temperature Contours\nclevtemp850 = np.arange(-20, 20, 2)\ncs2 = ax.contour(ds.lon, ds.lat, T, clevtemp850, colors='grey', linewidths=1.25, linestyles='--', transform=datacrs)\nplt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True)\n\n# Plot Colorfill of Temperature Advection\ncint = np.arange(-8, 9)\ncf = ax.contourf(ds.lon, ds.lat, T_adv, cint[cint != 0], extend='both', cmap='bwr', transform=datacrs)\ncb = plt.colorbar(cf, ax=ax, pad=0, aspect=50, orientation='horizontal', extendrect=True, ticks=cint)\ncb.set_label(r'$^{\\circ}$C 3h$^{-1}$', size='large')\n\n# Plot Wind Barbs\nax.barbs(ds.lon, ds.lat, u.magnitude, v.magnitude, length=6, regrid_shape=20, pivot='middle', transform=datacrs)\n\n# Change datetiem64 to datetime\nvalid = datetime.utcfromtimestamp(ds.time.values.astype('O')/1e9)\n\n# Add plot headers\nplt.title(f'GFS 850mb Temperature Advection', loc='left')\nplt.title(f'Run: {valid.strftime(\"%a %Y-%m-%d %H:%M\")} UTC\\nValid: {valid.strftime(\"%a %Y-%m-%d %H:%M\")} UTC', loc='right')\n\n# Add title\nplt.suptitle(f'weather.carterhumphreys.com', fontsize=16, x=0.50, y=0.90)\n \n# Export plot and close\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
d01e204e178a10782a66fe407b8342882f54e092
27,839
ipynb
Jupyter Notebook
samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
danishsamad/pipelines
135bfbb9f2945a7e841d5891ee0f5862c75aa3b7
[ "Apache-2.0" ]
null
null
null
samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
danishsamad/pipelines
135bfbb9f2945a7e841d5891ee0f5862c75aa3b7
[ "Apache-2.0" ]
null
null
null
samples/contrib/mnist/04_Reusable_and_Pre-build_Components_as_Pipeline.ipynb
danishsamad/pipelines
135bfbb9f2945a7e841d5891ee0f5862c75aa3b7
[ "Apache-2.0" ]
null
null
null
35.19469
499
0.58824
[ [ [ "# Copyright 2019 Google Inc. All Rights Reserved.\n#\n# 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# http://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.\n# ==============================================================================", "_____no_output_____" ] ], [ [ "# Composing a pipeline from reusable, pre-built, and lightweight components\n\nThis tutorial describes how to build a Kubeflow pipeline from reusable, pre-built, and lightweight components. The following provides a summary of the steps involved in creating and using a reusable component:\n\n- Write the program that contains your component’s logic. The program must use files and command-line arguments to pass data to and from the component.\n- Containerize the program.\n- Write a component specification in YAML format that describes the component for the Kubeflow Pipelines system.\n- Use the Kubeflow Pipelines SDK to load your component, use it in a pipeline and run that pipeline.\n\nThen, we will compose a pipeline from a reusable component, a pre-built component, and a lightweight component. The pipeline will perform the following steps:\n- Train an MNIST model and export it to Google Cloud Storage.\n- Deploy the exported TensorFlow model on AI Platform Prediction service.\n- Test the deployment by calling the endpoint with test data.", "_____no_output_____" ], [ "Note: Ensure that you have Docker installed, if you want to build the image locally, by running the following command:\n \n`which docker`\n \nThe result should be something like:\n\n`/usr/bin/docker`", "_____no_output_____" ] ], [ [ "import kfp\nimport kfp.gcp as gcp\nimport kfp.dsl as dsl\nimport kfp.compiler as compiler\nimport kfp.components as comp\nimport datetime\n\nimport kubernetes as k8s", "_____no_output_____" ], [ "# Required Parameters\nPROJECT_ID='<ADD GCP PROJECT HERE>'\nGCS_BUCKET='gs://<ADD STORAGE LOCATION HERE>'", "_____no_output_____" ] ], [ [ "## Create client\n\nIf you run this notebook **outside** of a Kubeflow cluster, run the following command:\n- `host`: The URL of your Kubeflow Pipelines instance, for example \"https://`<your-deployment>`.endpoints.`<your-project>`.cloud.goog/pipeline\"\n- `client_id`: The client ID used by Identity-Aware Proxy\n- `other_client_id`: The client ID used to obtain the auth codes and refresh tokens.\n- `other_client_secret`: The client secret used to obtain the auth codes and refresh tokens.\n\n```python\nclient = kfp.Client(host, client_id, other_client_id, other_client_secret)\n```\n\nIf you run this notebook **within** a Kubeflow cluster, run the following command:\n```python\nclient = kfp.Client()\n```\n\nYou'll need to create OAuth client ID credentials of type `Other` to get `other_client_id` and `other_client_secret`. Learn more about [creating OAuth credentials](\nhttps://cloud.google.com/iap/docs/authentication-howto#authenticating_from_a_desktop_app)", "_____no_output_____" ] ], [ [ "# Optional Parameters, but required for running outside Kubeflow cluster\n\n# The host for 'AI Platform Pipelines' ends with 'pipelines.googleusercontent.com'\n# The host for pipeline endpoint of 'full Kubeflow deployment' ends with '/pipeline'\n# Examples are:\n# https://7c021d0340d296aa-dot-us-central2.pipelines.googleusercontent.com\n# https://kubeflow.endpoints.kubeflow-pipeline.cloud.goog/pipeline\nHOST = '<ADD HOST NAME TO TALK TO KUBEFLOW PIPELINE HERE>'\n\n# For 'full Kubeflow deployment' on GCP, the endpoint is usually protected through IAP, therefore the following \n# will be needed to access the endpoint.\nCLIENT_ID = '<ADD OAuth CLIENT ID USED BY IAP HERE>'\nOTHER_CLIENT_ID = '<ADD OAuth CLIENT ID USED TO OBTAIN AUTH CODES HERE>'\nOTHER_CLIENT_SECRET = '<ADD OAuth CLIENT SECRET USED TO OBTAIN AUTH CODES HERE>'", "_____no_output_____" ], [ "# This is to ensure the proper access token is present to reach the end point for 'AI Platform Pipelines'\n# If you are not working with 'AI Platform Pipelines', this step is not necessary\n! gcloud auth print-access-token", "_____no_output_____" ], [ "# Create kfp client\nin_cluster = True\ntry:\n k8s.config.load_incluster_config()\nexcept:\n in_cluster = False\n pass\n\nif in_cluster:\n client = kfp.Client()\nelse:\n if HOST.endswith('googleusercontent.com'):\n CLIENT_ID = None\n OTHER_CLIENT_ID = None\n OTHER_CLIENT_SECRET = None\n\n client = kfp.Client(host=HOST, \n client_id=CLIENT_ID,\n other_client_id=OTHER_CLIENT_ID, \n other_client_secret=OTHER_CLIENT_SECRET)", "_____no_output_____" ] ], [ [ "# Build reusable components", "_____no_output_____" ], [ "## Writing the program code", "_____no_output_____" ], [ "The following cell creates a file `app.py` that contains a Python script. The script downloads MNIST dataset, trains a Neural Network based classification model, writes the training log and exports the trained model to Google Cloud Storage.\n\nYour component can create outputs that the downstream components can use as inputs. Each output must be a string and the container image must write each output to a separate local text file. For example, if a training component needs to output the path of the trained model, the component writes the path into a local file, such as `/output.txt`.", "_____no_output_____" ] ], [ [ "%%bash\n\n# Create folders if they don't exist.\nmkdir -p tmp/reuse_components_pipeline/mnist_training\n\n# Create the Python file that lists GCS blobs.\ncat > ./tmp/reuse_components_pipeline/mnist_training/app.py <<HERE\nimport argparse\nfrom datetime import datetime\nimport tensorflow as tf\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--model_path', type=str, required=True, help='Name of the model file.')\nparser.add_argument(\n '--bucket', type=str, required=True, help='GCS bucket name.')\nargs = parser.parse_args()\n\nbucket=args.bucket\nmodel_path=args.model_path\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nprint(model.summary()) \n\nmnist = tf.keras.datasets.mnist\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\ncallbacks = [\n tf.keras.callbacks.TensorBoard(log_dir=bucket + '/logs/' + datetime.now().date().__str__()),\n # Interrupt training if val_loss stops improving for over 2 epochs\n tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),\n]\n\nmodel.fit(x_train, y_train, batch_size=32, epochs=5, callbacks=callbacks,\n validation_data=(x_test, y_test))\n\nfrom tensorflow import gfile\n\ngcs_path = bucket + \"/\" + model_path\n# The export require the folder is new\nif gfile.Exists(gcs_path):\n gfile.DeleteRecursively(gcs_path)\ntf.keras.experimental.export_saved_model(model, gcs_path)\n\nwith open('/output.txt', 'w') as f:\n f.write(gcs_path)\nHERE", "_____no_output_____" ] ], [ [ "## Create a Docker container\nCreate your own container image that includes your program. ", "_____no_output_____" ], [ "### Creating a Dockerfile", "_____no_output_____" ], [ "Now create a container that runs the script. Start by creating a Dockerfile. A Dockerfile contains the instructions to assemble a Docker image. The `FROM` statement specifies the Base Image from which you are building. `WORKDIR` sets the working directory. When you assemble the Docker image, `COPY` copies the required files and directories (for example, `app.py`) to the file system of the container. `RUN` executes a command (for example, install the dependencies) and commits the results. ", "_____no_output_____" ] ], [ [ "%%bash\n\n# Create Dockerfile.\n# AI platform only support tensorflow 1.14\ncat > ./tmp/reuse_components_pipeline/mnist_training/Dockerfile <<EOF\nFROM tensorflow/tensorflow:1.14.0-py3\nWORKDIR /app\nCOPY . /app\nEOF", "_____no_output_____" ] ], [ [ "### Build docker image", "_____no_output_____" ], [ "Now that we have created our Dockerfile for creating our Docker image. Then we need to build the image and push to a registry to host the image. There are three possible options:\n- Use the `kfp.containers.build_image_from_working_dir` to build the image and push to the Container Registry (GCR). This requires [kaniko](https://cloud.google.com/blog/products/gcp/introducing-kaniko-build-container-images-in-kubernetes-and-google-container-builder-even-without-root-access), which will be auto-installed with 'full Kubeflow deployment' but not 'AI Platform Pipelines'.\n- Use [Cloud Build](https://cloud.google.com/cloud-build), which would require the setup of GCP project and enablement of corresponding API. If you are working with GCP 'AI Platform Pipelines' with GCP project running, it is recommended to use Cloud Build.\n- Use [Docker](https://www.docker.com/get-started) installed locally and push to e.g. GCR.", "_____no_output_____" ], [ "**Note**:\nIf you run this notebook **within Kubeflow cluster**, **with Kubeflow version >= 0.7** and exploring **kaniko option**, you need to ensure that valid credentials are created within your notebook's namespace.\n- With Kubeflow version >= 0.7, the credential is supposed to be copied automatically while creating notebook through `Configurations`, which doesn't work properly at the time of creating this notebook. \n- You can also add credentials to the new namespace by either [copying credentials from an existing Kubeflow namespace, or by creating a new service account](https://www.kubeflow.org/docs/gke/authentication/#kubeflow-v0-6-and-before-gcp-service-account-key-as-secret).\n- The following cell demonstrates how to copy the default secret to your own namespace.\n\n```bash\n%%bash\n\nNAMESPACE=<your notebook name space>\nSOURCE=kubeflow\nNAME=user-gcp-sa\nSECRET=$(kubectl get secrets \\${NAME} -n \\${SOURCE} -o jsonpath=\"{.data.\\${NAME}\\.json}\" | base64 -D)\nkubectl create -n \\${NAMESPACE} secret generic \\${NAME} --from-literal=\"\\${NAME}.json=\\${SECRET}\"\n```", "_____no_output_____" ] ], [ [ "IMAGE_NAME=\"mnist_training_kf_pipeline\"\nTAG=\"latest\" # \"v_$(date +%Y%m%d_%H%M%S)\"\n\nGCR_IMAGE=\"gcr.io/{PROJECT_ID}/{IMAGE_NAME}:{TAG}\".format(\n PROJECT_ID=PROJECT_ID,\n IMAGE_NAME=IMAGE_NAME,\n TAG=TAG\n)\n\nAPP_FOLDER='./tmp/reuse_components_pipeline/mnist_training/'", "_____no_output_____" ], [ "# In the following, for the purpose of demonstration\n# Cloud Build is choosen for 'AI Platform Pipelines'\n# kaniko is choosen for 'full Kubeflow deployment'\n\nif HOST.endswith('googleusercontent.com'):\n # kaniko is not pre-installed with 'AI Platform Pipelines'\n import subprocess\n # ! gcloud builds submit --tag ${IMAGE_NAME} ${APP_FOLDER}\n cmd = ['gcloud', 'builds', 'submit', '--tag', GCR_IMAGE, APP_FOLDER]\n build_log = (subprocess.run(cmd, stdout=subprocess.PIPE).stdout[:-1].decode('utf-8'))\n print(build_log)\n \nelse:\n if kfp.__version__ <= '0.1.36':\n # kfp with version 0.1.36+ introduce broken change that will make the following code not working\n import subprocess\n \n builder = kfp.containers._container_builder.ContainerBuilder(\n gcs_staging=GCS_BUCKET + \"/kfp_container_build_staging\"\n )\n\n kfp.containers.build_image_from_working_dir(\n image_name=GCR_IMAGE,\n working_dir=APP_FOLDER,\n builder=builder\n )\n else:\n raise(\"Please build the docker image use either [Docker] or [Cloud Build]\")", "_____no_output_____" ] ], [ [ "#### If you want to use docker to build the image\nRun the following in a cell\n```bash\n%%bash -s \"{PROJECT_ID}\"\n\nIMAGE_NAME=\"mnist_training_kf_pipeline\"\nTAG=\"latest\" # \"v_$(date +%Y%m%d_%H%M%S)\"\n\n# Create script to build docker image and push it.\ncat > ./tmp/components/mnist_training/build_image.sh <<HERE\nPROJECT_ID=\"${1}\"\nIMAGE_NAME=\"${IMAGE_NAME}\"\nTAG=\"${TAG}\"\nGCR_IMAGE=\"gcr.io/\\${PROJECT_ID}/\\${IMAGE_NAME}:\\${TAG}\"\ndocker build -t \\${IMAGE_NAME} .\ndocker tag \\${IMAGE_NAME} \\${GCR_IMAGE}\ndocker push \\${GCR_IMAGE}\ndocker image rm \\${IMAGE_NAME}\ndocker image rm \\${GCR_IMAGE}\nHERE\n\ncd tmp/components/mnist_training\nbash build_image.sh\n```", "_____no_output_____" ] ], [ [ "image_name = GCR_IMAGE", "_____no_output_____" ] ], [ [ "## Writing your component definition file\nTo create a component from your containerized program, you must write a component specification in YAML that describes the component for the Kubeflow Pipelines system.\n\nFor the complete definition of a Kubeflow Pipelines component, see the [component specification](https://www.kubeflow.org/docs/pipelines/reference/component-spec/). However, for this tutorial you don’t need to know the full schema of the component specification. The notebook provides enough information to complete the tutorial.\n\nStart writing the component definition (component.yaml) by specifying your container image in the component’s implementation section:", "_____no_output_____" ] ], [ [ "%%bash -s \"{image_name}\"\n\nGCR_IMAGE=\"${1}\"\necho ${GCR_IMAGE}\n\n# Create Yaml\n# the image uri should be changed according to the above docker image push output\n\ncat > mnist_pipeline_component.yaml <<HERE\nname: Mnist training\ndescription: Train a mnist model and save to GCS\ninputs:\n - name: model_path\n description: 'Path of the tf model.'\n type: String\n - name: bucket\n description: 'GCS bucket name.'\n type: String\noutputs:\n - name: gcs_model_path\n description: 'Trained model path.'\n type: GCSPath\nimplementation:\n container:\n image: ${GCR_IMAGE}\n command: [\n python, /app/app.py,\n --model_path, {inputValue: model_path},\n --bucket, {inputValue: bucket},\n ]\n fileOutputs:\n gcs_model_path: /output.txt\nHERE", "_____no_output_____" ], [ "import os\nmnist_train_op = kfp.components.load_component_from_file(os.path.join('./', 'mnist_pipeline_component.yaml')) ", "_____no_output_____" ], [ "mnist_train_op.component_spec", "_____no_output_____" ] ], [ [ "# Define deployment operation on AI Platform", "_____no_output_____" ] ], [ [ "mlengine_deploy_op = comp.load_component_from_url(\n 'https://raw.githubusercontent.com/kubeflow/pipelines/1.1.2/components/gcp/ml_engine/deploy/component.yaml')\n\ndef deploy(\n project_id,\n model_uri,\n model_id,\n runtime_version,\n python_version):\n \n return mlengine_deploy_op(\n model_uri=model_uri,\n project_id=project_id, \n model_id=model_id, \n runtime_version=runtime_version, \n python_version=python_version,\n replace_existing_version=True, \n set_default=True)", "_____no_output_____" ] ], [ [ "Kubeflow serving deployment component as an option. **Note that, the deployed Endppoint URI is not availabe as output of this component.**\n```python\nkubeflow_deploy_op = comp.load_component_from_url(\n 'https://raw.githubusercontent.com/kubeflow/pipelines/1.1.2/components/gcp/ml_engine/deploy/component.yaml')\n\ndef deploy_kubeflow(\n model_dir,\n tf_server_name):\n return kubeflow_deploy_op(\n model_dir=model_dir,\n server_name=tf_server_name,\n cluster_name='kubeflow', \n namespace='kubeflow',\n pvc_name='', \n service_type='ClusterIP')\n```", "_____no_output_____" ], [ "# Create a lightweight component for testing the deployment", "_____no_output_____" ] ], [ [ "def deployment_test(project_id: str, model_name: str, version: str) -> str:\n\n model_name = model_name.split(\"/\")[-1]\n version = version.split(\"/\")[-1]\n \n import googleapiclient.discovery\n \n def predict(project, model, data, version=None):\n \"\"\"Run predictions on a list of instances.\n\n Args:\n project: (str), project where the Cloud ML Engine Model is deployed.\n model: (str), model name.\n data: ([[any]]), list of input instances, where each input instance is a\n list of attributes.\n version: str, version of the model to target.\n\n Returns:\n Mapping[str: any]: dictionary of prediction results defined by the model.\n \"\"\"\n\n service = googleapiclient.discovery.build('ml', 'v1')\n name = 'projects/{}/models/{}'.format(project, model)\n\n if version is not None:\n name += '/versions/{}'.format(version)\n\n response = service.projects().predict(\n name=name, body={\n 'instances': data\n }).execute()\n\n if 'error' in response:\n raise RuntimeError(response['error'])\n\n return response['predictions']\n\n import tensorflow as tf\n import json\n \n mnist = tf.keras.datasets.mnist\n (x_train, y_train),(x_test, y_test) = mnist.load_data()\n x_train, x_test = x_train / 255.0, x_test / 255.0\n\n result = predict(\n project=project_id,\n model=model_name,\n data=x_test[0:2].tolist(),\n version=version)\n print(result)\n \n return json.dumps(result)", "_____no_output_____" ], [ "# # Test the function with already deployed version\n# deployment_test(\n# project_id=PROJECT_ID,\n# model_name=\"mnist\",\n# version='ver_bb1ebd2a06ab7f321ad3db6b3b3d83e6' # previous deployed version for testing\n# )", "_____no_output_____" ], [ "deployment_test_op = comp.func_to_container_op(\n func=deployment_test, \n base_image=\"tensorflow/tensorflow:1.15.0-py3\",\n packages_to_install=[\"google-api-python-client==1.7.8\"])", "_____no_output_____" ] ], [ [ "# Create your workflow as a Python function", "_____no_output_____" ], [ "Define your pipeline as a Python function. ` @kfp.dsl.pipeline` is a required decoration, and must include `name` and `description` properties. Then compile the pipeline function. After the compilation is completed, a pipeline file is created.", "_____no_output_____" ] ], [ [ "# Define the pipeline\[email protected](\n name='Mnist pipeline',\n description='A toy pipeline that performs mnist model training.'\n)\ndef mnist_reuse_component_deploy_pipeline(\n project_id: str = PROJECT_ID,\n model_path: str = 'mnist_model', \n bucket: str = GCS_BUCKET\n):\n train_task = mnist_train_op(\n model_path=model_path, \n bucket=bucket\n ).apply(gcp.use_gcp_secret('user-gcp-sa'))\n \n deploy_task = deploy(\n project_id=project_id,\n model_uri=train_task.outputs['gcs_model_path'],\n model_id=\"mnist\", \n runtime_version=\"1.14\",\n python_version=\"3.5\"\n ).apply(gcp.use_gcp_secret('user-gcp-sa')) \n \n deploy_test_task = deployment_test_op(\n project_id=project_id,\n model_name=deploy_task.outputs[\"model_name\"], \n version=deploy_task.outputs[\"version_name\"],\n ).apply(gcp.use_gcp_secret('user-gcp-sa'))\n \n return True", "_____no_output_____" ] ], [ [ "### Submit a pipeline run", "_____no_output_____" ] ], [ [ "pipeline_func = mnist_reuse_component_deploy_pipeline", "_____no_output_____" ], [ "experiment_name = 'minist_kubeflow'\n\narguments = {\"model_path\":\"mnist_model\",\n \"bucket\":GCS_BUCKET}\n\nrun_name = pipeline_func.__name__ + ' run'\n\n# Submit pipeline directly from pipeline function\nrun_result = client.create_run_from_pipeline_func(pipeline_func, \n experiment_name=experiment_name, \n run_name=run_name, \n arguments=arguments)", "_____no_output_____" ] ], [ [ "**As an alternative, you can compile the pipeline into a package.** The compiled pipeline can be easily shared and reused by others to run the pipeline.\n\n```python\npipeline_filename = pipeline_func.__name__ + '.pipeline.zip'\ncompiler.Compiler().compile(pipeline_func, pipeline_filename)\n\nexperiment = client.create_experiment('python-functions-mnist')\n\nrun_result = client.run_pipeline(\n experiment_id=experiment.id, \n job_name=run_name, \n pipeline_package_path=pipeline_filename, \n params=arguments)\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", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d01e231e1d09dccc72da8ee711a9577a688b5f08
353,021
ipynb
Jupyter Notebook
bronze/B30_Visualization_of_a_Qubit.ipynb
dilyaraahmetshina/quantum_computings
a618bae55def65b17974f3ad402ce27817f91842
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
bronze/B30_Visualization_of_a_Qubit.ipynb
dilyaraahmetshina/quantum_computings
a618bae55def65b17974f3ad402ce27817f91842
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
bronze/B30_Visualization_of_a_Qubit.ipynb
dilyaraahmetshina/quantum_computings
a618bae55def65b17974f3ad402ce27817f91842
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
405.305396
119,020
0.935647
[ [ [ "<table> <tr>\n <td style=\"background-color:#ffffff;\">\n <a href=\"http://qworld.lu.lv\" target=\"_blank\"><img src=\"..\\images\\qworld.jpg\" width=\"25%\" align=\"left\"> </a></td>\n <td style=\"background-color:#ffffff;vertical-align:bottom;text-align:right;\">\n prepared by <a href=\"http://abu.lu.lv\" target=\"_blank\">Abuzer Yakaryilmaz</a> (<a href=\"http://qworld.lu.lv/index.php/qlatvia/\" target=\"_blank\">QLatvia</a>)\n </td> \n</tr></table>", "_____no_output_____" ], [ "<table width=\"100%\"><tr><td style=\"color:#bbbbbb;background-color:#ffffff;font-size:11px;font-style:italic;text-align:right;\">This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. </td></tr></table>\n$ \\newcommand{\\bra}[1]{\\langle #1|} $\n$ \\newcommand{\\ket}[1]{|#1\\rangle} $\n$ \\newcommand{\\braket}[2]{\\langle #1|#2\\rangle} $\n$ \\newcommand{\\dot}[2]{ #1 \\cdot #2} $\n$ \\newcommand{\\biginner}[2]{\\left\\langle #1,#2\\right\\rangle} $\n$ \\newcommand{\\mymatrix}[2]{\\left( \\begin{array}{#1} #2\\end{array} \\right)} $\n$ \\newcommand{\\myvector}[1]{\\mymatrix{c}{#1}} $\n$ \\newcommand{\\myrvector}[1]{\\mymatrix{r}{#1}} $\n$ \\newcommand{\\mypar}[1]{\\left( #1 \\right)} $\n$ \\newcommand{\\mybigpar}[1]{ \\Big( #1 \\Big)} $\n$ \\newcommand{\\sqrttwo}{\\frac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\dsqrttwo}{\\dfrac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\onehalf}{\\frac{1}{2}} $\n$ \\newcommand{\\donehalf}{\\dfrac{1}{2}} $\n$ \\newcommand{\\hadamard}{ \\mymatrix{rr}{ \\sqrttwo & \\sqrttwo \\\\ \\sqrttwo & -\\sqrttwo }} $\n$ \\newcommand{\\vzero}{\\myvector{1\\\\0}} $\n$ \\newcommand{\\vone}{\\myvector{0\\\\1}} $\n$ \\newcommand{\\vhadamardzero}{\\myvector{ \\sqrttwo \\\\ \\sqrttwo } } $\n$ \\newcommand{\\vhadamardone}{ \\myrvector{ \\sqrttwo \\\\ -\\sqrttwo } } $\n$ \\newcommand{\\myarray}[2]{ \\begin{array}{#1}#2\\end{array}} $\n$ \\newcommand{\\X}{ \\mymatrix{cc}{0 & 1 \\\\ 1 & 0} } $\n$ \\newcommand{\\Z}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & -1} } $\n$ \\newcommand{\\Htwo}{ \\mymatrix{rrrr}{ \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} } } $\n$ \\newcommand{\\CNOT}{ \\mymatrix{cccc}{1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 0} } $\n$ \\newcommand{\\norm}[1]{ \\left\\lVert #1 \\right\\rVert } $\n$ \\newcommand{\\pstate}[1]{ \\lceil \\mspace{-1mu} #1 \\mspace{-1.5mu} \\rfloor } $", "_____no_output_____" ], [ "<h2>Visualization of a (Real-Valued) Qubit</h2>", "_____no_output_____" ], [ "_We use certain tools from python library \"<b>matplotlib.pyplot</b>\" for drawing. Check the notebook [Python: Drawing](../python/Python06_Drawing.ipynb) for the list of these tools._", "_____no_output_____" ], [ "Suppose that we have a single qubit. \n\nEach possible (real-valued) quantum state of this qubit is a point on 2-dimensional space.\n\nIt can also be represented as a vector from origin to that point.\n\nWe start with the visual representation of the following quantum states: \n\n$$ \\ket{0} = \\myvector{1\\\\0}, ~~ \\ket{1} = \\myvector{0\\\\1} , ~~ -\\ket{0} = \\myrvector{-1\\\\0}, ~~\\mbox{and}~~ -\\ket{1} = \\myrvector{0\\\\-1}. $$", "_____no_output_____" ], [ "We draw these quantum states as points.\n\nWe use one of our predefined functions for drawing axes: \"draw_axes()\". We include our predefined functions with the following line of code:\n\n %run qlatvia.py", "_____no_output_____" ] ], [ [ "# import the drawing methods\nfrom matplotlib.pyplot import plot, figure, show\n\n# draw a figure\nfigure(figsize=(6,6), dpi=80)\n\n# include our predefined functions\n%run qlatvia.py\n\n# draw the axes\ndraw_axes()\n\n# draw the origin\nplot(0,0,'ro') # a point in red color\n\n# draw these quantum states as points (in blue color)\nplot(1,0,'bo') \nplot(0,1,'bo')\nplot(-1,0,'bo')\nplot(0,-1,'bo')\n\nshow()", "_____no_output_____" ] ], [ [ "Now, we draw the quantum states as arrows (vectors):", "_____no_output_____" ] ], [ [ "# import the drawing methods\nfrom matplotlib.pyplot import figure, arrow, show\n\n# draw a figure\nfigure(figsize=(6,6), dpi=80)\n\n# include our predefined functions\n%run qlatvia.py\n\n# draw the axes\ndraw_axes()\n\n# draw the quantum states as vectors (in blue color)\narrow(0,0,0.92,0,head_width=0.04, head_length=0.08, color=\"blue\")\narrow(0,0,0,0.92,head_width=0.04, head_length=0.08, color=\"blue\")\narrow(0,0,-0.92,0,head_width=0.04, head_length=0.08, color=\"blue\")\narrow(0,0,0,-0.92,head_width=0.04, head_length=0.08, color=\"blue\")\n\nshow()", "_____no_output_____" ] ], [ [ "<h3> Task 1 </h3>\n\nWrite a function that returns a randomly created 2-dimensional (real-valued) quantum state.\n\n_You can use your code written for [a task given in notebook \"Quantum State](B28_Quantum_State.ipynb#task2)._\n\nCreate 100 random quantum states by using your function and then draw all of them as points.\n\nCreate 1000 random quantum states by using your function and then draw all of them as points.\n\nThe different colors can be used when drawing the points ([matplotlib.colors](https://matplotlib.org/2.0.2/api/colors_api.html)).", "_____no_output_____" ] ], [ [ "# randomly creating a 2-dimensional quantum state\nfrom random import randrange\ndef random_quantum_state():\n first_entry = randrange(-100,101)\n second_entry = randrange(-100,101)\n length_square = first_entry**2+second_entry**2\n while length_square == 0:\n first_entry = randrange(-100,101)\n second_entry = randrange(-100,101)\n length_square = first_entry**2+second_entry**2\n first_entry = first_entry / length_square**0.5\n second_entry = second_entry / length_square**0.5\n return [first_entry,second_entry]", "_____no_output_____" ], [ "# import the drawing methods\nfrom matplotlib.pyplot import plot, figure\n\n# draw a figure\nfigure(figsize=(6,6), dpi=60) \n\n# draw the origin\nplot(0,0,'ro') \n\nfrom random import randrange\ncolors = ['ro','bo','go','yo','co','mo','ko']\n\nfor i in range(100):\n # create a random quantum state\n quantum_state = random_quantum_state(); \n # draw a blue point for the random quantum state\n x = quantum_state[0];\n y = quantum_state[1];\n plot(x,y,colors[randrange(len(colors))]) \n\nshow()", "_____no_output_____" ], [ "# randomly creating a 2-dimensional quantum state\nfrom random import randrange\ndef random_quantum_state():\n first_entry = randrange(-1000,1001)\n second_entry = randrange(-1000,1001)\n length_square = first_entry**2+second_entry**2\n while length_square == 0:\n first_entry = randrange(-100,101)\n second_entry = randrange(-100,101)\n length_square = first_entry**2+second_entry**2\n first_entry = first_entry / length_square**0.5\n second_entry = second_entry / length_square**0.5\n return [first_entry,second_entry]", "_____no_output_____" ], [ "# import the drawing methods\nfrom matplotlib.pyplot import plot, figure\n\n# draw a figure\nfigure(figsize=(6,6), dpi=60) \n\n# draw the origin\nplot(0,0,'ro') \n\nfrom random import randrange\ncolors = ['ro','bo','go','yo','co','mo','ko']\n\nfor i in range(1000):\n # create a random quantum state\n quantum_state = random_quantum_state(); \n # draw a blue point for the random quantum state\n x = quantum_state[0];\n y = quantum_state[1];\n plot(x,y,colors[randrange(len(colors))]) \n\nshow()", "_____no_output_____" ] ], [ [ "<a href=\"B30_Visualization_of_a_Qubit_Solutions.ipynb#task1\">click for our solution</a>", "_____no_output_____" ], [ "<h3> Task 2 </h3>\n\nRepeat the previous task by drawing the quantum states as vectors (arrows) instead of points.\n\nThe different colors can be used when drawing the points ([matplotlib.colors](https://matplotlib.org/2.0.2/api/colors_api.html)).\n\n_Please keep the codes below for drawing axes for getting a better visual focus._", "_____no_output_____" ] ], [ [ "# randomly creating a 2-dimensional quantum state\nfrom random import randrange\ndef random_quantum_state():\n first_entry = randrange(-1000,1001)\n second_entry = randrange(-1000,1001)\n length_square = first_entry**2+second_entry**2\n while length_square == 0:\n first_entry = randrange(-100,101)\n second_entry = randrange(-100,101)\n length_square = first_entry**2+second_entry**2\n first_entry = first_entry / length_square**0.5\n second_entry = second_entry / length_square**0.5\n return [first_entry,second_entry]", "_____no_output_____" ], [ "# import the drawing methods\nfrom matplotlib.pyplot import plot, figure, arrow\n\n# draw a figure\nfigure(figsize=(6,6), dpi=60) \n\n# include our predefined functions\n%run qlatvia.py\n\n# draw the axes\ndraw_axes()\n\n# draw the origin\nplot(0,0,'ro') \n\nfrom random import randrange\ncolors = ['r','b','g','y','b','c','m']\n\nfor i in range(500):\n quantum_state = random_quantum_state(); \n x = quantum_state[0];\n y = quantum_state[1];\n x = 0.92 * x\n y = 0.92 * y\n arrow(0,0,x,y,head_width=0.04,head_length=0.08,color=colors[randrange(len(colors))])\n\nshow()", "_____no_output_____" ] ], [ [ "<a href=\"B30_Visualization_of_a_Qubit_Solutions.ipynb#task2\">click for our solution</a>", "_____no_output_____" ], [ "<h3> Unit circle </h3>\n\nAll quantum states of a qubit form the unit circle.\n\nThe length of each quantum state is 1.\n\nAll points that are 1 unit away from the origin form the circle with radius 1 unit.\n\nWe can draw the unit circle with python.\n\nWe have a predefined function for drawing the unit circle: \"draw_unit_circle()\".", "_____no_output_____" ] ], [ [ "# import the drawing methods\nfrom matplotlib.pyplot import figure\n\nfigure(figsize=(6,6), dpi=80) # size of the figure\n\n# include our predefined functions\n%run qlatvia.py\n\n# draw axes\ndraw_axes()\n\n# draw the unit circle\ndraw_unit_circle()", "_____no_output_____" ] ], [ [ "<h3>Quantum state of a qubit</h3>", "_____no_output_____" ], [ "Suppose that we have a single qubit. \n\nEach possible (real-valued) quantum state of this qubit is a point on 2-dimensional space.\n\nIt can also be represented as a vector from origin to that point.\n\nWe draw the quantum state $ \\myvector{3/5 \\\\ 4/5} $ and its elements.", "_____no_output_____" ], [ "<i style=\"font-size:10pt;\">\nOur predefined function \"draw_qubit()\" draws a figure, the origin, the axes, the unit circle, and base quantum states.\n<br>\nOur predefined function \"draw_quantum_state(x,y,name)\" draws an arrow from (0,0) to (x,y) and associates it with <u>name</u>.\n<br>\nWe include our predefined functions with the following line of code:\n \n %run qlatvia.py\n</i> ", "_____no_output_____" ] ], [ [ "%run qlatvia.py\n\ndraw_qubit()\n\ndraw_quantum_state(3/5,4/5,\"|v>\")", "_____no_output_____" ] ], [ [ "Now, we draw its angle with $ \\ket{0} $-axis and its projections on both axes.\n\n<i> For drawing the angle, we use the method \"Arc\" from library \"matplotlib.patches\". </i> ", "_____no_output_____" ] ], [ [ "%run qlatvia.py\n\ndraw_qubit()\n\ndraw_quantum_state(3/5,4/5,\"|v>\")\n\nfrom matplotlib.pyplot import arrow, text, gca\n\n# the projection on |0>-axis\narrow(0,0,3/5,0,color=\"blue\",linewidth=1.5)\narrow(0,4/5,3/5,0,color=\"blue\",linestyle='dotted')\ntext(0.1,-0.1,\"cos(a)=3/5\")\n\n# the projection on |1>-axis\narrow(0,0,0,4/5,color=\"blue\",linewidth=1.5)\narrow(3/5,0,0,4/5,color=\"blue\",linestyle='dotted')\ntext(-0.1,0.55,\"sin(a)=4/5\",rotation=\"90\")\n\n# drawing the angle with |0>-axis\nfrom matplotlib.patches import Arc\ngca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=53) )\ntext(0.08,0.05,'.',fontsize=30)\ntext(0.21,0.09,'a')", "_____no_output_____" ] ], [ [ "<b> Observations: </b>\n<ul>\n <li> The angle of quantum state with state $ \\ket{0} $ is $a$.</li> \n <li> The amplitude of state $ \\ket{0} $ is $ \\cos(a) = \\frac{3}{5} $.</li>\n <li> The probability of observing state $ \\ket{0} $ is $ \\cos^2(a) = \\frac{9}{25} $.</li>\n <li> The amplitude of state $ \\ket{1} $ is $ \\sin(a) = \\frac{4}{5} $.</li>\n <li> The probability of observing state $ \\ket{1} $ is $ \\sin^2(a) = \\frac{16}{25} $.</li>\n</ul>", "_____no_output_____" ], [ "<h3> The angle of a quantum state </h3>\n\nThe angle of a vector (in radians) on the unit circle is the length of arc in counter-clockwise direction that starts from $ (1,0) $ and with the points representing the vector.\n\nWe execute the following code a couple of times to see different examples, where the angle is picked randomly in each run.\n\nYou can also set the value of \"myangle\" manually for seeing a specific angle.", "_____no_output_____" ] ], [ [ "# set the angle\n\nfrom random import randrange\nmyangle = randrange(361)\n\n################################################\n\nfrom matplotlib.pyplot import figure,gca\nfrom matplotlib.patches import Arc\nfrom math import sin,cos,pi\n\n# draw a figure\nfigure(figsize=(6,6), dpi=60)\n\n%run qlatvia.py\n\ndraw_axes()\n\nprint(\"the selected angle is\",myangle,\"degrees\")\n\nratio_of_arc = ((1000*myangle/360)//1)/1000\n\nprint(\"it is\",ratio_of_arc,\"of a full circle\")\n\nprint(\"its length is\",ratio_of_arc,\"x 2\\u03C0\",\"=\",ratio_of_arc*2*pi)\n\nmyangle_in_radian = 2*pi*(myangle/360)\n\nprint(\"its radian value is\",myangle_in_radian)\n\ngca().add_patch( Arc((0,0),0.2,0.2,angle=0,theta1=0,theta2=myangle,color=\"red\",linewidth=2) )\n\ngca().add_patch( Arc((0,0),2,2,angle=0,theta1=0,theta2=myangle,color=\"brown\",linewidth=2) )\n\nx = cos(myangle_in_radian)\ny = sin(myangle_in_radian)\n\ndraw_quantum_state(x,y,\"|v>\")\n\n# the projection on |0>-axis\narrow(0,0,x,0,color=\"blue\",linewidth=1)\narrow(0,y,x,0,color=\"blue\",linestyle='dashed')\n\n# the projection on |1>-axis\narrow(0,0,0,y,color=\"blue\",linewidth=1)\narrow(x,0,0,y,color=\"blue\",linestyle='dashed')\n\nprint()\nprint(\"the amplitude of state |0> is\",x)\nprint(\"the amplitude of state |1> is\",y)\nprint()\nprint(\"the probability of observing state |0> is\",x*x)\nprint(\"the probability of observing state |1> is\",y*y)\nprint(\"the total probability is\",round(x*x+y*y,6))", "the selected angle is 27 degrees\nit is 0.075 of a full circle\nits length is 0.075 x 2π = 0.47123889803846897\nits radian value is 0.47123889803846897\n\nthe amplitude of state |0> is 0.8910065241883679\nthe amplitude of state |1> is 0.45399049973954675\n\nthe probability of observing state |0> is 0.7938926261462367\nthe probability of observing state |1> is 0.2061073738537634\nthe total probability is 1.0\n" ] ], [ [ "<h3> Random quantum states </h3>\n\nAny quantum state of a (real-valued) qubit is a point on the unit circle.\n\nWe use this fact to create random quantum states by picking a random point on the unit circle. \n\nFor this purpose, we randomly pick an angle between zero and 360 degrees and then find the amplitudes of the quantum state by using the basic trigonometric functions.", "_____no_output_____" ], [ "<a id=\"task3\"></a>\n<h3> Task 3 </h3>\n\nDefine a function randomly creating a quantum state based on this idea.\n\nRandomly create a quantum state by using this function.\n\nDraw the quantum state on the unit circle.\n\nRepeat the task for a few times.\n\nRandomly create 100 quantum states and draw all of them.", "_____no_output_____" ], [ "<i> You can save your function for using later: comment out the first command, give an appropriate file name, and then run the cell.</i>", "_____no_output_____" ] ], [ [ "# %%writefile FILENAME.py \n# randomly creating a 2-dimensional quantum state\nfrom random import randrange\ndef random_quantum_state2():\n angle_degree = randrange(360)\n angle_radian = 2*pi*angle/360\n return [cos(angle_radian),sin(angle_radian)]", "_____no_output_____" ] ], [ [ "<i style=\"font-size:10pt;\">\nOur predefined function \"draw_qubit()\" draws a figure, the origin, the axes, the unit circle, and base quantum states.\n<br>\nOur predefined function \"draw_quantum_state(x,y,name)\" draws an arrow from (0,0) to (x,y) and associates it with <u>name</u>.\n<br>\nWe include our predefined functions with the following line of code:\n \n %run qlatvia.py\n</i> ", "_____no_output_____" ] ], [ [ "# visually test your function\n%run qlatvia.py\n\n# draw the axes\ndraw_qubit()\n\nfrom random import randrange\nfor i in range(6):\n [x,y]=random_quantum_state2()\n draw_quantum_state(x,y,\"|v\"+str(i)+\">\")", "_____no_output_____" ], [ "# include our predefined functions\n%run qlatvia.py\n\n# draw the axes\ndraw_qubit()\n\nfor i in range(100):\n [x,y]=random_quantum_state2()\n draw_quantum_state(x,y,\"\")", "_____no_output_____" ] ], [ [ "<a href=\"B30_Visualization_of_a_Qubit_Solutions.ipynb#task3\">click for our solution</a>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d01e36f57ce791dc49c33d7879b376085ed30527
199,537
ipynb
Jupyter Notebook
notebooks/eda_ravi.ipynb
Windbenders/capstone_energy
520cada122e5ee16c81b19d1c93ec29771f458e1
[ "MIT" ]
null
null
null
notebooks/eda_ravi.ipynb
Windbenders/capstone_energy
520cada122e5ee16c81b19d1c93ec29771f458e1
[ "MIT" ]
null
null
null
notebooks/eda_ravi.ipynb
Windbenders/capstone_energy
520cada122e5ee16c81b19d1c93ec29771f458e1
[ "MIT" ]
2
2021-12-27T12:22:23.000Z
2021-12-28T08:29:53.000Z
93.067631
38,702
0.758351
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport statsmodels.api as sm\nimport pylab", "_____no_output_____" ], [ "df1 = pd.read_csv('data/power_act_.csv') \n", "_____no_output_____" ] ], [ [ " 'power_act_.csv'\n\n In total we have 18 columns and 64328 rows \n\n Coulmns names : \n ['dt_start_utc', 'power_act_21', 'power_act_24', 'power_act_47' .....]\n\n\n date ranges from '2019-06-30' to '2021-04-30'\n\n Date seems to be recorded for every 15 minutes\n\nAll the columns contains missing values only for 'power_act_21' its 1.5% whereas >20% for other features", "_____no_output_____" ] ], [ [ "df1.tail(10)", "_____no_output_____" ], [ "df1.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 64328 entries, 0 to 64327\nData columns (total 18 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 dt_start_utc 64328 non-null object \n 1 power_act_21 63323 non-null float64\n 2 power_act_24 35870 non-null float64\n 3 power_act_47 51966 non-null float64\n 4 power_act_84 35820 non-null float64\n 5 power_act_176 21472 non-null float64\n 6 power_act_179 11574 non-null float64\n 7 power_act_183 11634 non-null float64\n 8 power_act_196 36264 non-null float64\n 9 power_act_202 32659 non-null float64\n 10 power_act_206 36155 non-null float64\n 11 power_act_222 20587 non-null float64\n 12 power_act_233 35804 non-null float64\n 13 power_act_291 6976 non-null float64\n 14 power_act_292 6324 non-null float64\n 15 power_act_293 11608 non-null float64\n 16 power_act_308 11604 non-null float64\n 17 power_act_336 11434 non-null float64\ndtypes: float64(17), object(1)\nmemory usage: 8.8+ MB\n" ], [ "df1.describe()", "_____no_output_____" ], [ "df1.isnull().sum().sort_values(ascending=False)/len(df1)*100", "_____no_output_____" ], [ "df1['dt_start_utc'] = df1['dt_start_utc'].apply(pd.to_datetime)", "_____no_output_____" ], [ "df1 = df1.set_index('dt_start_utc')", "_____no_output_____" ], [ "plt.figure(figsize=(10,6))\ndf1['power_act_21'].plot()\n", "_____no_output_____" ], [ "plt.figure(figsize=(10,6))\ndf1['power_act_47'].plot()", "_____no_output_____" ], [ "plt.figure(figsize=(10,6))\ndf1['power_act_196'].plot()", "_____no_output_____" ], [ "df2 = pd.read_csv('data/power_fc_.csv') ", "_____no_output_____" ] ], [ [ "'power_fc_.csv'\n\n In total we have 23 columns and 66020 rows \n\n Coulmns names : \n ['dt_start_utc', 'power_act_21', 'power_act_24', 'power_act_47' .....]\n\n\n date ranges from ''2019-06-13 07:00'' to ''2021-04-30 23:45''\n\n Date seems to be recorded for every 15 minutes\n\nno null values for 'power_act_21' whereas for other features >17% null values", "_____no_output_____" ] ], [ [ "df2['dt_start_utc'].max()", "_____no_output_____" ], [ "df2.head()", "_____no_output_____" ], [ "df2.shape", "_____no_output_____" ], [ "df2.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 66020 entries, 0 to 66019\nData columns (total 23 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 dt_start_utc 66020 non-null object \n 1 power_fc_21 66020 non-null float64\n 2 power_fc_24 36708 non-null float64\n 3 power_fc_47 54789 non-null float64\n 4 power_fc_48 18400 non-null float64\n 5 power_fc_51 18400 non-null float64\n 6 power_fc_176 21934 non-null float64\n 7 power_fc_179 11639 non-null float64\n 8 power_fc_183 11639 non-null float64\n 9 power_fc_196 36708 non-null float64\n 10 power_fc_202 33261 non-null float64\n 11 power_fc_206 36612 non-null float64\n 12 power_fc_222 21934 non-null float64\n 13 power_fc_233 36708 non-null float64\n 14 power_fc_291 11624 non-null float64\n 15 power_fc_292 11624 non-null float64\n 16 power_fc_293 11624 non-null float64\n 17 power_fc_308 11624 non-null float64\n 18 power_fc_322 11624 non-null float64\n 19 power_fc_325 11624 non-null float64\n 20 power_fc_327 11624 non-null float64\n 21 power_fc_336 11624 non-null float64\n 22 power_fc_339 11624 non-null float64\ndtypes: float64(22), object(1)\nmemory usage: 11.6+ MB\n" ], [ "df2.isnull().sum().sort_values(ascending=False)/len(df1)*100", "_____no_output_____" ], [ "df2['dt_start_utc'] = df2['dt_start_utc'].apply(pd.to_datetime)\n#df2 = df2.reset_index('dt_start_utc')", "_____no_output_____" ], [ "df2['dt_start_utc'] = df2['dt_start_utc'].apply(pd.to_datetime)", "_____no_output_____" ], [ "df2.head()", "_____no_output_____" ], [ "df3 = pd.read_csv('data/regelleistung_aggr_results.csv')\n", "_____no_output_____" ] ], [ [ " 'regelleistung_aggr_results.csv'\n\n In total we have 17 columns and 16068 rows \n\n Coulmns names : \n ['date_start', 'date_end', 'product', 'reserve_type', 'total_min_capacity_price_eur_mw',# \n 'total_average_capacity_price_eur_mw', 'total_marginal_capacity_price_eur_mw','total_min_energy_price_eur_mwh', 'total_average_energy_price_eur_mwh', 'total_marginal_energy_price_eur_mwh', 'germany_min_capacity_price_eur_mw',\n 'germany_average_capacity_price_eur_mw', 'germany_marginal_capacity_price_eur_mw','germany_min_energy_price_eur_mwh',\n 'germany_average_energy_price_eur_mwh', 'germany_marginal_energy_price_eur_mwh', 'germany_import_export_mw']\n\n 2 unique reserve type ['MRL', 'SRL']\n\n 12 unique product type ['NEG_00_04', 'NEG_04_08', 'NEG_08_12', 'NEG_12_16', 'NEG_16_20','NEG_20_24', 'POS_00_04', 'POS_04_08', 'POS_08_12', 'POS_12_16', 'POS_16_20', 'POS_20_24']\n\n date ranges from '2019-01-01' to '2021-03-19'\n\n Date seems to be recorded for every hours (24 values for each days)\n\n Few columns contains missing values of about 37%", "_____no_output_____" ] ], [ [ "df3.shape", "_____no_output_____" ], [ "df3.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 16068 entries, 0 to 16067\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 date_start 16068 non-null object \n 1 date_end 16068 non-null object \n 2 product 16068 non-null object \n 3 reserve_type 16068 non-null object \n 4 total_min_capacity_price_eur_mw 16068 non-null float64\n 5 total_average_capacity_price_eur_mw 16068 non-null float64\n 6 total_marginal_capacity_price_eur_mw 16068 non-null float64\n 7 total_min_energy_price_eur_mwh 15828 non-null float64\n 8 total_average_energy_price_eur_mwh 15828 non-null float64\n 9 total_marginal_energy_price_eur_mwh 15828 non-null float64\n 10 germany_min_capacity_price_eur_mw 16068 non-null float64\n 11 germany_average_capacity_price_eur_mw 16068 non-null float64\n 12 germany_marginal_capacity_price_eur_mw 16068 non-null float64\n 13 germany_min_energy_price_eur_mwh 15828 non-null float64\n 14 germany_average_energy_price_eur_mwh 15828 non-null float64\n 15 germany_marginal_energy_price_eur_mwh 15828 non-null float64\n 16 germany_import_export_mw 16068 non-null int64 \ndtypes: float64(12), int64(1), object(4)\nmemory usage: 2.1+ MB\n" ], [ "df3.groupby(by='date_start').count().head(2)", "_____no_output_____" ], [ "df3['reserve_type'].unique()", "_____no_output_____" ], [ "df3['product'].unique()", "_____no_output_____" ], [ "#sns.pairplot(df3)", "_____no_output_____" ], [ "df3.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 16068 entries, 0 to 16067\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 date_start 16068 non-null object \n 1 date_end 16068 non-null object \n 2 product 16068 non-null object \n 3 reserve_type 16068 non-null object \n 4 total_min_capacity_price_eur_mw 16068 non-null float64\n 5 total_average_capacity_price_eur_mw 16068 non-null float64\n 6 total_marginal_capacity_price_eur_mw 16068 non-null float64\n 7 total_min_energy_price_eur_mwh 15828 non-null float64\n 8 total_average_energy_price_eur_mwh 15828 non-null float64\n 9 total_marginal_energy_price_eur_mwh 15828 non-null float64\n 10 germany_min_capacity_price_eur_mw 16068 non-null float64\n 11 germany_average_capacity_price_eur_mw 16068 non-null float64\n 12 germany_marginal_capacity_price_eur_mw 16068 non-null float64\n 13 germany_min_energy_price_eur_mwh 15828 non-null float64\n 14 germany_average_energy_price_eur_mwh 15828 non-null float64\n 15 germany_marginal_energy_price_eur_mwh 15828 non-null float64\n 16 germany_import_export_mw 16068 non-null int64 \ndtypes: float64(12), int64(1), object(4)\nmemory usage: 2.1+ MB\n" ], [ "df3.isnull().sum().sort_values(ascending=False)/len(df1)*100", "_____no_output_____" ], [ "df3.shape", "_____no_output_____" ], [ "df4 = pd.read_csv('data/regelleistung_demand.csv')", "_____no_output_____" ], [ "df4.head()", "_____no_output_____" ] ], [ [ " 'regelleistung_demand.csv'\n\n In total we have 6 columns and 16188 rows \n\n Coulmns names : ['date_start', 'date_end', 'product', 'total_demand_mw',\n 'germany_block_demand_mw', 'reserve_type']\n\n 2 unique reserve type ['MRL', 'SRL']\n\n 12 unique product type ['NEG_00_04', 'NEG_04_08', 'NEG_08_12', 'NEG_12_16', 'NEG_16_20','NEG_20_24', 'POS_00_04', 'POS_04_08', 'POS_08_12', 'POS_12_16', 'POS_16_20', 'POS_20_24']\n\n date ranges from '2019-01-01' to '2021-03-18'\n\n Date seems to be recorded for every hours (24 values for each days)\n\nno missing values ", "_____no_output_____" ] ], [ [ "df4.isnull().sum().sort_values(ascending=False)", "_____no_output_____" ], [ "def check_unique(df):\n ''' check unique values for each columns and \n print them if they are below 15'''\n\n for col in df.columns:\n n = df[col].nunique()\n print(f'{col} has {n} unique values')\n if n < 15:\n print(df[col].unique())", "_____no_output_____" ], [ "df4.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 16188 entries, 0 to 16187\nData columns (total 6 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 date_start 16188 non-null object\n 1 date_end 16188 non-null object\n 2 product 16188 non-null object\n 3 total_demand_mw 16188 non-null int64 \n 4 germany_block_demand_mw 16188 non-null int64 \n 5 reserve_type 16188 non-null object\ndtypes: int64(2), object(4)\nmemory usage: 758.9+ KB\n" ], [ "sns.pairplot(df4)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d01e405384d386061f20e84427f196aa07480e1c
20,143
ipynb
Jupyter Notebook
theory/dqmc.ipynb
dylanljones/dqmc
d4969b6624c1b596d8b2fd0dcaefb16064958eee
[ "MIT" ]
1
2022-01-18T22:27:47.000Z
2022-01-18T22:27:47.000Z
theory/dqmc.ipynb
dylanljones/dqmc
d4969b6624c1b596d8b2fd0dcaefb16064958eee
[ "MIT" ]
null
null
null
theory/dqmc.ipynb
dylanljones/dqmc
d4969b6624c1b596d8b2fd0dcaefb16064958eee
[ "MIT" ]
null
null
null
54.736413
655
0.564911
[ [ [ "# Determinant Quantum Monte Carlo", "_____no_output_____" ], [ "## 1 Hubbard model\n\nThe Hubbard model is defined as\n\n\\begin{align}\n \\label{eq:ham} \\tag{1}\n H &= -\\sum_{ij\\sigma} t_{ij} \\left( \\hat{c}_{i\\sigma}^\\dagger \\hat{c}_{j\\sigma} + hc \\right) \n + \\sum_{i\\sigma} (\\varepsilon_i - \\mu) \\hat{n}_{i\\sigma} \n + U \\sum_{i} \\left( \\hat{n}_{i\\uparrow} - \\tfrac{1}{2} \\right) \\left( \\hat{n}_{i\\downarrow} - \\tfrac{1}{2} \\right)\n\\end{align}\n\nwhere $U$ is the interaction strength, $\\varepsilon_i$ the on-site energy at site $i$ and $t_{ij}$ the hopping energy between the sites $i$ and $j$. The chemical potential is defined to be $\\mu = 0$ for a half filled Hubabrd model since the total chemical potential is given as $\\mu + \\tfrac{U}{2}$:\n\n\\begin{equation}\n H = -\\sum_{ij\\sigma} t_{ij} \\left( \\hat{c}_{i\\sigma}^\\dagger \\hat{c}_{j\\sigma} + hc \\right) \n + \\sum_{i\\sigma} \\left(\\varepsilon_i - \\mu - \\tfrac{U}{2}\\right) \\hat{n}_{i\\sigma}\n + U \\sum_{i} \\hat{n}_{i\\uparrow} \\hat{n}_{i\\downarrow}.\n\\end{equation}\n\nThe non-interacting of the Hubbard Hamiltonian is quadratic in the creation and annihilation operators,\n\n\\begin{equation}\n K = -\\sum_{ij\\sigma} t_{ij} \\left( \\hat{c}_{i\\sigma}^\\dagger \\hat{c}_{j\\sigma} + hc \\right) \n + \\sum_{i\\sigma} (\\varepsilon_i - \\mu) \\hat{n}_{i\\sigma}, \n \\label{eq:ham_kin} \\tag{2}\n\\end{equation}\n\nwhile the interaction part is quartic in the fermion operators:\n\n\\begin{equation}\n V = U \\sum_{i} \\left( \\hat{n}_{i\\uparrow} - \\tfrac{1}{2} \\right) \\left( \\hat{n}_{i\\downarrow} - \\tfrac{1}{2} \\right). \n \\label{eq:ham_inter} \\tag{3}\n\\end{equation}\n\n", "_____no_output_____" ], [ "## 2 Distribution operator\n\n\nThe expectation value of a observable $O$ is given by\n\n\\begin{equation}\n \\langle O \\rangle = \\text{Tr}(O \\mathcal{P}),\n\\end{equation}\n\nwhere $\\mathcal{P}$ is the distribution operator,\n\n\\begin{equation}\n \\mathcal{P} = \\frac{1}{\\mathcal{Z}} e^{-\\beta H},\n \\label{eq:distop} \\tag{4}\n\\end{equation}\n\n$\\mathcal{Z}$ is the partition function,\n\n\\begin{equation}\n \\mathcal{Z} = \\text{Tr}(e^{-\\beta H}),\n \\label{eq:partition}\n\\end{equation}\n\nand $\\beta = 1/k_B T$ is the inverse of the temperature. The trace is taken over the Hilbert space describing all occupied states of the system:\n\n\\begin{equation}\n \\text{Tr}(e^{-\\beta H}) = \\sum_i \\langle \\psi_i | e^{-\\beta H} | \\psi_i \\rangle.\n\\end{equation}\n\nIn order to obtain a computable approximation of the distribution operator the partition function has to be approximated. Since the quadratic term $ K $ and quartic term $ V $ of the Hubbard Hamiltonian do not commute a Trotter-Suzuki decomposition has to be used to approximate $\\mathcal{Z}$. By dividing the imaginary-time interval from $0$ to $\\beta$ into $L$ intervals of size $\\Delta \\tau = \\beta / L$, the partition function can be written as\n\n\\begin{equation}\n \\label{eq:partitionTrotterDecomp}\n \\mathcal{Z} = \\text{Tr}(e^{-\\beta H }) = \\text{Tr}( \\prod_{l=1}^{L} e^{-\\Delta \\tau H}) \n = \\text{Tr}( \\prod_{l=1}^{L} e^{-\\Delta \\tau K} e^{-\\Delta \\tau V}) + \\mathcal{O}(\\Delta \\tau^2).\n\\end{equation}\n\nThe spin-up and spin-down operators of the quadratic kinetic energy term are independent and can be written as\n\n\\begin{equation}\n e^{-\\Delta \\tau K} = e^{-\\Delta \\tau K_\\uparrow} e^{-\\Delta \\tau K_\\downarrow}.\n\\end{equation}\n\nThe particle number operators $\\hat{n}_{i\\sigma}$ in the interacting term of the Hubbard Hamiltonian are independent of the site index $i$:\n\n\\begin{equation}\n e^{-\\Delta \\tau V} = e^{- U \\Delta\\tau \\sum_{i=1}^N \n \\left( \\hat{n}_{i\\uparrow} - \\tfrac{1}{2} \\right) \\left( \\hat{n}_{i\\downarrow} - \\tfrac{1}{2} \\right)} \n = \\prod_{i=1}^N e^{- U \\Delta\\tau \\left( \\hat{n}_{i\\uparrow} - \\tfrac{1}{2} \\right) \\left( \\hat{n}_{i\\downarrow} - \\tfrac{1}{2} \\right)}\n\\end{equation}\n\nThe quartic contributions of the interacting term need to be represented in a quadratic form. This can be achieved by using the discrete \\emph{Hubbard-Stratonovich} transformation, which replaces the term $\\left( \\hat{n}_{i\\uparrow} - \\tfrac{1}{2} \\right) \\left( \\hat{n}_{i\\downarrow} - \\tfrac{1}{2} \\right)$ by a quadratic term of the form $\\left( \\hat{n}_{i\\uparrow} - \\hat{n}_{i\\downarrow} \\right)$. For $U>0$, this yields\n\n\\begin{equation}\n \\label{eq:hubbardStratanovichInteractionTerm}\n e^{- U \\Delta\\tau \\left( \\hat{n}_{i\\uparrow} - \\tfrac{1}{2} \\right) \\left( \\hat{n}_{i\\downarrow} - \\tfrac{1}{2} \\right)} = C \\sum_{h_i = \\pm 1} e^{\\nu h_i \\left( \\hat{n}_{i\\uparrow} - \\hat{n}_{i\\downarrow} \\right)},\n\\end{equation}\n\nwhere $C=\\frac{1}{2} e^{-\\frac{U \\Delta\\tau}{4}}$ and the constant $\\nu$ is defined by\n\\begin{equation}\n \\label{eq:lambda}\n \\cosh \\nu = e^{-\\frac{U \\Delta\\tau}{2}}.\n\\end{equation}\n\nThe set of auxiliary variables $\\lbrace h_i \\rbrace$ is called the *Hubbard-Stratonovich field* or *configuration*. The variables $h_i$ take the values $\\pm 1$ for a up- or down-spin, respectively. Using the Hubbard-Stratanovich transformation the interaction term can be formulated as\n\n\\begin{equation}\n\\begin{split}\n \\label{eq:hubbardStratanovichInteractionFull}\n e^{-\\Delta\\tau V} &= \\prod_{i=1}^N \\left(C \\sum_{h_i = \\pm 1} e^{\\nu h_i \\left( \\hat{n}_{i\\uparrow} - \\hat{n}_{i\\downarrow} \\right)}\\right) \\\\\n &= C^N \\sum_{h_i = \\pm 1} e^{\\sum_{i=1}^N \\nu h_i \\left( \\hat{n}_{i\\uparrow} - \\hat{n}_{i\\downarrow} \\right)} \\\\\n &= C^N \\text{Tr}_h e^{\\sum_{i=1}^N \\nu h_i \\left( \\hat{n}_{i\\uparrow} - \\hat{n}_{i\\downarrow} \\right)} \\\\\n &= C^N \\text{Tr}_h e^{\\sum_{i=1}^N \\nu h_i \\hat{n}_{i\\uparrow}} e^{-\\sum_{i=1}^N \\nu h_i \\hat{n}_{i\\downarrow}} \\\\\n &= C^N \\text{Tr}_h e^{V_\\uparrow} e^{V_\\downarrow}\n\\end{split}\n\\end{equation}\nwhere\n\\begin{equation}\n V_\\sigma = \\sum_{i=1}^N \\nu h_i \\hat{n}_{i\\sigma} = \\sigma \\nu \\boldsymbol{\\hat{c}}_\\sigma^\\dagger V(h) \\boldsymbol{\\hat{c}}_\\sigma\n\\end{equation}\n\n\nand $V(h)$ is a diagonal matrix of the configurations $V(h) = \\text{diag}(h_1, h_2, \\dots, h_N)$. Taking into account the $L$ imaginary time slices, the Hubbard-Stratonovich variables are expanded to have two indices $h_{i, l}$, where $i$ represents the site index and $l$ the imaginary time slice:\n\n\\begin{equation}\n h_i \\longrightarrow h_{il}, \\quad V(h) \\longrightarrow V_l(h_l), \\quad V_\\sigma \\longrightarrow V_{l\\sigma}.\n\\end{equation}\n\nThe Hubbard-Stratonovich field or configuration now is a $N \\times L$ matrix for a system of $N$ sites with $L$ time steps. \nTherefore, the partition function can be approximated by\n\n\\begin{equation}\n \\label{eq:partitionApproximation} \\tag{5}\n \\mathcal{Z} = \\eta_d \\text{Tr}_h \\text{Tr} \\left( \\prod_{l=1}^L e^{-\\Delta\\tau K_\\uparrow} e^{V_{l\\uparrow}} \\right) \\left( \\prod_{l=1}^L e^{-\\Delta\\tau K_\\downarrow} e^{V_{l\\downarrow}} \\right),\n\\end{equation}\n\nwhere $\\eta_d = C^{NL}$ is a normalization constant. At this point, all operators are quadratic in the fermion operators. For any quadratic operator\n\n\\begin{equation}\n H_l = \\sum_{ij} \\hat{c}_i^\\dagger (H_l)_{ij} \\hat{c}_j\n\\end{equation}\n\nthe trace can be computed via the a determinant:\n\n\\begin{equation}\n \\text{Tr}(e^{-H_1}e^{-H_2} \\dots e^{-H_L}) = \\det(I + e^{-H_L} e^{-H_{L-1}} \\dots e^{-H_1} )\n\\end{equation}\n\nUsing this identity, the trace in the expression of the partition function \\eqref{eq:partitionApproximation} can be turned into a computable form:\n\n\\begin{equation}\n \\label{eq:partitionComputable} \\tag{6}\n \\mathcal{Z}_h = \\eta_d \\text{Tr}_h \\det[M_\\uparrow(h)] \\det[M_\\downarrow(h)],\n\\end{equation}\n\nwhere for $\\sigma = \\pm1$ and $h=(h_1, h_2, \\dots, h_L)$ the matrix\n\n\\begin{equation}\n \\label{eq:mMatrix} \\tag{7}\n M_\\sigma(h) = I + B_{L,\\sigma}(h_L) B_{L-1,\\sigma}(h_{L-1}) \\dots B_{1,\\sigma}(h_1)\n\\end{equation}\n\nconsist of the time step matrices $B_{l,\\sigma}(h_l)$, which are associated with the operators $e^{-\\Delta\\tau K_\\sigma} e^{V_{l\\sigma}}$:\n\n\\begin{equation}\n \\label{eq:bMatrix}\n B_{l,\\sigma}(h_l) = e^{-\\Delta\\tau K_\\sigma} e^{\\sigma \\nu V_l(h_l)}.\n\\end{equation}\n\nWith the approximation \\eqref{eq:partitionComputable} the distribution operator $\\mathcal{P}$, defined in \\eqref{eq:distop}, can be expressed as the computable approximation\n\n\\begin{equation}\n \\label{eq:distopComputable} \\tag{8}\n \\mathcal{P}(h) = \\frac{\\eta_d}{\\mathcal{Z}_h} \\det[M_\\uparrow(h)] \\det[M_\\downarrow(h)].\n\\end{equation}\n\nThe Green's function $G$ associated with the configuration $h$ is defined as the inverse of the matrix $M_\\sigma(h)$:\n\n\\begin{equation}\n G_\\sigma(h) = \\left[M_\\sigma(h)\\right]^{-1}\n\\end{equation}\n\n", "_____no_output_____" ], [ "## 3 Determinant Quantum Monte Carlo algorithm\n\nThe simulation of the Hubbard model is a classical Monte Carlo problem. The Hubbard-Stratanovich variables or configurations $h$ are sampled such that the follow the probability distribution $\\mathcal{P}(h)$. The determinant QMC (DQMC) algorithm can be summarized by the following steps:\n\nFirst, the configuration $h$ is initialized with an array of randomly distributed values of $\\pm 1$. Starting from the time slice $l=1$, a change in the Hubbard-Stratanovich field on the lattice site $i=1$ is proposed:\n\\begin{equation}\n h^\\prime_{1, 1} = -h_{1, 1}.\n\\end{equation}\n\nWith the new configuration $h^\\prime$ the Metropolis ratio\n\\begin{equation}\n d_{1, 1} = \\frac{\\det[M_\\uparrow(h^\\prime)] \\det[M_\\downarrow(h^\\prime)]}{\\det[M_\\uparrow(h)] \\det[M_\\downarrow(h)]},\n\\end{equation}\n\ncan be computed. A random number generator is then used to sample a uniformly distributed random number $r$. If $r < d_{1, 1}$, the proposed update to the configuration is accepted:\n\\begin{equation}\n h = h^\\prime.\n\\end{equation}\n\nAfter all lattice sites $i = 1, \\dots, N$ of the imaginary time slice $l=1$ have been updated, the procedure is continued with the next time slice $l=2$ until all imaginary time slices $l=1, \\dots, L$ are updated. This concludes one \\emph{sweep} through the Hubbard-Stratanovich field. After a few hundred \"warmup-sweeps\" have been performed, measurements can be made after completing an entire set of updates to all space-time points of the system (see section \\ref{sec:measurements}). The measurement results have to be normalized with the number of \"measurement-sweeps\". One iteration (sweep) of the DQMC algorithm can be summarized as\n\n1. Set $l=1$ and $i=1$\n2. Propose new coonfiguration $h^\\prime$ by flipping spin:\n \\begin{equation}\n h^\\prime_{i, l} = -h_{i, l}.\n \\end{equation}\n3. Compute Metropolis ratio:\n \\begin{equation}\n d_{i, l} = \\frac{\\det[M_\\uparrow(h^\\prime)] \\det[M_\\downarrow(h^\\prime)]}{\\det[M_\\uparrow(h)] \\det[M_\\downarrow(h)]},\n \\end{equation}\n where \n \\begin{equation}\n M_\\sigma(h) = I + B_{l-1,\\sigma} \\dots B_{1, \\sigma} B_{L,\\sigma}B_{L-1,\\sigma} \\dots B_{l,\\sigma}.\n \\end{equation}\n \n4. Sample random number $r$\n5. Accept new configuration, if $r < d_{i, l}$:\n \\begin{equation}\n h_{i, l} = \\begin{cases} h^\\prime_{i, l} &\\text{if } r < d_{i, l} \\\\\n h_{i, l} &\\text{else }\n \\end{cases}\n \\end{equation}\n6. Increment site $i = i+1$ if $i < N$\n7. Increment time slice $l = l+1$ if $i=N$\n\n\n### 3.1 Rank-one update scheme\n\n\nThe one-site update of the inner DQMC loop leads to a simple rank-one update of the matrix $M_\\sigma(h)$, which leads to an efficient method of computing the Metropolis ratio $d_{i,l}$ and Green's function $G_\\sigma$.\n\nThe DQMC simulation requires the computation of $NL$ Metropolis ratios \n\n\\begin{equation}\n d = \\frac{\\det[M_\\uparrow(h^\\prime)] \\det[M_\\downarrow(h^\\prime)]}{\\det[M_\\uparrow(h)] \\det[M_\\downarrow(h)]}\n\\end{equation}\n\nfor the configurations $h = (h_1, h_2, \\dots, h_l)$ and $h^\\prime = (h^\\prime_1, h^\\prime_2, \\dots, h^\\prime_L)$ per sweep. The matrix $M_\\sigma(h)$, defined in \\eqref{eq:mMatrix}, is given by\n\n\\begin{equation}\n M_\\sigma = I + B_{L,\\sigma} B_{L-1,\\sigma} \\dots B_{1,\\sigma}.\n\\end{equation}\n\nwith the time step matrices\n\\begin{equation}\n B_{l,\\sigma} = e^{-\\Delta\\tau K_\\sigma} e^{\\sigma \\nu V_l(h_l)}.\n\\end{equation}\n\nThe Green's function of the configuration $h$ is defined as\n\\begin{equation}\n G_\\sigma(h) = M_\\sigma^{-1}.\n\\end{equation}\n\nThe elements of the configuration $h$ and $h^\\prime$ differ only by one element at a specific time slice $l$ and spatial site $i$, which gets inverted by a proposed update:\n\\begin{equation}\n h^\\prime_{i,l} = - h_{i, l}.\n\\end{equation}\n\n\nDuring one sweep of the QMC iteration the inner loops run over the $l=1, \\dots, L$ imaginary time slices and $i=1, \\dots, N$ lattice sites. Starting with the first time slice, $l=1$, the Metropolis ratio $d_{i, 1}$ for each lattice site $i$ is given by\n\\begin{equation}\n d_{i, 1} = d_\\uparrow d_\\downarrow,\n\\end{equation}\nwhere for $\\sigma = \\pm 1$\n\\begin{equation}\n d_\\sigma = 1 + \\alpha_{i,\\sigma} \\left[ 1 - \\boldsymbol{e}_i^T M_\\sigma^{-1}(h) \\boldsymbol{e}_i \\right] = 1 + \\alpha_{i, \\sigma} \\left[ 1 - G_{ii}^\\sigma(h) \\right]\n\\end{equation}\nand\n\\begin{equation}\n \\alpha_{i,\\sigma} = e^{-2\\sigma \\nu h_{i,1}} - 1.\n\\end{equation}\n\nThe Metropolis ration $d_{i, 1}$ can therefore be obtained by computing the inverse of the matrix $M_\\sigma(h)$, which corresponds to the Green's function $G_\\sigma(h)$. If $G_\\sigma(h)$ has already been computed in a previous step, then it is essentially free to compute the Metropolis ratio.\\\\\nIf the proposed update $h^\\prime$ to the configuration is accepted, the Green's function needs to be updated by a rank-1 matrix update:\n\\begin{equation}\n G_\\sigma(h^\\prime) = G_\\sigma(h) - \\frac{\\alpha_{i, \\sigma}}{d_{i, 1}} \\boldsymbol{u}_\\sigma \\boldsymbol{w}_\\sigma^T,\n\\end{equation}\nwhere \n\\begin{equation}\n \\boldsymbol{u}_\\sigma = \\left[I - G_\\sigma(h)\\right] \\boldsymbol{e}_i, \\qquad \\boldsymbol{w}_\\sigma = \\left[G_\\sigma(h)\\right]^T \\boldsymbol{e}_i.\n\\end{equation}\n\nAfter all spatial sites $i=1, \\dots, N$ have been updated, we can move to the next time slice $l=2$. The matrices $M_\\sigma(h)$ and $M_\\sigma(h^\\prime)$ can be written as\n\\begin{equation}\n\\begin{split}\n M_\\sigma(h) &= B_{1, \\sigma}^{-1}(h_1) \\hat{M}_\\sigma(h) B_{1, \\sigma}(h_1)\\\\\n M_\\sigma(h^\\prime) &= B_{1, \\sigma}^{-1}(h_1^\\prime) \\hat{M}_\\sigma(h^\\prime) B_{1, \\sigma}(h_1^\\prime)\n\\end{split}\n\\end{equation}\nwhere \n\\begin{equation}\n\\begin{split}\n \\hat{M}_\\sigma(h) &= I + B_{1, \\sigma}(h_1) B_{L, \\sigma}(h_L) B_{L-1, \\sigma}(h_{L-1}) \\dots B_{2, \\sigma}(h_2)\\\\\n \\hat{M}_\\sigma(h^\\prime) &= I + B_{1, \\sigma}(h_1^\\prime) B_{L, \\sigma}(h_L^\\prime) B_{L-1, \\sigma}(h_{L-1}^\\prime) \\dots B_{2, \\sigma}(h_2^\\prime)\n\\end{split}\n\\end{equation}\n\nare obtained by a cyclic permutation of the time step matrices $B_{l,\\sigma}(h_l)$. The Metropolis ratios $d_{i, 2}$ corresponding to the time slice $l=2$ can therefore be written as\n\\begin{equation}\n d_{i,2} = \\frac{\\det\\big[M_\\uparrow(h^\\prime)\\big] \\det\\big[M_\\downarrow(h^\\prime)\\big]}{\\det\\big[M_\\uparrow(h)\\big] \\det\\big[M_\\downarrow(h)\\big]} \n = \\frac{\\det\\big[\\hat{M}_\\uparrow(h^\\prime)\\big] \\det\\big[\\hat{M}_\\downarrow(h^\\prime)\\big]}{\\det\\big[\\hat{M}_\\uparrow(h)\\big] \\det\\big[\\hat{M}_\\downarrow(h)\\big]}.\n\\end{equation}\n\nThe associated Green's functions are given by \"wrapping\":\n\\begin{equation}\n \\hat{G}_\\sigma(h) = B^{-1}_{1,\\sigma}(h_1) G_\\sigma(h) B_{1,\\sigma}(h_1).\n\\end{equation}\n\nWrapping the Green's function ensures that the configurations $h_2$ and $h_2^\\prime$ associated with the time slice $l=2$ appear at the same location of the matrices $\\hat{M}_\\sigma(h)$ and $\\hat{M}_\\sigma(h^\\prime)$ as the configurations $h_1$ and $h_1^\\prime$ at the time slice $l=1$. Therefore the same formulation can be used for the time slice $l=2$ as for the time slice $l=1$ to compute the Metropolis ratio and update the Green's functions. This procedure can be repeated for all the remaining time slices $l=3, 4, \\dots, L$.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ] ]
d01e4daf40d4816894759decd512e0931ed3c2b2
19,850
ipynb
Jupyter Notebook
latex/MD_SMC/MD03 Matrices.ipynb
asimovian-academy/optimizacion-combinatoria
7859f1a944e0d5ae387967cee6fce0ca5991bf7f
[ "MIT" ]
1
2021-06-11T20:19:58.000Z
2021-06-11T20:19:58.000Z
latex/MD_SMC/MD03 Matrices.ipynb
julihocc/optimizacion-combinatoria
7859f1a944e0d5ae387967cee6fce0ca5991bf7f
[ "MIT" ]
null
null
null
latex/MD_SMC/MD03 Matrices.ipynb
julihocc/optimizacion-combinatoria
7859f1a944e0d5ae387967cee6fce0ca5991bf7f
[ "MIT" ]
null
null
null
24.031477
133
0.400151
[ [ [ "#1.1\nA=[[1,0],[1,1]]; A=Matrix(A); show(\"A=\",A)\nB=[[1,1,1],[1,0,0]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ], [ "#1.2\nA=[[0,0,0],[0,0,1]]; A=Matrix(A); show(\"A=\",A)\nB=[[1,1,1],[1,0,1],[0,1,1]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ], [ "#1.3\nA=[[1,1],[0,1],[0,0]]; A=Matrix(A); show(\"A=\",A)\nB=[[0],[1]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ], [ "#1.4\nA=[[1,0,1]]; A=Matrix(A); show(\"A=\",A)\nB=[[0],[0],[0]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\nshow(\"BA=\",B*A)", "_____no_output_____" ], [ "#1.5\nA=[[1,1,0]]; A=Matrix(A); show(\"A=\",A)\nB=[[0],[0],[0]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n\nshow(\"BA=\",B*A)", "_____no_output_____" ], [ "#1.6\nA=[[0,1],[0,1]]; A=Matrix(A); show(\"A=\",A)\nB=[[1,1,1],[1,1,0]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ] ], [ [ "#2.1\nA=[[5],[7],[0]]; A=Matrix(A); show(\"A=\",A)\nB=[[-4]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ] ], [ [ "#2.2\nA=[[2,7,2],[8,-6,6]]; A=Matrix(A); show(\"A=\",A)\nB=[[6,6],[-2,-3],[-6,8]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\nshow(\"BA=\",B*A)", "_____no_output_____" ], [ "#2.3\nA=[[-4,-6],[0,6]]; A=Matrix(A); show(\"A=\",A)\nB=[[-2],[-2]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ], [ "#2.4\nA=[[7],[6]]; A=Matrix(A); show(\"A=\",A)\nB=[[-9,8]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\nshow(\"BA=\",B*A)", "_____no_output_____" ], [ "#2.5\nA=[[-2],[-4]]; A=Matrix(A); show(\"A=\",A)\nB=[[-8]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ], [ "#2.6\nA=[[-5,-8,-1]]; A=Matrix(A); show(\"A=\",A)\nB=[[8,-1],[5,4],[4,-3]]; B=Matrix(B); show(\"B=\",B)\nshow(\"AB=\",A*B)\n#show(\"BA=\",B*A)", "_____no_output_____" ] ] ]
[ "code", "raw", "code" ]
[ [ "code", "code", "code", "code", "code", "code" ], [ "raw" ], [ "code", "code", "code", "code", "code" ] ]
d01e54ec032f6111e4fe9dc65f55424cbe3d95f4
45,872
ipynb
Jupyter Notebook
probablistic_language_modeling/cicero_corpus_counts.ipynb
todd-cook/ML-You-Can-Use
45c86d6f70b7d216c421ea005e022f5d6f5501cd
[ "Apache-2.0" ]
28
2019-02-25T09:57:23.000Z
2022-03-11T17:25:43.000Z
probablistic_language_modeling/cicero_corpus_counts.ipynb
todd-cook/ML-You-Can-Use
45c86d6f70b7d216c421ea005e022f5d6f5501cd
[ "Apache-2.0" ]
9
2021-01-09T08:49:26.000Z
2022-02-10T00:07:08.000Z
probablistic_language_modeling/cicero_corpus_counts.ipynb
todd-cook/ML-You-Can-Use
45c86d6f70b7d216c421ea005e022f5d6f5501cd
[ "Apache-2.0" ]
6
2020-01-28T18:35:32.000Z
2022-03-31T21:11:08.000Z
48.8
506
0.511358
[ [ [ "import os.path\nfrom collections import Counter\nfrom glob import glob\n\nimport inspect\nimport os\nimport pickle\nimport sys\nfrom cltk.corpus.latin.phi5_index import PHI5_INDEX\nfrom cltk.corpus.readers import get_corpus_reader\nfrom cltk.stem.latin.j_v import JVReplacer\nfrom cltk.stem.lemma import LemmaReplacer\nfrom cltk.tokenize.latin.sentence import SentenceTokenizer\nfrom cltk.tokenize.word import WordTokenizer\nfrom random import sample\nfrom tqdm import tqdm\nfrom typing import List, Dict, Tuple\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0,parentdir)\n \nfrom mlyoucanuse.aeoe_replacer import AEOEReplacer\nfrom mlyoucanuse.text_cleaners import ( normalize_accents, disappear_angle_brackets,\n drop_punct, disappear_round_brackets,\n truecase, dehyphenate, accept_editorial,\n swallow_braces, swallow_obelized_words,\n swallow_square_brackets)", "_____no_output_____" ], [ "import cltk\ncltk.__version__", "_____no_output_____" ] ], [ [ "## Text Cleaning\nfrom http://udallasclassics.org/wp-content/uploads/maurer_files/APPARATUSABBREVIATIONS.pdf\n\n[...] Square brackets, or in recent editions wavy brackets ʺ{...}ʺ, enclose words etc. that an editor thinks should be deleted (see ʺdel.ʺ) or marked as out of place (see ʺsecl.ʺ).\n\n[...] Square brackets in a papyrus text, or in an inscription, enclose places where words have been lost through physical damage. If this happens in mid-line, editors use ʺ[...]ʺ. If only the end of the line is missing, they use a single bracket ʺ[...ʺ If the lineʹs beginning is missing, they use ʺ...]ʺ Within the brackets, often each dot represents one missing letter.\n\n[[...]] Double brackets enclose letters or words deleted by the medieval copyist himself.\n\n(...) Round brackets are used to supplement words abbreviated by the original copyist; e.g. in an inscription: ʺtrib(unus) mil(itum) leg(ionis) IIIʺ\n\n<...> diamond ( = elbow = angular) brackets enclose words etc. that an editor has added (see ʺsuppl.ʺ)\n\n† An obelus (pl. obeli) means that the word(s etc.) is very plainly corrupt, but the editor cannot see how to emend. If only one word is corrupt, there is only one obelus, which precedes the word; if two or more words are corrupt, two obeli enclose them. (Such at least is the rule--but that rule is often broken, especially in older editions, which sometimes dagger several words using only one obelus.) To dagger words in this way is to ʺobelizeʺ them.", "_____no_output_____" ], [ "## Load/Build Truecasing dictionary; count all cased tokens, use to normalize cases later", "_____no_output_____" ] ], [ [ "truecase_file = 'truecase_counter.latin.pkl'\n\nif os.path.exists(truecase_file):\n with open(truecase_file, 'rb') as fin: \n case_counts = pickle.load(fin)\nelse:\n tesserae = get_corpus_reader(corpus_name='latin_text_tesserae', language='latin')\n case_counts = Counter()\n jv_replacer = JVReplacer()\n aeoe_replacer = AEOEReplacer()\n toker = WordTokenizer('latin')\n sent_toker = SentenceTokenizer()\n lemmatizer = LemmaReplacer('latin')\n \n for file in tqdm(tesserae.fileids(), total=len(tesserae.fileids())):\n for sent in tesserae.sents(file):\n sent = aeoe_replacer.replace(jv_replacer.replace(drop_punct(sent)))\n sent = normalize_accents(sent)\n sent = accept_editorial(sent)\n for token in toker.tokenize(sent):\n case_counts.update({token:1})\n \n with open(truecase_file, 'wb') as fout: \n pickle.dump(case_counts, fout) \n\nlen(case_counts)\n# 344393, 322711 \n# 318451\n# 316722\n# 311399\n# 310384\n# 310567\n# 309529", "100%|██████████| 762/762 [03:10<00:00, 3.99it/s]\n" ], [ "print(sample(list(case_counts.items()), 25))", "[('litigatur', 4), ('excreare', 4), ('cantharum', 14), ('circumdare', 40), ('Caesariem', 2), ('cultori', 5), ('semitari', 1), ('amplectatur', 4), ('Retraham', 1), ('totonderunt', 1), ('sonco', 1), ('Laurentium', 2), ('epicurei', 1), ('obrizo', 2), ('Teutomatus', 2), ('iniustissume', 1), ('parassent', 5), ('cognoscendas', 2), ('δηρόν', 1), ('Erconualdo', 1), ('audiar', 4), ('Melito', 1), ('Paxaea', 1), ('ramorum', 58), ('rge', 1)]\n" ], [ "def get_word_counts(files:List[str])->Tuple[Dict[str, int], Dict[str, int]]:\n \"\"\"\n Given a list of files, \n clean & tokenize the documents\n return Counters for:\n lemmatized words in the documents\n inflected words in the documents \n \"\"\"\n word_counter = Counter()\n inflected_word_counter = Counter()\n jv_replacer = JVReplacer()\n aeoe_replacer = AEOEReplacer()\n toker = WordTokenizer('latin')\n sent_toker = SentenceTokenizer()\n lemmatizer = LemmaReplacer('latin')\n\n for file in tqdm(files , total=len(files), unit='files'):\n with open(file, 'rt') as fin:\n text = fin.read()\n text = text.replace(\"-\\n\", \"\")\n text = text.replace(\"\\n\", \" \")\n text = aeoe_replacer.replace(jv_replacer.replace( text))\n for sent in sent_toker.tokenize(text):\n sent = dehyphenate(sent) # because it's Phi5\n sent = swallow_braces(sent)\n sent = swallow_square_brackets(sent)\n sent = disappear_round_brackets(sent)\n sent = swallow_obelized_words(sent)\n sent = disappear_angle_brackets(sent) \n sent = drop_punct(sent)\n sent = normalize_accents(sent) \n # lemmatizer prefers lower \n # sent = lemmatizer.lemmatize(sent.lower(), return_string=True)\n for word in toker.tokenize(sent):\n if word.isnumeric():\n continue\n inflected_word_counter.update({truecase(word, case_counts):1}) \n word = lemmatizer.lemmatize(word.lower(), return_string=True)\n # normalize capitals\n word_counter.update({truecase(word, case_counts) : 1})\n return word_counter, inflected_word_counter\n", "_____no_output_____" ], [ "def word_stats(author:str, lemma_counter:Counter, \n inflected_counter:Counter)->Tuple[float, float]:\n \"\"\"\n \n \"\"\"\n nw = sum(lemma_counter.values())\n print(f\"Total count of all tokens in {author} corpus: {nw:,}\")\n print(f\"Total number of distinct inflected words/tokens in {author} corpus: {len(inflected_counter):,}\")\n print(f\"Total number of lemmatized words/tokens in {author} corpus {len(lemma_counter):,}\")\n ciw1 = sum([1 for key, val in inflected_counter.items() if val == 1]) \n print(f\"Count of inflected tokens only occuring once {ciw1:,}\")\n cw1 = sum([1 for key, val in lemma_counter.items() if val == 1])\n print(f\"Count of lemmatized tokens only occuring once {cw1:,}\")\n Piu_one = ciw1 / nw\n print(f\"Probability of a single count unigram occuring in the {author} corpus: {Piu_one:.3f}\") \n Plu_one = cw1 / nw\n print(f\"Probability of a single count unigram in the lemmatized {author} corpus: {Plu_one:.3f}\") \n return (Piu_one, Plu_one)", "_____no_output_____" ], [ "# Cicero works\ncicero_files = glob(f\"{os.path.expanduser('~')}/cltk_data/latin/text/phi5/individual_works/LAT0474.TXT-0*.txt\")\nlen (cicero_files) ", "_____no_output_____" ], [ "cicero_lemmas, cicero_inflected_words = get_word_counts(cicero_files)", "100%|██████████| 75/75 [00:47<00:00, 1.59files/s]\n" ], [ "word_stats(author='Cicero', \n lemma_counter=cicero_lemmas,\n inflected_counter=cicero_inflected_words)", "Total count of all tokens in Cicero corpus: 1,196,512\nTotal number of distinct inflected words/tokens in Cicero corpus: 75,705\nTotal number of lemmatized words/tokens in Cicero corpus 23,345\nCount of inflected tokens only occuring once 34,608\nCount of lemmatized tokens only occuring once 10,656\nProbability of a single count unigram occuring in the Cicero corpus: 0.029\nProbability of a single count unigram in the lemmatized Cicero corpus: 0.009\n" ], [ "cicero_lemmas_counter_file = 'cicero_lemmas_counter.pkl'\ncicero_inflected_counter_file = 'cicero_inflected_counter.pkl'\n\nif not os.path.exists(cicero_lemmas_counter_file):\n with open(cicero_lemmas_counter_file, 'wb') as fout:\n pickle.dump(cicero_lemmas, fout)\nif not os.path.exists(cicero_inflected_counter_file):\n with open(cicero_inflected_counter_file, 'wb') as fout:\n pickle.dump(cicero_inflected_words, fout)", "_____no_output_____" ], [ "author_index = {val:key for key,val in PHI5_INDEX.items() \n if val != 'Marcus Tullius Cicero, Cicero, Tully'}", "_____no_output_____" ], [ "def get_phi5_author_files(author_name, author_index):\n stub = author_index[author_name]\n return glob(os.path.expanduser(f'~/cltk_data/latin/text/phi5/individual_works/{stub}*.txt'))\n", "_____no_output_____" ] ], [ [ "## Visualization of our corpus comparison: \nIf you took one page from one author and placed it into Cicero, how surprising would it be?\n\nIf the other author's vocabulary was substantially different, it would be noticeable. We can quantify this.\n\nAs a result, since we want to predict as close as possible to the author, we should only train a language model where the underlying corpus vocabularies are within a reasonable window of surprise.", "_____no_output_____" ] ], [ [ "results = []\n\nfor author in author_index:\n files = get_phi5_author_files(author, author_index)\n # cicero_lemmas, cicero_inflected_words = get_word_counts(cicero_files) \n author_lemmas, author_inflected_words = get_word_counts(files) \n\n author_words = set(author_lemmas.keys())\n cicero_words = set(cicero_lemmas.keys())\n common = author_words & cicero_words\n author_uniq = author_words - common \n P_one_x_lemma_unigram = len(author_uniq) / sum(author_lemmas.values())\n \n author_words = set(author_inflected_words.keys())\n cicero_words = set(cicero_inflected_words.keys())\n \n common = author_words & cicero_words\n author_uniq = author_words - common \n P_one_x_inflected_unigram = len(author_uniq) / sum(author_inflected_words.values())\n results.append((author, P_one_x_lemma_unigram, P_one_x_inflected_unigram ))\n\n\n", "100%|██████████| 1/1 [00:00<00:00, 2.22files/s]\n100%|██████████| 1/1 [00:01<00:00, 1.03s/files]\n100%|██████████| 8/8 [00:03<00:00, 2.54files/s]\n100%|██████████| 1/1 [00:00<00:00, 331.88files/s]\n100%|██████████| 1/1 [00:00<00:00, 170.88files/s]\n100%|██████████| 1/1 [00:00<00:00, 620.73files/s]\n100%|██████████| 1/1 [00:00<00:00, 358.92files/s]\n100%|██████████| 2/2 [00:00<00:00, 94.10files/s]\n100%|██████████| 1/1 [00:03<00:00, 3.36s/files]\n100%|██████████| 75/75 [00:48<00:00, 1.55files/s]\n100%|██████████| 1/1 [00:00<00:00, 504.49files/s]\n100%|██████████| 1/1 [00:00<00:00, 513.82files/s]\n100%|██████████| 2/2 [00:00<00:00, 200.66files/s]\n100%|██████████| 1/1 [00:00<00:00, 148.79files/s]\n100%|██████████| 2/2 [00:00<00:00, 389.86files/s]\n100%|██████████| 1/1 [00:00<00:00, 454.13files/s]\n100%|██████████| 1/1 [00:00<00:00, 551.59files/s]\n100%|██████████| 1/1 [00:00<00:00, 169.64files/s]\n100%|██████████| 1/1 [00:00<00:00, 27.88files/s]\n100%|██████████| 1/1 [00:00<00:00, 198.92files/s]\n100%|██████████| 1/1 [00:00<00:00, 7.69files/s]\n100%|██████████| 1/1 [00:00<00:00, 266.02files/s]\n100%|██████████| 1/1 [00:00<00:00, 152.88files/s]\n100%|██████████| 1/1 [00:00<00:00, 146.37files/s]\n100%|██████████| 1/1 [00:00<00:00, 313.99files/s]\n100%|██████████| 10/10 [00:04<00:00, 2.27files/s]\n100%|██████████| 1/1 [00:00<00:00, 16.94files/s]\n100%|██████████| 1/1 [00:00<00:00, 20.89files/s]\n100%|██████████| 2/2 [00:00<00:00, 11.28files/s]\n100%|██████████| 2/2 [00:00<00:00, 3.73files/s]\n100%|██████████| 1/1 [00:00<00:00, 128.77files/s]\n100%|██████████| 1/1 [00:00<00:00, 365.48files/s]\n100%|██████████| 3/3 [00:00<00:00, 4.12files/s]\n100%|██████████| 1/1 [00:00<00:00, 526.00files/s]\n100%|██████████| 1/1 [00:00<00:00, 220.42files/s]\n100%|██████████| 1/1 [00:00<00:00, 37.88files/s]\n100%|██████████| 2/2 [00:00<00:00, 332.93files/s]\n100%|██████████| 1/1 [00:00<00:00, 66.44files/s]\n100%|██████████| 2/2 [00:00<00:00, 14.79files/s]\n100%|██████████| 1/1 [00:00<00:00, 336.68files/s]\n100%|██████████| 1/1 [00:00<00:00, 153.84files/s]\n100%|██████████| 1/1 [00:00<00:00, 353.74files/s]\n100%|██████████| 2/2 [00:00<00:00, 14.96files/s]\n100%|██████████| 1/1 [00:00<00:00, 95.27files/s]\n100%|██████████| 2/2 [00:00<00:00, 474.52files/s]\n100%|██████████| 2/2 [00:00<00:00, 25.73files/s]\n100%|██████████| 2/2 [00:00<00:00, 378.14files/s]\n100%|██████████| 1/1 [00:00<00:00, 244.25files/s]\n100%|██████████| 1/1 [00:00<00:00, 657.31files/s]\n100%|██████████| 4/4 [00:00<00:00, 28.87files/s]\n100%|██████████| 1/1 [00:00<00:00, 198.34files/s]\n100%|██████████| 1/1 [00:00<00:00, 156.28files/s]\n100%|██████████| 2/2 [00:00<00:00, 546.60files/s]\n100%|██████████| 8/8 [00:00<00:00, 34.36files/s]\n100%|██████████| 1/1 [00:00<00:00, 519.55files/s]\n100%|██████████| 2/2 [00:01<00:00, 1.53files/s]\n100%|██████████| 1/1 [00:00<00:00, 25.65files/s]\n100%|██████████| 1/1 [00:00<00:00, 127.91files/s]\n100%|██████████| 1/1 [00:00<00:00, 3.12files/s]\n100%|██████████| 1/1 [00:00<00:00, 489.76files/s]\n100%|██████████| 1/1 [00:00<00:00, 1.25files/s]\n100%|██████████| 4/4 [00:04<00:00, 1.02s/files]\n100%|██████████| 1/1 [00:00<00:00, 435.18files/s]\n100%|██████████| 2/2 [00:02<00:00, 1.28s/files]\n100%|██████████| 2/2 [00:00<00:00, 519.48files/s]\n100%|██████████| 1/1 [00:00<00:00, 244.08files/s]\n100%|██████████| 2/2 [00:00<00:00, 6.98files/s]\n100%|██████████| 1/1 [00:00<00:00, 35.92files/s]\n100%|██████████| 1/1 [00:00<00:00, 449.45files/s]\n100%|██████████| 1/1 [00:00<00:00, 168.27files/s]\n100%|██████████| 3/3 [00:00<00:00, 12.78files/s]\n100%|██████████| 1/1 [00:00<00:00, 2.65files/s]\n100%|██████████| 1/1 [00:00<00:00, 474.79files/s]\n100%|██████████| 1/1 [00:00<00:00, 373.39files/s]\n100%|██████████| 1/1 [00:00<00:00, 343.06files/s]\n100%|██████████| 1/1 [00:00<00:00, 7.01files/s]\n100%|██████████| 1/1 [00:00<00:00, 165.01files/s]\n100%|██████████| 1/1 [00:00<00:00, 162.92files/s]\n100%|██████████| 1/1 [00:00<00:00, 265.53files/s]\n100%|██████████| 1/1 [00:00<00:00, 547.42files/s]\n100%|██████████| 1/1 [00:00<00:00, 148.24files/s]\n100%|██████████| 7/7 [00:00<00:00, 28.22files/s]\n100%|██████████| 1/1 [00:00<00:00, 185.87files/s]\n100%|██████████| 3/3 [00:03<00:00, 1.16s/files]\n100%|██████████| 1/1 [00:00<00:00, 200.67files/s]\n100%|██████████| 1/1 [00:00<00:00, 6.46files/s]\n100%|██████████| 1/1 [00:00<00:00, 576.46files/s]\n100%|██████████| 1/1 [00:00<00:00, 544.29files/s]\n100%|██████████| 1/1 [00:00<00:00, 165.24files/s]\n100%|██████████| 1/1 [00:01<00:00, 1.21s/files]\n100%|██████████| 1/1 [00:00<00:00, 3.37files/s]\n100%|██████████| 1/1 [00:00<00:00, 509.45files/s]\n100%|██████████| 2/2 [00:00<00:00, 53.79files/s]\n100%|██████████| 1/1 [00:00<00:00, 302.21files/s]\n100%|██████████| 1/1 [00:00<00:00, 37.27files/s]\n100%|██████████| 1/1 [00:00<00:00, 517.05files/s]\n100%|██████████| 2/2 [00:00<00:00, 172.96files/s]\n100%|██████████| 1/1 [00:00<00:00, 80.32files/s]\n100%|██████████| 15/15 [00:09<00:00, 1.55files/s]\n100%|██████████| 1/1 [00:00<00:00, 3.85files/s]\n100%|██████████| 1/1 [00:00<00:00, 153.47files/s]\n100%|██████████| 1/1 [00:01<00:00, 1.12s/files]\n100%|██████████| 1/1 [00:00<00:00, 246.35files/s]\n100%|██████████| 1/1 [00:00<00:00, 120.82files/s]\n100%|██████████| 7/7 [00:00<00:00, 60.69files/s]\n100%|██████████| 2/2 [00:00<00:00, 226.37files/s]\n100%|██████████| 8/8 [00:00<00:00, 39.11files/s]\n100%|██████████| 1/1 [00:00<00:00, 280.67files/s]\n100%|██████████| 2/2 [00:01<00:00, 1.62files/s]\n100%|██████████| 1/1 [00:00<00:00, 5.59files/s]\n100%|██████████| 2/2 [00:00<00:00, 11.13files/s]\n100%|██████████| 1/1 [00:00<00:00, 165.31files/s]\n100%|██████████| 1/1 [00:01<00:00, 1.96s/files]\n100%|██████████| 1/1 [00:00<00:00, 18.54files/s]\n100%|██████████| 1/1 [00:00<00:00, 489.19files/s]\n100%|██████████| 1/1 [00:00<00:00, 69.90files/s]\n100%|██████████| 1/1 [00:01<00:00, 1.56s/files]\n100%|██████████| 1/1 [00:01<00:00, 1.63s/files]\n100%|██████████| 1/1 [00:00<00:00, 27.05files/s]\n100%|██████████| 1/1 [00:00<00:00, 466.86files/s]\n100%|██████████| 1/1 [00:00<00:00, 623.41files/s]\n100%|██████████| 1/1 [00:00<00:00, 439.15files/s]\n100%|██████████| 1/1 [00:00<00:00, 449.07files/s]\n100%|██████████| 2/2 [00:00<00:00, 133.10files/s]\n100%|██████████| 1/1 [00:00<00:00, 184.23files/s]\n100%|██████████| 2/2 [00:00<00:00, 127.27files/s]\n100%|██████████| 1/1 [00:05<00:00, 5.13s/files]\n100%|██████████| 2/2 [00:00<00:00, 429.39files/s]\n100%|██████████| 2/2 [00:00<00:00, 323.83files/s]\n100%|██████████| 1/1 [00:00<00:00, 2.60files/s]\n100%|██████████| 30/30 [00:05<00:00, 5.48files/s]\n100%|██████████| 1/1 [00:00<00:00, 223.21files/s]\n100%|██████████| 1/1 [00:00<00:00, 118.25files/s]\n100%|██████████| 1/1 [00:00<00:00, 387.32files/s]\n100%|██████████| 1/1 [00:00<00:00, 659.59files/s]\n100%|██████████| 2/2 [00:00<00:00, 316.10files/s]\n100%|██████████| 1/1 [00:01<00:00, 1.10s/files]\n100%|██████████| 1/1 [00:02<00:00, 2.55s/files]\n100%|██████████| 2/2 [00:00<00:00, 297.27files/s]\n100%|██████████| 6/6 [00:02<00:00, 2.04files/s]\n100%|██████████| 3/3 [00:04<00:00, 1.52s/files]\n100%|██████████| 1/1 [00:00<00:00, 102.91files/s]\n100%|██████████| 6/6 [00:03<00:00, 1.74files/s]\n100%|██████████| 1/1 [00:00<00:00, 10.55files/s]\n100%|██████████| 1/1 [00:00<00:00, 171.67files/s]\n100%|██████████| 17/17 [00:03<00:00, 4.54files/s]\n100%|██████████| 1/1 [00:00<00:00, 121.36files/s]\n100%|██████████| 1/1 [00:00<00:00, 335.33files/s]\n100%|██████████| 14/14 [00:00<00:00, 18.71files/s]\n100%|██████████| 1/1 [00:00<00:00, 408.44files/s]\n100%|██████████| 2/2 [00:05<00:00, 2.52s/files]\n100%|██████████| 1/1 [00:00<00:00, 98.70files/s]\n100%|██████████| 1/1 [00:00<00:00, 1.13files/s]\n100%|██████████| 2/2 [00:00<00:00, 380.68files/s]\n100%|██████████| 1/1 [00:00<00:00, 81.92files/s]\n100%|██████████| 1/1 [00:03<00:00, 3.21s/files]\n100%|██████████| 1/1 [00:00<00:00, 513.82files/s]\n100%|██████████| 1/1 [00:00<00:00, 193.12files/s]\n100%|██████████| 2/2 [00:00<00:00, 208.97files/s]\n100%|██████████| 1/1 [00:00<00:00, 247.83files/s]\n100%|██████████| 1/1 [00:00<00:00, 27.85files/s]\n100%|██████████| 1/1 [00:00<00:00, 273.30files/s]\n100%|██████████| 1/1 [00:00<00:00, 105.58files/s]\n100%|██████████| 5/5 [00:01<00:00, 4.39files/s]\n100%|██████████| 7/7 [00:03<00:00, 1.98files/s]\n" ], [ "# sorted(results, key=lambda x:x[1])", "_____no_output_____" ], [ "results_map = {key: (val, val2) for key,val,val2 in results}", "_____no_output_____" ], [ "for author in author_index:\n files = get_phi5_author_files(author, author_index)\n if len(files) >= 3:\n print(author, results_map[author])\n# the values analogous to Cicero are: (0.02892407263780054, 0.008905886443261747) ", "Gaius Iulius Caesar, Caesar (0.016170899832329378, 0.0464137117307334)\nApuleius Madaurensis (0.039956560814859196, 0.12101183343319354)\nCaelius Apicius (0.04383594547528974, 0.09950159130486999)\nAnonymi Comici et Tragici (0.05979473449352968, 0.10397144132083891)\nC. Iul. Caes. Augustus Octavianus (0.16793743890518084, 0.20527859237536658)\nPublius Papinius Statius (0.03662215849687846, 0.1022791767482152)\nLucius Accius (0.0845518118245391, 0.16634880271243907)\nGaius Caesius Bassus (0.040359504832965916, 0.07953196540613872)\nPublius Vergilius Maro, Virgil, Vergil (0.03315200072836527, 0.0929348568307006)\nPublius Ovidius Naso (0.023965644822556705, 0.06525858344775079)\nGnaeus Naevius (0.11655300681959083, 0.20644761314321142)\nFragmenta Bobiensia (0.07398076042143839, 0.1385707741639945)\nScriptores Historiae Augustae (0.03177853760216489, 0.071072022819111)\nPublius Terentius Afer, Terence (0.028577576089507863, 0.058641733823644474)\nAulus Cornelius Celsus (0.017332921313593843, 0.0558848592109822)\nGaius Suetonius Tranquillus (0.033629947836759745, 0.0958944461491255)\nMarcus Terentius Varro, Varro (0.045866176600832524, 0.093891152245151)\nAppendix Vergiliana (0.0500247341083354, 0.1418501113034875)\nAnnius Florus (0.038297569987210456, 0.09140969162995595)\nPomponius Porphyrio (0.04030915576694411, 0.09312987184568636)\nMarcus Valerius Probus (0.03835521769177609, 0.08431237042156185)\nQuintus Ennius (0.05652467883705206, 0.12021636240703178)\nDidascaliae et Per. in Terentium (0.0782967032967033, 0.13598901098901098)\nCornelius Tacitus (0.02469418086200983, 0.07631488690859423)\nTitus Livius, Livy (0.011407436246836674, 0.03913716547549524)\nLucius Annaeus Seneca senior (0.01619733327917297, 0.052095498258405856)\nQuintus Horatius Flaccus, Horace (0.04486396446418656, 0.12253192670738479)\nGaius Asinius Pollio (0.03592814371257485, 0.08982035928143713)\nGaius Sallustius Crispus (0.020570966643975494, 0.059330326752893126)\nC. Plinius Caecilius Secundus, Pliny (0.01694301397770358, 0.06551977816761927)\nMarcus Fabius Quintilianus (0.009342494688624445, 0.0416682017463066)\nHyginus Gromaticus (0.0285692634131555, 0.08320703243407093)\nTitus Lucretius Carus (0.022190184885737107, 0.06787585965048998)\nClaudius Caesar Germanicus (0.04035804020100502, 0.12861180904522612)\nGaius, iur., Gaius (0.011268643689753487, 0.035144203727768185)\nQuintus Terentius Scaurus (0.04715169618092597, 0.09174311926605505)\nLucius Livius Andronicus (0.14615384615384616, 0.25)\nMarcus Cornelius Fronto (0.03605195520469984, 0.08350927115843583)\nDidascaliae et Argum. in Plautum (0.07712590639419907, 0.14831905075807514)\nArgum. Aen. et Tetrast. (0.07066381156316917, 0.1441827266238401)\nAnonymi Epici et Lyrici (0.09684487291849254, 0.19237510955302367)\nMarcus Porcius Cato, Cato (0.061287538049157236, 0.13079823724501385)\nSextus Iulius Frontinus (0.03041633518960488, 0.09337045876425351)\nLucius Annaeus Seneca iunior (0.012655345175352984, 0.05447654369184723)\nTitus Maccius Plautus (0.02682148990105487, 0.062141513731995376)\nMaurus Servius Honoratus, Servius (0.025347881711764008, 0.05923711189138313)\nQuintus Asconius Pedianus (0.010382059800664452, 0.029663028001898434)\n" ], [ "# grab prose authors\n\n# grab poets\n\n# consider individual files\n\n# Gaius Iulius Caesar, Caesar (0.016170899832329378, 0.0464137117307334)\n# Apuleius Madaurensis (0.039956560814859196, 0.12101183343319354)\n# Caelius Apicius (0.04383594547528974, 0.09950159130486999)\n# Anonymi Comici et Tragici (0.05979473449352968, 0.10397144132083891)\n# C. Iul. Caes. Augustus Octavianus (0.16793743890518084, 0.20527859237536658)\n# Publius Papinius Statius (0.03662215849687846, 0.1022791767482152)\n# Lucius Accius (0.0845518118245391, 0.16634880271243907)\n# Gaius Caesius Bassus (0.040359504832965916, 0.07953196540613872)\n# Publius Vergilius Maro, Virgil, Vergil (0.03315200072836527, 0.0929348568307006)\n# Publius Ovidius Naso (0.023965644822556705, 0.06525858344775079)\n# Gnaeus Naevius (0.11655300681959083, 0.20644761314321142)\n# Fragmenta Bobiensia (0.07398076042143839, 0.1385707741639945)\n# Scriptores Historiae Augustae (0.03177853760216489, 0.071072022819111)\n# Publius Terentius Afer, Terence (0.028577576089507863, 0.058641733823644474)\n# Aulus Cornelius Celsus (0.017332921313593843, 0.0558848592109822)\n# Gaius Suetonius Tranquillus (0.033629947836759745, 0.0958944461491255)\n# Marcus Terentius Varro, Varro (0.045866176600832524, 0.093891152245151)\n# Appendix Vergiliana (0.0500247341083354, 0.1418501113034875)\n# Annius Florus (0.038297569987210456, 0.09140969162995595)\n# Pomponius Porphyrio (0.04030915576694411, 0.09312987184568636)\n# Marcus Valerius Probus (0.03835521769177609, 0.08431237042156185)\n# Quintus Ennius (0.05652467883705206, 0.12021636240703178)\n# Didascaliae et Per. in Terentium (0.0782967032967033, 0.13598901098901098)\n# Cornelius Tacitus (0.02469418086200983, 0.07631488690859423)\n# Titus Livius, Livy (0.011407436246836674, 0.03913716547549524)\n# Lucius Annaeus Seneca senior (0.01619733327917297, 0.052095498258405856)\n# Quintus Horatius Flaccus, Horace (0.04486396446418656, 0.12253192670738479)\n# Gaius Asinius Pollio (0.03592814371257485, 0.08982035928143713)\n# Gaius Sallustius Crispus (0.020570966643975494, 0.059330326752893126)\n# C. Plinius Caecilius Secundus, Pliny (0.01694301397770358, 0.06551977816761927)\n# Marcus Fabius Quintilianus (0.009342494688624445, 0.0416682017463066)\n# Hyginus Gromaticus (0.0285692634131555, 0.08320703243407093)\n# Titus Lucretius Carus (0.022190184885737107, 0.06787585965048998)\n# Claudius Caesar Germanicus (0.04035804020100502, 0.12861180904522612)\n# Gaius, iur., Gaius (0.011268643689753487, 0.035144203727768185)\n# Quintus Terentius Scaurus (0.04715169618092597, 0.09174311926605505)\n# Lucius Livius Andronicus (0.14615384615384616, 0.25)\n# Marcus Cornelius Fronto (0.03605195520469984, 0.08350927115843583)\n# Didascaliae et Argum. in Plautum (0.07712590639419907, 0.14831905075807514)\n# Argum. Aen. et Tetrast. (0.07066381156316917, 0.1441827266238401)\n# Anonymi Epici et Lyrici (0.09684487291849254, 0.19237510955302367)\n# Marcus Porcius Cato, Cato (0.061287538049157236, 0.13079823724501385)\n# Sextus Iulius Frontinus (0.03041633518960488, 0.09337045876425351)\n# Lucius Annaeus Seneca iunior (0.012655345175352984, 0.05447654369184723)\n# Titus Maccius Plautus (0.02682148990105487, 0.062141513731995376)\n# Maurus Servius Honoratus, Servius (0.025347881711764008, 0.05923711189138313)\n# Quintus Asconius Pedianus (0.010382059800664452, 0.029663028001898434)\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d01e587c53a52ce28eef1acb9921d87d598c172c
80,095
ipynb
Jupyter Notebook
gans_keras.ipynb
andresvilla86/diadx-ia-ml
c6bad53ba2f1a22902b8fac049d6187ac957f921
[ "MIT" ]
null
null
null
gans_keras.ipynb
andresvilla86/diadx-ia-ml
c6bad53ba2f1a22902b8fac049d6187ac957f921
[ "MIT" ]
null
null
null
gans_keras.ipynb
andresvilla86/diadx-ia-ml
c6bad53ba2f1a22902b8fac049d6187ac957f921
[ "MIT" ]
null
null
null
95.237812
42,350
0.780024
[ [ [ "<a href=\"https://colab.research.google.com/github/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_07_2_Keras_gan.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# T81-558: Applications of Deep Neural Networks\n**Module 7: Generative Adversarial Networks**\n* Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)\n* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/).", "_____no_output_____" ], [ "# Module 7 Material\n\n* Part 7.1: Introduction to GANS for Image and Data Generation [[Video]](https://www.youtube.com/watch?v=0QnCH6tlZgc&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_07_1_gan_intro.ipynb)\n* **Part 7.2: Implementing a GAN in Keras** [[Video]](https://www.youtube.com/watch?v=T-MCludVNn4&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_07_2_Keras_gan.ipynb)\n* Part 7.3: Face Generation with StyleGAN and Python [[Video]](https://www.youtube.com/watch?v=Wwwyr7cOBlU&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_07_3_style_gan.ipynb)\n* Part 7.4: GANS for Semi-Supervised Learning in Keras [[Video]](https://www.youtube.com/watch?v=ZPewmEu7644&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_07_4_gan_semi_supervised.ipynb)\n* Part 7.5: An Overview of GAN Research [[Video]](https://www.youtube.com/watch?v=cvCvZKvlvq4&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_07_5_gan_research.ipynb)\n", "_____no_output_____" ] ], [ [ "# Nicely formatted time string\ndef hms_string(sec_elapsed):\n h = int(sec_elapsed / (60 * 60))\n m = int((sec_elapsed % (60 * 60)) / 60)\n s = sec_elapsed % 60\n return \"{}:{:>02}:{:>05.2f}\".format(h, m, s)", "_____no_output_____" ] ], [ [ "# Part 7.2: Implementing DCGANs in Keras\n\nPaper that described the type of DCGAN that we will create in this module. [[Cite:radford2015unsupervised]](https://arxiv.org/abs/1511.06434) This paper implements a DCGAN as follows:\n\n* No pre-processing was applied to training images besides scaling to the range of the tanh activation function [-1, 1]. \n* All models were trained with mini-batch stochastic gradient descent (SGD) with a mini-batch size of 128. \n* All weights were initialized from a zero-centered Normal distribution with standard deviation 0.02. \n* In the LeakyReLU, the slope of the leak was set to 0.2 in all models.\n* we used the Adam optimizer(Kingma & Ba, 2014) with tuned hyperparameters. We found the suggested learning rate of 0.001, to be too high, using 0.0002 instead. \n* Additionally, we found leaving the momentum term $\\beta{1}$ at the suggested value of 0.9 resulted in training oscillation and instability while reducing it to 0.5 helped stabilize training.\n\nThe paper also provides the following architecture guidelines for stable Deep Convolutional GANs:\n\n* Replace any pooling layers with strided convolutions (discriminator) and fractional-strided convolutions (generator).\n* Use batchnorm in both the generator and the discriminator.\n* Remove fully connected hidden layers for deeper architectures.\n* Use ReLU activation in generator for all layers except for the output, which uses Tanh.\n* Use LeakyReLU activation in the discriminator for all layers.\n\nWhile creating the material for this module I used a number of Internet resources, some of the most helpful were:\n\n* [Deep Convolutional Generative Adversarial Network (TensorFlow 2.0 example code)](https://www.tensorflow.org/tutorials/generative/dcgan)\n* [Keep Calm and train a GAN. Pitfalls and Tips on training Generative Adversarial Networks](https://medium.com/@utk.is.here/keep-calm-and-train-a-gan-pitfalls-and-tips-on-training-generative-adversarial-networks-edd529764aa9)\n* [Collection of Keras implementations of Generative Adversarial Networks GANs](https://github.com/eriklindernoren/Keras-GAN)\n* [dcgan-facegenerator](https://github.com/platonovsimeon/dcgan-facegenerator), [Semi-Paywalled Article by GitHub Author](https://medium.com/datadriveninvestor/generating-human-faces-with-keras-3ccd54c17f16)\n\nThe program created next will generate faces similar to these. While these faces are not perfect, they demonstrate how we can construct and train a GAN on or own. Later we will see how to import very advanced weights from nVidia to produce high resolution, realistic looking faces. Figure 7.GAN-GRID shows images from GAN training.\n\n**Figure 7.GAN-GRID: GAN Neural Network Training**\n![GAN](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/gan-3.png \"GAN Images\")\n\nAs discussed in the previous module, the GAN is made up of two different neural networks: the discriminator and the generator. The generator generates the images, while the discriminator detects if a face is real or was generated. These two neural networks work as shown in Figure 7.GAN-EVAL:\n\n**Figure 7.GAN-EVAL: Evaluating GANs**\n![GAN](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/gan_fig_1.png \"GAN\")\n\nThe discriminator accepts an image as its input and produces number that is the probability of the input image being real. The generator accepts a random seed vector and generates an image from that random vector seed. An unlimited number of new images can be created by providing additional seeds.", "_____no_output_____" ], [ "I suggest running this code with a GPU, it will be very slow on a CPU alone. The following code mounts your Google drive for use with Google CoLab. If you are not using CoLab, the following code will not work.", "_____no_output_____" ] ], [ [ "\ntry:\n from google.colab import drive\n drive.mount('/content/drive', force_remount=True)\n COLAB = True\n print(\"Note: using Google CoLab\")\n %tensorflow_version 2.x\nexcept:\n print(\"Note: not using Google CoLab\")\n COLAB = False", "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/drive\nNote: using Google CoLab\nTensorFlow 2.x selected.\n" ] ], [ [ "The following packages will be used to implement a basic GAN system in Python/Keras.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nfrom tensorflow.keras.layers import Input, Reshape, Dropout, Dense \nfrom tensorflow.keras.layers import Flatten, BatchNormalization\nfrom tensorflow.keras.layers import Activation, ZeroPadding2D\nfrom tensorflow.keras.layers import LeakyReLU\nfrom tensorflow.keras.layers import UpSampling2D, Conv2D\nfrom tensorflow.keras.models import Sequential, Model, load_model\nfrom tensorflow.keras.optimizers import Adam\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\nimport os \nimport time\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "These are the constants that define how the GANs will be created for this example. The higher the resolution, the more memory that will be needed. Higher resolution will also result in longer run times. For Google CoLab (with GPU) 128x128 resolution is as high as can be used (due to memory). Note that the resolution is specified as a multiple of 32. So **GENERATE_RES** of 1 is 32, 2 is 64, etc.\n\nTo run this you will need training data. The training data can be any collection of images. I suggest using training data from the following two locations. Simply unzip and combine to a common directory. This directory should be uploaded to Google Drive (if you are using CoLab). The constant **DATA_PATH** defines where these images are stored.\n\nThe source data (faces) used in this module can be found here:\n\n* [Kaggle Faces Data New](https://www.kaggle.com/gasgallo/faces-data-new)\n* [Kaggle Lag Dataset: Dataset of faces, from more than 1k different subjects](https://www.kaggle.com/gasgallo/lag-dataset)", "_____no_output_____" ] ], [ [ "# Generation resolution - Must be square \n# Training data is also scaled to this.\n# Note GENERATE_RES 4 or higher \n# will blow Google CoLab's memory and have not\n# been tested extensivly.\nGENERATE_RES = 3 # Generation resolution factor \n# (1=32, 2=64, 3=96, 4=128, etc.)\nGENERATE_SQUARE = 32 * GENERATE_RES # rows/cols (should be square)\nIMAGE_CHANNELS = 3\n\n# Preview image \nPREVIEW_ROWS = 4\nPREVIEW_COLS = 7\nPREVIEW_MARGIN = 16\n\n# Size vector to generate images from\nSEED_SIZE = 100\n\n# Configuration\nDATA_PATH = '/content/drive/My Drive/projects/faces'\nEPOCHS = 50\nBATCH_SIZE = 32\nBUFFER_SIZE = 60000\n\nprint(f\"Will generate {GENERATE_SQUARE}px square images.\")", "Will generate 96px square images.\n" ] ], [ [ "Next we will load and preprocess the images. This can take awhile. Google CoLab took around an hour to process. Because of this we store the processed file as a binary. This way we can simply reload the processed training data and quickly use it. It is most efficient to only perform this operation once. The dimensions of the image are encoded into the filename of the binary file because we need to regenerate it if these change.", "_____no_output_____" ] ], [ [ "# Image set has 11,682 images. Can take over an hour \n# for initial preprocessing.\n# Because of this time needed, save a Numpy preprocessed file.\n# Note, that file is large enough to cause problems for \n# sume verisons of Pickle,\n# so Numpy binary files are used.\ntraining_binary_path = os.path.join(DATA_PATH,\n f'training_data_{GENERATE_SQUARE}_{GENERATE_SQUARE}.npy')\n\nprint(f\"Looking for file: {training_binary_path}\")\n\nif not os.path.isfile(training_binary_path):\n start = time.time()\n print(\"Loading training images...\")\n\n training_data = []\n faces_path = os.path.join(DATA_PATH,'face_images')\n for filename in tqdm(os.listdir(faces_path)):\n path = os.path.join(faces_path,filename)\n image = Image.open(path).resize((GENERATE_SQUARE,\n GENERATE_SQUARE),Image.ANTIALIAS)\n training_data.append(np.asarray(image))\n training_data = np.reshape(training_data,(-1,GENERATE_SQUARE,\n GENERATE_SQUARE,IMAGE_CHANNELS))\n training_data = training_data.astype(np.float32)\n training_data = training_data / 127.5 - 1.\n\n\n print(\"Saving training image binary...\")\n np.save(training_binary_path,training_data)\n elapsed = time.time()-start\n print (f'Image preprocess time: {hms_string(elapsed)}')\nelse:\n print(\"Loading previous training pickle...\")\n training_data = np.load(training_binary_path)", "Looking for file: /content/drive/My Drive/projects/faces/training_data_96_96.npy\nLoading previous training pickle...\n" ] ], [ [ "We will use a TensorFlow **Dataset** object to actually hold the images. This allows the data to be quickly shuffled int divided into the appropriate batch sizes for training. ", "_____no_output_____" ] ], [ [ "# Batch and shuffle the data\ntrain_dataset = tf.data.Dataset.from_tensor_slices(training_data) \\\n .shuffle(BUFFER_SIZE).batch(BATCH_SIZE)", "_____no_output_____" ] ], [ [ "The code below creates the generator and discriminator.", "_____no_output_____" ], [ "Next we actually build the discriminator and the generator. Both will be trained with the Adam optimizer.", "_____no_output_____" ] ], [ [ "def build_generator(seed_size, channels):\n model = Sequential()\n\n model.add(Dense(4*4*256,activation=\"relu\",input_dim=seed_size))\n model.add(Reshape((4,4,256)))\n\n model.add(UpSampling2D())\n model.add(Conv2D(256,kernel_size=3,padding=\"same\"))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Activation(\"relu\"))\n\n model.add(UpSampling2D())\n model.add(Conv2D(256,kernel_size=3,padding=\"same\"))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Activation(\"relu\"))\n \n # Output resolution, additional upsampling\n model.add(UpSampling2D())\n model.add(Conv2D(128,kernel_size=3,padding=\"same\"))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Activation(\"relu\"))\n\n if GENERATE_RES>1:\n model.add(UpSampling2D(size=(GENERATE_RES,GENERATE_RES)))\n model.add(Conv2D(128,kernel_size=3,padding=\"same\"))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Activation(\"relu\"))\n\n # Final CNN layer\n model.add(Conv2D(channels,kernel_size=3,padding=\"same\"))\n model.add(Activation(\"tanh\"))\n\n return model\n\n\ndef build_discriminator(image_shape):\n model = Sequential()\n\n model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, \n padding=\"same\"))\n model.add(LeakyReLU(alpha=0.2))\n\n model.add(Dropout(0.25))\n model.add(Conv2D(64, kernel_size=3, strides=2, padding=\"same\"))\n model.add(ZeroPadding2D(padding=((0,1),(0,1))))\n model.add(BatchNormalization(momentum=0.8))\n model.add(LeakyReLU(alpha=0.2))\n\n model.add(Dropout(0.25))\n model.add(Conv2D(128, kernel_size=3, strides=2, padding=\"same\"))\n model.add(BatchNormalization(momentum=0.8))\n model.add(LeakyReLU(alpha=0.2))\n\n model.add(Dropout(0.25))\n model.add(Conv2D(256, kernel_size=3, strides=1, padding=\"same\"))\n model.add(BatchNormalization(momentum=0.8))\n model.add(LeakyReLU(alpha=0.2))\n\n model.add(Dropout(0.25))\n model.add(Conv2D(512, kernel_size=3, strides=1, padding=\"same\"))\n model.add(BatchNormalization(momentum=0.8))\n model.add(LeakyReLU(alpha=0.2))\n\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(1, activation='sigmoid'))\n\n return model", "_____no_output_____" ] ], [ [ "As we progress through training images will be produced to show the progress. These images will contain a number of rendered faces that show how good the generator has become. These faces will be ", "_____no_output_____" ] ], [ [ "def save_images(cnt,noise):\n image_array = np.full(( \n PREVIEW_MARGIN + (PREVIEW_ROWS * (GENERATE_SQUARE+PREVIEW_MARGIN)), \n PREVIEW_MARGIN + (PREVIEW_COLS * (GENERATE_SQUARE+PREVIEW_MARGIN)), 3), \n 255, dtype=np.uint8)\n \n generated_images = generator.predict(noise)\n\n generated_images = 0.5 * generated_images + 0.5\n\n image_count = 0\n for row in range(PREVIEW_ROWS):\n for col in range(PREVIEW_COLS):\n r = row * (GENERATE_SQUARE+16) + PREVIEW_MARGIN\n c = col * (GENERATE_SQUARE+16) + PREVIEW_MARGIN\n image_array[r:r+GENERATE_SQUARE,c:c+GENERATE_SQUARE] \\\n = generated_images[image_count] * 255\n image_count += 1\n\n \n output_path = os.path.join(DATA_PATH,'output')\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n \n filename = os.path.join(output_path,f\"train-{cnt}.png\")\n im = Image.fromarray(image_array)\n im.save(filename)", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "generator = build_generator(SEED_SIZE, IMAGE_CHANNELS)\n\nnoise = tf.random.normal([1, SEED_SIZE])\ngenerated_image = generator(noise, training=False)\n\nplt.imshow(generated_image[0, :, :, 0])", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "image_shape = (GENERATE_SQUARE,GENERATE_SQUARE,IMAGE_CHANNELS)\n\ndiscriminator = build_discriminator(image_shape)\ndecision = discriminator(generated_image)\nprint (decision)", "tf.Tensor([[0.50032634]], shape=(1, 1), dtype=float32)\n" ] ], [ [ "Loss functions must be developed that allow the generator and discriminator to be trained in an adversarial way. Because these two neural networks are being trained independently they must be trained in two separate passes. This requires two separate loss functions and also two separate updates to the gradients. When the discriminator's gradients are applied to decrease the discriminator's loss it is important that only the discriminator's weights are update. It is not fair, nor will it produce good results, to adversarially damage the weights of the generator to help the discriminator. A simple backpropagation would do this. It would simultaneously affect the weights of both generator and discriminator to lower whatever loss it was assigned to lower.\n\nFigure 7.TDIS shows how the discriminator is trained.\n\n**Figure 7.TDIS: Training the Discriminator**\n![Training the Discriminator](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/gan_fig_2.png \"Training the Discriminator\")\n\nHere a training set is generated with an equal number of real and fake images. The real images are randomly sampled (chosen) from the training data. An equal number of random images are generated from random seeds. For the discriminator training set, the $x$ contains the input images and the $y$ contains a value of 1 for real images and 0 for generated ones.\n\nLikewise, the Figure 7.TGEN shows how the generator is trained.\n\n**Figure 7.TGEN: Training the Generator**\n![Training the Generator](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/gan_fig_3.png \"Training the Generator\")\n\nFor the generator training set, the $x$ contains the random seeds to generate images and the $y$ always contains the value of 1, because the optimal is for the generator to have generated such good images that the discriminiator was fooled into assigning them a probability near 1.", "_____no_output_____" ] ], [ [ "# This method returns a helper function to compute cross entropy loss\ncross_entropy = tf.keras.losses.BinaryCrossentropy()\n\ndef discriminator_loss(real_output, fake_output):\n real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n total_loss = real_loss + fake_loss\n return total_loss\n\ndef generator_loss(fake_output):\n return cross_entropy(tf.ones_like(fake_output), fake_output)", "_____no_output_____" ] ], [ [ "Both the generator and discriminator use Adam and the same learning rate and momentum. This does not need to be the case. If you use a **GENERATE_RES** greater than 3 you may need to tune these learning rates, as well as other training and hyperparameters. ", "_____no_output_____" ] ], [ [ "generator_optimizer = tf.keras.optimizers.Adam(1.5e-4,0.5)\ndiscriminator_optimizer = tf.keras.optimizers.Adam(1.5e-4,0.5)", "_____no_output_____" ] ], [ [ "The following function is where most of the training takes place for both the discriminator and the generator. This function was based on the GAN provided by the [TensorFlow Keras exmples](https://www.tensorflow.org/tutorials/generative/dcgan) documentation. The first thing you should notice about this function is that it is annotated with the **tf.function** annotation. This causes the function to be precompiled and improves performance.\n\nThis function trans differently than the code we previously saw for training. This code makes use of **GradientTape** to allow the discriminator and generator to be trained together, yet separately. \n\n", "_____no_output_____" ] ], [ [ "# Notice the use of `tf.function`\n# This annotation causes the function to be \"compiled\".\[email protected]\ndef train_step(images):\n seed = tf.random.normal([BATCH_SIZE, SEED_SIZE])\n\n with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n generated_images = generator(seed, training=True)\n\n real_output = discriminator(images, training=True)\n fake_output = discriminator(generated_images, training=True)\n\n gen_loss = generator_loss(fake_output)\n disc_loss = discriminator_loss(real_output, fake_output)\n \n\n gradients_of_generator = gen_tape.gradient(\\\n gen_loss, generator.trainable_variables)\n gradients_of_discriminator = disc_tape.gradient(\\\n disc_loss, discriminator.trainable_variables)\n\n generator_optimizer.apply_gradients(zip(\n gradients_of_generator, generator.trainable_variables))\n discriminator_optimizer.apply_gradients(zip(\n gradients_of_discriminator, \n discriminator.trainable_variables))\n return gen_loss,disc_loss", "_____no_output_____" ], [ "def train(dataset, epochs):\n fixed_seed = np.random.normal(0, 1, (PREVIEW_ROWS * PREVIEW_COLS, \n SEED_SIZE))\n start = time.time()\n\n for epoch in range(epochs):\n epoch_start = time.time()\n\n gen_loss_list = []\n disc_loss_list = []\n\n for image_batch in dataset:\n t = train_step(image_batch)\n gen_loss_list.append(t[0])\n disc_loss_list.append(t[1])\n\n g_loss = sum(gen_loss_list) / len(gen_loss_list)\n d_loss = sum(disc_loss_list) / len(disc_loss_list)\n\n epoch_elapsed = time.time()-epoch_start\n print (f'Epoch {epoch+1}, gen loss={g_loss},disc loss={d_loss},'\\\n ' {hms_string(epoch_elapsed)}')\n save_images(epoch,fixed_seed)\n\n elapsed = time.time()-start\n print (f'Training time: {hms_string(elapsed)}')\n", "_____no_output_____" ], [ "train(train_dataset, EPOCHS)", "Epoch 1, gen loss=0.6737478375434875,disc loss=1.2876468896865845, 0:01:33.86\nEpoch 2, gen loss=0.6754337549209595,disc loss=1.2804691791534424, 0:01:26.96\nEpoch 3, gen loss=0.6792119741439819,disc loss=1.2002451419830322, 0:01:27.23\nEpoch 4, gen loss=0.6704637408256531,disc loss=1.1011184453964233, 0:01:26.74\nEpoch 5, gen loss=0.6726831197738647,disc loss=1.0789912939071655, 0:01:26.87\nEpoch 6, gen loss=0.6760282516479492,disc loss=1.086405873298645, 0:01:26.64\nEpoch 7, gen loss=0.6668657660484314,disc loss=1.0990564823150635, 0:01:26.75\nEpoch 8, gen loss=0.6794514060020447,disc loss=1.0572694540023804, 0:01:26.72\nEpoch 9, gen loss=0.667030930519104,disc loss=1.099564552307129, 0:01:26.83\nEpoch 10, gen loss=0.6715224385261536,disc loss=1.0793499946594238, 0:01:26.66\nEpoch 11, gen loss=0.6730715036392212,disc loss=1.078121304512024, 0:01:26.76\nEpoch 12, gen loss=0.6647288203239441,disc loss=1.1045489311218262, 0:01:26.72\nEpoch 13, gen loss=0.6678280234336853,disc loss=1.0965650081634521, 0:01:26.85\nEpoch 14, gen loss=0.6659991145133972,disc loss=1.0995577573776245, 0:01:26.63\nEpoch 15, gen loss=0.6716247797012329,disc loss=1.0771788358688354, 0:01:26.71\nEpoch 16, gen loss=0.6729282140731812,disc loss=1.070194125175476, 0:01:26.70\nEpoch 17, gen loss=0.5819647312164307,disc loss=1.2202180624008179, 0:01:26.77\nEpoch 18, gen loss=0.6757639646530151,disc loss=1.065081238746643, 0:01:26.61\nEpoch 19, gen loss=0.67451012134552,disc loss=1.0673273801803589, 0:01:26.69\nEpoch 20, gen loss=0.6766645908355713,disc loss=1.0598846673965454, 0:01:26.77\nEpoch 21, gen loss=0.6780093908309937,disc loss=1.0609248876571655, 0:01:26.69\nEpoch 22, gen loss=0.6759778261184692,disc loss=1.0606046915054321, 0:01:26.82\nEpoch 23, gen loss=0.6769225001335144,disc loss=1.054925799369812, 0:01:26.65\nEpoch 24, gen loss=0.6781579852104187,disc loss=1.0544047355651855, 0:01:26.73\nEpoch 25, gen loss=0.676042377948761,disc loss=1.0546783208847046, 0:01:26.75\nEpoch 26, gen loss=0.677901029586792,disc loss=1.052791953086853, 0:01:26.80\nEpoch 27, gen loss=0.681058406829834,disc loss=1.0429731607437134, 0:01:26.64\nEpoch 28, gen loss=0.6791036128997803,disc loss=1.0511810779571533, 0:01:26.73\nEpoch 29, gen loss=0.6798704266548157,disc loss=1.0473483800888062, 0:01:26.71\nEpoch 30, gen loss=0.6804633736610413,disc loss=1.0467922687530518, 0:01:26.79\nEpoch 31, gen loss=0.6794509291648865,disc loss=1.0476592779159546, 0:01:26.77\nEpoch 32, gen loss=0.6806340217590332,disc loss=1.0451370477676392, 0:01:26.61\nEpoch 33, gen loss=0.6815114617347717,disc loss=1.0450003147125244, 0:01:26.71\nEpoch 34, gen loss=0.6811343431472778,disc loss=1.0472784042358398, 0:01:26.67\nEpoch 35, gen loss=0.6814053058624268,disc loss=1.044533371925354, 0:01:26.79\nEpoch 36, gen loss=0.6829107403755188,disc loss=1.0392040014266968, 0:01:26.59\nEpoch 37, gen loss=0.68181312084198,disc loss=1.0412304401397705, 0:01:26.70\nEpoch 38, gen loss=0.6876026391983032,disc loss=1.023917555809021, 0:01:26.56\nEpoch 39, gen loss=0.6833422780036926,disc loss=1.0362210273742676, 0:01:26.75\nEpoch 40, gen loss=0.6848627328872681,disc loss=1.0325196981430054, 0:01:26.57\nEpoch 41, gen loss=0.6868091821670532,disc loss=1.0275564193725586, 0:01:26.60\nEpoch 42, gen loss=0.6845845580101013,disc loss=1.037258505821228, 0:01:26.65\nEpoch 43, gen loss=0.6817746758460999,disc loss=1.0453448295593262, 0:01:26.80\nEpoch 44, gen loss=0.6872225403785706,disc loss=1.0249252319335938, 0:01:26.50\nEpoch 45, gen loss=0.6867306232452393,disc loss=1.0273733139038086, 0:01:26.66\nEpoch 46, gen loss=0.6831635236740112,disc loss=1.041325330734253, 0:01:26.63\nEpoch 47, gen loss=0.6846590042114258,disc loss=1.033777117729187, 0:01:26.76\nEpoch 48, gen loss=0.683456301689148,disc loss=1.0370010137557983, 0:01:26.63\nEpoch 49, gen loss=0.6844978332519531,disc loss=1.034816861152649, 0:01:26.71\nEpoch 50, gen loss=0.6809002757072449,disc loss=1.0432080030441284, 0:01:26.67\nTraining time: 1:12:52.22\n" ] ], [ [ "", "_____no_output_____" ] ], [ [ "generator.save(os.path.join(DATA_PATH,\"face_generator.h5\"))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d01e6673f28a5ed622f563542b3af13485088507
8,471
ipynb
Jupyter Notebook
notebooks/keras/train.ipynb
Petr-By/qtpyvis
0b9a151ee6b9a56b486c2bece9c1f03414629efc
[ "MIT" ]
3
2017-10-04T14:51:26.000Z
2017-10-22T09:35:50.000Z
notebooks/keras/train.ipynb
CogSciUOS/DeepLearningToolbox
bf07578b9486d8c48e25df357bc4b9963b513b46
[ "MIT" ]
13
2017-11-26T10:05:00.000Z
2018-03-11T14:08:40.000Z
notebooks/keras/train.ipynb
CogSciUOS/DeepLearningToolbox
bf07578b9486d8c48e25df357bc4b9963b513b46
[ "MIT" ]
2
2017-09-24T21:39:42.000Z
2017-10-04T15:29:54.000Z
33.219608
129
0.525204
[ [ [ "from __future__ import print_function\nimport numpy as np\nnp.random.seed(1337) # for reproducibility\n\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras import backend as K", "Using TensorFlow backend.\n" ] ], [ [ "Preprocess data", "_____no_output_____" ] ], [ [ "nb_classes = 10\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n# number of convolutional filters to use\nnb_filters = 32\n# size of pooling area for max pooling\npool_size = (2, 2)\n# convolution kernel size\nkernel_size = (3, 3)\n\n# the data, shuffled and split between train and test sets\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\nif K.image_dim_ordering() == 'th':\n X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)\n X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\n X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255\nprint('X_train shape:', X_train.shape)\nprint(X_train.shape[0], 'train samples')\nprint(X_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\nY_train = np_utils.to_categorical(y_train, nb_classes)\nY_test = np_utils.to_categorical(y_test, nb_classes)", "X_train shape: (60000, 28, 28, 1)\n60000 train samples\n10000 test samples\n" ] ], [ [ "Build a Keras model using the `Sequential API`", "_____no_output_____" ] ], [ [ "batch_size = 50\nnb_epoch = 10\n\nmodel = Sequential()\n\nmodel.add(Convolution2D(nb_filters, kernel_size,\n padding='valid',\n input_shape=input_shape,\n activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Convolution2D(nb_filters, kernel_size,activation='relu'))\nmodel.add(Dropout(rate=0.25))\nmodel.add(Flatten())\nmodel.add(Dense(64,activation='relu'))\nmodel.add(Dropout(rate=5))\nmodel.add(Dense(nb_classes,activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_1 (Conv2D) (None, 26, 26, 32) 320 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 13, 13, 32) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 11, 11, 32) 9248 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 11, 11, 32) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 3872) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 64) 247872 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 64) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 258,090\nTrainable params: 258,090\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "Train and evaluate the model", "_____no_output_____" ] ], [ [ "model.fit(X_train[0:10000, ...], Y_train[0:10000, ...], batch_size=batch_size, epochs=nb_epoch,\n verbose=1, validation_data=(X_test, Y_test))\nscore = model.evaluate(X_test, Y_test, verbose=0)\nprint('Test score:', score[0])\nprint('Test accuracy:', score[1])", "Train on 10000 samples, validate on 10000 samples\nEpoch 1/10\n10000/10000 [==============================] - 5s - loss: 0.4915 - acc: 0.8532 - val_loss: 0.2062 - val_acc: 0.9433\nEpoch 2/10\n10000/10000 [==============================] - 5s - loss: 0.1562 - acc: 0.9527 - val_loss: 0.1288 - val_acc: 0.9605\nEpoch 3/10\n10000/10000 [==============================] - 5s - loss: 0.0950 - acc: 0.9704 - val_loss: 0.0890 - val_acc: 0.9741\nEpoch 4/10\n10000/10000 [==============================] - 5s - loss: 0.0678 - acc: 0.9788 - val_loss: 0.0972 - val_acc: 0.97000.9\nEpoch 5/10\n10000/10000 [==============================] - 5s - loss: 0.0532 - acc: 0.9826 - val_loss: 0.0822 - val_acc: 0.9739\nEpoch 6/10\n10000/10000 [==============================] - 5s - loss: 0.0382 - acc: 0.9876 - val_loss: 0.0898 - val_acc: 0.9751\nEpoch 7/10\n10000/10000 [==============================] - 5s - loss: 0.0293 - acc: 0.9903 - val_loss: 0.0652 - val_acc: 0.9822\nEpoch 8/10\n10000/10000 [==============================] - 5s - loss: 0.0277 - acc: 0.9917 - val_loss: 0.0840 - val_acc: 0.9758\nEpoch 9/10\n10000/10000 [==============================] - 5s - loss: 0.0217 - acc: 0.9918 - val_loss: 0.0736 - val_acc: 0.9787\nEpoch 10/10\n10000/10000 [==============================] - 5s - loss: 0.0188 - acc: 0.9936 - val_loss: 0.0735 - val_acc: 0.9812\nTest score: 0.0734814465971\nTest accuracy: 0.9812\n" ] ], [ [ "Save the model", "_____no_output_____" ] ], [ [ "model.save('example_keras_mnist_model.h5')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01e6693a0f1af46d02bffd4c4af2226c147798c
787,956
ipynb
Jupyter Notebook
Compute_forcing_1pctCO2.ipynb
Hegebf/CMIP5-forcing
48a9619f585b718a724018beadbb7f44f71b29d9
[ "MIT" ]
1
2022-01-19T09:34:10.000Z
2022-01-19T09:34:10.000Z
Compute_forcing_1pctCO2.ipynb
Hegebf/CMIP5-forcing
48a9619f585b718a724018beadbb7f44f71b29d9
[ "MIT" ]
null
null
null
Compute_forcing_1pctCO2.ipynb
Hegebf/CMIP5-forcing
48a9619f585b718a724018beadbb7f44f71b29d9
[ "MIT" ]
null
null
null
804.036735
142,996
0.947497
[ [ [ "# Compute forcing for 1%CO2 data", "_____no_output_____" ] ], [ [ "import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfiledir1 = '/Users/hege-beatefredriksen/OneDrive - UiT Office 365/Data/CMIP5_globalaverages/Forcingpaperdata'\nstoredata = False # store anomalies in file?\nstoreforcingdata = False\ncreatenewfile = False # if it is the first time this is run, new files should be created, that can later be loaded\n\nexp = '1pctCO2'\n\nfilenameT = 'annualTanom_1pctCO2.txt'\nfilenameN = 'annualNanom_1pctCO2.txt'\nfilenameFF = 'forcing_F13method_1pctCO2.txt'\nfilenameNF = 'forcing_estimates_1pctCO2.txt'\n\n# create file first time code is run:\nif createnewfile == True:\n cols = ['year','ACCESS1-0','ACCESS1-3','CanESM2','CCSM4','CNRM-CM5','CSIRO-Mk3-6-0','GFDL-CM3','GFDL-ESM2G','GFDL-ESM2M','GISS-E2-H','GISS-E2-R','HadGEM2-ES','inmcm4','IPSL-CM5A-LR','IPSL-CM5B-LR','MIROC-ESM','MIROC5','MPI-ESM-LR','MPI-ESM-MR','MRI-CGCM3','NorESM1-M']\n dfT = pd.DataFrame(np.full((140, len(cols)),'-'), columns = cols); dfT['year'] = np.arange(1,140+1)\n dfN = pd.DataFrame(np.full((140, len(cols)),'-'), columns = cols); dfN['year'] = np.arange(1,140+1)\n dfT.to_csv(filenameT, sep='\\t'); dfN.to_csv(filenameN, sep='\\t');\n dfFF = pd.DataFrame(np.full((140, len(cols)),'-'), columns = cols); dfFF['year'] = np.arange(1,140+1)\n dfNF = pd.DataFrame(np.full((140, len(cols)),'-'), columns = cols); dfNF['year'] = np.arange(1,140+1)\n dfFF.to_csv(filenameFF, sep='\\t'); dfNF.to_csv(filenameNF, sep='\\t');\n\n\n#model = 'ACCESS1-0'\n#model = 'ACCESS1-3'\n#model = 'CanESM2'\n#model = 'CCSM4'\n#model = 'CNRM-CM5'\n#model = 'CSIRO-Mk3-6-0'\n#model = 'GFDL-CM3'\n#model = 'GFDL-ESM2G' # 1pctco2 only for 70 years\n#model = 'GFDL-ESM2M' # 1pctco2 only for 70 years \n#model = 'GISS-E2-H'\n#model = 'GISS-E2-R'\n#model = 'HadGEM2-ES'\n#model = 'inmcm4'\n#model = 'IPSL-CM5A-LR'\n#model = 'IPSL-CM5B-LR'\n#model = 'MIROC-ESM'\n#model = 'MIROC5'\n#model = 'MPI-ESM-LR'\n#model = 'MPI-ESM-MR'\n#model = 'MRI-CGCM3'\nmodel = 'NorESM1-M'\n\n\nrealm = 'Amon'\nensemble = 'r1i1p1'\n\n\n## define time periods of data:\n\nif model == 'ACCESS1-0':\n controltimeperiod = '030001-079912'\n exptimeperiod = '030001-043912'\n control_branch_yr = 300\nelif model == 'ACCESS1-3':\n controltimeperiod = '025001-074912'\n exptimeperiod = '025001-038912'\n control_branch_yr = 250\nelif model == 'CanESM2':\n controltimeperiod = '201501-301012' \n exptimeperiod = '185001-198912'\n control_branch_yr = 2321\nelif model == 'CCSM4':\n controltimeperiod = '025001-130012'\n exptimeperiod = '185001-200512'\n control_branch_yr = 251\nelif model == 'CNRM-CM5':\n controltimeperiod = '185001-269912'\n exptimeperiod = '185001-198912'\n control_branch_yr = 1850\nelif model == 'CSIRO-Mk3-6-0':\n controltimeperiod = '000101-050012'\n exptimeperiod = '000101-014012'\n control_branch_yr = 104\nelif model == 'GFDL-CM3':\n controltimeperiod = '000101-050012'\n exptimeperiod = '000101-014012'\n control_branch_yr = 1\nelif model == 'GFDL-ESM2G' or model == 'GFDL-ESM2M': \n controltimeperiod = '000101-050012'\n exptimeperiod = '000101-020012' # 1pctco2 only for 70 years.\n control_branch_yr = 1\nelif model == 'GISS-E2-H':\n print(model + 'has control run for two different periods')\n #controltimeperiod = '118001-141912'\n controltimeperiod = '241001-294912'\n exptimeperiod = '185001-200012'\n control_branch_yr = 2410\nelif model == 'GISS-E2-R':\n #controltimeperiod = '333101-363012' \n #controltimeperiod1 = '398101-453012' \n controltimeperiod2 = '398101-920512'\n exptimeperiod = '185001-200012'\n control_branch_yr = 3981\n # Note: The two blocks of years that are present (3331-3630 and 3981-4530) represent different control runs\nelif model == 'HadGEM2-ES': \n controltimeperiod = '186001-243511'\n exptimeperiod = '186001-199912'\n control_branch_yr = 1860 # or actually december 1859, but I ignore this first month is the annual average \nelif model == 'inmcm4':\n controltimeperiod = '185001-234912' \n exptimeperiod = '209001-222912'\n control_branch_yr = 2090\nelif model == 'IPSL-CM5A-LR':\n controltimeperiod = '180001-279912'\n exptimeperiod = '185001-198912'\n control_branch_yr = 1850\nelif model == 'IPSL-CM5B-LR': \n controltimeperiod = '183001-212912' \n exptimeperiod = '185001-200012'\n control_branch_yr = 1850\nelif model == 'MIROC-ESM': \n controltimeperiod = '180001-242912' \n exptimeperiod = '000101-014012'\n control_branch_yr = 1880\nelif model == 'MIROC5': \n controltimeperiod = '200001-286912' \n exptimeperiod = '220001-233912' \n control_branch_yr = 2200\nelif model == 'MPI-ESM-LR': \n controltimeperiod = '185001-284912' \n exptimeperiod = '185001-199912'\n control_branch_yr = 1880\nelif model == 'MPI-ESM-MR': \n controltimeperiod = '185001-284912' \n exptimeperiod = '185001-199912'\n control_branch_yr = 1850\nelif model == 'MRI-CGCM3': \n controltimeperiod = '185101-235012'\n exptimeperiod = '185101-199012'\n control_branch_yr = 1891\nelif model == 'NorESM1-M':\n controltimeperiod = '070001-120012'\n exptimeperiod = '000101-014012'\n control_branch_yr = 700\n \n ", "_____no_output_____" ], [ "#### load 1pctCO2 data ####\n\nvar = 'tas' # temperatures\nstrings = [var, realm, model, exp, ensemble, exptimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\ntemp=datatable.iloc[0:len(datatable),0]\n\nvar = 'rlut' # rlut\nstrings = [var, realm, model, exp, ensemble, exptimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\nrlut=datatable.iloc[0:len(datatable),0]\n\nvar = 'rsut' # rsut\nstrings = [var, realm, model, exp, ensemble, exptimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\nrsut=datatable.iloc[0:len(datatable),0]\n\nvar = 'rsdt' # rsdt\nstrings = [var, realm, model, exp, ensemble, exptimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\nrsdt=datatable.iloc[0:len(datatable),0]\n\n# drop all data after 140 years\ntemp = temp[:140]; rlut = rlut[:140]; rsut = rsut[:140]; rsdt = rsdt[:140]\n\n\n###### load control run data ###### \nexp = 'piControl'\n\nvar = 'tas' # temperatures\nif model == 'GISS-E2-R': \n controltimeperiod = controltimeperiod2\n \nstrings = [var, realm, model, exp, ensemble, controltimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\ncontroltemp=datatable.iloc[:,0]\n\nvar = 'rlut' # rlut\nstrings = [var, realm, model, exp, ensemble, controltimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\ncontrolrlut=datatable.iloc[0:len(controltemp),0]\n\nvar = 'rsut' # rsut\nstrings = [var, realm, model, exp, ensemble, controltimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\ncontrolrsut=datatable.iloc[0:len(controltemp),0]\n\nvar = 'rsdt' # rsdt\nstrings = [var, realm, model, exp, ensemble, controltimeperiod]\nfilename = 'glannual_' + \"_\".join(strings) + '.txt'\nfile = os.path.join(filedir1, model, exp, filename)\ndatatable = pd.read_table(file, header=None,sep=\" \")\ncontrolrsdt=datatable.iloc[0:len(controltemp),0]\n", "_____no_output_____" ], [ "years = np.arange(1,len(temp)+1)\n\n# create figure\nfig, ax = plt.subplots(nrows=2,ncols=2,figsize = [16,10])\n\n# plot temperature\nvar = temp[:]; label = 'tas'\nax[0,0].plot(years,var,linewidth=2,color = \"black\")\n#ax[0,0].set_xlabel('t',fontsize = 18)\nax[0,0].set_ylabel(label + '(t)',fontsize = 18)\nax[0,0].set_title('1pctCO2 ' + label,fontsize = 18)\nax[0,0].grid()\nax[0,0].set_xlim(min(years),max(years))\nax[0,0].tick_params(axis='both',labelsize=18)\n\n# plot rlut\nvar = rlut[:]; label = 'rlut'\nax[0,1].plot(years,var,linewidth=2,color = \"black\")\n#ax[0,1].set_xlabel('t',fontsize = 18)\nax[0,1].set_ylabel(label + '(t)',fontsize = 18)\nax[0,1].set_title('1pctCO2 ' + label,fontsize = 18)\nax[0,1].grid()\nax[0,1].set_xlim(min(years),max(years))\nax[0,1].tick_params(axis='both',labelsize=18)\n\n# plot rsdt\nvar = rsdt[:]; label = 'rsdt'\nax[1,0].plot(years,var,linewidth=2,color = \"black\")\nax[1,0].set_xlabel('t',fontsize = 18)\nax[1,0].set_ylabel(label + '(t)',fontsize = 18)\nax[1,0].set_title('1pctCO2 ' + label,fontsize = 18)\nax[1,0].grid()\nax[1,0].set_xlim(min(years),max(years))\nax[1,0].tick_params(axis='both',labelsize=18)\n\n# plot rsut\nvar = rsut[:]; label = 'rsut'\nax[1,1].plot(years,var,linewidth=2,color = \"black\")\nax[1,1].set_xlabel('t',fontsize = 18)\nax[1,1].set_ylabel(label + '(t)',fontsize = 18)\nax[1,1].set_title('1pctCO2 ' + label,fontsize = 18)\nax[1,1].grid()\nax[1,1].set_xlim(min(years),max(years))\nax[1,1].tick_params(axis='both',labelsize=18)", "_____no_output_____" ], [ "# plot control run data and linear trends\n\ncontrolyears = np.arange(0,len(controltemp))\nbranchindex = control_branch_yr - int(controltimeperiod[0:4])\nprint(branchindex)\n\n\n# create figure\nfig, ax = plt.subplots(nrows=2,ncols=2,figsize = [16,10])\n\n# plot temperature\nvar = controltemp[:]; label = 'tas'\nax[0,0].plot(controlyears,var,linewidth=2,color = \"black\")\n# find linear fits to control T and nettoarad in the same period as exp:\np1 = np.polyfit(controlyears[branchindex:(branchindex + len(temp))], controltemp[branchindex:(branchindex + len(temp))], deg = 1)\nlintrendT = np.polyval(p1,controlyears[branchindex:(branchindex + len(temp))])\nax[0,0].plot(controlyears[branchindex:(branchindex + len(temp))], lintrendT, linewidth = 4)\nax[0,0].set_ylabel(label + '(t)',fontsize = 18)\nax[0,0].set_title('Control ' + label,fontsize = 18)\nax[0,0].grid()\nax[0,0].set_xlim(min(controlyears),max(controlyears))\nax[0,0].tick_params(axis='both',labelsize=18)\n\n# plot rlut\nvar = controlrlut[:]; label = 'rlut'\nax[0,1].plot(controlyears,var,linewidth=2,color = \"black\")\np2 = np.polyfit(controlyears[branchindex:(branchindex + len(temp))], controlrlut[branchindex:(branchindex + len(temp))], deg = 1)\nlintrend_rlut = np.polyval(p2,controlyears[branchindex:(branchindex + len(temp))])\nax[0,1].plot(controlyears[branchindex:(branchindex + len(temp))], lintrend_rlut, linewidth = 4)\nax[0,1].set_ylabel(label + '(t)',fontsize = 18)\nax[0,1].set_title('Control ' + label,fontsize = 18)\nax[0,1].grid()\nax[0,1].set_xlim(min(controlyears),max(controlyears))\nax[0,1].tick_params(axis='both',labelsize=18)\n\n# plot rsdt\nvar = controlrsdt[:]; label = 'rsdt'\nax[1,0].plot(controlyears,var,linewidth=2,color = \"black\")\np3 = np.polyfit(controlyears[branchindex:(branchindex + len(temp))], controlrsdt[branchindex:(branchindex + len(temp))], deg = 1)\nlintrend_rsdt = np.polyval(p3,controlyears[branchindex:(branchindex + len(temp))])\nax[1,0].plot(controlyears[branchindex:(branchindex + len(temp))], lintrend_rsdt, linewidth = 4)\nax[1,0].set_xlabel('t',fontsize = 18)\nax[1,0].set_ylabel(label + '(t)',fontsize = 18)\nax[1,0].set_title('Control ' + label,fontsize = 18)\nax[1,0].grid()\nax[1,0].set_xlim(min(controlyears),max(controlyears))\nax[1,0].set_ylim(var[0]-2,var[0]+2)\nax[1,0].tick_params(axis='both',labelsize=18)\n\n# plot rsut\nvar = controlrsut[:]; label = 'rsut'\nax[1,1].plot(controlyears,var,linewidth=2,color = \"black\")\np4 = np.polyfit(controlyears[branchindex:(branchindex + len(temp))], controlrsut[branchindex:(branchindex + len(temp))], deg = 1)\nlintrend_rsut = np.polyval(p4,controlyears[branchindex:(branchindex + len(temp))])\nax[1,1].plot(controlyears[branchindex:(branchindex + len(temp))], lintrend_rsut, linewidth = 4)\nax[1,1].set_xlabel('t',fontsize = 18)\nax[1,1].set_ylabel(label + '(t)',fontsize = 18)\nax[1,1].set_title('Control ' + label,fontsize = 18)\nax[1,1].grid()\nax[1,1].set_xlim(min(controlyears),max(controlyears))\nax[1,1].tick_params(axis='both',labelsize=18)", "0\n" ], [ "nettoarad = rsdt - rsut - rlut\ncontrolnettoarad = controlrsdt - controlrsut - controlrlut\nlintrendN = lintrend_rsdt - lintrend_rsut - lintrend_rlut\n\ndeltaN = nettoarad - lintrendN\ndeltaT = temp - lintrendT\n\n\n# create figure\nfig, ax = plt.subplots(nrows=1,ncols=2,figsize = [16,5])\n\n# plot 1pctCO2 net TOA rad\nvar = nettoarad[:]; label = 'net TOA rad'\nax[0,].plot(years,var,linewidth=2,color = \"black\")\nax[0,].set_xlabel('t',fontsize = 18)\nax[0,].set_ylabel(label + '(t)',fontsize = 18)\nax[0,].set_title('1pctCO2 ' + label,fontsize = 18)\nax[0,].grid()\nax[0,].set_xlim(min(years),max(years))\nax[0,].tick_params(axis='both',labelsize=18)\n\n# plot control net TOA rad\nvar = controlnettoarad[:]; label = 'net TOA rad'\nax[1,].plot(controlyears,var,linewidth=2,color = \"black\")\nax[1,].plot(controlyears[branchindex:(branchindex + len(temp))],lintrendN,linewidth=4)\nax[1,].set_xlabel('t',fontsize = 18)\nax[1,].set_ylabel(label + '(t)',fontsize = 18)\nax[1,].set_title('Control ' + label,fontsize = 18)\nax[1,].grid()\nax[1,].set_xlim(min(controlyears),max(controlyears))\nax[1,].tick_params(axis='both',labelsize=18)\n\n\n\n########### plot also anomalies: ########### \n\n# create figure\nfig, ax = plt.subplots(nrows=1,ncols=1,figsize = [8,5])\n\nvar = deltaN; label = 'net TOA rad'\nax.plot(years,var,linewidth=2,color = \"black\")\nax.set_xlabel('t',fontsize = 18)\nax.set_ylabel(label + '(t)',fontsize = 18)\nax.set_title('1pctCO2 ' + label + ' anomaly',fontsize = 18)\nax.grid()\nax.set_xlim(min(years),max(years))\nax.tick_params(axis='both',labelsize=18)\n\n# write time series to a dataframe?\nif storedata == True:\n dfT = pd.read_table(filenameT, index_col=0); dfN = pd.read_table(filenameN, index_col=0); # load files\n dfT[model] = deltaT; dfN[model] = deltaN\n dfT.to_csv(filenameT, sep='\\t'); dfN.to_csv(filenameN, sep='\\t') # save files again\n", "_____no_output_____" ] ], [ [ "## Load my estimated parameters", "_____no_output_____" ] ], [ [ "filename = 'best_estimated_parameters.txt'\n\nparameter_table = pd.read_table(filename,index_col=0)\nGregoryT2x = parameter_table.loc[model,'GregoryT2x']\nGregoryF2x = parameter_table.loc[model,'GregoryF2x']\nfbpar = GregoryF2x/GregoryT2x #feedback parameter from Gregory plot\nprint(fbpar)\n\nF = deltaN + fbpar*deltaT\n\nfig, ax = plt.subplots(figsize = [9,5]) \nplt.plot(years,F,linewidth=2,color = \"black\")\nax.set_xlabel('t (years)',fontsize = 18)\nax.set_ylabel('F(t) [$W/m^2$]',fontsize = 18)\nax.set_title('1pctCO2 forcing',fontsize = 18)\nax.grid()\nax.set_xlim(min(years),max(years))\nax.tick_params(axis='both',labelsize=22) \n\nif storeforcingdata == True:\n dfFF = pd.read_table(filenameFF, index_col=0); # load files\n dfFF[model] = F; \n dfFF.to_csv(filenameFF, sep='\\t'); # save file again\n\n", "1.108875012228765\n" ], [ "# load remaining parameters:\ntaulist = np.array(parameter_table.loc[model,'tau1':'tau3'])\na_n = np.array(parameter_table.loc[model,'a_1':'a_4'])\nb_n = np.array(parameter_table.loc[model,'b_1':'b_4'])\nF2x = parameter_table.loc[model,'F2x']\nT2x = parameter_table.loc[model,'T2x']\n\n# compute other needed parameters from these:\ndim = len(taulist)\n\nif any(a_n == 0):\n dim = np.count_nonzero(a_n[:dim])\n zeroindex = np.where(a_n == 0)[0]\n a_n = np.delete(a_n,zeroindex)\n b_n = np.delete(b_n,zeroindex)\n taulist = np.delete(taulist,zeroindex)\n \nfbparlist = (b_n/a_n)[:dim]\nprint(fbparlist)\namplitudes = a_n[:dim]/(2*F2x*taulist)\n\nprint(np.sum(a_n)/2)\nprint(T2x)", "[1.87032028 1.51817517 0.77623303]\n3.1691523255472656\n3.1691523255472656\n" ], [ "# compute components T_n(t) = exp(-t/tau_n)*F(t) (Here * is a convolution)\ndim = len(taulist)\nlf = len(F)\npredictors = np.full((lf,dim),np.nan) \n\n# compute exact predictors by integrating greens function\nfor k in range(0,dim):\n intgreensti = np.full((lf,lf),0.) # remember dot after 0 to create floating point number array instead of integer\n for t in range(0,lf):\n # compute one new contribution to the matrix:\n intgreensti[t,0] = taulist[k]*(np.exp(-t/taulist[k]) - np.exp(-(t+1)/taulist[k]))\n \n # take the rest from row above:\n if t > 0:\n intgreensti[t,1:(t+1)] = intgreensti[t-1,0:t]\n # compute discretized convolution integral by this matrix product:\n predictors[:,k] = [email protected](F)\n \nTn = amplitudes*predictors", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize = [9,5]) \nplt.plot(years,Tn[:,0],linewidth=2,color = \"black\",label = 'Mode with time scale ' + str(np.round(taulist[0])) + ' years')\nplt.plot(years,Tn[:,1],linewidth=2,color = \"blue\",label = 'Mode with time scale ' + str(np.round(taulist[1])) + ' years')\nif dim>2:\n plt.plot(years,Tn[:,2],linewidth=2,color = \"red\",label = 'Mode with time scale ' + str(np.round(taulist[2],1)) + ' years')\nax.set_xlabel('t',fontsize = 18)\nax.set_ylabel('T(t)',fontsize = 18)\nax.set_title('Temperature responses to forcing',fontsize = 18)\nax.grid()\nax.set_xlim(min(years),max(years))\nax.tick_params(axis='both',labelsize=22)\nax.legend(loc=2, prop={'size': 18});\n\nfig, ax = plt.subplots(figsize = [9,5]) \nplt.plot(years,np.sum(Tn, axis=1),linewidth=2,color = \"black\",label = 'Mode with time scale ' + str(np.round(taulist[0])) + ' years')\nax.set_xlabel('t (years)',fontsize = 18)\nax.set_ylabel('T(t) [°C]',fontsize = 18)\nax.set_title('Linear response to forcing',fontsize = 18)\nax.grid()\nax.set_xlim(min(years),max(years))\nax.tick_params(axis='both',labelsize=22)\n", "_____no_output_____" ], [ "# Compute new estimate of adjusted forcing\nit = 20 # number of iterations\nFiarray = np.full((lf,it),np.nan) \n\nFi = F\nfor i in range(0,it):\n\n # iterate\n predictors = np.full((lf,dim),np.nan) \n\n # compute exact predictors by integrating greens function\n for k in range(0,dim):\n intgreensti = np.full((lf,lf),0.) # remember dot after 0 to create floating point number array instead of integer\n for t in range(0,lf):\n # compute one new contribution to the matrix:\n intgreensti[t,0] = taulist[k]*(np.exp(-t/taulist[k]) - np.exp(-(t+1)/taulist[k]))\n\n # take the rest from row above:\n if t > 0:\n intgreensti[t,1:(t+1)] = intgreensti[t-1,0:t]\n # compute discretized convolution integral by this matrix product:\n predictors[:,k] = [email protected](Fi)\n\n Tni = amplitudes*predictors\n Fi = deltaN + Tni@fbparlist\n Fiarray[:,i] = Fi\n\n\nfig, ax = plt.subplots(nrows=1,ncols=2,figsize = [16,5])\nax[0,].plot(years,F,linewidth=2,color = \"black\",label = \"Old forcing\")\nfor i in range(0,it-1):\n ax[0,].plot(years,Fiarray[:,i],linewidth=1,color = \"gray\")\nax[0,].plot(years,Fiarray[:,it-1],linewidth=1,color = \"blue\",label = \"New forcing\")\nax[0,].set_xlabel('t (years)',fontsize = 18)\nax[0,].set_ylabel('F(t) [$W/m^2$]',fontsize = 18)\nax[0,].grid()\nax[0,].set_xlim(min(years),max(years))\nax[0,].tick_params(axis='both',labelsize=18) \n\nif model == 'GFDL-ESM2G' or model == 'GFDL-ESM2M': # linear fit for only 70 years\n # linear fit to forster forcing:\n linfitpar1 = np.polyfit(years[:70],F[:70],deg = 1)\n linfit_forcing1 = np.polyval(linfitpar1,years[:70])\n ax[0,].plot(years[:70],linfit_forcing1,'--',linewidth=1,color = \"black\")\n\n # linear fit to new forcing:\n linfitpar2 = np.polyfit(years[:70],Fiarray[:70,it-1],deg = 1)\n linfit_forcing2 = np.polyval(linfitpar2,years[:70])\n ax[0,].plot(years[:70],linfit_forcing2,'--',linewidth=1,color = \"blue\")\nelse: # linear fit for 140 years\n # linear fit to forster forcing:\n linfitpar1 = np.polyfit(years,F,deg = 1)\n linfit_forcing1 = np.polyval(linfitpar1,years)\n ax[0,].plot(years,linfit_forcing1,'--',linewidth=1,color = \"black\")\n\n # linear fit to new forcing:\n linfitpar2 = np.polyfit(years,Fiarray[:,it-1],deg = 1)\n linfit_forcing2 = np.polyval(linfitpar2,years)\n ax[0,].plot(years,linfit_forcing2,'--',linewidth=1,color = \"blue\")\n\n# Estimate and print out 4xCO2 forcing from end values of linear fits:\nprint(linfit_forcing1[-1])\nprint(linfit_forcing2[-1])\n\n# compare responses\nlabel = 'temperature'\n# plot temperature\nax[1,].plot(years,deltaT,linewidth=3,color = \"black\",label = model + \" modelled response\")\n\n# plot response\nax[1,].plot(years,np.sum(Tn,axis=1),'--',linewidth=2,color = \"black\",label = \"Linear response to old forcing\")\nax[1,].plot(years,np.sum(Tni,axis=1),'--',linewidth=2,color = \"blue\",label = \"Linear response to new forcing\")\nax[1,].set_xlabel('t (years)',fontsize = 18)\nax[1,].set_ylabel('T(t) [°C]',fontsize = 18)\n\nax[1,].set_title('1% CO$_2$ ' + label,fontsize = 18)\nax[0,].set_title('1% CO$_2$ effective forcing',fontsize = 18)\n\nax[1,].grid()\nax[1,].set_xlim(min(years),max(years))\nax[1,].tick_params(axis='both',labelsize=18)\n\nax[0,].text(0,1.03,'a)',transform=ax[0,].transAxes, fontsize=20)\nax[1,].text(0,1.03,'b)',transform=ax[1,].transAxes, fontsize=20)\n\n#plt.savefig('/Users/hege-beatefredriksen/OneDrive - UiT Office 365/Papers/Forcingpaper/Figures/' + model + '_1pctCO2_forcing_and_response.pdf', format='pdf', dpi=600, bbox_inches=\"tight\")\n\nif storeforcingdata == True:\n dfNF = pd.read_table(filenameNF, index_col=0); dfNF = pd.read_table(filenameNF, index_col=0); # load file\n dfNF[model] = Fiarray[:,it-1];\n dfNF.to_csv(filenameNF, sep='\\t'); # save file again", "6.03719377441265\n7.740062344354676\n" ], [ "# put results in pandas dataframe:\ncolumnnames = ['4xCO2forcingest_1pctCO2', '4xCO2forcingest_1pctCO2_F13method'];\n\n\n# if file is not already created, create a new file to store the results in:\nfilename = 'estimated_4xCO2forcing_from1pctCO2.txt'\n#dataframe = pd.DataFrame([np.concatenate((linfit_forcing2[-1], linfit_forcing1[-1]), axis=None)], index = [model], columns=columnnames)\n#dataframe.to_csv(filename, sep='\\t')\n#dataframe\n\n", "_____no_output_____" ], [ "# load existing dataframe, and append present result:\n\nloaded_dataframe = pd.read_table(filename,index_col=0)\npd.set_option('display.expand_frame_repr', False)\n# fill numbers into table:\nif model == 'GFDL-ESM2G' or model == 'GFDL-ESM2M':\n loaded_dataframe.loc[model,columnnames] = [np.concatenate((2*linfit_forcing2[-1], 2*linfit_forcing1[-1]), axis=None)]\nelse:\n loaded_dataframe.loc[model,columnnames] = [np.concatenate((linfit_forcing2[-1], linfit_forcing1[-1]), axis=None)]\n\n# write them to a file:\nloaded_dataframe.to_csv(filename, sep='\\t')\n\nloaded_dataframe", "_____no_output_____" ], [ "timedep_fbpar1 = Tni@fbparlist/np.sum(Tni,axis=1) # two alternative definitions\ntimedep_fbpar2 = Tni@fbparlist/deltaT\n\nfig, ax = plt.subplots(figsize = [9,5])\nlabel = 'Instantaneous feedback parameter'\n# plot response\nax.plot(years,timedep_fbpar1,linewidth=3,color = \"black\")\nax.plot(years,timedep_fbpar2,linewidth=1,color = \"gray\")\nax.plot(years,np.full((len(years),1),fbpar),linewidth=2,color = \"green\")\nax.set_xlabel('t',fontsize = 18)\nax.set_ylabel('$\\lambda$ (t)',fontsize = 18)\nax.set_title(label,fontsize = 18)\nax.grid()\nax.set_xlim(min(years),max(years))\nax.set_ylim(0,3)\nax.tick_params(axis='both',labelsize=18)\n\nfig, ax = plt.subplots(figsize = [9,5])\nlabel = 'Instantaneous climate sensitivity parameter'\n# plot response\nax.plot(years,1/timedep_fbpar1,linewidth=3,color = \"black\")\nax.plot(years,1/timedep_fbpar2,linewidth=1,color = \"gray\")\nax.plot(years,np.full((len(years),1),1/fbpar),linewidth=2,color = \"green\")\nax.set_xlabel('t',fontsize = 18)\nax.set_ylabel('S(t)',fontsize = 18)\nax.set_title(label,fontsize = 18)\nax.grid()\nax.set_xlim(min(years),max(years))\nax.set_ylim(0,2)\nax.tick_params(axis='both',labelsize=18)\n\nfig, ax = plt.subplots(figsize = [9,5])\nlabel = 'Instantaneous climate sensitivity'\n# plot response\nax.plot(years,F2x/timedep_fbpar1,linewidth=3,color = \"black\")\nax.plot(years,F2x/timedep_fbpar2,linewidth=1,color = \"gray\")\nax.plot(years,np.full((len(years),1),F2x/fbpar),linewidth=2,color = \"green\")\nax.set_xlabel('t',fontsize = 18)\nax.set_ylabel('ECS(t)',fontsize = 18)\nax.set_title(label,fontsize = 18)\nax.grid()\nax.set_xlim(min(years),max(years))\nax.set_ylim(0,6)\nax.tick_params(axis='both',labelsize=18)\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01e66e199bcd6d4a86ca03a9c1f50ada01ae763
14,001
ipynb
Jupyter Notebook
tutorials/video_classification.ipynb
isunjin/ClassyVision
2727e118fc434f3f38928c7864497d18ef04d9ba
[ "MIT" ]
null
null
null
tutorials/video_classification.ipynb
isunjin/ClassyVision
2727e118fc434f3f38928c7864497d18ef04d9ba
[ "MIT" ]
null
null
null
tutorials/video_classification.ipynb
isunjin/ClassyVision
2727e118fc434f3f38928c7864497d18ef04d9ba
[ "MIT" ]
null
null
null
44.589172
879
0.615527
[ [ [ "# How to do video classification ", "_____no_output_____" ], [ "In this tutorial, we will show how to train a video classification model in Classy Vision. Given an input video, the video classification task is to predict the most probable class label. This is very similar to image classification, which was covered in other tutorials, but there are a few differences that make video special. As the video duration can be long, we sample short video clips of a small number of frames, use the classifier to make predictions, and finally average the clip-level predictions to get the final video-level predictions. \n\nIn this tutorial we will: (1) load a video dataset; (2) configure a video model; (3) configure video meters; (4) build a task; (5) start training; Please note that these steps are being done separately in the tutorial for easy of exposition in the notebook format. As described in our [Getting started](https://classyvision.ai/tutorials/getting_started) tutorial, you can combine all configs used in this tutorial into a single config for ClassificationTask and train it using `classy_train.py`.", "_____no_output_____" ], [ "# 1. Prepare the dataset\n\nAll right! Let's start with the dataset. [UCF-101](https://www.crcv.ucf.edu/data/UCF101.php) is a canonical action recognition dataset. It has 101 action classes, and has 3 folds with different training/testing splitting . We use fold 1 in this tutorial. Classy Vision has implemented the dataset `ucf101`, which can be used to load the training and testing splits. ", "_____no_output_____" ] ], [ [ "from classy_vision.dataset import build_dataset\n\n# set it to the folder where video files are saved\nvideo_dir = \"[PUT YOUR VIDEO FOLDER HERE]\"\n# set it to the folder where dataset splitting files are saved\nsplits_dir = \"[PUT THE FOLDER WHICH CONTAINS SPLITTING FILES HERE]\"\n# set it to the file path for saving the metadata\nmetadata_file = \"[PUT THE FILE PATH OF DATASET META DATA HERE]\"\n\ndatasets = {}\ndatasets[\"train\"] = build_dataset({\n \"name\": \"ucf101\",\n \"split\": \"train\",\n \"batchsize_per_replica\": 8, # For training, we use 8 clips in a minibatch in each model replica\n \"use_shuffle\": True, # We shuffle the clips in the training split\n \"num_samples\": 64, # We train on 16 clips in one training epoch\n \"clips_per_video\": 1, # For training, we randomly sample 1 clip from each video\n \"frames_per_clip\": 8, # The video clip contains 8 frames\n \"video_dir\": video_dir,\n \"splits_dir\": splits_dir,\n \"metadata_file\": metadata_file,\n \"fold\": 1,\n \"transforms\": {\n \"video\": [\n {\n \"name\": \"video_default_augment\",\n \"crop_size\": 112,\n \"size_range\": [128, 160]\n }\n ]\n }\n})\ndatasets[\"test\"] = build_dataset({\n \"name\": \"ucf101\",\n \"split\": \"test\",\n \"batchsize_per_replica\": 10, # For testing, we will take 1 video once a time, and sample 10 clips per video\n \"use_shuffle\": False, # We do not shuffle clips in the testing split\n \"num_samples\": 80, # We test on 80 clips in one testing epoch\n \"clips_per_video\": 10, # We sample 10 clips per video\n \"frames_per_clip\": 8,\n \"video_dir\": video_dir,\n \"splits_dir\": splits_dir,\n \"metadata_file\": metadata_file,\n \"fold\": 1,\n \"transforms\": {\n \"video\": [\n {\n \"name\": \"video_default_no_augment\",\n \"size\": 128\n }\n ]\n } \n})", "_____no_output_____" ] ], [ [ "Note we specify different transforms for training and testing split. For training split, we first randomly select a size from `size_range` [128, 160], and resize the video clip so that its short edge is equal to the random size. After that, we take a random crop of spatial size 112 x 112. We find such data augmentation helps the model generalize better, and use it as the default transform with data augmentation. For testing split, we resize the video clip to have short edge of size 128, and skip the random cropping to use the entire video clip. This is the default transform without data augmentation.", "_____no_output_____" ], [ "# 2. Define a model trunk and a head\n\nNext, let's create the video model, which consists of a trunk and a head. The trunk can be viewed as a feature extractor for computing discriminative features from raw video pixels while the head is viewed as a classifier for producing the final predictions. Let's first create the trunk of architecture ResNet3D-18 by using the built-in `resnext3d` model in Classy Vision.", "_____no_output_____" ] ], [ [ "from classy_vision.models import build_model\n\nmodel = build_model({\n \"name\": \"resnext3d\",\n \"frames_per_clip\": 8, # The number of frames we have in each video clip\n \"input_planes\": 3, # We use RGB video frames. So the input planes is 3\n \"clip_crop_size\": 112, # We take croppings of size 112 x 112 from the video frames \n \"skip_transformation_type\": \"postactivated_shortcut\", # The type of skip connection in residual unit\n \"residual_transformation_type\": \"basic_transformation\", # The type of residual connection in residual unit\n \"num_blocks\": [2, 2, 2, 2], # The number of residual blocks in each of the 4 stages \n \"input_key\": \"video\", # The key used to index into the model input of dict type \n \"stage_planes\": 64, \n \"num_classes\": 101 # the number of classes\n})", "_____no_output_____" ] ], [ [ "We also need to create a model head, which consists of an average pooling layer and a linear layer, by using the `fully_convolutional_linear` head. At test time, the shape (channels, frames, height, width) of input tensor is typically `(3 x 8 x 128 x 173)`. The shape of input tensor to the average pooling layer is `(2048, 1, 8, 10)`. Since we do not use a global average pooling but an average pooling layer of kernel size `(1, 7, 7)`, the pooled feature map has shape `(2048, 1, 2, 5)`. The shape of prediction tensor from the linear layer is `(1, 2, 5, 101)`, which indicates the model computes a 101-D prediction vector densely over a `2 x 5` grid. That's why we name the head as `FullyConvolutionalLinearHead` because we use the linear layer as a `1x1` convolution layer to produce spatially dense predictions. Finally, predictions over the `2 x 5` grid are averaged.", "_____no_output_____" ] ], [ [ "from classy_vision.heads import build_head\nfrom collections import defaultdict\n\nunique_id = \"default_head\"\nhead = build_head({\n \"name\": \"fully_convolutional_linear\",\n \"unique_id\": unique_id,\n \"pool_size\": [1, 7, 7],\n \"num_classes\": 101,\n \"in_plane\": 512 \n})\n# In Classy Vision, the head can be attached to any residual block in the trunk. \n# Here we attach the head to the last block as in the standard ResNet model\nfork_block = \"pathway0-stage4-block1\"\nheads = defaultdict(dict)\nheads[fork_block][unique_id] = head\nmodel.set_heads(heads)", "_____no_output_____" ] ], [ [ "# 3. Choose the meters\n\nThis is the biggest difference between video and image classification. For images we used `AccuracyMeter` to measure top-1 and top-5 accuracy. For videos you can also use both `AccuracyMeter` and `VideoAccuracyMeter`, but they behave differently:\n * `AccuracyMeter` takes one clip-level prediction and compare it with groundtruth video label. It reports the clip-level accuracy.\n * `VideoAccuracyMeter` takes multiple clip-level predictions from the same video, averages them and compares that with groundtruth video label. It reports the video-level accuracy which is usually higher than clip-level accuracy. \n \n Both meters report top-1 and top-5 accuracy.", "_____no_output_____" ] ], [ [ "from classy_vision.meters import build_meters, AccuracyMeter, VideoAccuracyMeter\n\nmeters = build_meters({\n \"accuracy\": {\n \"topk\": [1, 5]\n },\n \"video_accuracy\": {\n \"topk\": [1, 5],\n \"clips_per_video_train\": 1,\n \"clips_per_video_test\": 10\n }\n})", "_____no_output_____" ] ], [ [ "# 4. Build a task\nGreat! we have defined the minimal set of components necessary for video classification, including dataset, model, loss function, meters and optimizer. We proceed to define a video classification task, and populate it with all the components.", "_____no_output_____" ] ], [ [ "from classy_vision.tasks import ClassificationTask\nfrom classy_vision.optim import build_optimizer\nfrom classy_vision.losses import build_loss\n\nloss = build_loss({\"name\": \"CrossEntropyLoss\"})\n\noptimizer = build_optimizer({\n \"name\": \"sgd\",\n \"lr\": {\n \"name\": \"multistep\",\n \"values\": [0.005, 0.0005],\n \"milestones\": [1]\n },\n \"num_epochs\": 2,\n \"weight_decay\": 0.0001,\n \"momentum\": 0.9\n})\n\nnum_epochs = 2\ntask = (\n ClassificationTask()\n .set_num_epochs(num_epochs)\n .set_loss(loss)\n .set_model(model)\n .set_optimizer(optimizer)\n .set_meters(meters)\n) \nfor phase in [\"train\", \"test\"]:\n task.set_dataset(datasets[phase], phase)", "_____no_output_____" ] ], [ [ "# 5. Start training\n\nAfter creating a task, you can simply pass that to a Trainer to start training. Here we will train on a single node and \nconfigure logging and checkpoints for training:", "_____no_output_____" ] ], [ [ "import time\nimport os\n\nfrom classy_vision.trainer import LocalTrainer\nfrom classy_vision.hooks import CheckpointHook\nfrom classy_vision.hooks import LossLrMeterLoggingHook\n\nhooks = [LossLrMeterLoggingHook(log_freq=4)]\n\ncheckpoint_dir = f\"/tmp/classy_checkpoint_{time.time()}\"\nos.mkdir(checkpoint_dir)\nhooks.append(CheckpointHook(checkpoint_dir, input_args={}))\n\ntask = task.set_hooks(hooks)\n\ntrainer = LocalTrainer()\ntrainer.train(task)", "_____no_output_____" ] ], [ [ "As the training progresses, you should see `LossLrMeterLoggingHook` printing the loss, learning rate and meter metrics. Checkpoints will be available in the folder created above.\n\n## 6. Conclusion\n\nVideo classification is very similar to image classification in Classy Vision, you just need to use an appropriate dataset, model and meters. This tutorial glossed over many details about training, please take a look at our [Getting started](https://classyvision.ai/tutorials/getting_started) tutorial to learn more. Refer to our API reference for more details about [ResNeXt3D](https://classyvision.ai/api/models.html#classy_vision.models.ResNeXt3D) models, [UCF101](https://classyvision.ai/api/dataset.html#classy_vision.dataset.UCF101Dataset) dataset and [VideoAccuracy](http://classyvision.ai/api/meters.html#classy_vision.meters.VideoAccuracyMeter) meters.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01e6b84e7bb78db7a868310ffa0c7c6a10cd0e4
2,244
ipynb
Jupyter Notebook
test/dist-correct/exam_97/test-exam.ipynb
chrispyles/jexam
ebe83b170f51c5820e0c93955824c3798922f097
[ "BSD-3-Clause" ]
1
2020-07-25T02:36:38.000Z
2020-07-25T02:36:38.000Z
test/dist-correct/exam_97/test-exam.ipynb
chrispyles/jexam
ebe83b170f51c5820e0c93955824c3798922f097
[ "BSD-3-Clause" ]
null
null
null
test/dist-correct/exam_97/test-exam.ipynb
chrispyles/jexam
ebe83b170f51c5820e0c93955824c3798922f097
[ "BSD-3-Clause" ]
null
null
null
17.952
251
0.497326
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d01e6f9ac48e76695054e553bb419552c2dc56d8
439,450
ipynb
Jupyter Notebook
R5.Bayesian_Regression/Bayesian_regression_professor.ipynb
ML4DS/ML4all
7336489dcb87d2412ad62b5b972d69c98c361752
[ "MIT" ]
27
2016-11-30T17:34:00.000Z
2022-03-23T23:11:48.000Z
R5.Bayesian_Regression/Bayesian_regression_professor.ipynb
ML4DS/ML4all
7336489dcb87d2412ad62b5b972d69c98c361752
[ "MIT" ]
5
2019-08-12T18:28:49.000Z
2019-11-26T11:01:39.000Z
R5.Bayesian_Regression/Bayesian_regression_professor.ipynb
ML4DS/ML4all
7336489dcb87d2412ad62b5b972d69c98c361752
[ "MIT" ]
14
2016-11-30T17:34:18.000Z
2021-09-15T09:53:32.000Z
263.77551
88,512
0.910074
[ [ [ "# Bayesian Parametric Regression\n\n Notebook version: 1.5 (Sep 24, 2019)\n\n Author: Jerónimo Arenas García ([email protected])\n Jesús Cid-Sueiro ([email protected])", "_____no_output_____" ], [ " Changes: v.1.0 - First version\n v.1.1 - ML Model selection included\n v.1.2 - Some typos corrected\n v.1.3 - Rewriting text, reorganizing content, some exercises.\n v.1.4 - Revised introduction\n v.1.5 - Revised notation. Solved exercise 5\n \n Pending changes: * Include regression on the stock data", "_____no_output_____" ] ], [ [ "# Import some libraries that will be necessary for working with data and displaying plots\n\n# To visualize plots in the notebook\n%matplotlib inline \nfrom IPython import display\n \nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io # To read matlab files\nimport pylab\nimport time", "_____no_output_____" ] ], [ [ "## A quick note on the mathematical notation\n\nIn this notebook we will make extensive use of probability distributions. In general, we will use capital letters\n${\\bf X}$, $S$, $E$ ..., to denote random variables, and lower-case letters ${\\bf x}$, $s$, $\\epsilon$ ..., to denote the values they can take. \n\nIn general, we will use letter $p$ for probability density functions (pdf). When necessary, we will use, capital subindices to make the random variable explicit. For instance, $p_{{\\bf X}, S}({\\bf x}, s)$ would be the joint pdf of random variables ${\\bf X}$ and $S$ at values ${\\bf x}$ and $s$, respectively. \n\nHowever, to avoid a notation overload, we will omit subindices when they are clear from the context. For instance, we will use $p({\\bf x}, s)$ instead of $p_{{\\bf X}, S}({\\bf x}, s)$.", "_____no_output_____" ], [ "## 1. Model-based parametric regression\n\n### 1.1. The regression problem.\n\nGiven an observation vector ${\\bf x}$, the goal of the regression problem is to find a function $f({\\bf x})$ providing *good* predictions about some unknown variable $s$. To do so, we assume that a set of *labelled* training examples, $\\{{\\bf x}_k, s_k\\}_{k=0}^{K-1}$ is available. \n\nThe predictor function should make good predictions for new observations ${\\bf x}$ not used during training. In practice, this is tested using a second set (the *test set*) of labelled samples.", "_____no_output_____" ], [ "### 1.2. Model-based parametric regression\n\nModel-based regression methods assume that all data in the training and test dataset have been generated by some stochastic process. In parametric regression, we assume that the probability distribution generating the data has a known parametric form, but the values of some parameters are unknown. \n\nIn particular, in this notebook we will assume the target variables in all pairs $({\\bf x}_k, s_k)$ from the training and test sets have been generated independently from some posterior distribution $p(s| {\\bf x}, {\\bf w})$, were ${\\bf w}$ is some unknown parameter. The training dataset is used to estimate ${\\bf w}$. ", "_____no_output_____" ], [ "<img src=\"figs/ParametricReg.png\" width=300>\n", "_____no_output_____" ], [ "### 1.3. Model assumptions\n\nIn order to estimate ${\\bf w}$ from the training data in a mathematicaly rigorous and compact form let us group the target variables into a vector\n$$\n{\\bf s} = \\left(s_0, \\dots, s_{K-1}\\right)^\\top\n$$\nand the input vectors into a matrix\n$$\n{\\bf X} = \\left({\\bf x}_0, \\dots, {\\bf x}_{K-1}\\right)^\\top\n$$\n\nWe will make the following assumptions:\n\n * A1. All samples in ${\\cal D}$ have been generated by the same distribution, $p({\\bf x}, s \\mid {\\bf w})$\n * A2. Input variables ${\\bf x}$ do not depend on ${\\bf w}$. This implies that\n$$\np({\\bf X} \\mid {\\bf w}) = p({\\bf X})\n$$\n * A3. Targets $s_0, \\dots, s_{K-1}$ are statistically independent, given ${\\bf w}$ and the inputs ${\\bf x}_0,\\ldots, {\\bf x}_{K-1}$, that is:\n$$\np({\\bf s} \\mid {\\bf X}, {\\bf w}) = \\prod_{k=0}^{K-1} p(s_k \\mid {\\bf x}_k, {\\bf w})\n$$\n ", "_____no_output_____" ], [ "## 2. Bayesian inference.\n\n### 2.1. The Bayesian approach\n\nThe main idea of Bayesian inference is the following: assume we want to estimate some unknown variable $U$ given an observed variable $O$. If $U$ and $O$ are random variables, we can describe the relation between $U$ and $O$ through the following functions:\n\n * **Prior distribution**: $p_U(u)$. It describes our uncertainty on the true value of $U$ before observing $O$.\n * **Likelihood function**: $p_{O \\mid U}(o \\mid u)$. It describes how the value of the observation is generated for a given value of $U$.\n * **Posterior distribution**: $p_{U|O}(u \\mid o)$. It describes our uncertainty on the true value of $U$ once the true value of $O$ is observed.", "_____no_output_____" ], [ "The major component of the Bayesian inference is the posterior distribution. All Bayesian estimates are computed as some of its central statistics (e.g. the mean, the median or the mode), for instance\n\n * **Maximum A Posteriori (MAP) estimate**: $\\qquad{\\widehat{u}}_{\\text{MAP}} = \\arg\\max_u p_{U \\mid O}(u \\mid o)$\n * **Minimum Mean Square Error (MSE) estimate**: $\\qquad\\widehat{u}_{\\text{MSE}} = \\mathbb{E}\\{U \\mid O=o\\}$\n\nThe choice between the MAP or the MSE estimate may depend on practical or computational considerations. From a theoretical point of view, $\\widehat{u}_{\\text{MSE}}$ has some nice properties: it minimizes $\\mathbb{E}\\{(U-\\widehat{u})^2\\}$ among all possible estimates, $\\widehat{u}$, so it is a natural choice. However, it involves the computation of an integral, which may not have a closed-form solution. In such cases, the MAP estimate can be a better choice.\n\nThe prior and the likelihood function are auxiliary distributions: if the posterior distribution is unknown, it can be computed from them using the Bayes rule:\n\\begin{equation}\np_{U|O}(u \\mid o) = \\frac{p_{O|U}(o \\mid u) \\cdot p_{U}(u)}{p_{O}(o)}\n\\end{equation}\n\nIn the next two sections we show that the Bayesian approach can be applied to both the prediction and the estimation problems.", "_____no_output_____" ], [ "### 2.2. Bayesian prediction under a known model\n\nAssuming that the model parameters ${\\bf w}$ are known, we can apply the Bayesian approach to predict ${\\bf s}$ for an input ${\\bf x}$. In that case, we can take\n\n * Unknown variable: ${\\bf s}$, and\n * Observations: ${\\bf x}$\n\nthe MAP and MSE predictions become\n\n* Maximum A Posterior (MAP): $\\qquad\\widehat{s}_{\\text{MAP}} = \\arg\\max_s p(s| {\\bf x}, {\\bf w})$\n* Minimum Mean Square Error (MSE): $\\qquad\\widehat{s}_{\\text{MSE}} = \\mathbb{E}\\{S |{\\bf x}, {\\bf w}\\}$\n", "_____no_output_____" ], [ "#### Exercise 1:\n\nAssuming \n$$\np(s\\mid x, w) = \\frac{s}{w x^2} \\exp\\left({-\\frac{s^2}{2 w x^2}}\\right), \\qquad s \\geq 0,\n$$\ncompute the MAP and MSE predictions of $s$ given $x$ and $w$.", "_____no_output_____" ], [ "#### Solution:\n<SOL>\n\\begin{align}\n\\widehat{s}_\\text{MAP} \n &= \\arg\\max_s \\left\\{\\frac{s}{w x^2} \\exp\\left({-\\frac{s^2}{2 w x^2}}\\right) \\right\\} \\\\\n &= \\arg\\max_s \\left\\{\\log(s) - \\log(w x^2) -\\frac{s^2}{2 w x^2} \\right\\} \\\\\n &= \\sqrt{w}x\n\\end{align}\nwhere the last step results from maximizing by differentiation.\n\n\n\\begin{align}\n\\widehat{s}_\\text{MSE} \n &= \\mathbb{E}\\{s | x, w\\} \\\\\n &= \\int_0^\\infty \\frac{s^2}{w x^2} \\exp\\left({-\\frac{s^2}{2 w x^2}}\\right) \\\\\n &= \\frac{1}{2} \\int_{-\\infty}^\\infty \\frac{s^2}{w x^2} \\exp\\left({-\\frac{s^2}{2 w x^2}}\\right) \\\\\n &= \\frac{\\sqrt{2\\pi}}{2\\sqrt{w x^2}} \\int_{-\\infty}^\\infty \\frac{s^2}{\\sqrt{2\\pi w x^2}} \\exp\\left({-\\frac{s^2}{2 w x^2}}\\right)\n\\end{align}\n\n\nNoting that the last integral corresponds to the variance of a zero-mean Gaussian distribution, we get\n\\begin{align}\n\\widehat{s}_\\text{MSE} \n &= \\frac{\\sqrt{2\\pi}}{2\\sqrt{w x^2}} w x^2 \\\\\n &= \\sqrt{\\frac{\\pi w}{2}}x\n\\end{align}\n</SOL>", "_____no_output_____" ], [ "#### 2.2.1. The Gaussian case\n\nA particularly interesting case arises when the data model is Gaussian:\n\n$$p(s|{\\bf x}, {\\bf w}) = \n \\frac{1}{\\sqrt{2\\pi}\\sigma_\\varepsilon}\n \\exp\\left(-\\frac{(s-{\\bf w}^\\top{\\bf z})^2}{2\\sigma_\\varepsilon^2}\\right)\n$$\n\nwhere ${\\bf z}=T({\\bf x})$ is a vector with components which can be computed directly from the observed variables. For a Gaussian distribution (and for any unimodal symetric distributions) the mean and the mode are the same and, thus,\n\n$$\n\\widehat{s}_\\text{MAP} = \\widehat{s}_\\text{MSE} = {\\bf w}^\\top{\\bf z}\n$$\n\n\nSuch expression includes a linear regression model, where ${\\bf z} = [1; {\\bf x}]$, as well as any other non-linear model as long as it can be expressed as a <i>\"linear in the parameters\"</i> model.\n\n", "_____no_output_____" ], [ "### 2.3. Bayesian Inference for Parameter Estimation\n\nIn a similar way, we can apply Bayesian inference to estimate the model parameters ${\\bf w}$ from a given dataset, $\\cal{D}$. In that case\n\n * the unknown variable is ${\\bf w}$, and\n * the observation is $\\cal{D} \\equiv \\{{\\bf X}, {\\bf s}\\}$\n\nso that\n\n* Maximum A Posterior (MAP): $\\qquad\\widehat{\\bf w}_{\\text{MAP}} = \\arg\\max_{\\bf w} p({\\bf w}| {\\cal D})$\n* Minimum Mean Square Error (MSE): $\\qquad\\widehat{\\bf w}_{\\text{MSE}} = \\mathbb{E}\\{{\\bf W} | {\\cal D}\\}$", "_____no_output_____" ], [ "## 3. Bayesian parameter estimation\n\nNOTE: Since the training data inputs are known, all probability density functions and expectations in the remainder of this notebook will be conditioned on the data matrix, ${\\bf X}$. To simplify the mathematical notation, from now on we will remove ${\\bf X}$ from all conditions. For instance, we will write $p({\\bf s}|{\\bf w})$ instead of $p({\\bf s}|{\\bf w}, {\\bf X})$, etc. Keep in mind that, in any case, all probabilities and expectations may depend on ${\\bf X}$ implicitely.\n\nSummarizing, the steps to design a Bayesian parametric regresion algorithm are the following:\n\n1. Assume a parametric data model $p(s| {\\bf x},{\\bf w})$ and a prior distribution $p({\\bf w})$.\n2. Using the data model and the i.i.d. assumption, compute $p({\\bf s}|{\\bf w})$.\n3. Applying the bayes rule, compute the posterior distribution $p({\\bf w}|{\\bf s})$.\n4. Compute the MAP or the MSE estimate of ${\\bf w}$ given ${\\bf x}$.\n5. Compute predictions using the selected estimate.\n", "_____no_output_____" ], [ "### 3.1. Bayesian Inference and Maximum Likelihood.\n\nApplying the Bayes rule the MAP estimate can be alternatively expressed as\n\\begin{align}\n\\qquad\\widehat{\\bf w}_{\\text{MAP}} \n &= \\arg\\max_{\\bf w} \\frac{p({\\cal D}| {\\bf w}) \\cdot p({\\bf w})}{p({\\cal D})} \\\\\n &= \\arg\\max_{\\bf w} p({\\cal D}| {\\bf w}) \\cdot p({\\bf w})\n\\end{align}\n\nBy comparisons, the ML (Maximum Likelihood) estimate has the form:\n$$\n\\widehat{\\bf w}_{\\text{ML}} = \\arg \\max_{\\bf w} p(\\mathcal{D}|{\\bf w})\n$$\n\nThis shows that the MAP estimate takes into account the prior distribution on the unknown parameter.\n\nAnother advantage of the Bayesian approach is that it provides not only a point estimate of the unknown parameter, but a whole funtion, the posterior distribution, which encompasses our belief on the unknown parameter given the data. For instance, we can take second order statistics like the variance of the posterior distributions to measure the uncertainty on the true value of the parameter around the mean.", "_____no_output_____" ], [ "### 3.2. The prior distribution\n\nSince each value of ${\\bf w}$ determines a regression function, by stating a prior distribution over the weights we state also a prior distribution over the space of regression functions.\n\nFor instance, assume that the data likelihood follows the Gaussian model in sec. 2.2.1, with $T(x) = (1, x, x^2, x^3)$, i.e. the regression functions have the form\n$$\nw_0 + w_1 x + w_2 x^2 + w_3 x^3\n$$\n\nEach value of ${\\bf w}$ determines a specific polynomial of degree 3. Thus, the prior distribution over ${\\bf w}$ describes which polynomials are more likely before observing the data.\n\nFor instance, assume a Gaussian prior with zero mean and variance ${\\bf V}_p$, i.e.,\n$$\np({\\bf w}) = \\frac{1}{(2\\pi)^{D/2} |{\\bf V}_p|^{1/2}} \n \\exp \\left(-\\frac{1}{2} {\\bf w}^\\intercal {\\bf V}_{p}^{-1}{\\bf w} \\right)\n$$\nwhere $D$ is the dimension of ${\\bf w}$. To abbreviate, we will also express this as\n$${\\bf w} \\sim {\\cal N}\\left({\\bf 0},{\\bf V}_{p} \\right)$$\nThe following code samples ${\\bf w}$ according to this distribution for ${\\bf V}_p = 0.002 \\, {\\bf I}$, and plots the resulting polynomial over the scatter plot of an arbitrary dataset.\n\nYou can check the effect of modifying the variance of the prior distribution.", "_____no_output_____" ] ], [ [ "n_grid = 200\ndegree = 3\nnplots = 20\n\n# Prior distribution parameters\nmean_w = np.zeros((degree+1,))\nv_p = 0.2 ### Try increasing this value\nvar_w = v_p * np.eye(degree+1)\n\nxmin = -1\nxmax = 1\nX_grid = np.linspace(xmin, xmax, n_grid)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nfor k in range(nplots):\n \n #Draw weigths fromt the prior distribution\n w_iter = np.random.multivariate_normal(mean_w, var_w)\n S_grid_iter = np.polyval(w_iter, X_grid)\n ax.plot(X_grid, S_grid_iter,'g-')\n\nax.set_xlim(xmin, xmax)\nax.set_ylim(-1, 1)\nax.set_xlabel('$x$')\nax.set_ylabel('$s$')\nplt.show()", "_____no_output_____" ] ], [ [ "The data observation will modify our belief about the true data model according to the posterior distribution. In the following we will analyze this in a Gaussian case.", "_____no_output_____" ], [ "## 4. Bayesian regression for a Gaussian model.\n\nWe will apply the above steps to derive a Bayesian regression algorithm for a Gaussian model.\n\n### 4.1. Step 1: The Gaussian model.\n\nLet us assume that the likelihood function is given by the Gaussian model described in Sec. 1.3.2.\n\n$$\ns~|~{\\bf w} \\sim {\\cal N}\\left({\\bf z}^\\top{\\bf w}, \\sigma_\\varepsilon^2 \\right)\n$$\n\nthat is \n$$p(s|{\\bf x}, {\\bf w}) = \n \\frac{1}{\\sqrt{2\\pi}\\sigma_\\varepsilon}\n \\exp\\left(-\\frac{(s-{\\bf w}^\\top{\\bf z})^2}{2\\sigma_\\varepsilon^2}\\right)\n$$\n\nAssume, also, that the prior is Gaussian\n\n$$\n{\\bf w} \\sim {\\cal N}\\left({\\bf 0},{\\bf V}_{p} \\right)\n$$", "_____no_output_____" ], [ "### 4.2. Step 2: Complete data likelihood\n\nUsing the assumptions A1, A2 and A3, it can be shown that\n\n$$\n{\\bf s}~|~{\\bf w} \\sim {\\cal N}\\left({\\bf Z}{\\bf w},\\sigma_\\varepsilon^2 {\\bf I} \\right)\n$$\nthat is\n$$\np({\\bf s}| {\\bf w})\n = \\frac{1}{\\left(\\sqrt{2\\pi}\\sigma_\\varepsilon\\right)^K}\n \\exp\\left(-\\frac{1}{2\\sigma_\\varepsilon^2}\\|{\\bf s}-{\\bf Z}{\\bf w}\\|^2\\right)\n$$\n\n", "_____no_output_____" ], [ "### 4.3. Step 3: Posterior weight distribution\n\nThe posterior distribution of the weights can be computed using the Bayes rule\n\n$$p({\\bf w}|{\\bf s}) = \\frac{p({\\bf s}|{\\bf w})~p({\\bf w})}{p({\\bf s})}$$\n\nSince both $p({\\bf s}|{\\bf w})$ and $p({\\bf w})$ follow a Gaussian distribution, we know also that the joint distribution and the posterior distribution of ${\\bf w}$ given ${\\bf s}$ are also Gaussian. Therefore,\n\n$${\\bf w}~|~{\\bf s} \\sim {\\cal N}\\left({\\bf w}_\\text{MSE}, {\\bf V}_{\\bf w}\\right)$$\n\nAfter some algebra, it can be shown that mean and the covariance matrix of the distribution are:\n\n$${\\bf V}_{\\bf w} = \\left[\\frac{1}{\\sigma_\\varepsilon^2} {\\bf Z}^{\\top}{\\bf Z} \n + {\\bf V}_p^{-1}\\right]^{-1}$$\n\n$${\\bf w}_\\text{MSE} = {\\sigma_\\varepsilon^{-2}} {\\bf V}_{\\bf w} {\\bf Z}^\\top {\\bf s}$$", "_____no_output_____" ], [ "#### Exercise 2: \n\nConsider the dataset with one-dimensional inputs given by", "_____no_output_____" ] ], [ [ "# True data parameters\nw_true = 3\nstd_n = 0.4\n\n# Generate the whole dataset\nn_max = 64\nX_tr = 3 * np.random.random((n_max,1)) - 0.5\nS_tr = w_true * X_tr + std_n * np.random.randn(n_max,1)\n\n# Plot data\nplt.figure()\nplt.plot(X_tr, S_tr, 'b.')\nplt.xlabel('$x$')\nplt.ylabel('$s$')\nplt.show()", "_____no_output_____" ] ], [ [ "Fit a Bayesian linear regression model assuming $z= x$ and", "_____no_output_____" ] ], [ [ "# Model parameters\nsigma_eps = 0.4\nmean_w = np.zeros((1,))\nsigma_p = 1e6\nVar_p = sigma_p**2* np.eye(1)", "_____no_output_____" ] ], [ [ "To do so, compute the posterior weight distribution using the first $k$ samples in the complete dataset, for $k = 1,2,4,8,\\ldots 128$. Draw all these posteriors along with the prior distribution in the same plot.", "_____no_output_____" ] ], [ [ "# No. of points to analyze\nn_points = [1, 2, 4, 8, 16, 32, 64]\n\n# Prepare plots\nw_grid = np.linspace(2.7, 3.4, 5000) # Sample the w axis\nplt.figure()\n\n# Compute the prior distribution over the grid points in w_grid\n# p = <FILL IN>\np = 1.0/(sigma_p*np.sqrt(2*np.pi)) * np.exp(-(w_grid**2)/(2*sigma_p**2))\nplt.plot(w_grid, p,'g-')\n\nfor k in n_points:\n\n # Select the first k samples\n Zk = X_tr[0:k, :]\n Sk = S_tr[0:k]\n\n # Parameters of the posterior distribution\n # 1. Compute the posterior variance.\n # (Make sure that the resulting variable, Var_w, is a 1x1 numpy array.)\n # Var_w = <FILL IN>\n Var_w = np.linalg.inv(np.dot(Zk.T, Zk)/(sigma_eps**2) + np.linalg.inv(Var_p))\n\n # 2. Compute the posterior mean.\n # (Make sure that the resulting variable, w_MSE, is a scalar)\n # w_MSE = <FILL IN>\n w_MSE = (Var_w.dot(Zk.T).dot(Sk)/(sigma_eps**2)).flatten()\n\n # Compute the posterior distribution over the grid points in w_grid\n sigma_w = np.sqrt(Var_w.flatten()) # First we take a scalar standard deviation\n # p = <FILL IN>\n p = 1.0/(sigma_w*np.sqrt(2*np.pi)) * np.exp(-((w_grid-w_MSE)**2)/(2*sigma_w**2))\n \n plt.plot(w_grid, p,'g-')\n plt.fill_between(w_grid, 0, p, alpha=0.8, edgecolor='#1B2ACC', facecolor='#089FFF',\n linewidth=1, antialiased=True)\n plt.title('Posterior distribution after {} samples'.format(k))\n plt.xlim(w_grid[0], w_grid[-1])\n plt.ylim(0, np.max(p))\n plt.xlabel('$w$')\n plt.ylabel('$p(w|s)$')\n\n display.clear_output(wait=True)\n display.display(plt.gcf())\n time.sleep(2.0)\n\n# Remove the temporary plots and fix the last one\ndisplay.clear_output(wait=True)\nplt.show()", "_____no_output_____" ] ], [ [ "#### Exercise 3: \n\nNote that, in the example above, the model assumptions are correct: the target variables have been generated by a linear model with noise standard deviation `sigma_n` which is exactly equal to the value assumed by the model, stored in variable `sigma_eps`. Check what happens if we take `sigma_eps=4*sigma_n` or `sigma_eps=sigma_n/4`. \n\n* Does the algorithm fail in that cases?\n* What differences can you observe with respect to the ideal case `sigma_eps=sigma_n`?", "_____no_output_____" ], [ "### 4.4. Step 4: Weight estimation.\n\nSince the posterior weight distribution is Gaussian, both the MAP and the MSE estimates are equal to the posterior mean, which has been already computed in step 3:\n\n$$\\widehat{\\bf w}_\\text{MAP} = \\widehat{\\bf w}_\\text{MSE} = {\\sigma_\\varepsilon^{-2}} {\\bf V}_{\\bf w} {\\bf Z}^\\top {\\bf s}$$", "_____no_output_____" ], [ "### 4.5. Step 5: Prediction\n\nUsing the MSE estimate, the final predictions are given by\n$$\n\\widehat{s}_\\text{MSE} = \\widehat{\\bf w}_\\text{MSE}^\\top{\\bf z}\n$$", "_____no_output_____" ], [ "#### Exercise 4:\n\nPlot the minimum MSE predictions of $s$ for inputs $x$ in the interval [-1, 3].", "_____no_output_____" ] ], [ [ "# <SOL>\nx = np.array([-1.0, 3.0])\ns_pred = w_MSE * x\n\nplt.figure()\nplt.plot(X_tr, S_tr,'b.')\nplt.plot(x, s_pred)\nplt.show()\n# </SOL>", "_____no_output_____" ] ], [ [ "## 5. Maximum likelihood vs Bayesian Inference. \n\n### 5.1. The Maximum Likelihood Estimate.\n\nFor comparative purposes, it is interesting to see here that the likelihood function is enough to compute the Maximum Likelihood (ML) estimate \n\n\\begin{align}\n{\\bf w}_\\text{ML} &= \\arg \\max_{\\bf w} p(\\mathcal{D}|{\\bf w}) \\\\\n &= \\arg \\min_{\\bf w} \\|{\\bf s}-{\\bf Z}{\\bf w}\\|^2\n\\end{align}\nwhich leads to the Least Squares (LS) solution\n$$\n{\\bf w}_\\text{ML} = ({\\bf Z}^\\top{\\bf Z})^{-1}{\\bf Z}^\\top{\\bf s}\n$$\n\nML estimation is prone to overfiting. In general, if the number of parameters (i.e. the dimension of ${\\bf w}$) is large in relation to the size of the training data, the predictor based on the ML estimate may have a small square error over the training set but a large error over the test set. Therefore, in practice, some cross validation procedure is required to keep the complexity of the predictor function under control depending on the size of the training set.\n\nBy defining a prior distribution over the unknown parameters, and using the Bayesian inference methods, the overfitting problems can be alleviated\n", "_____no_output_____" ], [ "### 5.2 Making predictions\n\n- Following an **ML approach**, we retain a single model, ${\\bf w}_{ML} = \\arg \\max_{\\bf w} p({\\bf s}|{\\bf w})$. Then, the predictive distribution of the target value for a new point would be obtained as:\n$$p({s^*}|{\\bf w}_{ML},{\\bf x}^*) $$\n \n For the generative model of Section 3.1.2 (additive i.i.d. Gaussian noise), this distribution is:\n$$p({s^*}|{\\bf w}_{ML},{\\bf x}^*) = \\frac{1}{\\sqrt{2\\pi\\sigma_\\varepsilon^2}} \\exp \\left(-\\frac{\\left(s^* - {\\bf w}_{ML}^\\top {\\bf z}^*\\right)^2}{2 \\sigma_\\varepsilon^2} \\right)$$\n \n * The mean of $s^*$ is just the same as the prediction of the LS model, and the same uncertainty is assumed independently of the observation vector (i.e., the variance of the noise of the model).\n * If a single value is to be kept, we would probably keep the mean of the distribution, which is equivalent to the LS prediction.", "_____no_output_____" ], [ "\n- Using <b>Bayesian inference</b>, we retain all models. Then, the inference of the value $s^* = s({\\bf x}^*)$ is carried out by mixing all models, according to the weights given by the posterior distribution.\n\\begin{align}\np({s^*}|{\\bf x}^*,{\\bf s}) \n & = \\int p({s^*}~|~{\\bf w},{\\bf x}^*) p({\\bf w}~|~{\\bf s}) d{\\bf w}\n\\end{align}\nwhere:\n * $p({s^*}|{\\bf w},{\\bf x}^*) = \\dfrac{1}{\\sqrt{2\\pi\\sigma_\\varepsilon^2}} \\exp \\left(-\\frac{\\left(s^* - {\\bf w}^\\top {\\bf z}^*\\right)^2}{2 \\sigma_\\varepsilon^2} \\right)$\n * $p({\\bf w} \\mid {\\bf s})$ is the posterior distribution of the weights, that can be computed using Bayes' Theorem.\n \nIn general the integral expression of the posterior distribution $p({s^*}|{\\bf x}^*,{\\bf s})$ cannot be computed analytically. Fortunately, for the Gaussian model, the computation of the posterior is simple, as we will show in the following section.\n", "_____no_output_____" ], [ "## 6. Posterior distribution of the target variable\n\nIn the same way that we have computed a distribution on ${\\bf w}$, we can compute a distribution on the target variable for a given input ${\\bf x}$ and given the whole dataset.\n\nSince ${\\bf w}$ is a random variable, the noise-free component of the target variable for an arbitrary input ${\\bf x}$, that is, $f = f({\\bf x}) = {\\bf w}^\\top{\\bf z}$ is also a random variable, and we can compute its distribution from the posterior distribution of ${\\bf w}$\n\nSince ${\\bf w}$ is Gaussian and $f$ is a linear transformation of ${\\bf w}$, $f$ is also a Gaussian random variable, whose posterior mean and variance can be calculated as follows:\n\n\\begin{align}\n\\mathbb{E}\\{f \\mid {\\bf s}, {\\bf z}\\} \n &= \\mathbb{E}\\{{\\bf w}^\\top {\\bf z}~|~{\\bf s}, {\\bf z}\\} \n = \\mathbb{E}\\{{\\bf w} ~|~{\\bf s}, {\\bf z}\\}^\\top {\\bf z} \\\\\n &= \\widehat{\\bf w}_\\text{MSE} ^\\top {\\bf z} \\\\\n% &= {\\sigma_\\varepsilon^{-2}} {{\\bf z}}^\\top {\\bf V}_{\\bf w} {\\bf Z}^\\top {\\bf s}\n\\end{align}\n\n\\begin{align}\n\\text{Cov}\\left[{{\\bf z}}^\\top {\\bf w}~|~{\\bf s}, {\\bf z}\\right] \n &= {\\bf z}^\\top \\text{Cov}\\left[{\\bf w}~|~{\\bf s}\\right] {\\bf z} \\\\\n &= {\\bf z}^\\top {\\bf V}_{\\bf w} {{\\bf z}}\n\\end{align}\n \nTherefore, \n$$\nf^*~|~{\\bf s}, {\\bf x} \n \\sim {\\cal N}\\left(\\widehat{\\bf w}_\\text{MSE} ^\\top {\\bf z}, ~~ \n {\\bf z}^\\top {\\bf V}_{\\bf w} {\\bf z} \\right)\n$$\n \nFinally, for $s = f + \\varepsilon$, the posterior distribution is \n$$\ns ~|~{\\bf s}, {\\bf z}^* \n \\sim {\\cal N}\\left(\\widehat{\\bf w}_\\text{MSE} ^\\top {\\bf z}, ~~\n {\\bf z}^\\top {\\bf V}_{\\bf w} {\\bf z} + \\sigma_\\varepsilon^2\\right)\n$$\n", "_____no_output_____" ], [ "#### Example:\n\nThe next figure shows a one-dimensional dataset with 15 points, which are noisy samples from a cosine signal (shown in the dotted curve)", "_____no_output_____" ] ], [ [ "n_points = 15\nn_grid = 200\nfrec = 3\nstd_n = 0.2\n\n# Data generation\nX_tr = 3 * np.random.random((n_points,1)) - 0.5\nS_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1)\n\n# Signal\nxmin = np.min(X_tr) - 0.1\nxmax = np.max(X_tr) + 0.1\nX_grid = np.linspace(xmin, xmax, n_grid)\nS_grid = - np.cos(frec*X_grid) #Noise free for the true model\n\n# Compute matrix with training input data for the polynomial model\nZ = []\nfor x_val in X_tr.tolist():\n Z.append([x_val[0]**k for k in range(degree+1)])\nZ = np.asmatrix(Z)\n\n# Plot data\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(X_tr,S_tr,'b.',markersize=10)\n\n# Plot noise-free function\nax.plot(X_grid, S_grid, 'b:', label='Noise-free signal') \n\n# Set axes\nax.set_xlim(xmin, xmax)\nax.set_ylim(S_tr[0] - 2, S_tr[-1] + 2)\nax.legend(loc='best')\nplt.show()", "_____no_output_____" ] ], [ [ "Let us assume that the cosine form of the noise-free signal is unknown, and we assume a polynomial model with a high degree. The following code plots the LS estimate", "_____no_output_____" ] ], [ [ "degree = 12\n\n# We plot also the least square solution\nw_LS = np.polyfit(X_tr.flatten(), S_tr.flatten(), degree)\nS_grid_LS = np.polyval(w_LS,X_grid)\n\n# Plot data\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(X_tr,S_tr,'b.',markersize=10)\n\n# Plot noise-free function\nax.plot(X_grid, S_grid, 'b:', label='Noise-free signal') \n# Plot LS regression function\nax.plot(X_grid, S_grid_LS, 'm-', label='LS regression') \n\n# Set axis\nax.set_xlim(xmin, xmax)\nax.set_ylim(S_tr[0] - 2, S_tr[-1] + 2)\nax.legend(loc='best')\nplt.show()", "_____no_output_____" ] ], [ [ "The following fragment of code computes the posterior weight distribution, draws random vectors from $p({\\bf w}|{\\bf s})$, and plots the corresponding regression curves along with the training points. Compare these curves with those extracted from the prior distribution of ${\\bf w}$ and with the LS solution.", "_____no_output_____" ] ], [ [ "nplots = 6\n\n# Prior distribution parameters\nsigma_eps = 0.2\nmean_w = np.zeros((degree+1,))\nsigma_p = .5\nVar_p = sigma_p**2 * np.eye(degree+1)\n\n# Compute matrix with training input data for the polynomial model\nZ = []\nfor x_val in X_tr.tolist():\n Z.append([x_val[0]**k for k in range(degree+1)])\nZ = np.asmatrix(Z)\n\n#Compute posterior distribution parameters\nVar_w = np.linalg.inv(np.dot(Z.T,Z)/(sigma_eps**2) + np.linalg.inv(Var_p))\nposterior_mean = Var_w.dot(Z.T).dot(S_tr)/(sigma_eps**2)\nposterior_mean = np.array(posterior_mean).flatten()\n\n# Plot data\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(X_tr,S_tr,'b.',markersize=10)\n\n# Plot noise-free function\nax.plot(X_grid, S_grid, 'b:', label='Noise-free signal') \n# Plot LS regression function\nax.plot(X_grid, S_grid_LS, 'm-', label='LS regression') \n\nfor k in range(nplots):\n \n # Draw weights from the posterior distribution\n w_iter = np.random.multivariate_normal(posterior_mean, Var_w)\n\n # Note that polyval assumes the first element of weight vector is the coefficient of\n # the highest degree term. Thus, we need to reverse w_iter\n S_grid_iter = np.polyval(w_iter[::-1], X_grid)\n ax.plot(X_grid,S_grid_iter,'g-')\n\n# Set axis\nax.set_xlim(xmin, xmax)\nax.set_ylim(S_tr[0] - 2, S_tr[-1] + 2)\nax.legend(loc='best')\nplt.show()", "_____no_output_____" ] ], [ [ "Not only do we obtain a better predictive model, but we also have confidence intervals (error bars) for the predictions.", "_____no_output_____" ] ], [ [ "# Compute standard deviation\nstd_x = []\nfor el in X_grid:\n x_ast = np.array([el**k for k in range(degree+1)])\n std_x.append(np.sqrt(x_ast.dot(Var_w).dot(x_ast)[0,0]))\nstd_x = np.array(std_x)\n\n# Plot data\nfig = plt.figure(figsize=(10,6))\nax = fig.add_subplot(111)\nax.plot(X_tr,S_tr,'b.',markersize=10)\n\n# Plot the posterior mean\n# Note that polyval assumes the first element of weight vector is the coefficient of\n# the highest degree term. Thus, we need to reverse w_iter\nS_grid_iter = np.polyval(posterior_mean[::-1],X_grid)\nax.plot(X_grid,S_grid_iter,'g-',label='Predictive mean, BI')\n\n#Plot confidence intervals for the Bayesian Inference\nplt.fill_between(X_grid, S_grid_iter-std_x, S_grid_iter+std_x,\n alpha=0.4, edgecolor='#1B2ACC', facecolor='#089FFF',\n linewidth=2, antialiased=True)\n\n#We plot also the least square solution\nw_LS = np.polyfit(X_tr.flatten(), S_tr.flatten(), degree)\nS_grid_iter = np.polyval(w_LS,X_grid)\n\n# Plot noise-free function\nax.plot(X_grid, S_grid, 'b:', label='Noise-free signal') \n# Plot LS regression function\nax.plot(X_grid, S_grid_LS, 'm-', label='LS regression') \n\n# Set axis\nax.set_xlim(xmin, xmax)\nax.set_ylim(S_tr[0]-2,S_tr[-1]+2)\nax.set_title('Predicting the target variable')\nax.set_xlabel('Input variable')\nax.set_ylabel('Target variable')\nax.legend(loc='best')\nplt.show()", "_____no_output_____" ] ], [ [ "#### Exercise 5:\n\nAssume the dataset ${\\cal{D}} = \\left\\{ x_k, s_k \\right\\}_{k=0}^{K-1}$ containing $K$ i.i.d. samples from a distribution\n\n$$p(s|x,w) = w x \\exp(-w x s), \\qquad s>0,\\quad x> 0,\\quad w> 0$$\n\nWe model also our uncertainty about the value of $w$ assuming a prior distribution for $w$ following a Gamma distribution with parameters $\\alpha>0$ and $\\beta>0$.\n\n$$\nw \\sim \\text{Gamma}\\left(\\alpha, \\beta \\right) \n = \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)} w^{\\alpha-1} \\exp\\left(-\\beta w\\right), \\qquad w>0\n$$\n\nNote that the mean and the mode of a Gamma distribution can be calculated in closed-form as\n\n$$\n\\mathbb{E}\\left\\{w\\right\\}=\\frac{\\alpha}{\\beta}; \\qquad\n$$\n$$\n\\text{mode}\\{w\\} = \\arg\\max_w p(w) = \\frac{\\alpha-1}{\\beta}\n$$\n\n**1.** Determine an expression for the likelihood function.", "_____no_output_____" ], [ "#### Solution:\n\n[comment]: # (<SOL>)\n\\begin{align}\np({\\bf s}| w) \n &= \\prod_{k=0}^{K-1} p(s_k|w, x_k) = \\prod_{k=0}^{K-1} \\left(w x_k \\exp(-w x_k s_k)\\right) \\nonumber\\\\\n &= w^K \\cdot \\left(\\prod_{k=0}^{K-1} x_k \\right) \\exp\\left( -w \\sum_{k=0}^{K-1} x_k s_k\\right)\n\\end{align}\n\n[comment]: # (</SOL>)\n", "_____no_output_____" ], [ "**2.** Determine the maximum likelihood coefficient, $\\widehat{w}_{\\text{ML}}$.", "_____no_output_____" ], [ "#### Solution:\n\n[comment]: # (<SOL>)\n\\begin{align}\n\\widehat{w}_{\\text{ML}} \n &= \\arg\\max_w w^K \\cdot \\left(\\prod_{k=0}^{K-1} x_k \\right) \\exp\\left( -w \\sum_{k=0}^{K-1} x_k s_k\\right)\n \\\\\n &= \\arg\\max_w \\left(w^K \\cdot \\exp\\left( -w \\sum_{k=0}^{K-1} x_k s_k\\right)\\right)\n \\\\\n &= \\arg\\max_w \\left(K \\log(w) - w \\sum_{k=0}^{K-1} x_k s_k \\right)\n \\\\\n &= \\frac{K}{\\sum_{k=0}^{K-1} x_k s_k} \n\\end{align}\n\n[comment]: # (</SOL>)\n", "_____no_output_____" ], [ "**3.** Obtain the posterior distribution $p(w|{\\bf s})$. Note that you do not need to calculate $p({\\bf s})$ since the posterior distribution can be readily identified as another Gamma distribution.", "_____no_output_____" ], [ "#### Solution:\n\n[comment]: # (<SOL>)\n\\begin{align}\np(w|{\\bf s}) \n &= \\frac{p({\\bf s}|w) p(w)}{p(s)} \\\\\n &= \\frac{1}{p(s)} \n \\left(w^K \\cdot \\left(\\prod_{k=0}^{K-1} x_k \\right) \\exp\\left( -w \\sum_{k=0}^{K-1} x_k s_k\\right) \\right)\n \\left(\\frac{\\beta^\\alpha}{\\Gamma(\\alpha)} w^{\\alpha-1} \\exp\\left(-\\beta w\\right)\\right) \\\\\n &= \\frac{1}{p(s)} \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)} \\left(\\prod_{k=0}^{K-1} x_k \\right) \n \\left(w^{K + \\alpha - 1} \\cdot \n \\exp\\left( -w \\left(\\beta + \\sum_{k=0}^{K-1} x_k s_k\\right) \\right) \\right)\n\\end{align}\nthat is\n$$\nw \\mid {\\bf s} \\sim Gamma\\left(K+\\alpha, \\beta + \\sum_{k=0}^{K-1} x_k s_k \\right)\n$$\n\n[comment]: # (</SOL>)", "_____no_output_____" ], [ "**4.** Determine the MSE and MAP a posteriori estimators of $w$: $w_\\text{MSE}=\\mathbb{E}\\left\\{w|{\\bf s}\\right\\}$ and $w_\\text{MAP} = \\max_w p(w|{\\bf s})$.", "_____no_output_____" ], [ "#### Solution:\n\n[comment]: # (<SOL>)\n$$\nw_{\\text{MSE}} = \\mathbb{E}\\left\\{w \\mid {\\bf s} \\right\\} \n = \\frac{K + \\alpha}{\\beta + \\sum_{k=0}^{K-1} x_k s_k}\n$$\n\n$$\nw_{\\text{MAP}} = \\text{mode}\\{w\\} = \\arg\\max_w p(w) = \\frac{K + \\alpha-1}{\\beta + \\sum_{k=0}^{K-1} x_k s_k}\n$$\n\n[comment]: # (</SOL>)\n \n \n\n", "_____no_output_____" ], [ "**5.** Compute the following estimators of $S$:\n\n$\\qquad\\widehat{s}_1 = \\mathbb{E}\\{s|w_\\text{ML},x\\}$\n\n$\\qquad\\widehat{s}_2 = \\mathbb{E}\\{s|w_\\text{MSE},x\\}$\n\n$\\qquad\\widehat{s}_3 = \\mathbb{E}\\{s|w_\\text{MAP},x\\}$", "_____no_output_____" ], [ "#### Solution:\n\n[comment]: # (<SOL>)\n$$\n\\widehat{s}_1 = \\mathbb{E}\\{s|w_\\text{ML},x\\} = w_\\text{ML} x\n$$\n\n$$\n\\widehat{s}_2 = \\mathbb{E}\\{s|w_\\text{MSE},x\\} = w_\\text{MSE} x\n$$\n\n$$\n\\widehat{s}_3 = \\mathbb{E}\\{s|w_\\text{MAP},x\\} = w_\\text{MAP} x\n$$\n \n[comment]: # (</SOL>)\n \n \n\n", "_____no_output_____" ], [ "## 7. Maximum evidence model selection\n\nWe have already addressed with Bayesian Inference the following two issues:\n\n - For a given degree, how do we choose the weights?\n \n - Should we focus on just one model, or can we use several models at once?\n \nHowever, we still needed some assumptions: a parametric model (i.e., polynomial function and <i>a priori</i> degree selection) and several parameters needed to be adjusted.\n\nThough we can recur to cross-validation, Bayesian inference opens the door to other strategies. \n\n - We could argue that rather than keeping single selections of these parameters, we could use simultaneously several sets of parameters (and/or several parametric forms), and average them in a probabilistic way ... (like we did with the models)\n \n - We will follow a simpler strategy, selecting just the most likely set of parameters according to an ML criterion", "_____no_output_____" ], [ "### 7.1 Model evidence\n\nThe evidence of a model is defined as\n\n$$L = p({\\bf s}~|~{\\cal M})$$\n\nwhere ${\\cal M}$ denotes the model itself and any free parameters it may have. For instance, for the polynomial model we have assumed so far, ${\\cal M}$ would represent the degree of the polynomia, the variance of the additive noise, and the <i>a priori</i> covariance matrix of the weights\n\nApplying the Theorem of Total probability, we can compute the evidence of the model as\n\n$$L = \\int p({\\bf s}~|~{\\bf f},{\\cal M}) p({\\bf f}~|~{\\cal M}) d{\\bf f} $$\n\nFor the linear model $f({\\bf x}) = {\\bf w}^\\top{\\bf z}$, the evidence can be computed as\n\n$$L = \\int p({\\bf s}~|~{\\bf w},{\\cal M}) p({\\bf w}~|~{\\cal M}) d{\\bf w} $$\n\nIt is important to notice that these probability density functions are exactly the ones we computed on the previous section. We are just making explicit that they depend on a particular model and the selection of its parameters. Therefore:\n\n - $p({\\bf s}~|~{\\bf w},{\\cal M})$ is the likelihood of ${\\bf w}$\n \n - $p({\\bf w}~|~{\\cal M})$ is the <i>a priori</i> distribution of the weights", "_____no_output_____" ], [ "### 7.2 Model selection via evidence maximization\n\n - As we have already mentioned, we could propose a prior distribution for the model parameters, $p({\\cal M})$, and use it to infer the posterior. However, this can be very involved (usually no closed-form expressions can be derived)\n \n - Alternatively, maximizing the evidence is normally good enough\n \n $${\\cal M}_\\text{ML} = \\arg\\max_{\\cal M} p(s~|~{\\cal M})$$\n \nNote that we are using the subscript 'ML' because the evidence can also be referred to as the likelihood of the model", "_____no_output_____" ], [ "### 7.3 Example: Selection of the degree of the polynomia\n\nFor the previous example we had (we consider a spherical Gaussian for the weights):\n\n - ${\\bf s}~|~{\\bf w},{\\cal M}~\\sim~{\\cal N}\\left({\\bf Z}{\\bf w},~\\sigma_\\varepsilon^2 {\\bf I} \\right)$\n \n - ${\\bf w}~|~{\\cal M}~\\sim~{\\cal N}\\left({\\bf 0},~\\sigma_p^2 {\\bf I} \\right)$\n \nIn this case, $p({\\bf s}~|~{\\cal M})$ follows also a Gaussian distribution, and it can be shown that\n\n - $L = p({\\bf s}~|~{\\cal M}) = {\\cal N}\\left({\\bf 0},\\sigma_p^2 {\\bf Z} {\\bf Z}^\\top+\\sigma_\\varepsilon^2 {\\bf I} \\right)$\n \nIf we just pursue the maximization of $L$, this is equivalent to maximizing the log of the evidence\n\n$$\\log(L) = -\\frac{M}{2} \\log(2\\pi) -{\\frac{1}{2}}\\log\\mid\\sigma_p^2 {\\bf Z} {\\bf Z}^\\top+\\sigma_\\varepsilon^2 {\\bf I}\\mid - \\frac{1}{2} {\\bf s}^\\top \\left(\\sigma_p^2 {\\bf Z} {\\bf Z}^\\top+\\sigma_\\varepsilon^2 {\\bf I}\\right)^{-1} {\\bf s}$$\n\nwhere $M$ denotes the length of vector ${\\bf z}$ (the degree of the polynomia minus 1).\n \nThe following fragment of code evaluates the evidence of the model as a function of the degree of the polynomia", "_____no_output_____" ] ], [ [ "from math import pi\n\nn_points = 15\nfrec = 3\nstd_n = 0.2\nmax_degree = 12\n\n#Prior distribution parameters\nsigma_eps = 0.2\nmean_w = np.zeros((degree+1,))\nsigma_p = 0.5\n\nX_tr = 3 * np.random.random((n_points,1)) - 0.5\nS_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1)\n\n#Compute matrix with training input data for the polynomial model\nZ = []\nfor x_val in X_tr.tolist():\n Z.append([x_val[0]**k for k in range(degree+1)])\nZ=np.asmatrix(Z)\n\n#Evaluate the posterior evidence\n\nlogE = []\nfor deg in range(max_degree):\n Z_iter = Z[:,:deg+1]\n logE_iter = -((deg+1)*np.log(2*pi)/2) \\\n -np.log(np.linalg.det((sigma_p**2)*Z_iter.dot(Z_iter.T) + (sigma_eps**2)*np.eye(n_points)))/2 \\\n -S_tr.T.dot(np.linalg.inv((sigma_p**2)*Z_iter.dot(Z_iter.T) + (sigma_eps**2)*np.eye(n_points))).dot(S_tr)/2\n logE.append(logE_iter[0,0])\n\nplt.plot(np.array(range(max_degree))+1,logE)\nplt.xlabel('Polynomia degree')\nplt.ylabel('log evidence')\nplt.show()\n", "_____no_output_____" ] ], [ [ "The above curve may change the position of its maximum from run to run.\n\nWe conclude the notebook by plotting the result of the Bayesian inference for $M=6$", "_____no_output_____" ] ], [ [ "n_points = 15\nn_grid = 200\nfrec = 3\nstd_n = 0.2\ndegree = 5 #M-1\nnplots = 6\n\n#Prior distribution parameters\nsigma_eps = 0.1\nmean_w = np.zeros((degree+1,))\nsigma_p = .5 * np.eye(degree+1)\n\nX_tr = 3 * np.random.random((n_points,1)) - 0.5\nS_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1)\nX_grid = np.linspace(-1,3,n_grid)\nS_grid = - np.cos(frec*X_grid) #Noise free for the true model\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(X_tr,S_tr,'b.',markersize=10)\n\n#Compute matrix with training input data for the polynomial model\nZ = []\nfor x_val in X_tr.tolist():\n Z.append([x_val[0]**k for k in range(degree+1)])\nZ=np.asmatrix(Z)\n\n#Compute posterior distribution parameters\nSigma_w = np.linalg.inv(np.dot(Z.T,Z)/(sigma_eps**2) + np.linalg.inv(sigma_p))\nposterior_mean = Sigma_w.dot(Z.T).dot(S_tr)/(sigma_eps**2)\nposterior_mean = np.array(posterior_mean).flatten()\n\n#Plot the posterior mean\n#Note that polyval assumes the first element of weight vector is the coefficient of\n#the highest degree term. Thus, we need to reverse w_iter\nS_grid_iter = np.polyval(posterior_mean[::-1],X_grid)\nax.plot(X_grid,S_grid_iter,'g-',label='Predictive mean, BI')\n\n#Plot confidence intervals for the Bayesian Inference\nstd_x = []\nfor el in X_grid:\n x_ast = np.array([el**k for k in range(degree+1)])\n std_x.append(np.sqrt(x_ast.dot(Sigma_w).dot(x_ast)[0,0]))\nstd_x = np.array(std_x)\nplt.fill_between(X_grid, S_grid_iter-std_x, S_grid_iter+std_x,\n alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',\n linewidth=4, linestyle='dashdot', antialiased=True)\n\n#We plot also the least square solution\nw_LS = np.polyfit(X_tr.flatten(), S_tr.flatten(), degree)\nS_grid_iter = np.polyval(w_LS,X_grid)\nax.plot(X_grid,S_grid_iter,'m-',label='LS regression')\n \nax.set_xlim(-1,3)\nax.set_ylim(S_tr[0]-2,S_tr[-1]+2)\nax.legend(loc='best')\nplt.show()", "_____no_output_____" ] ], [ [ "We can check, that now the model also seems quite appropriate for LS regression, but keep in mind that selection of such parameter was itself carried out using Bayesian inference.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01e73ff3c22b0145af3b1e9a789f5d248ed8c82
424,178
ipynb
Jupyter Notebook
study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/3) Resnet V2 Block (Type - 1).ipynb
arijitgupta42/monk_v1
bc7c57ad342f96fc779ac8db530d6ee614d093c0
[ "Apache-2.0" ]
7
2020-07-26T08:37:29.000Z
2020-10-30T10:23:11.000Z
study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/3) Resnet V2 Block (Type - 1).ipynb
arijitgupta42/monk_v1
bc7c57ad342f96fc779ac8db530d6ee614d093c0
[ "Apache-2.0" ]
null
null
null
study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/3) Resnet V2 Block (Type - 1).ipynb
arijitgupta42/monk_v1
bc7c57ad342f96fc779ac8db530d6ee614d093c0
[ "Apache-2.0" ]
null
null
null
284.492287
91,264
0.925986
[ [ [ "# Goals\n\n### 1. Learn to implement Resnet V2 Block (Type - 1) using monk\n - Monk's Keras\n - Monk's Pytorch\n - Monk's Mxnet\n \n### 2. Use network Monk's debugger to create complex blocks \n\n\n### 3. Understand how syntactically different it is to implement the same using\n - Traditional Keras\n - Traditional Pytorch\n - Traditional Mxnet", "_____no_output_____" ], [ "# Resnet V2 Block - Type 1\n \n - Note: The block structure can have variations too, this is just an example", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/resnet_v2_with_downsample.png')", "_____no_output_____" ] ], [ [ "# Table of contents\n\n[1. Install Monk](#1)\n\n\n[2. Block basic Information](#2)\n\n - [2.1) Visual structure](#2-1)\n \n - [2.2) Layers in Branches](#2-2)\n\n\n[3) Creating Block using monk visual debugger](#3)\n\n - [3.1) Create the first branch](#3-1)\n\n - [3.2) Create the second branch](#3-2)\n \n - [3.3) Merge the branches](#3-3)\n \n - [3.4) Debug the merged network](#3-4)\n \n - [3.5) Compile the network](#3-5)\n \n - [3.6) Visualize the network](#3-6)\n \n - [3.7) Run data through the network](#3-7)\n \n \n[4) Creating Block Using MONK one line API call](#4)\n\n - [Mxnet Backend](#4-1)\n \n - [Pytorch Backend](#4-2)\n \n - [Keras Backend](#4-3)\n \n \n \n[5) Appendix](#5)\n\n - [Study Material](#5-1)\n \n - [Creating block using traditional Mxnet](#5-2)\n \n - [Creating block using traditional Pytorch](#5-3)\n \n - [Creating block using traditional Keras](#5-4)\n ", "_____no_output_____" ], [ "<a id='1'></a>\n# Install Monk\n \n - git clone https://github.com/Tessellate-Imaging/monk_v1.git\n \n - cd monk_v1/installation/Linux && pip install -r requirements_cu9.txt\n - (Select the requirements file as per OS and CUDA version)", "_____no_output_____" ] ], [ [ "!git clone https://github.com/Tessellate-Imaging/monk_v1.git", "_____no_output_____" ] ], [ [ "# Imports", "_____no_output_____" ] ], [ [ "# Common\nimport numpy as np\nimport math\nimport netron\nfrom collections import OrderedDict\nfrom functools import partial", "_____no_output_____" ], [ "# Monk\nimport os\nimport sys\nsys.path.append(\"monk_v1/monk/\");", "_____no_output_____" ] ], [ [ "<a id='2'></a>\n# Block Information", "_____no_output_____" ], [ "<a id='2_1'></a>\n## Visual structure", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/resnet_v2_with_downsample.png')", "_____no_output_____" ] ], [ [ "<a id='2_2'></a>\n## Layers in Branches\n\n - Number of branches: 2\n \n \n - Common element\n - batchnorm -> relu\n \n \n \n - Branch 1\n - conv_1x1\n \n \n - Branch 2\n - conv_3x3 -> batchnorm -> relu -> conv_3x3\n \n \n - Branches merged using\n - Elementwise addition\n \n \n(See Appendix to read blogs on resnets)", "_____no_output_____" ], [ "<a id='3'></a>\n# Creating Block using monk debugger", "_____no_output_____" ] ], [ [ "# Imports and setup a project\n# To use pytorch backend - replace gluon_prototype with pytorch_prototype\n# To use keras backend - replace gluon_prototype with keras_prototype\n\nfrom gluon_prototype import prototype\n\n# Create a sample project\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");", "Mxnet Version: 1.5.1\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\n" ] ], [ [ "<a id='3-1'></a>\n## Create the first branch", "_____no_output_____" ] ], [ [ "def first_branch(output_channels=128, stride=1):\n network = [];\n network.append(gtf.convolution(output_channels=output_channels, kernel_size=1, stride=stride));\n return network;", "_____no_output_____" ], [ "# Debug the branch\nbranch_1 = first_branch(output_channels=128, stride=1)\nnetwork = [];\nnetwork.append(branch_1);\ngtf.debug_custom_model_design(network);", "_____no_output_____" ] ], [ [ "<a id='3-2'></a>\n## Create the second branch", "_____no_output_____" ] ], [ [ "def second_branch(output_channels=128, stride=1):\n network = [];\n network.append(gtf.convolution(output_channels=output_channels, kernel_size=3, stride=stride));\n network.append(gtf.batch_normalization());\n network.append(gtf.relu());\n network.append(gtf.convolution(output_channels=output_channels, kernel_size=3, stride=1));\n return network;", "_____no_output_____" ], [ "# Debug the branch\nbranch_2 = second_branch(output_channels=128, stride=1)\nnetwork = [];\nnetwork.append(branch_2);\ngtf.debug_custom_model_design(network);", "_____no_output_____" ] ], [ [ "<a id='3-3'></a>\n## Merge the branches", "_____no_output_____" ] ], [ [ "\ndef final_block(output_channels=128, stride=1):\n network = [];\n \n # Common elements\n network.append(gtf.batch_normalization());\n network.append(gtf.relu());\n \n #Create subnetwork and add branches\n subnetwork = [];\n branch_1 = first_branch(output_channels=output_channels, stride=stride)\n branch_2 = second_branch(output_channels=output_channels, stride=stride)\n subnetwork.append(branch_1);\n subnetwork.append(branch_2);\n \n # Add merging element\n subnetwork.append(gtf.add());\n \n # Add the subnetwork\n network.append(subnetwork);\n return network;", "_____no_output_____" ] ], [ [ "<a id='3-4'></a>\n## Debug the merged network", "_____no_output_____" ] ], [ [ "final = final_block(output_channels=128, stride=1)\nnetwork = [];\nnetwork.append(final);\ngtf.debug_custom_model_design(network);", "_____no_output_____" ] ], [ [ "<a id='3-5'></a>\n## Compile the network", "_____no_output_____" ] ], [ [ "gtf.Compile_Network(network, data_shape=(3, 224, 224), use_gpu=False);", "Model Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num of potentially trainable layers: 5\n Num of actual trainable layers: 5\n\n" ] ], [ [ "<a id='3-6'></a>\n## Run data through the network", "_____no_output_____" ] ], [ [ "import mxnet as mx\nx = np.zeros((1, 3, 224, 224));\nx = mx.nd.array(x);\ny = gtf.system_dict[\"local\"][\"model\"].forward(x);\nprint(x.shape, y.shape)", "(1, 3, 224, 224) (1, 128, 224, 224)\n" ] ], [ [ "<a id='3-7'></a>\n## Visualize network using netron", "_____no_output_____" ] ], [ [ "gtf.Visualize_With_Netron(data_shape=(3, 224, 224))", "Using Netron To Visualize\nNot compatible on kaggle\nCompatible only for Jupyter Notebooks\n\nStopping http://localhost:8080\nServing 'model-symbol.json' at http://localhost:8080\n" ] ], [ [ "<a id='4'></a>\n# Creating Using MONK LOW code API", "_____no_output_____" ], [ "<a id='4-1'></a>\n## Mxnet backend", "_____no_output_____" ] ], [ [ "from gluon_prototype import prototype\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");\n\n\nnetwork = [];\n\n# Single line addition of blocks\nnetwork.append(gtf.resnet_v2_block(output_channels=128));\n\n\ngtf.Compile_Network(network, data_shape=(3, 224, 224), use_gpu=False);\n", "Mxnet Version: 1.5.1\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num of potentially trainable layers: 5\n Num of actual trainable layers: 5\n\n" ] ], [ [ "<a id='4-2'></a>\n## Pytorch backend\n\n - Only the import changes", "_____no_output_____" ] ], [ [ "#Change gluon_prototype to pytorch_prototype\nfrom pytorch_prototype import prototype\n\n\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");\n\n\nnetwork = [];\n\n# Single line addition of blocks\nnetwork.append(gtf.resnet_v2_block(output_channels=128));\n\n\ngtf.Compile_Network(network, data_shape=(3, 224, 224), use_gpu=False);", "Pytorch Version: 1.2.0\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num layers in model: 5\n Num trainable layers: 5\n\n" ] ], [ [ "<a id='4-3'></a>\n## Keras backend\n\n - Only the import changes", "_____no_output_____" ] ], [ [ "#Change gluon_prototype to keras_prototype\nfrom keras_prototype import prototype\n\n\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");\n\n\nnetwork = [];\n\n# Single line addition of blocks\nnetwork.append(gtf.resnet_v1_block(output_channels=128));\n\n\ngtf.Compile_Network(network, data_shape=(3, 224, 224), use_gpu=False);", "Keras Version: 2.2.5\nTensorflow Version: 1.12.0\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num layers in model: 10\n Num trainable layers: 9\n\n" ] ], [ [ "<a id='5'></a>\n# Appendix", "_____no_output_____" ], [ "<a id='5-1'></a>\n## Study links\n - https://towardsdatascience.com/residual-blocks-building-blocks-of-resnet-fd90ca15d6ec\n - https://medium.com/@MaheshNKhatri/resnet-block-explanation-with-a-terminology-deep-dive-989e15e3d691\n - https://medium.com/analytics-vidhya/understanding-and-implementation-of-residual-networks-resnets-b80f9a507b9c\n - https://hackernoon.com/resnet-block-level-design-with-deep-learning-studio-part-1-727c6f4927ac", "_____no_output_____" ], [ "<a id='5-2'></a>\n## Creating block using traditional Mxnet\n\n - Code credits - https://mxnet.incubator.apache.org/", "_____no_output_____" ] ], [ [ "# Traditional-Mxnet-gluon\nimport mxnet as mx\nfrom mxnet.gluon import nn\nfrom mxnet.gluon.nn import HybridBlock, BatchNorm\nfrom mxnet.gluon.contrib.nn import HybridConcurrent, Identity\nfrom mxnet import gluon, init, nd", "_____no_output_____" ], [ "\ndef _conv3x3(channels, stride, in_channels):\n return nn.Conv2D(channels, kernel_size=3, strides=stride, padding=1,\n use_bias=False, in_channels=in_channels)\n\nclass ResnetBlockV2(HybridBlock):\n def __init__(self, channels, stride, in_channels=0,\n last_gamma=False, \n norm_layer=BatchNorm, norm_kwargs=None, **kwargs):\n super(ResnetBlockV2, self).__init__(**kwargs)\n \n #Branch - 1\n self.downsample = nn.Conv2D(channels, 1, stride, use_bias=False,\n in_channels=in_channels)\n \n \n # Branch - 2\n self.bn1 = norm_layer(**({} if norm_kwargs is None else norm_kwargs))\n self.conv1 = _conv3x3(channels, stride, in_channels)\n if not last_gamma:\n self.bn2 = norm_layer(**({} if norm_kwargs is None else norm_kwargs))\n else:\n self.bn2 = norm_layer(gamma_initializer='zeros',\n **({} if norm_kwargs is None else norm_kwargs))\n self.conv2 = _conv3x3(channels, 1, channels)\n\n\n \n\n\n def hybrid_forward(self, F, x):\n residual = x\n x = self.bn1(x)\n x = F.Activation(x, act_type='relu')\n \n residual = self.downsample(x)\n \n x = self.conv1(x)\n x = self.bn2(x)\n x = F.Activation(x, act_type='relu')\n x = self.conv2(x)\n\n return x + residual", "_____no_output_____" ], [ "# Invoke the block\nblock = ResnetBlockV2(64, 1)\n\n# Initialize network and load block on machine\nctx = [mx.cpu()];\nblock.initialize(init.Xavier(), ctx = ctx);\nblock.collect_params().reset_ctx(ctx)\nblock.hybridize()\n\n# Run data through network\nx = np.zeros((1, 3, 224, 224));\nx = mx.nd.array(x);\ny = block.forward(x);\nprint(x.shape, y.shape)\n\n\n# Export Model to Load on Netron\nblock.export(\"final\", epoch=0);\n\nnetron.start(\"final-symbol.json\", port=8082)", "_____no_output_____" ] ], [ [ "<a id='5-3'></a>\n## Creating block using traditional Pytorch\n\n - Code credits - https://pytorch.org/", "_____no_output_____" ] ], [ [ "# Traiditional-Pytorch\nimport torch\nfrom torch import nn\nfrom torch.jit.annotations import List\nimport torch.nn.functional as F", "_____no_output_____" ], [ "def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass ResnetBlock(nn.Module):\n expansion = 1\n __constants__ = ['downsample']\n\n def __init__(self, inplanes, planes, stride=1, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(ResnetBlock, self).__init__()\n \n norm_layer = nn.BatchNorm2d\n \n # Common Element\n self.bn0 = norm_layer(inplanes)\n self.relu0 = nn.ReLU(inplace=True)\n \n \n # Branch - 1\n self.downsample = conv1x1(inplanes, planes, stride)\n \n \n # Branch - 2\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n \n self.stride = stride\n\n \n def forward(self, x):\n x = self.bn0(x);\n x = self.relu0(x);\n \n identity = self.downsample(x)\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n\n\n out += identity\n out = self.relu(out)\n\n return out", "_____no_output_____" ], [ "# Invoke the block\nblock = ResnetBlock(3, 64, stride=1);\n\n# Initialize network and load block on machine\nlayers = []\nlayers.append(block);\nnet = nn.Sequential(*layers);\n\n# Run data through network\nx = torch.randn(1, 3, 224, 224)\ny = net(x)\nprint(x.shape, y.shape);\n\n# Export Model to Load on Netron\ntorch.onnx.export(net, # model being run\n x, # model input (or a tuple for multiple inputs)\n \"model.onnx\", # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=10, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['output'], # the model's output names\n dynamic_axes={'input' : {0 : 'batch_size'}, # variable lenght axes\n 'output' : {0 : 'batch_size'}})\nnetron.start('model.onnx', port=9998);", "torch.Size([1, 3, 224, 224]) torch.Size([1, 64, 224, 224])\nServing 'model.onnx' at http://localhost:9998\n" ] ], [ [ "<a id='5-4'></a>\n## Creating block using traditional Keras\n\n - Code credits: https://keras.io/", "_____no_output_____" ] ], [ [ "# Traditional-Keras\nimport keras\nimport keras.layers as kla\nimport keras.models as kmo\nimport tensorflow as tf\nfrom keras.models import Model\nbackend = 'channels_last'\nfrom keras import layers", "Using TensorFlow backend.\n/home/abhi/.virtualenvs/finetune_py36/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:523: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n/home/abhi/.virtualenvs/finetune_py36/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:524: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n/home/abhi/.virtualenvs/finetune_py36/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n/home/abhi/.virtualenvs/finetune_py36/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n/home/abhi/.virtualenvs/finetune_py36/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n/home/abhi/.virtualenvs/finetune_py36/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:532: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" ], [ "def resnet_conv_block(input_tensor,\n kernel_size,\n filters,\n stage,\n block,\n strides=(2, 2)):\n\n filters1, filters2, filters3 = filters\n bn_axis = 3\n \n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n \n # Common Element\n start = layers.BatchNormalization(axis=bn_axis, name=bn_name_base + '0a')(input_tensor)\n start = layers.Activation('relu')(start)\n \n\n #Branch - 1\n shortcut = layers.Conv2D(filters3, (1, 1), strides=strides,\n kernel_initializer='he_normal',\n name=conv_name_base + '1')(start)\n \n \n #Branch - 2\n x = layers.Conv2D(filters1, (1, 1), strides=strides,\n kernel_initializer='he_normal',\n name=conv_name_base + '2a')(start)\n x = layers.BatchNormalization(axis=bn_axis, name=bn_name_base + '2a')(x)\n x = layers.Activation('relu')(x)\n\n x = layers.Conv2D(filters2, kernel_size, padding='same',\n kernel_initializer='he_normal',\n name=conv_name_base + '2b')(x)\n\n \n x = layers.add([x, shortcut])\n x = layers.Activation('relu')(x)\n return x\n\n\ndef create_model(input_shape, kernel_size, filters, stage, block):\n img_input = layers.Input(shape=input_shape);\n x = resnet_conv_block(img_input, kernel_size, filters, stage, block) \n return Model(img_input, x);", "_____no_output_____" ], [ "# Invoke the block\nkernel_size=3;\nfilters=[64, 64, 64];\ninput_shape=(224, 224, 3);\nmodel = create_model(input_shape, kernel_size, filters, 0, \"0\");\n\n# Run data through network\nx = tf.placeholder(tf.float32, shape=(1, 224, 224, 3))\ny = model(x)\nprint(x.shape, y.shape)\n\n# Export Model to Load on Netron\nmodel.save(\"final.h5\");\nnetron.start(\"final.h5\", port=8082)", "(1, 224, 224, 3) (1, 112, 112, 64)\n\nStopping http://localhost:8082\nServing 'final.h5' at http://localhost:8082\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", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "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", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d01e7aa39a28d592a321f4077c48786e3ccf3e7f
46,430
ipynb
Jupyter Notebook
Tutorial-GRHD_Equations-Cartesian.ipynb
rhaas80/nrpytutorial
4398cd6b5a071c8fb8b2b584a01f07a4591dd5f4
[ "BSD-2-Clause" ]
null
null
null
Tutorial-GRHD_Equations-Cartesian.ipynb
rhaas80/nrpytutorial
4398cd6b5a071c8fb8b2b584a01f07a4591dd5f4
[ "BSD-2-Clause" ]
null
null
null
Tutorial-GRHD_Equations-Cartesian.ipynb
rhaas80/nrpytutorial
4398cd6b5a071c8fb8b2b584a01f07a4591dd5f4
[ "BSD-2-Clause" ]
null
null
null
44.388145
425
0.56457
[ [ [ "<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# Equations of General Relativistic Hydrodynamics (GRHD)\n\n## Authors: Zach Etienne & Patrick Nelson\n\n## This notebook documents and constructs a number of quantities useful for building symbolic (SymPy) expressions for the equations of general relativistic hydrodynamics (GRHD), using the same (Valencia) formalism as `IllinoisGRMHD`\n\n**Notebook Status:** <font color='orange'><b> Self-Validated </b></font>\n\n**Validation Notes:** This tutorial notebook has been confirmed to be self-consistent with its corresponding NRPy+ module, as documented [below](#code_validation). **Additional validation tests may have been performed, but are as yet, undocumented. (TODO)**\n\n## Introduction\n\nWe write the equations of general relativistic hydrodynamics in conservative form as follows (adapted from Eqs. 41-44 of [Duez et al](https://arxiv.org/pdf/astro-ph/0503420.pdf):\n\n\\begin{eqnarray}\n\\ \\partial_t \\rho_* &+& \\partial_j \\left(\\rho_* v^j\\right) = 0 \\\\\n\\partial_t \\tilde{\\tau} &+& \\partial_j \\left(\\alpha^2 \\sqrt{\\gamma} T^{0j} - \\rho_* v^j \\right) = s \\\\\n\\partial_t \\tilde{S}_i &+& \\partial_j \\left(\\alpha \\sqrt{\\gamma} T^j{}_i \\right) = \\frac{1}{2} \\alpha\\sqrt{\\gamma} T^{\\mu\\nu} g_{\\mu\\nu,i},\n\\end{eqnarray}\nwhere we assume $T^{\\mu\\nu}$ is the stress-energy tensor of a perfect fluid:\n$$\nT^{\\mu\\nu} = \\rho_0 h u^{\\mu} u^{\\nu} + P g^{\\mu\\nu},\n$$\nthe $s$ source term is given in terms of ADM quantities via\n\n$$\ns = \\alpha \\sqrt{\\gamma}\\left[\\left(T^{00}\\beta^i\\beta^j + 2 T^{0i}\\beta^j + T^{ij} \\right)K_{ij}\n- \\left(T^{00}\\beta^i + T^{0i} \\right)\\partial_i\\alpha \\right],\n$$\n\nand \n\\begin{align}\nv^j &= \\frac{u^j}{u^0} \\\\\n\\rho_* &= \\alpha\\sqrt{\\gamma} \\rho_0 u^0 \\\\\nh &= 1 + \\epsilon + \\frac{P}{\\rho_0}.\n\\end{align}\n\nAlso we will write the 4-metric in terms of the ADM 3-metric, lapse, and shift using standard equations.\n\nThus the full set of input variables include:\n* Spacetime quantities:\n * ADM quantities $\\alpha$, $\\beta^i$, $\\gamma_{ij}$, $K_{ij}$\n* Hydrodynamical quantities:\n * Rest-mass density $\\rho_0$\n * Pressure $P$\n * Internal energy $\\epsilon$\n * 4-velocity $u^\\mu$\n\nFor completeness, the rest of the conservative variables are given by\n\\begin{align}\n\\tilde{\\tau} &= \\alpha^2\\sqrt{\\gamma} T^{00} - \\rho_* \\\\\n\\tilde{S}_i &= \\alpha \\sqrt{\\gamma} T^0{}_i\n\\end{align}\n\n### A Note on Notation\n\nAs is standard in NRPy+, \n\n* Greek indices refer to four-dimensional quantities where the zeroth component indicates temporal (time) component.\n* Latin indices refer to three-dimensional quantities. This is somewhat counterintuitive since Python always indexes its lists starting from 0. As a result, the zeroth component of three-dimensional quantities will necessarily indicate the first *spatial* direction.\n\nFor instance, in calculating the first term of $b^2 u^\\mu u^\\nu$, we use Greek indices:\n\n```python\nT4EMUU = ixp.zerorank2(DIM=4)\nfor mu in range(4):\n for nu in range(4):\n # Term 1: b^2 u^{\\mu} u^{\\nu}\n T4EMUU[mu][nu] = smallb2*u4U[mu]*u4U[nu]\n```\n\nWhen we calculate $\\beta_i = \\gamma_{ij} \\beta^j$, we use Latin indices:\n```python\nbetaD = ixp.zerorank1(DIM=3)\nfor i in range(3):\n for j in range(3):\n betaD[i] += gammaDD[i][j] * betaU[j]\n```\n\nAs a corollary, any expressions involving mixed Greek and Latin indices will need to offset one set of indices by one: A Latin index in a four-vector will be incremented and a Greek index in a three-vector will be decremented (however, the latter case does not occur in this tutorial notebook). This can be seen when we handle $\\frac{1}{2} \\alpha \\sqrt{\\gamma} T^{\\mu \\nu}_{\\rm EM} \\partial_i g_{\\mu \\nu}$:\n```python\n# \\alpha \\sqrt{\\gamma} T^{\\mu \\nu}_{\\rm EM} \\partial_i g_{\\mu \\nu} / 2\nfor i in range(3):\n for mu in range(4):\n for nu in range(4):\n S_tilde_rhsD[i] += alpsqrtgam * T4EMUU[mu][nu] * g4DD_zerotimederiv_dD[mu][nu][i+1] / 2\n```", "_____no_output_____" ], [ "<a id='toc'></a>\n\n# Table of Contents\n$$\\label{toc}$$\n\nEach family of quantities is constructed within a given function (**boldfaced** below). This notebook is organized as follows\n\n\n1. [Step 1](#importmodules): Import needed NRPy+ & Python modules\n1. [Step 2](#stressenergy): Define the stress-energy tensor $T^{\\mu\\nu}$ and $T^\\mu{}_\\nu$:\n * **compute_enthalpy()**, **compute_T4UU()**, **compute_T4UD()**: \n1. [Step 3](#primtoconserv): Writing the conservative variables in terms of the primitive variables:\n * **compute_sqrtgammaDET()**, **compute_rho_star()**, **compute_tau_tilde()**, **compute_S_tildeD()**\n1. [Step 4](#grhdfluxes): Define the fluxes for the GRHD equations\n 1. [Step 4.a](#rhostarfluxterm): Define $\\rho_*$ flux term for GRHD equations:\n * **compute_vU_from_u4U__no_speed_limit()**, **compute_rho_star_fluxU()**:\n 1. [Step 4.b](#taustildesourceterms) Define $\\tilde{\\tau}$ and $\\tilde{S}_i$ flux terms for GRHD equations:\n * **compute_tau_tilde_fluxU()**, **compute_S_tilde_fluxUD()**\n1. [Step 5](#grhdsourceterms): Define source terms on RHSs of GRHD equations\n 1. [Step 5.a](#ssourceterm): Define $s$ source term on RHS of $\\tilde{\\tau}$ equation:\n * **compute_s_source_term()**\n 1. [Step 5.b](#stildeisourceterm): Define source term on RHS of $\\tilde{S}_i$ equation\n 1. [Step 5.b.i](#fourmetricderivs): Compute $g_{\\mu\\nu,i}$ in terms of ADM quantities and their derivatives:\n * **compute_g4DD_zerotimederiv_dD()**\n 1. [Step 5.b.ii](#stildeisource): Compute source term of the $\\tilde{S}_i$ equation: $\\frac{1}{2} \\alpha\\sqrt{\\gamma} T^{\\mu\\nu} g_{\\mu\\nu,i}$:\n * **compute_S_tilde_source_termD()**\n1. [Step 6](#convertvtou): Conversion of $v^i$ to $u^\\mu$ (Courtesy Patrick Nelson):\n * **u4U_in_terms_of_ValenciavU__rescale_ValenciavU_by_applying_speed_limit()**, **u4U_in_terms_of_vU__rescale_vU_by_applying_speed_limit()**\n1. [Step 7](#declarevarsconstructgrhdeqs): Declare ADM and hydrodynamical input variables, and construct GRHD equations\n1. [Step 8](#code_validation): Code Validation against `GRHD.equations` NRPy+ module\n1. [Step 9](#latex_pdf_output): Output this notebook to $\\LaTeX$-formatted PDF file", "_____no_output_____" ], [ "<a id='importmodules'></a>\n\n# Step 1: Import needed NRPy+ & Python modules \\[Back to [top](#toc)\\]\n$$\\label{importmodules}$$", "_____no_output_____" ] ], [ [ "# Step 1: Import needed core NRPy+ modules\nfrom outputC import nrpyAbs # NRPy+: Core C code output module\nimport NRPy_param_funcs as par # NRPy+: parameter interface\nimport sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends\nimport indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support", "_____no_output_____" ] ], [ [ "<a id='stressenergy'></a>\n\n# Step 2: Define the stress-energy tensor $T^{\\mu\\nu}$ and $T^\\mu{}_\\nu$ \\[Back to [top](#toc)\\]\n$$\\label{stressenergy}$$\n\nRecall from above that\n\n$$\nT^{\\mu\\nu} = \\rho_0 h u^{\\mu} u^{\\nu} + P g^{\\mu\\nu},\n$$\nwhere $h = 1 + \\epsilon + \\frac{P}{\\rho_0}$. Also \n\n$$\nT^\\mu{}_{\\nu} = T^{\\mu\\delta} g_{\\delta \\nu}\n$$", "_____no_output_____" ] ], [ [ "# Step 2.a: First define h, the enthalpy:\ndef compute_enthalpy(rho_b,P,epsilon):\n global h\n h = 1 + epsilon + P/rho_b\n\n# Step 2.b: Define T^{mu nu} (a 4-dimensional tensor)\ndef compute_T4UU(gammaDD,betaU,alpha, rho_b,P,epsilon,u4U):\n global T4UU\n\n compute_enthalpy(rho_b,P,epsilon)\n # Then define g^{mu nu} in terms of the ADM quantities:\n import BSSN.ADMBSSN_tofrom_4metric as AB4m\n AB4m.g4UU_ito_BSSN_or_ADM(\"ADM\",gammaDD,betaU,alpha)\n\n # Finally compute T^{mu nu}\n T4UU = ixp.zerorank2(DIM=4)\n for mu in range(4):\n for nu in range(4):\n T4UU[mu][nu] = rho_b * h * u4U[mu]*u4U[nu] + P*AB4m.g4UU[mu][nu]\n\n# Step 2.c: Define T^{mu}_{nu} (a 4-dimensional tensor)\ndef compute_T4UD(gammaDD,betaU,alpha, T4UU):\n global T4UD\n # Next compute T^mu_nu = T^{mu delta} g_{delta nu}, needed for S_tilde flux.\n # First we'll need g_{alpha nu} in terms of ADM quantities:\n import BSSN.ADMBSSN_tofrom_4metric as AB4m\n AB4m.g4DD_ito_BSSN_or_ADM(\"ADM\",gammaDD,betaU,alpha)\n T4UD = ixp.zerorank2(DIM=4)\n for mu in range(4):\n for nu in range(4):\n for delta in range(4):\n T4UD[mu][nu] += T4UU[mu][delta]*AB4m.g4DD[delta][nu]", "_____no_output_____" ] ], [ [ "<a id='primtoconserv'></a>\n\n# Step 3: Writing the conservative variables in terms of the primitive variables \\[Back to [top](#toc)\\]\n$$\\label{primtoconserv}$$\n\nRecall from above that the conservative variables may be written as\n\\begin{align}\n\\rho_* &= \\alpha\\sqrt{\\gamma} \\rho_0 u^0 \\\\\n\\tilde{\\tau} &= \\alpha^2\\sqrt{\\gamma} T^{00} - \\rho_* \\\\\n\\tilde{S}_i &= \\alpha \\sqrt{\\gamma} T^0{}_i\n\\end{align}\n\n$T^{\\mu\\nu}$ and $T^\\mu{}_\\nu$ have already been defined $-$ all in terms of primitive variables. Thus we'll just need $\\sqrt{\\gamma}=$`gammaDET`, and all conservatives can then be written in terms of other defined quantities, which themselves are written in terms of primitive variables and the ADM metric.", "_____no_output_____" ] ], [ [ "# Step 3: Writing the conservative variables in terms of the primitive variables\ndef compute_sqrtgammaDET(gammaDD):\n global sqrtgammaDET\n gammaUU, gammaDET = ixp.symm_matrix_inverter3x3(gammaDD)\n sqrtgammaDET = sp.sqrt(gammaDET)\n\ndef compute_rho_star(alpha, sqrtgammaDET, rho_b,u4U):\n global rho_star\n # Compute rho_star:\n rho_star = alpha*sqrtgammaDET*rho_b*u4U[0]\n\ndef compute_tau_tilde(alpha, sqrtgammaDET, T4UU,rho_star):\n global tau_tilde\n tau_tilde = alpha**2*sqrtgammaDET*T4UU[0][0] - rho_star\n\ndef compute_S_tildeD(alpha, sqrtgammaDET, T4UD):\n global S_tildeD\n S_tildeD = ixp.zerorank1(DIM=3)\n for i in range(3):\n S_tildeD[i] = alpha*sqrtgammaDET*T4UD[0][i+1]", "_____no_output_____" ] ], [ [ "<a id='grhdfluxes'></a>\n\n# Step 4: Define the fluxes for the GRHD equations \\[Back to [top](#toc)\\]\n$$\\label{grhdfluxes}$$\n\n<a id='rhostarfluxterm'></a>\n\n## Step 4.a: Define $\\rho_*$ flux term for GRHD equations \\[Back to [top](#toc)\\]\n$$\\label{rhostarfluxterm}$$\n\nRecall from above that\n\\begin{array}\n\\ \\partial_t \\rho_* &+ \\partial_j \\left(\\rho_* v^j\\right) = 0.\n\\end{array}\n\nHere we will define the $\\rho_* v^j$ that constitutes the flux of $\\rho_*$, first defining $v^j=u^j/u^0$:", "_____no_output_____" ] ], [ [ "# Step 4: Define the fluxes for the GRHD equations\n# Step 4.a: vU from u4U may be needed for computing rho_star_flux from u4U\ndef compute_vU_from_u4U__no_speed_limit(u4U):\n global vU\n # Now compute v^i = u^i/u^0:\n vU = ixp.zerorank1(DIM=3)\n for j in range(3):\n vU[j] = u4U[j+1]/u4U[0]\n\n# Step 4.b: rho_star flux\ndef compute_rho_star_fluxU(vU, rho_star):\n global rho_star_fluxU\n rho_star_fluxU = ixp.zerorank1(DIM=3)\n for j in range(3):\n rho_star_fluxU[j] = rho_star*vU[j]", "_____no_output_____" ] ], [ [ "<a id='taustildesourceterms'></a>\n\n## Step 4.b: Define $\\tilde{\\tau}$ and $\\tilde{S}_i$ flux terms for GRHD equations \\[Back to [top](#toc)\\]\n$$\\label{taustildesourceterms}$$\n\nRecall from above that\n\\begin{array}\n\\ \\partial_t \\tilde{\\tau} &+ \\partial_j \\underbrace{\\left(\\alpha^2 \\sqrt{\\gamma} T^{0j} - \\rho_* v^j \\right)} &= s \\\\\n\\partial_t \\tilde{S}_i &+ \\partial_j \\underbrace{\\left(\\alpha \\sqrt{\\gamma} T^j{}_i \\right)} &= \\frac{1}{2} \\alpha\\sqrt{\\gamma} T^{\\mu\\nu} g_{\\mu\\nu,i}.\n\\end{array}\n\nHere we will define all terms that go inside the $\\partial_j$'s on the left-hand side of the above equations (i.e., the underbraced expressions):", "_____no_output_____" ] ], [ [ "# Step 4.c: tau_tilde flux\ndef compute_tau_tilde_fluxU(alpha, sqrtgammaDET, vU,T4UU, rho_star):\n global tau_tilde_fluxU\n tau_tilde_fluxU = ixp.zerorank1(DIM=3)\n for j in range(3):\n tau_tilde_fluxU[j] = alpha**2*sqrtgammaDET*T4UU[0][j+1] - rho_star*vU[j]\n\n# Step 4.d: S_tilde flux\ndef compute_S_tilde_fluxUD(alpha, sqrtgammaDET, T4UD):\n global S_tilde_fluxUD\n S_tilde_fluxUD = ixp.zerorank2(DIM=3)\n for j in range(3):\n for i in range(3):\n S_tilde_fluxUD[j][i] = alpha*sqrtgammaDET*T4UD[j+1][i+1]", "_____no_output_____" ] ], [ [ "<a id='grhdsourceterms'></a>\n\n# Step 5: Define source terms on RHSs of GRHD equations \\[Back to [top](#toc)\\]\n$$\\label{grhdsourceterms}$$\n\n<a id='ssourceterm'></a>\n\n## Step 5.a: Define $s$ source term on RHS of $\\tilde{\\tau}$ equation \\[Back to [top](#toc)\\]\n$$\\label{ssourceterm}$$\n\n\nRecall again from above the $s$ source term on the right-hand side of the $\\tilde{\\tau}$ evolution equation is given in terms of ADM quantities and the stress-energy tensor via\n$$\ns = \\underbrace{\\alpha \\sqrt{\\gamma}}_{\\text{Term 3}}\\left[\\underbrace{\\left(T^{00}\\beta^i\\beta^j + 2 T^{0i}\\beta^j + T^{ij} \\right)K_{ij}}_{\\text{Term 1}}\n\\underbrace{- \\left(T^{00}\\beta^i + T^{0i} \\right)\\partial_i\\alpha}_{\\text{Term 2}} \\right],\n$$", "_____no_output_____" ] ], [ [ "def compute_s_source_term(KDD,betaU,alpha, sqrtgammaDET,alpha_dD, T4UU):\n global s_source_term\n s_source_term = sp.sympify(0)\n # Term 1:\n for i in range(3):\n for j in range(3):\n s_source_term += (T4UU[0][0]*betaU[i]*betaU[j] + 2*T4UU[0][i+1]*betaU[j] + T4UU[i+1][j+1])*KDD[i][j]\n # Term 2:\n for i in range(3):\n s_source_term += -(T4UU[0][0]*betaU[i] + T4UU[0][i+1])*alpha_dD[i]\n # Term 3:\n s_source_term *= alpha*sqrtgammaDET", "_____no_output_____" ] ], [ [ "<a id='stildeisourceterm'></a>\n\n## Step 5.b: Define source term on RHS of $\\tilde{S}_i$ equation \\[Back to [top](#toc)\\]\n$$\\label{stildeisourceterm}$$\n\nRecall from above\n$$\n\\partial_t \\tilde{S}_i + \\partial_j \\left(\\alpha \\sqrt{\\gamma} T^j{}_i \\right) = \\frac{1}{2} \\alpha\\sqrt{\\gamma} T^{\\mu\\nu} g_{\\mu\\nu,i}.\n$$\nOur goal here will be to compute\n$$\n\\frac{1}{2} \\alpha\\sqrt{\\gamma} T^{\\mu\\nu} g_{\\mu\\nu,i}.\n$$\n\n<a id='fourmetricderivs'></a>\n\n### Step 5.b.i: Compute $g_{\\mu\\nu,i}$ in terms of ADM quantities and their derivatives \\[Back to [top](#toc)\\]\n$$\\label{fourmetricderivs}$$\n\n\nTo compute $g_{\\mu\\nu,i}$ we need to evaluate the first derivative of $g_{\\mu\\nu}$ in terms of ADM variables.\n\nWe are given $\\gamma_{ij}$, $\\alpha$, and $\\beta^i$, and the 4-metric is given in terms of these quantities via\n$$\ng_{\\mu\\nu} = \\begin{pmatrix} \n-\\alpha^2 + \\beta^k \\beta_k & \\beta_i \\\\\n\\beta_j & \\gamma_{ij}\n\\end{pmatrix}.\n$$\n\nThus \n$$\ng_{\\mu\\nu,k} = \\begin{pmatrix} \n-2 \\alpha\\alpha_{,i} + \\beta^j_{,k} \\beta_j + \\beta^j \\beta_{j,k} & \\beta_{i,k} \\\\\n\\beta_{j,k} & \\gamma_{ij,k}\n\\end{pmatrix},\n$$\nwhere $\\beta_{i} = \\gamma_{ij} \\beta^j$, so\n$$\n\\beta_{i,k} = \\gamma_{ij,k} \\beta^j + \\gamma_{ij} \\beta^j_{,k}\n$$", "_____no_output_____" ] ], [ [ "def compute_g4DD_zerotimederiv_dD(gammaDD,betaU,alpha, gammaDD_dD,betaU_dD,alpha_dD):\n global g4DD_zerotimederiv_dD\n # Eq. 2.121 in B&S\n betaD = ixp.zerorank1(DIM=3)\n for i in range(3):\n for j in range(3):\n betaD[i] += gammaDD[i][j]*betaU[j]\n\n betaDdD = ixp.zerorank2(DIM=3)\n for i in range(3):\n for j in range(3):\n for k in range(3):\n # Recall that betaD[i] = gammaDD[i][j]*betaU[j] (Eq. 2.121 in B&S)\n betaDdD[i][k] += gammaDD_dD[i][j][k]*betaU[j] + gammaDD[i][j]*betaU_dD[j][k]\n\n # Eq. 2.122 in B&S\n g4DD_zerotimederiv_dD = ixp.zerorank3(DIM=4)\n for k in range(3):\n # Recall that g4DD[0][0] = -alpha^2 + betaU[j]*betaD[j]\n g4DD_zerotimederiv_dD[0][0][k+1] += -2*alpha*alpha_dD[k]\n for j in range(3):\n g4DD_zerotimederiv_dD[0][0][k+1] += betaU_dD[j][k]*betaD[j] + betaU[j]*betaDdD[j][k]\n\n for i in range(3):\n for k in range(3):\n # Recall that g4DD[i][0] = g4DD[0][i] = betaD[i]\n g4DD_zerotimederiv_dD[i+1][0][k+1] = g4DD_zerotimederiv_dD[0][i+1][k+1] = betaDdD[i][k]\n for i in range(3):\n for j in range(3):\n for k in range(3):\n # Recall that g4DD[i][j] = gammaDD[i][j]\n g4DD_zerotimederiv_dD[i+1][j+1][k+1] = gammaDD_dD[i][j][k]", "_____no_output_____" ] ], [ [ "<a id='stildeisource'></a>\n\n### Step 5.b.ii: Compute source term of the $\\tilde{S}_i$ equation: $\\frac{1}{2} \\alpha\\sqrt{\\gamma} T^{\\mu\\nu} g_{\\mu\\nu,i}$ \\[Back to [top](#toc)\\]\n$$\\label{stildeisource}$$\n\nNow that we've computed `g4DD_zerotimederiv_dD`$=g_{\\mu\\nu,i}$, the $\\tilde{S}_i$ evolution equation source term may be quickly constructed.", "_____no_output_____" ] ], [ [ "# Step 5.b.ii: Compute S_tilde source term\ndef compute_S_tilde_source_termD(alpha, sqrtgammaDET,g4DD_zerotimederiv_dD, T4UU):\n global S_tilde_source_termD\n S_tilde_source_termD = ixp.zerorank1(DIM=3)\n for i in range(3):\n for mu in range(4):\n for nu in range(4):\n S_tilde_source_termD[i] += sp.Rational(1,2)*alpha*sqrtgammaDET*T4UU[mu][nu]*g4DD_zerotimederiv_dD[mu][nu][i+1]", "_____no_output_____" ] ], [ [ "<a id='convertvtou'></a>\n\n# Step 6: Conversion of $v^i$ to $u^\\mu$ (Courtesy Patrick Nelson) \\[Back to [top](#toc)\\]\n$$\\label{convertvtou}$$\n\nAccording to Eqs. 9-11 of [the IllinoisGRMHD paper](https://arxiv.org/pdf/1501.07276.pdf), the Valencia 3-velocity $v^i_{(n)}$ is related to the 4-velocity $u^\\mu$ via\n\n\\begin{align}\n\\alpha v^i_{(n)} &= \\frac{u^i}{u^0} + \\beta^i \\\\\n\\implies u^i &= u^0 \\left(\\alpha v^i_{(n)} - \\beta^i\\right)\n\\end{align}\n\nDefining $v^i = \\frac{u^i}{u^0}$, we get\n\n$$v^i = \\alpha v^i_{(n)} - \\beta^i,$$\n\nand in terms of this variable we get\n\n\\begin{align}\ng_{00} \\left(u^0\\right)^2 + 2 g_{0i} u^0 u^i + g_{ij} u^i u^j &= \\left(u^0\\right)^2 \\left(g_{00} + 2 g_{0i} v^i + g_{ij} v^i v^j\\right)\\\\\n\\implies u^0 &= \\pm \\sqrt{\\frac{-1}{g_{00} + 2 g_{0i} v^i + g_{ij} v^i v^j}} \\\\\n&= \\pm \\sqrt{\\frac{-1}{(-\\alpha^2 + \\beta^2) + 2 \\beta_i v^i + \\gamma_{ij} v^i v^j}} \\\\\n&= \\pm \\sqrt{\\frac{1}{\\alpha^2 - \\gamma_{ij}\\left(\\beta^i + v^i\\right)\\left(\\beta^j + v^j\\right)}}\\\\\n&= \\pm \\sqrt{\\frac{1}{\\alpha^2 - \\alpha^2 \\gamma_{ij}v^i_{(n)}v^j_{(n)}}}\\\\\n&= \\pm \\frac{1}{\\alpha}\\sqrt{\\frac{1}{1 - \\gamma_{ij}v^i_{(n)}v^j_{(n)}}}\n\\end{align}\n\nGenerally speaking, numerical errors will occasionally drive expressions under the radical to either negative values or potentially enormous values (corresponding to enormous Lorentz factors). Thus a reliable approach for computing $u^0$ requires that we first rewrite the above expression in terms of the Lorentz factor squared: $\\Gamma^2=\\left(\\alpha u^0\\right)^2$:\n\\begin{align}\nu^0 &= \\pm \\frac{1}{\\alpha}\\sqrt{\\frac{1}{1 - \\gamma_{ij}v^i_{(n)}v^j_{(n)}}}\\\\\n\\implies \\left(\\alpha u^0\\right)^2 &= \\frac{1}{1 - \\gamma_{ij}v^i_{(n)}v^j_{(n)}} \\\\\n\\implies \\gamma_{ij}v^i_{(n)}v^j_{(n)} &= 1 - \\frac{1}{\\left(\\alpha u^0\\right)^2} \\\\\n&= 1 - \\frac{1}{\\Gamma^2}\n\\end{align}\n\nIn order for the bottom expression to hold true, the left-hand side must be between 0 and 1. Again, this is not guaranteed due to the appearance of numerical errors. In fact, a robust algorithm will not allow $\\Gamma^2$ to become too large (which might contribute greatly to the stress-energy of a given gridpoint), so let's define the largest allowed Lorentz factor as $\\Gamma_{\\rm max}$.\n\nThen our algorithm for computing $u^0$ is as follows:\n\nIf\n$$R=\\gamma_{ij}v^i_{(n)}v^j_{(n)}>1 - \\frac{1}{\\Gamma_{\\rm max}^2},$$ \nthen adjust the 3-velocity $v^i$ as follows:\n\n$$v^i_{(n)} \\to \\sqrt{\\frac{1 - \\frac{1}{\\Gamma_{\\rm max}^2}}{R}}v^i_{(n)}.$$\n\nAfter this rescaling, we are then guaranteed that if $R$ is recomputed, it will be set to its ceiling value $R=R_{\\rm max} = 1 - \\frac{1}{\\Gamma_{\\rm max}^2}$.\n\nThen, regardless of whether the ceiling on $R$ was applied, $u^0$ can be safely computed via\n\n$$\nu^0 = \\frac{1}{\\alpha \\sqrt{1-R}},\n$$\nand the remaining components $u^i$ via\n$$\nu^i = u^0 v^i.\n$$\n\nIn summary our algorithm for computing $u^{\\mu}$ from $v^i = \\frac{u^i}{u^0}$ is as follows:\n\n1. Choose a maximum Lorentz factor $\\Gamma_{\\rm max}$=`GAMMA_SPEED_LIMIT`, and define $v^i_{(n)} = \\frac{1}{\\alpha}\\left( \\frac{u^i}{u^0} + \\beta^i\\right)$.\n1. Compute $R=\\gamma_{ij}v^i_{(n)}v^j_{(n)}=1 - \\frac{1}{\\Gamma^2}$\n1. If $R \\le 1 - \\frac{1}{\\Gamma_{\\rm max}^2}$, then skip the next step.\n1. Otherwise if $R > 1 - \\frac{1}{\\Gamma_{\\rm max}^2}$ then adjust $v^i_{(n)}\\to \\sqrt{\\frac{1 - \\frac{1}{\\Gamma_{\\rm max}^2}}{R}}v^i_{(n)}$, which will force $R=R_{\\rm max}$.\n1. Given the $R$ computed in the above step, $u^0 = \\frac{1}{\\alpha \\sqrt{1-R}}$, and $u^i=u^0 v^i$.\n\nWhile the above algorithm is quite robust, its `if()` statement in the fourth step is not very friendly to NRPy+ or an optimizing C compiler, as it would require NRPy+ to generate separate C kernels for each branch of the `if()`. Let's instead try the following trick, which Roland Haas taught us. \n\nDefine $R^*$ as\n\n$$\nR^* = \\frac{1}{2} \\left(R_{\\rm max} + R - |R_{\\rm max} - R| \\right).\n$$\n\nIf $R>R_{\\rm max}$, then $|R_{\\rm max} - R|=R - R_{\\rm max}$, and we get:\n\n$$\nR^* = \\frac{1}{2} \\left(R_{\\rm max} + R - (R - R_{\\rm max}) \\right) = \\frac{1}{2} \\left(2 R_{\\rm max}\\right) = R_{\\rm max}\n$$\n\nIf $R\\le R_{\\rm max}$, then $|R_{\\rm max} - R|=R_{\\rm max} - R$, and we get:\n\n$$\nR^* = \\frac{1}{2} \\left(R_{\\rm max} + R - (R_{\\rm max} - R) \\right) = \\frac{1}{2} \\left(2 R\\right) = R\n$$\n\nThen we can rescale *all* $v^i_{(n)}$ via\n\n$$\nv^i_{(n)} \\to v^i_{(n)} \\sqrt{\\frac{R^*}{R}},\n$$\n\nthough we must be very careful to carefully handle the case in which $R=0$. To avoid any problems in this case, we simply adjust the above rescaling by adding a tiny number [`TINYDOUBLE`](https://en.wikipedia.org/wiki/Tiny_Bubbles) to $R$ in the denominator, typically `1e-100`:\n\n$$\nv^i_{(n)} \\to v^i_{(n)} \\sqrt{\\frac{R^*}{R + {\\rm TINYDOUBLE}}}.\n$$\n\nFinally, $u^0$ can be immediately and safely computed, via:\n$$\nu^0 = \\frac{1}{\\alpha \\sqrt{1-R^*}},\n$$\nand $u^i$ via \n$$\nu^i = u^0 v^i = u^0 \\left(\\alpha v^i_{(n)} - \\beta^i\\right).\n$$", "_____no_output_____" ] ], [ [ "# Step 6.a: Convert Valencia 3-velocity v_{(n)}^i into u^\\mu, and apply a speed limiter\n# Speed-limited ValenciavU is output to rescaledValenciavU global.\ndef u4U_in_terms_of_ValenciavU__rescale_ValenciavU_by_applying_speed_limit(alpha,betaU,gammaDD, ValenciavU):\n # Inputs: Metric lapse alpha, shift betaU, 3-metric gammaDD, Valencia 3-velocity ValenciavU\n # Outputs (as globals): u4U_ito_ValenciavU, rescaledValenciavU\n\n # R = gamma_{ij} v^i v^j\n R = sp.sympify(0)\n for i in range(3):\n for j in range(3):\n R += gammaDD[i][j]*ValenciavU[i]*ValenciavU[j]\n\n thismodule = \"GRHD\"\n # The default value isn't terribly important here, since we can overwrite in the main C code\n GAMMA_SPEED_LIMIT = par.Cparameters(\"REAL\", thismodule, \"GAMMA_SPEED_LIMIT\", 10.0) # Default value based on\n # IllinoisGRMHD.\n # GiRaFFE default = 2000.0\n Rmax = 1 - 1 / (GAMMA_SPEED_LIMIT * GAMMA_SPEED_LIMIT)\n # Now, we set Rstar = min(Rmax,R):\n # If R < Rmax, then Rstar = 0.5*(Rmax+R-Rmax+R) = R\n # If R >= Rmax, then Rstar = 0.5*(Rmax+R+Rmax-R) = Rmax\n Rstar = sp.Rational(1, 2) * (Rmax + R - nrpyAbs(Rmax - R))\n\n # We add TINYDOUBLE to R below to avoid a 0/0, which occurs when\n # ValenciavU == 0 for all Valencia 3-velocity components.\n # \"Those tiny *doubles* make me warm all over\n # with a feeling that I'm gonna love you till the end of time.\"\n # - Adapted from Connie Francis' \"Tiny Bubbles\"\n TINYDOUBLE = par.Cparameters(\"#define\",thismodule,\"TINYDOUBLE\",1e-100)\n\n # The rescaled (speed-limited) Valencia 3-velocity\n # is given by, v_{(n)}^i = sqrt{Rstar/R} v^i\n global rescaledValenciavU\n rescaledValenciavU = ixp.zerorank1(DIM=3)\n for i in range(3):\n # If R == 0, then Rstar == 0, so sqrt( Rstar/(R+TINYDOUBLE) )=sqrt(0/1e-100) = 0\n # If your velocities are of order 1e-100 and this is physically\n # meaningful, there must be something wrong with your unit conversion.\n rescaledValenciavU[i] = ValenciavU[i]*sp.sqrt(Rstar/(R + TINYDOUBLE))\n\n # Finally compute u^mu in terms of Valenciav^i\n # u^0 = 1/(alpha-sqrt(1-R^*))\n global u4U_ito_ValenciavU\n u4U_ito_ValenciavU = ixp.zerorank1(DIM=4)\n u4U_ito_ValenciavU[0] = 1/(alpha*sp.sqrt(1-Rstar))\n # u^i = u^0 ( alpha v^i_{(n)} - beta^i ), where v^i_{(n)} is the Valencia 3-velocity\n for i in range(3):\n u4U_ito_ValenciavU[i+1] = u4U_ito_ValenciavU[0] * (alpha * rescaledValenciavU[i] - betaU[i])\n\n# Step 6.b: Convert v^i into u^\\mu, and apply a speed limiter.\n# Speed-limited vU is output to rescaledvU global.\ndef u4U_in_terms_of_vU__rescale_vU_by_applying_speed_limit(alpha,betaU,gammaDD, vU):\n ValenciavU = ixp.zerorank1(DIM=3)\n for i in range(3):\n ValenciavU[i] = (vU[i] + betaU[i])/alpha\n u4U_in_terms_of_ValenciavU__rescale_ValenciavU_by_applying_speed_limit(alpha,betaU,gammaDD, ValenciavU)\n # Since ValenciavU is written in terms of vU,\n # u4U_ito_ValenciavU is actually u4U_ito_vU\n global u4U_ito_vU\n u4U_ito_vU = ixp.zerorank1(DIM=4)\n for mu in range(4):\n u4U_ito_vU[mu] = u4U_ito_ValenciavU[mu]\n # Finally compute the rescaled (speed-limited) vU\n global rescaledvU\n rescaledvU = ixp.zerorank1(DIM=3)\n for i in range(3):\n rescaledvU[i] = alpha * rescaledValenciavU[i] - betaU[i]", "_____no_output_____" ] ], [ [ "<a id='declarevarsconstructgrhdeqs'></a>\n\n# Step 7: Declare ADM and hydrodynamical input variables, and construct GRHD equations \\[Back to [top](#toc)\\]\n$$\\label{declarevarsconstructgrhdeqs}$$", "_____no_output_____" ] ], [ [ "# First define hydrodynamical quantities\nu4U = ixp.declarerank1(\"u4U\", DIM=4)\nrho_b,P,epsilon = sp.symbols('rho_b P epsilon',real=True)\n\n# Then ADM quantities\ngammaDD = ixp.declarerank2(\"gammaDD\",\"sym01\",DIM=3)\nKDD = ixp.declarerank2(\"KDD\" ,\"sym01\",DIM=3)\nbetaU = ixp.declarerank1(\"betaU\", DIM=3)\nalpha = sp.symbols('alpha', real=True)\n\n# First compute stress-energy tensor T4UU and T4UD:\ncompute_T4UU(gammaDD,betaU,alpha, rho_b,P,epsilon,u4U)\ncompute_T4UD(gammaDD,betaU,alpha, T4UU)\n\n# Next sqrt(gamma)\ncompute_sqrtgammaDET(gammaDD)\n\n# Compute conservative variables in terms of primitive variables\ncompute_rho_star( alpha, sqrtgammaDET, rho_b,u4U)\ncompute_tau_tilde(alpha, sqrtgammaDET, T4UU,rho_star)\ncompute_S_tildeD( alpha, sqrtgammaDET, T4UD)\n\n# Then compute v^i from u^mu\ncompute_vU_from_u4U__no_speed_limit(u4U)\n\n# Next compute fluxes of conservative variables\ncompute_rho_star_fluxU( vU, rho_star)\ncompute_tau_tilde_fluxU(alpha, sqrtgammaDET, vU,T4UU, rho_star)\ncompute_S_tilde_fluxUD( alpha, sqrtgammaDET, T4UD)\n\n# Then declare derivatives & compute g4DD_zerotimederiv_dD\ngammaDD_dD = ixp.declarerank3(\"gammaDD_dD\",\"sym01\",DIM=3)\nbetaU_dD = ixp.declarerank2(\"betaU_dD\" ,\"nosym\",DIM=3)\nalpha_dD = ixp.declarerank1(\"alpha_dD\" ,DIM=3)\ncompute_g4DD_zerotimederiv_dD(gammaDD,betaU,alpha, gammaDD_dD,betaU_dD,alpha_dD)\n\n# Then compute source terms on tau_tilde and S_tilde equations\ncompute_s_source_term(KDD,betaU,alpha, sqrtgammaDET,alpha_dD, T4UU)\ncompute_S_tilde_source_termD( alpha, sqrtgammaDET,g4DD_zerotimederiv_dD, T4UU)\n\n# Then compute the 4-velocities in terms of an input Valencia 3-velocity testValenciavU[i]\ntestValenciavU = ixp.declarerank1(\"testValenciavU\",DIM=3)\nu4U_in_terms_of_ValenciavU__rescale_ValenciavU_by_applying_speed_limit(alpha,betaU,gammaDD, testValenciavU)\n\n# Finally compute the 4-velocities in terms of an input 3-velocity testvU[i] = u^i/u^0\ntestvU = ixp.declarerank1(\"testvU\",DIM=3)\nu4U_in_terms_of_vU__rescale_vU_by_applying_speed_limit(alpha,betaU,gammaDD, testvU)", "_____no_output_____" ] ], [ [ "<a id='code_validation'></a>\n\n# Step 8: Code Validation against `GRHD.equations` NRPy+ module \\[Back to [top](#toc)\\]\n$$\\label{code_validation}$$\n\nAs a code validation check, we verify agreement in the SymPy expressions for the GRHD equations generated in\n1. this tutorial versus\n2. the NRPy+ [GRHD.equations](../edit/GRHD/equations.py) module.", "_____no_output_____" ] ], [ [ "import GRHD.equations as Ge\n\n# First compute stress-energy tensor T4UU and T4UD:\nGe.compute_T4UU(gammaDD,betaU,alpha, rho_b,P,epsilon,u4U)\nGe.compute_T4UD(gammaDD,betaU,alpha, Ge.T4UU)\n\n# Next sqrt(gamma)\nGe.compute_sqrtgammaDET(gammaDD)\n\n# Compute conservative variables in terms of primitive variables\nGe.compute_rho_star( alpha, Ge.sqrtgammaDET, rho_b,u4U)\nGe.compute_tau_tilde(alpha, Ge.sqrtgammaDET, Ge.T4UU,Ge.rho_star)\nGe.compute_S_tildeD( alpha, Ge.sqrtgammaDET, Ge.T4UD)\n\n# Then compute v^i from u^mu\nGe.compute_vU_from_u4U__no_speed_limit(u4U)\n\n# Next compute fluxes of conservative variables\nGe.compute_rho_star_fluxU ( Ge.vU, Ge.rho_star)\nGe.compute_tau_tilde_fluxU(alpha, Ge.sqrtgammaDET, Ge.vU,Ge.T4UU, Ge.rho_star)\nGe.compute_S_tilde_fluxUD (alpha, Ge.sqrtgammaDET, Ge.T4UD)\n\n# Then declare derivatives & compute g4DD_zerotimederiv_dD\n# gammaDD_dD = ixp.declarerank3(\"gammaDD_dD\",\"sym01\",DIM=3)\n# betaU_dD = ixp.declarerank2(\"betaU_dD\" ,\"nosym\",DIM=3)\n# alpha_dD = ixp.declarerank1(\"alpha_dD\" ,DIM=3)\nGe.compute_g4DD_zerotimederiv_dD(gammaDD,betaU,alpha, gammaDD_dD,betaU_dD,alpha_dD)\n\n# Finally compute source terms on tau_tilde and S_tilde equations\nGe.compute_s_source_term(KDD,betaU,alpha, Ge.sqrtgammaDET,alpha_dD, Ge.T4UU)\nGe.compute_S_tilde_source_termD( alpha, Ge.sqrtgammaDET,Ge.g4DD_zerotimederiv_dD,Ge.T4UU)\n\nGetestValenciavU = ixp.declarerank1(\"testValenciavU\")\nGe.u4U_in_terms_of_ValenciavU__rescale_ValenciavU_by_applying_speed_limit(alpha, betaU, gammaDD, GetestValenciavU)\n\nGetestvU = ixp.declarerank1(\"testvU\")\nGe.u4U_in_terms_of_vU__rescale_vU_by_applying_speed_limit( alpha, betaU, gammaDD, GetestvU)", "_____no_output_____" ], [ "all_passed=True\ndef comp_func(expr1,expr2,basename,prefixname2=\"Ge.\"):\n if str(expr1-expr2)!=\"0\":\n print(basename+\" - \"+prefixname2+basename+\" = \"+ str(expr1-expr2))\n all_passed=False\n\ndef gfnm(basename,idx1,idx2=None,idx3=None):\n if idx2 is None:\n return basename+\"[\"+str(idx1)+\"]\"\n if idx3 is None:\n return basename+\"[\"+str(idx1)+\"][\"+str(idx2)+\"]\"\n return basename+\"[\"+str(idx1)+\"][\"+str(idx2)+\"][\"+str(idx3)+\"]\"\n\nexpr_list = []\nexprcheck_list = []\nnamecheck_list = []\n\nnamecheck_list.extend([\"sqrtgammaDET\",\"rho_star\",\"tau_tilde\",\"s_source_term\"])\nexprcheck_list.extend([Ge.sqrtgammaDET,Ge.rho_star,Ge.tau_tilde,Ge.s_source_term])\nexpr_list.extend([sqrtgammaDET,rho_star,tau_tilde,s_source_term])\nfor mu in range(4):\n namecheck_list.extend([gfnm(\"u4_ito_ValenciavU\",mu),gfnm(\"u4U_ito_vU\",mu)])\n exprcheck_list.extend([ Ge.u4U_ito_ValenciavU[mu], Ge.u4U_ito_vU[mu]])\n expr_list.extend( [ u4U_ito_ValenciavU[mu], u4U_ito_vU[mu]])\n for nu in range(4):\n namecheck_list.extend([gfnm(\"T4UU\",mu,nu),gfnm(\"T4UD\",mu,nu)])\n exprcheck_list.extend([Ge.T4UU[mu][nu],Ge.T4UD[mu][nu]])\n expr_list.extend([T4UU[mu][nu],T4UD[mu][nu]])\n for delta in range(4):\n namecheck_list.extend([gfnm(\"g4DD_zerotimederiv_dD\",mu,nu,delta)])\n exprcheck_list.extend([Ge.g4DD_zerotimederiv_dD[mu][nu][delta]])\n expr_list.extend([g4DD_zerotimederiv_dD[mu][nu][delta]])\n\n\nfor i in range(3):\n namecheck_list.extend([gfnm(\"S_tildeD\",i),gfnm(\"vU\",i),gfnm(\"rho_star_fluxU\",i),\n gfnm(\"tau_tilde_fluxU\",i),gfnm(\"S_tilde_source_termD\",i),\n gfnm(\"rescaledValenciavU\",i), gfnm(\"rescaledvU\",i)])\n exprcheck_list.extend([Ge.S_tildeD[i],Ge.vU[i],Ge.rho_star_fluxU[i],\n Ge.tau_tilde_fluxU[i],Ge.S_tilde_source_termD[i],\n Ge.rescaledValenciavU[i],Ge.rescaledvU[i]])\n expr_list.extend([S_tildeD[i],vU[i],rho_star_fluxU[i],\n tau_tilde_fluxU[i],S_tilde_source_termD[i],\n rescaledValenciavU[i],rescaledvU[i]])\n for j in range(3):\n namecheck_list.extend([gfnm(\"S_tilde_fluxUD\",i,j)])\n exprcheck_list.extend([Ge.S_tilde_fluxUD[i][j]])\n expr_list.extend([S_tilde_fluxUD[i][j]])\n\nfor i in range(len(expr_list)):\n comp_func(expr_list[i],exprcheck_list[i],namecheck_list[i])\n\nimport sys\nif all_passed:\n print(\"ALL TESTS PASSED!\")\nelse:\n print(\"ERROR: AT LEAST ONE TEST DID NOT PASS\")\n sys.exit(1)", "ALL TESTS PASSED!\n" ] ], [ [ "<a id='latex_pdf_output'></a>\n\n# Step 9: 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-GRHD_Equations-Cartesian.pdf](Tutorial-GRHD_Equations-Cartesian.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-GRHD_Equations-Cartesian\")", "Created Tutorial-GRHD_Equations-Cartesian.tex, and compiled LaTeX file to\n PDF file Tutorial-GRHD_Equations-Cartesian.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", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d01e7c762c0124364c4faa5621abbee1c291be21
200,286
ipynb
Jupyter Notebook
committee103s5.ipynb
sashkarivkind/imagewalker
999e1ae78cfe1512e1be894d9e7891a7d0c41233
[ "Apache-2.0" ]
2
2021-04-28T13:33:45.000Z
2021-11-09T14:31:09.000Z
committee103s5.ipynb
sashkarivkind/imagewalker
999e1ae78cfe1512e1be894d9e7891a7d0c41233
[ "Apache-2.0" ]
null
null
null
committee103s5.ipynb
sashkarivkind/imagewalker
999e1ae78cfe1512e1be894d9e7891a7d0c41233
[ "Apache-2.0" ]
1
2021-03-07T13:25:59.000Z
2021-03-07T13:25:59.000Z
152.540746
64,164
0.847503
[ [ [ "from misc import HP\nimport argparse\nimport random\nimport time\nimport pickle\nimport copy\nimport SYCLOP_env as syc\nfrom misc import *\nimport sys\nimport os\nimport cv2\nimport argparse\nimport tensorflow.keras as keras\n\nfrom keras_networks import rnn_model_102, rnn_model_multicore_201, rnn_model_multicore_202\nfrom curriculum_utils import create_mnist_dataset, bad_res102", "_____no_output_____" ], [ "\ndef generate_trajectory(n_steps,max_q,acceleration_mode):\n starting_point = np.array([max_q[0] // 2, max_q[1] // 2])\n steps = []\n qdot=0\n for j in range(n_steps):\n steps.append(starting_point * 1)\n if acceleration_mode:\n qdot += np.random.randint(-1, 2, 2)\n starting_point += qdot\n else:\n starting_point += np.random.randint(-5, 6, 2)\n return np.array(steps)", "_____no_output_____" ], [ "def split_dataset_xy(dataset):\n dataset_x1 = [uu[0] for uu in dataset]\n dataset_x2 = [uu[1] for uu in dataset]\n dataset_y = [uu[-1] for uu in dataset]\n return (np.array(dataset_x1)[...,np.newaxis],np.array(dataset_x2)[:,:n_timesteps,:]),np.array(dataset_y)\n\n#parse hyperparameters\n\nlsbjob = os.getenv('LSB_JOBID')\nlsbjob = '' if lsbjob is None else lsbjob\n\nhp = HP()\nhp.save_path = 'saved_runs'\nhp.description=''\nparser = argparse.ArgumentParser()\nparser.add_argument('--tau_int', default=4., type=float, help='Integration timescale for adaaptation')\nparser.add_argument('--resize', default=1.0, type=float, help='resize of images')\nparser.add_argument('--run_name_suffix', default='', type=str, help='suffix for runname')\nparser.add_argument('--eval_dir', default=None, type=str, help='eval dir')\n\nparser.add_argument('--dqn_initial_network', default=None, type=str, help='dqn_initial_network')\nparser.add_argument('--decoder_initial_network', default=None, type=str, help='decoder_initial_network')\nparser.add_argument('--decoder_arch', default='default', type=str, help='decoder_network architecture: default / multicore_201')\nparser.add_argument('--decoder_n_cores', default=1, type=int, help='decoder number of cores')\n\nparser.add_argument('--decoder_learning_rate', default=1e-3, type=float, help='decoder learning rate')\nparser.add_argument('--decoder_dropout', default=0.0, type=float, help='decoder dropout')\nparser.add_argument('--decoder_rnn_type', default='gru', type=str, help='gru or rnn')\nparser.add_argument('--decoder_rnn_units', default=100, type=int, help='decoder rnn units')\nparser.add_argument('--decoder_rnn_layers', default=1, type=int, help='decoder rnn units')\n\n\nparser.add_argument('--decoder_ignore_position', dest='decoder_ignore_position', action='store_true')\nparser.add_argument('--no-decoder_ignore_position', dest='decoder_ignore_position', action='store_false')\n\nparser.add_argument('--syclop_learning_rate', default=2.5e-3, type=float, help='syclop (RL) learning rate')\n\nparser.add_argument('--color', default='grayscale', type=str, help='grayscale/rgb')\nparser.add_argument('--speed_reward', default=0.0, type=float, help='speed reward, typically negative')\nparser.add_argument('--intensity_reward', default=0.0, type=float, help='speed penalty reward')\nparser.add_argument('--loss_reward', default=-1.0, type=float, help='reward for loss, typically negative')\nparser.add_argument('--resolution', default=28, type=int, help='resolution')\nparser.add_argument('--max_eval_episodes', default=10000, type=int, help='episodes for evaluation mode')\nparser.add_argument('--steps_per_episode', default=5, type=int, help='time steps in each episode in ')\nparser.add_argument('--fit_verbose', default=1, type=int, help='verbose level for model.fit ')\nparser.add_argument('--steps_between_learnings', default=100, type=int, help='steps_between_learnings')\nparser.add_argument('--num_epochs', default=100, type=int, help='steps_between_learnings')\n\nparser.add_argument('--alpha_increment', default=0.01, type=float, help='reward for loss, typically negative')\n\n\nparser.add_argument('--beta_t1', default=400000, type=int, help='time rising bete')\nparser.add_argument('--beta_t2', default=700000, type=int, help='end rising beta')\nparser.add_argument('--beta_b1', default=0.1, type=float, help='beta initial value')\nparser.add_argument('--beta_b2', default=1.0, type=float, help='beta final value')\n\nparser.add_argument('--curriculum_enable', dest='curriculum_enable', action='store_true')\nparser.add_argument('--no-curriculum_enable', dest='curriculum_enable', action='store_false')\n\nparser.add_argument('--conv_fe', dest='conv_fe', action='store_true')\nparser.add_argument('--no-conv_fe', dest='conv_fe', action='store_false')\n\nparser.add_argument('--acceleration_mode', dest='acceleration_mode', action='store_true')\nparser.add_argument('--no-acceleration_mode', dest='acceleration_mode', action='store_false')\n\n\nparser.set_defaults(eval_mode=False, decode_from_dvs=False,test_mode=False,rising_beta_schedule=True,decoder_ignore_position=False, curriculum_enable=True, conv_fe=False,\n acceleration_mode=True)\nconfig = parser.parse_args('')\n\n# config = parser.parse_args()\nconfig = vars(config)\nhp.upadte_from_dict(config)\nhp.this_run_name = sys.argv[0] + '_noname_' + hp.run_name_suffix + '_' + lsbjob + '_' + str(int(time.time()))\n\n#define model\nn_timesteps = hp.steps_per_episode\n\n##\n# deploy_logs()\n##\n# if hp.decoder_arch == 'multicore_201':\n# decoder = rnn_model_multicore_201(n_cores=hp.decoder_n_cores,lr=hp.decoder_learning_rate,ignore_input_B=hp.decoder_ignore_position,dropout=hp.decoder_dropout,rnn_type=hp.decoder_rnn_type,\n# input_size=(hp.resolution,hp.resolution, 1),rnn_layers=hp.decoder_rnn_layers,conv_fe=hp.conv_fe, rnn_units=hp.decoder_rnn_units, n_timesteps=hp.steps_per_episode)\n# if hp.decoder_arch == 'multicore_202':\n# decoder = rnn_model_multicore_202(n_cores=hp.decoder_n_cores, lr=hp.decoder_learning_rate,\n# ignore_input_B=hp.decoder_ignore_position, dropout=hp.decoder_dropout,\n# rnn_type=hp.decoder_rnn_type,\n# input_size=(hp.resolution, hp.resolution, 1),\n# rnn_layers=hp.decoder_rnn_layers, conv_fe=hp.conv_fe,\n# rnn_units=hp.decoder_rnn_units, n_timesteps=hp.steps_per_episode)\n# elif hp.decoder_arch == 'default':\n# decoder = rnn_model_102(lr=hp.decoder_learning_rate,ignore_input_B=hp.decoder_ignore_position,dropout=hp.decoder_dropout,rnn_type=hp.decoder_rnn_type,\n# input_size=(hp.resolution,hp.resolution, 1),rnn_layers=hp.decoder_rnn_layers,conv_fe=hp.conv_fe,rnn_units=hp.decoder_rnn_units, n_timesteps=hp.steps_per_episode)\ndecoder_initial_network = 'saved_runs/trajectory_curriculum101.py_noname__613128_1624010531_1//final_decoder.nwk'\ndecoder = keras.models.load_model(decoder_initial_network)\n #define dataset\n(images, labels), (images_test, labels_test) = keras.datasets.mnist.load_data(path=\"mnist.npz\")\n\n\n#fit one epoch in a time\n# scheduler = Scheduler(hp.lambda_schedule)\n# for epoch in range(hp.num_epochs):\n# lambda_epoch = scheduler.step(epoch)", "_____no_output_____" ], [ "hp.acceleration_mode", "_____no_output_____" ], [ "alpha=0\nhp.num_trials = 30\ntrajectories = []\ntrain_pred_pred = []\nval_pred_pred = []\nfor trial in range(hp.num_trials):\n this_trajectory=generate_trajectory(hp.steps_per_episode,[72,72],hp.acceleration_mode)\n# this_trajectory=trajectories[trial]\n train_dataset, test_dataset = create_mnist_dataset(images, labels, 6, sample=hp.steps_per_episode, bad_res_func=bad_res102,\n return_datasets=True, q_0=this_trajectory, alpha=0.0,\n random_trajectories=True,acceleration_mode=hp.acceleration_mode)\n train_dataset_x, train_dataset_y = split_dataset_xy(train_dataset)\n test_dataset_x, test_dataset_y = split_dataset_xy(test_dataset)\n q_prime = train_dataset_x[1][0]\n# print('epoch', epoch, ' CONTROL!!!',' first q --', q_prime.reshape([-1]))\n\n print(\"evaluating trajectory \", trial)\n train_preds = decoder.predict(\n train_dataset_x,\n batch_size=64,\n verbose=hp.fit_verbose,\n # We pass some validation for\n # monitoring validation loss and metrics\n # at the end of each epoch\n )\n val_preds = decoder.predict(\n test_dataset_x,\n batch_size=64,\n verbose=hp.fit_verbose,\n # We pass some validation for\n # monitoring validation loss and metrics\n # at the end of each epoch\n )\n accuracy = np.mean(np.argmax(val_preds, axis=1)==test_dataset_y)\n print('accuracy:', accuracy)\n trajectories.append(this_trajectory+0.)\n train_pred_pred.append(train_preds+0.0)\n val_pred_pred.append(val_preds+0.0)", "Are we random? 5\nevaluating trajectory 0\n55000/55000 [==============================] - 14s 261us/sample\n5000/5000 [==============================] - 1s 245us/sample\naccuracy: 0.8166\nAre we random? 4\nevaluating trajectory 1\n55000/55000 [==============================] - 14s 253us/sample\n5000/5000 [==============================] - 1s 255us/sample\naccuracy: 0.8478\nAre we random? 17\nevaluating trajectory 2\n55000/55000 [==============================] - 14s 252us/sample\n5000/5000 [==============================] - 1s 254us/sample\naccuracy: 0.8238\nAre we random? 2\nevaluating trajectory 3\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 250us/sample\naccuracy: 0.8318\nAre we random? 15\nevaluating trajectory 4\n55000/55000 [==============================] - 14s 255us/sample\n5000/5000 [==============================] - 1s 248us/sample\naccuracy: 0.8292\nAre we random? 12\nevaluating trajectory 5\n55000/55000 [==============================] - 14s 254us/sample\n5000/5000 [==============================] - 1s 257us/sample\naccuracy: 0.8412\nAre we random? 1\nevaluating trajectory 6\n55000/55000 [==============================] - 14s 251us/sample\n5000/5000 [==============================] - 1s 255us/sample\naccuracy: 0.7984\nAre we random? 18\nevaluating trajectory 7\n55000/55000 [==============================] - 14s 250us/sample\n5000/5000 [==============================] - 1s 259us/sample\naccuracy: 0.8478\nAre we random? 2\nevaluating trajectory 8\n55000/55000 [==============================] - 14s 251us/sample\n5000/5000 [==============================] - 1s 257us/sample\naccuracy: 0.8024\nAre we random? 15\nevaluating trajectory 9\n55000/55000 [==============================] - 14s 252us/sample\n5000/5000 [==============================] - 1s 256us/sample\naccuracy: 0.7598\nAre we random? 9\nevaluating trajectory 10\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 259us/sample\naccuracy: 0.8084\nAre we random? 4\nevaluating trajectory 11\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 259us/sample\naccuracy: 0.8576\nAre we random? 1\nevaluating trajectory 12\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 252us/sample\naccuracy: 0.802\nAre we random? 14\nevaluating trajectory 13\n55000/55000 [==============================] - 14s 258us/sample\n5000/5000 [==============================] - 1s 254us/sample\naccuracy: 0.8302\nAre we random? 11\nevaluating trajectory 14\n55000/55000 [==============================] - 14s 256us/sample\n5000/5000 [==============================] - 1s 260us/sample\naccuracy: 0.7792\nAre we random? 12\nevaluating trajectory 15\n55000/55000 [==============================] - 14s 252us/sample\n5000/5000 [==============================] - 1s 248us/sample\naccuracy: 0.6864\nAre we random? 13\nevaluating trajectory 16\n55000/55000 [==============================] - 14s 258us/sample\n5000/5000 [==============================] - 1s 253us/sample\naccuracy: 0.8326\nAre we random? 8\nevaluating trajectory 17\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 259us/sample\naccuracy: 0.851\nAre we random? 18\nevaluating trajectory 18\n55000/55000 [==============================] - 14s 256us/sample\n5000/5000 [==============================] - 1s 258us/sample\naccuracy: 0.841\nAre we random? 2\nevaluating trajectory 19\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 256us/sample\naccuracy: 0.7664\nAre we random? 19\nevaluating trajectory 20\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 258us/sample\naccuracy: 0.812\nAre we random? 15\nevaluating trajectory 21\n55000/55000 [==============================] - 14s 261us/sample\n5000/5000 [==============================] - 1s 262us/sample\naccuracy: 0.856\nAre we random? 19\nevaluating trajectory 22\n55000/55000 [==============================] - 14s 259us/sample\n5000/5000 [==============================] - 1s 263us/sample\naccuracy: 0.7936\nAre we random? 11\nevaluating trajectory 23\n55000/55000 [==============================] - 14s 260us/sample\n5000/5000 [==============================] - 1s 268us/sample\naccuracy: 0.8256\nAre we random? 18\nevaluating trajectory 24\n55000/55000 [==============================] - 14s 259us/sample\n5000/5000 [==============================] - 1s 262us/sample\naccuracy: 0.8232\nAre we random? 18\nevaluating trajectory 25\n55000/55000 [==============================] - 14s 259us/sample\n5000/5000 [==============================] - 1s 260us/sample\naccuracy: 0.6844\nAre we random? 12\nevaluating trajectory 26\n55000/55000 [==============================] - 14s 261us/sample\n5000/5000 [==============================] - 1s 263us/sample\naccuracy: 0.8796\nAre we random? 8\nevaluating trajectory 27\n55000/55000 [==============================] - 14s 255us/sample\n5000/5000 [==============================] - 1s 256us/sample\naccuracy: 0.8008\nAre we random? 9\nevaluating trajectory 28\n55000/55000 [==============================] - 14s 258us/sample\n5000/5000 [==============================] - 1s 260us/sample\naccuracy: 0.858\nAre we random? 7\nevaluating trajectory 29\n55000/55000 [==============================] - 14s 257us/sample\n5000/5000 [==============================] - 1s 258us/sample\naccuracy: 0.8172\n" ], [ "accuracy = np.mean(np.argmax(val_preds, axis=1)==test_dataset_y)", "_____no_output_____" ], [ "accuracy", "_____no_output_____" ], [ "ent = np.zeros([np.shape(test_dataset_y)[0],hp.num_trials])\nlablab = np.zeros([np.shape(test_dataset_y)[0],hp.num_trials])\nfor jj,preds in enumerate(val_pred_pred):\n ent[:,jj]=np.sum(-preds*np.log(preds),axis=1)\n lablab[:,jj]=np.argmax(preds, axis=1)", "_____no_output_____" ], [ "ii=np.argmin(ent,axis=1)", "_____no_output_____" ], [ "best_lbl=[]\nfor jj,uu in enumerate(ii):\n best_lbl.append(lablab[jj,uu])\n", "_____no_output_____" ], [ "np.mean(best_lbl==test_dataset_y)", "_____no_output_____" ], [ "#random syclop, \nnp.mean(lablab==test_dataset_y.reshape([-1,1]))", "_____no_output_____" ], [ "accuracies=np.mean(lablab==test_dataset_y.reshape([-1,1]),axis=0)", "_____no_output_____" ], [ "best_ii=np.argmax(np.mean(lablab==test_dataset_y.reshape([-1,1]),axis=0))", "_____no_output_____" ], [ "np.mean(ii==best_ii)", "_____no_output_____" ], [ "np.mean(np.any(lablab==test_dataset_y.reshape([-1,1]),axis=1))", "_____no_output_____" ], [ "best_ent=np.min(ent,axis=1)", "_____no_output_____" ], [ "_=plt.hist(best_ent,bins=20)", "_____no_output_____" ], [ "_=plt.hist(best_ent[best_lbl!=test_dataset_y],bins=20)", "_____no_output_____" ], [ "_=plt.hist(best_ent[best_lbl==test_dataset_y],bins=20)", "_____no_output_____" ], [ "super_pred=np.sum(val_pred_pred,axis=0)", "_____no_output_____" ], [ "super_label=np.argmax(super_pred,axis=1)", "_____no_output_____" ], [ "np.mean(super_label==test_dataset_y)", "_____no_output_____" ], [ "super_label.shape", "_____no_output_____" ], [ "with open('committee103s5_traj_30.pkl','wb') as f:\n pickle.dump(trajectories,f)", "_____no_output_____" ], [ "def super_pred_fun(pred,T=1):\n logits = np.log(pred)\n pred_T = np.exp(1./T*logits)\n pred_T = pred_T/np.sum(pred_T,axis=-1)[...,np.newaxis]\n super_pred=np.sum(pred_T,axis=0)\n return super_pred", "_____no_output_____" ], [ "super_pred = super_pred_fun(train_pred_pred)", "_____no_output_____" ], [ "super_pred = super_pred_fun(val_pred_pred,T=1000)\nsuper_label=np.argmax(super_pred,axis=1)\nprint(np.mean(super_label==test_dataset_y))", "0.936\n" ], [ "np.linspace(0.1,5.0,100)", "_____no_output_____" ], [ "super_pred = super_pred_fun(val_pred_pred[:15],T=1000)\nsuper_label=np.argmax(super_pred,axis=1)\nprint(np.mean(super_label==test_dataset_y))", "0.9356\n" ], [ "super_pred = super_pred_fun(val_pred_pred[:5],T=1000)\nsuper_label=np.argmax(super_pred,axis=1)\nprint(np.mean(super_label==test_dataset_y))", "0.9194\n" ], [ "super_pred = super_pred_fun(val_pred_pred[:2],T=1000)\nsuper_label=np.argmax(super_pred,axis=1)\nprint(np.mean(super_label==test_dataset_y))", "0.8702\n" ], [ "# x = np.linspace(0, 2*np.pi, 64)\n# y = np.cos(x) \n\n# pl.figure()\n# pl.plot(x,y)\n\nn = hp.num_trials\n# colors = plt.cm.jet(accuracies)\ncolors = plt.cm.jet((accuracies-np.min(accuracies))/(np.max(accuracies)-np.min(accuracies)))\n# \nfor trial in range(hp.num_trials):\n plt.plot(trajectories[trial][:,0],trajectories[trial][:,1], color=colors[trial])\n# plt.colorbar()", "_____no_output_____" ], [ "colors = plt.cm.jet((accuracies-np.min(accuracies))/(np.max(accuracies)-np.min(accuracies)))", "_____no_output_____" ], [ "n = hp.num_trials\n# colors = plt.cm.jet(accuracies)\ncolors = plt.cm.RdYlGn((accuracies-np.min(accuracies))/(np.max(accuracies)-np.min(accuracies)))\n# \nfor trial in range(hp.num_trials):\n plt.plot(trajectories[trial][:,0],trajectories[trial][:,1], color=colors[trial],linewidth=3)", "_____no_output_____" ], [ "plt.cm.jet(1.0)", "_____no_output_____" ], [ "n_lines = hp.num_trials\nx = np.arange(100)\n\nyint = np.arange(0, n_lines*10, 10)\nys = np.array([x + b for b in yint])\nxs = np.array([x for i in range(n_lines)]) # could also use np.tile\n\ncolors = np.arange(n_lines)\n\nfig, ax = plt.subplots()\nlc = multiline(xs, ys, yint, cmap='bwr', lw=2)\n\naxcb = fig.colorbar(lc)\naxcb.set_label('Y-intercept')\nax.set_title('Line Collection with mapped colors')", "_____no_output_____" ], [ "# Set the input shape\ninput_shape = (300,)\n# print(f'Feature shape: {input_shape}')\n\n# Create the model\nmodel = keras.Sequential()\nmodel.add(keras.layers.Dense(300, input_shape=input_shape, activation='relu'))\nmodel.add(keras.layers.Dropout(0.4))\nmodel.add(keras.layers.Dense(100, activation='relu'))\nmodel.add(keras.layers.Dropout(0.4))\nmodel.add(keras.layers.Dense(50, activation='relu'))\nmodel.add(keras.layers.Dropout(0.2))\nmodel.add(keras.layers.Dense(10, activation='softmax'))\n\n# Configure the model and start training\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(np.transpose(train_pred_pred,[1,2,0]).reshape([-1,300]), train_dataset_y.astype(int), epochs=100, batch_size=250, verbose=1, validation_split=0.2)\n", "Train on 44000 samples, validate on 11000 samples\nEpoch 1/100\n44000/44000 [==============================] - 3s 70us/sample - loss: 0.4232 - acc: 0.8942 - val_loss: 0.1964 - val_acc: 0.9452\nEpoch 2/100\n44000/44000 [==============================] - 2s 35us/sample - loss: 0.2114 - acc: 0.9469 - val_loss: 0.1776 - val_acc: 0.9505\nEpoch 3/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.1877 - acc: 0.9527 - val_loss: 0.1606 - val_acc: 0.9550\nEpoch 4/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.1689 - acc: 0.9565 - val_loss: 0.1568 - val_acc: 0.9555\nEpoch 5/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.1569 - acc: 0.9593 - val_loss: 0.1511 - val_acc: 0.9566\nEpoch 6/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.1501 - acc: 0.9604 - val_loss: 0.1464 - val_acc: 0.9574\nEpoch 7/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.1454 - acc: 0.9620 - val_loss: 0.1456 - val_acc: 0.9585\nEpoch 8/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.1359 - acc: 0.9641 - val_loss: 0.1461 - val_acc: 0.9588\nEpoch 9/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.1297 - acc: 0.9655 - val_loss: 0.1421 - val_acc: 0.9605\nEpoch 10/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.1236 - acc: 0.9675 - val_loss: 0.1433 - val_acc: 0.9611\nEpoch 11/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.1169 - acc: 0.9678 - val_loss: 0.1495 - val_acc: 0.9598\nEpoch 12/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.1130 - acc: 0.9689 - val_loss: 0.1430 - val_acc: 0.9610\nEpoch 13/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.1085 - acc: 0.9711 - val_loss: 0.1425 - val_acc: 0.9597\nEpoch 14/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.1029 - acc: 0.9716 - val_loss: 0.1395 - val_acc: 0.9612\nEpoch 15/100\n44000/44000 [==============================] - 2s 35us/sample - loss: 0.1003 - acc: 0.9733 - val_loss: 0.1419 - val_acc: 0.9602\nEpoch 16/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0973 - acc: 0.9736 - val_loss: 0.1469 - val_acc: 0.9600\nEpoch 17/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.0909 - acc: 0.9749 - val_loss: 0.1454 - val_acc: 0.9605\nEpoch 18/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0887 - acc: 0.9756 - val_loss: 0.1458 - val_acc: 0.9607\nEpoch 19/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0853 - acc: 0.9763 - val_loss: 0.1515 - val_acc: 0.9603\nEpoch 20/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0811 - acc: 0.9772 - val_loss: 0.1507 - val_acc: 0.9625\nEpoch 21/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0802 - acc: 0.9774 - val_loss: 0.1494 - val_acc: 0.9626\nEpoch 22/100\n44000/44000 [==============================] - 2s 35us/sample - loss: 0.0734 - acc: 0.9797 - val_loss: 0.1572 - val_acc: 0.9600\nEpoch 23/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0738 - acc: 0.9798 - val_loss: 0.1596 - val_acc: 0.9593\nEpoch 24/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0711 - acc: 0.9802 - val_loss: 0.1576 - val_acc: 0.9622\nEpoch 25/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0668 - acc: 0.9807 - val_loss: 0.1622 - val_acc: 0.9615\nEpoch 26/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0650 - acc: 0.9822 - val_loss: 0.1648 - val_acc: 0.9591\nEpoch 27/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0621 - acc: 0.9830 - val_loss: 0.1601 - val_acc: 0.9618\nEpoch 28/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0598 - acc: 0.9831 - val_loss: 0.1618 - val_acc: 0.9596\nEpoch 29/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0590 - acc: 0.9844 - val_loss: 0.1646 - val_acc: 0.9605\nEpoch 30/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0558 - acc: 0.9850 - val_loss: 0.1655 - val_acc: 0.9605\nEpoch 31/100\n44000/44000 [==============================] - 2s 35us/sample - loss: 0.0585 - acc: 0.9834 - val_loss: 0.1674 - val_acc: 0.9604\nEpoch 32/100\n44000/44000 [==============================] - 2s 35us/sample - loss: 0.0527 - acc: 0.9856 - val_loss: 0.1667 - val_acc: 0.9604\nEpoch 33/100\n44000/44000 [==============================] - 2s 35us/sample - loss: 0.0523 - acc: 0.9856 - val_loss: 0.1681 - val_acc: 0.9623\nEpoch 34/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0499 - acc: 0.9862 - val_loss: 0.1754 - val_acc: 0.9617\nEpoch 35/100\n44000/44000 [==============================] - 2s 35us/sample - loss: 0.0515 - acc: 0.9854 - val_loss: 0.1671 - val_acc: 0.9609\nEpoch 36/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.0447 - acc: 0.9874 - val_loss: 0.1833 - val_acc: 0.9612\nEpoch 37/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0502 - acc: 0.9853 - val_loss: 0.1754 - val_acc: 0.9623\nEpoch 38/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.0457 - acc: 0.9871 - val_loss: 0.1818 - val_acc: 0.9610\nEpoch 39/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0456 - acc: 0.9872 - val_loss: 0.1740 - val_acc: 0.9610\nEpoch 40/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.0409 - acc: 0.9887 - val_loss: 0.1887 - val_acc: 0.9599\nEpoch 41/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0441 - acc: 0.9879 - val_loss: 0.1784 - val_acc: 0.9605\nEpoch 42/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0417 - acc: 0.9879 - val_loss: 0.1806 - val_acc: 0.9605\nEpoch 43/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0418 - acc: 0.9881 - val_loss: 0.1897 - val_acc: 0.9604\nEpoch 44/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0390 - acc: 0.9888 - val_loss: 0.1849 - val_acc: 0.9609\nEpoch 45/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0378 - acc: 0.9895 - val_loss: 0.1865 - val_acc: 0.9606\nEpoch 46/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0412 - acc: 0.9880 - val_loss: 0.1839 - val_acc: 0.9600\nEpoch 47/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0366 - acc: 0.9899 - val_loss: 0.1920 - val_acc: 0.9608\nEpoch 48/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0370 - acc: 0.9896 - val_loss: 0.1867 - val_acc: 0.9603\nEpoch 49/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0374 - acc: 0.9890 - val_loss: 0.1990 - val_acc: 0.9611\nEpoch 50/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0352 - acc: 0.9898 - val_loss: 0.2035 - val_acc: 0.9612\nEpoch 51/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0340 - acc: 0.9903 - val_loss: 0.2028 - val_acc: 0.9600\nEpoch 52/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0375 - acc: 0.9895 - val_loss: 0.1923 - val_acc: 0.9591\nEpoch 53/100\n44000/44000 [==============================] - 2s 36us/sample - loss: 0.0334 - acc: 0.9902 - val_loss: 0.2010 - val_acc: 0.9605\nEpoch 54/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0349 - acc: 0.9896 - val_loss: 0.2002 - val_acc: 0.9595\nEpoch 55/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0334 - acc: 0.9903 - val_loss: 0.2063 - val_acc: 0.9611\nEpoch 56/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0337 - acc: 0.9904 - val_loss: 0.1959 - val_acc: 0.9609\nEpoch 57/100\n44000/44000 [==============================] - 2s 38us/sample - loss: 0.0316 - acc: 0.9914 - val_loss: 0.1966 - val_acc: 0.9605\nEpoch 58/100\n44000/44000 [==============================] - 2s 37us/sample - loss: 0.0319 - acc: 0.9908 - val_loss: 0.2037 - val_acc: 0.9605\n" ], [ "plt.hist(accuracies,bins=30)", "_____no_output_____" ], [ "for pred in np.array(val_pred_pred)[:,7,:]:\n plt.plot(pred)\n plt.xlabel('label')\n plt.ylabel('probability')", "_____no_output_____" ], [ "np.array(val_pred_pred[:,0,:])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01e836d090df6e298bd255ad94914eff61faf28
9,516
ipynb
Jupyter Notebook
Algorithms.ipynb
BeanHam/STA-663-Project
64e4b5ea11b937b3b8ef9e200ce5db0b7785663e
[ "MIT" ]
null
null
null
Algorithms.ipynb
BeanHam/STA-663-Project
64e4b5ea11b937b3b8ef9e200ce5db0b7785663e
[ "MIT" ]
null
null
null
Algorithms.ipynb
BeanHam/STA-663-Project
64e4b5ea11b937b3b8ef9e200ce5db0b7785663e
[ "MIT" ]
1
2019-12-19T17:32:59.000Z
2019-12-19T17:32:59.000Z
38.370968
118
0.476986
[ [ [ "### K-Means", "_____no_output_____" ] ], [ [ "class Kmeans:\n \"\"\"K-Means Clustering Algorithm\"\"\"\n \n def __init__(self, k, centers=None, cost=None,iter=None, labels=None, max_iter = 1000):\n \"\"\"Initialize Parameters\"\"\"\n \n self.max_iter = max_iter\n self.k = k\n self.centers = np.empty(1)\n self.cost = []\n self.iter = 1\n self.labels = np.empty(1)\n\n def calc_distances(self, data, centers, weights):\n \"\"\"Distance Matrix\"\"\"\n \n distance = pairwise_distances(data, centers)**2\n min_distance = np.min(distance, axis = 1)\n D = min_distance*weights\n return D \n \n def fit(self, data):\n \"\"\"Clustering Process\"\"\"\n \n ## Initial centers\n if type(data) == pd.DataFrame: data = data.values\n nrow = data.shape[0]\n index = np.random.choice(range(nrow), self.k, False)\n self.centers = data[index]\n \n while (self.iter <= self.max_iter):\n distance = pairwise_distances(data, self.centers)**2\n self.cost.append(sum(np.min(distance, axis=1)))\n self.labels = np.argmin(distance, axis=1)\n centers_new = np.array([np.mean(data[self.labels == i], axis=0) for i in np.unique(self.labels)])\n \n ## sanity check\n if(np.all(self.centers == centers_new)): break \n self.centers = centers_new\n self.iter += 1\n \n ## convergence check\n if (sum(np.min(pairwise_distances(data, self.centers)**2, axis=1)) != self.cost[-1]):\n warnings.warn(\"Algorithm Did Not Converge In {} Iterations\".format(self.max_iter))\n return self", "_____no_output_____" ] ], [ [ "### K-Means++", "_____no_output_____" ] ], [ [ "class Kmeanspp:\n \"\"\"K-Means++ Clustering Algorithm\"\"\"\n \n def __init__(self, k, centers=None, cost=None,iter=None, labels=None, max_iter = 1000):\n \"\"\"Initialize Parameters\"\"\"\n \n self.max_iter = max_iter\n self.k = k\n self.centers = np.empty(1)\n self.cost = []\n self.iter = 1\n self.labels = np.empty(1)\n\n def calc_distances(self, data, centers, weights):\n \"\"\"Distance Matrix\"\"\"\n \n distance = pairwise_distances(data, centers)**2\n min_distance = np.min(distance, axis = 1)\n D = min_distance*weights\n return D\n \n def initial_centers_Kmeansapp(self, data, k, weights):\n \"\"\"Initialize centers for K-Means++\"\"\"\n \n centers = []\n centers.append(random.choice(data))\n while(len(centers) < k): \n distances = self.calc_distances(data, centers, weights)\n prob = distances/sum(distances)\n c = np.random.choice(range(data.shape[0]), 1, p=prob)\n centers.append(data[c[0]])\n return centers\n \n\n def fit(self, data, weights=None):\n \"\"\"Clustering Process\"\"\"\n \n if weights is None: weights = np.ones(len(data))\n if type(data) == pd.DataFrame: data=data.values\n nrow = data.shape[0]\n self.centers = self.initial_centers_Kmeansapp(data, self.k, weights)\n \n while (self.iter <= self.max_iter):\n distance = pairwise_distances(data, self.centers)**2\n self.cost.append(sum(np.min(distance, axis=1)))\n self.labels = np.argmin(distance, axis=1)\n centers_new = np.array([np.mean(data[self.labels == i], axis=0) for i in np.unique(self.labels)])\n \n ## sanity check\n if(np.all(self.centers == centers_new)): break \n self.centers = centers_new\n self.iter += 1\n \n ## convergence check\n if (sum(np.min(pairwise_distances(data, self.centers)**2, axis=1)) != self.cost[-1]):\n warnings.warn(\"Algorithm Did Not Converge In {} Iterations\".format(self.max_iter))\n return self", "_____no_output_____" ] ], [ [ "### K-Meansll", "_____no_output_____" ] ], [ [ "class Kmeansll:\n \"\"\"K-Meansll Clustering Algorithm\"\"\"\n \n def __init__(self, k, omega, centers=None, cost=None,iter=None, labels=None, max_iter = 1000):\n \"\"\"Initialize Parameters\"\"\"\n \n self.max_iter = max_iter\n self.k = k\n self.omega = omega\n self.centers = np.empty(1)\n self.cost = []\n self.iter = 1\n self.labels = np.empty(1)\n \n def calc_weight(self, data, centers):\n \"\"\"Weight Calculation\"\"\"\n \n l = len(centers)\n distance = pairwise_distances(data, centers)\n labels = np.argmin(distance, axis=1)\n weights = [sum(labels == i) for i in range(l)]\n return (weights/sum(weights))\n\n def calc_distances(self, data, centers, weights):\n \"\"\"Distance Matrix\"\"\"\n \n distance = pairwise_distances(data, centers)**2\n min_distance = np.min(distance, axis = 1)\n D = min_distance*weights\n return D\n \n def initial_centers_Kmeansll(self, data, k, omega, weights): \n \"\"\"Initialize Centers for K-Meansll\"\"\"\n \n centers = []\n centers.append(random.choice(data))\n phi = np.int(np.round(np.log(sum(self.calc_distances(data, centers, weights)))))\n l = k*omega ## oversampling factor\n for i in range(phi):\n dist = self.calc_distances(data, centers, weights)\n prob = l*dist/sum(dist)\n for i in range(len(prob)):\n if prob[i] > np.random.uniform():\n centers.append(data[i])\n centers = np.array(centers)\n recluster_weight = self.calc_weight(data, centers)\n reclusters = kmeanspp.Kmeanspp(k).fit(centers, recluster_weight).labels\n initial_centers = []\n for i in np.unique(reclusters):\n initial_centers.append(np.mean(centers[reclusters == i], axis = 0))\n return initial_centers\n \n \n def fit(self, data, weights=None):\n \"\"\"Clustering Process\"\"\"\n \n if weights is None: weights = np.ones(len(data))\n if type(data) == pd.DataFrame: data=data.values\n nrow = data.shape[0]\n self.centers = self.initial_centers_Kmeansll(data, self.k, self.omega, weights)\n while (self.iter <= self.max_iter):\n distance = pairwise_distances(data, self.centers)**2\n self.cost.append(sum(np.min(distance, axis=1)))\n self.labels = np.argmin(distance, axis=1)\n centers_new = np.array([np.mean(data[self.labels == i], axis=0) for i in np.unique(self.labels)])\n \n ## sanity check\n if(np.all(self.centers == centers_new)): break \n self.centers = centers_new\n self.iter += 1\n \n ## convergence check\n if (sum(np.min(pairwise_distances(data, self.centers)**2, axis=1)) != self.cost[-1]):\n warnings.warn(\"Algorithm Did Not Converge In {} Iterations\".format(self.max_iter))\n return self", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01e89bc3a5b15812cc76cd2a443a93cf73dfd31
409,334
ipynb
Jupyter Notebook
Poster/2021-03-11_small_multiples_DF.ipynb
ph1001/Data_Visualisation_Project_Group_I
6ae4ba6ede9a5b827c9a6c0617c206cc352c512b
[ "MIT" ]
null
null
null
Poster/2021-03-11_small_multiples_DF.ipynb
ph1001/Data_Visualisation_Project_Group_I
6ae4ba6ede9a5b827c9a6c0617c206cc352c512b
[ "MIT" ]
null
null
null
Poster/2021-03-11_small_multiples_DF.ipynb
ph1001/Data_Visualisation_Project_Group_I
6ae4ba6ede9a5b827c9a6c0617c206cc352c512b
[ "MIT" ]
null
null
null
48.846539
163,940
0.554254
[ [ [ "import os\nimport pandas as pd\nimport numpy as np\nimport plotly.graph_objects as go\nfrom sklearn.preprocessing import MinMaxScaler\nfrom plotly.subplots import make_subplots", "_____no_output_____" ], [ "df_dict = {}\nfor path in os.listdir('Data/FINAL INDEX'):\n var = path.split('.')[0] \n vars()[var] = pd.read_csv('Data/FINAL INDEX/' + path, thousands = ',')\n df_dict[var] = vars()[var]", "_____no_output_____" ], [ "for df_name in df_dict.keys():\n df_dict[df_name]['Date'] = pd.to_datetime(df_dict[df_name]['Date'])", "_____no_output_____" ], [ "dj_pharma.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 93 entries, 0 to 92\nData columns (total 7 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Date 93 non-null datetime64[ns]\n 1 Price 93 non-null float64 \n 2 Open 93 non-null float64 \n 3 High 93 non-null float64 \n 4 Low 93 non-null float64 \n 5 Vol. 93 non-null object \n 6 Change % 93 non-null object \ndtypes: datetime64[ns](1), float64(4), object(2)\nmemory usage: 5.2+ KB\n" ], [ "scatters = [[\n dict(\n type=\"scatter\",\n x=df_dict[df_name][\"Date\"].sort_values(),\n y=df_dict[df_name][\"Price\"].map(lambda x : np.log(x)), # Since we just want to look at a trend use the log values \n name=None,\n line_color=\"rgba(217, 217, 217, 1.0)\", # Same color for all the graphics in the plot except for the highlighted\n )\n if df_name != df_name_main\n else dict(\n type=\"scatter\",\n x=df_dict[df_name][\"Date\"].sort_values(),\n y=df_dict[df_name][\"Price\"].map(lambda x : np.log(x)),\n name=False,\n line_color=\"rgba(156, 165, 196, 1.0)\", # Highlight color\n )\n for df_name in df_dict\n \n] for df_name_main in df_dict]", "_____no_output_____" ], [ "# titles = [df_name.split('_')[1] for df_name in df_dict]\n\ntitles = ['Financials',\n 'Pharmaceuticals',\n 'Retail',\n 'Technology',\n 'Telecommunications',\n 'Travel']\n\nplot = make_subplots(rows=2, \n cols=3,\n subplot_titles=titles,\n specs=[ [dict(type='xy', rowspan=1), dict(type='xy', rowspan=1), dict(type='xy', rowspan=1)],\n [dict(type='xy', rowspan=1), dict(type='xy', rowspan=1), dict(type='xy', rowspan=1)]])\n\ni = 0\nr = 1\nc = 1\nwhile True:\n for j in range(len(scatters[i])):\n plot.add_trace(scatters[i][j], row=r, col = c)\n i += 1\n c += 1\n if c == 4 and r == 1:\n r += 1\n c = 1\n elif c == 4 and r == 2:\n break\n\n# Define the new layout\nlayout_scatter =dict(title=dict(text='', font=dict(size=12), x=0.5),\n plot_bgcolor='rgba(0,0,0,0)',\n# paper_bgcolor='rgba(0,0,0,0)',\n showlegend = False,\n )\n\nplot.update_yaxes(title_text=\"Stock Value\", row=1, col=1)\nplot.update_yaxes(title_text=\"Stock Value\", row=2, col=1)\nplot.update_yaxes(visible = False, row=1, col=2)\nplot.update_yaxes(visible = False, row=2, col=2)\nplot.update_yaxes(visible = False, row=1, col=3)\nplot.update_yaxes(visible = False, row=2, col=3)\n\nplot.update_xaxes(title_text=\"Date\", row=2, col=1)\nplot.update_xaxes(title_text=\"Date\", row=2, col=2)\nplot.update_xaxes(title_text=\"Date\", row=2, col=3)\nplot.update_xaxes(visible = False, row=1, col=1)\nplot.update_xaxes(visible = False, row=1, col=2)\nplot.update_xaxes(visible = False, row=1, col=3)\n\n\nplot.update_layout(layout_scatter,\n height=600,\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)'\n)\n \nplot.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
d01e8c98e8db66578bb86274d546bac4e0733e48
76,741
ipynb
Jupyter Notebook
cn/examen/Examen - Proba practică.ipynb
GabrielMajeri/teme-fmi
b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e
[ "MIT" ]
54
2020-03-17T10:00:15.000Z
2022-03-31T06:40:30.000Z
cn/examen/Examen - Proba practică.ipynb
GabrielMajeri/teme-fmi
b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e
[ "MIT" ]
null
null
null
cn/examen/Examen - Proba practică.ipynb
GabrielMajeri/teme-fmi
b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e
[ "MIT" ]
59
2020-01-22T11:39:59.000Z
2022-03-28T00:19:06.000Z
206.849057
37,172
0.907025
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "# 1.", "_____no_output_____" ], [ "## a)", "_____no_output_____" ] ], [ [ "def simetrica(A):\n \"Verifică dacă matricea A este simetrică\"\n return np.all(A == A.T)\n\ndef pozitiv_definita(A):\n \"Verifică dacă matricea A este pozitiv definită\"\n\n for i in range(1, len(A) + 1):\n d_minor = np.linalg.det(A[:i, :i])\n if d_minor < 0:\n return False\n return True\n\ndef fact_ll(A):\n # Pasul 1\n if not simetrica(A):\n raise Exception(\"Nu este simetrica\")\n if not pozitiv_definita(A):\n raise Exception(\"Nu este pozitiv definită\")\n \n N = A.shape[0]\n\n # Pasul 2\n S = A.copy()\n L = np.zeros((N, N))\n\n # Pasul 3\n for i in range(N):\n # Actualizez coloana i din matricea L\n L[:, i] = S[:, i] / np.sqrt(S[i, i])\n\n # Calculez noul complement Schur\n S_21 = S[i + 1:, i]\n \n S_nou = np.eye(N)\n S_nou[i + 1:, i + 1:] = S[i + 1:, i + 1:] - np.outer(S_21, S_21.T) / S[i, i]\n\n S = S_nou\n \n # Returnez matricea calculată\n return L", "_____no_output_____" ], [ "A = np.array([\n [25, 15, -5],\n [15, 18, 0],\n [-5, 0, 11]\n], dtype=np.float64)\n\nL = fact_ll(A)\nprint(\"L este:\")\nprint(L)\nprint(\"Verificare:\")\nprint(L @ L.T)", "L este:\n[[ 5. 0. 0.]\n [ 3. 3. 0.]\n [-1. 1. 3.]]\nVerificare:\n[[25. 15. -5.]\n [15. 18. 0.]\n [-5. 0. 11.]]\n" ] ], [ [ "## b)", "_____no_output_____" ] ], [ [ "b = np.array([1, 2, 3], dtype=np.float64)\ny = np.zeros(3)\nx = np.zeros(3)\n\n# Substituție ascendentă\nfor i in range(0, 3):\n coefs = L[i, :i + 1]\n values = y[:i + 1]\n\n y[i] = (b[i] - coefs @ values) / L[i, i]\n\nL_t = L.T\n \n# Substituție descendentă\nfor i in range(2, -1, -1):\n coefs = L_t[i, i + 1:]\n values = x[i + 1:]\n\n x[i] = (y[i] - coefs @ values) / L_t[i, i]\n\nprint(\"x =\", x)\nprint()\nprint(\"Verificare: A @ x =\", A @ x)", "x = [0.06814815 0.05432099 0.3037037 ]\n\nVerificare: A @ x = [1. 2. 3.]\n" ] ], [ [ "## 2.", "_____no_output_____" ] ], [ [ "def step(x, f, df):\n \"Calculează un pas din metoda Newton-Rhapson.\"\n return x - f(x) / df(x)\n\ndef newton_rhapson(f, df, x0, eps):\n \"Determină o soluție a f(x) = 0 plecând de la x_0\"\n # Primul punct este cel primit ca parametru\n prev_x = x0\n \n # Execut o iterație\n x = step(x0, f, df)\n\n N = 1\n while True:\n # Verific condiția de oprire\n if abs(x - prev_x) / abs(prev_x) < eps:\n break\n\n # Execut încă un pas\n prev_x = x\n x = step(x, f, df)\n \n # Contorizez numărul de iterații\n N += 1\n\n return x, N", "_____no_output_____" ] ], [ [ "Funcția dată este\n$$\nf(x) = x^3 + 3 x^2 - 18 x - 40\n$$\niar derivatele ei sunt\n$$\nf'(x) = 3x^2 + 6 x - 18\n$$\n\n$$\nf''(x) = 6x + 6\n$$", "_____no_output_____" ] ], [ [ "f = lambda x: (x ** 3) + 3 * (x ** 2) - 18 * x - 40\ndf = lambda x: 3 * (x ** 2) + 6 * x - 18\nddf = lambda x: 6 * x + 6\n\nleft = -8\nright = +8\nx_grafic = np.linspace(left, right, 500)", "_____no_output_____" ], [ "def set_spines(ax):\n # Mut axele de coordonate\n ax.spines['bottom'].set_position('zero')\n ax.spines['top'].set_color('none')\n ax.spines['left'].set_position('zero')\n ax.spines['right'].set_color('none')", "_____no_output_____" ], [ "fig, ax = plt.subplots(dpi=120)\n\nset_spines(ax)\n\nplt.plot(x_grafic, f(x_grafic), label='$f$')\nplt.plot(x_grafic, df(x_grafic), label=\"$f'$\")\nplt.plot(x_grafic, ddf(x_grafic), label=\"$f''$\")\nplt.legend()\n\nplt.show()", "_____no_output_____" ] ], [ [ "Alegem subintervale astfel încât $f(a) f(b) < 0$:\n- $[-8, -4]$\n- $[-4, 0]$\n- $[2, 6]$\n\nPentru fiecare dintre acestea, căutăm un punct $x_0$ astfel încât $f(x_0) f''(x_0) > 0$:\n- $-6$\n- $-1$\n- $5$", "_____no_output_____" ] ], [ [ "eps = 1e-3\n\nx1, _ = newton_rhapson(f, df, -6, eps)\nx2, _ = newton_rhapson(f, df, -1, eps)\nx3, _ = newton_rhapson(f, df, 5, eps)", "_____no_output_____" ], [ "fig, ax = plt.subplots(dpi=120)\nplt.suptitle('Soluțiile lui $f(x) = 0$')\n\nset_spines(ax)\n\nplt.plot(x_grafic, f(x_grafic))\nplt.scatter(x1, 0)\nplt.scatter(x2, 0)\nplt.scatter(x3, 0)\n\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d01e906e9e5e0dc8822aba81b67f96a6ffc56081
17,869
ipynb
Jupyter Notebook
_notebooks/2020-12-26-Array-Visualiser.ipynb
logicatcore/scratchpad
0460fff340a893a8245ba684a1b96825228e3d1d
[ "Apache-2.0" ]
1
2022-03-07T08:44:12.000Z
2022-03-07T08:44:12.000Z
_notebooks/2020-12-26-Array-Visualiser.ipynb
logicatcore/scratchpad
0460fff340a893a8245ba684a1b96825228e3d1d
[ "Apache-2.0" ]
3
2021-05-20T23:03:11.000Z
2021-09-28T05:48:07.000Z
_notebooks/2020-12-26-Array-Visualiser.ipynb
logicatcore/scratchpad
0460fff340a893a8245ba684a1b96825228e3d1d
[ "Apache-2.0" ]
null
null
null
41.363426
404
0.533382
[ [ [ "# Input data representation as 2D array of 3D blocks\n> An easy way to represent input data to neural networks or any other machine learning algorithm in the form of 2D array of 3D-blocks\n\n- toc: false\n- branch: master\n- badges: true\n- comments: true\n- categories: [machine learning, jupyter, graphviz]\n- image: images/array_visualiser/thumbnail.png\n- search_exclude: false", "_____no_output_____" ], [ "---\nOften while working with machine learning algorithms the developer has a good picture of how the input data looks like apart from knowing what the input data is. Also, most of the times the input data is usually represented or decribed with array terminology. Hence, this particular post is one such attempt to create simple 2D representations of 3D-blocks symbolising the arrays used for input.\n\n[Graphviz](https://graphviz.readthedocs.io/en/stable/) a highly versatile graphing library that creates graphs based on DOT language is used to create the 2D array representation of 3D blocks with annotation and color uniformity to create quick and concise graphs/pictures for good explanations of input data used in various machine learning/deep learning algorithms.\n\nIn what follows is a script to create the 2D array representation og 3D blocks mainly intented for time-series data. The script facilitates some features which include-\n* Starting at time instant 0 or -1\n* counting backwards i.e. t-4 -> t-3 -> t-2 -> t-1 -> t-0 or counting forwards t-0 -> t-1 -> t-2 -> t-3 -> t-4 -> t-5", "_____no_output_____" ], [ "### Imports and global constants", "_____no_output_____" ] ], [ [ "import graphviz as G # to create the required graphs\nimport random # to generate random hex codes for colors\n\nFORWARDS = True # to visualise array from left to right\nBACKWARDS = False # to visualise array from right to left", "_____no_output_____" ] ], [ [ "### Properties of 2D representation of 3D array blocks\nMain features/properties of the array visualisation needed are defined gere before actually creating the graph/picture.\n1) Number of Rows: similar to rows in a matrix where each each row corresponds to one particular data type with data across different time instants arranged in columns\n\n2) Blocks: which corresponds to the number of time instants in each row (jagged arrays can also be graphed)\n\n3) Prefix: the annotation used to annotate each 3D block in the 2D array representation", "_____no_output_____" ] ], [ [ "ROW_NUMS = [1, 2] # Layer numbers corresponding to the number of rows of array data (must be contiguous)\nBLOCKS = [3, 3] # number of data fields in each row i.e., columns in each row\n\ndiff = [x - ROW_NUMS[i] for i, x in enumerate(ROW_NUMS[1:])]\nassert diff == [1]*(len(ROW_NUMS) - 1), '\"layer_num\" should contain contiguous numbers only'\nassert len(ROW_NUMS) == len(BLOCKS), \"'cells' list and 'layer_num' list should contain same number of entries\"\n\ndirection = BACKWARDS # control the direction of countdown of timesteps \nINCLUDE_ZERO = True # for time series based data\nSTART_AT = 0 if INCLUDE_ZERO else 1\n\n# names = [['Softmax\\nprobabilities', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10'],['', ' +', ' +', ' +', ' +', ' +', ' +'],['GMM\\nprobabilities', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6']]\n\n# the trick to adding symbols like the \"partial(dou)\" i.e. '∂' is to write these symbols in a markdown cell using the $\\partial$ utilising the mathjax support and\n# copying the content after being rendered and paste in the code as a string wherever needed\nprefix = ['∂(i)-', '∂(v)-']", "_____no_output_____" ], [ "r = lambda: random.randint(0,255) # to generate random colors for each row \n\n# intantiate a directed graph with intial properties\ndot = G.Digraph(comment='Matrix', \n graph_attr={'nodesep':'0.02', 'ranksep':'0.02', 'bgcolor':'transparent'},\n node_attr={'shape':'box3d','fixedsize':'true', 'width':'1.1'})\n\nfor row_no in ROW_NUMS:\n if row_no != 1:\n dot.edge(str(row_no-1)+str(START_AT), str(row_no)+str(START_AT), style='invis') # invisible edges to contrain layout\n with dot.subgraph() as sg:\n sg.attr(rank='same')\n color = '#{:02x}{:02x}{:02x}'.format(r(),r(),r())\n for block_no in range(START_AT, BLOCKS[row_no-1]+START_AT):\n if direction:\n sg.node(str(row_no)+str(block_no), 't-'+str(block_no), style='filled', fillcolor=color)\n else:\n if START_AT == 0:\n sg.node(str(row_no)+str(block_no), prefix[row_no-1]+str(BLOCKS[row_no-1]-block_no-1), style='filled', fillcolor=color)\n else:\n sg.node(str(row_no)+str(block_no), prefix[row_no-1]+str(BLOCKS[row_no-1]-block_no-1), style='filled', fillcolor=color) ", "_____no_output_____" ] ], [ [ "### Render", "_____no_output_____" ] ], [ [ "dot", "_____no_output_____" ] ], [ [ "### Save/Export", "_____no_output_____" ] ], [ [ "# dot.format = 'jpeg' # or PDF, SVG, JPEG, PNG, etc. ", "_____no_output_____" ], [ "# to save the file, pdf is default\ndot.render('./lstm_input')", "_____no_output_____" ] ], [ [ "### Additional script to just show the breakdown of train-test data of the dataset being used", "_____no_output_____" ] ], [ [ "import random\nr = lambda: random.randint(0,255) # to generate random colors for each row ", "_____no_output_____" ], [ "folders = G.Digraph(node_attr={'style':'filled'}, graph_attr={'style':'invis', 'rankdir':'LR'},edge_attr={'color':'black', 'arrowsize':'.2'})", "_____no_output_____" ], [ "color = '#{:02x}{:02x}{:02x}'.format(r(),r(),r())\nwith folders.subgraph(name='cluster0') as f:\n f.node('root', 'Dataset \\n x2000', shape='folder', fillcolor=color)", "_____no_output_____" ], [ "color = '#{:02x}{:02x}{:02x}'.format(r(),r(),r())\nwith folders.subgraph(name='cluster1') as f:\n f.node('train', 'Train \\n 1800', shape='note', fillcolor=color)\n f.node('test', 'Test \\n x200', shape='note', fillcolor=color)", "_____no_output_____" ], [ "folders.edge('root', 'train')\nfolders.edge('root', 'test')", "_____no_output_____" ], [ "folders", "_____no_output_____" ], [ "folders.render('./dataset')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d01e9e6e267f0396dc454a608390a983297b0dcc
361,679
ipynb
Jupyter Notebook
jupman-tests.ipynb
DavidLeoni/iep
c8b62d0e896003b58ab9cd45265bffce5c8fddeb
[ "Apache-2.0" ]
null
null
null
jupman-tests.ipynb
DavidLeoni/iep
c8b62d0e896003b58ab9cd45265bffce5c8fddeb
[ "Apache-2.0" ]
null
null
null
jupman-tests.ipynb
DavidLeoni/iep
c8b62d0e896003b58ab9cd45265bffce5c8fddeb
[ "Apache-2.0" ]
null
null
null
157.388599
202,812
0.511644
[ [ [ "import jupman;\njupman.init()", "_____no_output_____" ] ], [ [ "# Jupman Tests\n\nTests and cornercases.\n\nThe page Title has one sharp, the Sections always have two sharps.\n\n## Sezione 1\n\nbla bla \n\n## Sezione 2\n\nSubsections always have three sharps\n\n### Subsection 1\nbla bla \n\n### Subsection 2\nbla bla \n", "_____no_output_____" ], [ "## Quotes", "_____no_output_____" ], [ "> I'm quoted with **greater than** symbol\n> on multiple lines\n> Am I readable?", "_____no_output_____" ], [ " I'm quoted with **spaces** \n on multiple lines\n Am I readable?", "_____no_output_____" ], [ "## Download links\n\nFiles manually put in `_static` : \n\n* Download [trial.odt](_static/trial.odt)\n* Download [trial.pdf](_static/trial.pdf)\n\nFiles in arbitrary folder position : \n\n* Download [requirements.txt](requirements.txt)\n\nNOTE: download links are messy, [see issue 8](https://github.com/DavidLeoni/jupman/issues/8)\n\n\n", "_____no_output_____" ], [ "## Info/Warning Boxes\n\nUntil there is an info/warning extension for Markdown/CommonMark (see this issue), such boxes can be created by using HTML <div> elements like this:", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n\n**Note:** This is an info!\n\n</div>", "_____no_output_____" ], [ "<div class=\"alert alert-warning\">\n\n**Note:** This is a warn!\n\n</div>", "_____no_output_____" ], [ "For this to work reliably, you should obey the following guidelines:\n\n* The class attribute has to be either \"alert alert-info\" or \"alert alert-warning\", other values will not be converted correctly.\n* No further attributes are allowed.\n* For compatibility with CommonMark, you should add an empty line between the <div> start tag and the beginning of the content.\n", "_____no_output_____" ], [ "\n## Math\n\nFor math stuff, [see npshpinx docs](https://nbsphinx.readthedocs.io/en/0.2.14/markdown-cells.html#Equations)\n\nHere we put just some equation to show it behaves fine in Jupman\n\nThis is infinity: $\\infty$ ", "_____no_output_____" ], [ "## Unicode \n\nUnicode characters should display an HTML, but with latex you might have problems, and need to manually map characters in conf.py\n\n\nYou should see a star in a black circle: ✪ \n\nYou should see a check: ✓\n\ntable characters: │ ├ └ ─", "_____no_output_____" ], [ "## Image\n\n### SVG Images\n\nSVG images work in notebook, but here it is commented since it breaks Latex, [see issue](https://github.com/DavidLeoni/jupman/issues/1)\n\n```\n![An image](img/cc-by.svg)\n```\n\nThis one also doesn't works (and shows ugly code in the notebook anyway)\n\n```\nfrom IPython.display import SVG\nSVG(filename='img/cc-by.svg')\n```\n", "_____no_output_____" ], [ "### PNG Images\n\n![A PNG image](_static/img/notebook_icon.png)", "_____no_output_____" ], [ "### Inline images - pure markdown", "_____no_output_____" ], [ " Bla ![A PNG image](_static/img/notebook_icon.png) bli blo", "_____no_output_____" ], [ "Bla ![A PNG image](_static/img/notebook_icon.png) bli blo", "_____no_output_____" ], [ "### Inline images - markdown and img", "_____no_output_____" ], [ " bla <img style=\"display:inline\" src=\"_static/img/notebook_icon.png\"> bli blo", "_____no_output_____" ], [ "\nbla <img style=\"display:inline !important\" src=\"_static/img/notebook_icon.png\"> bli blo", "_____no_output_____" ], [ "### Img class\n\nIf we pass a class, it will to be present in the website:\n\n <img class=\"jupman-inline-img\" src=\"_static/img/notebook_icon.png\">\n \nThis <img class=\"jupman-inline-img\" src=\"_static/img/notebook_icon.png\"> should be inline", "_____no_output_____" ], [ "## Expressions list\n\nHighlighting **does** work both in Jupyter and Sphinx\n\nThree quotes, multiple lines - Careful: put **exactly 4 spaces** indentation\n\n1. ```python \n [2,3,1] != \"[2,3,1]\"\n ```\n1. ```python \n [4,8,12] == [2*2,\"4*2\",6*2]\n ```\n1. ```python \n [][:] == []\n ```", "_____no_output_____" ], [ "Three quotes, multiple lines, more compact - works in Jupyter, **doesn't** in Sphinx\n\n1. ```python \n [2,3,1] != \"[2,3,1]\"```\n1. ```python \n [4,8,12] == [2*2,\"4*2\",6*2]```\n1. ```python \n [][:] == []```", "_____no_output_____" ], [ "Highlighting **doesn't** work in Jupyter neither in Sphinx:\n\nThree quotes, single line\n\n1. ```python [2,3,1] != [\"2\",3,1]```\n1. ```python [4,8,12] == [2*2,\"4*2\",6*2]```\n1. ```python [][:] == \"[]\"```\n\nSingle quote, single line\n\n1. `python [2,3,1] != [\"2\",3,1]`\n1. `python [4,8,12] == [2*2,\"4*2\",6*2]`\n1. `python [][:] == \"[]\"`\n", "_____no_output_____" ], [ "## Togglable cells\n\nThere are various ways to have togglable cells.\n\n### Show/hide exercises (PREFERRED)\n\nIf you need clickable show/hide buttons for exercise solutions , see here: [Usage - Exercise types](https://jupman.softpython.org/en/latest/usage.html#Type-of-exercises). It manages comprehensively use cases for display in website, student zips, exams, etc\n\nIf you have other needs, we report here some test we made, but keep in mind this sort of hacks tend to change behaviour with different versions of jupyter.\n\n### Toggling with Javascript\n\n* Works in MarkDown\n* Works while in Jupyter\n* Works in HTML\n* Does not show in Latex (which might be a good point, if you intend to put somehow solutions at the end of the document)\n* NOTE: after creating the text to see the results you have to run the initial cell with jupman.init (as for the toc) \n* NOTE: you can't use Markdown block code since of Sept 2017 doesn't show well in HTML output \n\n<div class=\"jupman-togglable\">\n\n<code>\n<pre>\n # SOME CODE\n color = raw_input(\"What's your eyes' color?\")\n if color == \"\":\n sys.exit()\n</pre>\n</code>\n</div>\n\n<div class=\"jupman-togglable\" \n data-jupman-show=\"Customized show msg\" \n data-jupman-hide=\"Customized hide msg\">\n\n<code>\n<pre>\n # SOME OTHER CODE\n how_old = raw_input(\"How old are you?\")\n x = random.randint(1,8)\n if question == \"\":\n sys.exit()\n \n</pre>\n</code>\n</div>", "_____no_output_____" ], [ "### HTML details in Markdown, code tag \n\n* Works while in Jupyter\n* Doesn't work in HTML output\n* as of Sept Oct 2017, not yet supported in Microsoft browsers\n\n<details>\n\n<summary>Click here to see the code</summary>\n\n<code>\n\n question = raw_input(\"What?\")\n answers = random.randint(1,8)\n if question == \"\":\n sys.exit()\n</code>\n\n</details>\n", "_____no_output_____" ], [ "### HTML details in Markdown, Markdown mixed code\n\n* Works while in Jupyter \n* Doesn't work in HTML output\n* as of Sept Oct 2017, not yet supported in Microsoft browsers\n\n\n<details>\n\n<summary>Click here to see the code</summary>\n\n```python\n question = raw_input(\"What?\")\n answers = random.randint(1,8)\n if question == \"\":\n sys.exit()\n```\n\n</details>\n", "_____no_output_____" ], [ "### HTML details in HTML, raw NBConvert Format \n\n* Doesn't work in Jupyter\n* Works in HTML output\n * NOTE: as of Sept Oct 2017, not yet supported in Microsoft browsers\n* Doesn't show at all in PDF output\n", "_____no_output_____" ] ], [ [ "<details>\n<summary>Click here to see the code</summary>\n<code>\n<pre>\n question = raw_input(\"What?\")\n answers = random.randint(1,8)\n if question == \"\":\n sys.exit()\n</pre>\n</code>\n</details>", "_____no_output_____" ] ], [ [ "Some other Markdown cell afterwards ....", "_____no_output_____" ], [ "## Files in templates\n\nSince Dec 2019 they are not accessible [see issue 10](https://github.com/DavidLeoni/jupman/issues/10), but it is not a great problem, you can always put a link to Github, see for example [exam-yyyy-mm-dd.ipynb](https://github.com/DavidLeoni/jupman/tree/master/_templates/exam/exam-yyyy-mm-dd.ipynb)", "_____no_output_____" ], [ "## Python tutor\n\nThere are various ways to embed Python tutor, first we put the recommended one.", "_____no_output_____" ], [ "### jupman.pytut", "_____no_output_____" ], [ "**RECOMMENDED**: You can put a call to `jupman.pytut()` at the end of a cell, and the cell code will magically appear in python tutor in the output (except the call to `pytut()` of course). \nDoes not need internet connection.", "_____no_output_____" ] ], [ [ "x = [5,8,4,10,30,20,40,50,60,70,20,30]\ny= {3:9}\nz = [x]\n\njupman.pytut()", "_____no_output_____" ] ], [ [ "**jupman.pytut scope**: BEWARE of variables which were initialized in previous cells, they WILL NOT be available in Python Tutor:", "_____no_output_____" ] ], [ [ "w = 8", "_____no_output_____" ], [ "x = w + 5\njupman.pytut()", "Traceback (most recent call last):\n File \"/home/da/Da/prj/jupman/prj/jupman.py\", line 2305, in _runscript\n self.run(script_str, user_globals, user_globals)\n File \"/usr/lib/python3.5/bdb.py\", line 431, in run\n exec(cmd, globals, locals)\n File \"<string>\", line 2, in <module>\nNameError: name 'w' is not defined\n" ] ], [ [ "**jupman.pytut window overflow**: When too much right space is taken, it might be difficult to scroll:\n", "_____no_output_____" ] ], [ [ "x = [3,2,5,2,42,34,2,4,34,2,3,4,23,4,23,4,2,34,23,4,23,4,23,4,234,34,23,4,23,4,23,4,2]\n\njupman.pytut()", "_____no_output_____" ], [ "x = w + 5\njupman.pytut()", "Traceback (most recent call last):\n File \"/home/da/Da/prj/jupman/prj/jupman.py\", line 2305, in _runscript\n self.run(script_str, user_globals, user_globals)\n File \"/usr/lib/python3.5/bdb.py\", line 431, in run\n exec(cmd, globals, locals)\n File \"<string>\", line 2, in <module>\nNameError: name 'w' is not defined\n" ] ], [ [ "**jupman.pytut execution:** Some cells might execute in Jupyter but not so well in Python Tutor, due to [its inherent limitations](https://github.com/pgbovine/OnlinePythonTutor/blob/master/unsupported-features.md):", "_____no_output_____" ] ], [ [ "x = 0\nfor i in range(10000):\n x += 1\nprint(x)\njupman.pytut()", "10000\n" ] ], [ [ "**jupman.pytut infinite loops**: Since execution occurs first in Jupyter and then in Python tutor, if you have an infinite loop no Python Tutor instance will be spawned: \n\n```python\nwhile True:\n pass\n\njupman.pytut()\n```", "_____no_output_____" ], [ "**jupman.pytut() resizability:** long vertical and horizontal expansion should work:", "_____no_output_____" ] ], [ [ "x = {0:'a'}\nfor i in range(1,30):\n x[i] = x[i-1]+str(i*10000)\njupman.pytut()", "_____no_output_____" ] ], [ [ "**jupman.pytut cross arrows**: With multiple visualizations, arrows shouldn't cross from one to the other even if underlying script is loaded multiple times (relates to visualizerIdOverride)", "_____no_output_____" ] ], [ [ "x = [1,2,3]\n\n\njupman.pytut()", "_____no_output_____" ] ], [ [ "**jupman.pytut print output**: With only one line of print, Print output panel shouldn't be too short:", "_____no_output_____" ] ], [ [ "print(\"hello\")\n\njupman.pytut()", "hello\n" ], [ "y = [1,2,3,4]\n\n\njupman.pytut()", "_____no_output_____" ] ], [ [ "### HTML magics\n\nAnother option is to directly paste Python Tutor iframe in the cells, and use Jupyter `%%HTML` magics command. \n\nHTML should be available both in notebook and website - of course, requires an internet connection.\n\nBeware: you need the HTTP**S** !", "_____no_output_____" ] ], [ [ "%%HTML\n\n<iframe width=\"800\" height=\"300\" frameborder=\"0\"\n src=\"https://pythontutor.com/iframe-embed.html#code=x+%3D+5%0Ay+%3D+10%0Az+%3D+x+%2B+y&cumulative=false&py=2&curInstr=3\">\n</iframe>", "_____no_output_____" ] ], [ [ "### NBTutor", "_____no_output_____" ], [ "To show Python Tutor in notebooks, there is already a jupyter extension called [NBTutor](https://github.com/lgpage/nbtutor) , afterwards you can use magic `%%nbtutor` to show the interpreter.\n\nUnfortunately, it doesn't show in the generated HTML :-/\n", "_____no_output_____" ] ], [ [ "%reload_ext nbtutor", "_____no_output_____" ], [ "%%nbtutor\n\nfor x in range(1,4):\n print(\"ciao\")\nx=5\ny=7\nx +y\n", "ciao\nciao\nciao\n" ] ], [ [ "## Stripping answers\n\nFor stripping answers examples, see [jupyter-example/jupyter-example-sol](jupyter-example/jupyter-example-sol.ipynb). For explanation, see [usage](usage.ipynb#Tags-to-strip)", "_____no_output_____" ], [ "## Metadata to HTML classes\n", "_____no_output_____" ], [ "## Formatting problems", "_____no_output_____" ], [ "### Characters per line\n\n\nPython standard for code has limit to 79, many styles have 80 (see [Wikipedia](https://en.wikipedia.org/wiki/Characters_per_line))\n\nWe can keep 80:\n\n```\n--------------------------------------------------------------------------------\n```\n\n\n```python\n--------------------------------------------------------------------------------\n```\n\n\nErrors hold 75 dashes:\n\nPlain:\n```\n---------------------------------------------------------------------------\nZeroDivisionError Traceback (most recent call last)\n<ipython-input-15-9e1622b385b6> in <module>()\n----> 1 1/0\n\nZeroDivisionError: division by zero\n\n```\n\nAs Python markup:\n```python\n---------------------------------------------------------------------------\nZeroDivisionError Traceback (most recent call last)\n<ipython-input-15-9e1622b385b6> in <module>()\n----> 1 1/0\n\nZeroDivisionError: division by zero\n```", "_____no_output_____" ] ], [ [ "len('---------------------------------------------------------------------------')", "_____no_output_____" ] ], [ [ "On website this **may** display a scroll bar, because it will actually print `'` apexes plus the dashes", "_____no_output_____" ] ], [ [ "'-'*80", "_____no_output_____" ] ], [ [ "This should **not** display a scrollbar:", "_____no_output_____" ] ], [ [ "'-'*78", "_____no_output_____" ] ], [ [ "This should **not** display a scrollbar:", "_____no_output_____" ] ], [ [ "print('-'*80)", "--------------------------------------------------------------------------------\n" ] ], [ [ "### Very large input\n\nIn Jupyter: default behaviour, show scrollbar\n\nOn the website: should expand in horizontal as much as it wants, the rationale is that for input code since it may be printed to PDF you should always manually put line breaks.", "_____no_output_____" ] ], [ [ "# line with an exceedingly long comment line with an exceedingly long comment line with an exceedingly long comment line with an exceedingly long comment line with an exceedingly long comment line with an exceedingly long comment\n\n# line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment line with an an out-of-this-world long comment\n\n", "_____no_output_____" ] ], [ [ "**Very long HTML** (and long code line)\n\nShould expand in vertical as much as it wants.", "_____no_output_____" ] ], [ [ "%%HTML\n\n<iframe width=\"100%\" height=\"1300px\" frameBorder=\"0\" src=\"https://umap.openstreetmap.fr/en/map/mia-mappa-agritur_182055?scaleControl=false&miniMap=false&scrollWheelZoom=false&zoomControl=true&allowEdit=false&moreControl=true&searchControl=null&tilelayersControl=null&embedControl=null&datalayersControl=true&onLoadPanel=undefined&captionBar=false#11/46.0966/11.4024\"></iframe><p><a href=\"http://umap.openstreetmap.fr/en/map/mia-mappa-agritur_182055\">See full screen</a></p>\n\n", "_____no_output_____" ] ], [ [ "### Very long output\n\nIn Jupyter: by clicking, you can collapse\n\nOn the website: a scrollbar should appear", "_____no_output_____" ] ], [ [ "for x in range(150):\n print('long output ...', x)", "long output ... 0\nlong output ... 1\nlong output ... 2\nlong output ... 3\nlong output ... 4\nlong output ... 5\nlong output ... 6\nlong output ... 7\nlong output ... 8\nlong output ... 9\nlong output ... 10\nlong output ... 11\nlong output ... 12\nlong output ... 13\nlong output ... 14\nlong output ... 15\nlong output ... 16\nlong output ... 17\nlong output ... 18\nlong output ... 19\nlong output ... 20\nlong output ... 21\nlong output ... 22\nlong output ... 23\nlong output ... 24\nlong output ... 25\nlong output ... 26\nlong output ... 27\nlong output ... 28\nlong output ... 29\nlong output ... 30\nlong output ... 31\nlong output ... 32\nlong output ... 33\nlong output ... 34\nlong output ... 35\nlong output ... 36\nlong output ... 37\nlong output ... 38\nlong output ... 39\nlong output ... 40\nlong output ... 41\nlong output ... 42\nlong output ... 43\nlong output ... 44\nlong output ... 45\nlong output ... 46\nlong output ... 47\nlong output ... 48\nlong output ... 49\nlong output ... 50\nlong output ... 51\nlong output ... 52\nlong output ... 53\nlong output ... 54\nlong output ... 55\nlong output ... 56\nlong output ... 57\nlong output ... 58\nlong output ... 59\nlong output ... 60\nlong output ... 61\nlong output ... 62\nlong output ... 63\nlong output ... 64\nlong output ... 65\nlong output ... 66\nlong output ... 67\nlong output ... 68\nlong output ... 69\nlong output ... 70\nlong output ... 71\nlong output ... 72\nlong output ... 73\nlong output ... 74\nlong output ... 75\nlong output ... 76\nlong output ... 77\nlong output ... 78\nlong output ... 79\nlong output ... 80\nlong output ... 81\nlong output ... 82\nlong output ... 83\nlong output ... 84\nlong output ... 85\nlong output ... 86\nlong output ... 87\nlong output ... 88\nlong output ... 89\nlong output ... 90\nlong output ... 91\nlong output ... 92\nlong output ... 93\nlong output ... 94\nlong output ... 95\nlong output ... 96\nlong output ... 97\nlong output ... 98\nlong output ... 99\nlong output ... 100\nlong output ... 101\nlong output ... 102\nlong output ... 103\nlong output ... 104\nlong output ... 105\nlong output ... 106\nlong output ... 107\nlong output ... 108\nlong output ... 109\nlong output ... 110\nlong output ... 111\nlong output ... 112\nlong output ... 113\nlong output ... 114\nlong output ... 115\nlong output ... 116\nlong output ... 117\nlong output ... 118\nlong output ... 119\nlong output ... 120\nlong output ... 121\nlong output ... 122\nlong output ... 123\nlong output ... 124\nlong output ... 125\nlong output ... 126\nlong output ... 127\nlong output ... 128\nlong output ... 129\nlong output ... 130\nlong output ... 131\nlong output ... 132\nlong output ... 133\nlong output ... 134\nlong output ... 135\nlong output ... 136\nlong output ... 137\nlong output ... 138\nlong output ... 139\nlong output ... 140\nlong output ... 141\nlong output ... 142\nlong output ... 143\nlong output ... 144\nlong output ... 145\nlong output ... 146\nlong output ... 147\nlong output ... 148\nlong output ... 149\n" ] ] ]
[ "code", "markdown", "raw", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "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", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "raw" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d01ea93a3506ed2be6aa8ff31aa58d658b6dfc07
142,768
ipynb
Jupyter Notebook
bike-sharing-demand/bike-sharing-demand-rf.ipynb
jaepil-choi/Kaggle_bikeshare
338705ae239b6c332276fc68c25ca202e4713d2f
[ "MIT" ]
null
null
null
bike-sharing-demand/bike-sharing-demand-rf.ipynb
jaepil-choi/Kaggle_bikeshare
338705ae239b6c332276fc68c25ca202e4713d2f
[ "MIT" ]
null
null
null
bike-sharing-demand/bike-sharing-demand-rf.ipynb
jaepil-choi/Kaggle_bikeshare
338705ae239b6c332276fc68c25ca202e4713d2f
[ "MIT" ]
null
null
null
126.45527
58,420
0.854897
[ [ [ "## Load Dataset", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# 노트북 안에 그래프를 그리기 위해\n%matplotlib inline\n\n# 그래프에서 마이너스 폰트 깨지는 문제에 대한 대처\nmpl.rcParams['axes.unicode_minus'] = False\n\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "train = pd.read_csv(\"data/train.csv\", parse_dates=[\"datetime\"])\ntrain.shape", "_____no_output_____" ], [ "test = pd.read_csv(\"data/test.csv\", parse_dates=[\"datetime\"])\ntest.shape", "_____no_output_____" ] ], [ [ "## Feature Engineering", "_____no_output_____" ] ], [ [ "train[\"year\"] = train[\"datetime\"].dt.year\ntrain[\"month\"] = train[\"datetime\"].dt.month\ntrain[\"day\"] = train[\"datetime\"].dt.day\ntrain[\"hour\"] = train[\"datetime\"].dt.hour\ntrain[\"minute\"] = train[\"datetime\"].dt.minute\ntrain[\"second\"] = train[\"datetime\"].dt.second\ntrain[\"dayofweek\"] = train[\"datetime\"].dt.dayofweek\ntrain.shape", "_____no_output_____" ], [ "test[\"year\"] = test[\"datetime\"].dt.year\ntest[\"month\"] = test[\"datetime\"].dt.month\ntest[\"day\"] = test[\"datetime\"].dt.day\ntest[\"hour\"] = test[\"datetime\"].dt.hour\ntest[\"minute\"] = test[\"datetime\"].dt.minute\ntest[\"second\"] = test[\"datetime\"].dt.second\ntest[\"dayofweek\"] = test[\"datetime\"].dt.dayofweek\ntest.shape", "_____no_output_____" ], [ "# widspeed 풍속에 0 값이 가장 많다. => 잘못 기록된 데이터를 고쳐 줄 필요가 있음\nfig, axes = plt.subplots(nrows=2)\nfig.set_size_inches(18,10)\n\nplt.sca(axes[0])\nplt.xticks(rotation=30, ha='right')\naxes[0].set(ylabel='Count',title=\"train windspeed\")\nsns.countplot(data=train, x=\"windspeed\", ax=axes[0])\n\nplt.sca(axes[1])\nplt.xticks(rotation=30, ha='right')\naxes[1].set(ylabel='Count',title=\"test windspeed\")\nsns.countplot(data=test, x=\"windspeed\", ax=axes[1])", "_____no_output_____" ], [ "# 풍속의 0값에 특정 값을 넣어준다.\n# 평균을 구해 일괄적으로 넣어줄 수도 있지만, 예측의 정확도를 높이는 데 도움이 될것 같진 않다.\n# train.loc[train[\"windspeed\"] == 0, \"windspeed\"] = train[\"windspeed\"].mean()\n# test.loc[train[\"windspeed\"] == 0, \"windspeed\"] = train[\"windspeed\"].mean()", "_____no_output_____" ], [ "# 풍속이 0인것과 아닌 것의 세트를 나누어 준다.\ntrainWind0 = train.loc[train['windspeed'] == 0]\ntrainWindNot0 = train.loc[train['windspeed'] != 0]\nprint(trainWind0.shape)\nprint(trainWindNot0.shape)", "(1313, 19)\n(9573, 19)\n" ], [ "# 그래서 머신러닝으로 예측을 해서 풍속을 넣어주도록 한다.\nfrom sklearn.ensemble import RandomForestClassifier\n\ndef predict_windspeed(data):\n \n # 풍속이 0인것과 아닌 것을 나누어 준다.\n dataWind0 = data.loc[data['windspeed'] == 0]\n dataWindNot0 = data.loc[data['windspeed'] != 0]\n \n # 풍속을 예측할 피처를 선택한다.\n wCol = [\"season\", \"weather\", \"humidity\", \"month\", \"temp\", \"year\", \"atemp\"]\n\n # 풍속이 0이 아닌 데이터들의 타입을 스트링으로 바꿔준다.\n dataWindNot0[\"windspeed\"] = dataWindNot0[\"windspeed\"].astype(\"str\")\n\n # 랜덤포레스트 분류기를 사용한다.\n rfModel_wind = RandomForestClassifier()\n\n # wCol에 있는 피처의 값을 바탕으로 풍속을 학습시킨다.\n rfModel_wind.fit(dataWindNot0[wCol], dataWindNot0[\"windspeed\"])\n\n # 학습한 값을 바탕으로 풍속이 0으로 기록 된 데이터의 풍속을 예측한다.\n wind0Values = rfModel_wind.predict(X = dataWind0[wCol])\n\n # 값을 다 예측 후 비교해 보기 위해\n # 예측한 값을 넣어 줄 데이터 프레임을 새로 만든다.\n predictWind0 = dataWind0\n predictWindNot0 = dataWindNot0\n\n # 값이 0으로 기록 된 풍속에 대해 예측한 값을 넣어준다.\n predictWind0[\"windspeed\"] = wind0Values\n\n # dataWindNot0 0이 아닌 풍속이 있는 데이터프레임에 예측한 값이 있는 데이터프레임을 합쳐준다.\n data = predictWindNot0.append(predictWind0)\n\n # 풍속의 데이터타입을 float으로 지정해 준다.\n data[\"windspeed\"] = data[\"windspeed\"].astype(\"float\")\n\n data.reset_index(inplace=True)\n data.drop('index', inplace=True, axis=1)\n \n return data", "_____no_output_____" ], [ "# 0값을 조정한다.\ntrain = predict_windspeed(train)\n# test = predict_windspeed(test)\n\n# widspeed 의 0값을 조정한 데이터를 시각화\nfig, ax1 = plt.subplots()\nfig.set_size_inches(18,6)\n\nplt.sca(ax1)\nplt.xticks(rotation=30, ha='right')\nax1.set(ylabel='Count',title=\"train windspeed\")\nsns.countplot(data=train, x=\"windspeed\", ax=ax1)", "_____no_output_____" ] ], [ [ "## Feature Selection\n* 신호와 잡음을 구분해야 한다.\n* 피처가 많다고 해서 무조건 좋은 성능을 내지 않는다.\n* 피처를 하나씩 추가하고 변경해 가면서 성능이 좋지 않은 피처는 제거하도록 한다.", "_____no_output_____" ] ], [ [ "# 연속형 feature와 범주형 feature \n# 연속형 feature = [\"temp\",\"humidity\",\"windspeed\",\"atemp\"]\n# 범주형 feature의 type을 category로 변경 해 준다.\ncategorical_feature_names = [\"season\",\"holiday\",\"workingday\",\"weather\",\n \"dayofweek\",\"month\",\"year\",\"hour\"]\n\nfor var in categorical_feature_names:\n train[var] = train[var].astype(\"category\")\n test[var] = test[var].astype(\"category\")", "_____no_output_____" ], [ "feature_names = [\"season\", \"weather\", \"temp\", \"atemp\", \"humidity\", \"windspeed\",\n \"year\", \"hour\", \"dayofweek\", \"holiday\", \"workingday\"]\n\nfeature_names", "_____no_output_____" ], [ "X_train = train[feature_names]\n\nprint(X_train.shape)\nX_train.head()", "(10886, 11)\n" ], [ "X_test = test[feature_names]\n\nprint(X_test.shape)\nX_test.head()", "(6493, 11)\n" ], [ "label_name = \"count\"\n\ny_train = train[label_name]\n\nprint(y_train.shape)\ny_train.head()", "(10886,)\n" ] ], [ [ "# Score\n## RMSLE\n과대평가 된 항목보다는 과소평가 된 항목에 패널티를 준다.\n\n오차(Error)를 제곱(Square)해서 평균(Mean)한 값의 제곱근(Root) 으로 값이 작을 수록 정밀도가 높다. \n\n0에 가까운 값이 나올 수록 정밀도가 높은 값이다.\n\nSubmissions are evaluated one the Root Mean Squared Logarithmic Error (RMSLE)", "_____no_output_____" ], [ "$$ \\sqrt{\\frac{1}{n} \\sum_{i=1}^n (\\log(p_i + 1) - \\log(a_i+1))^2 } $$", "_____no_output_____" ], [ "* \\\\({n}\\\\) is the number of hours in the test set\n* \\\\(p_i\\\\) is your predicted count\n* \\\\(a_i\\\\) is the actual count\n* \\\\(\\log(x)\\\\) is the natural logarithm\n\n* 좀 더 자세한 설명은 : [RMSLE cost function](https://www.slideshare.net/KhorSoonHin/rmsle-cost-function)\n\n* 잔차(residual)에 대한 평균에 로그를 씌운 값이다. => 과대평가 된 항목보다 과소 평가 된 항목에 패널티를 주기위해\n* 정답에 대한 오류를 숫자로 나타낸 값으로 값이 클 수록 오차가 크다는 의미다.\n* 값이 작을 수록 오류가 적다는 의미를 나타낸다.\n\n![image.png](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Logarithms.svg/456px-Logarithms.svg.png)\n이미지 출처 : 위키피디아 https://ko.wikipedia.org/wiki/로그", "_____no_output_____" ] ], [ [ "from sklearn.metrics import make_scorer\n\ndef rmsle(predicted_values, actual_values):\n # 넘파이로 배열 형태로 바꿔준다.\n predicted_values = np.array(predicted_values)\n actual_values = np.array(actual_values)\n \n # 예측값과 실제 값에 1을 더하고 로그를 씌워준다.\n log_predict = np.log(predicted_values + 1)\n log_actual = np.log(actual_values + 1)\n \n # 위에서 계산한 예측값에서 실제값을 빼주고 제곱을 해준다.\n difference = log_predict - log_actual\n # difference = (log_predict - log_actual) ** 2\n difference = np.square(difference)\n \n # 평균을 낸다.\n mean_difference = difference.mean()\n \n # 다시 루트를 씌운다.\n score = np.sqrt(mean_difference)\n \n return score\n\nrmsle_scorer = make_scorer(rmsle)\nrmsle_scorer", "_____no_output_____" ] ], [ [ "### Cross Validation 교차 검증\n* 일반화 성능을 측정하기 위해 데이터를 여러 번 반복해서 나누고 여러 모델을 학습한다.\n![image.png](https://www.researchgate.net/profile/Halil_Bisgin/publication/228403467/figure/fig2/AS:302039595798534@1449023259454/Figure-4-k-fold-cross-validation-scheme-example.png)\n이미지 출처 : https://www.researchgate.net/figure/228403467_fig2_Figure-4-k-fold-cross-validation-scheme-example\n\n\n* KFold 교차검증 \n * 데이터를 폴드라 부르는 비슷한 크기의 부분집합(n_splits)으로 나누고 각각의 폴드 정확도를 측정한다.\n * 첫 번째 폴드를 테스트 세트로 사용하고 나머지 폴드를 훈련세트로 사용하여 학습한다.\n * 나머지 훈련세트로 만들어진 세트의 정확도를 첫 번째 폴드로 평가한다.\n * 다음은 두 번째 폴드가 테스트 세트가 되고 나머지 폴드의 훈련세트를 두 번째 폴드로 정확도를 측정한다.\n * 이 과정을 마지막 폴드까지 반복한다.\n * 이렇게 훈련세트와 테스트세트로 나누는 N개의 분할마다 정확도를 측정하여 평균 값을 낸게 정확도가 된다.\n", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n\nk_fold = KFold(n_splits=10, shuffle=True, random_state=0)", "_____no_output_____" ] ], [ [ "## RandomForest", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestRegressor\n\nmax_depth_list = []\n\nmodel = RandomForestRegressor(n_estimators=100, # 높을수록 좋지만, 느려짐. \n n_jobs=-1,\n random_state=0)\nmodel", "_____no_output_____" ], [ "%time score = cross_val_score(model, X_train, y_train, cv=k_fold, scoring=rmsle_scorer)\nscore = score.mean()\n# 0에 근접할수록 좋은 데이터\nprint(\"Score= {0:.5f}\".format(score))", "Wall time: 19.9 s\nScore= 0.33110\n" ] ], [ [ "## Train", "_____no_output_____" ] ], [ [ "# 학습시킴, 피팅(옷을 맞출 때 사용하는 피팅을 생각함) - 피처와 레이블을 넣어주면 알아서 학습을 함\nmodel.fit(X_train, y_train)", "_____no_output_____" ], [ "# 예측\npredictions = model.predict(X_test)\n\nprint(predictions.shape)\npredictions[0:10]", "(6493,)\n" ], [ "# 예측한 데이터를 시각화 해본다. \nfig,(ax1,ax2)= plt.subplots(ncols=2)\nfig.set_size_inches(12,5)\nsns.distplot(y_train,ax=ax1,bins=50)\nax1.set(title=\"train\")\nsns.distplot(predictions,ax=ax2,bins=50)\nax2.set(title=\"test\")", "_____no_output_____" ] ], [ [ "# Submit", "_____no_output_____" ] ], [ [ "submission = pd.read_csv(\"data/sampleSubmission.csv\")\nsubmission\n\nsubmission[\"count\"] = predictions\n\nprint(submission.shape)\nsubmission.head()", "(6493, 2)\n" ], [ "submission.to_csv(\"data/Score_{0:.5f}_submission.csv\".format(score), index=False)", "_____no_output_____" ] ], [ [ "참고 : \n* [EDA & Ensemble Model (Top 10 Percentile) | Kaggle](https://www.kaggle.com/viveksrinivasan/eda-ensemble-model-top-10-percentile)\n* [How to finish top 10 percentile in Bike Sharing Demand Competition In Kaggle? (part -1)](https://medium.com/@viveksrinivasan/how-to-finish-top-10-percentile-in-bike-sharing-demand-competition-in-kaggle-part-1-c816ea9c51e1)\n* [How to finish top 10 percentile in Bike Sharing Demand Competition In Kaggle? (part -2)](https://medium.com/@viveksrinivasan/how-to-finish-top-10-percentile-in-bike-sharing-demand-competition-in-kaggle-part-2-29e854aaab7d)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d01eb4731f08d86ae6c2d1bc2281de260cd36515
18,541
ipynb
Jupyter Notebook
code/model_his_her_tfidf_nmf.ipynb
my321/project4_econtwitter
1ce705fea7da10b1954e2f6fc64f80ec1881bcc6
[ "MIT" ]
1
2021-11-03T14:45:58.000Z
2021-11-03T14:45:58.000Z
code/model_his_her_tfidf_nmf.ipynb
my321/project4_econtwitter
1ce705fea7da10b1954e2f6fc64f80ec1881bcc6
[ "MIT" ]
null
null
null
code/model_his_her_tfidf_nmf.ipynb
my321/project4_econtwitter
1ce705fea7da10b1954e2f6fc64f80ec1881bcc6
[ "MIT" ]
null
null
null
51.077135
284
0.685724
[ [ [ "import pandas as pd \nimport re\nimport json \nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer \nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import NMF\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom collections import Counter\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib.pyplot as plt\n", "_____no_output_____" ] ], [ [ "##### After separating tweets out as male and female tweets, try to find topic", "_____no_output_____" ] ], [ [ "with open('her_list.txt', 'r') as filename: \n her_list=json.load(filename)", "_____no_output_____" ], [ "with open('his_list.txt','r') as filename: \n his_list=json.load(filename)", "_____no_output_____" ], [ "cv_tfidf = TfidfVectorizer(stop_words='english')", "_____no_output_____" ], [ "X_tfidf = cv_tfidf.fit_transform(her_list)", "_____no_output_____" ], [ "nmf_model = NMF(3)\ntopic_matrix = nmf_model.fit_transform(X_tfidf)", "_____no_output_____" ], [ "def display_topics(model, feature_names, no_top_words, topic_names=None):\n for ix, topic in enumerate(model.components_):\n if not topic_names or not topic_names[ix]:\n print(\"\\nTopic \", ix)\n else:\n print(\"\\nTopic: '\",topic_names[ix],\"'\")\n print(\", \".join([feature_names[i]\n for i in topic.argsort()[:-no_top_words - 1:-1]]))", "_____no_output_____" ], [ "display_topics(nmf_model, cv_tfidf.get_feature_names(), 25)", "\nTopic 0\nwomen, men, economics, gender, economists, covid, labor, jobs, economist, market, black, held, impact, work, macro, especially, pandemic, participation, married, womens, look, important, children, force, economy\n\nTopic 1\njodiecongirl, prasoonpratham, bad, tweet, imbernomics, mattkahn, actually, laugh, liberty, thought, jaminspeer, board, jenniferdoleac, math, exposure, link, rich, fair, nicduquette, ask, mikeshor, probably, chrisweiss_, sisselfreports, witchcraft\n\nTopic 2\nwork, wife, daughter, woman, good, great, new, got, said, day, years, year, shes, girl, old, womens, read, today, female, research, love, school, big, paper, ago\n" ], [ "lsa = TruncatedSVD(2)\ndoc_topic = lsa.fit_transform(X_tfidf)\nlsa.explained_variance_ratio_", "_____no_output_____" ], [ "display_topics(lsa, cv_tfidf.get_feature_names(), 20)", "\nTopic 0\nwomen, work, jodiecongirl, economics, men, new, woman, great, covid, womens, wife, good, year, got, gender, day, female, daughter, research, said\n\nTopic 1\njodiecongirl, wife, day, tweet, prasoonpratham, bad, daughter, got, actually, said, imbernomics, thought, mattkahn, good, laugh, ive, liberty, jaminspeer, probably, pretty\n" ], [ "for tweet in her_list: \n if ' men ' in tweet: \n print(tweet)", "dancassino ithat when psychologists ask women to choose between men who are creative but poor and uncreative but rich many women will prefer creative and poor especially for short term relationships\nsocieties with tales portraying men as dominant and women as submissive tend to relegate their women to subordinate positions in their communities both historically and today this iscool\nas we watch potapovawilliams your reminder that a study indicated women choke less often than men in tennis despite what you are seeing\ni have seen so many notfirstrate men misuse econometrics typically men are misusing this of course that might reflect we still have enough women in economics\nlindseyadler thatgirlmareena as long as men comment on sports without knowing anything and that never stops women should never have to explain why they are sports fans\nnot everyone can read this story but it as disturbing as this quote suggests women keep reporting harassment in sports it keeps happening and it increasingly seemsmost men in sports are awfulthat conclusion then the mento do something\none thing we have learned about men who sexually harass women is that they see to tell other men about this behavior ever andthis should not be shocking so if you only talk to men you are neverto hear this\nmento read this men being nice to you tells you nothing about how they treat women\neconomiststowomen get less in society because women risk andor competition these stories essentially blame women for the outcomes we see for women odd economists blame men for these outcomes of course economists also tend to be men\na reminder to men silence is possible you have to correct women teasingly or not\nso we are halftime of a womens basketball game on fs two men doing the halftime show and they are talking mens college basketball they notwomens basketball\nif your not asking men a question ask women that question\ngay women play sports weto normalize gay men playing sports\nchloergibbs was comparing notes w some women econ friends this week were accumulating anecdotes about men whose papers w limited robustness checks etc go out for review at top journals while womens objectivelybetter more thorough papers are desk rejected \ndocelovitz janevandis omgchronicles hologic temkins equitydocs womxnshc drjessigold resaelewiss men sometimes are subject to sexism although much less than women\nmany women however were bothered when men wont accept their money nearly two thirds of men believed that women should contribute and nearly half of men said they would stop dating a woman who never pays \nylvamoberg victoriakvernon immigrant men married to immigrant women tend to have marriages following traditional gender roles depending on country of origin it is also different from immigrant men married to native women\nsimilarities between effect of covid on men and womens livelihoods in india similar to that effect in the us and italy\ntweepsmap tells me of my followers are women are men so many of my followers are economists what do you expect and the rest are businesses\nwomen authored only of the articles in the the world in bagehot banyan bartleby bello charlemagnelexington are all men i wonder if theeconomist still has ato go to achieve gender equality in its own workplace aeacswep econtwitter\nlwsamson iyouto separate out the women out of workforce for family caring reasons but thisshow for instance that strong labor market last few years was bringing back the women but not the men in aggregate\njillfilipovic i will keep saying that mento come get this guy this is on men not women to fix\ni guess it took assa to remind me how mad i can get at a white manel discussing what theycould be driving different labor market effects for men and women\nretirement literacy among women and men is woefully low survey thinkadvisor gender\nsomething ive not seen or read much covid_ death rates in men seem significantly higher than women\nhombres en mxico quien apoyar el derecho a decidir de las mujeres donen dinero a fondomariamx men in the us do youto support theto abortion of women donate money to ppfa\nit is fine if your book isdiscrimination of women economists in the us but if your book is discrimination of women it may turn out that the much more salient cleavage is between women elsewhere and men and even women elsewhere and women in the us\n a gender gap in selfpromotion on stem tasks women selfpromote less than men on verbal tasks it disappears but flip juddkesslerc exley show this is about more than confidence or incentives solution end self evaluation takeaways from changebcfg seminar\nin this paper we analyze how a labordemand shock that is biased towards men affects the labor market outcomes of women using large oil field discoveries in the early th century us as a natural experiment\nmarcgoldwein ernietedeschi how do men vs women payrolls look from ces i thought women saw a larger overall decline\nn matching by race rows white men black men columns white women black women recently married yo source acs psid \ncheck the interactive database for some interesting results men are more boring than women\ni agree that this is a nice initiative weird that theywe welcome participation by both men and women duh\na shecession but this months change different womens jobs fell million jobs over year mens by m a shecession but this month jobs held by women increased k over the month and those held by men fell k keep an eye on it one month noisy\nclarification applying industryspecific job change rates to nov employment levels by industrygenderignoring any gender differences in loss rates within industry the total implied job change for women is k and for men is k very close to the observed levels\nwomen lost k jobs last month while men gained k per bls_gov gender differences in loss rates in industry figure cant explain it instead industry job loss rates strongly correlate r wwomens job share caveat month estimates are noisy esp for subgroups\nformer economic officials leaders of the economics profession in the academy top policy wonks leaders of progressivetanks mostly white men some white women not a single person of color not a single person outside elite circles not a single unemployed person\nlarry summers has a looooong history ofasking questions of dubious character outrageous one maybe womens iq is lower than men and why there arent more women scientists my reply\nejmr so precious you anonymously harass and disparage economists often women men of color and lgbtq by name on a public website but now this\ncomparing across fields we see that the gender disparity in the number of questions is driven by the macro programs which exhibit a very large gender gap where women are asked more questions than men during an nber talk\ntrump call biden concede resign and go to capitol tell them to go home now no apology could ever come close to enough for the men and women who risked and lost their lives to defend our democracy\nthe_torffasian women and men are somewhat more likely to pursue economics in us universities than the overall asian student population however it was pointed out to me that relative to world population asians are massively underrepresented at top econ programs\nif ya havent noticed these early career scholars are mix of women and men and international and us programs so much exciting macro\ntranslation fields with power attractwhopower they then prey onwith less power basically anyone notthem women men of color lgbtq non elite background etc that drives thoseaway ps causality runs from harassment to exclusion\ndirect payments this spring cost billion went to about of americans women men and children do it money will be very popular and mean so much for families thisof year ps business owners wouldpeople to do holiday shopping too\nwe study whether the perceived genderbias of strategic interactions affects the strategic sophistication of men and women this is important because success in life interactions rests on strategic sophistication we study this in competitive games where a prize is at stake\nthe key thing to understand here is that there is structural sexism in how these activities are coded things men do are leisure things women do are personal care cc eortizospina\nso if you take the sum of market laborcare of household and nonhouseholdsleep and chores you get minutesday of sleeplabor for men and minutesday of sleeplabor for women\ntwo quick things this quite match what i get in atus i get minutes men women but more to the point this is the wrongto measure leisureits literally being measured here as minutes peoplethey spend on leisure\nsome lfs tabs mapped out the aggregate hours worked by men and women indexed to january when i start dealing with subsamplesnever confident in what do with seasonality and longterm trends so this is not adjusted\ni always find these discrepancies in reporting interesting even when we condition on wfh during covid men report a more equal division of parental tasks than women do\neduardsuari kvseconomen esbtweets more bald men than women\nthere is a small number ofdominated by men who how i communicate ironically s the feeling is mutual ive learned that with suchwomenme cant win i am confident i am opinionated i am me deal with it\nremarkably as of january men and women have seen exactly the same magnitude cumulative decline in overall employmenttopopulation ratios since last february pp\nleah_boustan dougwebberecon ps of men and of women satisfy the bmi criterion\nus capitalisms failures to prepare for or contain covid hurt us women more than men in terms of careers family incomeshousehold stresses these social costs of system failures cut deepneed corrective action now wecandobetterthancapitalism\nwomen carry an increasingly heavier load than men in providing childcare and educational support to their children during this covid crisis even while still working\nif men get their feelings hurt by a womans success i am in favor of them getting hurt everyday of their lives\n" ], [ "X_tfidf_2 = cv_tfidf.fit_transform(his_list)", "_____no_output_____" ], [ "nmf_model_2 = NMF(3)\ntopic_matrix_2 = nmf_model_2.fit_transform(X_tfidf_2)", "_____no_output_____" ], [ "display_topics(nmf_model_2, cv_tfidf.get_feature_names(), 25)", "\nTopic 0\ntrump, men, said, good, president, work, great, years, white, new, got, read, economics, year, day, says, biden, covid, election, point, book, thing, paper, today, women\n\nTopic 1\nman, oh, boy, andrew___baker, good, thanks, old, life, sorry, young, thankyou, love, year, dclingi, got, heart, sucks, thou, wow, work, wait, world, hate, dangerous, bad\n\nTopic 2\nhes, andrew___baker, talking, saying, got, best, wrong, doing, thing, point, sure, guy, ok, thinking, twitter, good, guess, kind, economist, gonna, gelbach, wearing, noahpinion, modeledbehavior, probably\n" ], [ "lsa_2 = TruncatedSVD(4)\ndoc_topic = lsa_2.fit_transform(X_tfidf_2)\nlsa.explained_variance_ratio_", "_____no_output_____" ], [ "display_topics(lsa_2, cv_tfidf.get_feature_names(), 10)", "\nTopic 0\nhes, man, trump, good, men, said, oh, great, got, work\n\nTopic 1\nman, oh, boy, thanks, old, life, thankyou, work, sorry, young\n\nTopic 2\nhes, man, andrew___baker, oh, talking, boy, gelbach, modeledbehavior, wearing, saying\n\nTopic 3\nmen, women, white, work, good, economics, macro, great, read, labor\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01eb5e348305afccacce6b87492176e8d0a6acd
6,360
ipynb
Jupyter Notebook
src/02_loops_condicionais_metodos_funcoes/06_funcao_range.ipynb
ralsouza/python_fundamentos
f3ccf4b036036327394aac181659eaf463768e9d
[ "MIT" ]
1
2019-07-29T02:43:25.000Z
2019-07-29T02:43:25.000Z
src/02_loops_condicionais_metodos_funcoes/06_funcao_range.ipynb
ralsouza/python_fundamentos
f3ccf4b036036327394aac181659eaf463768e9d
[ "MIT" ]
null
null
null
src/02_loops_condicionais_metodos_funcoes/06_funcao_range.ipynb
ralsouza/python_fundamentos
f3ccf4b036036327394aac181659eaf463768e9d
[ "MIT" ]
null
null
null
22.394366
283
0.390252
[ [ [ "<a href=\"https://colab.research.google.com/github/ralsouza/python_fundamentos/blob/master/src/02_loops_condicionais_metodos_funcoes/06_funcao_range.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "# Range", "_____no_output_____" ], [ "Imprimir os números pares entre 50 e 101. \n\nUsar a técnica da função range que executa saltos entre os números.", "_____no_output_____" ] ], [ [ "for i in range(50,101,2):\n print(i)\n ", "50\n52\n54\n56\n58\n60\n62\n64\n66\n68\n70\n72\n74\n76\n78\n80\n82\n84\n86\n88\n90\n92\n94\n96\n98\n100\n" ] ], [ [ "Imprimir de 3 à 6, lembrando que o último número é exclusivo.", "_____no_output_____" ] ], [ [ "for i in range(3,6):\n print(i)", "3\n4\n5\n" ] ], [ [ "Gerar uma lista negativa, iniciando de 0 até -20, saltando de dois em dois números.\nLembrando novamente que o valor máximo é exclusivo.", "_____no_output_____" ] ], [ [ "for i in range(0,-20,-2):\n print(i)", "0\n-2\n-4\n-6\n-8\n-10\n-12\n-14\n-16\n-18\n" ] ], [ [ "Configurar o valor máximo do range, conforme o tamanho de um objeto em um loop for.", "_____no_output_____" ] ], [ [ "lista = ['morango','abacaxi','banana','melão']\n\nfor i in range(0, len(lista)):\n print(lista[i])", "morango\nabacaxi\nbanana\nmelão\n" ], [ "# Checar o tipo do objeto range\ntype(range(0,5))", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d01ec756903adcfddddb46e8049cecf6153b35b1
57,008
ipynb
Jupyter Notebook
00_Variables_to_Classes.ipynb
Zqs0527/geothermics
8001c93cee3091e8d5e0d4dc3fabbf1463aa4c15
[ "MIT" ]
null
null
null
00_Variables_to_Classes.ipynb
Zqs0527/geothermics
8001c93cee3091e8d5e0d4dc3fabbf1463aa4c15
[ "MIT" ]
null
null
null
00_Variables_to_Classes.ipynb
Zqs0527/geothermics
8001c93cee3091e8d5e0d4dc3fabbf1463aa4c15
[ "MIT" ]
null
null
null
98.459413
27,102
0.840303
[ [ [ "# From Variables to Classes\n## A short Introduction \n\nPython - as any programming language - has many extensions and libraries at its disposal. Basically, there exist libraries for everything. \n\n<center>But what are **libraries**? </center> \n\nBasically, **libraries** are a collection of methods (_small pieces of code where you put sth in and get sth else out_) which you can use to analyse your data, visualise your data, run models ... do anything you like. \n\nAs said, methods usually take _something_ as input. That _something_ is usually a **variable**. \n\nIn the following, we will work our way from **variables** to **libraries**.", "_____no_output_____" ], [ "## Variables \n\nVariables are one of the simplest types of objects in a programming language. An [object](https://en.wikipedia.org/wiki/Object_(computer_science) is a value stored in the memory of your computer, marked by a specific identifyer. Variables can have different types, such as [strings, numbers, and booleans](https://www.learnpython.org/en/Variables_and_Types). Differently to other programming languages, you do not need to declare the type of a variable, as variables are handled as objects in Python. \n\n```python\nx = 4.2 # floating point number\ny = 'Hello World!' # string\nz = True # boolean\n```", "_____no_output_____" ] ], [ [ "x = 4.24725723 \nprint(type(x))\n\ny = 'Hello World! Hello universe'\nprint(y)\n\nz = True\nprint(type(z))", "<class 'float'>\nHello World! Hello universe\n<class 'bool'>\n" ] ], [ [ "We can use operations (normal arithmetic operations) to use variables for getting results we want. With numbers, you can add, substract, multiply, divide, basically taking the values from the memory assigned to the variable name and performing calculations. \n\nLet's have a look at operations with numbers and strings. We leave booleans to the side for the moment. We will simply add the variables below. \n\n```python \nn1 = 7 \nn2 = 42\n\ns1 = 'Looking good, '\ns2 = 'you are.'\n```", "_____no_output_____" ] ], [ [ "n1 = 7\nn2 = 42\n\ns1 = 'Looking good, ' \ns2 = 'you are.'\n\nfirst_sum = n1 + n2\nprint(first_sum)\nfirst_conc = s1 + s2\nprint(first_conc)", "49\nLooking good, you are.\n" ] ], [ [ "Variables can be more than just a number. If you think of an Excel-Spreadsheet, a variable can be the content of a single cell, or multiple cells can be combined in one variable (e.g. one column of an Excel table). \nSo let's create a list -_a collection of variables_ - from `x`, `n1`, and `n2`. Lists in python are created using [ ]. \nNow, if you want to calculate the sum of this list, it is really exhausting to sum up every item of this list manually. \n\n```python\nfirst_list = [x, n1, n2] \n# a sum of a list could look like\nsecond_sum = some_list[0] + some_list[1] + ... + some_list[n] # where n is the last item of the list, e.g. 2 for first_list. \n```", "_____no_output_____" ], [ "Actually, writing the second sum like this is the same as before. It would be great, if this step of calculating the sum could be used many times without writing it out. And this is, what functions are for. For example, there already exists a sum function: \n\n```python \nsum(first_list)```", "_____no_output_____" ] ], [ [ "first_list = [x, n1, n2]\nsecond_sum = first_list[0] + first_list[1] + first_list[2]\nprint('manual sum {}'.format(second_sum))\n\n# This can also be done with a function \nprint('sum function {}'.format(sum(first_list)))", "manual sum 53.2\nsum function 53.2\n" ] ], [ [ "## Functions \nThe `sum()` method we used above is a **function**. \nFunctions (later we will call them methods) are pieces of code, which take an input, perform some kind of operation, and (_optionally_) return an output. ", "_____no_output_____" ], [ "In Python, functions are written like: \n\n```python\ndef func(input):\n \"\"\"\n Description of the functions content # called the function header\n \"\"\"\n some kind of operation on input # called the function body\n \n return output\n```\nAs an example, we write a `sumup` function which sums up a list.", "_____no_output_____" ] ], [ [ "def sumup(inp):\n \"\"\"\n input: inp - list/array with floating point or integer numbers\n return: sumd - scalar value of the summed up list\n \"\"\"\n val = 0\n for i in inp:\n val = val + i\n return val\n\n# let's compare the implemented standard sum function with the new sumup function\nsum1 = sum(first_list)\nsum2 = sumup(first_list)\nprint(\"The python sum function yields {}, \\nand our sumup function yields {}.\".format(*(sum1,sum2)))", "The python sum function yields 53.2, \nand our sumup function yields 53.2.\n" ], [ "# summing up the numbers from 1 to 100\nimport numpy as np\nar_2_sum = np.linspace(1,100,100, dtype='i')\n\nprint(\"the sum of the array is: {}\".format(sumup(ar_2_sum)))", "the sum of the array is: 5050\n" ] ], [ [ "As we see above, functions are quite practical and save a lot of time. Further, they help structuring your code. Some functions are directly available in python without any libraries or other external software. In the example above however, you might have noticed, that we `import`ed a library called `numpy`. \nIn those libraries, functions are merged to one package, having the advantage that you don't need to import each single function at a time. \nImagine you move and have to pack all your belongings. You can think of libraries as packing things with similar purpose in the same box (= library).", "_____no_output_____" ], [ "## Functions to Methods as part of classes\nWhen we talk about functions in the environment of classes, we usually call them methods. But what are **classes**? \n[Classes](https://docs.python.org/3/tutorial/classes.html) are ways to bundle functionality together. Logically, functionality with similar purpose (or different kind of similarity). \nOne example could be: think of **apples**. \n\nApples are now a class. You can apply methods to this class, such as `eat()` or `cut()`. Or more sophisticated methods including various recipes using apples comprised in a cookbook. \nThe `eat()` method is straight forward. But the `cut()` method may be more interesting, since there are various ways to cut an apple.\n", "_____no_output_____" ], [ "Let's assume there are two apples to be cut differently. In python, once you have assigned a class to a variable, you have created an **instance** of that class. Then, methods of are applied to that instance by using a . notation.\n```python\nGolden_Delicious = apple()\nYoya = apple()\n\nGolden_Delicious.cut(4)\nYoya.cut(8)\n```\nThe two apples Golden Delicious and Yoya are _instances_ of the class apple. Real _incarnations_ of the abstract concept _apple_. The Golden Delicious is cut into 4 pieces, while the Yoya is cut into 8 pieces. ", "_____no_output_____" ], [ "This is similar to more complex libraries, such as the `scikit-learn`. In one exercise, you used the command: \n```python\nfrom sklearn.cluster import KMeans\n```\nwhich simply imports the **class** `KMeans` from the library part `sklearn.cluster`. `KMeans` comprises several methods for clustering, which you can use by calling them similar to the apple example before.", "_____no_output_____" ], [ " For this, you need to create an _instance_ of the `KMeans` class. \n```python\n...\nkmeans_inst = KMeans(n_clusters=n_clusters) # first we create the instance of the KMeans class called kmeans_inst\nkmeans_inst.fit(data) # then we apply a method to the instance kmeans_inst\n...\n```\nAn example:", "_____no_output_____" ] ], [ [ "# here we just create the data for clustering\nfrom sklearn.datasets.samples_generator import make_blobs\nimport matplotlib.pyplot as plt\n%matplotlib inline\nX, y = make_blobs(n_samples=100, centers=3, cluster_std= 0.5,\n random_state=0)\n\nplt.scatter(X[:,0], X[:,1], s=70)", "_____no_output_____" ], [ "# now we create an instance of the KMeans class\nfrom sklearn.cluster import KMeans\nnr_of_clusters = 3 # because we see 3 clusters in the plot above\nkmeans_inst = KMeans(n_clusters= nr_of_clusters) # create the instance kmeans_inst\nkmeans_inst.fit(X) # apply a method to the instance\ny_predict = kmeans_inst.predict(X) # apply another method to the instance and save it in another variable", "_____no_output_____" ], [ "# lets plot the predicted cluster centers colored in the cluster color\nplt.scatter(X[:, 0], X[:, 1], c=y_predict, s=50, cmap='Accent')\ncenters = kmeans_inst.cluster_centers_ # apply the method to find the new centers of the determined clusters\nplt.scatter(centers[:, 0], centers[:, 1], c='red', s=200, alpha=0.6); # plot the cluster centers", "_____no_output_____" ] ], [ [ "## Summary \nThis short presentation is meant to make you familiar with the concept of variables, functions, methods and classes. All of which are objects! \n* Variables are normally declared by the user and link a value stored in the memory of your pc to a variable name. They are usually the input of functions \n* Functions are pieces of code taking an input and performing some operation on said input. Optionally, they return directly an output value \n* To facilitate the use of functions, they are sometimes bundled as methods within classes. Classes in turn can build up whole libraries in python. ", "_____no_output_____" ], [ "* Similar to real book libraries, python libraries contain a collection of _recipes_ which can be applied to your data. \n* In terms of apples: You own different kinds of apples. A book about apple dishes (_class_) from the library contains different recipes (_methods_) which can be used for your different apples (_instances of the class_).", "_____no_output_____" ], [ "## Further links \n* [Data Science Handbook](https://jakevdp.github.io/PythonDataScienceHandbook/)\n* [Python for Geosciences](https://github.com/koldunovn/python_for_geosciences) \n* [Introduction to Python for Geoscientists](http://ggorman.github.io/Introduction-to-programming-for-geoscientists/) \n* [Full Video course on Object Oriented Programming](https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
d01ec80d2418020e47cdc7f9a9320ec1fd867b06
66,459
ipynb
Jupyter Notebook
Missions_to_Mars/mission_to_mars.ipynb
yawavi92/web-scraping-challenge
9df99a4523cfd08231f9ce6802255858ad2ed098
[ "ADSL" ]
null
null
null
Missions_to_Mars/mission_to_mars.ipynb
yawavi92/web-scraping-challenge
9df99a4523cfd08231f9ce6802255858ad2ed098
[ "ADSL" ]
null
null
null
Missions_to_Mars/mission_to_mars.ipynb
yawavi92/web-scraping-challenge
9df99a4523cfd08231f9ce6802255858ad2ed098
[ "ADSL" ]
null
null
null
45.73916
6,801
0.465219
[ [ [ "# Dependencies\nfrom bs4 import BeautifulSoup as bs\nimport requests\nimport pymongo\nfrom splinter import Browser\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd", "_____no_output_____" ] ], [ [ " Step 1 - Scraping", "_____no_output_____" ] ], [ [ "#setup splinter\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)\n", "\n\n====== WebDriver manager ======\nCurrent google-chrome version is 93.0.4577\nGet LATEST driver version for 93.0.4577\nDriver [C:\\Users\\carol\\.wdm\\drivers\\chromedriver\\win32\\93.0.4577.63\\chromedriver.exe] found in cache\n" ], [ "# Save url and visit the page\nurl = 'https://redplanetscience.com/'\nbrowser.visit(url)", "_____no_output_____" ], [ "html = browser.html\nsoup = bs(html, \"html.parser\")", "_____no_output_____" ], [ "#collect the latest tand extract text News Title form html document \ntitle = soup.find('div', class_='content_title').text\n#collect Paragraph Text \nnew_p = soup.find('div', class_='article_teaser_body').text\n# Print title and paragraph\nprint(title)\nprint('------------------------------------------------------')\nprint(new_p)", "NASA Perseverance Mars Rover Scientists Train in the Nevada Desert\n------------------------------------------------------\nTeam members searched for signs of ancient microscopic life there, just as NASA's latest rover will on the Red Planet next year.\n" ], [ "# get the image url\nnew_url=\"https://spaceimages-mars.com/\"\nbrowser.visit(new_url)\n\n# set the path\nxpath = \"/html/body/div[1]/img\"\n#bring the full resolution\nfull = browser.find_by_xpath(xpath)\nimage_ = full[0]\nimage_.click()", "_____no_output_____" ], [ "#create a beautiful object\nhtml = browser.html\nsoup = bs(html, \"html.parser\")\nimage_url = soup.find(\"img\", class_=\"headerimage fade-in\")[\"src\"]\n#concatenate to find the image url\nfeatured_image_url = url + image_url\nfeatured_image_url", "_____no_output_____" ] ], [ [ "Mars Facts", "_____no_output_____" ] ], [ [ "#set the URL\nmars_url =\"https://galaxyfacts-mars.com/\"\n\n#Extract the Facts Table from the URL using pandas\ntables = pd.read_html(mars_url)\ntables", "_____no_output_____" ], [ "# set the columns in the dataframes\nmars_df = tables[1]\nmars_df.rename(columns ={0 :'Description', 1: 'Dimension'}, inplace = True)\nmars_df", "_____no_output_____" ], [ "#convert the dataframe back to html format\nhtml = mars_df.to_html()\nhtml", "_____no_output_____" ] ], [ [ "Mars Hemispheres", "_____no_output_____" ] ], [ [ "#extract the image from html file\nastro =\"https://marshemispheres.com/\"\nbrowser.visit(astro)\n\n#create a beautiful object\nhtml = browser.html\nsoup = bs(html, \"html.parser\")\nprint(soup.prettify())", "<html lang=\"en\">\n <head>\n <meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>\n <link href=\"css/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>\n Astropedia Search Results | GUSS Astrogeology Science Center\n </title>\n <meta content=\"GUSS Astrogeology Science Center Astropedia search results.\" name=\"description\"/>\n <meta content=\"GUSS,Astrogeology Science Center,Cartography,Geology,Space,Geological Survey,Mapping\" name=\"keywords\"/>\n <meta content=\"IE=edge\" http-equiv=\"X-UA-Compatible\"/>\n <meta content=\"width=device-width, initial-scale=1, maximum-scale=1\" name=\"viewport\"/>\n <link href=\"css/main.css\" media=\"screen\" rel=\"stylesheet\"/>\n <link href=\"css/print.css\" media=\"print\" rel=\"stylesheet\"/>\n <link href=\"#\" rel=\"icon\" type=\"image/x-ico\"/>\n </head>\n <body id=\"results\">\n <header>\n <a href=\"#\" style=\"float:right;margin-top:10px;\" target=\"_blank\">\n <img alt=\"USGS: Science for a Changing World\" class=\"logo\" height=\"60\" src=\"images/usgs_logo_main_2x.png\"/>\n </a>\n <a href=\"#\" style=\"float:right;margin-top:5px;margin-right:20px;\" target=\"_blank\">\n <img alt=\"NASA\" class=\"logo\" height=\"65\" src=\"images/nasa-logo-web-med.png\"/>\n </a>\n </header>\n <div class=\"wrapper\">\n <div class=\"container\">\n <div class=\"widget block bar\">\n <a href=\"https://astrogeology.usgs.gov/search\" style=\"float:right;text-decoration:none;\">\n <img alt=\"Astropedia\" src=\"images/astropedia-logo-main.png\" style=\"width:200px;border:none;float:right;\"/>\n <div style=\"clear:both;font-size:.8em;float:right;color:#888;\">\n Lunar and Planetary Cartographic Catalog\n </div>\n </a>\n <div style=\"float:left;height:60px;\">\n </div>\n </div>\n <div class=\"full-content\">\n <section class=\"block\" id=\"results-accordian\">\n <div class=\"result-list\" data-section=\"product\" id=\"product-section\">\n <div class=\"accordian\">\n <h2>\n Products\n </h2>\n <span class=\"count\">\n 4 Results\n </span>\n <span class=\"collapse\">\n Collapse\n </span>\n </div>\n <div class=\"collapsible results\">\n <div class=\"item\">\n <a class=\"itemLink product-item\" href=\"cerberus.html\">\n <img alt=\"Cerberus Hemisphere Enhanced thumbnail\" class=\"thumb\" src=\"images/39d3266553462198bd2fbc4d18fbed17_cerberus_enhanced.tif_thumb.png\"/>\n </a>\n <div class=\"description\">\n <a class=\"itemLink product-item\" href=\"cerberus.html\">\n <h3>\n Cerberus Hemisphere Enhanced\n </h3>\n </a>\n <span class=\"subtitle\" style=\"float:left\">\n image/tiff 21 MB\n </span>\n <span class=\"pubDate\" style=\"float:right\">\n </span>\n <br/>\n <p>\n Mosaic of the Cerberus hemisphere of Mars projected into point perspective, a view similar to that which one would see from a spacecraft. This mosaic is composed of 104 Viking Orbiter images acquired…\n </p>\n </div>\n <!-- end description -->\n </div>\n <div class=\"item\">\n <a class=\"itemLink product-item\" href=\"schiaparelli.html\">\n <img alt=\"Schiaparelli Hemisphere Enhanced thumbnail\" class=\"thumb\" src=\"images/08eac6e22c07fb1fe72223a79252de20_schiaparelli_enhanced.tif_thumb.png\"/>\n </a>\n <div class=\"description\">\n <a class=\"itemLink product-item\" href=\"schiaparelli.html\">\n <h3>\n Schiaparelli Hemisphere Enhanced\n </h3>\n </a>\n <span class=\"subtitle\" style=\"float:left\">\n image/tiff 35 MB\n </span>\n <span class=\"pubDate\" style=\"float:right\">\n </span>\n <br/>\n <p>\n Mosaic of the Schiaparelli hemisphere of Mars projected into point perspective, a view similar to that which one would see from a spacecraft. The images were acquired in 1980 during early northern…\n </p>\n </div>\n <!-- end description -->\n </div>\n <div class=\"item\">\n <a class=\"itemLink product-item\" href=\"syrtis.html\">\n <img alt=\"Syrtis Major Hemisphere Enhanced thumbnail\" class=\"thumb\" src=\"images/55a0a1e2796313fdeafb17c35925e8ac_syrtis_major_enhanced.tif_thumb.png\"/>\n </a>\n <div class=\"description\">\n <a class=\"itemLink product-item\" href=\"syrtis.html\">\n <h3>\n Syrtis Major Hemisphere Enhanced\n </h3>\n </a>\n <span class=\"subtitle\" style=\"float:left\">\n image/tiff 25 MB\n </span>\n <span class=\"pubDate\" style=\"float:right\">\n </span>\n <br/>\n <p>\n Mosaic of the Syrtis Major hemisphere of Mars projected into point perspective, a view similar to that which one would see from a spacecraft. This mosaic is composed of about 100 red and violet…\n </p>\n </div>\n <!-- end description -->\n </div>\n <div class=\"item\">\n <a class=\"itemLink product-item\" href=\"valles.html\">\n <img alt=\"Valles Marineris Hemisphere Enhanced thumbnail\" class=\"thumb\" src=\"images/4e59980c1c57f89c680c0e1ccabbeff1_valles_marineris_enhanced.tif_thumb.png\"/>\n </a>\n <div class=\"description\">\n <a class=\"itemLink product-item\" href=\"valles.html\">\n <h3>\n Valles Marineris Hemisphere Enhanced\n </h3>\n </a>\n <span class=\"subtitle\" style=\"float:left\">\n image/tiff 27 MB\n </span>\n <span class=\"pubDate\" style=\"float:right\">\n </span>\n <br/>\n <p>\n Mosaic of the Valles Marineris hemisphere of Mars projected into point perspective, a view similar to that which one would see from a spacecraft. The distance is 2500 kilometers from the surface of…\n </p>\n </div>\n <!-- end description -->\n </div>\n </div>\n <!-- end this-section -->\n </div>\n </section>\n </div>\n <div class=\"navigation clear\" style=\"display: none;\">\n <a class=\"itemLink product-item\" href=\"#\" onclick=\"showMain()\">\n <h3>\n Back\n </h3>\n </a>\n </div>\n </div>\n <footer>\n <div class=\"left\">\n <a href=\"#\">\n Search\n </a>\n |\n <a href=\"#\">\n About\n </a>\n |\n <a href=\"#\">\n Contact\n </a>\n </div>\n <div class=\"right\">\n <a href=\"#\">\n GUSS Science Center\n </a>\n </div>\n </footer>\n </div>\n <div class=\"page-background\" style=\"\n background:url('./images/mars.jpg');\n filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(\n src='./images/mars.jpg', sizingMethod='scale');\n \">\n </div>\n <script type=\"text/javascript\">\n var baseUrl = \"\";\n </script>\n <script src=\"js/jquery.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/jquery-ui.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/general.js\" type=\"text/javascript\">\n </script>\n </body>\n</html>\n" ] ], [ [ "Step 2 - MongoDB and Flask Application", "_____no_output_____" ] ], [ [ "# Extract the hemisphere element\nresults = soup.find(\"div\", class_=\"collapsible results\")\nhemispheres = results.find_all(\"div\", class_=\"item\")\n#create the list to store the image urls\nhemisphere_image_urls=[]\n\n#Iterate trough each image\nfor hemisphere in hemispheres :\n # Scrape the titles\n title = hemisphere.find(\"h3\").text\n \n # the hem links\n link = hemisphere.find(\"a\")[\"href\"]\n u_url =\"https://marshemispheres.com/\"\n hem_link = u_url + link \n browser.visit(hem_link)\n \n # Parse link HTMLs with Beautiful Soup\n html = browser.html\n soup = bs(html, \"html.parser\")\n print(soup.prettify())\n # Scrape the full size images\n load = soup.find(\"div\", class_=\"downloads\")\n load_url = load.find(\"a\")[\"href\"]\n \n # Add URLs and Titles \n hemisphere_image_urls.append({\"title\": title, \"image_url\": url + load_url})\n\n# Print image title and url\nprint(hemisphere_image_urls)", "<html lang=\"en\">\n <head>\n <meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>\n <link href=\"css/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>\n Astropedia Search Results | GUSS Astrogeology Science Center\n </title>\n <meta content=\"GUSS Astrogeology Science Center Astropedia search results.\" name=\"description\"/>\n <meta content=\"GUSS,Astrogeology Science Center,Cartography,Geology,Space,Geological Survey,Mapping\" name=\"keywords\"/>\n <meta content=\"IE=edge\" http-equiv=\"X-UA-Compatible\"/>\n <meta content=\"width=device-width, initial-scale=1, maximum-scale=1\" name=\"viewport\"/>\n <link href=\"css/main.css\" media=\"screen\" rel=\"stylesheet\"/>\n <link href=\"css/print.css\" media=\"print\" rel=\"stylesheet\"/>\n <link href=\"#\" rel=\"icon\" type=\"image/x-ico\"/>\n </head>\n <body id=\"results\">\n <header>\n <a href=\"#\" style=\"float:right;margin-top:10px;\" target=\"_blank\">\n <img alt=\"USGS: Science for a Changing World\" class=\"logo\" height=\"60\" src=\"images/usgs_logo_main_2x.png\"/>\n </a>\n <a href=\"#\" style=\"float:right;margin-top:5px;margin-right:20px;\" target=\"_blank\">\n <img alt=\"NASA\" class=\"logo\" height=\"65\" src=\"images/nasa-logo-web-med.png\"/>\n </a>\n </header>\n <div class=\"wrapper\">\n <div class=\"container\">\n <div class=\"widget block bar\">\n <a href=\"https://astrogeology.usgs.gov/search\" style=\"float:right;text-decoration:none;\">\n <img alt=\"Astropedia\" src=\"images/astropedia-logo-main.png\" style=\"width:200px;border:none;float:right;\"/>\n <div style=\"clear:both;font-size:.8em;float:right;color:#888;\">\n Lunar and Planetary Cartographic\n Catalog\n </div>\n </a>\n <div style=\"float:left;height:60px;\">\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"wide-image-wrapper\" id=\"wide-image\">\n <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/39d3266553462198bd2fbc4d18fbed17_cerberus_enhanced.tif_thumb.png\"/>\n <h3>\n Download\n </h3>\n <ul>\n <li>\n <a href=\"images/full.jpg\" target=\"_blank\">\n Sample\n </a>\n (jpg) 1024px wide\n </li>\n <li>\n <a href=\"images/cerberus_enhanced.tif\" target=\"_blank\">\n Original\n </a>\n (tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n ) 21 MB\n </li>\n </ul>\n </div>\n <img class=\"wide-image\" src=\"images/f5e372a36edfa389625da6d0cc25d905_cerberus_enhanced.tif_full.jpg\"/>\n <a class=\"open-toggle\" href=\"#open\" id=\"wide-image-toggle\">\n Open\n </a>\n </div>\n <div class=\"cover\">\n <h2 class=\"title\">\n Cerberus Hemisphere Enhanced\n </h2>\n <p>\n Mosaic of the Cerberus hemisphere of Mars projected into point perspective, a view similar to that which\n one would see from a spacecraft. This mosaic is composed of 104 Viking Orbiter images acquired on\n February 11, 1980. At that time, it was early northern summer on Mars. The center of the image is at\n latitude 3 degrees, longitude 185 degrees.\n </p>\n <!-- <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/39d3266553462198bd2fbc4d18fbed17_cerberus_enhanced.tif_thumb.png\">\n <h3>Download</h3>\n <ul>\n <li><a target=\"_blank\" href=\"images/full.jpg\">Sample</a> (jpg) 1024px wide</li>\n <li><a target=\"_blank\" href=\"images/cerberus_enhanced.tif\">Original</a> (tif<span class=\"tooltip word-tif\" title=\"\"></span>) 21 MB</li>\n </ul>\n </div> -->\n <div class=\"description\">\n <dl>\n <dt>\n Mimetype\n </dt>\n <dd>\n image/tiff\n </dd>\n <dt>\n Filename\n </dt>\n <dd>\n <a href=\"images/cerberus_enhanced.tif\">\n cerberus_enhanced.tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n </a>\n </dd>\n <dt>\n Originator\n </dt>\n <dd>\n </dd>\n <dt>\n Group\n </dt>\n <dd>\n </dd>\n <dt>\n Added to Astropedia\n </dt>\n <dd>\n 29 September 2011\n </dd>\n <dt>\n Modified\n </dt>\n <dd>\n 3 November 2017\n </dd>\n </dl>\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"navigation clear\">\n <a class=\"itemLink product-item\" href=\"index.html\">\n <h3>\n Back\n </h3>\n </a>\n </div>\n </div>\n <footer>\n <div class=\"left\">\n <a href=\"#\">\n Search\n </a>\n |\n <a href=\"#\">\n About\n </a>\n |\n <a href=\"#\">\n Contact\n </a>\n </div>\n <div class=\"right\">\n <a href=\"#\">\n GUSS Science Center\n </a>\n </div>\n </footer>\n </div>\n <div class=\"page-background\" style=\"\n background:url('./images/mars.jpg');\n filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(\n src='./images/mars.jpg', sizingMethod='scale');\n \">\n </div>\n <script type=\"text/javascript\">\n var baseUrl = \"\";\n </script>\n <script src=\"js/jquery.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/jquery-ui.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/general.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/app.js\" type=\"text/javascript\">\n </script>\n </body>\n</html>\n<html lang=\"en\">\n <head>\n <meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>\n <link href=\"css/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>\n Astropedia Search Results | GUSS Astrogeology Science Center\n </title>\n <meta content=\"GUSS Astrogeology Science Center Astropedia search results.\" name=\"description\"/>\n <meta content=\"GUSS,Astrogeology Science Center,Cartography,Geology,Space,Geological Survey,Mapping\" name=\"keywords\"/>\n <meta content=\"IE=edge\" http-equiv=\"X-UA-Compatible\"/>\n <meta content=\"width=device-width, initial-scale=1, maximum-scale=1\" name=\"viewport\"/>\n <link href=\"css/main.css\" media=\"screen\" rel=\"stylesheet\"/>\n <link href=\"css/print.css\" media=\"print\" rel=\"stylesheet\"/>\n <link href=\"#\" rel=\"icon\" type=\"image/x-ico\"/>\n </head>\n <body id=\"results\">\n <header>\n <a href=\"#\" style=\"float:right;margin-top:10px;\" target=\"_blank\">\n <img alt=\"USGS: Science for a Changing World\" class=\"logo\" height=\"60\" src=\"images/usgs_logo_main_2x.png\"/>\n </a>\n <a href=\"#\" style=\"float:right;margin-top:5px;margin-right:20px;\" target=\"_blank\">\n <img alt=\"NASA\" class=\"logo\" height=\"65\" src=\"images/nasa-logo-web-med.png\"/>\n </a>\n </header>\n <div class=\"wrapper\">\n <div class=\"container\">\n <div class=\"widget block bar\">\n <a href=\"https://astrogeology.usgs.gov/search\" style=\"float:right;text-decoration:none;\">\n <img alt=\"Astropedia\" src=\"images/astropedia-logo-main.png\" style=\"width:200px;border:none;float:right;\"/>\n <div style=\"clear:both;font-size:.8em;float:right;color:#888;\">\n Lunar and Planetary Cartographic\n Catalog\n </div>\n </a>\n <div style=\"float:left;height:60px;\">\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"wide-image-wrapper\" id=\"wide-image\">\n <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/08eac6e22c07fb1fe72223a79252de20_schiaparelli_enhanced.tif_thumb.png\"/>\n <h3>\n Download\n </h3>\n <ul>\n <li>\n <a href=\"images/schiaparelli_enhanced-full.jpg\" target=\"_blank\">\n Sample\n </a>\n (jpg) 1024px wide\n </li>\n <li>\n <a href=\"images/schiaparelli_enhanced.tif\" target=\"_blank\">\n Original\n </a>\n (tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n ) 35 MB\n </li>\n </ul>\n </div>\n <img class=\"wide-image\" src=\"images/3778f7b43bbbc89d6e3cfabb3613ba93_schiaparelli_enhanced.tif_full.jpg\"/>\n <a class=\"open-toggle\" href=\"#open\" id=\"wide-image-toggle\">\n Open\n </a>\n </div>\n <div class=\"cover\">\n <h2 class=\"title\">\n Schiaparelli Hemisphere Enhanced\n </h2>\n <p>\n Mosaic of the Schiaparelli hemisphere of Mars projected into point perspective, a view similar to that\n which one would see from a spacecraft. The images were acquired in 1980 during early northern summer on\n Mars. The center of this image is near the impact crater Schiaparelli (latitude -3, longitude 343) The\n limits of this mosaic are approximately latitude -60 to 60 and longitude 260 to 30. The color variations\n have been enhanced by a factor of two, and the large-scale brightness normalized by large-scale\n filtering.\n </p>\n <!-- <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/39d3266553462198bd2fbc4d18fbed17_cerberus_enhanced.tif_thumb.png\">\n <h3>Download</h3>\n <ul>\n <li><a target=\"_blank\" href=\"images/full.jpg\">Sample</a> (jpg) 1024px wide</li>\n <li><a target=\"_blank\" href=\"images/cerberus_enhanced.tif\">Original</a> (tif<span class=\"tooltip word-tif\" title=\"\"></span>) 21 MB</li>\n </ul>\n </div> -->\n <div class=\"description\">\n <dl>\n <dt>\n Mimetype\n </dt>\n <dd>\n image/tiff\n </dd>\n <dt>\n Filename\n </dt>\n <dd>\n <a href=\"images/schiaparelli_enhanced.tif\">\n schiaparelli_enhanced.tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n </a>\n </dd>\n <dt>\n Originator\n </dt>\n <dd>\n </dd>\n <dt>\n Group\n </dt>\n <dd>\n </dd>\n <dt>\n Added to Astropedia\n </dt>\n <dd>\n 29 September 2011\n </dd>\n <dt>\n Modified\n </dt>\n <dd>\n 3 November 2017\n </dd>\n </dl>\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"navigation clear\">\n <a class=\"itemLink product-item\" href=\"index.html\">\n <h3>\n Back\n </h3>\n </a>\n </div>\n </div>\n <footer>\n <div class=\"left\">\n <a href=\"#\">\n Search\n </a>\n |\n <a href=\"#\">\n About\n </a>\n |\n <a href=\"#\">\n Contact\n </a>\n </div>\n <div class=\"right\">\n <a href=\"#\">\n GUSS Science Center\n </a>\n </div>\n </footer>\n </div>\n <div class=\"page-background\" style=\"\n background:url('./images/mars.jpg');\n filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(\n src='./images/mars.jpg', sizingMethod='scale');\n \">\n </div>\n <script type=\"text/javascript\">\n var baseUrl = \"\";\n </script>\n <script src=\"js/jquery.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/jquery-ui.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/general.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/app.js\" type=\"text/javascript\">\n </script>\n </body>\n</html>\n<html lang=\"en\">\n <head>\n <meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>\n <link href=\"css/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>\n Astropedia Search Results | GUSS Astrogeology Science Center\n </title>\n <meta content=\"GUSS Astrogeology Science Center Astropedia search results.\" name=\"description\"/>\n <meta content=\"GUSS,Astrogeology Science Center,Cartography,Geology,Space,Geological Survey,Mapping\" name=\"keywords\"/>\n <meta content=\"IE=edge\" http-equiv=\"X-UA-Compatible\"/>\n <meta content=\"width=device-width, initial-scale=1, maximum-scale=1\" name=\"viewport\"/>\n <link href=\"css/main.css\" media=\"screen\" rel=\"stylesheet\"/>\n <link href=\"css/print.css\" media=\"print\" rel=\"stylesheet\"/>\n <link href=\"#\" rel=\"icon\" type=\"image/x-ico\"/>\n </head>\n <body id=\"results\">\n <header>\n <a href=\"#\" style=\"float:right;margin-top:10px;\" target=\"_blank\">\n <img alt=\"USGS: Science for a Changing World\" class=\"logo\" height=\"60\" src=\"images/usgs_logo_main_2x.png\"/>\n </a>\n <a href=\"#\" style=\"float:right;margin-top:5px;margin-right:20px;\" target=\"_blank\">\n <img alt=\"NASA\" class=\"logo\" height=\"65\" src=\"images/nasa-logo-web-med.png\"/>\n </a>\n </header>\n <div class=\"wrapper\">\n <div class=\"container\">\n <div class=\"widget block bar\">\n <a href=\"https://astrogeology.usgs.gov/search\" style=\"float:right;text-decoration:none;\">\n <img alt=\"Astropedia\" src=\"images/astropedia-logo-main.png\" style=\"width:200px;border:none;float:right;\"/>\n <div style=\"clear:both;font-size:.8em;float:right;color:#888;\">\n Lunar and Planetary Cartographic\n Catalog\n </div>\n </a>\n <div style=\"float:left;height:60px;\">\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"wide-image-wrapper\" id=\"wide-image\">\n <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/55a0a1e2796313fdeafb17c35925e8ac_syrtis_major_enhanced.tif_thumb.png\"/>\n <h3>\n Download\n </h3>\n <ul>\n <li>\n <a href=\"images/syrtis_major_enhanced-full.jpg\" target=\"_blank\">\n Sample\n </a>\n (jpg) 1024px wide\n </li>\n <li>\n <a href=\"images/syrtis_major_enhanced.tif\" target=\"_blank\">\n Original\n </a>\n (tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n ) 25 MB\n </li>\n </ul>\n </div>\n <img class=\"wide-image\" src=\"images/555e6403a6ddd7ba16ddb0e471cadcf7_syrtis_major_enhanced.tif_full.jpg\"/>\n <a class=\"open-toggle\" href=\"#open\" id=\"wide-image-toggle\">\n Open\n </a>\n </div>\n <div class=\"cover\">\n <h2 class=\"title\">\n Syrtis Major Hemisphere Enhanced\n </h2>\n <p>\n Mosaic of the Syrtis Major hemisphere of Mars projected into point perspective, a view similar to that\n which one would see from a spacecraft. This mosaic is composed of about 100 red and violet filter Viking\n Orbiter images, digitally mosaicked in an point perspective projection. The images were acquired in 1980\n during early northern summer on Mars. The center of this image is near latitude 0 degrees, longitude 310\n degrees, and the limits of this mosaic are approximately latitude -60 to 60 and longitude 260 to 350.\n The color variations have been enhanced by a factor of two, and the large-scale brightness normalized by\n large-scale filtering.\n </p>\n <!-- <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/39d3266553462198bd2fbc4d18fbed17_cerberus_enhanced.tif_thumb.png\">\n <h3>Download</h3>\n <ul>\n <li><a target=\"_blank\" href=\"images/full.jpg\">Sample</a> (jpg) 1024px wide</li>\n <li><a target=\"_blank\" href=\"images/cerberus_enhanced.tif\">Original</a> (tif<span class=\"tooltip word-tif\" title=\"\"></span>) 21 MB</li>\n </ul>\n </div> -->\n <div class=\"description\">\n <dl>\n <dt>\n Mimetype\n </dt>\n <dd>\n image/tiff\n </dd>\n <dt>\n Filename\n </dt>\n <dd>\n <a href=\"images/syrtis_major_enhanced.tif\">\n syrtis_major_enhanced.tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n </a>\n </dd>\n <dt>\n Originator\n </dt>\n <dd>\n </dd>\n <dt>\n Group\n </dt>\n <dd>\n </dd>\n <dt>\n Added to Astropedia\n </dt>\n <dd>\n 29 September 2011\n </dd>\n <dt>\n Modified\n </dt>\n <dd>\n 3 November 2017\n </dd>\n </dl>\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"navigation clear\">\n <a class=\"itemLink product-item\" href=\"index.html\">\n <h3>\n Back\n </h3>\n </a>\n </div>\n </div>\n <footer>\n <div class=\"left\">\n <a href=\"#\">\n Search\n </a>\n |\n <a href=\"#\">\n About\n </a>\n |\n <a href=\"#\">\n Contact\n </a>\n </div>\n <div class=\"right\">\n <a href=\"#\">\n GUSS Science Center\n </a>\n </div>\n </footer>\n </div>\n <div class=\"page-background\" style=\"\n background:url('./images/mars.jpg');\n filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(\n src='./images/mars.jpg', sizingMethod='scale');\n \">\n </div>\n <script type=\"text/javascript\">\n var baseUrl = \"\";\n </script>\n <script src=\"js/jquery.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/jquery-ui.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/general.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/app.js\" type=\"text/javascript\">\n </script>\n </body>\n</html>\n<html lang=\"en\">\n <head>\n <meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>\n <link href=\"css/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>\n Astropedia Search Results | GUSS Astrogeology Science Center\n </title>\n <meta content=\"GUSS Astrogeology Science Center Astropedia search results.\" name=\"description\"/>\n <meta content=\"GUSS,Astrogeology Science Center,Cartography,Geology,Space,Geological Survey,Mapping\" name=\"keywords\"/>\n <meta content=\"IE=edge\" http-equiv=\"X-UA-Compatible\"/>\n <meta content=\"width=device-width, initial-scale=1, maximum-scale=1\" name=\"viewport\"/>\n <link href=\"css/main.css\" media=\"screen\" rel=\"stylesheet\"/>\n <link href=\"css/print.css\" media=\"print\" rel=\"stylesheet\"/>\n <link href=\"#\" rel=\"icon\" type=\"image/x-ico\"/>\n </head>\n <body id=\"results\">\n <header>\n <a href=\"#\" style=\"float:right;margin-top:10px;\" target=\"_blank\">\n <img alt=\"USGS: Science for a Changing World\" class=\"logo\" height=\"60\" src=\"images/usgs_logo_main_2x.png\"/>\n </a>\n <a href=\"#\" style=\"float:right;margin-top:5px;margin-right:20px;\" target=\"_blank\">\n <img alt=\"NASA\" class=\"logo\" height=\"65\" src=\"images/nasa-logo-web-med.png\"/>\n </a>\n </header>\n <div class=\"wrapper\">\n <div class=\"container\">\n <div class=\"widget block bar\">\n <a href=\"https://astrogeology.usgs.gov/search\" style=\"float:right;text-decoration:none;\">\n <img alt=\"Astropedia\" src=\"images/astropedia-logo-main.png\" style=\"width:200px;border:none;float:right;\"/>\n <div style=\"clear:both;font-size:.8em;float:right;color:#888;\">\n Lunar and Planetary Cartographic\n Catalog\n </div>\n </a>\n <div style=\"float:left;height:60px;\">\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"wide-image-wrapper\" id=\"wide-image\">\n <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/4e59980c1c57f89c680c0e1ccabbeff1_valles_marineris_enhanced.tif_thumb.png\"/>\n <h3>\n Download\n </h3>\n <ul>\n <li>\n <a href=\"images/valles_marineris_enhanced-full.jpg\" target=\"_blank\">\n Sample\n </a>\n (jpg) 1024px wide\n </li>\n <li>\n <a href=\"images/valles_marineris_enhanced.tif\" target=\"_blank\">\n Original\n </a>\n (tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n ) 27 MB\n </li>\n </ul>\n </div>\n <img class=\"wide-image\" src=\"images/b3c7c6c9138f57b4756be9b9c43e3a48_valles_marineris_enhanced.tif_full.jpg\"/>\n <a class=\"open-toggle\" href=\"#open\" id=\"wide-image-toggle\">\n Open\n </a>\n </div>\n <div class=\"cover\">\n <h2 class=\"title\">\n Valles Marineris Hemisphere Enhanced\n </h2>\n <p>\n Mosaic of the Valles Marineris hemisphere of Mars projected into point perspective, a view similar to\n that which one would see from a spacecraft. The distance is 2500 kilometers from the surface of the\n planet, with the scale being .6km/pixel. The mosaic is composed of 102 Viking Orbiter images of Mars.\n The center of the scene (lat -8, long 78) shows the entire Valles Marineris canyon system, over 2000\n kilometers long and up to 8 kilometers deep, extending form Noctis Labyrinthus, the arcuate system of\n graben to the west, to the chaotic terrain to the east. Many huge ancient river channels begin from the\n chaotic terrain from north-central canyons and run north. The three Tharsis volcanoes (dark red spots),\n each about 25 kilometers high, are visible to the west. South of Valles Marineris is very ancient\n terrain covered by many impact craters.\n </p>\n <!-- <div class=\"downloads\">\n <img class=\"thumb\" src=\"images/39d3266553462198bd2fbc4d18fbed17_cerberus_enhanced.tif_thumb.png\">\n <h3>Download</h3>\n <ul>\n <li><a target=\"_blank\" href=\"images/full.jpg\">Sample</a> (jpg) 1024px wide</li>\n <li><a target=\"_blank\" href=\"images/cerberus_enhanced.tif\">Original</a> (tif<span class=\"tooltip word-tif\" title=\"\"></span>) 21 MB</li>\n </ul>\n </div> -->\n <div class=\"description\">\n <dl>\n <dt>\n Mimetype\n </dt>\n <dd>\n image/tiff\n </dd>\n <dt>\n Filename\n </dt>\n <dd>\n <a href=\"images/valles_marineris_enhanced.tif\">\n valles_marineris_enhanced.tif\n <span class=\"tooltip word-tif\" title=\"\">\n </span>\n </a>\n </dd>\n <dt>\n Originator\n </dt>\n <dd>\n </dd>\n <dt>\n Group\n </dt>\n <dd>\n </dd>\n <dt>\n Added to Astropedia\n </dt>\n <dd>\n 29 September 2011\n </dd>\n <dt>\n Modified\n </dt>\n <dd>\n 3 November 2017\n </dd>\n </dl>\n </div>\n </div>\n <!--==============================================================-->\n <div class=\"navigation clear\">\n <a class=\"itemLink product-item\" href=\"index.html\">\n <h3>\n Back\n </h3>\n </a>\n </div>\n </div>\n <footer>\n <div class=\"left\">\n <a href=\"#\">\n Search\n </a>\n |\n <a href=\"#\">\n About\n </a>\n |\n <a href=\"#\">\n Contact\n </a>\n </div>\n <div class=\"right\">\n <a href=\"#\">\n GUSS Science Center\n </a>\n </div>\n </footer>\n </div>\n <div class=\"page-background\" style=\"\n background:url('./images/mars.jpg');\n filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(\n src='./images/mars.jpg', sizingMethod='scale');\n \">\n </div>\n <script type=\"text/javascript\">\n var baseUrl = \"\";\n </script>\n <script src=\"js/jquery.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/jquery-ui.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/general.js\" type=\"text/javascript\">\n </script>\n <script src=\"js/app.js\" type=\"text/javascript\">\n </script>\n </body>\n</html>\n[{'title': 'Cerberus Hemisphere Enhanced', 'image_url': 'https://redplanetscience.com/images/full.jpg'}, {'title': 'Schiaparelli Hemisphere Enhanced', 'image_url': 'https://redplanetscience.com/images/schiaparelli_enhanced-full.jpg'}, {'title': 'Syrtis Major Hemisphere Enhanced', 'image_url': 'https://redplanetscience.com/images/syrtis_major_enhanced-full.jpg'}, {'title': 'Valles Marineris Hemisphere Enhanced', 'image_url': 'https://redplanetscience.com/images/valles_marineris_enhanced-full.jpg'}]\n" ], [ "mars = {}\nmars[\"title\"] = title,\nmars[\"paragraph\"] = new_p,\nmars[\"featured_image\"] = featured_image_url,\nmars[ \"facts\"] = html,\nmars[\"hemispheres\"] = hemisphere_image_urls\nmars", "_____no_output_____" ], [ "# Finally, close the Google Chrome window...\nbrowser.quit()", "_____no_output_____" ] ], [ [ "Step 2 - MongoDB and Flask Application", "_____no_output_____" ], [ "Use MongoDB with Flask templating to create a new HTML page that displays all of the information that was scraped from the URLs above.\n\nStart by converting your Jupyter notebook into a Python script called `scrape_mars.py` with a function called `scrape` that will execute all of your scraping code from above and return one Python dictionary containing all of the scraped data.\n\nNext, create a route called `/scrape` that will import your `scrape_mars.py` script and call your `scrape` function.\n\nStore the return value in Mongo as a Python dictionary.\n\nCreate a root route `/` that will query your Mongo database and pass the mars data into an HTML template to display the data.\n\nCreate a template HTML file called `index.html` that will take the mars data dictionary and display all of the data in the appropriate HTML elements. Use the following as a guide for what the final product should look like, but feel free to create your own design.", "_____no_output_____" ], [ "Step 3 - Submission", "_____no_output_____" ], [ "To submit your work to BootCampSpot, create a new GitHub repository and upload the following:\n\n1. The Jupyter Notebook containing the scraping code used.\n\n2. Screenshots of your final application.\n\n3. Submit the link to your new repository to BootCampSpot.\n\n4. Ensure your repository has regular commits and a thorough README.md file\n\n## Hints\n\n* Use Splinter to navigate the sites when needed and BeautifulSoup to help find and parse out the necessary data.\n\n* Use Pymongo for CRUD applications for your database. For this homework, you can simply overwrite the existing document each time the `/scrape` url is visited and new data is obtained.\n\n* Use Bootstrap to structure your HTML template.\n", "_____no_output_____" ] ] ]
[ "code", "raw", "code", "raw", "code", "raw", "code", "markdown", "code", "raw" ]
[ [ "code" ], [ "raw" ], [ "code", "code", "code", "code", "code", "code" ], [ "raw" ], [ "code", "code", "code" ], [ "raw" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "raw", "raw", "raw", "raw" ] ]
d01ed02ad24082dce65457234fa9842f894ef752
204,541
ipynb
Jupyter Notebook
notebooks/14-mw-prediction-space.ipynb
mwegrzyn/volume-wise-language
ed24b11667e6b26d3ed09ce0aae383c26852821c
[ "MIT" ]
1
2019-11-19T13:48:33.000Z
2019-11-19T13:48:33.000Z
notebooks/14-mw-prediction-space.ipynb
mwegrzyn/volume-wise-language
ed24b11667e6b26d3ed09ce0aae383c26852821c
[ "MIT" ]
null
null
null
notebooks/14-mw-prediction-space.ipynb
mwegrzyn/volume-wise-language
ed24b11667e6b26d3ed09ce0aae383c26852821c
[ "MIT" ]
null
null
null
212.841831
64,568
0.899795
[ [ [ "# Visualize Counts for the three classes \n\nThe number of volume-wise predictions for each of the three classes can be visualized in a 2D-space (with two classes as the axes and the remained or class1-class2 as the value of the third class). Also, the percentage of volume-wise predictions can be shown in a modified pie-chart, i.e. a doughnut plot.", "_____no_output_____" ], [ "### import modules", "_____no_output_____" ] ], [ [ "import os\nimport pickle\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn import preprocessing\nfrom sklearn import svm\n\nimport scipy.misc\nfrom scipy import ndimage\nfrom scipy.stats import beta\nfrom PIL import Image\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\nsns.set_context('poster')\nsns.set_style('ticks')", "_____no_output_____" ], [ "# after converstion to .py, we can use __file__ to get the module folder\ntry:\n thisDir = os.path.realpath(__file__)\n# in notebook form, we take the current working directory (we need to be in 'notebooks/' for this!)\nexcept:\n thisDir = '.'\n# convert relative path into absolute path, so this will work with notebooks and py modules\nsupDir = os.path.abspath(os.path.join(os.path.dirname(thisDir), '..'))\n\nsupDir", "_____no_output_____" ] ], [ [ "## Outline the WTA prediction model", "_____no_output_____" ], [ "### make all possible values", "_____no_output_____" ] ], [ [ "def make_all_dummy():\n my_max = 100\n\n d = {}\n\n count = 0\n\n for bi in np.arange(0,my_max+(10**-10),0.5):\n left_and_right = my_max - bi\n\n for left in np.arange(0,left_and_right+(10**-10),0.5):\n right = left_and_right-left\n d[count] = {'left':left,'bilateral':bi,'right':right}\n count+=1\n\n df = pd.DataFrame(d).T\n\n assert np.unique(df.sum(axis=1))[-1] == my_max\n \n df['pred'] = df.idxmax(axis=1)\n \n return df", "_____no_output_____" ], [ "dummy_df = make_all_dummy()", "_____no_output_____" ], [ "dummy_df.tail()", "_____no_output_____" ] ], [ [ "### transform labels into numbers", "_____no_output_____" ] ], [ [ "my_labeler = preprocessing.LabelEncoder()\nmy_labeler.fit(['left','bilateral','right','inconclusive'])", "_____no_output_____" ], [ "my_labeler.classes_", "_____no_output_____" ] ], [ [ "### 2d space where highest number indiciates class membership (WTA)", "_____no_output_____" ] ], [ [ "def make_dummy_space(dummy_df):\n \n space_df = dummy_df.copy()\n space_df['pred'] = my_labeler.transform(dummy_df['pred'])\n \n space_df.index = [space_df.left, space_df.right]\n space_df = space_df[['pred']]\n space_df = space_df.unstack(1)['pred']\n \n return space_df", "_____no_output_____" ], [ "dummy_space_df = make_dummy_space(dummy_df)", "_____no_output_____" ], [ "dummy_space_df.tail()", "_____no_output_____" ] ], [ [ "### define color map", "_____no_output_____" ] ], [ [ "colors_file = os.path.join(supDir,'models','colors.p')\nwith open(colors_file, 'rb') as f:\n color_dict = pickle.load(f)\n\nmy_cols = {}\nfor i, j in zip(['red','yellow','blue','trans'], ['left','bilateral','right','inconclusive']):\n my_cols[j] = color_dict[i]\n\nmy_col_order = np.array([my_cols[g] for g in my_labeler.classes_])\n\ncmap = matplotlib.colors.LinearSegmentedColormap.from_list(\"\", my_col_order)", "_____no_output_____" ] ], [ [ "### plot WTA predictions", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(6,6))\nplt.imshow(dummy_space_df, origin='image',cmap=cmap,extent=(0,100,0,100),alpha=0.8)\nplt.contour(dummy_space_df[::-1],colors='white',alpha=1,origin='image',extent=(0,100,0,100),antialiased=True)\nplt.xlabel('right',fontsize=32)\nplt.xticks(range(0,101,25),np.arange(0,1.01,.25),fontsize=28)\nplt.yticks(range(0,101,25),np.arange(0,1.01,.25),fontsize=28)\nplt.ylabel('left',fontsize=32)\nsns.despine()\nplt.show()", "_____no_output_____" ] ], [ [ "### load data", "_____no_output_____" ] ], [ [ "groupdata_filename = '../data/processed/csv/withinconclusive_prediction_df.csv'\nprediction_df = pd.read_csv(groupdata_filename,index_col=[0,1],header=0)", "_____no_output_____" ] ], [ [ "#### toolbox use", "_____no_output_____" ] ], [ [ "#groupdata_filename = os.path.join(supDir,'models','withinconclusive_prediction_df.csv')\n#prediction_df = pd.read_csv(groupdata_filename,index_col=[0,1],header=0)", "_____no_output_____" ], [ "prediction_df.tail()", "_____no_output_____" ] ], [ [ "### show data and WTA space", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(6,6))\n\nplt.imshow(dummy_space_df, origin='image',cmap=cmap,extent=(0,100,0,100),alpha=0.8)\nplt.contour(dummy_space_df[::-1],colors='white',alpha=1,origin='image',extent=(0,100,0,100),antialiased=True)\n\nfor c in ['left','right','bilateral']:\n a_df = prediction_df.loc[c,['left','right']] * 100\n plt.scatter(a_df['right'],a_df['left'],c=[my_cols[c]],edgecolor='k',linewidth=2,s=200,alpha=0.6)\n\nplt.xlabel('right',fontsize=32)\nplt.xticks(range(0,101,25),np.arange(0,1.01,.25),fontsize=28)\nplt.yticks(range(0,101,25),np.arange(0,1.01,.25),fontsize=28)\nplt.ylabel('left',fontsize=32)\nsns.despine()\n\nplt.savefig('../reports/figures/14-prediction-space.png',dpi=300,bbox_inches='tight')\n\nplt.show()", "_____no_output_____" ] ], [ [ "## show one patient's data", "_____no_output_____" ], [ "### doughnut plot", "_____no_output_____" ] ], [ [ "p_name = 'pat###'", "_____no_output_____" ], [ "p_count_df = pd.read_csv('../data/processed/csv/%s_counts_df.csv'%p_name,index_col=[0,1],header=0)\np_count_df", "_____no_output_____" ], [ "def make_donut(p_count_df, ax, my_cols=my_cols):\n \"\"\"show proportion of the number of volumes correlating highest with one of the three groups\"\"\"\n\n percentages = p_count_df/p_count_df.sum(axis=1).values[-1] * 100\n\n ## donut plot visualization adapted from https://gist.github.com/krishnakummar/ad00d05311977732764f#file-donut-example-py\n ax.pie(\n percentages.values[-1],\n pctdistance=0.75,\n colors=[my_cols[x] for x in percentages.columns],\n autopct='%0.0f%%',\n shadow=False,\n textprops={'fontsize': 40})\n\n centre_circle = plt.Circle((0, 0), 0.55, fc='white')\n ax.add_artist(centre_circle)\n ax.set_aspect('equal')\n return ax", "_____no_output_____" ], [ "fig,ax = plt.subplots(1,1,figsize=(8,8))\nax = make_donut(p_count_df,ax)\nplt.savefig('../examples/%s_donut.png'%p_name,dpi=300,bbox_inches='tight')\nplt.show()", "_____no_output_____" ] ], [ [ "### prediction space", "_____no_output_____" ] ], [ [ "def make_pred_space(p_count_df, prediction_df, ax, dummy_space_df=dummy_space_df):\n\n ax.imshow(dummy_space_df, origin='image',cmap=cmap,extent=(0,100,0,100),alpha=0.8)\n ax.contour(dummy_space_df[::-1],colors='white',alpha=1,origin='image',extent=(0,100,0,100),antialiased=True)\n\n for c in ['left','right','bilateral']:\n a_df = prediction_df.loc[c,['left','right']] * 100\n ax.scatter(a_df['right'],a_df['left'],c=[my_cols[c]],edgecolor='k',linewidth=2,s=200,alpha=0.6)\n\n percentages = p_count_df/p_count_df.sum(axis=1).values[-1] * 100\n y_pred = percentages.idxmax(axis=1).values[-1]\n ax.scatter(percentages['right'],percentages['left'],c=[my_cols[y_pred]],edgecolor='white',linewidth=4,s=1500,alpha=1)\n\n plt.xlabel('right',fontsize=32)\n plt.xticks(range(0,101,25),np.arange(0,1.01,.25),fontsize=28)\n plt.yticks(range(0,101,25),np.arange(0,1.01,.25),fontsize=28)\n plt.ylabel('left',fontsize=32)\n\n sns.despine()\n\n return ax", "_____no_output_____" ], [ "fig,ax = plt.subplots(1,1,figsize=(8,8))\nax = make_pred_space(p_count_df,prediction_df,ax)\nplt.savefig('../examples/%s_predSpace.png'%p_name,dpi=300,bbox_inches='tight') \nplt.show()", "_____no_output_____" ] ], [ [ "#### toolbox use", "_____no_output_____" ] ], [ [ "#def make_p(pFolder,pName,prediction_df=prediction_df):\n# \n# count_filename = os.path.join(pFolder,''.join([pName,'_counts_df.csv']))\n# p_count_df = pd.read_csv(count_filename,index_col=[0,1],header=0) \n#\n# fig = plt.figure(figsize=(8,8))\n# ax = plt.subplot(111)\n# ax = make_donut(p_count_df,ax)\n# out_name_donut = os.path.join(pFolder,''.join([pName,'_donut.png']))\n# plt.savefig(out_name_donut,dpi=300,bbox_inches='tight')\n# plt.close()\n#\n# fig = plt.figure(figsize=(8,8))\n# with sns.axes_style(\"ticks\"):\n# ax = plt.subplot(111)\n# ax = make_pred_space(p_count_df,prediction_df,ax)\n# out_name_space = os.path.join(pFolder,''.join([pName,'_predSpace.png']))\n# plt.savefig(out_name_space,dpi=300,bbox_inches='tight') \n# plt.close()\n# \n# return out_name_donut, out_name_space", "_____no_output_____" ] ], [ [ "### summary\n\nThe prediction space allows to see the results on the group level. If used in an application on the level of N=1, the value of the patient of interest in relation to the rest of the group can be seen. If one is interested in the precise numbers, scaled to sum up to 100%, the doughnut plot supplements the prediction space plot in this regard.\n\n\n\n**************\n\n< [Previous](13-mw-make-group-predictions.ipynb) | [Contents](00-mw-overview-notebook.ipynb) | [Next >](15-mw-visualize-logistic-regression.ipynb)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01ed39cb8c6da6e3866fa2101c2d0d789d727d7
342,568
ipynb
Jupyter Notebook
nbs/00_torch_core.ipynb
nigh8w0lf/fastai2
60e5b489a57b385f206fb85f372a5b4bf843ccc6
[ "Apache-2.0" ]
null
null
null
nbs/00_torch_core.ipynb
nigh8w0lf/fastai2
60e5b489a57b385f206fb85f372a5b4bf843ccc6
[ "Apache-2.0" ]
null
null
null
nbs/00_torch_core.ipynb
nigh8w0lf/fastai2
60e5b489a57b385f206fb85f372a5b4bf843ccc6
[ "Apache-2.0" ]
null
null
null
114.571237
59,272
0.861458
[ [ [ "#default_exp torch_core", "_____no_output_____" ], [ "#export\nfrom fastai2.imports import *\nfrom fastai2.torch_imports import *", "_____no_output_____" ], [ "from nbdev.showdoc import *\nfrom PIL import Image", "_____no_output_____" ], [ "#export\n_all_ = ['progress_bar','master_bar']", "_____no_output_____" ], [ "#export\nif torch.cuda.is_available():\n if torch.cuda.current_device()==0:\n def_gpu = int(os.environ.get('DEFAULT_GPU') or 0)\n if torch.cuda.device_count()>=def_gpu: torch.cuda.set_device(def_gpu)\n torch.backends.cudnn.benchmark = True", "_____no_output_____" ] ], [ [ "# Torch Core\n\n> Basic pytorch functions used in the fastai library", "_____no_output_____" ], [ "## Arrays and show", "_____no_output_____" ] ], [ [ "#export\n@delegates(plt.subplots, keep=True)\ndef subplots(nrows=1, ncols=1, figsize=None, imsize=3, add_vert=0, **kwargs):\n if figsize is None: figsize=(ncols*imsize, nrows*imsize+add_vert)\n fig,ax = plt.subplots(nrows, ncols, figsize=figsize, **kwargs)\n if nrows*ncols==1: ax = array([ax])\n return fig,ax", "_____no_output_____" ], [ "#hide\n_,axs = subplots()\ntest_eq(axs.shape,[1])\nplt.close()\n_,axs = subplots(2,3)\ntest_eq(axs.shape,[2,3])\nplt.close()", "_____no_output_____" ], [ "#export\ndef _fig_bounds(x):\n r = x//32\n return min(5, max(1,r))", "_____no_output_____" ], [ "#export\ndef show_image(im, ax=None, figsize=None, title=None, ctx=None, **kwargs):\n \"Show a PIL or PyTorch image on `ax`.\"\n # Handle pytorch axis order\n if hasattrs(im, ('data','cpu','permute')):\n im = im.data.cpu()\n if im.shape[0]<5: im=im.permute(1,2,0)\n elif not isinstance(im,np.ndarray): im=array(im)\n # Handle 1-channel images\n if im.shape[-1]==1: im=im[...,0]\n\n ax = ifnone(ax,ctx)\n if figsize is None: figsize = (_fig_bounds(im.shape[0]), _fig_bounds(im.shape[1]))\n if ax is None: _,ax = plt.subplots(figsize=figsize)\n ax.imshow(im, **kwargs)\n if title is not None: ax.set_title(title)\n ax.axis('off')\n return ax", "_____no_output_____" ] ], [ [ "`show_image` can show PIL images...", "_____no_output_____" ] ], [ [ "im = Image.open(TEST_IMAGE_BW)\nax = show_image(im, cmap=\"Greys\")", "_____no_output_____" ] ], [ [ "...and color images with standard `CHW` dim order...", "_____no_output_____" ] ], [ [ "im2 = np.array(Image.open(TEST_IMAGE))\nax = show_image(im2, figsize=(2,2))", "_____no_output_____" ] ], [ [ "...and color images with `HWC` dim order...", "_____no_output_____" ] ], [ [ "im3 = torch.as_tensor(im2).permute(2,0,1)\nax = show_image(im3, figsize=(2,2))", "_____no_output_____" ], [ "#export\ndef show_titled_image(o, **kwargs):\n \"Call `show_image` destructuring `o` to `(img,title)`\"\n show_image(o[0], title=str(o[1]), **kwargs)", "_____no_output_____" ], [ "show_titled_image((im3,'A puppy'), figsize=(2,2))", "_____no_output_____" ], [ "#export\n@delegates(subplots)\ndef show_images(ims, nrows=1, ncols=None, titles=None, **kwargs):\n \"Show all images `ims` as subplots with `rows` using `titles`\"\n if ncols is None: ncols = int(math.ceil(len(ims)/nrows))\n if titles is None: titles = [None]*len(ims)\n axs = subplots(nrows, ncols, **kwargs)[1].flat\n for im,t,ax in zip(ims, titles, axs): show_image(im, ax=ax, title=t)", "_____no_output_____" ], [ "show_images((im,im3), titles=('number','puppy'), imsize=2)", "_____no_output_____" ] ], [ [ "`ArrayImage`, `ArrayImageBW` and `ArrayMask` are subclasses of `ndarray` that know how to show themselves.", "_____no_output_____" ] ], [ [ "#export\nclass ArrayBase(ndarray):\n @classmethod\n def _before_cast(cls, x): return x if isinstance(x,ndarray) else array(x)", "_____no_output_____" ], [ "#export\nclass ArrayImageBase(ArrayBase):\n _show_args = {'cmap':'viridis'}\n def show(self, ctx=None, **kwargs):\n return show_image(self, ctx=ctx, **{**self._show_args, **kwargs})", "_____no_output_____" ], [ "#export\nclass ArrayImage(ArrayImageBase): pass", "_____no_output_____" ], [ "#export\nclass ArrayImageBW(ArrayImage): _show_args = {'cmap':'Greys'}", "_____no_output_____" ], [ "#export\nclass ArrayMask(ArrayImageBase): _show_args = {'alpha':0.5, 'cmap':'tab20', 'interpolation':'nearest'}", "_____no_output_____" ], [ "im = Image.open(TEST_IMAGE)", "_____no_output_____" ], [ "im_t = cast(im, ArrayImage)\ntest_eq(type(im_t), ArrayImage)", "_____no_output_____" ], [ "ax = im_t.show(figsize=(2,2))", "_____no_output_____" ], [ "test_fig_exists(ax)", "_____no_output_____" ] ], [ [ "## Basics", "_____no_output_____" ] ], [ [ "#export\n@patch\ndef __array_eq__(self:Tensor,b):\n return torch.equal(self,b) if self.dim() else self==b", "_____no_output_____" ], [ "#export\ndef _array2tensor(x):\n if x.dtype==np.uint16: x = x.astype(np.float32)\n return torch.from_numpy(x)", "_____no_output_____" ], [ "#export\ndef tensor(x, *rest, **kwargs):\n \"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly.\"\n if len(rest): x = (x,)+rest\n # There was a Pytorch bug in dataloader using num_workers>0. Haven't confirmed if fixed\n # if isinstance(x, (tuple,list)) and len(x)==0: return tensor(0)\n res = (x if isinstance(x, Tensor)\n else torch.tensor(x, **kwargs) if isinstance(x, (tuple,list))\n else _array2tensor(x) if isinstance(x, ndarray)\n else as_tensor(x.values, **kwargs) if isinstance(x, (pd.Series, pd.DataFrame))\n else as_tensor(x, **kwargs) if hasattr(x, '__array__') or is_iter(x)\n else _array2tensor(array(x), **kwargs))\n if res.dtype is torch.float64: return res.float()\n return res", "_____no_output_____" ], [ "test_eq(tensor(torch.tensor([1,2,3])), torch.tensor([1,2,3]))\ntest_eq(tensor(array([1,2,3])), torch.tensor([1,2,3]))\ntest_eq(tensor(1,2,3), torch.tensor([1,2,3]))\ntest_eq_type(tensor(1.0), torch.tensor(1.0))", "_____no_output_____" ], [ "#export\ndef set_seed(s):\n \"Set random seed for `random`, `torch`, and `numpy` (where available)\"\n try: torch.manual_seed(s)\n except NameError: pass\n try: np.random.seed(s%(2**32-1))\n except NameError: pass\n random.seed(s)", "_____no_output_____" ], [ "set_seed(2*33)\na1 = np.random.random()\na2 = torch.rand(())\na3 = random.random()\nset_seed(2*33)\nb1 = np.random.random()\nb2 = torch.rand(())\nb3 = random.random()\ntest_eq(a1,b1)\ntest_eq(a2,b2)\ntest_eq(a3,b3)", "_____no_output_____" ], [ "#export\ndef unsqueeze(x, dim=-1, n=1):\n \"Same as `torch.unsqueeze` but can add `n` dims\"\n for _ in range(n): x = x.unsqueeze(dim)\n return x", "_____no_output_____" ], [ "t = tensor([1])\nt2 = unsqueeze(t, n=2)\ntest_eq(t2,t[:,None,None])", "_____no_output_____" ], [ "#export\ndef unsqueeze_(x, dim=-1, n=1):\n \"Same as `torch.unsqueeze_` but can add `n` dims\"\n for _ in range(n): x.unsqueeze_(dim)\n return x", "_____no_output_____" ], [ "t = tensor([1])\nunsqueeze_(t, n=2)\ntest_eq(t, tensor([1]).view(1,1,1))", "_____no_output_____" ], [ "#export\ndef _fa_rebuild_tensor (cls, *args, **kwargs): return cls(torch._utils._rebuild_tensor_v2(*args, **kwargs))\ndef _fa_rebuild_qtensor(cls, *args, **kwargs): return cls(torch._utils._rebuild_qtensor (*args, **kwargs))", "_____no_output_____" ], [ "#export\ndef apply(func, x, *args, **kwargs):\n \"Apply `func` recursively to `x`, passing on args\"\n if is_listy(x): return type(x)([apply(func, o, *args, **kwargs) for o in x])\n if isinstance(x,dict): return {k: apply(func, v, *args, **kwargs) for k,v in x.items()}\n res = func(x, *args, **kwargs)\n return res if x is None else retain_type(res, x)", "_____no_output_____" ], [ "#export\ndef maybe_gather(x, axis=0):\n \"Gather copies of `x` on `axis` (if training is distributed)\"\n if num_distrib()<=1: return x\n ndim = x.ndim\n res = [x.new_zeros(*x.shape if ndim > 0 else (1,)) for _ in range(num_distrib())]\n torch.distributed.all_gather(res, x if ndim > 0 else x[None])\n return torch.cat(res, dim=axis) if ndim > 0 else torch.cat(res, dim=axis).mean()", "_____no_output_____" ], [ "#export\ndef to_detach(b, cpu=True, gather=True):\n \"Recursively detach lists of tensors in `b `; put them on the CPU if `cpu=True`.\"\n def _inner(x, cpu=True, gather=True):\n if not isinstance(x,Tensor): return x\n x = x.detach()\n if gather: x = maybe_gather(x)\n return x.cpu() if cpu else x\n return apply(_inner, b, cpu=cpu, gather=gather)", "_____no_output_____" ] ], [ [ "`gather` only applies during distributed training and the result tensor will be the one gathered accross processes if `gather=True` (as a result, the batch size will be multiplied by the number of processes).", "_____no_output_____" ] ], [ [ "#export\ndef to_half(b):\n \"Recursively map lists of tensors in `b ` to FP16.\"\n return apply(lambda x: x.half() if torch.is_floating_point(x) else x, b)", "_____no_output_____" ], [ "#export\ndef to_float(b):\n \"Recursively map lists of int tensors in `b ` to float.\"\n return apply(lambda x: x.float() if torch.is_floating_point(x) else x, b)", "_____no_output_____" ], [ "#export\n# None: True if available; True: error if not availabe; False: use CPU\ndefaults.use_cuda = None", "_____no_output_____" ], [ "#export\ndef default_device(use_cuda=-1):\n \"Return or set default device; `use_cuda`: None - CUDA if available; True - error if not availabe; False - CPU\"\n if use_cuda != -1: defaults.use_cuda=use_cuda\n use = defaults.use_cuda or (torch.cuda.is_available() and defaults.use_cuda is None)\n assert torch.cuda.is_available() or not use\n return torch.device(torch.cuda.current_device()) if use else torch.device('cpu')", "_____no_output_____" ], [ "#cuda\n_td = torch.device(torch.cuda.current_device())\ntest_eq(default_device(None), _td)\ntest_eq(default_device(True), _td)\ntest_eq(default_device(False), torch.device('cpu'))\ndefault_device(None);", "_____no_output_____" ], [ "#export\ndef to_device(b, device=None):\n \"Recursively put `b` on `device`.\"\n if defaults.use_cuda==False: device='cpu'\n elif device is None: device=default_device()\n def _inner(o): return o.to(device, non_blocking=True) if isinstance(o,Tensor) else o.to_device(device) if hasattr(o, \"to_device\") else o\n return apply(_inner, b)", "_____no_output_____" ], [ "t = to_device((3,(tensor(3),tensor(2))))\nt1,(t2,t3) = t\ntest_eq_type(t,(3,(tensor(3).cuda(),tensor(2).cuda())))\ntest_eq(t2.type(), \"torch.cuda.LongTensor\")\ntest_eq(t3.type(), \"torch.cuda.LongTensor\")", "_____no_output_____" ], [ "#export\ndef to_cpu(b):\n \"Recursively map lists of tensors in `b ` to the cpu.\"\n return to_device(b,'cpu')", "_____no_output_____" ], [ "t3 = to_cpu(t3)\ntest_eq(t3.type(), \"torch.LongTensor\")\ntest_eq(t3, 2)", "_____no_output_____" ], [ "#export\ndef to_np(x):\n \"Convert a tensor to a numpy array.\"\n return apply(lambda o: o.data.cpu().numpy(), x)", "_____no_output_____" ], [ "t3 = to_np(t3)\ntest_eq(type(t3), np.ndarray)\ntest_eq(t3, 2)", "_____no_output_____" ], [ "#export\ndef to_concat(xs, dim=0):\n \"Concat the element in `xs` (recursively if they are tuples/lists of tensors)\"\n if is_listy(xs[0]): return type(xs[0])([to_concat([x[i] for x in xs], dim=dim) for i in range_of(xs[0])])\n if isinstance(xs[0],dict): return {k: to_concat([x[k] for x in xs], dim=dim) for k in xs[0].keys()}\n #We may receives xs that are not concatenatable (inputs of a text classifier for instance),\n # in this case we return a big list\n try: return retain_type(torch.cat(xs, dim=dim), xs[0])\n except: return sum([L(retain_type(o_.index_select(dim, tensor(i)).squeeze(dim), xs[0])\n for i in range_of(o_)) for o_ in xs], L())", "_____no_output_____" ], [ "test_eq(to_concat([tensor([1,2]), tensor([3,4])]), tensor([1,2,3,4]))\ntest_eq(to_concat([tensor([[1,2]]), tensor([[3,4]])], dim=1), tensor([[1,2,3,4]]))\ntest_eq_type(to_concat([(tensor([1,2]), tensor([3,4])), (tensor([3,4]), tensor([5,6]))]), (tensor([1,2,3,4]), tensor([3,4,5,6])))\ntest_eq_type(to_concat([[tensor([1,2]), tensor([3,4])], [tensor([3,4]), tensor([5,6])]]), [tensor([1,2,3,4]), tensor([3,4,5,6])])\ntest_eq_type(to_concat([(tensor([1,2]),), (tensor([3,4]),)]), (tensor([1,2,3,4]),))\n\ntest_eq(to_concat([tensor([[1,2]]), tensor([[3,4], [5,6]])], dim=1), [tensor([1]),tensor([3, 5]),tensor([4, 6])])", "_____no_output_____" ], [ "test_eq(type(to_concat([dict(foo=tensor([1,2]), bar=tensor(3,4))])), dict)", "_____no_output_____" ] ], [ [ "## Tensor subtypes", "_____no_output_____" ] ], [ [ "#export\n@patch\ndef set_meta(self:Tensor, x):\n \"Set all metadata in `__dict__`\"\n if hasattr(x,'__dict__'): self.__dict__ = x.__dict__", "_____no_output_____" ], [ "#export\n@patch\ndef get_meta(self:Tensor, n, d=None):\n \"Set `n` from `self._meta` if it exists and returns default `d` otherwise\"\n return getattr(self, '_meta', {}).get(n, d)", "_____no_output_____" ], [ "#export\n@patch\ndef as_subclass(self:Tensor, typ):\n \"Cast to `typ` (should be in future PyTorch version, so remove this then)\"\n res = torch.Tensor._make_subclass(typ, self)\n return retain_meta(self, res)", "_____no_output_____" ] ], [ [ "`Tensor.set_meta` and `Tensor.as_subclass` work together to maintain `_meta` after casting.", "_____no_output_____" ] ], [ [ "class _T(Tensor): pass\nt = tensor(1)\nt._meta = {'img_size': 1}\nt2 = t.as_subclass(_T)\ntest_eq(t._meta, t2._meta)\ntest_eq(t2.get_meta('img_size'), 1)", "_____no_output_____" ], [ "#export\nclass TensorBase(Tensor):\n def __new__(cls, x, **kwargs):\n res = cast(tensor(x), cls)\n res._meta = kwargs\n return res\n\n @classmethod\n def _before_cast(cls, x): return x if isinstance(x,Tensor) else tensor(x)\n\n def __reduce_ex__(self,proto):\n torch.utils.hooks.warn_if_has_hooks(self)\n args = (type(self), self.storage(), self.storage_offset(), tuple(self.size()), self.stride())\n if self.is_quantized: args = args + (self.q_scale(), self.q_zero_point())\n f = _fa_rebuild_qtensor if self.is_quantized else _fa_rebuild_tensor\n return (f, args + (self.requires_grad, OrderedDict()))\n\n def gi(self, i):\n res = self[i]\n return res.as_subclass(type(self)) if isinstance(res,Tensor) else res\n \n def __repr__(self):\n return re.sub('tensor', self.__class__.__name__, super().__repr__())", "_____no_output_____" ], [ "#export\ndef _patch_tb():\n if getattr(TensorBase,'_patched',False): return\n TensorBase._patched = True\n\n def get_f(fn):\n def _f(self, *args, **kwargs):\n cls = self.__class__\n res = getattr(super(TensorBase, self), fn)(*args, **kwargs)\n return retain_type(res, self)\n return _f\n\n t = tensor([1])\n skips = 'as_subclass __getitem__ __class__ __deepcopy__ __delattr__ __dir__ __doc__ __getattribute__ __hash__ __init__ \\\n __init_subclass__ __new__ __reduce__ __reduce_ex__ __repr__ __module__ __setstate__'.split()\n\n for fn in dir(t):\n if fn in skips: continue\n f = getattr(t, fn)\n if isinstance(f, (MethodWrapperType, BuiltinFunctionType, BuiltinMethodType, MethodType, FunctionType)):\n setattr(TensorBase, fn, get_f(fn))\n\n_patch_tb()", "_____no_output_____" ], [ "#export \nclass TensorCategory(TensorBase): pass", "_____no_output_____" ], [ "#export \nclass TensorMultiCategory(TensorCategory): pass", "_____no_output_____" ], [ "class _T(TensorBase): pass", "_____no_output_____" ], [ "t = _T(range(5))\ntest_eq(t[0], 0)\ntest_eq_type(t.gi(0), _T(0))\ntest_eq_type(t.gi(slice(2)), _T([0,1]))\ntest_eq_type(t+1, _T(range(1,6)))\ntest_eq(repr(t), '_T([0, 1, 2, 3, 4])')\n\ntest_eq(type(pickle.loads(pickle.dumps(t))), _T)", "/home/sgugger/anaconda3/lib/python3.7/site-packages/torch/storage.py:34: FutureWarning: pickle support for Storage will be removed in 1.5. Use `torch.save` instead\n warnings.warn(\"pickle support for Storage will be removed in 1.5. Use `torch.save` instead\", FutureWarning)\n" ], [ "t = tensor([1,2,3])\nm = TensorBase([False,True,True])\ntest_eq(t[m], tensor([2,3]))\nt = tensor([[1,2,3],[1,2,3]])\nm = cast(tensor([[False,True,True],\n [False,True,True]]), TensorBase)\ntest_eq(t[m], tensor([2,3,2,3]))", "_____no_output_____" ], [ "t = tensor([[1,2,3],[1,2,3]])\nt._meta = {'img_size': 1}\nt2 = cast(t, TensorBase)\ntest_eq(t2._meta, t._meta)\nx = retain_type(tensor([4,5,6]), t2)\ntest_eq(x._meta, t._meta)\nt3 = TensorBase([[1,2,3],[1,2,3]], img_size=1)\ntest_eq(t3._meta, t._meta)", "_____no_output_____" ], [ "#export\nclass TensorImageBase(TensorBase):\n _show_args = ArrayImageBase._show_args\n def show(self, ctx=None, **kwargs):\n return show_image(self, ctx=ctx, **{**self._show_args, **kwargs})", "_____no_output_____" ], [ "#export\nclass TensorImage(TensorImageBase): pass", "_____no_output_____" ], [ "#export\nclass TensorImageBW(TensorImage): _show_args = ArrayImageBW._show_args", "_____no_output_____" ], [ "#export\nclass TensorMask(TensorImageBase):\n _show_args = ArrayMask._show_args\n\n def show(self, ctx=None, **kwargs):\n codes = self.get_meta('codes')\n if codes is not None: kwargs = merge({'vmin': 1, 'vmax': len(codes)}, kwargs)\n return super().show(ctx=ctx, **kwargs)", "_____no_output_____" ], [ "im = Image.open(TEST_IMAGE)\nim_t = cast(array(im), TensorImage)\ntest_eq(type(im_t), TensorImage)", "_____no_output_____" ], [ "im_t2 = cast(tensor(1), TensorMask)\ntest_eq(type(im_t2), TensorMask)\ntest_eq(im_t2, tensor(1))", "_____no_output_____" ], [ "ax = im_t.show(figsize=(2,2))", "_____no_output_____" ], [ "test_fig_exists(ax)", "_____no_output_____" ], [ "#hide (last test of to_concat)\ntest_eq_type(to_concat([TensorImage([1,2]), TensorImage([3,4])]), TensorImage([1,2,3,4]))", "_____no_output_____" ], [ "#export\nclass TitledTensorScalar(TensorBase):\n \"A tensor containing a scalar that has a `show` method\"\n def show(self, **kwargs): show_title(self.item(), **kwargs)", "_____no_output_____" ] ], [ [ "## L -", "_____no_output_____" ] ], [ [ "#export\n@patch\ndef tensored(self:L):\n \"`mapped(tensor)`\"\n return self.map(tensor)\n@patch\ndef stack(self:L, dim=0):\n \"Same as `torch.stack`\"\n return torch.stack(list(self.tensored()), dim=dim)\n@patch\ndef cat (self:L, dim=0):\n \"Same as `torch.cat`\"\n return torch.cat (list(self.tensored()), dim=dim)", "_____no_output_____" ], [ "show_doc(L.tensored)", "_____no_output_____" ] ], [ [ "There are shortcuts for `torch.stack` and `torch.cat` if your `L` contains tensors or something convertible. You can manually convert with `tensored`.", "_____no_output_____" ] ], [ [ "t = L(([1,2],[3,4]))\ntest_eq(t.tensored(), [tensor(1,2),tensor(3,4)])", "_____no_output_____" ], [ "show_doc(L.stack)", "_____no_output_____" ], [ "test_eq(t.stack(), tensor([[1,2],[3,4]]))", "_____no_output_____" ], [ "show_doc(L.cat)", "_____no_output_____" ], [ "test_eq(t.cat(), tensor([1,2,3,4]))", "_____no_output_____" ] ], [ [ "## Chunks", "_____no_output_____" ] ], [ [ "#export\ndef concat(*ls):\n \"Concatenate tensors, arrays, lists, or tuples\"\n if not len(ls): return []\n it = ls[0]\n if isinstance(it,torch.Tensor): res = torch.cat(ls)\n elif isinstance(it,ndarray): res = np.concatenate(ls)\n else:\n res = itertools.chain.from_iterable(map(L,ls))\n if isinstance(it,(tuple,list)): res = type(it)(res)\n else: res = L(res)\n return retain_type(res, it)", "_____no_output_____" ], [ "a,b,c = [1],[1,2],[1,1,2]\ntest_eq(concat(a,b), c)\ntest_eq_type(concat(tuple (a),tuple (b)), tuple (c))\ntest_eq_type(concat(array (a),array (b)), array (c))\ntest_eq_type(concat(tensor(a),tensor(b)), tensor(c))\ntest_eq_type(concat(TensorBase(a),TensorBase(b)), TensorBase(c))\ntest_eq_type(concat([1,1],1), [1,1,1])\ntest_eq_type(concat(1,1,1), L(1,1,1))\ntest_eq_type(concat(L(1,2),1), L(1,2,1))", "_____no_output_____" ], [ "#export\nclass Chunks:\n \"Slice and int indexing into a list of lists\"\n def __init__(self, chunks, lens=None):\n self.chunks = chunks\n self.lens = L(map(len,self.chunks) if lens is None else lens)\n self.cumlens = np.cumsum(0+self.lens)\n self.totlen = self.cumlens[-1]\n\n def __getitem__(self,i):\n if isinstance(i,slice): return retain_type(self.getslice(i), old=self.chunks[0])\n di,idx = self.doc_idx(i)\n return retain_type(self.chunks[di][idx], old=self.chunks[0])\n\n def getslice(self, i):\n st_d,st_i = self.doc_idx(ifnone(i.start,0))\n en_d,en_i = self.doc_idx(ifnone(i.stop,self.totlen+1))\n res = [self.chunks[st_d][st_i:(en_i if st_d==en_d else sys.maxsize)]]\n for b in range(st_d+1,en_d): res.append(self.chunks[b])\n if st_d!=en_d and en_d<len(self.chunks): res.append(self.chunks[en_d][:en_i])\n return concat(*res)\n\n def doc_idx(self, i):\n if i<0: i=self.totlen+i # count from end\n docidx = np.searchsorted(self.cumlens, i+1)-1\n cl = self.cumlens[docidx]\n return docidx,i-cl", "_____no_output_____" ], [ "docs = L(list(string.ascii_lowercase[a:b]) for a,b in ((0,3),(3,7),(7,8),(8,16),(16,24),(24,26)))\n\nb = Chunks(docs)\ntest_eq([b[ o] for o in range(0,5)], ['a','b','c','d','e'])\ntest_eq([b[-o] for o in range(1,6)], ['z','y','x','w','v'])\ntest_eq(b[6:13], 'g,h,i,j,k,l,m'.split(','))\ntest_eq(b[20:77], 'u,v,w,x,y,z'.split(','))\ntest_eq(b[:5], 'a,b,c,d,e'.split(','))\ntest_eq(b[:2], 'a,b'.split(','))", "_____no_output_____" ], [ "t = torch.arange(26)\ndocs = L(t[a:b] for a,b in ((0,3),(3,7),(7,8),(8,16),(16,24),(24,26)))\nb = Chunks(docs)\ntest_eq([b[ o] for o in range(0,5)], range(0,5))\ntest_eq([b[-o] for o in range(1,6)], [25,24,23,22,21])\ntest_eq(b[6:13], torch.arange(6,13))\ntest_eq(b[20:77], torch.arange(20,26))\ntest_eq(b[:5], torch.arange(5))\ntest_eq(b[:2], torch.arange(2))", "_____no_output_____" ], [ "docs = L(TensorBase(t[a:b]) for a,b in ((0,3),(3,7),(7,8),(8,16),(16,24),(24,26)))\nb = Chunks(docs)\ntest_eq_type(b[:2], TensorBase(range(2)))\ntest_eq_type(b[:5], TensorBase(range(5)))\ntest_eq_type(b[9:13], TensorBase(range(9,13)))", "_____no_output_____" ] ], [ [ "## Simple types", "_____no_output_____" ] ], [ [ "#export\ndef show_title(o, ax=None, ctx=None, label=None, color='black', **kwargs):\n \"Set title of `ax` to `o`, or print `o` if `ax` is `None`\"\n ax = ifnone(ax,ctx)\n if ax is None: print(o)\n elif hasattr(ax, 'set_title'):\n t = ax.title.get_text()\n if len(t) > 0: o = t+'\\n'+str(o)\n ax.set_title(o, color=color)\n elif isinstance(ax, pd.Series):\n while label in ax: label += '_'\n ax = ax.append(pd.Series({label: o}))\n return ax", "_____no_output_____" ], [ "test_stdout(lambda: show_title(\"title\"), \"title\")\n# ensure that col names are unique when showing to a pandas series\nassert show_title(\"title\", ctx=pd.Series(dict(a=1)), label='a').equals(pd.Series(dict(a=1,a_='title')))", "_____no_output_____" ], [ "#export\nclass ShowTitle:\n \"Base class that adds a simple `show`\"\n _show_args = {'label': 'text'}\n def show(self, ctx=None, **kwargs):\n \"Show self\"\n return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledInt(Int, ShowTitle):\n _show_args = {'label': 'text'}\n def show(self, ctx=None, **kwargs):\n \"Show self\"\n return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledFloat(Float, ShowTitle):\n _show_args = {'label': 'text'}\n def show(self, ctx=None, **kwargs):\n \"Show self\"\n return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledStr(Str, ShowTitle):\n _show_args = {'label': 'text'}\n def show(self, ctx=None, **kwargs):\n \"Show self\"\n return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledTuple(Tuple, ShowTitle):\n _show_args = {'label': 'text'}\n def show(self, ctx=None, **kwargs):\n \"Show self\"\n return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nadd_docs(TitledInt, \"An `int` with `show`\"); add_docs(TitledStr, \"An `str` with `show`\");\nadd_docs(TitledFloat, \"A `float` with `show`\"); add_docs(TitledTuple, \"A `Tuple` with `show`\")", "_____no_output_____" ], [ "show_doc(TitledInt, title_level=3)", "_____no_output_____" ], [ "show_doc(TitledStr, title_level=3)", "_____no_output_____" ], [ "show_doc(TitledFloat, title_level=3)", "_____no_output_____" ], [ "test_stdout(lambda: TitledStr('s').show(), 's')\ntest_stdout(lambda: TitledInt(1).show(), '1')", "_____no_output_____" ], [ "show_doc(TitledTuple, title_level=3)", "_____no_output_____" ], [ "#hide\ndf = pd.DataFrame(index = range(1))\nrow = df.iloc[0]\nx = TitledFloat(2.56)\nrow = x.show(ctx=row, label='lbl')\ntest_eq(float(row.lbl), 2.56)", "_____no_output_____" ], [ "#export\n@patch\ndef truncate(self:TitledStr, n):\n \"Truncate self to `n`\"\n words = self.split(' ')[:n]\n return TitledStr(' '.join(words))", "_____no_output_____" ] ], [ [ "## Other functions", "_____no_output_____" ] ], [ [ "#export\nif not hasattr(pd.DataFrame,'_old_init'): pd.DataFrame._old_init = pd.DataFrame.__init__", "_____no_output_____" ], [ "#export\n@patch\ndef __init__(self:pd.DataFrame, data=None, index=None, columns=None, dtype=None, copy=False):\n if data is not None and isinstance(data, Tensor): data = to_np(data)\n self._old_init(data, index=index, columns=columns, dtype=dtype, copy=copy)", "_____no_output_____" ], [ "#export\ndef get_empty_df(n):\n \"Return `n` empty rows of a dataframe\"\n df = pd.DataFrame(index = range(n))\n return [df.iloc[i] for i in range(n)]", "_____no_output_____" ], [ "#export\ndef display_df(df):\n \"Display `df` in a notebook or defaults to print\"\n try: from IPython.display import display, HTML\n except: return print(df)\n display(HTML(df.to_html()))", "_____no_output_____" ], [ "#export\ndef get_first(c):\n \"Get the first element of c, even if c is a dataframe\"\n return getattr(c, 'iloc', c)[0]", "_____no_output_____" ], [ "#export\ndef one_param(m):\n \"First parameter in `m`\"\n return first(m.parameters())", "_____no_output_____" ], [ "#export\ndef item_find(x, idx=0):\n \"Recursively takes the `idx`-th element of `x`\"\n if is_listy(x): return item_find(x[idx])\n if isinstance(x,dict):\n key = list(x.keys())[idx] if isinstance(idx, int) else idx\n return item_find(x[key])\n return x", "_____no_output_____" ], [ "#export\ndef find_device(b):\n \"Recursively search the device of `b`.\"\n return item_find(b).device", "_____no_output_____" ], [ "t2 = to_device(tensor(0))\ndev = default_device()\ntest_eq(find_device(t2), dev)\ntest_eq(find_device([t2,t2]), dev)\ntest_eq(find_device({'a':t2,'b':t2}), dev)\ntest_eq(find_device({'a':[[t2],[t2]],'b':t2}), dev)", "_____no_output_____" ], [ "#export\ndef find_bs(b):\n \"Recursively search the batch size of `b`.\"\n return item_find(b).shape[0]", "_____no_output_____" ], [ "x = torch.randn(4,5)\ntest_eq(find_bs(x), 4)\ntest_eq(find_bs([x, x]), 4)\ntest_eq(find_bs({'a':x,'b':x}), 4)\ntest_eq(find_bs({'a':[[x],[x]],'b':x}), 4)", "_____no_output_____" ], [ "def np_func(f):\n \"Convert a function taking and returning numpy arrays to one taking and returning tensors\"\n def _inner(*args, **kwargs):\n nargs = [to_np(arg) if isinstance(arg,Tensor) else arg for arg in args]\n return tensor(f(*nargs, **kwargs))\n functools.update_wrapper(_inner, f)\n return _inner", "_____no_output_____" ] ], [ [ "This decorator is particularly useful for using numpy functions as fastai metrics, for instance:", "_____no_output_____" ] ], [ [ "from sklearn.metrics import f1_score\n\n@np_func\ndef f1(inp,targ): return f1_score(targ, inp)\n\na1,a2 = array([0,1,1]),array([1,0,1])\nt = f1(tensor(a1),tensor(a2))\ntest_eq(f1_score(a1,a2), t)\nassert isinstance(t,Tensor)", "_____no_output_____" ], [ "#export\nclass Module(nn.Module, metaclass=PrePostInitMeta):\n \"Same as `nn.Module`, but no need for subclasses to call `super().__init__`\"\n def __pre_init__(self, *args, **kwargs): super().__init__()\n def __init__(self): pass", "_____no_output_____" ], [ "show_doc(Module, title_level=3)", "_____no_output_____" ], [ "class _T(Module):\n def __init__(self): self.f = nn.Linear(1,1)\n def forward(self,x): return self.f(x)\n\nt = _T()\nt(tensor([1.]))", "_____no_output_____" ], [ "# export\nfrom torch.nn.parallel import DistributedDataParallel\n\ndef get_model(model):\n \"Return the model maybe wrapped inside `model`.\"\n return model.module if isinstance(model, (DistributedDataParallel, nn.DataParallel)) else model", "_____no_output_____" ], [ "# export\ndef one_hot(x, c):\n \"One-hot encode `x` with `c` classes.\"\n res = torch.zeros(c, dtype=torch.uint8)\n if isinstance(x, Tensor) and x.numel()>0: res[x] = 1.\n else: res[list(L(x, use_list=None))] = 1.\n return res", "_____no_output_____" ], [ "test_eq(one_hot([1,4], 5), tensor(0,1,0,0,1).byte())\ntest_eq(one_hot(torch.tensor([]), 5), tensor(0,0,0,0,0).byte())\ntest_eq(one_hot(2, 5), tensor(0,0,1,0,0).byte())", "_____no_output_____" ], [ "#export\ndef one_hot_decode(x, vocab=None):\n return L(vocab[i] if vocab else i for i,x_ in enumerate(x) if x_==1)", "_____no_output_____" ], [ "test_eq(one_hot_decode(tensor(0,1,0,0,1)), [1,4])\ntest_eq(one_hot_decode(tensor(0,0,0,0,0)), [ ])\ntest_eq(one_hot_decode(tensor(0,0,1,0,0)), [2 ])", "_____no_output_____" ], [ "#export\ndef params(m):\n \"Return all parameters of `m`\"\n return [p for p in m.parameters()]", "_____no_output_____" ], [ "#export\ndef trainable_params(m):\n \"Return all trainable parameters of `m`\"\n return [p for p in m.parameters() if p.requires_grad]", "_____no_output_____" ], [ "m = nn.Linear(4,5)\ntest_eq(trainable_params(m), [m.weight, m.bias])\nm.weight.requires_grad_(False)\ntest_eq(trainable_params(m), [m.bias])", "_____no_output_____" ], [ "#export\nnorm_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d)", "_____no_output_____" ], [ "#export\ndef bn_bias_params(m, with_bias=True): # TODO: Rename to `norm_bias_params`\n \"Return all bias and BatchNorm parameters\"\n if isinstance(m, norm_types): return L(m.parameters())\n res = L(m.children()).map(bn_bias_params, with_bias=with_bias).concat()\n if with_bias and getattr(m, 'bias', None) is not None: res.append(m.bias)\n return res", "_____no_output_____" ], [ "for norm_func in [nn.BatchNorm1d, partial(nn.InstanceNorm1d, affine=True)]:\n model = nn.Sequential(nn.Linear(10,20), norm_func(20), nn.Conv1d(3,4, 3))\n test_eq(bn_bias_params(model), [model[0].bias, model[1].weight, model[1].bias, model[2].bias])\n model = nn.ModuleList([nn.Linear(10,20, bias=False), nn.Sequential(norm_func(20), nn.Conv1d(3,4,3))])\n test_eq(bn_bias_params(model), [model[1][0].weight, model[1][0].bias, model[1][1].bias])\n model = nn.ModuleList([nn.Linear(10,20), nn.Sequential(norm_func(20), nn.Conv1d(3,4,3))])\n test_eq(bn_bias_params(model, with_bias=False), [model[1][0].weight, model[1][0].bias])", "_____no_output_____" ], [ "#export\ndef batch_to_samples(b, max_n=10):\n \"'Transposes' a batch to (at most `max_n`) samples\"\n if isinstance(b, Tensor): return retain_types(list(b[:max_n]), [b])\n else:\n res = L(b).map(partial(batch_to_samples,max_n=max_n))\n return retain_types(res.zip(), [b])", "_____no_output_____" ], [ "t = tensor([1,2,3])\ntest_eq(batch_to_samples([t,t+1], max_n=2), ([1,2],[2,3]))\ntest_eq(batch_to_samples(tensor([1,2,3]), 10), [1, 2, 3])\ntest_eq(batch_to_samples([tensor([1,2,3]), tensor([4,5,6])], 10), [(1, 4), (2, 5), (3, 6)])\ntest_eq(batch_to_samples([tensor([1,2,3]), tensor([4,5,6])], 2), [(1, 4), (2, 5)])\ntest_eq(batch_to_samples([tensor([1,2,3]), [tensor([4,5,6]),tensor([7,8,9])]], 10), \n [(1, (4, 7)), (2, (5, 8)), (3, (6, 9))])\ntest_eq(batch_to_samples([tensor([1,2,3]), [tensor([4,5,6]),tensor([7,8,9])]], 2), [(1, (4, 7)), (2, (5, 8))])\n\nt = Tuple(tensor([1,2,3]),TensorBase([2,3,4]))\ntest_eq_type(batch_to_samples(t)[0][1], TensorBase(2))\ntest_eq(batch_to_samples(t).map(type), [Tuple]*3)", "_____no_output_____" ], [ "#export\n@patch\ndef interp_1d(x:Tensor, xp, fp):\n \"Same as `np.interp`\"\n slopes = (fp[1:]-fp[:-1])/(xp[1:]-xp[:-1])\n incx = fp[:-1] - (slopes*xp[:-1])\n locs = (x[:,None]>=xp[None,:]).long().sum(1)-1\n locs = locs.clamp(0,len(slopes)-1)\n return slopes[locs]*x + incx[locs]", "_____no_output_____" ], [ "brks = tensor(0,1,2,4,8,64).float()\nys = tensor(range_of(brks)).float()\nys /= ys[-1].item()\npts = tensor(0.2,0.5,0.8,3,5,63)\n\npreds = pts.interp_1d(brks, ys)\ntest_close(preds.numpy(), np.interp(pts.numpy(), brks.numpy(), ys.numpy()))\n\nplt.scatter(brks,ys)\nplt.scatter(pts,preds)\nplt.legend(['breaks','preds']);", "_____no_output_____" ], [ "#export\n@patch\ndef pca(x:Tensor, k=2):\n \"Compute PCA of `x` with `k` dimensions.\"\n x = x-torch.mean(x,0)\n U,S,V = torch.svd(x.t())\n return torch.mm(x,U[:,:k])", "_____no_output_____" ], [ "# export\ndef logit(x):\n \"Logit of `x`, clamped to avoid inf.\"\n x = x.clamp(1e-7, 1-1e-7)\n return -(1/x-1).log()", "_____no_output_____" ], [ "#export\ndef num_distrib():\n \"Return the number of processes in distributed training (if applicable).\"\n return int(os.environ.get('WORLD_SIZE', 0))", "_____no_output_____" ], [ "#export\ndef rank_distrib():\n \"Return the distributed rank of this process (if applicable).\"\n return int(os.environ.get('RANK', 0))", "_____no_output_____" ], [ "#export\ndef distrib_barrier():\n \"Place a synchronization barrier in distributed training so that ALL sub-processes in the pytorch process group must arrive here before proceeding.\"\n if num_distrib() > 1: torch.distributed.barrier()", "_____no_output_____" ], [ "#export\n# Saving arrays requires pytables - optional dependency\ntry: import tables\nexcept: pass", "_____no_output_____" ], [ "#export\ndef _comp_filter(lib='lz4',lvl=3): return tables.Filters(complib=f'blosc:{lib}', complevel=lvl)", "_____no_output_____" ], [ "#export\n@patch\ndef save_array(p:Path, o, complib='lz4', lvl=3):\n \"Save numpy array to a compressed `pytables` file, using compression level `lvl`\"\n if isinstance(o,Tensor): o = to_np(o)\n with tables.open_file(p, mode='w', filters=_comp_filter(lib=complib,lvl=lvl)) as f: f.create_carray('/', 'data', obj=o)", "_____no_output_____" ] ], [ [ "Compression lib can be any of: blosclz, lz4, lz4hc, snappy, zlib or zstd.", "_____no_output_____" ] ], [ [ "#export\n@patch\ndef load_array(p:Path):\n \"Save numpy array to a `pytables` file\"\n with tables.open_file(p, 'r') as f: return f.root.data.read()", "_____no_output_____" ], [ "inspect.getdoc(load_array)", "_____no_output_____" ], [ "str(inspect.signature(load_array))", "_____no_output_____" ], [ "#export\ndef base_doc(elt):\n \"Print a base documentation of `elt`\"\n name = getattr(elt, '__qualname__', getattr(elt, '__name__', ''))\n print(f'{name}{inspect.signature(elt)}\\n{inspect.getdoc(elt)}\\n')\n print('To get a prettier result with hyperlinks to source code and documentation, install nbdev: pip install nbdev')", "_____no_output_____" ], [ "#export\ndef doc(elt):\n \"Try to use doc form nbdev and fall back to `base_doc`\"\n try:\n from nbdev.showdoc import doc\n doc(elt)\n except: base_doc(elt)", "_____no_output_____" ], [ "#export\ndef nested_reorder(t, idxs):\n \"Reorder all tensors in `t` using `idxs`\"\n if isinstance(t, (Tensor,L)): return t[idxs]\n elif is_listy(t): return type(t)(nested_reorder(t_, idxs) for t_ in t)\n if t is None: return t\n raise TypeError(f\"Expected tensor, tuple, list or L but got {type(t)}\")", "_____no_output_____" ], [ "x = tensor([0,1,2,3,4,5])\nidxs = tensor([2,5,1,0,3,4])\ntest_eq_type(nested_reorder(([x], x), idxs), ([idxs], idxs))\n\ny = L(0,1,2,3,4,5)\nz = L(i.item() for i in idxs)\ntest_eq_type(nested_reorder((y, x), idxs), (z,idxs))", "_____no_output_____" ] ], [ [ "## Image helpers", "_____no_output_____" ] ], [ [ "#export\ndef to_image(x):\n if isinstance(x,Image.Image): return x\n if isinstance(x,Tensor): x = to_np(x.permute((1,2,0)))\n if x.dtype==np.float32: x = (x*255).astype(np.uint8)\n return Image.fromarray(x, mode=['RGB','CMYK'][x.shape[0]==4])", "_____no_output_____" ], [ "#export\ndef make_cross_image(bw=True):\n \"Create a tensor containing a cross image, either `bw` (True) or color\"\n if bw:\n im = torch.zeros(5,5)\n im[2,:] = 1.\n im[:,2] = 1.\n else:\n im = torch.zeros(3,5,5)\n im[0,2,:] = 1.\n im[1,:,2] = 1.\n return im", "_____no_output_____" ], [ "plt.imshow(make_cross_image(), cmap=\"Greys\");", "_____no_output_____" ], [ "plt.imshow(make_cross_image(False).permute(1,2,0));", "_____no_output_____" ], [ "#export\ndef show_image_batch(b, show=show_titled_image, items=9, cols=3, figsize=None, **kwargs):\n \"Display batch `b` in a grid of size `items` with `cols` width\"\n if items<cols: cols=items\n rows = (items+cols-1) // cols\n if figsize is None: figsize = (cols*3, rows*3)\n fig,axs = plt.subplots(rows, cols, figsize=figsize)\n for *o,ax in zip(*to_cpu(b), axs.flatten()): show(o, ax=ax, **kwargs)", "_____no_output_____" ], [ "show_image_batch(([Image.open(TEST_IMAGE_BW),Image.open(TEST_IMAGE)],['bw','color']), items=2)", "_____no_output_____" ] ], [ [ "## Model init", "_____no_output_____" ] ], [ [ "#export\ndef requires_grad(m):\n \"Check if the first parameter of `m` requires grad or not\"\n ps = list(m.parameters())\n return ps[0].requires_grad if len(ps)>0 else False", "_____no_output_____" ], [ "tst = nn.Linear(4,5)\nassert requires_grad(tst)\nfor p in tst.parameters(): p.requires_grad_(False)\nassert not requires_grad(tst)", "_____no_output_____" ], [ "#export\ndef init_default(m, func=nn.init.kaiming_normal_):\n \"Initialize `m` weights with `func` and set `bias` to 0.\"\n if func:\n if hasattr(m, 'weight'): func(m.weight)\n if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bias.data.fill_(0.)\n return m", "_____no_output_____" ], [ "tst = nn.Linear(4,5)\ntst.weight.data.uniform_(-1,1)\ntst.bias.data.uniform_(-1,1)\ntst = init_default(tst, func = lambda x: x.data.fill_(1.))\ntest_eq(tst.weight, torch.ones(5,4))\ntest_eq(tst.bias, torch.zeros(5))", "_____no_output_____" ], [ "#export\ndef cond_init(m, func):\n \"Apply `init_default` to `m` unless it's a batchnorm module\"\n if (not isinstance(m, norm_types)) and requires_grad(m): init_default(m, func)", "_____no_output_____" ], [ "tst = nn.Linear(4,5)\ntst.weight.data.uniform_(-1,1)\ntst.bias.data.uniform_(-1,1)\ncond_init(tst, func = lambda x: x.data.fill_(1.))\ntest_eq(tst.weight, torch.ones(5,4))\ntest_eq(tst.bias, torch.zeros(5))\n\ntst = nn.BatchNorm2d(5)\ninit = [tst.weight.clone(), tst.bias.clone()]\ncond_init(tst, func = lambda x: x.data.fill_(1.))\ntest_eq(tst.weight, init[0])\ntest_eq(tst.bias, init[1])", "_____no_output_____" ], [ "#export\ndef apply_leaf(m, f):\n \"Apply `f` to children of `m`.\"\n c = m.children()\n if isinstance(m, nn.Module): f(m)\n for l in c: apply_leaf(l,f)", "_____no_output_____" ], [ "tst = nn.Sequential(nn.Linear(4,5), nn.Sequential(nn.Linear(4,5), nn.Linear(4,5)))\napply_leaf(tst, partial(init_default, func=lambda x: x.data.fill_(1.)))\nfor l in [tst[0], *tst[1]]: test_eq(l.weight, torch.ones(5,4))\nfor l in [tst[0], *tst[1]]: test_eq(l.bias, torch.zeros(5))", "_____no_output_____" ], [ "#export\ndef apply_init(m, func=nn.init.kaiming_normal_):\n \"Initialize all non-batchnorm layers of `m` with `func`.\"\n apply_leaf(m, partial(cond_init, func=func))", "_____no_output_____" ], [ "tst = nn.Sequential(nn.Linear(4,5), nn.Sequential(nn.Linear(4,5), nn.BatchNorm1d(5)))\ninit = [tst[1][1].weight.clone(), tst[1][1].bias.clone()]\napply_init(tst, func=lambda x: x.data.fill_(1.))\nfor l in [tst[0], tst[1][0]]: test_eq(l.weight, torch.ones(5,4))\nfor l in [tst[0], tst[1][0]]: test_eq(l.bias, torch.zeros(5))\ntest_eq(tst[1][1].weight, init[0])\ntest_eq(tst[1][1].bias, init[1])", "_____no_output_____" ] ], [ [ "## Multiprocessing", "_____no_output_____" ] ], [ [ "#export\nfrom multiprocessing import Process, Queue", "_____no_output_____" ], [ "#export\ndef set_num_threads(nt):\n \"Get numpy (and others) to use `nt` threads\"\n try: import mkl; mkl.set_num_threads(nt)\n except: pass\n torch.set_num_threads(1)\n os.environ['IPC_ENABLE']='1'\n for o in ['OPENBLAS_NUM_THREADS','NUMEXPR_NUM_THREADS','OMP_NUM_THREADS','MKL_NUM_THREADS']:\n os.environ[o] = str(nt)", "_____no_output_____" ], [ "#export \n@delegates(concurrent.futures.ProcessPoolExecutor)\nclass ProcessPoolExecutor(concurrent.futures.ProcessPoolExecutor):\n def __init__(self, max_workers=None, on_exc=print, **kwargs):\n self.not_parallel = max_workers==0\n self.on_exc = on_exc\n if self.not_parallel: max_workers=1\n super().__init__(max_workers, **kwargs)\n\n def map(self, f, items, *args, **kwargs):\n g = partial(f, *args, **kwargs)\n if self.not_parallel: return map(g, items)\n try: return super().map(g, items)\n except Exception as e: self.on_exc(e)", "_____no_output_____" ], [ "#export \ndef parallel(f, items, *args, n_workers=defaults.cpus, total=None, progress=True, **kwargs):\n \"Applies `func` in parallel to `items`, using `n_workers`\"\n with ProcessPoolExecutor(n_workers) as ex:\n r = ex.map(f,items, *args, **kwargs)\n if progress:\n if total is None: total = len(items)\n r = progress_bar(r, total=total, leave=False)\n return L(r)", "_____no_output_____" ], [ "def add_one(x, a=1): \n time.sleep(random.random()/100)\n return x+a\n\ninp,exp = range(50),range(1,51)\ntest_eq(parallel(add_one, inp, n_workers=2), exp)\ntest_eq(parallel(add_one, inp, n_workers=0), exp)\ntest_eq(parallel(add_one, inp, n_workers=1, a=2), range(2,52))\ntest_eq(parallel(add_one, inp, n_workers=0, a=2), range(2,52))", "_____no_output_____" ], [ "#export\ndef run_procs(f, f_done, args):\n \"Call `f` for each item in `args` in parallel, yielding `f_done`\"\n processes = L(args).map(Process, args=arg0, target=f)\n for o in processes: o.start()\n try: yield from f_done()\n except Exception as e: print(e)\n finally: processes.map(Self.join())", "_____no_output_____" ], [ "#export \ndef parallel_gen(cls, items, n_workers=defaults.cpus, as_gen=False, **kwargs):\n \"Instantiate `cls` in `n_workers` procs & call each on a subset of `items` in parallel.\"\n batches = np.array_split(items, n_workers)\n idx = np.cumsum(0 + L(batches).map(len))\n queue = Queue()\n def f(batch, start_idx):\n for i,b in enumerate(cls(**kwargs)(batch)): queue.put((start_idx+i,b))\n def done(): return (queue.get() for _ in progress_bar(items, leave=False))\n yield from run_procs(f, done, L(batches,idx).zip())", "_____no_output_____" ] ], [ [ "`cls` is any class with `__call__`. It will be passed `args` and `kwargs` when initialized. Note that `n_workers` instances of `cls` are created, one in each process. `items` are then split in `n_workers` batches and one is sent to each `cls`. The function then returns a list of all the results, matching the order of `items` (if not `as_gen`) or a generator of tuples of item indices and results (if `as_gen`).", "_____no_output_____" ] ], [ [ "class SleepyBatchFunc:\n def __init__(self): self.a=1\n def __call__(self, batch):\n for k in batch:\n time.sleep(random.random()/4)\n yield k+self.a\n\nx = np.linspace(0,0.99,20)\nres = L(parallel_gen(SleepyBatchFunc, x, n_workers=2))\ntest_eq(res.sorted().itemgot(1), x+1)", "_____no_output_____" ] ], [ [ "## autograd jit functions", "_____no_output_____" ] ], [ [ "#export\ndef script_use_ctx(f):\n \"Decorator: create jit script and pass everything in `ctx.saved_variables to `f`, after `*args`\"\n sf = torch.jit.script(f)\n def _f(ctx, *args, **kwargs): return sf(*args, *ctx.saved_variables, **kwargs)\n return update_wrapper(_f,f)", "_____no_output_____" ], [ "#export\ndef script_save_ctx(static, *argidx):\n \"Decorator: create jit script and save args with indices `argidx` using `ctx.save_for_backward`\"\n def _dec(f):\n sf = torch.jit.script(f)\n def _f(ctx, *args, **kwargs):\n if argidx:\n save = [args[o] for o in argidx]\n ctx.save_for_backward(*save)\n if not argidx: args = [ctx]+args\n return sf(*args, **kwargs)\n if static: _f = staticmethod(_f)\n return update_wrapper(_f,f)\n return _dec", "_____no_output_____" ], [ "#export\ndef script_fwd(*argidx):\n \"Decorator: create static jit script and save args with indices `argidx` using `ctx.save_for_backward`\"\n return script_save_ctx(True, *argidx)", "_____no_output_____" ], [ "#export\ndef script_bwd(f):\n \"Decorator: create static jit script and pass everything in `ctx.saved_variables to `f`, after `*args`\"\n return staticmethod(script_use_ctx(f))", "_____no_output_____" ], [ "#export\ndef grad_module(cls):\n \"Decorator: convert `cls` into an autograd function\"\n class _c(nn.Module):\n def forward(self, *args, **kwargs): return cls.apply(*args, **kwargs)\n return _c", "_____no_output_____" ] ], [ [ "# Export -", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.export import notebook2script\nnotebook2script()", "Converted 00_torch_core.ipynb.\nConverted 01_layers.ipynb.\nConverted 02_data.load.ipynb.\nConverted 03_data.core.ipynb.\nConverted 04_data.external.ipynb.\nConverted 05_data.transforms.ipynb.\nConverted 06_data.block.ipynb.\nConverted 07_vision.core.ipynb.\nConverted 08_vision.data.ipynb.\nConverted 09_vision.augment.ipynb.\nConverted 09b_vision.utils.ipynb.\nConverted 09c_vision.widgets.ipynb.\nConverted 10_tutorial.pets.ipynb.\nConverted 11_vision.models.xresnet.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_callback.core.ipynb.\nConverted 13a_learner.ipynb.\nConverted 13b_metrics.ipynb.\nConverted 14_callback.schedule.ipynb.\nConverted 14a_callback.data.ipynb.\nConverted 15_callback.hook.ipynb.\nConverted 15a_vision.models.unet.ipynb.\nConverted 16_callback.progress.ipynb.\nConverted 17_callback.tracker.ipynb.\nConverted 18_callback.fp16.ipynb.\nConverted 18a_callback.training.ipynb.\nConverted 19_callback.mixup.ipynb.\nConverted 20_interpret.ipynb.\nConverted 20a_distributed.ipynb.\nConverted 21_vision.learner.ipynb.\nConverted 22_tutorial.imagenette.ipynb.\nConverted 23_tutorial.vision.ipynb.\nConverted 24_tutorial.siamese.ipynb.\nConverted 24_vision.gan.ipynb.\nConverted 30_text.core.ipynb.\nConverted 31_text.data.ipynb.\nConverted 32_text.models.awdlstm.ipynb.\nConverted 33_text.models.core.ipynb.\nConverted 34_callback.rnn.ipynb.\nConverted 35_tutorial.wikitext.ipynb.\nConverted 36_text.models.qrnn.ipynb.\nConverted 37_text.learner.ipynb.\nConverted 38_tutorial.text.ipynb.\nConverted 40_tabular.core.ipynb.\nConverted 41_tabular.data.ipynb.\nConverted 42_tabular.model.ipynb.\nConverted 43_tabular.learner.ipynb.\nConverted 44_tutorial.tabular.ipynb.\nConverted 45_collab.ipynb.\nConverted 46_tutorial.collab.ipynb.\nConverted 50_tutorial.datablock.ipynb.\nConverted 60_medical.imaging.ipynb.\nConverted 61_tutorial.medical_imaging.ipynb.\nConverted 65_medical.text.ipynb.\nConverted 70_callback.wandb.ipynb.\nConverted 71_callback.tensorboard.ipynb.\nConverted 72_callback.neptune.ipynb.\nConverted 73_callback.captum.ipynb.\nConverted 74_callback.cutmix.ipynb.\nConverted 97_test_utils.ipynb.\nConverted 99_pytorch_doc.ipynb.\nConverted index.ipynb.\nConverted tutorial.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" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "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", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d01edb84f2931921b31ed12c04bc59a1692033ec
26,512
ipynb
Jupyter Notebook
v1-uvod/sc-siit-v1-cv-basics.ipynb
ftn-ai-lab/sc-2019-siit
935980fa256ad25f6b4488d0235d0103ecadbf9d
[ "MIT" ]
7
2019-11-04T10:19:34.000Z
2020-10-11T18:09:05.000Z
v1-uvod/sc-siit-v1-cv-basics.ipynb
ftn-ai-lab/sc-2019-siit
935980fa256ad25f6b4488d0235d0103ecadbf9d
[ "MIT" ]
74
2019-11-26T16:43:53.000Z
2020-07-06T18:05:52.000Z
v1-uvod/sc-siit-v1-cv-basics.ipynb
ftn-ai-lab/sc-2019-siit
935980fa256ad25f6b4488d0235d0103ecadbf9d
[ "MIT" ]
4
2019-11-04T19:06:20.000Z
2020-07-16T17:58:25.000Z
31.827131
719
0.612025
[ [ [ "# Soft Computing\n\n## Vežba 1 - Digitalna slika, computer vision, OpenCV\n\n### OpenCV\n\nOpen source biblioteka namenjena oblasti računarske vizije (eng. computer vision). Dokumentacija dostupna <a href=\"https://opencv.org/\">ovde</a>.\n\n### matplotlib\n\nPlotting biblioteka za programski jezik Python i njegov numerički paket NumPy. Dokumentacija dostupna <a href=\"https://matplotlib.org/\">ovde</a>.", "_____no_output_____" ], [ "### Učitavanje slike\n\nOpenCV metoda za učitavanje slike sa diska je <b>imread(path_to_image)</b>, koja kao parametar prima putanju do slike na disku. Učitana slika <i>img</i> je zapravo NumPy matrica, čije dimenzije zavise od same prirode slike. Ako je slika u boji, onda je <i>img</i> trodimenzionalna matrica, čije su prve dve dimenzije visina i širina slike, a treća dimenzija je veličine 3, zato što ona predstavlja boju (RGB, po jedan segment za svaku osnonvu boju).", "_____no_output_____" ] ], [ [ "import numpy as np\nimport cv2 # OpenCV biblioteka\nimport matplotlib\nimport matplotlib.pyplot as plt ", "_____no_output_____" ], [ "# iscrtavanje slika i grafika unutar samog browsera\n%matplotlib inline \n# prikaz vecih slika \nmatplotlib.rcParams['figure.figsize'] = 16,12", "_____no_output_____" ], [ "img = cv2.imread('images/girl.jpg') # ucitavanje slike sa diska\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # konvertovanje iz BGR u RGB model boja (OpenCV ucita sliku kao BGR)\nplt.imshow(img) # prikazivanje slike", "_____no_output_____" ] ], [ [ "### Prikazivanje dimenzija slike", "_____no_output_____" ] ], [ [ "print(img.shape) # shape je property Numpy array-a za prikaz dimenzija", "_____no_output_____" ] ], [ [ "Obratiti pažnju da slika u boji ima 3 komponente za svaki piksel na slici - R (red), G (green) i B (blue).\n![images/cat_rgb.png](images/cat_rgb.png)", "_____no_output_____" ] ], [ [ "img", "_____no_output_____" ] ], [ [ "Primetite da je svaki element matrice **uint8** (unsigned 8-bit integer), odnosno celobroja vrednost u interval [0, 255].", "_____no_output_____" ] ], [ [ "img.dtype", "_____no_output_____" ] ], [ [ "### Osnovne operacije pomoću NumPy\n\nPredstavljanje slike kao NumPy array je vrlo korisna stvar, jer omogućava jednostavnu manipulaciju i izvršavanje osnovih operacija nad slikom.", "_____no_output_____" ], [ "#### Isecanje (crop)", "_____no_output_____" ] ], [ [ "img_crop = img[100:200, 300:600] # prva koordinata je po visini (formalno red), druga po širini (formalo kolona)\nplt.imshow(img_crop)", "_____no_output_____" ] ], [ [ "#### Okretanje (flip)", "_____no_output_____" ] ], [ [ "img_flip_h = img[:, ::-1] # prva koordinata ostaje ista, a kolone se uzimaju unazad\nplt.imshow(img_flip_h)", "_____no_output_____" ], [ "img_flip_v = img[::-1, :] # druga koordinata ostaje ista, a redovi se uzimaju unazad\nplt.imshow(img_flip_v)", "_____no_output_____" ], [ "img_flip_c = img[:, :, ::-1] # možemo i izmeniti redosled boja (RGB->BGR), samo je pitanje koliko to ima smisla\nplt.imshow(img_flip_c)", "_____no_output_____" ] ], [ [ "#### Invertovanje", "_____no_output_____" ] ], [ [ "img_inv = 255 - img # ako su pikeli u intervalu [0,255] ovo je ok, a ako su u intervalu [0.,1.] onda bi bilo 1. - img\nplt.imshow(img_inv)", "_____no_output_____" ] ], [ [ "### Konvertovanje iz RGB u \"grayscale\"\n\nKonvertovanjem iz RGB modela u nijanse sivih (grayscale) se gubi informacija o boji piksela na slici, ali sama slika postaje mnogo lakša za dalju obradu.\n\nOvo se može uraditi na više načina:\n1. **Srednja vrednost** RGB komponenti - najjednostavnija varijanta $$ G = \\frac{R+G+B}{3} $$\n2. **Metod osvetljenosti** - srednja vrednost najjače i najslabije boje $$ G = \\frac{max(R,G,B) + min(R,G,B)}{2} $$\n3. **Metod perceptivne osvetljenosti** - težinska srednja vrednost koja uzima u obzir ljudsku percepciju (npr. najviše smo osetljivi na zelenu boju, pa to treba uzeti u obzir)$$ G = 0.21*R + 0.72*G + 0.07*B $$", "_____no_output_____" ] ], [ [ "# implementacija metode perceptivne osvetljenosti\ndef my_rgb2gray(img_rgb):\n img_gray = np.ndarray((img_rgb.shape[0], img_rgb.shape[1])) # zauzimanje memorije za sliku (nema trece dimenzije)\n img_gray = 0.21*img_rgb[:, :, 0] + 0.77*img_rgb[:, :, 1] + 0.07*img_rgb[:, :, 2]\n img_gray = img_gray.astype('uint8') # u prethodnom koraku smo mnozili sa float, pa sada moramo da vratimo u [0,255] opseg\n return img_gray\n\nimg_gray = my_rgb2gray(img)\nplt.imshow(img_gray, 'gray') # kada se prikazuje slika koja nije RGB, obavezno je staviti 'gray' kao drugi parametar", "_____no_output_____" ] ], [ [ "Ipak je najbolje se držati implementacije u **OpenCV** biblioteci :).", "_____no_output_____" ] ], [ [ "img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)", "_____no_output_____" ], [ "img_gray.shape", "_____no_output_____" ], [ "plt.imshow(img_gray, 'gray') ", "_____no_output_____" ], [ "img_gray", "_____no_output_____" ] ], [ [ "### Binarna slika\n\nSlika čiji pikseli imaju samo dve moguće vrednosti: crno i belo. U zavisnosti da li interval realan (float32) ili celobrojan (uint8), ove vrednosti mogu biti {0,1} ili {0,255}.\n\nU binarnoj slici često izdvajamo ono što nam je bitno (**foreground**), od ono što nam je nebitno (**background**). Formalnije, ovaj postupak izdvajanja bitnog od nebitnog na slici nazivamo **segmentacija**.\n\nNajčešći način dobijanja binarne slike je korišćenje nekog praga (**threshold**), pa ako je vrednost piksela veća od zadatog praga taj piksel dobija vrednost 1, u suprotnom 0. Postoji više tipova threshold-ovanja:\n\n1. Globalni threshold - isti prag se primenjuje na sve piksele\n2. Lokalni threshold - različiti pragovi za različite delove slike\n3. Adaptivni threshold - prag se ne određuje ručno (ne zadaje ga čovek), već kroz neki postupak. Može biti i globalni i lokalni.", "_____no_output_____" ], [ "#### Globalni threshold\n\nKako izdvojiti npr. samo lice?", "_____no_output_____" ] ], [ [ "img_tr = img_gray > 127 # svi piskeli koji su veci od 127 ce dobiti vrednost True, tj. 1, i obrnuto\nplt.imshow(img_tr, 'gray')", "_____no_output_____" ] ], [ [ "OpenCV ima metodu <b>threshold</b> koja kao prvi parametar prima sliku koja se binarizuje, kao drugi parametar prima prag binarizacije, treći parametar je vrednost rezultujućeg piksela ako je veći od praga (255=belo), poslednji parametar je tip thresholda (u ovo slučaju je binarizacija).", "_____no_output_____" ] ], [ [ "ret, image_bin = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY) # ret je vrednost praga, image_bin je binarna slika\nprint(ret)\nplt.imshow(image_bin, 'gray')", "_____no_output_____" ] ], [ [ "#### Otsu threshold\n\n<a href=\"https://en.wikipedia.org/wiki/Otsu%27s_method\">Otsu metoda</a> se koristi za automatsko pronalaženje praga za threshold na slici.", "_____no_output_____" ] ], [ [ "ret, image_bin = cv2.threshold(img_gray, 0, 255, cv2.THRESH_OTSU) # ret je izracunata vrednost praga, image_bin je binarna slika\nprint(\"Otsu's threshold: \" + str(ret))\nplt.imshow(image_bin, 'gray')", "_____no_output_____" ] ], [ [ "#### Adaptivni threshold\n\nU nekim slučajevima primena globalnog praga za threshold ne daje dobre rezultate. Dobar primer su slike na kojima se menja osvetljenje, gde globalni threshold praktično uništi deo slike koji je previše osvetljen ili zatamnjen.\n\nAdaptivni threshold je drugačiji pristup, gde se za svaki piksel na slici izračunava zaseban prag, na osnovu njemu okolnnih piksela. <a href=\"https://docs.opencv.org/master/d7/d4d/tutorial_py_thresholding.html#gsc.tab=0\">Primer</a>", "_____no_output_____" ] ], [ [ "image_ada = cv2.imread('images/sonnet.png')\nimage_ada = cv2.cvtColor(image_ada, cv2.COLOR_BGR2GRAY)\nplt.imshow(image_ada, 'gray')", "_____no_output_____" ], [ "ret, image_ada_bin = cv2.threshold(image_ada, 100, 255, cv2.THRESH_BINARY)\nplt.imshow(image_ada_bin, 'gray')", "_____no_output_____" ] ], [ [ "Loši rezultati su dobijeni upotrebom globalnog thresholda.\nPoboljšavamo rezultate korišćenjem adaptivnog thresholda. Pretposlednji parametar metode <b>adaptiveThreshold</b> je ključan, jer predstavlja veličinu bloka susednih piksela (npr. 15x15) na osnovnu kojih se računa lokalni prag.", "_____no_output_____" ] ], [ [ "# adaptivni threshold gde se prag racuna = srednja vrednost okolnih piksela\nimage_ada_bin = cv2.adaptiveThreshold(image_ada, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 5)\nplt.figure() # ako je potrebno da se prikaze vise slika u jednoj celiji\nplt.imshow(image_ada_bin, 'gray')\n\n# adaptivni threshold gde se prag racuna = tezinska suma okolnih piksela, gde su tezine iz gausove raspodele\nimage_ada_bin = cv2.adaptiveThreshold(image_ada, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 5)\nplt.figure()\nplt.imshow(image_ada_bin, 'gray')", "_____no_output_____" ] ], [ [ "### Histogram\n\nMožemo koristiti **histogram**, koji će nam dati informaciju o distribuciji osvetljenosti piksela.\n\nVrlo koristan kada je potrebno odrediti prag za globalni threshold.\n\nPseudo-kod histograma za grayscale sliku: \n```code\ninicijalizovati nula vektor od 256 elemenata \n\nza svaki piksel na slici:\n preuzeti inicijalni intezitet piksela\n uvecati za 1 broj piksela tog inteziteta\n\nplotovati histogram\n```", "_____no_output_____" ] ], [ [ "def hist(image):\n height, width = image.shape[0:2]\n x = range(0, 256)\n y = np.zeros(256)\n \n for i in range(0, height):\n for j in range(0, width):\n pixel = image[i, j]\n y[pixel] += 1\n \n return (x, y)\n\nx,y = hist(img_gray)\nplt.plot(x, y, 'b')\nplt.show()", "_____no_output_____" ] ], [ [ "Koristeći <b>matplotlib</b>:", "_____no_output_____" ] ], [ [ "plt.hist(img_gray.ravel(), 255, [0, 255])\nplt.show()", "_____no_output_____" ] ], [ [ "Koristeći <b>OpenCV</b>:", "_____no_output_____" ] ], [ [ "hist_full = cv2.calcHist([img_gray], [0], None, [255], [0, 255])\nplt.plot(hist_full)\nplt.show()", "_____no_output_____" ] ], [ [ "Pretpostavimo da su vrednosti piksela lica između 100 i 200.", "_____no_output_____" ] ], [ [ "img_tr = (img_gray > 100) * (img_gray < 200)\nplt.imshow(img_tr, 'gray')", "_____no_output_____" ] ], [ [ "### Konverovanje iz \"grayscale\" u RGB\n\nOvo je zapravo trivijalna operacija koja za svaki kanal boje (RGB) napravi kopiju od originalne grayscale slike. Ovo je zgodno kada nešto što je urađeno u grayscale modelu treba iskoristiti zajedno sa RGB slikom.", "_____no_output_____" ] ], [ [ "img_tr_rgb = cv2.cvtColor(img_tr.astype('uint8'), cv2.COLOR_GRAY2RGB)", "_____no_output_____" ], [ "plt.imshow(img*img_tr_rgb) # množenje originalne RGB slike i slike sa izdvojenim pikselima lica", "_____no_output_____" ] ], [ [ "### Morfološke operacije\n\nVeliki skup operacija za obradu digitalne slike, gde su te operacije zasnovane na oblicima, odnosno **strukturnim elementima**. U morfološkim operacijama, vrednost svakog piksela rezultujuće slike se zasniva na poređenju odgovarajućeg piksela na originalnoj slici sa svojom okolinom. Veličina i oblik ove okoline predstavljaju strukturni element.", "_____no_output_____" ] ], [ [ "kernel = np.ones((3, 3)) # strukturni element 3x3 blok\nprint(kernel)", "_____no_output_____" ] ], [ [ "#### Erozija\n\nMorfološka erozija postavlja vrednost piksela rez. slike na ```(i,j)``` koordinatama na **minimalnu** vrednost svih piksela u okolini ```(i,j)``` piksela na orig. slici.\n\nU suštini erozija umanjuje regione belih piksela, a uvećava regione crnih piksela. Često se koristi za uklanjanje šuma (u vidu sitnih regiona belih piksela).\n\n![images/erosion.gif](images/erosion.gif)", "_____no_output_____" ] ], [ [ "plt.imshow(cv2.erode(image_bin, kernel, iterations=1), 'gray')", "_____no_output_____" ] ], [ [ "#### Dilacija\n\nMorfološka dilacija postavlja vrednost piksela rez. slike na ```(i,j)``` koordinatama na **maksimalnu** vrednost svih piksela u okolini ```(i,j)``` piksela na orig. slici.\n\nU suštini dilacija uvećava regione belih piksela, a umanjuje regione crnih piksela. Zgodno za izražavanje regiona od interesa.\n\n![images/dilation.gif](images/dilation.gif)", "_____no_output_____" ] ], [ [ "# drugaciji strukturni element\nkernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5,5)) # MORPH_ELIPSE, MORPH_RECT...\nprint(kernel)\nplt.imshow(cv2.dilate(image_bin, kernel, iterations=5), 'gray') # 5 iteracija", "_____no_output_____" ] ], [ [ "#### Otvaranje i zatvaranje\n\n**```otvaranje = erozija + dilacija```**, uklanjanje šuma erozijom i vraćanje originalnog oblika dilacijom.\n\n**```zatvaranje = dilacija + erozija```**, zatvaranje sitnih otvora među belim pikselima", "_____no_output_____" ] ], [ [ "kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))\nprint(kernel)\nimg_ero = cv2.erode(image_bin, kernel, iterations=1)\nimg_open = cv2.dilate(img_ero, kernel, iterations=1)\nplt.imshow(img_open, 'gray')", "_____no_output_____" ], [ "img_dil = cv2.dilate(image_bin, kernel, iterations=1)\nimg_close = cv2.erode(img_dil, kernel, iterations=1)\nplt.imshow(img_close, 'gray')", "_____no_output_____" ] ], [ [ "Primer detekcije ivica na binarnoj slici korišćenjem dilatacije i erozije:", "_____no_output_____" ] ], [ [ "kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\nimage_edges = cv2.dilate(image_bin, kernel, iterations=1) - cv2.erode(image_bin, kernel, iterations=1)\nplt.imshow(image_edges, 'gray')", "_____no_output_____" ] ], [ [ "### Zamućenje (blur)\n\nZamućenje slike se dobija tako što se za svaki piksel slike kao nova vrednost uzima srednja vrednost okolnih piksela, recimo u okolini 5 x 5. Kernel <b>k</b> predstavlja kernel za <i>uniformno zamućenje</i>. Ovo je jednostavnija verzija <a href=\"https://en.wikipedia.org/wiki/Gaussian_blur\">Gausovskog zamućenja</a>.\n\n<img src=\"https://render.githubusercontent.com/render/math?math=k%285x5%29%3D%0A%20%20%5Cbegin%7Bbmatrix%7D%0A%20%20%20%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%5C%5C%0A%20%20%20%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%5C%5C%0A%20%20%20%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%5C%5C%0A%20%20%20%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%5C%5C%0A%20%20%20%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%20%26amp%3B%201%2F25%0A%20%20%5Cend%7Bbmatrix%7D&mode=display\">", "_____no_output_____" ] ], [ [ "from scipy import signal\n\nk_size = 5\nk = (1./k_size*k_size) * np.ones((k_size, k_size))\nimage_blur = signal.convolve2d(img_gray, k)\nplt.imshow(image_blur, 'gray')", "_____no_output_____" ] ], [ [ "### Regioni i izdvajanje regiona\n\nNajjednostavnije rečeno, region je skup međusobno povezanih belih piksela. Kada se kaže povezanih, misli se na to da se nalaze u neposrednoj okolini. Razlikuju se dve vrste povezanosti: tzv. **4-connectivity** i **8-connectivity**:\n\n![images/48connectivity.png](images/48connectivity.png)\n\nPostupak kojim se izdvajanju/obeležavaju regioni se naziva **connected components labelling**. Ovo ćemo primeniti na problemu izdvajanja barkoda.", "_____no_output_____" ] ], [ [ "# ucitavanje slike i convert u RGB\nimg_barcode = cv2.cvtColor(cv2.imread('images/barcode.jpg'), cv2.COLOR_BGR2RGB)\nplt.imshow(img_barcode)", "_____no_output_____" ] ], [ [ "Recimo da želimo da izdvojimo samo linije barkoda sa slike.\nZa početak, uradimo neke standardne operacije, kao što je konvertovanje u grayscale i adaptivni threshold.", "_____no_output_____" ] ], [ [ "img_barcode_gs = cv2.cvtColor(img_barcode, cv2.COLOR_RGB2GRAY) # konvert u grayscale\nplt.imshow(img_barcode_gs, 'gray')", "_____no_output_____" ], [ "#ret, image_barcode_bin = cv2.threshold(img_barcode_gs, 80, 255, cv2.THRESH_BINARY)\nimage_barcode_bin = cv2.adaptiveThreshold(img_barcode_gs, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 35, 10)\nplt.imshow(image_barcode_bin, 'gray')", "_____no_output_____" ] ], [ [ "### Pronalaženje kontura/regiona\n\nKonture, odnosno regioni na slici su grubo rečeno grupe crnih piksela. OpenCV metoda <b>findContours</b> pronalazi sve ove grupe crnih piksela, tj. regione. Druga povratna vrednost metode, odnosno <i>contours</i> je lista pronađeih kontura na slici.\n\nOve konture je zaim moguće iscrtati metodom <b>drawContours</b>, gde je prvi parametar slika na kojoj se iscrtavaju pronađene konture, drugi parametar je lista kontura koje je potrebno iscrtati, treći parametar određuje koju konturu po redosledu iscrtati (-1 znači iscrtavanje svih kontura), četvrti parametar je boja kojom će se obeležiti kontura, a poslednji parametar je debljina linije.", "_____no_output_____" ] ], [ [ "contours, hierarchy = cv2.findContours(image_barcode_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\nimg = img_barcode.copy()\ncv2.drawContours(img, contours, -1, (255, 0, 0), 1)\nplt.imshow(img)", "_____no_output_____" ] ], [ [ "#### Osobine regiona\n\nSvi pronađeni regioni imaju neke svoje karakteristične osobine: površina, obim, konveksni omotač, konveksnost, obuhvatajući pravougaonik, ugao... Ove osobine mogu biti izuzetno korisne kada je neophodno izdvojiti samo određene regione sa slike koji ispoljavaju neku osobinu. Za sve osobine pogledati <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html\">ovo</a> i <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_properties/py_contour_properties.html\">ovo</a>.\n\nIzdvajamo samo bar-kod sa slike.", "_____no_output_____" ] ], [ [ "contours_barcode = [] #ovde ce biti samo konture koje pripadaju bar-kodu\nfor contour in contours: # za svaku konturu\n center, size, angle = cv2.minAreaRect(contour) # pronadji pravougaonik minimalne povrsine koji ce obuhvatiti celu konturu\n width, height = size\n if width > 3 and width < 30 and height > 300 and height < 400: # uslov da kontura pripada bar-kodu\n contours_barcode.append(contour) # ova kontura pripada bar-kodu\n\nimg = img_barcode.copy()\ncv2.drawContours(img, contours_barcode, -1, (255, 0, 0), 1)\nplt.imshow(img)", "_____no_output_____" ], [ "print('Ukupan broj regiona: %d' % len(contours_barcode))", "_____no_output_____" ] ], [ [ "Naravno, u ogromnom broj slučajeva odnos visine i širine neće biti dovoljan, već se moraju koristiti i ostale osobine.", "_____no_output_____" ], [ "## Zadaci\n\n* Sa slike sa sijalicama (**images/bulbs.jpg**) prebrojati koliko ima sijalica.\n* Sa slike barkoda (**images/barcode.jpg**) izdvojiti samo brojeve i slova, bez linija barkoda.\n* Na slici sa snouborderima (**images/snowboarders.jpg**) prebrojati koliko ima snoubordera.\n* Na slici sa fudbalerima (**images/football.jpg**) izdvojiti samo one fudbalere u belim dresovima.\n* Na slici sa crvenim krvnim zrncima (**images/bloodcells.jpg**), prebrojati koliko ima crvenih krvnih zrnaca.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
d01eeb35694bd0dae461f98e757eb78cd17962ef
159,504
ipynb
Jupyter Notebook
paper_code/Beuzen_et_al_2019_code.ipynb
TomasBeuzen/BeuzenEtAl_2019_NHESS_GP_runup_model
ee2a3eae715619b0b7e264d01f968b178bb1587c
[ "MIT" ]
2
2019-11-23T03:22:03.000Z
2022-02-04T00:38:13.000Z
paper_code/Beuzen_et_al_2019_code.ipynb
TomasBeuzen/BeuzenEtAl_GP_Paper
ee2a3eae715619b0b7e264d01f968b178bb1587c
[ "MIT" ]
null
null
null
paper_code/Beuzen_et_al_2019_code.ipynb
TomasBeuzen/BeuzenEtAl_GP_Paper
ee2a3eae715619b0b7e264d01f968b178bb1587c
[ "MIT" ]
1
2019-09-23T18:00:25.000Z
2019-09-23T18:00:25.000Z
239.855639
71,108
0.903256
[ [ [ "## <center>Ensemble models from machine learning: an example of wave runup and coastal dune erosion</center>\n### <center>Tomas Beuzen<sup>1</sup>, Evan B. Goldstein<sup>2</sup>, Kristen D. Splinter<sup>1</sup></center>\n<center><sup>1</sup>Water Research Laboratory, School of Civil and Environmental Engineering, UNSW Sydney, NSW, Australia</center>\n\n<center><sup>2</sup>Department of Geography, Environment, and Sustainability, University of North Carolina at Greensboro, Greensboro, NC, USA</center>\n\n\nThis notebook contains the code required to develop the Gaussian Process (GP) runup predictor developed in the manuscript \"*Ensemble models from machine learning: an example of wave runup and coastal dune erosion*\" by Beuzen et al.\n\n**Citation:** Beuzen, T, Goldstein, E.B., Splinter, K.S. (In Review). Ensemble models from machine learning: an example of wave runup and coastal dune erosion, Natural Hazards and Earth Systems Science, SI Advances in computational modeling of geoprocesses and geohazards.\n\n### Table of Contents:\n1. [Imports](#bullet-0)\n2. [Load and Visualize Data](#bullet-1)\n3. [Develop GP Runup Predictor](#bullet-2)\n4. [Test GP Runup Predictor](#bullet-3)\n5. [Explore GP Prediction Uncertainty](#bullet-4)", "_____no_output_____" ], [ "## 1. Imports <a class=\"anchor\" id=\"bullet-0\"></a>", "_____no_output_____" ] ], [ [ "# Required imports\n# Standard computing packages\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Gaussian Process tools\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, WhiteKernel\n\n# Notebook functionality\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## 2. Load and Visualize Data <a class=\"anchor\" id=\"bullet-1\"></a>\nIn this section, we will load and visualise the wave, beach slope, and runup data we will use to develop the Gaussian process (GP) runup predictor.", "_____no_output_____" ] ], [ [ "# Read in .csv data file as a pandas dataframe\ndf = pd.read_csv('../data_repo_temporary/lidar_runup_data_for_GP_training.csv',index_col=0)\n# Print the size and head of the dataframe\nprint('Data size:', df.shape)\ndf.head()", "Data size: (416, 4)\n" ], [ "# This cell plots histograms of the data\n# Initialize the figure and axes\nfig, axes = plt.subplots(2,2,figsize=(6,6))\nplt.tight_layout(w_pad=0.1, h_pad=3)\n# Subplot (0,0): Hs\nax = axes[0,0]\nax.hist(df.Hs,28,color=(0.6,0.6,0.6),edgecolor='k',lw=0.5) # Plot histogram\nax.set_xlabel('H$_s$ (m)') # Format plot\nax.set_ylabel('Frequency')\nax.set_xticks((0,1.5,3,4.5))\nax.set_xlim((0,4.5))\nax.set_ylim((0,50))\nax.grid(lw=0.5,alpha=0.7)\nax.text(-1.1, 52, 'A)', fontsize=12)\nax.tick_params(direction='in')\nax.set_axisbelow(True)\n# Subplot (0,1): Tp\nax = axes[0,1]\nax.hist(df.Tp,20,color=(0.6,0.6,0.6),edgecolor='k',lw=0.5) # Plot histogram\nax.set_xlabel('T$_p$ (s)') # Format plot\nax.set_xticks((0,6,12,18))\nax.set_xlim((0,18))\nax.set_ylim((0,50))\nax.set_yticklabels([])\nax.grid(lw=0.5,alpha=0.7)\nax.text(-2.1, 52, 'B)', fontsize=12)\nax.tick_params(direction='in')\nax.set_axisbelow(True)\n# Subplot (1,0): beta\nax = axes[1,0]\nax.hist(df.beach_slope,20,color=(0.6,0.6,0.6),edgecolor='k',lw=0.5) # Plot histogram\nax.set_xlabel(r'$\\beta$') # Format plot\nax.set_ylabel('Frequency')\nax.set_xticks((0,0.1,0.2,0.3))\nax.set_xlim((0,0.3))\nax.set_ylim((0,50))\nax.grid(lw=0.5,alpha=0.7)\nax.text(-0.073, 52, 'C)', fontsize=12)\nax.tick_params(direction='in')\nax.set_axisbelow(True)\n# Subplot (1,1): R2\nax = axes[1,1]\nax.hist(df.runup,24,color=(0.9,0.2,0.2),edgecolor='k',lw=0.5) # Plot histogram\nax.set_xlabel('R$_2$ (m)') # Format plot\nax.set_xticks((0,1,2,3))\nax.set_xlim((0,3))\nax.set_ylim((0,50))\nax.set_yticklabels([])\nax.grid(lw=0.5,alpha=0.7)\nax.text(-0.35, 52, 'D)', fontsize=12)\nax.tick_params(direction='in')\nax.set_axisbelow(True);", "_____no_output_____" ] ], [ [ "## 3. Develop GP Runup Predictor <a class=\"anchor\" id=\"bullet-2\"></a>\nIn this section we will develop the GP runup predictor.\n\nWe standardize the data for use in the GP by removing the mean and scaling to unit variance. This does not really affect GP performance but improves computational efficiency (see sklearn documentation for more information).\n\nA kernel must be specified to develop the GP. Many kernels were trialled in initial GP development. The final kernel is a combination of the RBF and WhiteKernel. See **Section 2.1** and **Section 2.2** of the manuscript for further discussion.", "_____no_output_____" ] ], [ [ "# Define features and response data\nX = df.drop(columns=df.columns[-1]) # Drop the last column to retain input features (Hs, Tp, slope)\ny = df[[df.columns[-1]]] # The last column is the predictand (R2)", "_____no_output_____" ] ], [ [ "# Standardize data for use in the GP\nscaler = StandardScaler()\nscaler.fit(X) # Fit the scaler to the training data\nX_scaled = scaler.transform(X) # Scale training data", "_____no_output_____" ] ], [ [ "# Specify the kernel to use in the GP\nkernel = RBF(0.1, (1e-2, 1e2)) + WhiteKernel(1,(1e-2,1e2))", "_____no_output_____" ], [ "# Train GP model on training dataset\ngp = GaussianProcessRegressor(kernel=kernel,\n n_restarts_optimizer=9,\n normalize_y=True,\n random_state=123)\ngp.fit(X, y);", "_____no_output_____" ] ], [ [ "## 4. Test GP Runup Predictor <a class=\"anchor\" id=\"bullet-3\"></a>\nThis section now shows how the GP runup predictor can be used to test 50 test samples not previosuly used in training.", "_____no_output_____" ] ], [ [ "# Read in .csv test data file as a pandas dataframe\ndf_test = pd.read_csv('../data_repo_temporary/lidar_runup_data_for_GP_testing.csv',index_col=0)\n# Print the size and head of the dataframe\nprint('Data size:', df_test.shape)\ndf_test.head()", "Data size: (50, 4)\n" ], [ "# Predict the data\nX_test = df_test.drop(columns=df.columns[-1]) # Drop the last column to retain input features (Hs, Tp, slope)\ny_test = df_test[[df_test.columns[-1]]] # The last column is the predictand (R2)\ny_test_predictions = gp.predict(X_test)\nprint('GP RMSE on test data =', format(np.sqrt(mean_squared_error(y_test,y_test_predictions)),'.2f'))", "GP RMSE on test data = 0.22\n" ], [ "# This cell plots a figure comparing GP predictions to observations for the testing dataset\n# Similar to Figure 4 in the manuscript\n# Initialize the figure and axes\nfig, axes = plt.subplots(figsize=(6,6))\nplt.tight_layout(pad=2.2)\n# Plot and format\naxes.scatter(y_test,y_test_predictions,s=20,c='b',marker='.')\naxes.plot([0,4],[0,4],'k--')\naxes.set_ylabel('Predicted R$_2$ (m)')\naxes.set_xlabel('Observed R$_2$ (m)')\naxes.grid(lw=0.5,alpha=0.7)\naxes.set_xlim(0,1.5)\naxes.set_ylim(0,1.5)\n# Print some statistics\nprint('GP RMSE on test data =', format(np.sqrt(mean_squared_error(y_test,y_test_predictions)),'.2f'))\nprint('GP bias on test data =', format(np.mean(y_test_predictions-y_test.values),'.2f'))", "GP RMSE on test data = 0.22\nGP bias on test data = 0.07\n" ] ], [ [ "## 5. Explore GP Prediction Uncertainty <a class=\"anchor\" id=\"bullet-3\"></a>\nThis section explores how we can draw random samples from the GP to explain scatter in the runup predictions. We randomly draw 100 samples from the GP and calculate how much of the scatter in the runup predictions is captured by the ensemble envelope for different ensemble sizes. The process is repeated 100 times for robustness. See **Section 3.3** of the manuscript for further discussion.\n\nWe then plot the prediction with prediction uncertainty to help visualize.", "_____no_output_____" ] ], [ [ "# Draw 100 samples from the GP model using the testing dataset\nGP_draws = gp.sample_y(X_test, n_samples=100, random_state=123).squeeze() # Draw 100 random samples from the GP\n# Initialize result arrays\nperc_ens = np.zeros((100,100)) # Initialize ensemble capture array\nperc_err = np.zeros((100,)) # Initialise arbitray error array\n# Loop to get results\nfor i in range(0,perc_ens.shape[0]):\n # Caclulate capture % in envelope created by adding arbitrary, uniform error to mean GP prediction\n lower = y_test_predictions*(1-i/100) # Lower bound\n upper = y_test_predictions*(1+i/100) # Upper bound\n perc_err[i] = sum((np.squeeze(y_test)>=np.squeeze(lower)) & (np.squeeze(y_test)<=np.squeeze(upper)))/y_test.shape[0] # Store percent capture\n for j in range(0,perc_ens.shape[1]):\n ind = np.random.randint(0,perc_ens.shape[0],i+1) # Determine i random integers\n lower = np.min(GP_draws[:,ind],axis=1) # Lower bound of ensemble of i random members\n upper = np.max(GP_draws[:,ind],axis=1) # Upper bound of ensemble of i random members\n perc_ens[i,j] = sum((np.squeeze(y_test)>=lower) & (np.squeeze(y_test)<=upper))/y_test.shape[0] # Store percent capture", "_____no_output_____" ], [ "# This cell plots a figure showing how samples from the GP can help to capture uncertainty in predictions\n# Similar to Figure 5 from the manuscript\n# Initialize the figure and axes\nfig, axes = plt.subplots(1,2,figsize=(9,4))\nplt.tight_layout()\nlim = 0.95 # Desired limit to test\n# Plot ensemble results\nax = axes[0]\nperc_ens_mean = np.mean(perc_ens,axis=1)\nax.plot(perc_ens_mean*100,'k-',lw=2)\nind = np.argmin(abs(perc_ens_mean-lim)) # Find where the capture rate > lim\nax.plot([ind,ind],[0,perc_ens_mean[ind]*100],'r--')\nax.plot([0,ind],[perc_ens_mean[ind]*100,perc_ens_mean[ind]*100],'r--')\nax.set_xlabel('# Draws from GP')\nax.set_ylabel('Observations captured \\n within ensemble range (%)')\nax.grid(lw=0.5,alpha=0.7)\nax.minorticks_on()\nax.set_xlim(0,100);\nax.set_ylim(0,100);\nax.text(-11.5, 107, 'A)', fontweight='bold', fontsize=12)\nprint('# draws needed for ' + format(lim*100,'.0f') + '% capture = ' + str(ind))\nprint('Mean/Min/Max for ' + str(ind) + ' draws = '\n + format(np.mean(perc_ens[ind,:])*100,'.1f') + '%/'\n + format(np.min(perc_ens[ind,:])*100,'.1f') + '%/'\n + format(np.max(perc_ens[ind,:])*100,'.1f') + '%')\n# Plot arbitrary error results\nax = axes[1]\nax.plot(perc_err*100,'k-',lw=2)\nind = np.argmin(abs(perc_err-lim)) # Find where the capture rate > lim\nax.plot([ind,ind],[0,perc_err[ind]*100],'r--')\nax.plot([0,ind],[perc_err[ind]*100,perc_err[ind]*100],'r--')\nax.set_xlabel('% Error added to mean GP estimate')\nax.grid(lw=0.5,alpha=0.7)\nax.minorticks_on()\nax.set_xlim(0,100);\nax.set_ylim(0,100);\nax.text(-11.5, 107, 'B)', fontweight='bold', fontsize=12)\nprint('% added error needed for ' + format(lim*100,'.0f') + '% capture = ' + str(ind) + '%')", "# draws needed for 95% capture = 11\nMean/Min/Max for 11 draws = 95.0%/86.0%/100.0%\n% added error needed for 95% capture = 59%\n" ], [ "# This cell plots predictions for all 50 test samples with prediction uncertainty from 12 ensemble members.\n# In the cell above, 12 members was identified as optimal for capturing 95% of observations.\n# Initialize the figure and axes\nfig, axes = plt.subplots(1,1,figsize=(10,6))\n# Make some data for plotting\nx = np.arange(1, len(y_test)+1)\nlower = np.min(GP_draws[:,:12],axis=1) # Lower bound of ensemble of 12 random members\nupper = np.max(GP_draws[:,:12],axis=1) # Upper bound of ensemble of 12 random members\n# Plot\naxes.plot(x,y_test,'o',linestyle='-',color='C0',mfc='C0',mec='k',zorder=10,label='Observed')\naxes.plot(x,y_test_predictions,'k',marker='o',color='C1',mec='k',label='GP Ensemble Mean')\n\naxes.fill_between(x,\n lower,\n upper,\n alpha=0.2,\n facecolor='C1',\n label='GP Ensemble Range')\n# Formatting\naxes.set_xlim(0,50)\naxes.set_ylim(0,2.5)\naxes.set_xlabel('Observation')\naxes.set_ylabel('R2 (m)')\naxes.grid()\naxes.legend(framealpha=1)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "raw", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "raw" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d01ef20a85439b6956960e98c50c8e4fc4975cc2
22,318
ipynb
Jupyter Notebook
NN using PyTorch.ipynb
Spurryag/PyTorch-Scholarship-Programme-Solutions
360e15a833a204b3234d0410830661f27487c3f2
[ "MIT" ]
null
null
null
NN using PyTorch.ipynb
Spurryag/PyTorch-Scholarship-Programme-Solutions
360e15a833a204b3234d0410830661f27487c3f2
[ "MIT" ]
null
null
null
NN using PyTorch.ipynb
Spurryag/PyTorch-Scholarship-Programme-Solutions
360e15a833a204b3234d0410830661f27487c3f2
[ "MIT" ]
null
null
null
43.675147
4,964
0.633793
[ [ [ "import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Define a transform to normalize the data - change the range of values in the image [histogram stretch]\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n\n# Download and load the training data\ntrainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n#batch_size up indicates that 64 images are taken at a time from the data loader", "_____no_output_____" ], [ "#create iterator to go through images\ndetaiter = iter(trainloader)\nimages,labels = detaiter.next()\nprint(type(images))\nprint(images.shape)#64 images per batch, 1 color channel and 28 x 28 pixels\nprint(labels.shape)#1 label per image", "<class 'torch.Tensor'>\ntorch.Size([64, 1, 28, 28])\ntorch.Size([64])\n" ], [ "#plot a sample image\nplt.imshow(images[1].numpy().squeeze(),cmap= 'Greys_r');", "_____no_output_____" ], [ "#Need to convert the current tensor to vector such that one image is a vector of (1 * 28 * 28) or (784)\n#This will lead to each batch of 64 having size 784 => (64, 784)\n#Source: https://www.aiworkbox.com/lessons/flatten-a-pytorch-tensor\n\nflattened = images.view(images.shape[0],-1)\nprint(flattened)", "tensor([[-1., -1., -1., ..., -1., -1., -1.],\n [-1., -1., -1., ..., -1., -1., -1.],\n [-1., -1., -1., ..., -1., -1., -1.],\n ...,\n [-1., -1., -1., ..., -1., -1., -1.],\n [-1., -1., -1., ..., -1., -1., -1.],\n [-1., -1., -1., ..., -1., -1., -1.]])\n" ], [ "##Random sampling creation ops are contained in torch.randn\n#Iterator in Python is simply an object that can be iterated upon. \n#An object which will return data, one element at a time. \n\n#images.shape[0] returns the dimensions o fhte array => basically take the first batch of images and flatten", "_____no_output_____" ], [ "#Use sigmoid for activation layer\n\n\"\"\"\"Same as before we start by defining the activation function\"\"\"\n\n#Define the sigmoid activtion function\ndef activation(x):\n \"\"\" Sigmoid activation function \n \n Arguments\n ---------\n x: torch.Tensor\n \"\"\"\n return 1/(1+torch.exp(-x))", "_____no_output_____" ], [ "#Sample solution for flattening images\n\ninputs = images.view(images.shape[0],-1) #change the size of the image iterator based on the first image and flatten\n\n#Create the weights and bias parameters\n#build network with 784 input units, 256 hidden units and 10 output units for weights and biases\n\n#Input layer\nw1 = torch.randn(784,256)\nb1 = torch.randn(256)\n\n#hidden layer\nw2 = torch.randn(256,10)\nb2 = torch.randn(10)\n\n#Connected layers\nh = activation(torch.mm(inputs,w1)+b1)\nout = torch.mm(h,w2)+b2", "_____no_output_____" ], [ "print(out.shape)", "torch.Size([64, 10])\n" ], [ "#Define the softmax activation function to obtain a probability distribution of the result\n\ndef softmax(x):\n return torch.exp(x)/torch.sum(torch.exp(x), dim=1).view(-1, 1)\n\nprobabilities = softmax(out)\n\n\n#Setting dim=0 takes the sum across the rows while dim=1 takes the sum across the columns.\n\n#=> Sanity checks\n\n# Does it have the right shape? Should be (64, 10)\nprint(probabilities.shape)\n# Does it sum to 1?\nprint(probabilities.sum(dim=1))", "torch.Size([64, 10])\ntensor([1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000])\n" ], [ "from torch import nn\n\nclass Network(nn.Module):\n def __init__(self):\n super().__init__()\n \n # Inputs to hidden layer linear transformation\n self.hidden = nn.Linear(784, 256)\n # Output layer, 10 units - one for each digit\n self.output = nn.Linear(256, 10)\n \n # Define sigmoid activation and softmax output \n self.sigmoid = nn.Sigmoid()\n self.softmax = nn.Softmax(dim=1)\n \n def forward(self, x):\n # Pass the input tensor through each of our operations\n x = self.hidden(x)\n x = self.sigmoid(x)\n x = self.output(x)\n x = self.softmax(x)\n \n return x", "_____no_output_____" ] ], [ [ "Let's go through this bit by bit.\n\n```python\nclass Network(nn.Module):\n```\n\nHere we're inheriting from `nn.Module`. Combined with `super().__init__()` this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from `nn.Module` when you're creating a class for your network. The name of the class itself can be anything.\n\n```python\nself.hidden = nn.Linear(784, 256)\n```\n\nThis line creates a module for a linear transformation, $x\\mathbf{W} + b$, with 784 inputs and 256 outputs and assigns it to `self.hidden`. The module automatically creates the weight and bias tensors which we'll use in the `forward` method. You can access the weight and bias tensors once the network (`net`) is created with `net.hidden.weight` and `net.hidden.bias`.\n\n```python\nself.output = nn.Linear(256, 10)\n```\n\nSimilarly, this creates another linear transformation with 256 inputs and 10 outputs.\n\n```python\nself.sigmoid = nn.Sigmoid()\nself.softmax = nn.Softmax(dim=1)\n```\n\nHere I defined operations for the sigmoid activation and softmax output. Setting `dim=1` in `nn.Softmax(dim=1)` calculates softmax across the columns.\n\n```python\ndef forward(self, x):\n```\n\nPyTorch networks created with `nn.Module` must have a `forward` method defined. It takes in a tensor `x` and passes it through the operations you defined in the `__init__` method.\n\n```python\nx = self.hidden(x)\nx = self.sigmoid(x)\nx = self.output(x)\nx = self.softmax(x)\n```\n\nHere the input tensor `x` is passed through each operation a reassigned to `x`. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the `__init__` method doesn't matter, but you'll need to sequence the operations correctly in the `forward` method.\n\nNow we can create a `Network` object.", "_____no_output_____" ] ], [ [ "#Text version of model architecture\n\nmodel = Network()\nmodel", "_____no_output_____" ], [ "# #Common way to define model using PyTorch\n\n# import torch.nn.functional as F\n\n# class Network(nn.Module):\n# def __init__(self):\n# super().__init__()\n# # Inputs to hidden layer linear transformation\n# self.hidden = nn.Linear(784, 256)\n# # Output layer, 10 units - one for each digit\n# self.output = nn.Linear(256, 10)\n \n# def forward(self, x):\n# # Hidden layer with sigmoid activation\n# x = F.sigmoid(self.hidden(x))\n# # Output layer with softmax activation\n# x = F.softmax(self.output(x), dim=1)\n \n# return x", "_____no_output_____" ], [ "from torch import nn\nimport torch.nn.functional as F\n\n#Create a network with 784 input units, a hidden layer with 128 units and a ReLU activation, \n#then a hidden layer with 64 units and a ReLU activation, \n#and finally an output layer with a softmax activation as shown above.\n\n\nclass Network(nn.Module):\n def __init__(self):\n super().__init__()\n # Defining the layers, 128, 64, 10 units each\n self.fc1 = nn.Linear(784, 128)\n self.fc2 = nn.Linear(128, 64)\n # Output layer, 10 units - one for each digit\n self.fc3 = nn.Linear(64, 10)\n \n def forward(self, x):\n ''' Forward pass through the network, returns the output logits '''\n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n x = F.relu(x)\n x = self.fc3(x)\n x = F.softmax(x, dim=1)\n return x\n", "_____no_output_____" ], [ "model1 = Network()\nmodel1", "_____no_output_____" ], [ "# Import necessary packages\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport torch\n\nimport helper\n\nimport matplotlib.pyplot as plt\n\n# Hyperparameters for our network\ninput_size = 784\nhidden_sizes = [128, 64]\noutput_size = 10\n\n# Build a feed-forward network\nmodel = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),\n nn.ReLU(),\n nn.Linear(hidden_sizes[0], hidden_sizes[1]),\n nn.ReLU(),\n nn.Linear(hidden_sizes[1], output_size),\n nn.Softmax(dim=1))\nprint(model)\n\n# Forward pass through the network and display output\nimages, labels = next(iter(trainloader))\nimages.resize_(images.shape[0], 1, 784)\nps = model.forward(images[0,:])\nhelper.view_classify(images[0].view(1, 28, 28), ps)", "Sequential(\n (0): Linear(in_features=784, out_features=128, bias=True)\n (1): ReLU()\n (2): Linear(in_features=128, out_features=64, bias=True)\n (3): ReLU()\n (4): Linear(in_features=64, out_features=10, bias=True)\n (5): Softmax()\n)\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d01efc423c6f773aa7178495142b2e036267e6dc
35,256
ipynb
Jupyter Notebook
Resources/Generator/GenerateData.ipynb
Ryan-Malin/Wk19MachineLearning
550c1a539718cab387f2f00d0e0415821873fcbb
[ "ADSL" ]
null
null
null
Resources/Generator/GenerateData.ipynb
Ryan-Malin/Wk19MachineLearning
550c1a539718cab387f2f00d0e0415821873fcbb
[ "ADSL" ]
null
null
null
Resources/Generator/GenerateData.ipynb
Ryan-Malin/Wk19MachineLearning
550c1a539718cab387f2f00d0e0415821873fcbb
[ "ADSL" ]
null
null
null
54.07362
2,530
0.495916
[ [ [ "!wget https://LoanStats_2019Q1.csv.zip\n!wget https://LoanStats_2019Q2.csv.zip\n!wget https://LoanStats_2019Q3.csv.zip\n!wget https://LoanStats_2019Q4.csv.zip\n//LoanStats_2020Q1.csv.zip", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom collections import Counter\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "columns = [\n \"loan_amnt\", \"int_rate\", \"installment\", \"home_ownership\", \"annual_inc\", \n \"verification_status\", \"pymnt_plan\", \"dti\", \"delinq_2yrs\", \n \"inq_last_6mths\", \"open_acc\", \"pub_rec\", \"revol_bal\", \"total_acc\", \n \"initial_list_status\", \"out_prncp\", \"out_prncp_inv\", \"total_pymnt\", \n \"total_pymnt_inv\", \"total_rec_prncp\", \"total_rec_int\", \n \"total_rec_late_fee\", \"recoveries\", \"collection_recovery_fee\", \n \"last_pymnt_amnt\", \"collections_12_mths_ex_med\", \"policy_code\", \n \"application_type\", \"acc_now_delinq\", \"tot_coll_amt\", \"tot_cur_bal\", \n \"open_acc_6m\", \"open_act_il\", \"open_il_12m\", \"open_il_24m\", \n \"mths_since_rcnt_il\", \"total_bal_il\", \"il_util\", \"open_rv_12m\", \n \"open_rv_24m\", \"max_bal_bc\", \"all_util\", \"total_rev_hi_lim\", \"inq_fi\", \n \"total_cu_tl\", \"inq_last_12m\", \"acc_open_past_24mths\", \"avg_cur_bal\", \n \"bc_open_to_buy\", \"bc_util\", \"chargeoff_within_12_mths\", \"delinq_amnt\", \n \"mo_sin_old_il_acct\", \"mo_sin_old_rev_tl_op\", \"mo_sin_rcnt_rev_tl_op\", \n \"mo_sin_rcnt_tl\", \"mort_acc\", \"mths_since_recent_bc\", \n \"mths_since_recent_inq\", \"num_accts_ever_120_pd\", \"num_actv_bc_tl\",\n \"num_actv_rev_tl\", \"num_bc_sats\", \"num_bc_tl\", \"num_il_tl\", \n \"num_op_rev_tl\", \"num_rev_accts\", \"num_rev_tl_bal_gt_0\", \"num_sats\", \n \"num_tl_120dpd_2m\", \"num_tl_30dpd\", \"num_tl_90g_dpd_24m\", \n \"num_tl_op_past_12m\", \"pct_tl_nvr_dlq\", \"percent_bc_gt_75\", \n \"pub_rec_bankruptcies\", \"tax_liens\", \"tot_hi_cred_lim\", \n \"total_bal_ex_mort\", \"total_bc_limit\", \"total_il_high_credit_limit\", \n \"hardship_flag\", \"debt_settlement_flag\",\n \"loan_status\"\n]\n\ntarget = \"loan_status\"", "_____no_output_____" ], [ "# Load the data\ndf1 = pd.read_csv(Path('../Resources/LoanStats_2019Q1.csv.zip'), skiprows=1)[:-2]\ndf2 = pd.read_csv(Path('../Resources/LoanStats_2019Q2.csv.zip'), skiprows=1)[:-2]\ndf3 = pd.read_csv(Path('../Resources/LoanStats_2019Q3.csv.zip'), skiprows=1)[:-2]\ndf4 = pd.read_csv(Path('../Resources/LoanStats_2019Q4.csv.zip'), skiprows=1)[:-2]\n\ndf = pd.concat([df1, df2, df3, df4]).loc[:, columns].copy()\n\n# Drop the null columns where all values are null\ndf = df.dropna(axis='columns', how='all')\n\n# Drop the null rows\ndf = df.dropna()\n\n# Remove the `Issued` loan status\nissued_mask = df['loan_status'] != 'Issued'\ndf = df.loc[issued_mask]\n\n# convert interest rate to numerical\ndf['int_rate'] = df['int_rate'].str.replace('%', '')\ndf['int_rate'] = df['int_rate'].astype('float') / 100\n\n\n# Convert the target column values to low_risk and high_risk based on their values\nx = {'Current': 'low_risk'} \ndf = df.replace(x)\n\nx = dict.fromkeys(['Late (31-120 days)', 'Late (16-30 days)', 'Default', 'In Grace Period'], 'high_risk') \ndf = df.replace(x)\n\n\nlow_risk_rows = df[df[target] == 'low_risk']\nhigh_risk_rows = df[df[target] == 'high_risk']\n\n#df = pd.concat([low_risk_rows, high_risk_rows.sample(n=len(low_risk_rows), replace=True)])\ndf = pd.concat([low_risk_rows.sample(n=len(high_risk_rows), random_state=42), high_risk_rows])\ndf = df.reset_index(drop=True)\ndf = df.rename({target:'target'}, axis=\"columns\")\ndf", "_____no_output_____" ], [ "df.to_csv('2019loans.csv', index=False)", "_____no_output_____" ], [ "# Load the data\nvalidate_df = pd.read_csv(Path('../Resources/LoanStats_2020Q1.csv.zip'), skiprows=1)[:-2]\nvalidate_df = validate_df.loc[:, columns].copy()\n\n# Drop the null columns where all values are null\nvalidate_df = validate_df.dropna(axis='columns', how='all')\n\n# Drop the null rows\nvalidate_df = validate_df.dropna()\n\n# Remove the `Issued` loan status\nissued_mask = validate_df[target] != 'Issued'\nvalidate_df = validate_df.loc[issued_mask]\n\n# convert interest rate to numerical\nvalidate_df['int_rate'] = validate_df['int_rate'].str.replace('%', '')\nvalidate_df['int_rate'] = validate_df['int_rate'].astype('float') / 100\n\n\n# Convert the target column values to low_risk and high_risk based on their values\nx = dict.fromkeys(['Current', 'Fully Paid'], 'low_risk') \nvalidate_df = validate_df.replace(x)\n\nx = dict.fromkeys(['Late (31-120 days)', 'Late (16-30 days)', 'Default', 'In Grace Period', 'Charged Off'], 'high_risk') \nvalidate_df = validate_df.replace(x)\n\nlow_risk_rows = validate_df[validate_df[target] == 'low_risk']\nhigh_risk_rows = validate_df[validate_df[target] == 'high_risk']\n\nvalidate_df = pd.concat([low_risk_rows.sample(n=len(high_risk_rows), random_state=37), high_risk_rows])\nvalidate_df = validate_df.reset_index(drop=True)\nvalidate_df = validate_df.rename({target:'target'}, axis=\"columns\")\nvalidate_df", "Z:\\Travis\\anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3063: DtypeWarning: Columns (0,138,139,140) have mixed types.Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n" ], [ "validate_df.to_csv('2020Q1loans.csv', index=False)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d01eff1c77ec92e1ca9ce8e74245d31ad853b842
828,173
ipynb
Jupyter Notebook
pretrained-model/tts/fastspeech2/export/fastspeech2-haqkiem.ipynb
ishine/malaya-speech
fd34afc7107af1656dff4b3201fa51dda54fde18
[ "MIT" ]
111
2020-08-31T04:58:54.000Z
2022-03-29T15:44:18.000Z
pretrained-model/tts/fastspeech2/export/fastspeech2-haqkiem.ipynb
ishine/malaya-speech
fd34afc7107af1656dff4b3201fa51dda54fde18
[ "MIT" ]
14
2020-12-16T07:27:22.000Z
2022-03-15T17:39:01.000Z
pretrained-model/tts/fastspeech2/export/fastspeech2-haqkiem.ipynb
ishine/malaya-speech
fd34afc7107af1656dff4b3201fa51dda54fde18
[ "MIT" ]
29
2021-02-09T08:57:15.000Z
2022-03-12T14:09:19.000Z
876.373545
134,136
0.953214
[ [ [ "import os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = ''", "_____no_output_____" ], [ "# !git pull", "_____no_output_____" ], [ "import tensorflow as tf\nimport malaya_speech\nimport malaya_speech.train\nfrom malaya_speech.train.model import fastspeech2\nimport numpy as np", "WARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/optimizer/__init__.py:38: The name tf.train.AdagradOptimizer is deprecated. Please use tf.compat.v1.train.AdagradOptimizer instead.\n\nWARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/optimizer/__init__.py:39: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.\n\nWARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/optimizer/__init__.py:40: The name tf.train.FtrlOptimizer is deprecated. Please use tf.compat.v1.train.FtrlOptimizer instead.\n\nWARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/optimizer/__init__.py:42: The name tf.train.RMSPropOptimizer is deprecated. Please use tf.compat.v1.train.RMSPropOptimizer instead.\n\nWARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/optimizer/__init__.py:43: The name tf.train.GradientDescentOptimizer is deprecated. Please use tf.compat.v1.train.GradientDescentOptimizer instead.\n\nWARNING:tensorflow:\nThe TensorFlow contrib module will not be included in TensorFlow 2.0.\nFor more information, please see:\n * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n * https://github.com/tensorflow/addons\n * https://github.com/tensorflow/io (for I/O related ops)\nIf you depend on functionality not listed there, please file an issue.\n\nWARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/model/openseq2seq/layer.py:6: The name tf.layers.Conv1D is deprecated. Please use tf.compat.v1.layers.Conv1D instead.\n\nWARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/model/openseq2seq/attention.py:4: The name tf.layers.Layer is deprecated. Please use tf.compat.v1.layers.Layer instead.\n\n" ], [ "_pad = 'pad'\n_start = 'start'\n_eos = 'eos'\n_punctuation = \"!'(),.:;? \"\n_special = '-'\n_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n_rejected = '\\'():;\"'\n\nMALAYA_SPEECH_SYMBOLS = (\n [_pad, _start, _eos] + list(_special) + list(_punctuation) + list(_letters)\n)", "_____no_output_____" ], [ "input_ids = tf.placeholder(tf.int32, [None, None])\nlens = tf.placeholder(tf.int32, [None, None])\nmel_outputs = tf.placeholder(tf.float32, [None, None, 80])\nmel_lengths = tf.placeholder(tf.int32, [None])\nenergies = tf.placeholder(tf.float32, [None, None])\nenergies_lengths = tf.placeholder(tf.int32, [None])\nf0s = tf.placeholder(tf.float32, [None, None])\nf0s_lengths = tf.placeholder(tf.int32, [None])", "_____no_output_____" ], [ "config = malaya_speech.config.fastspeech2_config\nconfig = fastspeech2.Config(\n vocab_size = len(MALAYA_SPEECH_SYMBOLS), **config\n)\nmodel = fastspeech2.Model(config)", "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/keras/initializers.py:119: calling RandomUniform.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\nInstructions for updating:\nCall initializer instance with the dtype argument instead of passing it to the constructor\nWARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/model/fastspeech/layer.py:11: The name tf.keras.initializers.TruncatedNormal is deprecated. Please use tf.compat.v1.keras.initializers.TruncatedNormal instead.\n\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/keras/initializers.py:94: calling TruncatedNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\nInstructions for updating:\nCall initializer instance with the dtype argument instead of passing it to the constructor\n" ], [ "r_training = model(input_ids, lens, f0s, energies, training = False)", "WARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/model/fastspeech/model.py:68: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/array_ops.py:1475: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\n" ], [ "speed_ratios = tf.placeholder(tf.float32, [None], name = 'speed_ratios')\nf0_ratios = tf.placeholder(tf.float32, [None], name = 'f0_ratios')\nenergy_ratios = tf.placeholder(tf.float32, [None], name = 'energy_ratios')\n\nr = model.inference(input_ids, speed_ratios, f0_ratios, energy_ratios)", "_____no_output_____" ], [ "r", "_____no_output_____" ], [ "decoder_output = tf.identity(r[0], name = 'decoder_output')\npost_mel_outputs = tf.identity(r[1], name = 'post_mel_outputs')", "_____no_output_____" ], [ "sess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())", "_____no_output_____" ], [ "path = 'fastspeech2-haqkiem'\nckpt_path = tf.train.latest_checkpoint(path)\nckpt_path", "_____no_output_____" ], [ "saver = tf.train.Saver()\nsaver.restore(sess, ckpt_path)", "INFO:tensorflow:Restoring parameters from fastspeech2-haqkiem/model.ckpt-200000\n" ], [ "import re\nfrom unidecode import unidecode\nimport malaya\n\nnormalizer = malaya.normalize.normalizer(date = False, time = False)\npad_to = 8\n\ndef tts_encode(string: str, add_eos: bool = True):\n r = [MALAYA_SPEECH_SYMBOLS.index(c) for c in string if c in MALAYA_SPEECH_SYMBOLS]\n if add_eos:\n r = r + [MALAYA_SPEECH_SYMBOLS.index('eos')]\n return r\n\ndef put_spacing_num(string):\n string = re.sub('[A-Za-z]+', lambda ele: ' ' + ele[0] + ' ', string)\n return re.sub(r'[ ]+', ' ', string).strip()\n\ndef convert_to_ascii(string):\n return unidecode(string)\n\ndef collapse_whitespace(string):\n return re.sub(_whitespace_re, ' ', string)\n\ndef cleaning(string, normalize = True, add_eos = False):\n sequence = []\n string = convert_to_ascii(string)\n if string[-1] in '-,':\n string = string[:-1]\n if string[-1] not in '.,?!':\n string = string + '.'\n string = string.replace('&', ' dan ')\n string = string.replace(':', ',').replace(';', ',')\n if normalize:\n t = normalizer._tokenizer(string)\n for i in range(len(t)):\n if t[i] == '-':\n t[i] = ','\n string = ' '.join(t)\n string = normalizer.normalize(string, \n check_english = False, \n normalize_entity = False, \n normalize_text = False,\n normalize_url = True,\n normalize_email = True,\n normalize_year = True)\n string = string['normalize']\n else:\n string = string\n string = put_spacing_num(string)\n string = ''.join([c for c in string if c in MALAYA_SPEECH_SYMBOLS and c not in _rejected])\n string = re.sub(r'[ ]+', ' ', string).strip()\n string = string.lower()\n ids = tts_encode(string, add_eos = add_eos)\n text_input = np.array(ids)\n num_pad = pad_to - ((len(text_input) + 2) % pad_to)\n text_input = np.pad(\n text_input, ((1, 1)), 'constant', constant_values = ((1, 2))\n )\n text_input = np.pad(\n text_input, ((0, num_pad)), 'constant', constant_values = 0\n )\n \n return string, text_input", "_____no_output_____" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "# https://umno-online.my/2020/12/28/isu-kartel-daging-haram-lagi-pihak-gesa-kerajaan-ambil-tindakan-tegas-drastik/\n\nt, ids = cleaning('Haqkiem adalah pelajar tahun akhir yang mengambil Ijazah Sarjana Muda Sains Komputer Kecerdasan Buatan utama dari Universiti Teknikal Malaysia Melaka (UTeM) yang kini berusaha untuk latihan industri di mana dia secara praktikal dapat menerapkan pengetahuannya dalam Perisikan Perisian dan Pengaturcaraan ke arah organisasi atau industri yang berkaitan.')\nt, ids", "_____no_output_____" ], [ "%%time\n\no = sess.run([decoder_output, post_mel_outputs], feed_dict = {input_ids: [ids], \n speed_ratios: [1.0],\n f0_ratios: [1.0], \n energy_ratios: [1.0]})", "CPU times: user 4.87 s, sys: 232 ms, total: 5.1 s\nWall time: 655 ms\n" ], [ "o[1].shape", "_____no_output_____" ], [ "mel_outputs_ = np.reshape(o[1], [-1, 80])\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-before-Spectrogram')\nim = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()", "_____no_output_____" ], [ "mel_outputs_ = np.reshape(o[0], [-1, 80])\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-before-Spectrogram')\nim = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()", "_____no_output_____" ], [ "import pickle\n\nwith open('a.pkl', 'wb') as fopen:\n pickle.dump([np.reshape(o[0], [-1, 80]), np.reshape(o[1], [-1, 80])], fopen)", "_____no_output_____" ], [ "saver = tf.train.Saver()\nsaver.save(sess, 'fastspeech2-haqkiem-output/model.ckpt')", "_____no_output_____" ], [ "strings = ','.join(\n [\n n.name\n for n in tf.get_default_graph().as_graph_def().node\n if ('Variable' in n.op\n or 'gather' in n.op.lower()\n or 'Placeholder' in n.name\n or 'ratios' in n.name\n or 'post_mel_outputs' in n.name\n or 'decoder_output' in n.name\n or 'alignment_histories' in n.name)\n and 'adam' not in n.name\n and 'global_step' not in n.name\n and 'Assign' not in n.name\n and 'ReadVariableOp' not in n.name\n and 'Gather' not in n.name\n and 'IsVariableInitialized' not in n.name\n ]\n)\nstrings.split(',')", "_____no_output_____" ], [ "def freeze_graph(model_dir, output_node_names):\n\n if not tf.gfile.Exists(model_dir):\n raise AssertionError(\n \"Export directory doesn't exists. Please specify an export \"\n 'directory: %s' % model_dir\n )\n\n checkpoint = tf.train.get_checkpoint_state(model_dir)\n input_checkpoint = checkpoint.model_checkpoint_path\n\n absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])\n output_graph = absolute_model_dir + '/frozen_model.pb'\n clear_devices = True\n with tf.Session(graph = tf.Graph()) as sess:\n saver = tf.train.import_meta_graph(\n input_checkpoint + '.meta', clear_devices = clear_devices\n )\n saver.restore(sess, input_checkpoint)\n output_graph_def = tf.graph_util.convert_variables_to_constants(\n sess,\n tf.get_default_graph().as_graph_def(),\n output_node_names.split(','),\n )\n with tf.gfile.GFile(output_graph, 'wb') as f:\n f.write(output_graph_def.SerializeToString())\n print('%d ops in the final graph.' % len(output_graph_def.node))", "_____no_output_____" ], [ "freeze_graph('fastspeech2-haqkiem-output', strings)", "INFO:tensorflow:Restoring parameters from fastspeech2-haqkiem-output/model.ckpt\nWARNING:tensorflow:From <ipython-input-24-9a7215a4e58a>:23: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.convert_variables_to_constants`\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.extract_sub_graph`\nINFO:tensorflow:Froze 187 variables.\nINFO:tensorflow:Converted 187 variables to const ops.\n2896 ops in the final graph.\n" ], [ "def load_graph(frozen_graph_filename):\n with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n \n with tf.Graph().as_default() as graph:\n tf.import_graph_def(graph_def)\n \n return graph", "_____no_output_____" ], [ "g = load_graph('fastspeech2-haqkiem-output/frozen_model.pb')", "_____no_output_____" ], [ "test_sess = tf.InteractiveSession(graph = g)", "_____no_output_____" ], [ "X = g.get_tensor_by_name('import/Placeholder:0')\nspeed_ratios = g.get_tensor_by_name('import/speed_ratios:0')\nf0_ratios = g.get_tensor_by_name('import/f0_ratios:0')\nenergy_ratios = g.get_tensor_by_name('import/energy_ratios:0')", "_____no_output_____" ], [ "output_nodes = ['decoder_output', 'post_mel_outputs']\noutputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}", "_____no_output_____" ], [ "%%time\n\no = test_sess.run(outputs, feed_dict = {X: [ids], \n speed_ratios: [1.0],\n f0_ratios: [1.0], \n energy_ratios: [1.0]})", "CPU times: user 5.03 s, sys: 335 ms, total: 5.36 s\nWall time: 942 ms\n" ], [ "mel_outputs_ = np.reshape(o['decoder_output'], [-1, 80])\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-before-Spectrogram')\nim = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()", "_____no_output_____" ], [ "mel_outputs_ = np.reshape(o['post_mel_outputs'], [-1, 80])\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-before-Spectrogram')\nim = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()", "_____no_output_____" ], [ "from tensorflow.tools.graph_transforms import TransformGraph", "_____no_output_____" ], [ "transforms = ['add_default_attributes',\n 'remove_nodes(op=Identity, op=CheckNumerics)',\n 'fold_batch_norms',\n 'fold_old_batch_norms',\n 'quantize_weights(fallback_min=-1024, fallback_max=1024)',\n 'strip_unused_nodes',\n 'sort_by_execution_order']", "_____no_output_____" ], [ "pb = 'fastspeech2-haqkiem-output/frozen_model.pb'", "_____no_output_____" ], [ "input_graph_def = tf.GraphDef()\nwith tf.gfile.FastGFile(pb, 'rb') as f:\n input_graph_def.ParseFromString(f.read())\n\ntransformed_graph_def = TransformGraph(input_graph_def, \n ['Placeholder', 'speed_ratios', 'f0_ratios', 'energy_ratios'],\n output_nodes, transforms)\n \nwith tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:\n f.write(transformed_graph_def.SerializeToString())", "WARNING:tensorflow:From <ipython-input-37-e3d22b44649d>:2: FastGFile.__init__ (from tensorflow.python.platform.gfile) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.gfile.GFile.\n" ], [ "g = load_graph('fastspeech2-haqkiem-output/frozen_model.pb.quantized')", "_____no_output_____" ], [ "test_sess = tf.InteractiveSession(graph = g)\nX = g.get_tensor_by_name(f'import/Placeholder:0')\nspeed_ratios = g.get_tensor_by_name('import/speed_ratios:0')\nf0_ratios = g.get_tensor_by_name('import/f0_ratios:0')\nenergy_ratios = g.get_tensor_by_name('import/energy_ratios:0')\noutputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}", "_____no_output_____" ], [ "%%time\n\no = test_sess.run(outputs, feed_dict = {X: [ids], \n speed_ratios: [1.0],\n f0_ratios: [1.0], \n energy_ratios: [1.0]})", "CPU times: user 5.01 s, sys: 355 ms, total: 5.36 s\nWall time: 1.01 s\n" ], [ "mel_outputs_ = np.reshape(o['decoder_output'], [-1, 80])\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-before-Spectrogram')\nim = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()", "_____no_output_____" ], [ "mel_outputs_ = np.reshape(o['post_mel_outputs'], [-1, 80])\nfig = plt.figure(figsize=(10, 8))\nax1 = fig.add_subplot(311)\nax1.set_title(f'Predicted Mel-before-Spectrogram')\nim = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')\nfig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01f037ba1cd050e72af183ec64f14b5fc1e0fda
963,672
ipynb
Jupyter Notebook
AppliedDataScienceWithPython/Week3.ipynb
MikeBeaulieu/coursework
5f8ad9da8252b64992cea40d24615c63e31f7890
[ "MIT" ]
null
null
null
AppliedDataScienceWithPython/Week3.ipynb
MikeBeaulieu/coursework
5f8ad9da8252b64992cea40d24615c63e31f7890
[ "MIT" ]
null
null
null
AppliedDataScienceWithPython/Week3.ipynb
MikeBeaulieu/coursework
5f8ad9da8252b64992cea40d24615c63e31f7890
[ "MIT" ]
null
null
null
70.967818
48,403
0.66844
[ [ [ "# Subplots", "_____no_output_____" ] ], [ [ "%matplotlib notebook\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.subplot?", "_____no_output_____" ], [ "plt.figure()\n# subplot with 1 row, 2 columns, and current axis is 1st subplot axes\nplt.subplot(1, 2, 1)\n\nlinear_data = np.array([1,2,3,4,5,6,7,8])\n\nplt.plot(linear_data, '-o')", "_____no_output_____" ], [ "exponential_data = linear_data**2 \n\n# subplot with 1 row, 2 columns, and current axis is 2nd subplot axes\nplt.subplot(1, 2, 2)\nplt.plot(exponential_data, '-o')", "_____no_output_____" ], [ "# plot exponential data on 1st subplot axes\nplt.subplot(1, 2, 1)\nplt.plot(exponential_data, '-x')", "_____no_output_____" ], [ "plt.figure()\nax1 = plt.subplot(1, 2, 1)\nplt.plot(linear_data, '-o')\n# pass sharey=ax1 to ensure the two subplots share the same y axis\nax2 = plt.subplot(1, 2, 2, sharey=ax1)\nplt.plot(exponential_data, '-x')", "_____no_output_____" ], [ "plt.figure()\n# the right hand side is equivalent shorthand syntax\nplt.subplot(1,2,1) == plt.subplot(121)", "_____no_output_____" ], [ "# create a 3x3 grid of subplots\nfig, ((ax1,ax2,ax3), (ax4,ax5,ax6), (ax7,ax8,ax9)) = plt.subplots(3, 3, sharex=True, sharey=True)\n# plot the linear_data on the 5th subplot axes \nax5.plot(linear_data, '-')", "_____no_output_____" ], [ "# set inside tick labels to visible\nfor ax in plt.gcf().get_axes():\n for label in ax.get_xticklabels() + ax.get_yticklabels():\n label.set_visible(True)", "_____no_output_____" ], [ "# necessary on some systems to update the plot\nplt.gcf().canvas.draw()", "_____no_output_____" ] ], [ [ "# Histograms", "_____no_output_____" ] ], [ [ "# create 2x2 grid of axis subplots\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True)\naxs = [ax1,ax2,ax3,ax4]\n\n# draw n = 10, 100, 1000, and 10000 samples from the normal distribution and plot corresponding histograms\nfor n in range(0,len(axs)):\n sample_size = 10**(n+1)\n sample = np.random.normal(loc=0.0, scale=1.0, size=sample_size)\n axs[n].hist(sample)\n axs[n].set_title('n={}'.format(sample_size))", "_____no_output_____" ], [ "# repeat with number of bins set to 100\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True)\naxs = [ax1,ax2,ax3,ax4]\n\nfor n in range(0,len(axs)):\n sample_size = 10**(n+1)\n sample = np.random.normal(loc=0.0, scale=1.0, size=sample_size)\n axs[n].hist(sample, bins=100)\n axs[n].set_title('n={}'.format(sample_size))", "_____no_output_____" ], [ "plt.figure()\nY = np.random.normal(loc=0.0, scale=1.0, size=10000)\nX = np.random.random(size=10000)\nplt.scatter(X,Y)", "_____no_output_____" ], [ "# use gridspec to partition the figure into subplots\nimport matplotlib.gridspec as gridspec\n\nplt.figure()\ngspec = gridspec.GridSpec(3, 3)\n\ntop_histogram = plt.subplot(gspec[0, 1:])\nside_histogram = plt.subplot(gspec[1:, 0])\nlower_right = plt.subplot(gspec[1:, 1:])", "_____no_output_____" ], [ "Y = np.random.normal(loc=0.0, scale=1.0, size=10000)\nX = np.random.random(size=10000)\nlower_right.scatter(X, Y)\ntop_histogram.hist(X, bins=100)\ns = side_histogram.hist(Y, bins=100, orientation='horizontal')", "_____no_output_____" ], [ "# clear the histograms and plot normed histograms\ntop_histogram.clear()\ntop_histogram.hist(X, bins=100, normed=True)\nside_histogram.clear()\nside_histogram.hist(Y, bins=100, orientation='horizontal', normed=True)\n# flip the side histogram's x axis\nside_histogram.invert_xaxis()", "_____no_output_____" ], [ "# change axes limits\nfor ax in [top_histogram, lower_right]:\n ax.set_xlim(0, 1)\nfor ax in [side_histogram, lower_right]:\n ax.set_ylim(-5, 5)", "_____no_output_____" ], [ "%%HTML\n<img src='http://educationxpress.mit.edu/sites/default/files/journal/WP1-Fig13.jpg' />", "_____no_output_____" ] ], [ [ "# Box and Whisker Plots", "_____no_output_____" ] ], [ [ "import pandas as pd\nnormal_sample = np.random.normal(loc=0.0, scale=1.0, size=10000)\nrandom_sample = np.random.random(size=10000)\ngamma_sample = np.random.gamma(2, size=10000)\n\ndf = pd.DataFrame({'normal': normal_sample, \n 'random': random_sample, \n 'gamma': gamma_sample})", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ], [ "plt.figure()\n# create a boxplot of the normal data, assign the output to a variable to supress output\n_ = plt.boxplot(df['normal'], whis='range')", "_____no_output_____" ], [ "# clear the current figure\nplt.clf()\n# plot boxplots for all three of df's columns\n_ = plt.boxplot([ df['normal'], df['random'], df['gamma'] ], whis='range')", "_____no_output_____" ], [ "plt.figure()\n_ = plt.hist(df['gamma'], bins=100)", "_____no_output_____" ], [ "import mpl_toolkits.axes_grid1.inset_locator as mpl_il\n\nplt.figure()\nplt.boxplot([ df['normal'], df['random'], df['gamma'] ], whis='range')\n# overlay axis on top of another \nax2 = mpl_il.inset_axes(plt.gca(), width='60%', height='40%', loc=2)\nax2.hist(df['gamma'], bins=100)\nax2.margins(x=0.5)", "_____no_output_____" ], [ "# switch the y axis ticks for ax2 to the right side\nax2.yaxis.tick_right()", "_____no_output_____" ], [ "# if `whis` argument isn't passed, boxplot defaults to showing 1.5*interquartile (IQR) whiskers with outliers\nplt.figure()\n_ = plt.boxplot([ df['normal'], df['random'], df['gamma'] ] )", "_____no_output_____" ] ], [ [ "# Heatmaps", "_____no_output_____" ] ], [ [ "plt.figure()\n\nY = np.random.normal(loc=0.0, scale=1.0, size=10000)\nX = np.random.random(size=10000)\n_ = plt.hist2d(X, Y, bins=25)", "_____no_output_____" ], [ "plt.figure()\n_ = plt.hist2d(X, Y, bins=100)", "_____no_output_____" ], [ "# add a colorbar legend\nplt.colorbar()", "_____no_output_____" ] ], [ [ "# Animations", "_____no_output_____" ] ], [ [ "import matplotlib.animation as animation\n\nn = 100\nx = np.random.randn(n)", "_____no_output_____" ], [ "# create the function that will do the plotting, where curr is the current frame\ndef update(curr):\n # check if animation is at the last frame, and if so, stop the animation a\n if curr == n: \n a.event_source.stop()\n plt.cla()\n bins = np.arange(-4, 4, 0.5)\n plt.hist(x[:curr], bins=bins)\n plt.axis([-4,4,0,30])\n plt.gca().set_title('Sampling the Normal Distribution')\n plt.gca().set_ylabel('Frequency')\n plt.gca().set_xlabel('Value')\n plt.annotate('n = {}'.format(curr), [3,27])", "_____no_output_____" ], [ "fig = plt.figure()\na = animation.FuncAnimation(fig, update, interval=1000)", "_____no_output_____" ] ], [ [ "# Interactivity", "_____no_output_____" ] ], [ [ "plt.figure()\ndata = np.random.rand(10)\nplt.plot(data)\n\ndef onclick(event):\n plt.cla()\n plt.plot(data)\n plt.gca().set_title('Event at pixels {},{} \\nand data {},{}'.format(event.x, event.y, event.xdata, event.ydata))\n\n# tell mpl_connect we want to pass a 'button_press_event' into onclick when the event is detected\nplt.gcf().canvas.mpl_connect('button_press_event', onclick)", "_____no_output_____" ], [ "from random import shuffle\norigins = ['China', 'Brazil', 'India', 'USA', 'Canada', 'UK', 'Germany', 'Iraq', 'Chile', 'Mexico']\n\nshuffle(origins)\n\ndf = pd.DataFrame({'height': np.random.rand(10),\n 'weight': np.random.rand(10),\n 'origin': origins})\ndf", "_____no_output_____" ], [ "plt.figure()\n# picker=5 means the mouse doesn't have to click directly on an event, but can be up to 5 pixels away\nplt.scatter(df['height'], df['weight'], picker=5)\nplt.gca().set_ylabel('Weight')\nplt.gca().set_xlabel('Height')", "_____no_output_____" ], [ "def onpick(event):\n origin = df.iloc[event.ind[0]]['origin']\n plt.gca().set_title('Selected item came from {}'.format(origin))\n\n# tell mpl_connect we want to pass a 'pick_event' into onpick when the event is detected\nplt.gcf().canvas.mpl_connect('pick_event', onpick)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d01f03f308dc4687c9fea7b96b440cae8e4c9b38
32,373
ipynb
Jupyter Notebook
custom-who-to-follow/exploration.ipynb
ericmbudd/twitter-data-viz
55eebab346a0cac8f5eaec17f8b78361fa35738c
[ "MIT" ]
null
null
null
custom-who-to-follow/exploration.ipynb
ericmbudd/twitter-data-viz
55eebab346a0cac8f5eaec17f8b78361fa35738c
[ "MIT" ]
null
null
null
custom-who-to-follow/exploration.ipynb
ericmbudd/twitter-data-viz
55eebab346a0cac8f5eaec17f8b78361fa35738c
[ "MIT" ]
null
null
null
36.871298
187
0.396133
[ [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport networkx as nx\n%matplotlib inline", "_____no_output_____" ], [ "followers = pd.read_csv(\"giant_csv_of_followers.csv\",dtype = {\"user\":str,\"id\":str})", "_____no_output_____" ], [ "followers.drop(\"id\",axis = 1,inplace = True)\nfollowers.set_index(\"user\",inplace = True)\nfollowers.head()", "_____no_output_____" ], [ "followers[\"user_degree\"] = followers[followers.columns[0:99]].apply(sum,axis = 1)", "_____no_output_____" ], [ "followers_higher_degree = followers[followers[\"user_degree\"] > 1]", "_____no_output_____" ], [ "edge_list = []\nfor column in followers_higher_degree.columns[0:99]:\n edge_list.extend([(x,column) for x in followers_higher_degree[followers_higher_degree[column] == 1].index.tolist()])", "_____no_output_____" ], [ "influencers = {x:{\"is_influencer\":True} for x in followers_higher_degree.columns[0:99].tolist()}", "_____no_output_____" ], [ "followers_higher_degree[\"is_influencer\"] = False", "_____no_output_____" ], [ "users = followers_higher_degree[[\"ericmbudd_follows\",\"followers\",\"following\",\"tweets_count\",\"is_influencer\"]].transpose().to_dict()", "_____no_output_____" ], [ "digraph = nx.DiGraph()\ndigraph.add_nodes_from(influencers)\ndigraph.add_nodes_from(users)", "_____no_output_____" ], [ "digraph.add_edges_from(edge_list)", "_____no_output_____" ], [ "eric_follows = followers_higher_degree[followers_higher_degree[\"ericmbudd_follows\"] == 1].index.tolist()\ng_eric_follows = digraph.subgraph(eric_follows + list(influencers.keys()))", "_____no_output_____" ], [ "influencers_dict = {k:v for k,v in zip(range(0,100), followers_higher_degree[1:100].columns.tolist())}", "_____no_output_____" ], [ "followers_higher_degree.loc[:,\"edge_list\"] = followers_higher_degree[list(influencers.keys())].apply(\n lambda x: \",\".join([influencers_dict[i] for i,j in enumerate(x.tolist()) if j == 1]),axis = 1)", "/mnt/home/fiona/.virtualenvs/graph-analysis/lib/python3.5/site-packages/pandas/core/indexing.py:477: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self.obj[item] = s\n" ], [ "test = (followers_higher_degree[[\"edge_list\",\"ericmbudd_follows\"]]\n .reset_index()\n .groupby(\"edge_list\")\n .agg({\"user\": pd.Series.nunique, \"ericmbudd_follows\": sum})\n .sort_values(by = \"user\",ascending = False))", "_____no_output_____" ], [ "test.sort_values(by = \"ericmbudd_follows\", ascending = False)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d01f161cfbc2a56b79b31eccb9a93a39f55da3b1
5,151
ipynb
Jupyter Notebook
Homework 2 Solutions.ipynb
newby-jay/MATH381-Fall2021-JupyterNotebooks
9181fb6e154081de26fb267e0794a67f60ae11a0
[ "Apache-2.0" ]
null
null
null
Homework 2 Solutions.ipynb
newby-jay/MATH381-Fall2021-JupyterNotebooks
9181fb6e154081de26fb267e0794a67f60ae11a0
[ "Apache-2.0" ]
null
null
null
Homework 2 Solutions.ipynb
newby-jay/MATH381-Fall2021-JupyterNotebooks
9181fb6e154081de26fb267e0794a67f60ae11a0
[ "Apache-2.0" ]
null
null
null
35.280822
302
0.537566
[ [ [ "%pylab inline\n%config InlineBackend.figure_format = 'retina'\nfrom ipywidgets import interact\nimport scipy\nimport scipy.special", "Populating the interactive namespace from numpy and matplotlib\n" ] ], [ [ "# Question #1\nAssume that $f(\\cdot)$ is an infinitely smooth and continuous scalar function. Suppose that $a\\in \\mathbb{R}$ is a given constant in the domain of the function $f$ and that $h>0$ is a given parameter assumed to be small. Consider the following numerical approximation of a first derivative,\n$$ f'(a) \\approx c_h(a) = \\frac{f(a+h) - f(a - h)}{2h}.$$\n\nA. Use a Taylor's series expansion of the function $f$ around $a$ to show that the approximation error is $O(h^2)$ provided that $f'''(a) \\neq 0$.\n\nB. What happens to the error if $f'''(a) = 0$?\n", "_____no_output_____" ], [ "-------------------------------------\n## Solution\nA.\nThe absolute error is\n$$\\mathcal{E}_{\\rm abs} = \\left \\vert\\frac{f(x+h) - f(x - h)}{2h} - f'(x) \\right \\vert. $$\nTo derive the error, we expand our function in a Taylor's series, with\n$$ f(a \\pm h) = f(a) \\pm h f'(a) + \\frac{h^2}{2}f''(a) \\pm \\frac{h^3}{6} f'''(a) + O(h^4) $$\nSubstituting the Taylor's series into the absolute error yields\n\\begin{align*}\n\\mathcal{E}_{\\rm abs} &= \\left \\vert\n\\frac{1}{2h}\\left(hf'(a) + \\frac{h^2}{2}f''(a) + \\frac{h^3}{6} f'''(a) + O(h^4) + hf'(a) - \\frac{h^2}{2}f''(a) + \\frac{h^3}{6} f'''(a) - O(h^4)\\right) \\right \\vert \\\\\n &= \\left \\vert f'(a) + \\frac{h^2}{6}f'''(a) + O(h^4) - f'(a)\\right \\vert \\\\\n &= \\left \\vert \\frac{h^2}{6}f'''(a) + O(h^4) \\right \\vert \\\\\n &= \\frac{h^2}{6}\\left \\vert f'''(a)\\right \\vert + O(h^4) \n\\end{align*}\n\nB. The next nonzero term in the Taylor's series expansion of the error is $O(h^4)$, namely \n$$ \\frac{h^4}{5!}f^{(5)}(a). $$\nNote that the $O(h^3)$ cancels out.", "_____no_output_____" ], [ "# Question #2\nUse Example 2 in the Week 2 Jupyter notebook as a starting point. Copy the code and paste it into a new cell (you should be using a copy of the Week 2 notebook or a new notebook).\n\nA. Compute the derivative approximation derived in Q1 for the function $f(x) = \\sin(x)$ at the point $x=1.2$ for a range of values $10^{-20} \\leq h \\leq 10^{-1}$. \n$$$$\nB. Compute the absolute error between the approximation and the exact derivative for a range of values $10^{-20} \\leq h \\leq 10^{-1}$. \n\n(For parts A and B, turn in a screen shot of your code.)\n\nC. Create a plot of the absolute error. Add a plot of the discretization error that you derived in Q1. Is the derivative approximation that you derived in Q2 more accurate than the approximation used in Example 2? ", "_____no_output_____" ] ], [ [ "x0 = 1.2\nf0 = sin(x0)\nfp = cos(x0)\nfpp = -sin(x0)\nfppp = -cos(x0)\ni = linspace(-20, 0, 40)\nh = 10.0**i\nfp_approx = (sin(x0 + h) - f0)/h\nfp_center_diff_approx = (sin(x0 + h) - sin(x0 - h))/(2*h)\nerr = absolute(fp - fp_approx)\nerr2 = absolute(fp - fp_center_diff_approx)\nd_err = h/2*absolute(fpp) \nd2_err = h**2/6*absolute(fppp)\n\nfigure(1, [7, 5])\nloglog(h, err, '-*')\nloglog(h, err2, '-*')\nloglog(h, d_err, 'r-', label=r'$\\frac{h}{2}\\vert f^{\\prime\\prime}(x) \\vert $')\nloglog(h, d2_err, label=r'$\\frac{h^2}{6}\\vert f^{\\prime\\prime\\prime}(x) \\vert $')\nxlabel('h', fontsize=20)\nylabel('absolute error', fontsize=20)\nylim(1e-15, 1)\nlegend(fontsize=24);", "_____no_output_____" ] ], [ [ "The centered difference formula is more accurate for (roughly) $h>10^{-8}$. After the cancelation error takes over, the two errors are roughly comparable.", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
d01f172ad5f8f184c32d274bc7b3ea08fba35d55
128,905
ipynb
Jupyter Notebook
examples/2-profiling-vision.ipynb
raymon-ai/raymon
e1b0370de1f1d55c06b3c78fd820b1c1fe65db68
[ "MIT" ]
21
2021-06-14T08:37:22.000Z
2022-03-08T05:41:54.000Z
examples/2-profiling-vision.ipynb
raymon-ai/raymon
e1b0370de1f1d55c06b3c78fd820b1c1fe65db68
[ "MIT" ]
57
2021-01-30T08:45:13.000Z
2022-02-21T16:15:00.000Z
examples/2-profiling-vision.ipynb
raymon-ai/raymon
e1b0370de1f1d55c06b3c78fd820b1c1fe65db68
[ "MIT" ]
1
2021-06-18T09:53:58.000Z
2021-06-18T09:53:58.000Z
429.683333
83,666
0.938676
[ [ [ "# Building and using data schemas for computer vision\nThis tutorial illustrates how to use raymon profiling to guard image quality in your production system. The image data is taken from [Kaggle](https://www.kaggle.com/ravirajsinh45/real-life-industrial-dataset-of-casting-product) and is courtesy of PILOT TECHNOCAST, Shapar, Rajkot. Commercial use of this data is not permitted, but we have received permission to use this data in our tutorials.\n\nNote that some outputs may not work when viewing on Github since they are shown in iframes. We recommend to clone this repo and execute the notebooks locally.", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\n\nfrom PIL import Image\nfrom pathlib import Path", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ] ], [ [ "First, let's load some data. In this tutorial, we'll take the example of quality inspection in manufacturing. The puprose of our system may be to determine whether a manufactured part passes the required quality checks. These checks may measure the roudness of the part, the smoothness of the edges, the smoothness of the part overall, etc... let's assume you have automated those checks with an ML based system.\n\nWhat we demonstrate here is how you can easily set up quality checks on the incoming data like whether the image is sharp enough and whether it is similar enough to the data the model was trained on. Doing checks like this may be important because people's actions, periodic maintenance and wear and tear may have an impact on what data exaclty is sent to your system. If your data changes, your system may keep running but will suffer from reduced performance, resulting in lower business value.", "_____no_output_____" ] ], [ [ "DATA_PATH = Path(\"../raymon/tests/sample_data/castinginspection/ok_front/\")\nLIM = 150\n\ndef load_data(dpath, lim):\n files = dpath.glob(\"*.jpeg\")\n images = []\n for n, fpath in enumerate(files):\n if n == lim:\n break\n img = Image.open(fpath)\n images.append(img)\n return images\n\n\nloaded_data = load_data(dpath=DATA_PATH, lim=LIM)\nloaded_data[0]", "_____no_output_____" ] ], [ [ "## Constructing and building a profile\nFor this tutorial, we'll construct a profile that checks the image sharpness and will calculate an outlier score on the image. This way, we hope to get alerting when something seems off with the input data.\n\nJust like in the case of structured data, we need to start by specifying a profile and its components. ", "_____no_output_____" ] ], [ [ "from raymon import ModelProfile, InputComponent\nfrom raymon.profiling.extractors.vision import Sharpness, DN2AnomalyScorer\n\n\nprofile = ModelProfile(\n name=\"casting-inspection\",\n version=\"0.0.1\",\n components=[\n InputComponent(name=\"sharpness\", extractor=Sharpness()),\n InputComponent(name=\"outlierscore\", extractor=DN2AnomalyScorer(k=16))\n ],\n)\n\nprofile.build(input=loaded_data)", "_____no_output_____" ], [ "## Inspect the schema", "_____no_output_____" ], [ "profile.view(poi=loaded_data[-1], mode=\"external\")", "_____no_output_____" ] ], [ [ "## Use the profile to check new data\nWe can save the schema to JSON, load it again (in your production system), and use it to validate incoming data.", "_____no_output_____" ] ], [ [ "profile.save(\".\")\nprofile = ModelProfile.load(\"[email protected]\")\n\ntags = profile.validate_input(loaded_data[-1])\ntags", "_____no_output_____" ] ], [ [ "As you can see, all the extracted feature values are returned. This is useful for when you want to track feature distributions on your monitoring backend (which is what happens on the Raymon.ai platform). Also note that these features are not necessarily the ones going into your ML model.\n\n## Corrupting inputs\n\nLet's see what happens when we blur an image. ", "_____no_output_____" ] ], [ [ "from PIL import ImageFilter\n\nimg_blur = loaded_data[-1].copy().filter(ImageFilter.GaussianBlur(radius=5))\nimg_blur", "_____no_output_____" ], [ "profile.validate_input(img_blur)", "_____no_output_____" ] ], [ [ "As can be seen, every feature extractor now gives rise to 2 tags: one being the feature and one being a schema error, indicating that the data has failed both sanity checks. Awesome.\n\nWe can visualize this datum while inspecting the profile.", "_____no_output_____" ] ], [ [ "profile.view(poi=img_blur, mode=\"external\")", "_____no_output_____" ] ], [ [ "As we can see, the calculated feature values are way outside the range that were seen during training. Having alerting set up for this is crucial to deliver reliable systems.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d01f2146651afa938d0677d2193e88eca37f5931
93,049
ipynb
Jupyter Notebook
clustering/k_means.ipynb
JVBravoo/Learning-Machine-Learning
1ee58c1c74661450132f2af6a26066980b5f9cf2
[ "MIT" ]
1
2020-08-05T20:51:02.000Z
2020-08-05T20:51:02.000Z
clustering/k_means.ipynb
JVBravoo/Learning-Machine-Learning
1ee58c1c74661450132f2af6a26066980b5f9cf2
[ "MIT" ]
1
2020-08-04T19:27:22.000Z
2020-08-04T19:27:22.000Z
clustering/k_means.ipynb
JVBravoo/Learning-Machine-Learning
1ee58c1c74661450132f2af6a26066980b5f9cf2
[ "MIT" ]
null
null
null
122.594203
22,344
0.834636
[ [ [ "pip install pandas", "Requirement already satisfied: pandas in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (1.0.3)\nRequirement already satisfied: numpy>=1.13.3 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from pandas) (1.18.3)\nRequirement already satisfied: python-dateutil>=2.6.1 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from pandas) (2.8.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from pandas) (2020.1)\nRequirement already satisfied: six>=1.5 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from python-dateutil>=2.6.1->pandas) (1.14.0)\nNote: you may need to restart the kernel to use updated packages.\n" ], [ "pip install numpy", "Requirement already satisfied: numpy in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (1.18.3)\nNote: you may need to restart the kernel to use updated packages.\n" ], [ "pip install sklearn", "Requirement already satisfied: sklearn in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (0.0)\nRequirement already satisfied: scikit-learn in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from sklearn) (0.22.2.post1)\nRequirement already satisfied: numpy>=1.11.0 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from scikit-learn->sklearn) (1.18.3)\nRequirement already satisfied: joblib>=0.11 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from scikit-learn->sklearn) (0.14.1)\nRequirement already satisfied: scipy>=0.17.0 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from scikit-learn->sklearn) (1.4.1)\nNote: you may need to restart the kernel to use updated packages.\n" ], [ "pip install matplotlib", "Requirement already satisfied: matplotlib in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (3.2.1)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from matplotlib) (1.2.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from matplotlib) (2.4.7)\nRequirement already satisfied: cycler>=0.10 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from matplotlib) (0.10.0)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from matplotlib) (2.8.1)\nRequirement already satisfied: numpy>=1.11 in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from matplotlib) (1.18.3)\nRequirement already satisfied: six in /usr/local/Cellar/jupyterlab/2.1.1/libexec/lib/python3.8/site-packages (from cycler>=0.10->matplotlib) (1.14.0)\nNote: you may need to restart the kernel to use updated packages.\n" ], [ "from sklearn import cluster\nfrom sklearn.cluster import KMeans\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt", "_____no_output_____" ], [ "df = pd.read_csv(\"sample_stocks.csv\")\ndf", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 648 entries, 0 to 647\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 returns 648 non-null int64 \n 1 dividendyield 648 non-null float64\ndtypes: float64(1), int64(1)\nmemory usage: 10.2 KB\n" ], [ "# x = df['returns']\n# idx = np.argsort(x)\n# dividen = df['dividendyield']\n\n# plt.figure(figsize = (20, 7))\n\n# Plotar a dispersão de Returns vs dividendyield\n\nplt.scatter(df[\"returns\"], df[\"dividendyield\"])\nplt.show()", "_____no_output_____" ], [ "# Normalizar os dados\n\nfrom sklearn.preprocessing import StandardScaler\n\nnormalize = StandardScaler()\n\nx = pd.DataFrame(normalize.fit_transform(df))", "_____no_output_____" ], [ "# Plotar a dispersão novamente\n\nplt.scatter(x[0], x[1])\nplt.show()", "_____no_output_____" ], [ "# Crie e treine o Kmeans\n\nfrom sklearn import cluster\n\nkmeans = cluster.KMeans(n_clusters = 2)\nkmeans = kmeans.fit(x)", "_____no_output_____" ], [ "# Plote a dispersão juntamente com o KMeans.cluster_centers_\n# Na primeira linha foi usado \"c\", pois é: color, sequence, or sequence of colors\n\nplt.scatter(x[0], x[1], c = kmeans.labels_, cmap = \"viridis_r\")\nplt.scatter(kmeans.cluster_centers_, kmeans.cluster_centers_, color = \"blue\")\nplt.show()", "_____no_output_____" ], [ "# Analisar K, usando o método Elbow\n\ninertia = []\n\nfor i in range(1,15):\n kmeans = KMeans(n_clusters = i)\n kmeans = kmeans.fit(x)\n inertia.append(kmeans.inertia_)\n print(kmeans.inertia_)\n\nplt.plot(range(1, 15), inertia, \"bx-\")\nplt.plot(range(1, 15), inertia, \"bx-\")\nplt.show()", "1296.0\n386.98068568789614\n77.62109287678899\n61.645431515125466\n54.05304317182545\n47.94481730115659\n41.82918560622205\n37.32535802966952\n33.67665162322588\n29.536386870133075\n27.226257686902716\n24.112937198786298\n20.844490825782454\n19.155912821002545\n" ] ], [ [ "# Clustering hierárquico", "_____no_output_____" ] ], [ [ "# imports necessários\n\nfrom sklearn.cluster import AgglomerativeClustering\nfrom scipy.cluster.hierarchy import dendrogram", "_____no_output_____" ], [ "# Implemente Clustering Hierárquico\n\nmodelo = AgglomerativeClustering(distance_threshold = 0, n_clusters = None, linkage = \"single\")\nmodelo.fit_predict(x)\n# clusters.children_", "_____no_output_____" ], [ "# Plotando o dendograma\n\ndef plot_dendrogram(modelo, **kwargs):\n \n counts = np.zeros(modelo.children_.shape[0])\n n_samples = len(modelo.labels_)\n \n for i, merge in enumerate(modelo.children_):\n current_count = 0\n for child_index in merge:\n if child_index < n_samples:\n current_count += 1\n else:\n current_count += counts[child_index - n_samples]\n counts[i] = current_count\n linkage_matrix = np.column_stack([modelo.children_, modelo.distances_, counts]).astype(float)\n dendrogram(linkage_matrix, **kwargs)\n\nplot_dendrogram(modelo, truncate_mode = 'level', p = 12)\nplt.show()", "_____no_output_____" ], [ "# DBSCAN\n# https://scikit-learn.org/stable/modules/generated/sklearn.cluster.dbscan.html?highlight=dbscan#sklearn.cluster.dbscan\n\nfrom sklearn.cluster import DBSCAN\n\ndbscan = DBSCAN(eps = .5, min_samples = 15).fit(x)\n\n# Não consegui desenvolver essa forma de clustering", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]