hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
list
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
list
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
list
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
list
cell_types
list
cell_type_groups
list
4af01c589ca79819194dfb1ace854437f66a443a
10,765
ipynb
Jupyter Notebook
MLP_model.ipynb
vedant130701/Programming-Language-Classifier
43e418e4d564ed8e22a3224f2faa004aeac0aa29
[ "MIT" ]
null
null
null
MLP_model.ipynb
vedant130701/Programming-Language-Classifier
43e418e4d564ed8e22a3224f2faa004aeac0aa29
[ "MIT" ]
10
2021-10-01T12:38:32.000Z
2021-10-03T21:02:57.000Z
MLP_model.ipynb
vedant130701/Programming-Language-Classifier
43e418e4d564ed8e22a3224f2faa004aeac0aa29
[ "MIT" ]
5
2021-09-30T19:55:47.000Z
2021-10-01T13:47:30.000Z
26.778607
98
0.399628
[ [ [ "!git clone https://github.com/onosyoono/Programming-Language-Classifier.git", "Cloning into 'Programming-Language-Classifier'...\nremote: Enumerating objects: 55, done.\u001b[K\nremote: Counting objects: 100% (55/55), done.\u001b[K\nremote: Compressing objects: 100% (54/54), done.\u001b[K\nremote: Total 55 (delta 23), reused 3 (delta 1), pack-reused 0\u001b[K\nUnpacking objects: 100% (55/55), done.\n" ], [ "!ls", "Programming-Language-Classifier sample_data\n" ] ], [ [ "## **Imports**", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.neural_network import MLPClassifier", "_____no_output_____" ] ], [ [ "### **Loading**", "_____no_output_____" ] ], [ [ "df = pd.read_csv(\"./Programming-Language-Classifier/dataset.csv\")\ndf.head()", "_____no_output_____" ], [ "df = df.values", "_____no_output_____" ], [ "X, Y = df.T[0], df.T[1]", "_____no_output_____" ] ], [ [ "## Vectorizing", "_____no_output_____" ] ], [ [ "vectorizer = CountVectorizer()\nX_vec = vectorizer.fit_transform(X)\nX_vec = X_vec.toarray()\nprint(X_vec.shape)", "(1933, 10916)\n" ], [ "print(\"Dic Size:\", len(vectorizer.get_feature_names()))", "Dic Size: 10916\n" ] ], [ [ "## Presenting A Random Forest Classifier:", "_____no_output_____" ] ], [ [ "MLPclf = MLPClassifier()\nMLPclf.fit(X_vec[:int(0.8*len(Y))], Y[:int(0.8*len(Y))])", "_____no_output_____" ] ], [ [ "## Measuring Performance:", "_____no_output_____" ], [ "### Training:", "_____no_output_____" ] ], [ [ "MLPclf.score(X_vec[:int(0.8*len(Y))], Y[:int(0.8*len(Y))])\n", "_____no_output_____" ] ], [ [ "### Validation:", "_____no_output_____" ] ], [ [ "MLPclf.score(X_vec[int(0.8*len(Y)):], Y[int(0.8*len(Y)):])", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4af029b9e4f3c1c4b9c44efa4bc190d77c6a0b28
213,090
ipynb
Jupyter Notebook
notebooks/Test Disk KDE.ipynb
iancze/TWA-3-orbit
e852f69b298d315aacc5801dacb42346e3a281c1
[ "MIT" ]
null
null
null
notebooks/Test Disk KDE.ipynb
iancze/TWA-3-orbit
e852f69b298d315aacc5801dacb42346e3a281c1
[ "MIT" ]
null
null
null
notebooks/Test Disk KDE.ipynb
iancze/TWA-3-orbit
e852f69b298d315aacc5801dacb42346e3a281c1
[ "MIT" ]
null
null
null
1,651.860465
105,328
0.962016
[ [ [ "cd ..", "/Users/ianczekala/Documents/TWA-3-orbit\n" ], [ "import src.data as d\nimport corner\nimport numpy as np", "_____no_output_____" ], [ "d.disk_samples", "_____no_output_____" ], [ "d.disk_samples[:,[1,2]] /= (np.pi/180)", "_____no_output_____" ], [ "corner.corner(d.disk_samples, labels=[\"MA\", \"incl\", \"Omega\"])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4af02b3ccdd9aa858fc9a58df3441c56069a4cb3
138,348
ipynb
Jupyter Notebook
algorithms/defi-borrowing-cost-prediction/notebooks/01_compound_data.ipynb
AlgoveraAI/creations
6aa1cfffb4a59b7ff9fd9573ed743195be5bcfdc
[ "MIT" ]
null
null
null
algorithms/defi-borrowing-cost-prediction/notebooks/01_compound_data.ipynb
AlgoveraAI/creations
6aa1cfffb4a59b7ff9fd9573ed743195be5bcfdc
[ "MIT" ]
null
null
null
algorithms/defi-borrowing-cost-prediction/notebooks/01_compound_data.ipynb
AlgoveraAI/creations
6aa1cfffb4a59b7ff9fd9573ed743195be5bcfdc
[ "MIT" ]
null
null
null
347.60804
24,868
0.936501
[ [ [ "import pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nimport _init_paths", "_____no_output_____" ], [ "data_dir = Path('data')\ndf = pd.read_csv(data_dir / 'Compound_-_Data_1.csv')", "_____no_output_____" ], [ "ys = pd.DataFrame(df, columns=['Token', 'Borrowing Rate'])\nys_eth = ys[ys['Token'] == 'ETH']\nys_dai = ys[ys['Token'] == 'DAI']\nys_usdc = ys[ys['Token'] == 'USDC']\nys_usdt = ys[ys['Token'] == 'USDT']", "_____no_output_____" ], [ "xs = pd.DataFrame(df, columns=['Token', 'Deposit Rate', 'Borrow Volume', 'Supply Volume'])\nxs_eth = xs[xs['Token'] == 'ETH']\nxs_dai = xs[xs['Token'] == 'DAI']\nxs_usdc = xs[xs['Token'] == 'USDC']\nxs_usdt = xs[xs['Token'] == 'USDT']", "_____no_output_____" ], [ "print(ys_dai)", " Token Borrowing Rate\n0 DAI 0.073195\n4 DAI 0.073101\n8 DAI 0.073061\n12 DAI 0.073436\n16 DAI 0.067829\n... ... ...\n66732 DAI 0.046638\n66737 DAI 0.046120\n66740 DAI 0.046639\n66744 DAI 0.046691\n66749 DAI 0.047191\n\n[16688 rows x 2 columns]\n" ], [ "plt.plot(ys_usdt['Borrowing Rate'])", "_____no_output_____" ], [ "plt.plot(xs_eth['Supply Volume'])", "_____no_output_____" ], [ "plt.plot(xs_eth['Deposit Rate'])", "_____no_output_____" ], [ "plt.plot(xs_eth['Borrow Volume'])", "_____no_output_____" ], [ "aave = pd.read_csv(data_dir / 'aave_v2_borrow.csv')", "_____no_output_____" ], [ "print(aave['symbol'])", "0 USDC\n1 DAI\n2 USDC\n3 USDT\n4 USDC\n ... \n100564 USDC\n100565 DAI\n100566 DAI\n100567 DAI\n100568 DAI\nName: symbol, Length: 100569, dtype: object\n" ], [ "ys = pd.DataFrame(aave, columns=['symbol', 'avg_variable_borrow_rate'])\nys_eth = ys[ys['symbol'] == 'WETH']\nys_dai = ys[ys['symbol'] == 'DAI']\nys_usdc = ys[ys['symbol'] == 'USDC']\nys_usdt = ys[ys['symbol'] == 'USDT']", "_____no_output_____" ], [ "xs = pd.DataFrame(aave, columns=['symbol', 'avg_variable_borrow_rate'])\nxs_eth = xs[xs['symbol'] == 'WETH']\nxs_dai = xs[xs['symbol'] == 'DAI']\nxs_usdc = xs[xs['symbol'] == 'USDC']\nxs_usdt = xs[xs['symbol'] == 'USDT']", "_____no_output_____" ], [ "print(ys_eth)", " symbol avg_variable_borrow_rate\n5 WETH 0.313114\n13 WETH 0.313457\n19 WETH 0.280901\n20 WETH 0.280447\n21 WETH 0.280634\n... ... ...\n100499 WETH NaN\n100554 WETH 0.332631\n100556 WETH 0.332833\n100561 WETH 1.933514\n100562 WETH 0.175774\n\n[9384 rows x 2 columns]\n" ], [ "plt.plot(ys_eth['avg_variable_borrow_rate'])", "_____no_output_____" ], [ "plt.plot(xs_eth['avg_variable_borrow_rate'])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af02d6a2636d6b5cad27b06e1022ae0e4bd878d
5,184
ipynb
Jupyter Notebook
courses/compilation/notebooks/dnn.ipynb
gouarin/MAP586
43794936e88bb42e25ae71fecfe785626f000be7
[ "BSD-3-Clause" ]
4
2022-01-28T15:55:49.000Z
2022-02-15T12:14:32.000Z
courses/compilation/notebooks/dnn.ipynb
gouarin/MAP586
43794936e88bb42e25ae71fecfe785626f000be7
[ "BSD-3-Clause" ]
null
null
null
courses/compilation/notebooks/dnn.ipynb
gouarin/MAP586
43794936e88bb42e25ae71fecfe785626f000be7
[ "BSD-3-Clause" ]
3
2021-12-27T08:57:07.000Z
2022-01-17T22:22:02.000Z
42.146341
297
0.620177
[ [ [ "# Deep Neural Network\n\nYou see a lot of people around you who are interested in deep neural networks and you think that it might be interesting to start thinking about creating a software that is as flexible as possible and allows novice users to test this kind of methods.\n\nYou have no previous knowledge and while searching a bit on the internet, you come across this project https://github.com/HyTruongSon/Neural-Network-MNIST-CPP. You say to yourself that this is a good starting point and decide to spend a bit more time on it.\n\nWe recall here the key elements found in deep neural networks. We will not go into the mathematical details as this is not the purpose of this course.\n\nA deep neurl network is composed of an input, an output and several hidden layers.\n\nA neuron is illustrated by the following figure\n\n![image](./figures/dnn1.png)\n\nThis figure comes from a CNRS course called fiddle (https://gricad-gitlab.univ-grenoble-alpes.fr/talks/fidle).\n\nWe can observe that a neuron is made of weights, a bias and an activation function. The activation function can be a sigmoid, reLU, tanh, ...\n\nA deep neural network is composed of several hidden layers with several neurons as illustrated in the following figure\n\n![image](./figures/dnn2.png)\n\nThis figure also comes from the CNRS course fiddle.", "_____no_output_____" ], [ "In the following, we will use these notations:\n\n- $w^l_{j,i}$ is the weight of the layer $l$ for the neuron $j$ and the input entry $i$.\n- $z^l_j$ is the aggregation: $\\sum_i x_{i}^l w_{j, i}^l + b_j^l$ where $x_{i}$ is the input.\n- $\\sigma$ is the activation function. \n- $a^l_j$ is the output of the neuron $j$ for the layer $l$.\n- $L$ is the index of the last layer.\n- $C(a^L, y)$ is the cost function where $a^L$ is the predict value and $y$ is the expected result.\n\nThe algorithm has three steps:\n\n- The forward propagation: for a given input, cross all the layers until the output and fill $z^l$ and $a^l$.\n- Change the weights and biases to minimize the cost function using a descent gradient. This is called backward propagation.\n- iterate until reaching the maximum number of iterations or a given tolerance.\n\nThe gradient descent can be written as\n\n$$\nw_{j, i}^l = w_{j, i}^l - \\mu \\frac{\\partial C}{\\partial w_{j, i}^l},\n$$\n\nwhere $\\mu$ is the learning rate.\n\nThe equations of the backward propagation are\n\n- $\\delta^L_j = \\frac{\\partial C}{\\partial a_j^L}\\sigma'(z_j^L)$\n- $\\delta^l_j = \\sum_i w^{l+1}_{i, j}\\delta^{l+1}_i \\sigma'(z_j^l)$\n- $\\frac{\\partial C}{\\partial b^l_j} = \\delta_j^l$\n- $\\frac{\\partial C}{\\partial w^l_{j, i}} = a^{l-1}_i \\delta_j^l$\n\nIn our case,\n\n$$\nC'(\\hat{y}, y) = \\hat{y} - y.\n$$\n\nWe need to set of datas: datas for training the neural network and datas for testing the final weights and biases.\n", "_____no_output_____" ], [ "- Read the code https://github.com/HyTruongSon/Neural-Network-MNIST-CPP carefully and try to recognize each element of the algorithm.\n\n- Think of a code organization and data structure that offer more flexibility and readability.\n\n- Duplicate `step_0` into `step_1` and add all the `CMakeLists.twt` to create a library of `dnn` source files and the executable of the main function\n\n- Duplicate `step_1` into `step_2` and implement the following functions\n - `forward_propagation`\n - `backward_propagation`\n - `evaluate`\n \n- How to proceed to have more flexibility in the choice of the activation function ?\n\n**Note**: for the moment, you have only seen the C++ functions. We can see that it is difficult to have a flexible implementation with only functions. The use of C++ classes will improve the implementation considerably and will allow to add several activation and cost functions more easily.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown" ] ]
4af03a1970bd84e3b657797701b5b2375e567f60
34,481
ipynb
Jupyter Notebook
HeroesOfPymoli/.ipynb_checkpoints/Heroes of Pymoli Data Analysis-3-checkpoint.ipynb
rulaothman/pandas-challenge
8a92700c5d613db2228db06f6ef11d8448d87988
[ "ADSL" ]
null
null
null
HeroesOfPymoli/.ipynb_checkpoints/Heroes of Pymoli Data Analysis-3-checkpoint.ipynb
rulaothman/pandas-challenge
8a92700c5d613db2228db06f6ef11d8448d87988
[ "ADSL" ]
null
null
null
HeroesOfPymoli/.ipynb_checkpoints/Heroes of Pymoli Data Analysis-3-checkpoint.ipynb
rulaothman/pandas-challenge
8a92700c5d613db2228db06f6ef11d8448d87988
[ "ADSL" ]
null
null
null
46.47035
277
0.542154
[ [ [ "Heroes of Pymoli Data Analysis", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ], [ "Pymoli=\"/Users/rulaothman/Desktop/pandas-challenge/04-Numpy-Pandas/Instructions/HeroesOfPymoli/purchase_data.json\"", "_____no_output_____" ], [ "currency= '${0:.2f}'", "_____no_output_____" ], [ "Pymoli_df=pd.read_json(Pymoli)\nPymoli_df.head()", "_____no_output_____" ], [ "#Player Count \nPlayer_count=Pymoli_df['SN'].value_counts().count()\nPlayer_count", "_____no_output_____" ], [ "#Purchasing Analysis \nunique = Pymoli_df['Item Name'].value_counts().count()\nunique\ncount = Pymoli_df['Price'].count()\naverage = Pymoli_df['Price'].mean()\ntotal = Pymoli_df['Price'].sum()\n\nPlayer_data = [{'Number of Unique Items':unique,\n 'Number of Purchases':count,\n 'Average Purchase Price':average,\n 'Total Revenue': total}]\nplayer_analysis = pd.DataFrame(Player_data).style.format({'Percentage': '{:.2%}'})\nplayer_analysis", "_____no_output_____" ], [ "#Gender Demographics \nGender_df = Pymoli_df.groupby(['Gender'])\nprint(Gender_df)", "<pandas.core.groupby.DataFrameGroupBy object at 0x114789d68>\n" ], [ "count = Pymoli_df.groupby(['Gender']).count()\ntotal = Pymoli_df['Gender'].count()\npercentage = count/total\ngender_data = {'Percentage': percentage['SN'],\n 'Total Players': count['SN']}\ngender_analysis = pd.DataFrame(gender_data).style.format({'Percentage': '{:.2%}'})\ngender_analysis", "_____no_output_____" ], [ "#Purchase Analysis by gender \ncount = Pymoli_df.groupby(['Gender']).count()\naverage = Pymoli_df.groupby(['Gender']).mean()\ntotal = Pymoli_df.groupby(['Gender']).sum()\n\ngenderpurchase_data= {'Purchase Count': count['Price'],\n 'Average Purchase Price': average['Price'],\n 'Total Purchase Value': total['Price']}\n\npurchase_analysis = pd.DataFrame(genderpurchase_data).style.format({'Average Purchase Price': currency, 'Total Purchase Value': currency})\npurchase_analysis", "_____no_output_____" ], [ "Pymoli_df['Age'].max()", "_____no_output_____" ], [ "Pymoli_df['Age'].min()", "_____no_output_____" ], [ "#4-year bins \nbins=([0, 10, 15, 20, 25, 30, 35, 40, 45])\ngroup_names= [\"<10\",\"10-14\",\"15-19\",\"20-24\",\"25-29\",\"30-34\",\"35-39\",\"40+\"]\n\ndf= Pymoli_df.groupby(pd.cut(Pymoli_df[\"Age\"], bins, labels = group_names))\ncount= Pymoli_df.groupby(pd.cut(Pymoli_df[\"Age\"], bins, labels = group_names)).count()\naverage= Pymoli_df.groupby(pd.cut(Pymoli_df[\"Age\"], bins, labels = group_names)).mean()\ntotal= Pymoli_df.groupby((pd.cut(Pymoli_df[\"Age\"], bins, labels = group_names))).sum()\n\nagedemo_data= {'Purchase Count': count['Price'],\n 'Average Purchase Price': average['Price'],\n 'Total Purchase Value': total['Price']}\npurchase_analysis = pd.DataFrame(agedemo_data).rename(index={'0-10':'<10','10-14':'10-14','15-19':'15-19','20-24':'20-24','25-29':'25-29','30-34':'30-34','35-39':'35-39','40+':'>40'}).style.format({'Average Purchase Price': currency, 'Total Purchase Value': currency})\npurchase_analysis", "_____no_output_____" ], [ "#Top 5 Spenders \ncount = Pymoli_df.groupby(['SN']).count()\naverage = Pymoli_df.groupby(['SN']).mean()\ntotal = Pymoli_df.groupby(['SN']).sum()\n\ntopspender_data= {'Purchase Count': count['Price'],\n 'Average Purchase Price': average['Price'],\n 'Total Purchase Value': total['Price']}\npurchase_analysis = pd.DataFrame(topspender_data).sort_values('Total Purchase Value', ascending=False).head(5).style.format({'Average Purchase Price': currency, 'Total Purchase Value': currency})\npurchase_analysis\n", "_____no_output_____" ], [ "#Most Popular Item\ncount = Pymoli_df.groupby(['Item ID','Item Name']).count()\naverage = Pymoli_df.groupby(['Item ID','Item Name']).mean()\ntotal = Pymoli_df.groupby(['Item ID','Item Name']).sum()\n\ntopitem_data= {'Purchase Count': count['Price'],\n 'Average Purchase Price': average['Price'],\n 'Total Purchase Value': total['Price']}\n\npurchase_analysis = pd.DataFrame(topitem_data).sort_values('Purchase Count', ascending=False).head(5).style.format({'Average Purchase Price': currency, 'Total Purchase Value': currency})\npurchase_analysis", "_____no_output_____" ], [ "#Most Profitable Item\npurchase_analysis = pd.DataFrame(topitem_data).sort_values('Total Purchase Value', ascending=False).head(5).style.format({'Average Purchase Price': currency, 'Total Purchase Value': currency})\npurchase_analysis", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af03e6b5e4c86d6b98e340ce0c66206e35ab6d6
3,017
ipynb
Jupyter Notebook
QueryParametersAPIcalls.ipynb
IEPEREZ/FastAPItutorial
cac10f4ddb60bb95aa5aa9a2871f019720f53d3d
[ "MIT" ]
null
null
null
QueryParametersAPIcalls.ipynb
IEPEREZ/FastAPItutorial
cac10f4ddb60bb95aa5aa9a2871f019720f53d3d
[ "MIT" ]
null
null
null
QueryParametersAPIcalls.ipynb
IEPEREZ/FastAPItutorial
cac10f4ddb60bb95aa5aa9a2871f019720f53d3d
[ "MIT" ]
null
null
null
29.009615
194
0.552867
[ [ [ "# Step 0: import requests and json\nimport requests\nimport json", "_____no_output_____" ], [ "# Step 1: see the json response from Step 2 of QueryParameters.ipynb \nresponse = requests.get('http://127.0.0.1:8001/items/?skip=0&limit=10') \nprint (json.dumps(response.json(), indent=2, sort_keys=True))\nprint(response)\nprint(response.url)", "[\n {\n \"item_name\": \"Foo\"\n },\n {\n \"item_name\": \"Bar\"\n },\n {\n \"item_name\": \"Baz\"\n }\n]\n<Response [200]>\nhttp://127.0.0.1:8001/items/?skip=0&limit=10\n" ], [ "# Section 2: see the json response from section 2 \n# Section 2.1 cases\n# a. foo, short=1\nresponse = requests.get('http://127.0.0.1:8001/items/foo?short=1') \nprint (json.dumps(response.json(), indent=2, sort_keys=True))\n# b. foo, short=True\nresponse = requests.get('http://127.0.0.1:8001/items/foo?short=True') \nprint (json.dumps(response.json(), indent=2, sort_keys=True))\n# c. foo, short=true\nresponse = requests.get('http://127.0.0.1:8001/items/foo?short=true') \nprint (json.dumps(response.json(), indent=2, sort_keys=True))\n# d. foo, short=on\nresponse = requests.get('http://127.0.0.1:8001/items/foo?short=on') \nprint (json.dumps(response.json(), indent=2, sort_keys=True))\n# e. foo, short=yes\nresponse = requests.get('http://127.0.0.1:8001/items/foo?short=yes') \nprint (json.dumps(response.json(), indent=2, sort_keys=True))", "{\n \"item_id\": \"foo\"\n}\n{\n \"item_id\": \"foo\"\n}\n{\n \"item_id\": \"foo\"\n}\n{\n \"item_id\": \"foo\"\n}\n{\n \"item_id\": \"foo\"\n}\n" ], [ "#", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4af04874ab404a0a6ba3b71a21c7c3b220190637
6,392
ipynb
Jupyter Notebook
data_loader.ipynb
sakhawathsumit/RSR-GAN
a42201ed908113e7227ca1eda8d3dc54f266d337
[ "Apache-2.0" ]
8
2018-06-04T13:38:35.000Z
2021-05-28T08:42:39.000Z
data_loader.ipynb
sakhawathsumit/RSR-GAN
a42201ed908113e7227ca1eda8d3dc54f266d337
[ "Apache-2.0" ]
null
null
null
data_loader.ipynb
sakhawathsumit/RSR-GAN
a42201ed908113e7227ca1eda8d3dc54f266d337
[ "Apache-2.0" ]
2
2019-01-15T02:12:22.000Z
2021-08-08T10:35:50.000Z
36.112994
99
0.502972
[ [ [ "from __future__ import print_function, division\n\nimport json\nimport numpy as np\nimport pandas as pd\n\nimport librosa\nimport soundfile as sf\n\nimport torch\nfrom torch.utils.data import Dataset\n\nfrom keras.preprocessing.sequence import pad_sequences\n# Ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "class SpeechDataset(Dataset):\n \"\"\"Speech dataset.\"\"\"\n\n def __init__(self, csv_file, labels_file, audio_conf, transform=None, normalize=True):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file contain audio and transcript path.\n labels_file (string): Path to the json file contain label dictionary.\n audio_conf (dict) : Audio config info.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.speech_frame = pd.read_csv(csv_file, header=None)\n with open(labels_file, 'r') as f:\n self.labels = json.loads(f.read())\n self.window = audio_conf['window']\n self.window_size = audio_conf['window_size']\n self.window_stride = audio_conf['window_stride']\n self.sampling_rate = audio_conf['sampling_rate']\n self.transform = transform\n self.normalize = normalize\n\n def __len__(self):\n return len(self.speech_frame)\n\n def __getitem__(self, idx):\n wav_file = self.speech_frame.iloc[idx, 0]\n transcript_file = self.speech_frame.iloc[idx, 1]\n try:\n signal, _ = sf.read(wav_file)\n signal /= 1 << 31\n signal = self.spectrogram(signal)\n\n with open(transcript_file, 'r') as f:\n transcript = f.read().strip()\n transcript_idx = []\n transcript_idx.append(self.labels['<sos>'])\n for char in list(transcript):\n if char in self.labels:\n transcript_idx.append(self.labels[char])\n transcript_idx.append(self.labels['<eos>'])\n sample = {'signal': signal, 'transcript': np.array(transcript_idx)}\n if self.transform:\n sample = self.transform(sample)\n\n return sample\n except:\n return wav_file\n \n def spectrogram(self, signal):\n n_fft = int(self.sampling_rate * self.window_size)\n win_length = n_fft\n hop_length = int(self.sampling_rate * self.window_stride)\n # STFT\n D = librosa.stft(signal, n_fft=n_fft, hop_length=hop_length,\n window=self.window, win_length=win_length)\n spect, phase = librosa.magphase(D)\n # S = log(S+1)\n spect = np.log1p(spect)\n spect = torch.FloatTensor(spect)\n if self.normalize:\n mean = spect.mean()\n std = spect.std()\n spect.add_(-mean)\n spect.div_(std)\n \n return spect", "_____no_output_____" ], [ "class Padding(object):\n \"\"\"Rescale the audio signal and transcript to a given size.\n\n Args:\n signal_size (int): Desired output size of signal.\n transcript_size (int): Desired output size of transcript.\n labels_file (string): Path to the json file contain label dictionary.\n \"\"\"\n\n def __init__(self, signal_size, transcript_size, labels_file):\n assert isinstance(signal_size, (int))\n assert isinstance(transcript_size, (int))\n self.signal_size = signal_size\n self.transcript_size = transcript_size\n with open(labels_file, 'r') as f:\n self.labels = json.loads(f.read())\n\n def __call__(self, sample):\n signal, transcript = sample['signal'], sample['transcript']\n signal /= 1 << 31\n signal = pad_sequences(signal, \n maxlen=self.signal_size, padding='post', \n truncating='post', value=0.0, dtype='float')\n transcript = pad_sequences(transcript.reshape(1, -1), \n maxlen=self.transcript_size, padding='post', \n truncating='post', value=self.labels['pad'], dtype='int')\n \n return {'signal': signal, 'transcript': transcript}", "_____no_output_____" ], [ "class ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n signal, transcript = sample['signal'], sample['transcript']\n\n return {'signal': torch.from_numpy(signal),\n 'transcript': torch.from_numpy(transcript)}", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4af05d24619070e76fe4d3db9abbec7ac81fa95d
5,830
ipynb
Jupyter Notebook
mat3.ipynb
datascientist681/projects
9b74c7fcb6e61e7c5297d797af143a9e0690091d
[ "MIT" ]
null
null
null
mat3.ipynb
datascientist681/projects
9b74c7fcb6e61e7c5297d797af143a9e0690091d
[ "MIT" ]
null
null
null
mat3.ipynb
datascientist681/projects
9b74c7fcb6e61e7c5297d797af143a9e0690091d
[ "MIT" ]
null
null
null
25.238095
337
0.47084
[ [ [ "# Bar Charts and Analyzing Data from CSVs", "_____no_output_____" ] ], [ [ "import csv\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\nfrom matplotlib import pyplot as plt\n\nplt.style.use(\"fivethirtyeight\")\n\ndata = pd.read_csv('F:\\jupyter\\data.csv')\nids = data['Responder_id']\nlang_responses = data['LanguagesWorkedWith']\n\nlanguage_counter = Counter()\n\nfor response in lang_responses:\n language_counter.update(response.split(';'))\n\nlanguages = []\npopularity = []\n\nfor item in language_counter.most_common(15):\n languages.append(item[0])\n popularity.append(item[1])\n\nlanguages.reverse()\npopularity.reverse()\n\nplt.barh(languages, popularity)\n\nplt.title(\"Most Popular Languages\")\n# plt.ylabel(\"Programming Languages\")\nplt.xlabel(\"Number of People Who Use\")\n\nplt.tight_layout()\n\nplt.show()\n", "_____no_output_____" ], [ "#A Counter is a dict subclass for counting hashable objects.It is a collection where elements are \n#stored as dictionary keys and their counts are stored as dictionary values.\n\nfrom collections import Counter\nlist=Counter('shinwari')\nlist.update('khan')\nlist", "_____no_output_____" ], [ "word = \"mississippi\"\ncounter = {}\n\nfor letter in word:\n if letter not in counter:\n counter[letter] = 0\n counter[letter] += 1\ncounter", "_____no_output_____" ], [ "word='khaan'\ncounter={}\nfor i in word:\n if i not in counter:\n counter[i]=0\n counter[i]+=1\ncounter", "_____no_output_____" ], [ "from collections import Counter\nitem=['java','java','java','python','python','python','python','python','python']\nCounter(item)\nlist=[]\nlist1=[]\nplt.style.use(\"fivethirtyeight\")\nfor i in Counter(item).most_common(2):\n list.append(i[0])\n list1.append(i[1])\nplt.barh(list,list1)\nplt.legend()\nplt.grid()\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4af05ddfa3f8920051bd3317ce880f8cda72d4ba
94,581
ipynb
Jupyter Notebook
notebooks/Image Stitching.ipynb
hpearnshaw/cmost-analysis
a88cc3cd5381bbe775832ac559a99bd52ea466fd
[ "MIT" ]
null
null
null
notebooks/Image Stitching.ipynb
hpearnshaw/cmost-analysis
a88cc3cd5381bbe775832ac559a99bd52ea466fd
[ "MIT" ]
6
2021-02-04T02:40:26.000Z
2021-03-10T22:37:51.000Z
notebooks/Image Stitching.ipynb
hpearnshaw/cmost-analysis
a88cc3cd5381bbe775832ac559a99bd52ea466fd
[ "MIT" ]
1
2021-01-06T17:36:47.000Z
2021-01-06T17:36:47.000Z
685.369565
91,564
0.956207
[ [ [ "# Before running, make sure you've run pip install opencv-python, pip install imutils\n\n# Import OpenCV etc.\nimport os\nimport cv2\nimport imutils\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimdir = '/Users/hannah/Dropbox/PhD/CMOST/OneDrive_1_6-16-2021'", "_____no_output_____" ], [ "# Create and set up Stitcher instance\nstitcher = cv2.Stitcher.create(mode=1) # Scan mode\n\n# Initialize images list\nprint(\"Loading images...\")\nimage_paths = os.listdir(imdir)\nimage_paths.sort()\n\nimages = []\nfor path in image_paths:\n if not path.startswith('.'):\n image = cv2.imread(imdir+'/'+path)\n images.append(image)\n \nprint(\"Done: {} images loaded\".format(len(images)))", "Loading images...\nDone: 63 images loaded\n" ], [ "# Now stitch images\nprint(\"Stitching images...\")\nstatus, stitched = stitcher.stitch(images[0:10])\n\nif status == 0:\n print(\"Done\")\nelse:\n print(\"Image stitching failed ({})\".format(status))\n \n# Convert colors from BGR to RGB\nstitched = cv2.cvtColor(stitched, cv2.COLOR_BGR2RGB)", "Stitching images...\nDone\n" ], [ "# Display stitched image\nplt.figure()\nplt.imshow(stitched)\nplt.show()\n\n# Successfully manages to stitch image30 and image31 due to large amount of overlap but doesn't manage the others", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4af07cc58fab4e4ff23b67bf0b6fe0c3088047ac
12,917
ipynb
Jupyter Notebook
Course-1-Analyze Datasets and Train ML Models using AutoML/Week-3/SageMakerAutopilotDataExplorationNotebook.ipynb
BhargavTumu/coursera-practical-data-science-specialization
bb9dba48320fa93138cf245817413227305300a9
[ "MIT" ]
null
null
null
Course-1-Analyze Datasets and Train ML Models using AutoML/Week-3/SageMakerAutopilotDataExplorationNotebook.ipynb
BhargavTumu/coursera-practical-data-science-specialization
bb9dba48320fa93138cf245817413227305300a9
[ "MIT" ]
null
null
null
Course-1-Analyze Datasets and Train ML Models using AutoML/Week-3/SageMakerAutopilotDataExplorationNotebook.ipynb
BhargavTumu/coursera-practical-data-science-specialization
bb9dba48320fa93138cf245817413227305300a9
[ "MIT" ]
null
null
null
37.769006
191
0.542154
[ [ [ "# Amazon SageMaker Autopilot Data Exploration\n\nThis report provides insights about the dataset you provided as input to the AutoML job.\nIt was automatically generated by the AutoML training job: **automl-dm-1632956082**.\n\nAs part of the AutoML job, the input dataset was randomly split into two pieces, one for **training** and one for\n**validation**. The training dataset was randomly sampled, and metrics were computed for each of the columns.\nThis notebook provides these metrics so that you can:\n\n1. Understand how the job analyzed features to select the candidate pipelines.\n2. Modify and improve the generated AutoML pipelines using knowledge that you have about the dataset.\n\nWe read **`7110`** rows from the training dataset.\nThe dataset has **`2`** columns and the column named **`sentiment`** is used as the target column.\nThis is identified as a **`MulticlassClassification`** problem.\nHere are **3** examples of labels: `['-1', '1', '0']`.\n\n<div class=\"alert alert-info\"> 💡 <strong> Suggested Action Items</strong>\n\n- Look for sections like this for recommended actions that you can take.\n</div>\n\n\n---\n\n## Contents\n1. [Dataset Sample](#Dataset-Sample)\n1. [Column Analysis](#Column-Analysis)\n---\n", "_____no_output_____" ], [ "## Dataset Sample\nThe following table is a random sample of **10** rows from the training dataset.\n\n<div class=\"alert alert-info\"> 💡 <strong> Suggested Action Items</strong>\n\n- Verify the input headers correctly align with the columns of the dataset sample.\n If they are incorrect, update the header names of your input dataset in Amazon Simple Storage Service (Amazon S3).\n</div>\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>sentiment</th>\n <th>review_body</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>1</td>\n <td>This skirt is stunning but i really wish it wa...</td>\n </tr>\n <tr>\n <th>1</th>\n <td>0</td>\n <td>This is a very cute shirt with great details. ...</td>\n </tr>\n <tr>\n <th>2</th>\n <td>1</td>\n <td>I'm really looking forward to wearing this sko...</td>\n </tr>\n <tr>\n <th>3</th>\n <td>-1</td>\n <td>Ag jeans have been a main stay for me. they ar...</td>\n </tr>\n <tr>\n <th>4</th>\n <td>1</td>\n <td>The fabric is thin though. you better wash it...</td>\n </tr>\n <tr>\n <th>5</th>\n <td>-1</td>\n <td>I'm a rather small person--5'2\" about 100 lbs...</td>\n </tr>\n <tr>\n <th>6</th>\n <td>0</td>\n <td>This top fits like shown in the pictures. howe...</td>\n </tr>\n <tr>\n <th>7</th>\n <td>1</td>\n <td>Super cute and comfy perfect for fall and win...</td>\n </tr>\n <tr>\n <th>8</th>\n <td>0</td>\n <td>This dress has been one that i just adored onl...</td>\n </tr>\n <tr>\n <th>9</th>\n <td>0</td>\n <td>Loved the design and print of this blouse. ho...</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n", "_____no_output_____" ], [ "## Column Analysis\nThe AutoML job analyzed the **`2`** input columns to infer each data type and select\nthe feature processing pipelines for each training algorithm.\nFor more details on the specific AutoML pipeline candidates, see [Amazon SageMaker Autopilot Candidate Definition Notebook.ipynb](./SageMakerAutopilotCandidateDefinitionNotebook.ipynb).", "_____no_output_____" ], [ "### Percent of Missing Values\nWithin the data sample, the following columns contained missing values, such as: `nan`, white spaces, or empty fields.\n\nSageMaker Autopilot will attempt to fill in missing values using various techniques. For example,\nmissing values can be replaced with a new 'unknown' category for `Categorical` features\nand missing `Numerical` values can be replaced with the **mean** or **median** of the column.\n\nWe found **0 of the 2** of the columns contained missing values.\n\n<div class=\"alert alert-info\"> 💡 <strong> Suggested Action Items</strong>\n\n- Investigate the governance of the training dataset. Do you expect this many missing values?\n Are you able to fill in the missing values with real data?\n- Use domain knowledge to define an appropriate default value for the feature. Either:\n - Replace all missing values with the new default value in your dataset in Amazon S3.\n - Add a step to the feature pre-processing pipeline to fill missing values, for example with a\n [sklearn.impute.SimpleImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html).\n</div>\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>% of Missing Values</th>\n </tr>\n </thead>\n <tbody>\n </tbody>\n</table>\n</div>\n\n", "_____no_output_____" ], [ "### Count Statistics\nFor `String` features, it is important to count the number of unique values to determine whether to treat a feature as `Categorical` or `Text`\nand then processes the feature according to its type.\n\nFor example, SageMaker Autopilot counts the number of unique entries and the number of unique words.\nThe following string column would have **3** total entries, **2** unique entries, and **3** unique words.\n\n| | String Column |\n|-------|-------------------|\n| **0** | \"red blue\" |\n| **1** | \"red blue\" |\n| **2** | \"red blue yellow\" |\n\nIf the feature is `Categorical`, SageMaker Autopilot can look at the total number of unique entries and transform it using techniques such as one-hot encoding.\nIf the field contains a `Text` string, we look at the number of unique words, or the vocabulary size, in the string.\nWe can use the unique words to then compute text-based features, such as Term Frequency-Inverse Document Frequency (tf-idf).\n\n**Note:** If the number of unique values is too high, we risk data transformations expanding the dataset to too many features.\nIn that case, SageMaker Autopilot will attempt to reduce the dimensionality of the post-processed data,\nsuch as by capping the number vocabulary words for tf-idf, applying Principle Component Analysis (PCA), or other dimensionality reduction techniques.\n\nThe table below shows **2 of the 2** columns ranked by the number of unique entries.\n\n<div class=\"alert alert-info\"> 💡 <strong> Suggested Action Items</strong>\n\n- Verify the number of unique values of a feature is expected with respect to domain knowledge.\n If it differs, one explanation could be multiple encodings of a value.\n For example `US` and `U.S.` will count as two different words.\n You could correct the error at the data source or pre-process your dataset in your S3 bucket.\n- If the number of unique values seems too high for Categorical variables,\n investigate if using domain knowledge to group the feature\n to a new feature with a smaller set of possible values improves performance.\n</div>\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Number of Unique Entries</th>\n <th>Number of Unique Words (if Text)</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>sentiment</th>\n <td>3</td>\n <td>n/a</td>\n </tr>\n <tr>\n <th>review_body</th>\n <td>7108</td>\n <td>17986</td>\n </tr>\n </tbody>\n</table>\n</div>", "_____no_output_____" ], [ "### Descriptive Statistics\nFor each of the numerical input features, several descriptive statistics are computed from the data sample.\n\nSageMaker Autopilot may treat numerical features as `Categorical` if the number of unique entries is sufficiently low.\nFor `Numerical` features, we may apply numerical transformations such as normalization, log and quantile transforms,\nand binning to manage outlier values and difference in feature scales.\n\nWe found **1 of the 2** columns contained at least one numerical value.\nThe table below shows the **1** columns which have the largest percentage of numerical values.\n\n<div class=\"alert alert-info\"> 💡 <strong> Suggested Action Items</strong>\n\n- Investigate the origin of the data field. Are some values non-finite (e.g. infinity, nan)?\n Are they missing or is it an error in data input?\n- Missing and extreme values may indicate a bug in the data collection process.\n Verify the numerical descriptions align with expectations.\n For example, use domain knowledge to check that the range of values for a feature meets with expectations.\n</div>\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>% of Numerical Values</th>\n <th>Mean</th>\n <th>Median</th>\n <th>Min</th>\n <th>Max</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>sentiment</th>\n <td>100.0%</td>\n <td>0.0</td>\n <td>0.0</td>\n <td>-1.0</td>\n <td>1.0</td>\n </tr>\n </tbody>\n</table>\n</div>\n", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af082568a3ccd2dce1d8f4d3b843ce030a207fa
118,209
ipynb
Jupyter Notebook
Regression/CatBoost/CatBoostRegressor_RobustScaler.ipynb
shreepad-nade/ds-seed
93ddd3b73541f436b6832b94ca09f50872dfaf10
[ "Apache-2.0" ]
53
2021-08-28T07:41:49.000Z
2022-03-09T02:20:17.000Z
Regression/CatBoost/CatBoostRegressor_RobustScaler.ipynb
shreepad-nade/ds-seed
93ddd3b73541f436b6832b94ca09f50872dfaf10
[ "Apache-2.0" ]
142
2021-07-27T07:23:10.000Z
2021-08-25T14:57:24.000Z
Regression/CatBoost/CatBoostRegressor_RobustScaler.ipynb
shreepad-nade/ds-seed
93ddd3b73541f436b6832b94ca09f50872dfaf10
[ "Apache-2.0" ]
38
2021-07-27T04:54:08.000Z
2021-08-23T02:27:20.000Z
164.40751
80,328
0.893553
[ [ [ "# CatBoostRegressor with RobustScaler", "_____no_output_____" ], [ "This Code template is for regression analysis using CatBoostRegressor and Robust Scaler Feature Scaling technique. CatBoost is an algorithm for gradient boosting on decision trees.\n\n<img src=\"https://cdn.blobcity.com/assets/gpu_recommended.png\" height=\"25\" style=\"margin-bottom:-15px\" />", "_____no_output_____" ], [ "### Required Packages", "_____no_output_____" ] ], [ [ "!pip install catboost", "_____no_output_____" ], [ "import warnings \nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport seaborn as se \nfrom sklearn.preprocessing import LabelEncoder, RobustScaler\nfrom sklearn.model_selection import train_test_split \nfrom catboost import CatBoostRegressor\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error \n\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "### Initialization\n\nFilepath of CSV file", "_____no_output_____" ] ], [ [ "#filepath\nfile_path= ''", "_____no_output_____" ] ], [ [ "List of features which are required for model training .", "_____no_output_____" ] ], [ [ "#x_values\nfeatures=[]", "_____no_output_____" ] ], [ [ "Target feature for prediction.", "_____no_output_____" ] ], [ [ "#y_value\ntarget=''", "_____no_output_____" ] ], [ [ "### Data Fetching\n\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.", "_____no_output_____" ] ], [ [ "df=pd.read_csv(file_path)\ndf.head()", "_____no_output_____" ] ], [ [ "### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.", "_____no_output_____" ] ], [ [ "X = df[features]\nY = df[target]", "_____no_output_____" ] ], [ [ "### Data Preprocessing\n\nSince the majority of the machine learning models doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n", "_____no_output_____" ] ], [ [ "def NullClearner(df):\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\n df.fillna(df.mean(),inplace=True)\n return df\n elif(isinstance(df, pd.Series)):\n df.fillna(df.mode()[0],inplace=True)\n return df\n else:return df\ndef EncodeX(df):\n return pd.get_dummies(df)", "_____no_output_____" ], [ "x=X.columns.to_list()\nfor i in x:\n X[i]=NullClearner(X[i]) \nX=EncodeX(X)\nY=NullClearner(Y)\nX.head()", "_____no_output_____" ] ], [ [ "#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.", "_____no_output_____" ] ], [ [ "f,ax = plt.subplots(figsize=(18, 18))\nmatrix = np.triu(X.corr())\nse.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)\nplt.show()", "_____no_output_____" ] ], [ [ "### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.", "_____no_output_____" ] ], [ [ "x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123)", "_____no_output_____" ] ], [ [ "### Data Rescaling\n\nIt scales features using statistics that are robust to outliers. This method removes the median and scales the data in the range between 1st quartile and 3rd quartile. i.e., in between 25th quantile and 75th quantile range. This range is also called an Interquartile range.\n\n<a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html\">More about Robust Scaler</a>", "_____no_output_____" ] ], [ [ "robust = RobustScaler()\nx_train = robust.fit_transform(x_train)\nx_test = robust.transform(x_test)", "_____no_output_____" ] ], [ [ "### Model\n\nCatBoost is an algorithm for gradient boosting on decision trees. Developed by Yandex researchers and engineers, it is the successor of the MatrixNet algorithm that is widely used within the company for ranking tasks, forecasting and making recommendations\n\n#### Tuning parameters\n\n1. **learning_rate**:, float, default = it is defined automatically for Logloss, MultiClass & RMSE loss functions depending on the number of iterations if none of these parameters is set\n>The learning rate. Used for reducing the gradient step.\n\n2. **l2_leaf_reg**: float, default = 3.0\n>Coefficient at the L2 regularization term of the cost function. Any positive value is allowed.\n\n3. **bootstrap_type**: string, default = depends on the selected mode and processing unit\n>Bootstrap type. Defines the method for sampling the weights of objects.\n * Supported methods:\n * Bayesian\n * Bernoulli\n * MVS\n * Poisson (supported for GPU only)\n * No\n4. **subsample**: float, default = depends on the dataset size and the bootstrap type\n>Sample rate for bagging. This parameter can be used if one of the following bootstrap types is selected:\n * Poisson\n * Bernoulli\n * MVS\n\nFor more information refer: [API](https://catboost.ai/docs/concepts/python-reference_catboostregressor.html)", "_____no_output_____" ] ], [ [ "# Build Model here\nmodel = CatBoostRegressor(verbose=False)\nmodel.fit(x_train, y_train)", "_____no_output_____" ] ], [ [ "#### Model Accuracy\n\nscore() method return the mean accuracy on the given test data and labels.\n\nIn multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.", "_____no_output_____" ] ], [ [ "print(\"Accuracy score {:.2f} %\\n\".format(model.score(x_test,y_test)*100))", "Accuracy score 96.26 %\n\n" ] ], [ [ "> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. \n\n> **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. \n\n> **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ", "_____no_output_____" ] ], [ [ "y_pred=model.predict(x_test)\nprint(\"R2 Score: {:.2f} %\".format(r2_score(y_test,y_pred)*100))\nprint(\"Mean Absolute Error {:.2f}\".format(mean_absolute_error(y_test,y_pred)))\nprint(\"Mean Squared Error {:.2f}\".format(mean_squared_error(y_test,y_pred)))", "R2 Score: 96.26 %\nMean Absolute Error 2.37\nMean Squared Error 10.84\n" ] ], [ [ "#### Prediction Plot\n\nFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.\nFor the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(14,10))\nplt.plot(range(20),y_test[0:20], color = \"green\")\nplt.plot(range(20),model.predict(x_test[0:20]), color = \"red\")\nplt.legend([\"Actual\",\"prediction\"]) \nplt.title(\"Predicted vs True Value\")\nplt.xlabel(\"Record number\")\nplt.ylabel(target)\nplt.show()", "_____no_output_____" ] ], [ [ "## Creator: Abhishek Garg, Github: [Profile](https://github.com/abhishek-252)\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "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" ] ]
4af08c32a89bdd6386d0194cb888953b685815e0
4,370
ipynb
Jupyter Notebook
notebooks/2 - Base API Client Class.ipynb
spotify-song-suggester1/machine_learning
a5132200748fe5f160c38dc2809d1fa4a580ac05
[ "MIT" ]
null
null
null
notebooks/2 - Base API Client Class.ipynb
spotify-song-suggester1/machine_learning
a5132200748fe5f160c38dc2809d1fa4a580ac05
[ "MIT" ]
1
2020-11-21T20:02:25.000Z
2020-11-21T20:02:25.000Z
notebooks/2 - Base API Client Class.ipynb
spotify-song-suggester1/machine_learning
a5132200748fe5f160c38dc2809d1fa4a580ac05
[ "MIT" ]
null
null
null
26.484848
107
0.529748
[ [ [ "import requests\nimport base64\nimport datetime", "_____no_output_____" ], [ "client_id = '18bf732ea7ab485e91a45dfe7b75d5ec'\nclient_secret = '61d0f5271ab34e7aa519f1bebd81d3c9'", "_____no_output_____" ], [ "class SpotifyAPI(object):\n access_token = None\n access_token_expires = datetime.datetime.now()\n access_token_did_expire = True\n client_id = None\n client_secret = None\n token_url = 'https://accounts.spotify.com/api/token'\n\n def __init__(self, client_id, client_secret, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.client_id = client_id\n self.client_secret = client_secret\n\n def get_client_credentials(self):\n \"\"\"\n Returns a base 64 encoded string\n \"\"\"\n client_id = self.client_id\n client_secret = self.client_secret\n\n if client_secret == None or client_id == None:\n raise Exception(\"You must set client_id and client_secret\")\n\n client_creds = f\"{client_id}:{client_secret}\"\n client_creds_b64 = base64.b64encode(client_creds.encode())\n return client_creds_b64.decode()\n\n def get_token_headers(self):\n client_creds_b64 = self.get_client_credentials()\n return {\n 'Authorization': f'Basic {client_creds_b64}'\n }\n \n def get_token_data(self):\n return {\n 'grant_type': 'client_credentials'\n }\n\n def perform_auth(self):\n token_url = self.token_url\n token_data = self.get_token_data()\n token_headers = self.get_token_headers()\n r = requests.post(token_url, data=token_data, headers=token_headers)\n\n if r.status_code not in range(200, 299):\n return False\n data = r.json()\n now = datetime.datetime.now()\n access_token = data['access_token']\n expires_in = data['expires_in'] # seconds\n expires = now + datetime.timedelta(seconds=expires_in)\n self.access_token = access_token\n self.access_token_expires = expires\n self.access_token_did_expire = expires < now\n return True\n", "_____no_output_____" ], [ "spotify = SpotifyAPI(client_id, client_secret)", "_____no_output_____" ], [ "spotify.perform_auth()", "_____no_output_____" ], [ "spotify.access_token", "_____no_output_____" ], [ "# client.search", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4af08dcc4848b17702646a76a8740f0815581094
103,553
ipynb
Jupyter Notebook
DNN_NumPy.ipynb
chaudharyachint08/tipr-second-assignment
55a192e4b625a9c641f5be6d78b1c5ceba5b624a
[ "MIT" ]
null
null
null
DNN_NumPy.ipynb
chaudharyachint08/tipr-second-assignment
55a192e4b625a9c641f5be6d78b1c5ceba5b624a
[ "MIT" ]
null
null
null
DNN_NumPy.ipynb
chaudharyachint08/tipr-second-assignment
55a192e4b625a9c641f5be6d78b1c5ceba5b624a
[ "MIT" ]
1
2021-12-10T01:01:28.000Z
2021-12-10T01:01:28.000Z
34.209779
181
0.465028
[ [ [ "<pre><h1>E1-313 TIPR Assignment 2 Code base & Report</h1>\n<h2>Neural Network Implementation in Python3</h2>\n<h3><i> - Achint Chaudhary</i></h3>\n<h3>15879, M.Tech (CSA)</h3>\n<h5>Note:</h5> Please Scroll Down for Report section, or search \"Part 1\"\n<img src=\"Images/dnn_architecture.png\"/>", "_____no_output_____" ], [ "<pre>\n\n\n", "_____no_output_____" ], [ "<h3>Standard Library Imports</h3>", "_____no_output_____" ] ], [ [ "import sys, os, shutil, itertools as it\nfrom copy import deepcopy\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import ndimage\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom skimage import io\nfrom sklearn.metrics import f1_score, accuracy_score, classification_report\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping\n\nimport warnings\nwarnings.filterwarnings(\"error\")\n\ntry:\n res_stdout\nexcept:\n res_stdout = (sys.stdout if sys.stdout else sys.__stdout__)", "_____no_output_____" ], [ "verbose = bool( eval(input('Do you want Verbose??: 0/1 ')))", "_____no_output_____" ] ], [ [ "<h3>Changing File I/O & Matplotlib inlining if not verbose</h3>", "_____no_output_____" ] ], [ [ "if not verbose:\n sys.stdout = sys.__stdout__ = open('stdoutbuffer','a',buffering=1)\n mpl.use('Agg')\nelse:\n sys.stdout = sys.__stdout__ = res_stdout\n %matplotlib inline", "_____no_output_____" ] ], [ [ "<pre>\n\n\n", "_____no_output_____" ], [ "<h3>Activation Functions</h3>", "_____no_output_____" ] ], [ [ "class ActV:\n def sigmoid(x):\n return 1/(1+np.exp(-x))\n def relu(x):\n return np.maximum(0,x)\n def tanh(x):\n return 2*ActV.sigmoid(x)-1\n def swish(x):\n return x*ActV.sigmoid(x)\n def softmax(x):\n x = x-x.max(axis=1,keepdims=True)\n _ = np.exp(x)\n return _/np.sum(_,axis=1,keepdims=True)\n\nclass ActD:\n def sigmoid(x):\n _ = ActV.sigmoid( x )\n return _ * (1-_)\n def relu(x):\n '1 for x>=0'\n return (np.sign(x)>=0)\n def tanh(x):\n return 1-(ActV.tanh(x))**2\n def swish(x):\n 'y’ = y + σ(x) . (1 – y)'\n _1 = ActV.swish(x)\n _2 = ActV.sigmoid(x)\n return _1 + _2*(1-_1)\n def softmax(x):# Still in doubt, it should be a matrix\n _ = ActV.softmax( x )\n return _ * (1-_)", "_____no_output_____" ] ], [ [ "<h3>Adding \"Swish\" function to Keras</h3>", "_____no_output_____" ] ], [ [ "# Ref: https://stackoverflow.com/questions/43915482/how-do-you-create-a-custom-activation-function-with-keras\nfrom keras.layers import Activation\nfrom keras import backend as K\nfrom keras.utils.generic_utils import get_custom_objects\n\ndef swish2(x):\n return x*K.sigmoid(x)\n\nget_custom_objects().update({'swish': Activation(swish2)})\n\ndef addswish(model):\n model.add(Activation(swish2))", "_____no_output_____" ] ], [ [ "<h3>Cost Functions & Performance Metrics</h3>", "_____no_output_____" ] ], [ [ "class CostV:\n def cross_entropy(act, pred):\n pred = np.where(act!=1,pred+np.e,pred) # Handling perfect prediction\n pred = np.where(np.logical_and(act==1,pred==0),pred+10**-8,pred) # Handling imperfect prediction\n return -1*np.mean( act*np.log(pred) ,axis=0,keepdims=True)\n def MSE(act, pred):\n return np.mean( (pred-act)**2 ,axis=0,keepdims=True)\n \nclass CostD:\n def cross_entropy(act, pred):\n return pred - act\n def MSE(act, pred):\n return 2*(pred-act)\n\nclass Metrices:\n def accuracy(act, pred):\n return np.mean((act==pred).all(axis=1))\n\ndef one_hot(y):\n return 1*(y==y.max(axis=1,keepdims=True))\n\ndef cattooht(Y):\n Y = np.ravel(Y)\n _ = sorted(set(Y))\n tmp = np.zeros((Y.shape[0],len(_)),dtype='int32')\n for i in range(len(Y)):\n tmp[i][_.index(Y[i])] = 1\n return tmp,_", "_____no_output_____" ] ], [ [ "<h3>Xavier-He Initialization</h3>\n<img src=\"Images/XHE.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ] ], [ [ "def initWB(IP,OP,function='relu',He=True,mode='gaussian'):\n if He:\n # Xavier & He initialization\n _ = 1/(IP+OP)**0.5\n if function in ('sigmoid','softmax'):\n r, s = 6**0.5, 2**0.5\n elif function=='tanh':\n r, s = 4*6**0.5, 4*2**0.5\n else: # relu or swish function\n r, s = 12**0.5, 2\n r, s = r*_, s*_\n else:\n r, s = 1, 1\n # Generating matrices\n if mode=='uniform':\n return 2*r*np.random.random((IP,OP))-r , 2*r*np.random.random((1,OP))-r\n elif mode=='gaussian':\n return np.random.randn(IP,OP)*s , np.random.randn(1,OP)*s\n else:\n raise Exception('Code should be unreachable')", "_____no_output_____" ] ], [ [ "<h3>Data split function family</h3>", "_____no_output_____" ] ], [ [ "def RSplit(X,Y,K=10):\n 'Random Split Function'\n _ = list(range(X.shape[0]))\n index_set = []\n indxs = set(_)\n batch_size = round(X.shape[0]/K)\n np.random.shuffle(_)\n for k in range(0,X.shape[0],batch_size):\n test = set(_[k:k+batch_size])\n train = indxs - test\n index_set.append((list(train),list(test)))\n return index_set\n\ndef SSplit(X,Y,K=10,seed=True):\n 'Stratified Split Function'\n if seed:\n np.random.seed(42)\n Y = pd.DataFrame([tuple(y) for y in Y])\n classes = set(Y)\n c2i = {}\n for index,label in Y.iterrows():\n label = label[0]\n if label in c2i:\n c2i[label].add(index)\n else:\n c2i[label] = {index}\n \n # Each class -> list of indices\n for i in c2i:\n c2i[i] = list(c2i[i])\n np.random.shuffle(c2i[i])\n \n # Each class with its set of train, test split indices\n c2is = {}\n for cls in c2i:\n a = int(np.round(len(c2i[cls])/K))\n c2is[cls] = []\n for fold in range(K):\n test_indices = c2i[cls][a*fold:a*(fold+1)]\n train_indices = c2i[cls][0:a*fold] + c2i[cls][a*(fold+1):]\n c2is[cls].append((train_indices,test_indices))\n np.random.shuffle(c2is[cls])\n \n index_set = []\n for i in range(K):\n train,test = set(),set()\n for cls in c2is:\n _ = c2is[cls][i]\n train.update(set(_[0]))\n test.update (set(_[1]))\n index_set.append((list(train),list(test)))\n return index_set\n\ndef BSplit(X,Y,K=10):\n 'Biased Split Function'\n indx = sorted(np.arange(X.shape[0]),key = lambda i:list(Y[i]))\n indices = set(indx)\n index_set = []\n step = int(np.ceil(len(indx)/K))\n for i in range(0,len(indx),step):\n test = set(indx[i:i+step])\n train = indices - test\n index_set.append((list(train),list(test)))\n return index_set\n\ndef Split(X,Y,K=10,mode='R'):\n if mode=='S':\n return SSplit(X,Y,K)\n elif mode=='B':\n return BSplit(X,Y,K)\n else:\n return RSplit(X,Y,K)", "_____no_output_____" ] ], [ [ "<h3>Max-Pooling Code for Image Compression</h3>", "_____no_output_____" ] ], [ [ "# Ref: https://stackoverflow.com/questions/42463172/how-to-perform-max-mean-pooling-on-a-2d-array-using-numpy\ndef asStride(arr,sub_shape,stride):\n '''Get a strided sub-matrices view of an ndarray.\n See also skimage.util.shape.view_as_windows()\n '''\n s0,s1 = arr.strides[:2]\n m1,n1 = arr.shape[:2]\n m2,n2 = sub_shape\n view_shape = (1+(m1-m2)//stride[0],1+(n1-n2)//stride[1],m2,n2)+arr.shape[2:]\n strides = (stride[0]*s0,stride[1]*s1,s0,s1)+arr.strides[2:]\n subs = np.lib.stride_tricks.as_strided(arr,view_shape,strides=strides)\n return subs\n\ndef poolingOverlap(mat,ksize,stride=None,method='max',pad=False):\n '''Overlapping pooling on 2D or 3D data.\n\n <mat>: ndarray, input array to pool.\n <ksize>: tuple of 2, kernel size in (ky, kx).\n <stride>: tuple of 2 or None, stride of pooling window.\n If None, same as <ksize> (non-overlapping pooling).\n <method>: str, 'max for max-pooling,\n 'mean' for mean-pooling.\n <pad>: bool, pad <mat> or not. If no pad, output has size\n (n-f)//s+1, n being <mat> size, f being kernel size, s stride.\n if pad, output has size ceil(n/s).\n\n Return <result>: pooled matrix.\n '''\n m, n = mat.shape[:2]\n ky,kx = ksize\n if stride is None:\n stride = (ky,kx)\n sy,sx = stride\n\n _ceil = lambda x,y: int(np.ceil(x/float(y)))\n\n if pad:\n ny = _ceil(m,sy)\n nx = _ceil(n,sx)\n size = ((ny-1)*sy+ky, (nx-1)*sx+kx) + mat.shape[2:]\n mat_pad = np.full(size,np.nan)\n mat_pad[:m,:n,...]=mat\n else:\n mat_pad=mat[:(m-ky)//sy*sy+ky, :(n-kx)//sx*sx+kx, ...]\n\n view=asStride(mat_pad,ksize,stride)\n\n if method=='max':\n result=np.nanmax(view,axis=(2,3))\n else:\n result=np.nanmean(view,axis=(2,3))\n\n return result", "_____no_output_____" ] ], [ [ "<h3>Global Dataset store & Dummy set generation</h3>", "_____no_output_____" ] ], [ [ "try:\n datasets\nexcept:\n datasets = {}\n\nname = 'Dummy'\nL = 1000\n_1,_2 = list(np.random.random((L,2))), list(np.random.random((L,2)))\nX1,X2 = [],[]\nY1,Y2 = [],[]\nrad = 0.8\nfor i in range(L):\n a,b = _1[i][0],_1[i][1]\n if a**2+b**2<rad**2:\n Y1.append([1,0])\n X1.append(_1[i])\n elif a**2+b**2>=rad**2:\n Y1.append([0,1])\n X1.append(_1[i])\n a,b = _2[i][0],_2[i][1]\n if a**2+b**2<rad**2:\n Y2.append([1,0])\n X2.append(_2[i])\n elif a**2+b**2>=rad**2:\n Y2.append([0,1])\n X2.append(_2[i])\nX1 = np.array(X1)\nX2 = np.array(X2)\nY1 = np.array(Y1)\nY2 = np.array(Y2)\ndatasets[name] = (X1,Y1,['In','Out'])", "_____no_output_____" ], [ "m, n = 5,5\nX = np.array( list(it.product(np.arange(m),np.arange(n))) )\nY = np.array( cattooht( np.ravel( ((np.array([list(np.arange(n))]*m).T+np.arange(m)).T)%2 ) )[0] )\ndatasets['XOR'] = (X,Y,['E','O'])", "_____no_output_____" ] ], [ [ "<h3>Loading MNIST & Cat-Dog datasets</h3>", "_____no_output_____" ] ], [ [ "path = 'data'\nres_path = os.getcwd()\n\nos.chdir(path)\nfor fldr in os.listdir():\n if not fldr.startswith('.'):\n datasets[fldr] = ([],[])\n os.chdir(fldr)\n _ = sorted([x for x in os.listdir() if not x.startswith('.')])\n name_index = {x:_.index(x) for x in _}\n for category in _:\n label = [0]*len(_)\n label[name_index[category]] = 1\n os.chdir(category)\n for sample in os.listdir(): #[:2000]:\n if not fldr.startswith('.'):\n img_mat = io.imread(sample, as_gray=True)\n if fldr=='Cat-Dog': img_mat = poolingOverlap(img_mat,(4,4))\n img_mat = np.ravel(img_mat)\n datasets[fldr][0].append(img_mat)\n datasets[fldr][1].append(label)\n os.chdir('..')\n datasets[fldr] = tuple(map(np.array,datasets[fldr]))+(_,)\n os.chdir('..')\n\nos.chdir( res_path )\nfor i in datasets:\n datasets[i] = np.array(datasets[i][0],dtype='float64'), datasets[i][1], datasets[i][2]", "_____no_output_____" ] ], [ [ "<h3>Back-propagation Algorithm for Neural Network</h3>\n<img src=\"Images/BP.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h3>Neural Network Class</h3>", "_____no_output_____" ] ], [ [ "class NN:\n def __init__(self):\n self.Num, self.fun = [], []\n self.IP, self.OP, self.W, self.B, self.delta = {}, {}, {}, {}, {}\n self.beta1, self.beta2, self.eps = 0.9, 0.999, 10**-8\n\n def data_feed( self, M, L, targets):\n self.raw, self.labels, self.target_names = M, L, targets\n\n def data_validate( self, M=np.array([]), L=np.array([]) ):\n self.vraw, self.vlabels = M, L\n\n def add(self,N,f='relu'):\n self.Num.append(N); self.fun.append(f)\n\n def data_preprocess(self,mode='standard'):\n sp = np.nan_to_num\n try:\n mode = self.preprocess_mode\n except:\n self.preprocess_mode = mode\n if mode=='scale':\n try:\n self.mn, self.mx\n except:\n self.mn, self.mx = self.raw.min(axis=0), self.raw.max(axis=0)\n mx = np.where(self.mx==self.mn,self.mx+1,self.mx)\n self.data = sp((self.raw - self.mn)/(mx-self.mn))\n try: # If validation data is defined\n self.vdata = sp((self.vraw - self.mn)/(self.mx-self.mn))\n except:\n self.vdata = self.data\n elif mode=='standard':\n try:\n self.mean, self.std\n except:\n self.mean, self.std = self.raw.mean(axis=0), self.raw.std(axis=0)\n std = np.where(self.std==0,1,self.std)\n self.data = sp((self.raw-self.mean)/std)\n try: # If validation data is defined\n self.vdata = sp((self.vraw-self.mean)/std)\n except:\n self.vdata = self.data\n else:\n raise Exception('Code should be unreachable')\n \n def initialize_layers(self,He=True,mode='gaussian'):\n for i in range(len(self.Num)):\n if i==0:\n self.W[i],self.B[i], = initWB(self.data.shape[1],self.Num[i],self.fun[i],He,mode)\n else:\n self.W[i],self.B[i], = initWB(self.Num[i-1],self.Num[i],self.fun[i],He,mode)\n \n def forward_prop(self,predict=False):\n self.IP[0] = self.fdata\n for i in range(len(self.Num)):\n wx_b = np.dot(self.IP[i],self.W[i])+self.B[i]\n if not predict:\n self.OP[i] = wx_b\n _ = eval('ActV.{0}(wx_b)'.format(self.fun[i]))\n self.IP[i+1] = _\n if predict:\n del self.IP[i]\n return self.IP[len(self.Num)]\n\n def back_prop(self,debug=False):\n for i in range(len(self.Num)-1,-1,-1):\n if debug: print('Layer',i)\n if i==(len(self.Num)-1):\n costD = eval('CostD.{0}(self.flabels,self.IP[len(self.Num)])'.format(self.cost))\n actvD = eval('ActD.{0}(self.OP[i])'.format(self.fun[i]))\n self.delta[i] = costD * actvD\n if debug: print('>>',self.IP[i].shape,costD.shape,actvD.shape,self.delta[i].shape)\n else:\n costD = np.dot(self.W[i+1],self.delta[i+1].T).T # ((6,2),(100,2).T).T => (100,6)\n actvD = eval('ActD.{0}(self.OP[i])'.format(self.fun[i])) #(100,6)\n self.delta[i] = costD * actvD\n if debug: print('>>',self.IP[i].shape,costD.shape,actvD.shape,self.delta[i].shape)\n uW = np.dot( self.IP[i].T , self.delta[i] ) / self.IP[i].shape[0]\n uB = np.mean( self.delta[i] ,axis=0, keepdims=True)\n if debug: print( self.W[i].shape , self.B[i].shape)\n if debug: print( uW.shape , uB.shape)\n self.W[i] -= self.learning_rate*uW\n self.B[i] -= self.learning_rate*uB\n if debug: input()\n\n def back_prop2(self,Iteration_Count=1,debug=False,amsgrad=False):\n if Iteration_Count==1:\n self.UW, self.UB, self.SW, self.SB = deepcopy(self.W), deepcopy(self.B), deepcopy(self.W), deepcopy(self.B)\n for i in self.UW:\n self.UW[i], self.UB[i], self.SW[i], self.SB[i] = 0*self.UW[i], 0*self.UB[i], 0*self.SW[i], 0*self.SB[i]\n for i in range(len(self.Num)-1,-1,-1):\n if i==(len(self.Num)-1):\n costD = eval('CostD.{0}(self.flabels,self.IP[len(self.Num)])'.format(self.cost))\n actvD = eval('ActD.{0}(self.OP[i])'.format(self.fun[i]))\n self.delta[i] = costD * actvD\n else:\n costD = np.dot(self.W[i+1],self.delta[i+1].T).T\n actvD = eval('ActD.{0}(self.OP[i])'.format(self.fun[i]))\n self.delta[i] = costD * actvD\n uW = np.dot( self.IP[i].T , self.delta[i] ) / self.IP[i].shape[0]\n uB = np.mean( self.delta[i] ,axis=0, keepdims=True)\n # Eqn 1\n self.UW[i] = self.beta1*self.UW[i] + (1-self.beta1)*uW\n self.UB[i] = self.beta1*self.UB[i] + (1-self.beta1)*uB\n # Eqn 2\n self.SW[i] = self.beta2*self.SW[i] + (1-self.beta2)*uW**2\n self.SB[i] = self.beta2*self.SB[i] + (1-self.beta2)*uB**2\n # Eqn 3\n UW = self.UW[i]/(1-self.beta1**Iteration_Count)\n UB = self.UB[i]/(1-self.beta1**Iteration_Count)\n # Eqn 4\n SW = self.SW[i]/(1-self.beta2**Iteration_Count)\n SB = self.SB[i]/(1-self.beta2**Iteration_Count)\n # Eqn 5\n self.W[i] -= self.learning_rate*UW/(SW**0.5+self.eps)\n self.B[i] -= self.learning_rate*UB/(SB**0.5+self.eps)\n if np.isnan(self.W[i]).any() or np.isnan(self.B[i]).any():\n raise Exception('NAN value arises')\n\n def back_prop3(self,Epoch_Count=1,debug=False):\n for i in range(len(self.Num)-1,-1,-1):\n if i==(len(self.Num)-1):\n costD = eval('CostD.{0}(self.flabels,self.IP[len(self.Num)])'.format(self.cost))\n actvD = eval('ActD.{0}(self.OP[i])'.format(self.fun[i]))\n self.delta[i] = costD * actvD\n else:\n costD = np.dot(self.W[i+1],self.delta[i+1].T).T\n actvD = eval('ActD.{0}(self.OP[i])'.format(self.fun[i]))\n self.delta[i] = costD * actvD\n uW = np.dot( self.IP[i].T , self.delta[i] ) / self.IP[i].shape[0]\n uB = np.mean( self.delta[i] ,axis=0, keepdims=True)\n # Eqn 1\n _W1 = (1-self.beta1)*uW/(1-self.beta1**Epoch_Count)\n _B1 = (1-self.beta1)*uB/(1-self.beta1**Epoch_Count)\n # Eqn 2\n _W2 = (1-self.beta2)*uW**2/(1-self.beta2**Epoch_Count)\n _B2 = (1-self.beta2)*uB**2/(1-self.beta2**Epoch_Count)\n # Eqn 3\n self.W[i] -= self.learning_rate*_W1/(_W2**0.5+self.eps)\n self.B[i] -= self.learning_rate*_B1/(_B2**0.5+self.eps)\n if np.isnan(self.W[i]).any() or np.isnan(self.B[i]).any():\n raise Exception('NAN value arises')\n\n def feed_adam(beta1, beta2, eps):\n self.beta1, self.beta2, self.eps = beta1, beta2, eps\n\n def plot_feed(self,feed=True):\n self.fdata,self.flabels = self.data, self.labels\n y_pred = self.forward_prop(predict=True)\n costV = eval('CostV.{0}(self.flabels,y_pred)'.format(self.cost))\n y_pred = one_hot(y_pred)\n mvalue = eval('Metrices.{0}(self.flabels,y_pred)'.format(self.metric))\n act2 = [ list(rw).index(1) for rw in self.flabels ]\n pred2 = [ list(rw).index(1) for rw in y_pred ]\n if feed:\n self.costs.append( np.mean(costV) )\n self.mvalues.append( mvalue )\n self.f1m.append( f1_score(act2,pred2,average='micro') )\n self.f1M.append( f1_score(act2,pred2,average='macro') )\n \n self.fdata,self.flabels = self.vdata, self.vlabels\n y_pred = one_hot( self.forward_prop(predict=True) )\n vmvalue = eval('Metrices.{0}(self.flabels,y_pred)'.format(self.metric))\n self.vmvalues.append( vmvalue )\n \n return act2, pred2\n\n\n def train(self,epochs=1000,batchsize=30,learning_rate=0.001,\\\n optimizer='adam',cost='cross_entropy',metric='accuracy',es=(True,0,True),amsgrad=False):\n \n self.cost, self.metric, self.learning_rate = cost, metric, learning_rate\n self.costs, self.mvalues, self.f1m, self.f1M, self.vmvalues = [], [], [], [], []\n if es[0]: prev_entropy = [np.inf]\n # Random value at starting NN\n self.plot_feed()\n f = open('continue_next_epoch','w')\n f.close()\n\n for T in range(epochs):\n if 'continue_next_epoch' not in os.listdir(): break\n init = datetime.now()\n print('Epoch {0:{1}} ['.format(T+1,int(np.log10(epochs+1))+1),end='')\n if es[0]: W,B = [deepcopy(self.W)],[deepcopy(self.B)] # Saving Weights for Early Stopping\n mb_indx, splits = 0, int(np.ceil(self.data.shape[0]/batchsize))\n self.index_set = Split(self.data, self.labels, splits ,'R')\n for ln in range(len(self.index_set)):\n train_indx, test_indx = self.index_set[ln]\n self.fdata,self.flabels = self.data[test_indx],self.labels[test_indx]\n self.forward_prop()\n if optimizer=='gd':\n self.back_prop()\n elif optimizer=='adam':\n self.back_prop2(T*len(self.index_set)+(ln+1))\n else:\n self.back_prop3(T+1)\n if(mb_indx>=(splits*0.04)):\n print('=',end='')\n mb_indx = 0\n mb_indx+=1\n # Early Stopping using Validation Set #CHECKPOINT\n if es[0]:\n if es[1]==-1:\n pass\n else:\n delta = 0 # Exploring with compromising observed value\n self.fdata,self.flabels = self.vdata,self.vlabels\n y_pred = self.forward_prop(predict=True)\n costV = eval('CostV.{0}(self.flabels,y_pred)'.format(self.cost))\n best_entropy, cur_entropy = min(prev_entropy), np.mean(costV)\n if ( cur_entropy - best_entropy) > delta :\n if len(prev_entropy)==(es[1]+1):\n if es[2]: # Restoring Best Weights\n bst_indx = len(prev_entropy)-prev_entropy[::-1].index(best_entropy) - 1\n self.W,self.B = W[bst_indx], B[bst_indx]\n print(']\\n',best_entropy,'==>',cur_entropy)\n break\n else:\n prev_entropy.append( cur_entropy )\n W.append(deepcopy(self.W)); B.append(deepcopy(self.B))\n else:\n W,B = [deepcopy(self.W)],[deepcopy(self.B)]\n prev_entropy = [ cur_entropy ]\n # To plot results for entire datasets\n self.plot_feed()\n print('] Loss {0:.6e}, Accuracy {1:.2f}%, Accuracy-V {2:.2f}%, Time {3:}'.format(self.costs[-1],self.mvalues[-1]*100,self.vmvalues[-1]*100,datetime.now()-init))\n\n def krs(self,epochs=1000,batchsize=30,learning_rate=0.001,\\\n optimizer='adam',cost='cross_entropy',metric='accuracy',es=(True,0,True)):\n model = Sequential()\n addswish(model)\n model.add(Dense(self.Num[0], activation=self.fun[0], input_dim=self.data.shape[1]))\n for i in range(1,len(self.Num)-1):\n model.add(Dense(self.Num[i], activation=self.fun[i]))\n model.add(Dense(self.labels.shape[1], activation='softmax'))\n cb = [EarlyStopping(monitor='val_loss', patience=es[1], restore_best_weights=es[2])] if (es[0] and es[1]!=-1) else []\n model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=learning_rate,amsgrad=False), metrics=[metric])\n model.fit(self.data, self.labels, epochs=epochs, batch_size=batchsize,\\\n validation_data=(self.vdata, self.vlabels), callbacks=cb )\n y_pred = model.predict(self.vdata)\n y_pred = one_hot(y_pred)\n self.kmodel = model\n return classification_report(self.vlabels, y_pred, target_names=self.target_names, digits = 4 )\n\n def report(self,model=None):\n if model:\n y_true1, y_pred1 = self.labels, one_hot(model.predict(self.data))\n y_true2, y_pred2 = self.vlabels, one_hot(model.predict(self.vdata))\n else:\n self.fdata, self.flabels = self.data, self.labels\n y_true1, y_pred1 = self.labels, one_hot( self.forward_prop(predict=True) )\n self.fdata, self.flabels = self.vdata, self.vlabels\n y_true2, y_pred2 = self.vlabels, one_hot( self.forward_prop(predict=True) )\n \n r1 = classification_report(y_true1, y_pred1, target_names=self.target_names, digits = 4 )\n r2 = classification_report(y_true2, y_pred2, target_names=self.target_names, digits = 4 )\n return r1, r2\n\n def plot(self,prms={},learning_plot=False):\n mpl.rcParams['figure.dpi'] = 100\n plt.close()\n ax = plt.subplot(111)\n\n ls = [ self.mvalues[1:], self.f1M[1:], self.f1m[1:], self.vmvalues[1:] ]\n c1, c2 = min((min(l) for l in ls)), max((max(l) for l in ls))\n _ = (np.array(self.costs[1:])-min(self.costs[1:])) / (max(self.costs[1:])-min(self.costs[1:]))\n _ = list( (_*(c2-c1)+c1) )\n ls = [_]+ls\n for i in range(len(ls)):\n ls[i] = np.array(ls[i])\n s = np.exp(-5)\n if learning_plot:\n for i in range(len(ls)):\n ls[i] = -np.log((c2+s)-np.array(ls[i]))\n # Best Depiction of Learning process\n indx = list( np.linspace(-np.log((c2+s)-c1),-np.log((c2+s)-c2),10) )\n yticks = np.round(np.linspace(c1,c2,10),3)\n\n _1 = plt.plot(np.arange(1,len(ls[0])+1), ls[0],'-',label=self.cost)\n _2 = plt.plot(np.arange(1,len(ls[1])+1), ls[1],'*',label='Accuracy-T')\n _3 = plt.plot(np.arange(1,len(ls[2])+1), ls[2],'-.',label='F1-Macro')\n _4 = plt.plot(np.arange(1,len(ls[3])+1), ls[3],':',label='F1-Micro')\n _5 = plt.plot(np.arange(1,len(ls[4])+1), ls[4],'--',label='Accuracy-V')\n\n if learning_plot:\n plt.yticks(indx,yticks)\n\n p1 = '{0} Accuracy {1:.2f}%'.format(self.name,(self.mvalues[-1]*0.9+self.vmvalues[-1]*0.1)*100)\n prms = {x:prms[x] for x in prms if x in grid_params}\n p2 = ', '.join(str(x) for x in tuple(prms[x] for x in grid_params) ) # Grid Search Hyperparameters\n title = '\\n'.join((p1,p2))\n plt.title(title)\n plt.xlabel('Epochs')\n plt.legend(loc=0)\n plt.savefig(title+'.png',dpi=300,bbox_inches = 'tight')\n if verbose:\n plt.show()\n plt.close()\n \n def missed(self,diff_validation=True):\n try:\n shutil.rmtree('missed')\n except:\n pass\n finally:\n os.mkdir('missed')\n os.chdir('missed')\n try:\n ls = [(self.data,self.labels)]\n if diff_validation:\n ls.append( (self.vdata,self.vlabels) )\n for data,labels in ls:\n self.fdata, self.flabels = deepcopy(data), deepcopy(labels)\n pred = one_hot( self.forward_prop(predict=True) )\n act = self.flabels\n count = {}\n for i in range(len(self.fdata)):\n if not (act[i]==pred[i]).all():\n lbl_a = self.target_names[ np.sum( act[i]*np.arange(act[i].shape[0])) ]\n lbl_p = self.target_names[ np.sum(pred[i]*np.arange(pred[i].shape[0])) ]\n if (lbl_a,lbl_p) in count:\n count[(lbl_a,lbl_p)]+=1\n else:\n count[(lbl_a,lbl_p)]=1\n mat = deepcopy( self.fdata[i] )\n try:\n mat = mat*(self.mx-self.mn)+self.mn\n except:\n mat = mat*self.std+self.mean\n mat = mat.reshape(round(mat.shape[0]**0.5),round(mat.shape[0]**0.5))\n mpl.image.imsave('{1},{2},{0}.png'.format(count[(lbl_a,lbl_p)],lbl_a,lbl_p),mat)\n except:\n pass\n finally:\n os.chdir('..')\n \n def save_model(self,model_store='models'):\n if model_store not in os.listdir():\n os.mkdir(model_store)\n try:\n try:\n shutil.rmtree('{}/{}'.format(model_store,self.name))\n except:\n pass\n finally:\n os.mkdir('{}/{}'.format(model_store,self.name))\n os.chdir('{}/{}'.format(model_store,self.name))\n with open('config','w') as f:\n print(repr(self.Num) ,file=f)\n print(repr(self.fun) ,file=f)\n print(self.preprocess_mode,end = '',file=f) \n dct = {}\n with open('parameters','wb') as f:\n if self.preprocess_mode == 'standard':\n dct['mean'], dct['std'] = self.mean, self.std\n elif self.preprocess_mode == 'scale':\n dct['mn'], dct['mx'] = self.mn, self.mx\n else:\n raise Exception('Code should be unreachable')\n for i in self.W:\n dct['W{}'.format(i)] = self.W[i]\n dct['B{}'.format(i)] = self.B[i]\n np.savez(f,**dct)\n except Exception as exc:\n pass\n finally:\n os.chdir('../..')\n \n def load_model(self,model_store = 'models'):\n if model_store not in os.listdir():\n raise Exception(\"{} directory does not Exist\".format(model_store))\n try:\n os.chdir('{}/{}'.format(model_store,self.name))\n with open('config') as f:\n self.Num = eval(f.readline().strip())\n self.fun = eval(f.readline().strip())\n self.preprocess_mode = f.readline().strip()\n with open('parameters','rb') as f:\n npzfile = np.load(f)\n if self.preprocess_mode == 'standard':\n self.mean, self.std = npzfile['mean'], npzfile['std']\n elif self.preprocess_mode == 'scale':\n self.mn, self.mx = npzfile['mn'], npzfile['mx']\n else:\n raise Exception('Code should be unreachable')\n for i in range(len(self.Num)):\n self.W[i] = npzfile['W{}'.format(i)]\n self.B[i] = npzfile['B{}'.format(i)]\n except Exception as exc:\n pass\n finally:\n os.chdir('../..')\n ", "_____no_output_____" ] ], [ [ "<h3>Dataset Evaluation Wrapper</h3>", "_____no_output_____" ] ], [ [ "# Early Stopping Parameters\n# (Enable, ValidationPartition, Patience, Restore)\n\ndef evaldata(name,NumFun,prprc='standard',He=True,initmode='gaussian',\\\n epochs=1000,batchsize=30,lr=0.001,opt='adam',es=(True,False,0,True),krs=True):\n params = locals()\n if 'grid_params' not in globals():\n global grid_params\n grid_params = []\n\n print('Dataset under processing: ',name)\n X,Y,targets = datasets[name]\n net = NN()\n net.name = name\n if es[1]:\n index_set = SSplit(X,Y,10)\n np.random.shuffle(index_set)\n train_index, test_index = index_set[0]\n X1, Y1, X2, Y2 = X[train_index], Y[train_index], X[test_index], Y[test_index]\n else:\n X1, Y1, X2, Y2 = X, Y, X, Y\n net.data_feed(X1,Y1,targets) # Feeding Raw data\n net.data_validate(X2,Y2) # Used for Early Stopping\n net.data_preprocess(prprc)\n #Adding Hidden Layers\n for n,f in NumFun:\n net.add(n,f) \n # Output Layer & Cost function\n net.add(Y.shape[1],'softmax')\n net.initialize_layers(He,initmode)\n # Calling Training module, with optmizer & regularization parameters\n print('\\n\\t\\t','#'*16,'NumPy Implementation','#'*16,'\\n')\n net.train( epochs, batchsize, lr, opt, 'cross_entropy', 'accuracy', es[0:1]+es[2:] )\n r1, r2 = net.report()\n print('\\n\\t\\t\\t','-'*8,'Classification Report on Training data','-'*8,'\\n',r1)\n if es[1]: print('\\n\\t\\t','-'*8,'Classification Report on Validation data','-'*8,'\\n',r2)\n if krs:\n print('\\n\\t\\t','#'*16,'Keras Implementation','#'*16,'\\n')\n net.krs( epochs, batchsize, lr, opt, 'cross_entropy', 'accuracy', es[0:1]+es[2:] )\n r1, r2 = net.report(net.kmodel)\n print('\\n\\t\\t\\t','-'*8,'Classification Report on Training data','-'*8,'\\n',r1)\n if es[1]: print('\\n\\t\\t','-'*8,'Classification Report on Validation data','-'*8,'\\n',r2)\n\n net.plot(params) \n if krs:\n net.missed(es[1])\n net.save_model()\n net.load_model()\n return net.mvalues, net.costs, net.f1M, net.f1m", "_____no_output_____" ] ], [ [ "<h3>Grid Search for Hyper-parameter tuning</h3>\n<pre>\n<b>Sample Worst Case Sample given below, 9k+ executions</b><br>\n ########################################################\n ################ DON'T TRY THIS AT HOME ################\n ########################################################\n\n dct = {\n 'A datasets' : ['Dummy'],\n 'B units' : list(zip((392,784,1568),(64,128,128))),\n 'C functions' : it.product(('sigmoid','tanh','relu','swish'),('sigmoid','tanh','relu','swish')),\n 'D preproc' : ['scale','standard'],\n 'E He' : [True,False],\n 'F initmodes' : ['uniform','gaussian'],\n 'G epochs' : [10,20,40],\n 'H batchsize' : [128,256,512,1024],\n 'I learning_rate' : [0.001,0.0003,0.0001],\n 'J optimizer' : ['adam'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [True],\n }\n res = grid_search(dct)\n grid_plot(res)\n", "_____no_output_____" ] ], [ [ "def grid_search(dct):\n grid_values = { 'Accuracy':{}, 'Cost':{}, 'F1-Macro':{}, 'F1-Micro':{} }\n for prms in it.product(*(dct[x] for x in dct)):\n name = prms[0]\n prms = list(prms)\n prms[1:3] = [tuple(zip(prms[1],prms[2]))]\n prms = tuple(prms)\n print('STARTED ',prms)\n _ = eval( 'evaldata{0}'.format(tuple(prms)))\n print('COMPLETED',prms,end='\\n'*3)\n for i in range(len(_)):\n ls = sorted( grid_values.keys() )\n grid_values[ls[i]][prms] = _[i][-1]\n return grid_values\n\ndef grid_plot(res,dct):\n 'Under assumption that only one quantity will be varied at a time'\n tmp_grid_params = ['DataSet','Config','Preprocess','He','InitMode','Epochs','Batch_Size','Learning_Rate']\n \n def plot(metric,inner_dct,color):\n param_vals, y_values = {i:set() for i in range(len(tmp_grid_params))}, []\n for params in sorted(inner_dct):\n y_values.append( inner_dct[params] )\n for indx in range(len(tmp_grid_params)):\n param_vals[ indx ].add(params[indx])\n\n for indx in range(len(tmp_grid_params)):\n if len(param_vals[indx])>1:\n break\n else: # No graph can be shown with no changing values\n return\n\n if tmp_grid_params[indx]=='Config':\n sample = list(inner_dct.keys())[0][indx]\n inner_indx_dct = {(i,j):set() for i in range(len(sample)) for j in range(2)}\n for params in sorted(inner_dct):\n for i in range(len(sample)):\n for j in range(2):\n inner_indx_dct[(i,j)].add(params[indx][i][j])\n for inner_indx in inner_indx_dct:\n if len(inner_indx_dct[inner_indx])>1:\n break\n else:\n return\n i,j = inner_indx\n par_name = 'Layer {0}'.format(i+1)+' '+('Activation' if j else 'Units')\n x_values = sorted(inner_indx_dct[inner_indx])\n else:\n par_name = tmp_grid_params[indx]\n x_values = [params[indx] for params in sorted(inner_dct)]\n \n ind = np.arange(len(y_values))\n plt.xlabel(par_name)\n plt.ylabel(metric)\n plt.xticks( ind,x_values)\n try:\n styl = ('*' if set(map(int,x_values))=={0,1} else '-')\n except:\n styl = '*'\n plt.plot( ind,y_values,styl,color=color)\n title = ', '.join((metric,par_name))\n plt.title(title)\n plt.savefig(title+'.png',dpi=300,bbox_inches = 'tight')\n if verbose:\n plt.show()\n plt.close()\n\n for metric,color in zip(res,('g','r','b','y')):\n plt.close()\n plot(metric,res[metric],color)\n \ndef multi_grid_search(dct,plot=False):\n for i in dct:\n if i=='next':\n for dct2 in dct[i]:\n multi_grid_search({dct2:dct[i][dct2]},plot)\n else:\n _ = os.getcwd()\n try:\n shutil.rmtree(i)\n except:\n pass\n finally:\n os.mkdir(i)\n os.chdir(i)\n print('\\n'+'#'*16+' Grid Search Started in {0} '.format(i)+'#'*16)\n res = grid_search(dct[i])\n try:\n if plot: grid_plot(res,dct)\n except Exception as exc:\n print(exc)\n pass\n finally:\n os.chdir(_)", "_____no_output_____" ] ], [ [ "<pre>\n\n\n", "_____no_output_____" ], [ "<h1>Part 0 Pre-execution checks & Sample executions</h1>", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "sys.stdout = sys.__stdout__ = open('stdoutbuffer','a',buffering=1)", "_____no_output_____" ], [ "# os.chdir('..')\nos.getcwd()", "_____no_output_____" ], [ "grid_params = ['NumFun','prprc','He', 'initmode', 'batchsize','lr']", "_____no_output_____" ], [ "name,config = 'Dummy',[(4,'swish'),(3,'relu')]\n_ = evaldata(name,config,'standard',True,'gaussian',100,30,0.01,'adam',(True,True,-1,True),False)", "_____no_output_____" ], [ "name,config = 'XOR',[(10,'sigmoid'),(10,'sigmoid'),]\n_ = evaldata(name,config,'standard',True,'uniform',1000,1,0.001,'gd',(True,False,-1,True),False)", "_____no_output_____" ], [ "name,config = 'MNIST',[(1568,'swish'),(256,'swish'),]\n_1 = evaldata(name,config,'standard',True,'gaussian',10,2000,0.001,'myopt',(True,True,-1,True),False)", "_____no_output_____" ], [ "name,config = 'Cat-Dog',[(2048,'relu'),(256,'relu'),(64,'tanh')]\n_ = evaldata(name,config,'standard',True,'gaussian',100,200,0.0001,'myopt',(True,False,-1,True),False)", "_____no_output_____" ] ], [ [ "<pre>\n\n\n", "_____no_output_____" ], [ "<h1>Part 1 \"MNIST\" Evaluation and Experiments</h1>", "_____no_output_____" ] ], [ [ "grid_params = ['NumFun','prprc','He', 'initmode', 'batchsize','lr']", "_____no_output_____" ] ], [ [ "<h3>Task 1 - Varying Number of Layers</h3>", "_____no_output_____" ] ], [ [ "try:\n shutil.rmtree('Task1')\nexcept:\n pass\nfinally:\n os.mkdir('Task1')\n os.chdir('Task1')\n\ngrid_params = ['NumFun','prprc','He', 'initmode', 'batchsize','lr']\nname,config = 'MNIST',[(1568,'relu'),]\n_1 = evaldata(name,config,'standard',True,'gaussian',20,1000,0.001,'myopt',(True,True,5,True),False)\nname,config = 'MNIST',[(1568,'relu'),(256,'tanh')]\n_2 = evaldata(name,config,'standard',True,'gaussian',20,1000,0.001,'myopt',(True,True,5,True),False)\nname,config = 'MNIST',[(1568,'relu'),(256,'tanh'),(64,'tanh')]\n_3 = evaldata(name,config,'standard',True,'gaussian',20,1000,0.001,'myopt',(True,True,5,True),False)\n\nls = ['Accuracy','F1-Macro','F1-Micro']\ncolor = ['green','blue','red']\n\n\n_ = [_1,_2,_3]\nfor i in range(3):\n _[i] = list(_[i])\n _[i][:2] = _[i][:2][::-1]\n\nfor i in range(3): #Metric\n plt.close()\n plt.title(ls[i])\n plt.plot(list(range(1,3+1)),[_[j][i+1][-1] for j in range(3)],color=color[i])\n plt.savefig(ls[i]+'1')\n plt.close()\n \nos.chdir('..')", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part1/Task1/Accuracy1.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task1/F1Macro1.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task1/F1Micro1.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h3>Task 2 - Trying Various number of neurons in each layer</h3>", "_____no_output_____" ], [ "<h5>SubTask 1 - Changing Number of Units in 1<sup>st</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct1 = {\n '1 Layer' :\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((49,98,196,392,784,1176,1568,)),\n 'C functions' : it.product(('relu',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part1/Task2/1Layer/CostLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/1Layer/AccuracyLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/1Layer/F1MacroLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/1Layer/F1MicroLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 2 - Changing Number of Units in 2<sup>nd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct2 = {\n '2 Layer' :\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(16,32,64,128,256)),\n 'C functions' : it.product(('relu',),('tanh',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct2,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part1/Task2/2Layer/CostLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/2Layer/AccuracyLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/2Layer/F1MacroLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/2Layer/F1MicroLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 3 - Changing Number of Units in 3<sup>rd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct3 = {\n '3 Layer' :\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(256,),(16,32,64)),\n 'C functions' : it.product(('relu',),('tanh',),('tanh',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct3,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part1/Task2/3Layer/CostLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/3Layer/AccuracyLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/3Layer/F1MacroLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task2/3Layer/F1MicroLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h3>Task 3 - Trying Activation Functions on each layer</h3>", "_____no_output_____" ], [ "<h5>SubTask 1 - Changing Activation Functions in 1<sup>st</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct1 = {\n '1 Layer FUNCTIONS' :\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,)),\n 'C functions' : it.product(('sigmoid','relu','tanh','swish')),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part1/Task3/1LayerF/CostLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/1LayerF/AccuracyLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/1LayerF/F1MacroLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/1LayerF/F1MicroLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 2 - Changing Activation Functions in 2<sup>nd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct2 = {\n '2 Layer FUNCTIONS' :\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(256,)),\n 'C functions' : it.product(('relu',),('sigmoid','relu','tanh','swish')),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct2,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part1/Task3/2LayerF/CostLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/2LayerF/AccuracyLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/2LayerF/F1MacroLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/2LayerF/F1MicroLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 3 - Changing Activation Functions in 3<sup>rd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct3 = {\n '3 Layer FUNCTIONS' :\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(256,),(64,)),\n 'C functions' : it.product(('relu',),('tanh',),('relu','tanh','swish'),),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct3,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part1/Task3/3LayerF/CostLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/3LayerF/AccuracyLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/3LayerF/F1MacroLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part1/Task3/3LayerF/F1MicroLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h3>Task 4 Initialization & Preprocessing Techniques</h3>", "_____no_output_____" ], [ "<h5>SubTask 1 Impact of Xavier-He weight Initiliazation</h5>", "_____no_output_____" ] ], [ [ "dct2 = {\n 'Xavier-He':\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(256,)),\n 'C functions' : it.product(('relu',),('tanh',)),\n 'D preproc' : ['standard'],\n 'E He' : [False,True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct2,True)", "_____no_output_____" ] ], [ [ "<h5>Observed learning curve for Initialization technique as \"Default\" vs \"Xavier-He\"</h5>\n<br><img src=\"output_plots/Part1/Task4/XH/NHE.png\" height=\"300\" width=\"450\" align=\"left\">\n<img src=\"output_plots/Part1/Task4/XH/YHE.png\" height=\"300\" width=\"450\" align=\"right\">", "_____no_output_____" ], [ "<h5>SubTask 2 Finding Suitable Preprocesing & Initialization Distirbution</h5>", "_____no_output_____" ] ], [ [ "dct1 = {\n 'Init Gaussian':\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(256,)),\n 'C functions' : it.product(('relu',),('tanh',)),\n 'D preproc' : ['standard','scale'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n },\n\n 'Init Uniform':\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(256,)),\n 'C functions' : it.product(('relu',),('tanh',)),\n 'D preproc' : ['standard','scale'],\n 'E He' : [True],\n 'F initmodes' : ['uniform'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<h5>Observed learning curve for Preprocessing from \"Scaling\" vs \"Standardization\"</h5>\n<br><img src=\"output_plots/Part1/Task4/IG/GraphG2.png\" height=\"300\" width=\"450\" align=\"left\">\n<img src=\"output_plots/Part1/Task4/IG/GraphG.png\" height=\"250\" width=\"450\" align=\"right\">", "_____no_output_____" ], [ "<b>Note: </b>Standard preprocessing, being insensitive to out-liers performs better than Min-Max Scaling<br>\nHence, most our experiments shown use standardization, and might follow same for future ones", "_____no_output_____" ], [ "<h5>Observed learning curve for Initialization from \"Uniform\" vs \"Gaussian\"</h5>\n<br><img src=\"output_plots/Part1/Task4/IU/GraphU.png\" height=\"300\" width=\"450\" align=\"left\">\n<img src=\"output_plots/Part1/Task4/IG/GraphG.png\" height=\"250\" width=\"450\" align=\"right\">", "_____no_output_____" ], [ "<b>General obervation:</b>\nInitialization when done from Gaussian distribution inserts minimum information in a system<br>\nHence our most experiments will use it, you are free to experiment with other options", "_____no_output_____" ], [ "<h3>Task 5 Comparing Classification Reports of Numpy & Keras implementations</h3>", "_____no_output_____" ] ], [ [ "dct1 = {\n 'Keras':\n {\n 'A datasets' : ['MNIST'],\n 'B units' : it.product((1568,),(256,)),\n 'C functions' : it.product(('relu',),('tanh',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [20],\n 'H batchsize' : [1000],\n 'I learning_rate' : [0.001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,5,True)],\n 'L keras' : [True],\n },\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<pre>\n\n\t\t ################ NumPy Implementation ################ \n\n -------- Classification Report on Training data -------- \n precision recall f1-score support\n\n 0 0.9984 0.9997 0.9991 3719\n 1 1.0000 0.9983 0.9992 4212\n 2 0.9989 0.9995 0.9992 3746\n 3 0.9992 0.9977 0.9985 3925\n 4 0.9986 0.9989 0.9988 3644\n 5 0.9985 0.9985 0.9985 3438\n 6 0.9992 0.9987 0.9989 3715\n 7 0.9977 0.9997 0.9987 3970\n 8 0.9986 0.9997 0.9992 3665\n 9 0.9981 0.9968 0.9975 3766\n\n micro avg 0.9988 0.9988 0.9988 37800\n macro avg 0.9987 0.9988 0.9988 37800\nweighted avg 0.9988 0.9988 0.9988 37800\n samples avg 0.9988 0.9988 0.9988 37800\n\n\n -------- Classification Report on Validation data -------- \n precision recall f1-score support\n\n 0 0.9689 0.9806 0.9747 413\n 1 0.9871 0.9703 0.9786 472\n 2 0.9630 0.9652 0.9641 431\n 3 0.9240 0.9413 0.9326 426\n 4 0.9620 0.9463 0.9541 428\n 5 0.9660 0.9552 0.9606 357\n 6 0.9833 0.9787 0.9810 422\n 7 0.9578 0.9490 0.9534 431\n 8 0.9358 0.9523 0.9440 398\n 9 0.9343 0.9431 0.9387 422\n\n micro avg 0.9583 0.9583 0.9583 4200\n macro avg 0.9582 0.9582 0.9582 4200\nweighted avg 0.9585 0.9583 0.9584 4200\n\n\n\n\t\t ################ Keras Implementation ################ \n \n -------- Classification Report on Training data -------- \n precision recall f1-score support\n\n 0 0.9995 1.0000 0.9997 3719\n 1 0.9995 0.9991 0.9993 4212\n 2 0.9997 1.0000 0.9999 3746\n 3 0.9997 0.9987 0.9992 3925\n 4 0.9997 0.9997 0.9997 3644\n 5 0.9994 0.9997 0.9996 3438\n 6 0.9992 0.9997 0.9995 3715\n 7 0.9982 0.9995 0.9989 3970\n 8 0.9995 0.9992 0.9993 3665\n 9 0.9992 0.9981 0.9987 3766\n\n micro avg 0.9994 0.9994 0.9994 37800\n macro avg 0.9994 0.9994 0.9994 37800\nweighted avg 0.9994 0.9994 0.9994 37800\n samples avg 0.9994 0.9994 0.9994 37800\n\n\n\t\t -------- Classification Report on Validation data -------- \n precision recall f1-score support\n\n 0 0.9806 0.9782 0.9794 413\n 1 0.9850 0.9746 0.9798 472\n 2 0.9501 0.9722 0.9610 431\n 3 0.9307 0.9460 0.9383 426\n 4 0.9553 0.9486 0.9519 428\n 5 0.9624 0.9328 0.9474 357\n 6 0.9833 0.9739 0.9786 422\n 7 0.9471 0.9559 0.9515 431\n 8 0.9340 0.9598 0.9467 398\n 9 0.9444 0.9265 0.9354 422\n\n micro avg 0.9574 0.9574 0.9574 4200\n macro avg 0.9573 0.9569 0.9570 4200\nweighted avg 0.9576 0.9574 0.9574 4200\n samples avg 0.9574 0.9574 0.9574 4200", "_____no_output_____" ], [ "<pre>\n\n\n", "_____no_output_____" ], [ "<h1>Part 2 \"Cat-Dog\" Evaluation and Experiments</h1>", "_____no_output_____" ] ], [ [ "grid_params = ['NumFun','prprc','He', 'initmode', 'batchsize','lr']", "_____no_output_____" ] ], [ [ "<h3>Task 1 - Varying Number of Layers</h3>", "_____no_output_____" ] ], [ [ "try:\n shutil.rmtree('Task1')\nexcept:\n pass\nfinally:\n os.mkdir('Task1')\n os.chdir('Task1')\n\ngrid_params = ['NumFun','prprc','He', 'initmode', 'batchsize','lr']\nname,config = 'Cat-Dog',[(2048,'relu'),]\n_1 = evaldata(name,config,'standard',True,'gaussian',100,200,0.0001,'myopt',(True,True,-1,True),False)\nname,config = 'Cat-Dog',[(2048,'relu'),(256,'relu')]\n_2 = evaldata(name,config,'standard',True,'gaussian',100,200,0.0001,'myopt',(True,True,-1,True),False)\nname,config = 'Cat-Dog',[(2048,'relu'),(256,'relu'),(64,'tanh')]\n_3 = evaldata(name,config,'standard',True,'gaussian',100,200,0.0001,'myopt',(True,True,-1,True),False)\n\nls = ['Accuracy','F1-Macro','F1-Micro']\ncolor = ['green','blue','red']\n\n\n_ = [_1,_2,_3]\nfor i in range(3):\n _[i] = list(_[i])\n _[i][:2] = _[i][:2][::-1]\n\nfor i in range(3): #Metric\n plt.close()\n plt.title(ls[i])\n plt.plot(list(range(1,3+1)),[_[j][i+1][-1] for j in range(3)],color=color[i])\n plt.savefig(ls[i]+'1')\n plt.close()\n \nos.chdir('..')", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part2/Task1/Accuracy1.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task1/F1Macro1.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task1/F1Micro1.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h3>Task 2 - Trying Various number of neurons in each layer</h3>", "_____no_output_____" ], [ "<h5>SubTask 1 - Changing Number of Units in 1<sup>st</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct1 = {\n '1 Layer' :\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((512,1024,2048)),\n 'C functions' : it.product(('relu',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part2/Task2/1Layer/CostLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/1Layer/AccuracyLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/1Layer/F1MacroLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/1Layer/F1MicroLayer1Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 2 - Changing Number of Units in 2<sup>nd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct2 = {\n '2 Layer' :\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((1024,),(64,128,256)),\n 'C functions' : it.product(('relu',),('relu',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct2,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part2/Task2/2Layer/CostLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/2Layer/AccuracyLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/2Layer/F1MacroLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/2Layer/F1MicroLayer2Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 3 - Changing Number of Units in 3<sup>rd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct3 = {\n '3 Layer' :\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((1024,),(256,),(16,32,64)),\n 'C functions' : it.product(('relu',),('relu',),('tanh',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct3,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part2/Task2/3Layer/CostLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/3Layer/AccuracyLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/3Layer/F1MacroLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task2/3Layer/F1MicroLayer3Units.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h3>Task 3 - Trying Activation Functions on each layer</h3>", "_____no_output_____" ], [ "<h5>SubTask 1 - Changing Activation Functions in 1<sup>st</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct1 = {\n '1 Layer FUNCTIONS' :\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((2048,)),\n 'C functions' : it.product(('sigmoid','relu','tanh','swish')),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part2/Task3/1LayerF/CostLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/1LayerF/AccuracyLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/1LayerF/F1MacroLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/1LayerF/F1MicroLayer1Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 2 - Changing Activation Functions in 2<sup>nd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct2 = {\n '2 Layer FUNCTIONS' :\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((1024,),(256,)),\n 'C functions' : it.product(('relu',),('sigmoid','relu','tanh','swish')),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct2,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part2/Task3/2LayerF/CostLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/2LayerF/AccuracyLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/2LayerF/F1MacroLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/2LayerF/F1MicroLayer2Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 3 - Changing Activation Functions in 3<sup>rd</sup> Hidden Layer of Architecture</h5>", "_____no_output_____" ] ], [ [ "dct3 = {\n '3 Layer FUNCTIONS' :\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((1024,),(256,),(64,)),\n 'C functions' : it.product(('relu',),('relu',),('relu','tanh','swish'),),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct3,True)", "_____no_output_____" ] ], [ [ "<img src=\"output_plots/Part2/Task3/3LayerF/CostLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/3LayerF/AccuracyLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/3LayerF/F1MacroLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<img src=\"output_plots/Part2/Task3/3LayerF/F1MicroLayer3Activation.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<h3>Task 4 Initialization & Preprocessing Techniques</h3>", "_____no_output_____" ], [ "<h5>SubTask 1 Impact of Xavier-He weight Initiliazation</h5>", "_____no_output_____" ] ], [ [ "dct2 = {\n 'Xavier-He':\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((1024,),(256,)),\n 'C functions' : it.product(('relu',),('relu',)),\n 'D preproc' : ['standard'],\n 'E He' : [False,True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct2,True)", "_____no_output_____" ] ], [ [ "<h5>Observed learning curve for Initialization technique as \"Default\" vs \"Xavier-He\"</h5>\n<br><img src=\"output_plots/Part2/Task4/XH/NHE.png\" height=\"300\" width=\"450\" align=\"left\">\n<img src=\"output_plots/Part2/Task4/XH/YHE.png\" height=\"300\" width=\"450\" align=\"left\">", "_____no_output_____" ], [ "<h5>SubTask 2 Finding Suitable Preprocesing & Initialization Distirbution</h5>", "_____no_output_____" ] ], [ [ "dct1 = {\n 'Init Gaussian':\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((1024,),(256,)),\n 'C functions' : it.product(('relu',),('relu',)),\n 'D preproc' : ['standard','scale'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n },\n\n 'Init Uniform':\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((1024,),(256,)),\n 'C functions' : it.product(('relu',),('relu',)),\n 'D preproc' : ['standard','scale'],\n 'E He' : [True],\n 'F initmodes' : ['uniform'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [False],\n }\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<h5>Observed learning curve for Preprocessing from \"Scaling\" vs \"Standardization\"</h5>\n<br><img src=\"output_plots/Part2/Task4/IG/GraphG2.png\" height=\"300\" width=\"450\" align=\"left\">\n<img src=\"output_plots/Part2/Task4/IG/GraphG.png\" height=\"250\" width=\"450\" align=\"right\">", "_____no_output_____" ], [ "<b>Note: </b>Standard preprocessing, being insensitive to out-liers performs better than Min-Max Scaling<br>\nHence, most our experiments shown use standardization, and might follow same for future ones", "_____no_output_____" ], [ "<h5>Observed learning curve for Initialization from \"Uniform\" vs \"Gaussian\"</h5>\n<br><img src=\"output_plots/Part2/Task4/IU/GraphU.png\" height=\"300\" width=\"450\" align=\"left\">\n<img src=\"output_plots/Part2/Task4/IG/GraphG.png\" height=\"250\" width=\"450\" align=\"right\">", "_____no_output_____" ], [ "<b>General obervation:</b>\nInitialization when done from Gaussian distribution inserts minimum information in a system<br>\nHence our most experiments will use it, you are free to experiment with other options", "_____no_output_____" ], [ "<h3>Task 5 Comparing Classification Reports of Numpy & Keras implementations</h3>", "_____no_output_____" ] ], [ [ "dct1 = {\n 'Keras':\n {\n 'A datasets' : ['Cat-Dog'],\n 'B units' : it.product((2048,),(256,),(64,)),\n 'C functions' : it.product(('relu',),('relu',),('tanh',)),\n 'D preproc' : ['standard'],\n 'E He' : [True],\n 'F initmodes' : ['gaussian'],\n 'G epochs' : [100],\n 'H batchsize' : [200],\n 'I learning_rate' : [0.0001],\n 'J optimizer' : ['myopt'],\n 'K early_stopping' : [(True,True,-1,True)],\n 'L keras' : [True],\n },\n }\n\nmulti_grid_search(dct1,True)", "_____no_output_____" ] ], [ [ "<pre>\n\n\t\t ################ NumPy Implementation ################ \n\n -------- Classification Report on Training data -------- \n precision recall f1-score support\n\n cat 1.0000 1.0000 1.0000 11250\n dog 1.0000 1.0000 1.0000 11250\n\n micro avg 1.0000 1.0000 1.0000 22500\n macro avg 1.0000 1.0000 1.0000 22500\nweighted avg 1.0000 1.0000 1.0000 22500\n samples avg 1.0000 1.0000 1.0000 22500\n\n\n\t\t -------- Classification Report on Validation data -------- \n precision recall f1-score support\n\n cat 0.6341 0.6392 0.6367 1250\n dog 0.6363 0.6312 0.6337 1250\n\n micro avg 0.6352 0.6352 0.6352 2500\n macro avg 0.6352 0.6352 0.6352 2500\nweighted avg 0.6352 0.6352 0.6352 2500\n samples avg 0.6352 0.6352 0.6352 2500\n\n\n\n\t\t ################ Keras Implementation ################ \n \n -------- Classification Report on Training data -------- \n precision recall f1-score support\n\n cat 0.9932 0.9986 0.9959 11250\n dog 0.9986 0.9932 0.9959 11250\n\n micro avg 0.9959 0.9959 0.9959 22500\n macro avg 0.9959 0.9959 0.9959 22500\nweighted avg 0.9959 0.9959 0.9959 22500\n samples avg 0.9959 0.9959 0.9959 22500\n\n\n\t\t -------- Classification Report on Validation data -------- \n precision recall f1-score support\n\n cat 0.6193 0.7224 0.6669 1250\n dog 0.6670 0.5560 0.6065 1250\n\n micro avg 0.6392 0.6392 0.6392 2500\n macro avg 0.6432 0.6392 0.6367 2500\nweighted avg 0.6432 0.6392 0.6367 2500\n samples avg 0.6392 0.6392 0.6392 2500", "_____no_output_____" ], [ "<pre>\n\n\n", "_____no_output_____" ], [ "<h1>Part 3 Execution of Neural Nets on Datasets of Assignment 1</h1>", "_____no_output_____" ], [ "<h3>Loading Datasets & Preprocessing of Twitter data into bag-of-word</h3>", "_____no_output_____" ] ], [ [ "# 1. Dolphins\nX1 = pd.read_csv('/data2/dolphins/dolphins.csv',sep=' ',header=None)\nY1 = pd.read_csv('/data2/dolphins/dolphins_label.csv',sep=' ',header=None)\nX1, Y1 = np.array(X1), np.array(Y1)\nY1 = cattooht(Y1)\n\n# 2. Twitter(bag-of-Word)\nX2 = pd.read_csv('/data2/twitter/twitter.csv',header=None)\nY2 = pd.read_csv('/data2/twitter/twitter_label.csv',header=None)\n\n# Converting into bag-of-word\nall_words = set()\nlocal_ls = []\nfor indx,stmt in X2.iterrows():\n local = {}\n for word in stmt[0].strip().split():\n if word in local:\n local[word] += 1\n else:\n local[word] = 1\n \n local_ls.append(local)\n all_words.update(local)\n\nmat = [[(local[word] if word in local else 0) for word in all_words] for local in local_ls]\nX2 = pd.DataFrame(np.array(mat))\nX2, Y2 = np.array(X2), np.array(Y2)\nY2 = cattooht(Y2)\n\n# 3. PubMed\nX3 = pd.read_csv('/data2/pubmed/pubmed.csv',sep=' ',header=None)\nY3 = pd.read_csv('/data2/pubmed/pubmed_label.csv',sep=' ',header=None)\nX3, Y3 = np.array(X3), np.array(Y3)\nY3 = cattooht(Y3)\n\n\n# Assignment into Global Datastructure\ndatasets['Dolphins'] = X1,Y1[0],list(map(str,Y1[1]))\ndatasets['Twitter'] = X2,Y2[0],list(map(str,Y2[1]))\ndatasets['PubMed'] = X3,Y3[0],list(map(str,Y3[1]))", "_____no_output_____" ] ], [ [ "<h3> Evaluation on Dolphins datasets</h3>", "_____no_output_____" ] ], [ [ "# 1. Dolphins Execution\nname = 'Dolphins'\nipdim, opdim = datasets[name][0].shape[1], datasets[name][1].shape[1]\ns1 = ipdim*2\ns2 = int(round((s1*opdim)**0.5))\nname,config = name,[(s1,'relu'),(s2,'relu')]\nln = len(datasets[name][0])\n_ = evaldata(name,config,'standard',True,'gaussian',100,10,0.001,'myopt',(True,True,-1,True),False)", "_____no_output_____" ] ], [ [ "<pre>Previous Bayesian Classification Metrics\nAccuracy : 0.90833 F1-Micro : 0.90833 F1-Macro : 0.85333\n\nPrevious KNN Classification Metrices\nAccuracy 0.98333 F1-Micro : 0.98333 F1-Macro : 0.98222", "_____no_output_____" ], [ "<img src=\"output_plots/Part3/Dolphins.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<b>General obervation:</b>\nNeural Network is able to make precise prediction in class imbalanced dataset", "_____no_output_____" ], [ "<h3> Evaluation on Twitter datasets</h3>", "_____no_output_____" ] ], [ [ "name = 'Twitter'\nipdim, opdim = datasets[name][0].shape[1], datasets[name][1].shape[1]\ns1 = ipdim*2\ns2 = int(round((s1*opdim)**0.5))\nname,config = name,[(s1,'relu'),(s2,'relu')]\nln = len(datasets[name][0])\n_ = evaldata(name,config,'standard',True,'gaussian',10,300,0.0003,'myopt',(True,True,-1,True),False)", "_____no_output_____" ] ], [ [ "<pre>Previous Bayesian Classification Metrics\nAccuracy : 0.56010 F1-Micro : 0.56010 F1-Macro : 0.34854\n\nPrevious KNN Classification Metrices\nAccuracy 0.48414 F1-Micro : 0.48414 F1-Macro : 0.41388", "_____no_output_____" ], [ "<img src=\"output_plots/Part3/Twittr.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<b>General obervation:</b>\nNo improvement on validation data is observed during training<br>\nNetwork is just overfitting Training data, sequence modelling should be captured<br>\nWhich is not possible with ordinary Neural Network Architecture of this assignment", "_____no_output_____" ], [ "<h3> Evaluation on PubMed datasets</h3>", "_____no_output_____" ] ], [ [ "name = 'PubMed'\nipdim, opdim = datasets[name][0].shape[1], datasets[name][1].shape[1]\ns1 = ipdim*2\ns2 = int(round((s1*opdim)**0.5))\nname,config = name,[(s1,'relu'),(s2,'relu')]\nln = len(datasets[name][0])\n_ = evaldata(name,config,'standard',True,'gaussian',100,500,0.001,'myopt',(True,True,-1,True),False)", "_____no_output_____" ] ], [ [ "<pre>Previous Bayesian Classification Metrics\nAccuracy : 0.44144 F1-Micro : 0.44144 F1-Macro : 0.33277\n\nPrevious KNN Classification Metrices\nAccuracy 0.35412 F1-Micro : 0.35412 F1-Macro : 0.34554", "_____no_output_____" ], [ "<img src=\"output_plots/Part3/PubMed.png\" height=\"450\" width=\"600\" align=\"left\">", "_____no_output_____" ], [ "<b>General obervation:</b>\nThis dataset is again overfitted by Neural Network<br>\nMultinomial Naive Bayes' performed some better than Neural network", "_____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" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
4af08e7d418e4b32307804cabd78d4660638795f
5,115
ipynb
Jupyter Notebook
Tutorials/TypingAPL.ipynb
mbaas2/APLcourse
3acdbef4a1f7c06be049e8677b71ce8536815a72
[ "MIT" ]
null
null
null
Tutorials/TypingAPL.ipynb
mbaas2/APLcourse
3acdbef4a1f7c06be049e8677b71ce8536815a72
[ "MIT" ]
null
null
null
Tutorials/TypingAPL.ipynb
mbaas2/APLcourse
3acdbef4a1f7c06be049e8677b71ce8536815a72
[ "MIT" ]
null
null
null
47.361111
577
0.477419
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af0b83d20121ad71763b2fe7539b76073bd1803
13,102
ipynb
Jupyter Notebook
python/08.Condition,Loop,Function_03.ipynb
Seoheesu1/TIL
5e58e4d07c76c5319da486427857375a29ec0e50
[ "MIT" ]
null
null
null
python/08.Condition,Loop,Function_03.ipynb
Seoheesu1/TIL
5e58e4d07c76c5319da486427857375a29ec0e50
[ "MIT" ]
null
null
null
python/08.Condition,Loop,Function_03.ipynb
Seoheesu1/TIL
5e58e4d07c76c5319da486427857375a29ec0e50
[ "MIT" ]
null
null
null
20.4081
873
0.465654
[ [ [ "### 함수\n- 반복되는 코드를 묶음으로 효율적인 코드를 작성하도록 해주는 기능\n- 기본 함수\n- 파라미터와 아규먼트\n- 리턴\n- `*args`, `**kwargw`\n- docstring\n- scope\n- inner function\n- lambda function\n- Map, filter, Reduce\n- Decorlator", "_____no_output_____" ], [ "#### 1. 기본 함수\n- 선언과 호출", "_____no_output_____" ] ], [ [ "point=88\n\nif point >= 90:\n print(\"A\")\nelif point>= 80:\n print(\"B\")\nelse:\n print(\"C\")", "B\n" ], [ "# 함수 선언 (식별자 스네이크로)\ndef grade(point): \n if point >= 90:\n print(\"A\")\n elif point>= 80:\n print(\"B\")\n else:\n print(\"C\")", "_____no_output_____" ], [ "# 함수호출\ngrade(88)", "B\n" ], [ "grade(78)", "C\n" ] ], [ [ "### 2. 파라미터와 아규먼트\n- 파라미터: 함수를 선언할때 호출하는 부분에서 보내주는 데이터를 받는 변수\n- 아규먼트: 함수를 호출할때 함수에 보내주는 데이터 (함수를 사용할때 입력하는,,)", "_____no_output_____" ] ], [ [ "def plus(num1, num2): #파라미터\n print(num1+num2)", "_____no_output_____" ], [ "plus(1,2) # 아규먼트", "3\n" ], [ "plus(3, 4) #아규먼트", "7\n" ], [ "plus(3) # 아규먼트 개수가 요구되는 파라미터 개수랑 다를땐 오류가남", "_____no_output_____" ], [ "def plus(num1, num2=10): #파라미터 : 디폴트 파라미터\n print(num1+num2)", "_____no_output_____" ], [ "# 아무것도 입력하지 않으면 디폴트 값을 10으로 하겠다\nplus(3)", "13\n" ], [ "def plus(num1,num2=10,num3=20):\n print(num1+num2-num3)", "_____no_output_____" ], [ "plus(3,num3=100) # 아규먼트: 키워드 아규먼트 \n# 아규먼트를 어떤 파라미터역할에 대입할지 지정하는것", "-87\n" ] ], [ [ "### 3. 리턴\n- 함수를 실행한 결과를 저장하고 싶을때 사용합니다.\n- return", "_____no_output_____" ] ], [ [ "def plus(num1,num2):\n print(num1+num2)", "_____no_output_____" ], [ "result=plus(1,2)\nprint(result)\n# 출력까지는 해줬는데 값을 내보내진 않음", "3\nNone\n" ], [ "def plus(num1,num2):\n print(num1+num2)\n return num1+num2\n# return (num1+num2) ->를 하면 튜플로 저장됨 안해주는게 맞음", "_____no_output_____" ], [ "result=plus(1,2)\nprint(result)", "3\n3\n" ], [ "data1=\"python\"\nresult=data1.upper()\nprint(result)", "PYTHON\n" ], [ "data2=[3,1,2]\nresult=data2.sort()\nprint(result)\n# sort에는 return이 포함되어있지 않음", "None\n" ], [ "# 결과를 저장하는 함수 예시\ndef grade(point):\n result=\"\"\n if point >=90:\n return \"A\"\n elif point >= 80:\n return 'B'\n else:\n return \"C\"", "_____no_output_____" ], [ "point=78\nresult=grade(point)\nprint(result)", "C\n" ], [ "# 함수에서 return 코드가 실행되면 무조건 함수의 코드 실행이 종료 (break와같이)\n# 함수 종료를 위해서도 쓰임\ndef echo(msg):\n if msg == \"Quit\":\n return\n print(msg)", "_____no_output_____" ], [ "echo(\"python\")", "python\n" ], [ "echo(\"Quit\")", "_____no_output_____" ] ], [ [ "#### 4. `*args`, `**kwargs`\n- 함수를 호출할때 아규먼트와 키워드 아규먼트의 개수를 특정지을수 없을때 사용", "_____no_output_____" ] ], [ [ "def plus(num1, num2):\n return num1, num2", "_____no_output_____" ], [ "plus(1,2)", "_____no_output_____" ], [ "# `*args` 아규먼트 개수에 상관없이 들어온 모든 아큐먼트에 대해 적용,,\ndef plus(*args):\n print(type(args),args)\n return sum(args)", "_____no_output_____" ], [ "plus(1,2,3,4,5)", "<class 'tuple'> (1, 2, 3, 4, 5)\n" ], [ "# `*args` 아규먼트 개수에 상관없이 들어온 모든 아규먼트에 대해 적용,,\n# '**kargs' 키워드가 있는 아규먼트들을 일컫는말 키워드 있는 아규먼트들은 kargs에 들어감\n# kargs 키워드 있음 -> 딕셔너리 타입으로!\ndef plus(*args,**kargs):\n print(type(args),args)\n print(type(kargs),kargs)\n return sum(args)+sum(list(kargs.values()))", "_____no_output_____" ], [ "plus(1,2,3,4,5,num1=6,num2=7)", "<class 'tuple'> (1, 2, 3, 4, 5)\n<class 'dict'> {'num1': 6, 'num2': 7}\n" ], [ "def func(num1,num2,num3):\n return num1+num2+num3\n\ndata=[1,2,3]\nfunc(*data) # func(1,2,3)\n# *args 이것처럼 *data 하면 data안에있는 요소들을 args하나하나로 넣음!", "_____no_output_____" ], [ "def func(num1,num2,num3):\n return num1+num2+num3\n\ndata=[1,2,3]\nfunc(data) # func([1,2,3]) 이렇게 들어간 거라 1,2,3이 num1에 들어가 에러남\n# *args 이것처럼 *data 하면 data안에있는 요소들을 args하나하나로 넣음!", "_____no_output_____" ], [ "data={\n \"num2\":100,\n \"num3\":200,\n}\nfunc(1,**data)\n# 1은 num1에 data에 num2와 func의 num2 같으니 num2에 100, num3에는 200 \n# (**karg는 키값 같은걸 넣어줌)\n# func(1,num2=100,num3=200)와 동일한 결과", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af0c30654a39a777b47099e75e237df3a0836cb
43,009
ipynb
Jupyter Notebook
site/en/r1/guide/distribute_strategy.ipynb
Harirai/docs
c61b885bd5761f5283c1073b866a5ccfd56d7abf
[ "Apache-2.0" ]
1
2020-09-02T07:40:29.000Z
2020-09-02T07:40:29.000Z
site/en/r1/guide/distribute_strategy.ipynb
Harirai/docs
c61b885bd5761f5283c1073b866a5ccfd56d7abf
[ "Apache-2.0" ]
null
null
null
site/en/r1/guide/distribute_strategy.ipynb
Harirai/docs
c61b885bd5761f5283c1073b866a5ccfd56d7abf
[ "Apache-2.0" ]
null
null
null
46.146996
1,173
0.621661
[ [ [ "##### Copyright 2018 The TensorFlow Authors.\n", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ] ], [ [ "# Distributed Training in TensorFlow", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r1/guide/distribute_strategy.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r1/guide/distribute_strategy.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>", "_____no_output_____" ], [ "> Note: This is an archived TF1 notebook. These are configured\nto run in TF2's \n[compatbility mode](https://www.tensorflow.org/guide/migrate)\nbut will run in TF1 as well. To use TF1 in Colab, use the\n[%tensorflow_version 1.x](https://colab.research.google.com/notebooks/tensorflow_version.ipynb)\nmagic.", "_____no_output_____" ], [ "## Overview\n\n`tf.distribute.Strategy` is a TensorFlow API to distribute training\nacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.\n\n`tf.distribute.Strategy` has been designed with these key goals in mind:\n\n* Easy to use and support multiple user segments, including researchers, ML engineers, etc.\n* Provide good performance out of the box.\n* Easy switching between strategies.\n\n`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/r1/guide/keras) and [tf.estimator](https://www.tensorflow.org/r1/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).\nIn TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.\n\nAs you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.\n\nIn this guide, we will talk about various types of strategies and how one can use them in different situations.\n\nNote: For a deeper understanding of the concepts, please watch [this deep-dive presentation](https://youtu.be/jKV53r9-H14). This is especially recommended if you plan to write your own training loop.", "_____no_output_____" ] ], [ [ "import tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()", "_____no_output_____" ] ], [ [ "## Types of strategies\n`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:\n\n* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.\n* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.\n\nIn order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF.", "_____no_output_____" ], [ "### MirroredStrategy\n`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one model replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.\n\nEfficient all-reduce algorithms are used to communicate the variable updates across the devices.\nAll-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.\nIt’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.\n\nHere is the simplest way of creating `MirroredStrategy`:\n", "_____no_output_____" ] ], [ [ "mirrored_strategy = tf.distribute.MirroredStrategy()", "_____no_output_____" ] ], [ [ "This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.\n\nIf you wish to use only some of the GPUs on your machine, you can do so like this:", "_____no_output_____" ] ], [ [ "mirrored_strategy = tf.distribute.MirroredStrategy(devices=[\"/gpu:0\", \"/gpu:1\"])", "_____no_output_____" ] ], [ [ "If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.", "_____no_output_____" ] ], [ [ "mirrored_strategy = tf.distribute.MirroredStrategy(\n cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())", "_____no_output_____" ] ], [ [ "### CentralStorageStrategy\n`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.\n\nCreate a `CentralStorageStrategy` by:\n", "_____no_output_____" ] ], [ [ "central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()", "_____no_output_____" ] ], [ [ "This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables.", "_____no_output_____" ], [ "Note: This strategy is [`experimental`](https://www.tensorflow.org/r1/guide/version_compat#what_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future.", "_____no_output_____" ], [ "### MultiWorkerMirroredStrategy\n\n`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.\n\nIt uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.\n\nIt also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.\n\nHere is the simplest way of creating `MultiWorkerMirroredStrategy`:", "_____no_output_____" ] ], [ [ "multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()", "_____no_output_____" ] ], [ [ "`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:\n", "_____no_output_____" ] ], [ [ "multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(\n tf.distribute.experimental.CollectiveCommunication.NCCL)", "_____no_output_____" ] ], [ [ "One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. \"TF_CONFIG\" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on [\"TF_CONFIG\" below](#TF_CONFIG) for more details on how this can be done.\n", "_____no_output_____" ], [ "Note: This strategy is [`experimental`](https://www.tensorflow.org/r1/guide/version_compat#what_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future.", "_____no_output_____" ], [ "### TPUStrategy\n`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).\n\nIn terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.\n\nHere is how you would instantiate `TPUStrategy`.\nNote: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.\n\n```\nresolver = tf.distribute.cluster_resolver.TPUClusterResolver()\ntf.tpu.experimental.initialize_tpu_system(resolver)\ntpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)\n```\n", "_____no_output_____" ], [ "`TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost.", "_____no_output_____" ], [ "Note: This strategy is [`experimental`](https://www.tensorflow.org/r1/guide/version_compat#what_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future.", "_____no_output_____" ], [ "### ParameterServerStrategy\n`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of all the workers.\n\nIn terms of code, it looks similar to other strategies:\n```\nps_strategy = tf.distribute.experimental.ParameterServerStrategy()\n```", "_____no_output_____" ], [ "For multi worker training, \"TF_CONFIG\" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in [TF_CONFIG](#TF_CONFIG) below.", "_____no_output_____" ], [ "So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end.", "_____no_output_____" ], [ "## Using `tf.distribute.Strategy` with Keras\nWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the\n[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.\n\nHere is a snippet of code to do this for a very simple Keras model with one dense layer:", "_____no_output_____" ] ], [ [ "mirrored_strategy = tf.distribute.MirroredStrategy()\nwith mirrored_strategy.scope():\n model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])\n model.compile(loss='mse', optimizer='sgd')", "_____no_output_____" ] ], [ [ "In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.", "_____no_output_____" ] ], [ [ "dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)\nmodel.fit(dataset, epochs=2)\nmodel.evaluate(dataset)", "_____no_output_____" ] ], [ [ "Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:", "_____no_output_____" ] ], [ [ "import numpy as np\ninputs, targets = np.ones((100, 1)), np.ones((100, 1))\nmodel.fit(inputs, targets, epochs=2, batch_size=10)", "_____no_output_____" ] ], [ [ "In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.", "_____no_output_____" ] ], [ [ "# Compute global batch size using number of replicas.\nBATCH_SIZE_PER_REPLICA = 5\nglobal_batch_size = (BATCH_SIZE_PER_REPLICA *\n mirrored_strategy.num_replicas_in_sync)\ndataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)\ndataset = dataset.batch(global_batch_size)\n\nLEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}\nlearning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]", "_____no_output_____" ] ], [ [ "### What's supported now?\n\nIn [TF nightly release](https://pypi.org/project/tf-nightly-gpu/), we now support training with Keras using all strategies.\n\nNote: When using `TPUStrategy` with TPU pods with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently.\n\n### Examples and Tutorials\n\nHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:\n\n1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.\n2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/vision/image_classification/resnet_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.\n3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`.", "_____no_output_____" ], [ "## Using `tf.distribute.Strategy` with Estimator\n`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.\n\nThe usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.\n\nHere is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:\n", "_____no_output_____" ] ], [ [ "mirrored_strategy = tf.distribute.MirroredStrategy()\nconfig = tf.estimator.RunConfig(\n train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)\nregressor = tf.estimator.LinearRegressor(\n feature_columns=[tf.feature_column.numeric_column('feats')],\n optimizer='SGD',\n config=config)", "_____no_output_____" ] ], [ [ "We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.\n\nNow we can train and evaluate this Estimator with an input function:\n", "_____no_output_____" ] ], [ [ "def input_fn():\n dataset = tf.data.Dataset.from_tensors(({\"feats\":[1.]}, [1.]))\n return dataset.repeat(1000).batch(10)\nregressor.train(input_fn=input_fn, steps=10)\nregressor.evaluate(input_fn=input_fn, steps=10)", "_____no_output_____" ] ], [ [ "Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb).", "_____no_output_____" ], [ "We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:\n```\nconfig = tf.estimator.RunConfig(\n train_distribute=tpu_strategy, eval_distribute=tpu_strategy)\n```", "_____no_output_____" ], [ "And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set \"TF_CONFIG\" environment variables for each binary running in your cluster.", "_____no_output_____" ], [ "### What's supported now?\n\nIn TF nightly release, we support training with Estimator using all strategies.\n\n### Examples and Tutorials\nHere are some examples that show end to end usage of various strategies with Estimator:\n\n1. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.\n2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/r1/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.\n3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy.", "_____no_output_____" ], [ "## Using `tf.distribute.Strategy` with custom training loops\nAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.\n\nTensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.\n\nFor these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.\n\nHere we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.\nNote: These APIs are still experimental and we are improving them to make them more user friendly.", "_____no_output_____" ], [ "First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.", "_____no_output_____" ] ], [ [ "with mirrored_strategy.scope():\n model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])\n optimizer = tf.train.GradientDescentOptimizer(0.1)", "_____no_output_____" ] ], [ [ "Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.\n", "_____no_output_____" ] ], [ [ "dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(\n global_batch_size)\ndist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)", "_____no_output_____" ] ], [ [ "Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put it in a function `step_fn` and pass it to `tf.distribute.Strategy.run` along with the inputs from the iterator:", "_____no_output_____" ] ], [ [ "def train_step(dist_inputs):\n def step_fn(inputs):\n features, labels = inputs\n logits = model(features)\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=labels)\n loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)\n train_op = optimizer.minimize(loss)\n with tf.control_dependencies([train_op]):\n return tf.identity(loss)\n\n per_replica_losses = mirrored_strategy.run(\n step_fn, args=(dist_inputs,))\n mean_loss = mirrored_strategy.reduce(\n tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)\n return mean_loss", "_____no_output_____" ] ], [ [ "A few other things to note in the code above:\n\n1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.\n2. We used the `strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.run`. `tf.distribute.Strategy.run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results(results)`to get the list of values contained in the result, one per local replica.\n", "_____no_output_____" ], [ "Finally, once we have defined the training step, we can initialize the iterator and variables and run the training in a loop:", "_____no_output_____" ] ], [ [ "with mirrored_strategy.scope():\n input_iterator = dist_dataset.make_initializable_iterator()\n iterator_init = input_iterator.initializer\n var_init = tf.global_variables_initializer()\n loss = train_step(input_iterator.get_next())\n with tf.Session() as sess:\n sess.run([var_init, iterator_init])\n for _ in range(10):\n print(sess.run(loss))", "_____no_output_____" ] ], [ [ "In the example above, we used `tf.distribute.Strategy.experimental_distribute_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.", "_____no_output_____" ], [ "This covers the simplest case of using `tf.distribute.Strategy` API to distribute custom training loops. We are in the process of improving these APIs. Since this use case requires more work on the part of the user, we will be publishing a separate detailed guide in the future.", "_____no_output_____" ], [ "### What's supported now?\nIn TF nightly release, we support training with custom training loops using `MirroredStrategy` and `TPUStrategy` as shown above. Support for other strategies will be coming in soon. `MultiWorkerMirorredStrategy` support will be coming in the future.\n\n### Examples and Tutorials\nHere are some examples for using distribution strategy with custom training loops:\n\n1. [Example](https://github.com/tensorflow/tensorflow/blob/5456cc28f3f8d9c17c645d9a409e495969e584ae/tensorflow/contrib/distribute/python/examples/mnist_tf1_tpu.py) to train MNIST using `TPUStrategy`.\n", "_____no_output_____" ], [ "## Other topics\nIn this section, we will cover some topics that are relevant to multiple use cases.", "_____no_output_____" ], [ "<a id=\"TF_CONFIG\">\n### Setting up TF\\_CONFIG environment variable\n</a>\nFor multi-worker training, as mentioned before, you need to set \"TF\\_CONFIG\" environment variable for each\nbinary running in your cluster. The \"TF\\_CONFIG\" environment variable is a JSON string which specifies what\ntasks constitute a cluster, their addresses and each task's role in the cluster. We provide a Kubernetes template in the\n[tensorflow/ecosystem](https://github.com/tensorflow/ecosystem) repo which sets\n\"TF\\_CONFIG\" for your training tasks.\n\nOne example of \"TF\\_CONFIG\" is:\n```\nos.environ[\"TF_CONFIG\"] = json.dumps({\n \"cluster\": {\n \"worker\": [\"host1:port\", \"host2:port\", \"host3:port\"],\n \"ps\": [\"host4:port\", \"host5:port\"]\n },\n \"task\": {\"type\": \"worker\", \"index\": 1}\n})\n```\n", "_____no_output_____" ], [ "This \"TF\\_CONFIG\" specifies that there are three workers and two ps tasks in the\ncluster along with their hosts and ports. The \"task\" part specifies that the\nrole of the current task in the cluster, worker 1 (the second worker). Valid roles in a cluster is\n\"chief\", \"worker\", \"ps\" and \"evaluator\". There should be no \"ps\" job except when using `tf.distribute.experimental.ParameterServerStrategy`.", "_____no_output_____" ], [ "## What's next?\n\n`tf.distribute.Strategy` is actively under development. We welcome you to try it out and provide your feedback via [issues on GitHub](https://github.com/tensorflow/tensorflow/issues/new).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af0cbbd39f5ce8fc7e90212b062f2def5d7f41a
7,651
ipynb
Jupyter Notebook
digit-sums/digitsums.ipynb
TotalVerb/EMAC
dbbb6b7875d07f125d90f71d31d46074fbf2c6df
[ "MIT" ]
null
null
null
digit-sums/digitsums.ipynb
TotalVerb/EMAC
dbbb6b7875d07f125d90f71d31d46074fbf2c6df
[ "MIT" ]
null
null
null
digit-sums/digitsums.ipynb
TotalVerb/EMAC
dbbb6b7875d07f125d90f71d31d46074fbf2c6df
[ "MIT" ]
null
null
null
23.469325
581
0.504771
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af0d3cd423099144b29b89915c3aa9d2ae69c7b
230,441
ipynb
Jupyter Notebook
FAST_pet_breeds_classifier.ipynb
psmathur/pets_breeds_classifier
36c8f66914f1142e53abd16c7d447da6053d1110
[ "MIT" ]
null
null
null
FAST_pet_breeds_classifier.ipynb
psmathur/pets_breeds_classifier
36c8f66914f1142e53abd16c7d447da6053d1110
[ "MIT" ]
null
null
null
FAST_pet_breeds_classifier.ipynb
psmathur/pets_breeds_classifier
36c8f66914f1142e53abd16c7d447da6053d1110
[ "MIT" ]
null
null
null
439.772901
191,622
0.92494
[ [ [ "!pip install -qq fastbook\nimport fastbook\n# fastbook.setup_book()", "\u001b[?25l\r\u001b[K |█ | 10kB 25.1MB/s eta 0:00:01\r\u001b[K |█▉ | 20kB 18.6MB/s eta 0:00:01\r\u001b[K |██▉ | 30kB 9.0MB/s eta 0:00:01\r\u001b[K |███▊ | 40kB 11.2MB/s eta 0:00:01\r\u001b[K |████▋ | 51kB 11.1MB/s eta 0:00:01\r\u001b[K |█████▋ | 61kB 10.9MB/s eta 0:00:01\r\u001b[K |██████▌ | 71kB 10.7MB/s eta 0:00:01\r\u001b[K |███████▍ | 81kB 9.9MB/s eta 0:00:01\r\u001b[K |████████▍ | 92kB 9.2MB/s eta 0:00:01\r\u001b[K |█████████▎ | 102kB 9.4MB/s eta 0:00:01\r\u001b[K |██████████▏ | 112kB 9.4MB/s eta 0:00:01\r\u001b[K |███████████▏ | 122kB 9.4MB/s eta 0:00:01\r\u001b[K |████████████ | 133kB 9.4MB/s eta 0:00:01\r\u001b[K |█████████████ | 143kB 9.4MB/s eta 0:00:01\r\u001b[K |██████████████ | 153kB 9.4MB/s eta 0:00:01\r\u001b[K |██████████████▉ | 163kB 9.4MB/s eta 0:00:01\r\u001b[K |███████████████▊ | 174kB 9.4MB/s eta 0:00:01\r\u001b[K |████████████████▊ | 184kB 9.4MB/s eta 0:00:01\r\u001b[K |█████████████████▋ | 194kB 9.4MB/s eta 0:00:01\r\u001b[K |██████████████████▌ | 204kB 9.4MB/s eta 0:00:01\r\u001b[K |███████████████████▌ | 215kB 9.4MB/s eta 0:00:01\r\u001b[K |████████████████████▍ | 225kB 9.4MB/s eta 0:00:01\r\u001b[K |█████████████████████▎ | 235kB 9.4MB/s eta 0:00:01\r\u001b[K |██████████████████████▎ | 245kB 9.4MB/s eta 0:00:01\r\u001b[K |███████████████████████▏ | 256kB 9.4MB/s eta 0:00:01\r\u001b[K |████████████████████████ | 266kB 9.4MB/s eta 0:00:01\r\u001b[K |█████████████████████████ | 276kB 9.4MB/s eta 0:00:01\r\u001b[K |██████████████████████████ | 286kB 9.4MB/s eta 0:00:01\r\u001b[K |███████████████████████████ | 296kB 9.4MB/s eta 0:00:01\r\u001b[K |███████████████████████████▉ | 307kB 9.4MB/s eta 0:00:01\r\u001b[K |████████████████████████████▊ | 317kB 9.4MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▊ | 327kB 9.4MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▋ | 337kB 9.4MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▌| 348kB 9.4MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 358kB 9.4MB/s \n\u001b[K |████████████████████████████████| 51kB 6.5MB/s \n\u001b[K |████████████████████████████████| 1.0MB 14.4MB/s \n\u001b[K |████████████████████████████████| 61kB 7.9MB/s \n\u001b[K |████████████████████████████████| 40kB 5.5MB/s \n\u001b[K |████████████████████████████████| 92kB 11.0MB/s \n\u001b[K |████████████████████████████████| 61kB 8.8MB/s \n\u001b[K |████████████████████████████████| 51kB 7.8MB/s \n\u001b[K |████████████████████████████████| 2.6MB 30.0MB/s \n\u001b[31mERROR: fastai 2.0.7 has requirement pandas>=1.1.0, but you'll have pandas 1.0.5 which is incompatible.\u001b[0m\n\u001b[?25h" ], [ "from fastbook import *", "_____no_output_____" ], [ "!pip install -qq fastai", "_____no_output_____" ] ], [ [ "# Image Classification", "_____no_output_____" ] ], [ [ "from fastai.vision.all import *\npath = untar_data(URLs.PETS)", "_____no_output_____" ], [ "#hide\nPath.BASE_PATH = path", "_____no_output_____" ], [ "path.ls()", "_____no_output_____" ], [ "(path/\"images\").ls()", "_____no_output_____" ], [ "fname = (path/\"images\").ls()[0]", "_____no_output_____" ], [ "re.findall(r'(.+)_\\d+.jpg$', fname.name)", "_____no_output_____" ], [ "pets = DataBlock(blocks = (ImageBlock, CategoryBlock),\n get_items=get_image_files, \n splitter=RandomSplitter(seed=42),\n get_y=using_attr(RegexLabeller(r'(.+)_\\d+.jpg$'), 'name'),\n item_tfms=Resize(460),\n batch_tfms=aug_transforms(size=224, min_scale=0.75))\ndls = pets.dataloaders(path/\"images\")", "_____no_output_____" ] ], [ [ "### Checking and Debugging a DataBlock", "_____no_output_____" ] ], [ [ "dls.show_batch(nrows=1, ncols=3)", "_____no_output_____" ] ], [ [ "### Discriminative Learning Rates", "_____no_output_____" ] ], [ [ "learn = cnn_learner(dls, resnet34, metrics=error_rate)\nlearn.fit_one_cycle(3, 3e-3)\nlearn.unfreeze()\nlearn.fit_one_cycle(3, lr_max=slice(1e-6,1e-4))", "_____no_output_____" ], [ "learn.recorder.plot_loss()", "_____no_output_____" ] ], [ [ "### Export Model", "_____no_output_____" ] ], [ [ "learn.export()", "_____no_output_____" ] ], [ [ "### Tranform Model to ONNX Format", "_____no_output_____" ] ], [ [ "sample_img_input = torch.randn(1, 3, 224, 224, device='cuda')\nonnx_path = \"pets_model.onnx\"\ntorch.onnx.export(learn.model, sample_img_input, onnx_path, verbose=False)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4af0d7770c371eeea5af55da65199533756a734d
96,288
ipynb
Jupyter Notebook
Post_blog_Attribution(MAM).ipynb
andretocci/notebooks
be89c1c14db8436f75f9e8b1c783fec755c214d6
[ "Apache-2.0" ]
null
null
null
Post_blog_Attribution(MAM).ipynb
andretocci/notebooks
be89c1c14db8436f75f9e8b1c783fec755c214d6
[ "Apache-2.0" ]
null
null
null
Post_blog_Attribution(MAM).ipynb
andretocci/notebooks
be89c1c14db8436f75f9e8b1c783fec755c214d6
[ "Apache-2.0" ]
null
null
null
68.483642
27,322
0.650413
[ [ [ "<a href=\"https://colab.research.google.com/github/andretocci/notebooks/blob/master/Post_blog_Attribution(MAM).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "## Demostração Blog DP6", "_____no_output_____" ], [ "Importando pacotes necessários:", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n!pip install marketing_attribution_models\nfrom marketing_attribution_models import MAM", "_____no_output_____" ], [ "#@title Importando e Tratando as Bases\nimport glob\nfrom google.colab import drive\ndrive.mount('/content/drive/')\n\nfilepath = '/content/drive/Shared drives/Data Science/Ultron/Recipes/DP6tribution/'\nfilename = '*'\nall_files = glob.glob(filepath + filename)\npd.set_option('display.float_format', lambda x: '%.3f' % x)", "_____no_output_____" ] ], [ [ "Para está demonstração, optamos por demonstrar utilizando uma base de dados bastante conhecida pelos profissionais do Marketing: Google Merchandise Store. Está base foi extraída da conta de demonstração do Google Analytics, que pode ser acessada por qualquer usuário do Google.", "_____no_output_____" ] ], [ [ "#Lendo os dados do Google Merchandise Store, mas selecioanndo apenas as colunas que serão utilizadas para gerar os modelos\ndf = pd.read_csv(all_files[0], \n usecols=['channelGrouping', \n 'date', \n 'fullVisitorId', \n 'totals_transactions', \n 'totals_transactionRevenue'],\n dtype = {'channelGrouping':str, \n 'fullVisitorId':str, \n 'totals_transactions' : np.float64, \n 'totals_transactionRevenue' : np.float64} )\n\n#Analizando o DF retornado\ndf.head()", "_____no_output_____" ] ], [ [ "Mas antes de aplicarmos o modelo utilizando a MAM, precisamos realizar alguns ajustes na base de dados. \n\nE analisando o .head() e o .info(), conseguimos observar que:\n\n- A coluna de data não está no formato datetime;\n- As colunas totals_transactions e totals_transactionRevenue possuem valores vazios;\n- fullVisitorId foi lido como objeto, temos que tomar cuidado para não ler essa informação como número, 001 pode ser um ID diferente de1; \n- A base não possui nenhum agrupamento de jornada;", "_____no_output_____" ] ], [ [ "#Selecionando colunas necessárias\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 73948 entries, 0 to 73947\nData columns (total 5 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 channelGrouping 73948 non-null object \n 1 date 73948 non-null int64 \n 2 fullVisitorId 73948 non-null object \n 3 totals_transactions 818 non-null float64\n 4 totals_transactionRevenue 817 non-null float64\ndtypes: float64(2), int64(1), object(2)\nmemory usage: 2.8+ MB\n" ] ], [ [ "Assim, tratamos a coluna de data para o formato correto, tratamos os valores nulos e criamos uma coluna indicando se houve ou não uma conversão naquela sessão.", "_____no_output_____" ] ], [ [ "df['date_tratada'] = pd.to_datetime( df['date'], format='%Y%m%d' )\ndf['totals_transactions'].fillna(0, inplace=True)\ndf['totals_transactionRevenue'].fillna(0, inplace=True)\ndf['has_transaction'] = df.totals_transactions.apply(lambda x: True if x > 0 else False)\n\ndf.head()", "_____no_output_____" ] ], [ [ "Agora que tratamos nossa base, podemos criar o nosso objeto MAM, como nossa base está na granularidade de sessão por usuário e não possuímos um ID de agrupamento de jornada, é importante que passamos como True os parametros group_channels e create_journey_id_based_on_conversion.", "_____no_output_____" ] ], [ [ "DP_tribution = MAM(df, \n channels_colname='channelGrouping',\n group_channels=True, \n group_channels_by_id_list=['fullVisitorId'], \n group_timestamp_colname='date_tratada',\n journey_with_conv_colname='has_transaction',\n create_journey_id_based_on_conversion = True,\n conversion_value='totals_transactionRevenue')", "_____no_output_____" ] ], [ [ "Acessando o atributo .DataFrame, conseguimos observar que houve uma mudança significativa em nossa base de dados. Observamos que a granularidade da tabela foi alterada de sessão para jornada e que há uma coluna nova de id da jornada.", "_____no_output_____" ] ], [ [ "DP_tribution.DataFrame.sort_values('conversion_value', ascending=False).head()", "_____no_output_____" ] ], [ [ "### Aplicando os Modelos", "_____no_output_____" ], [ "Para rodar o modelo do Shapley Value, basta aplicar o método .attribution_shapley().\n\nO parâmetro **size limita quantidade de canais únicos na jornada**, por **padrão** é definido como os **4 últimos**. Isso ocorre pois o número de iterações aumenta exponencialmente com o número de canais. Da ordem de 2N, sendo N o número de canais. \n\nA metodologia do cálculo das contribuições marginais pode variar através do **parâmetro order**, que por padrão calcula a contribuição da **combinação dos canais independende da ordem em que aparecem** nas diferentes jornadas.\n\nPor fim, parâmetro na qual o Shapley Value será calculado pode ser alterado em **values_col**, que por padrão utiliza a **taxa de conversão** que é uma forma de **considerarmos as não conversões no cálculo do modelo**. Contudo, também podemos considerar no cálculo o total de conversões ou o valor gerados pelas conversões, como demostrado abaixo. ", "_____no_output_____" ] ], [ [ "shapley_results = DP_tribution.attribution_shapley()", "_____no_output_____" ] ], [ [ "O método retorna uma tupla contendo :\n- Os resultados agrupados por jornadas únicas;", "_____no_output_____" ] ], [ [ "shapley_results[0]", "_____no_output_____" ] ], [ [ "- E os resultados agrupados por canais:", "_____no_output_____" ] ], [ [ "shapley_results[1].reset_index()", "_____no_output_____" ] ], [ [ "Para rodar o modelo das **Cadeias de Markov**, basta aplicar o método .attribution_markov().\n\nNo parâmetro de entrada transition_to_same_state, indica se irá ser retornado ou não a probabilidade de transição para o mesmo estado. Essa configuração **não afeta os resultados agregados** e que são atribuídos para cada canal, **mas sim os valores observados na matriz de transição**.", "_____no_output_____" ] ], [ [ "markov_results = DP_tribution.attribution_markov(transition_to_same_state=False)", "_____no_output_____" ] ], [ [ "O método retorna uma tupla contendo :\n- Os resultados em nível de jornada, que também pode ser obeservado acessando o .DataFrame. ", "_____no_output_____" ] ], [ [ "markov_results[0].head()", "_____no_output_____" ] ], [ [ "- E os resultados agrupados por canais, como retornado pelo modelo Shapley acima;", "_____no_output_____" ] ], [ [ "markov_results[1]", "_____no_output_____" ] ], [ [ "- Matrix de transição:", "_____no_output_____" ] ], [ [ "ax, fig = plt.subplots(figsize=(15,10))\nsns.heatmap(markov_results[2].round(3), cmap=\"YlGnBu\", annot=True, linewidths=.5)", "_____no_output_____" ] ], [ [ "- **Removal Effect**, quarto output dos resultados attribution_markov, que como detalhado anteriormente, nos auxilia a entender a impertância de cada canal analisado:", "_____no_output_____" ] ], [ [ "ax, fig = plt.subplots(figsize=(2,5))\nsns.heatmap(markov_results[3].round(3), cmap=\"YlGnBu\", annot=True, linewidths=.5)", "_____no_output_____" ] ], [ [ "#### Comparando os Resultados\n\nAgora que rodamos ambos os modelos, podemos comparar seus resultados acessando o atributo group_by_channels_models, que retorna todos os diferentes modelos aplicados nos passos anteriores.", "_____no_output_____" ] ], [ [ "DP_tribution.group_by_channels_models", "_____no_output_____" ], [ "DP_tribution.group_by_channels_models.sum()", "_____no_output_____" ], [ " DP_tribution.plot()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4af11a0bf61fc9b3bd074665a49cb49662ddefa8
1,712
ipynb
Jupyter Notebook
algorithms/122-Best-Time-to-Buy-and-Sell-Stock-II.ipynb
DjangoPeng/leetcode-solutions
9aa2b911b0278e743448f04241828d33182c9d76
[ "Apache-2.0" ]
10
2019-03-23T15:15:55.000Z
2020-07-12T02:37:31.000Z
algorithms/122-Best-Time-to-Buy-and-Sell-Stock-II.ipynb
DjangoPeng/leetcode-solutions
9aa2b911b0278e743448f04241828d33182c9d76
[ "Apache-2.0" ]
null
null
null
algorithms/122-Best-Time-to-Buy-and-Sell-Stock-II.ipynb
DjangoPeng/leetcode-solutions
9aa2b911b0278e743448f04241828d33182c9d76
[ "Apache-2.0" ]
3
2019-06-21T12:13:23.000Z
2020-12-08T07:49:33.000Z
19.906977
55
0.431659
[ [ [ "class Solution:\n def maxProfit(self, prices: [int]) -> int:\n if len(prices) == 0:\n return 0\n min = prices[0]\n max = prices[0]\n profit = 0\n prices.append(0)\n for price in prices:\n if price > max:\n max = price\n if price < max:\n profit = max - min + profit\n min = price\n max = price\n return profit ", "_____no_output_____" ], [ "s = Solution()", "_____no_output_____" ], [ "s.maxProfit([7,1,6,3,4,1])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
4af12011e8e86a65b976eff4031c15b9a64bfe26
1,686
ipynb
Jupyter Notebook
Python Data Science Toolbox -Part 2/List comprehensions and generators/01. Write a basic list comprehension.ipynb
nazmusshakib121/Python-Programming
3ea852641cd5fe811228f27a780109a44174e8e5
[ "MIT" ]
null
null
null
Python Data Science Toolbox -Part 2/List comprehensions and generators/01. Write a basic list comprehension.ipynb
nazmusshakib121/Python-Programming
3ea852641cd5fe811228f27a780109a44174e8e5
[ "MIT" ]
null
null
null
Python Data Science Toolbox -Part 2/List comprehensions and generators/01. Write a basic list comprehension.ipynb
nazmusshakib121/Python-Programming
3ea852641cd5fe811228f27a780109a44174e8e5
[ "MIT" ]
null
null
null
33.058824
212
0.596085
[ [ [ "### Write a basic list comprehension\nIn this exercise, you will practice what you've learned from the video about writing list comprehensions. You will write a list comprehension and identify the output that will be produced.\n\nThe following list has been pre-loaded in the environment.\n\ndoctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson']\nHow would a list comprehension that produces a list of the first character of each string in doctor look like? Note that the list comprehension uses doc as the iterator variable. What will the output be?\n\n#### Possible Answers\n- The list comprehension is [for doc in doctor: doc[0]] and produces the list ['h', 'c', 'c', 't', 'w'].\n- The list comprehension is [doc[0] for doc in doctor] and produces the list ['h', 'c', 'c', 't', 'w'].\n- The list comprehension is [doc[0] in doctor] and produces the list ['h', 'c', 'c', 't', 'w'].\n", "_____no_output_____" ], [ "The list comprehension is [doc[0] for doc in doctor] and produces the list ['h', 'c', 'c', 't', 'w'].", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown" ] ]
4af1427ec9eb09ff27a5fc878283e1cf64b3842a
13,858
ipynb
Jupyter Notebook
train.ipynb
metanav/Handwriting_Recognition_IMU
8d874ced4a7c97f14733719805cbc54262c07673
[ "Apache-2.0" ]
6
2020-04-09T14:28:44.000Z
2022-01-08T21:48:21.000Z
train.ipynb
metanav/Handwriting_Recognition_IMU
8d874ced4a7c97f14733719805cbc54262c07673
[ "Apache-2.0" ]
1
2021-03-19T04:12:02.000Z
2021-03-22T02:58:32.000Z
train.ipynb
metanav/Handwriting_Recognition_IMU
8d874ced4a7c97f14733719805cbc54262c07673
[ "Apache-2.0" ]
1
2021-04-21T04:57:06.000Z
2021-04-21T04:57:06.000Z
31.639269
274
0.553038
[ [ [ "from __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom os import listdir, path\nimport numpy as np\nfrom collections import defaultdict\nimport datetime\nimport random\n\nrandom.seed(42) # Keep the order stable everytime shuffling the files while creating training datasets", "_____no_output_____" ] ], [ [ "## Global variables", "_____no_output_____" ] ], [ [ "seq_length = 36 # This will be used to keep the fixed input size for the first CNN layer\ndim = 6 # Number of datapoints in a single reading accX,accY,accZ,gyrX,gyrY,gyrZ\nnum_classes = 10 # Number of output classes [0,9] ", "_____no_output_____" ] ], [ [ "## Sequence Padding\n#### When collecting sequence data, individual samples have different lengths. Since the input data for a convolutional neural network must be a single tensor, samples need to be padded. The sequence are padded at the beginning and at the end with neighboring values.", "_____no_output_____" ] ], [ [ "def padding(data):\n padded_data = []\n noise_level = [ 20, 20, 20, 0.2, 0.2, 0.2 ]\n \n tmp_data = (np.random.rand(seq_length, dim) - 0.5) * noise_level + data[0]\n tmp_data[(seq_length - min(len(data), seq_length)):] = data[:min(len(data), seq_length)]\n padded_data.append(tmp_data)\n\n tmp_data = (np.random.rand(seq_length, dim) - 0.5) * noise_level + data[-1]\n tmp_data[:min(len(data), seq_length)] = data[:min(len(data), seq_length)]\n \n padded_data.append(tmp_data)\n return padded_data", "_____no_output_____" ] ], [ [ "## Convert to TensorFlow dataset, keeps data and labels together\n", "_____no_output_____" ] ], [ [ "def build_dataset(data, label):\n # Add 2 padding, initialize data and label\n padded_num = 2\n length = len(data) * padded_num\n features = np.zeros((length, seq_length, dim))\n labels = np.zeros(length)\n # Get padding for train, valid and test\n for idx, (data, label) in enumerate(zip(data, label)):\n padded_data = padding(data)\n for num in range(padded_num):\n features[padded_num * idx + num] = padded_data[num]\n labels[padded_num * idx + num] = label\n # Turn into tf.data.Dataset\n dataset = tf.data.Dataset.from_tensor_slices((features, labels.astype(\"int32\")))\n return length, dataset", "_____no_output_____" ] ], [ [ "## Time Warping", "_____no_output_____" ] ], [ [ "def time_warping(molecule, denominator, data):\n tmp_data = [[0 for i in range(len(data[0]))] for j in range((int(len(data) / molecule) - 1) * denominator)]\n \n for i in range(int(len(data) / molecule) - 1):\n for j in range(len(data[i])):\n for k in range(denominator):\n tmp_data[denominator * i + k][j] = (data[molecule * i + k][j] * (denominator - k) \n + data[molecule * i + k + 1][j] * k) / denominator\n return tmp_data\n", "_____no_output_____" ] ], [ [ "## Data augmentation", "_____no_output_____" ] ], [ [ "def augment_data(original_data, original_label):\n new_data = []\n new_label = []\n for idx, (data, label) in enumerate(zip(original_data, original_label)): # pylint: disable=unused-variable\n # Original data\n new_data.append(data)\n new_label.append(label)\n # Shift Sequence\n for num in range(5): # pylint: disable=unused-variable\n new_data.append((np.array(data, dtype=np.float32) +\n (random.random() - 0.5) * 200).tolist())\n new_label.append(label)\n # Add Random noise\n tmp_data = [[0 for i in range(len(data[0]))] for j in range(len(data))]\n for num in range(5):\n for i in range(len(tmp_data)):\n for j in range(len(tmp_data[i])):\n tmp_data[i][j] = data[i][j] + 5 * random.random()\n new_data.append(tmp_data)\n new_label.append(label)\n # Time warping\n fractions = [(3, 2), (5, 3), (2, 3), (3, 4), (9, 5), (6, 5), (4, 5)]\n for molecule, denominator in fractions:\n new_data.append(time_warping(molecule, denominator, data))\n new_label.append(label)\n # Movement amplification\n for molecule, denominator in fractions:\n new_data.append(\n (np.array(data, dtype=np.float32) * molecule / denominator).tolist())\n new_label.append(label)\n return new_data, new_label", "_____no_output_____" ] ], [ [ "## Load data from files", "_____no_output_____" ] ], [ [ "def load_data(data_type, files):\n data = []\n labels = []\n random.shuffle(files)\n \n for file in files:\n with open(file) as f:\n label = path.splitext(file)[0][-1]\n labels.append(label)\n readings = []\n for line in f:\n reading = line.strip().split(',')\n readings.append([float(i) for i in reading[0:6]])\n\n data.append(readings)\n \n if data_type == 'train':\n data, labels = augment_data(data, labels)\n \n return build_dataset(data, labels)", "_____no_output_____" ] ], [ [ "## Prepare training, validation, and test datasets", "_____no_output_____" ] ], [ [ "files_path = defaultdict(list)\ndir = './data'\nfor filename in listdir(dir):\n if filename.endswith('.csv'):\n digit = path.splitext(filename)[0][-1]\n files_path[digit].append(path.join(dir, filename))\n\ntrain_files = []\nvalidation_files = []\ntest_files = []\n\nfor digit in files_path:\n random.shuffle(files_path[digit])\n \n train_split = int(len(files_path[digit]) * 0.6) # 60%\n validation_split = train_split + int(len(files_path[digit]) * 0.2) # 20%\n\n train_files += files_path[digit][:train_split]\n validation_files += files_path[digit][train_split:validation_split]\n # remaining 20%\n test_files += files_path[digit][validation_split:]\n\ntrain_length, train_data = load_data('train', train_files)\nvalidation_length, validation_data = load_data('validation', validation_files)\ntest_length, test_data = load_data('test', test_files )\n\nprint('train_length={} validation_length={} test_length{}'.format(train_length, validation_length, test_length))", "_____no_output_____" ] ], [ [ "## Build a sequential model", "_____no_output_____" ] ], [ [ "model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(8, (3, 3), padding=\"same\", activation=\"relu\", input_shape=(seq_length, dim, 1)),\n tf.keras.layers.Conv2D(8, (3, 3), padding=\"same\", activation=\"relu\"),\n tf.keras.layers.MaxPool2D((2, 2)),\n tf.keras.layers.Dropout(0.1),\n tf.keras.layers.Conv2D(8, (3, 3), padding=\"same\", activation=\"relu\"),\n tf.keras.layers.MaxPool2D((2, 2), padding=\"same\"),\n tf.keras.layers.Dropout(0.1),\n tf.keras.layers.Conv2D(16, (3, 3), padding=\"same\", activation=\"relu\"),\n tf.keras.layers.MaxPool2D((2, 2), padding=\"same\"),\n tf.keras.layers.Dropout(0.1),\n tf.keras.layers.Conv2D(16, (3, 3), padding=\"same\", activation=\"relu\"),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(64, activation=\"relu\"),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(32, activation=\"relu\"),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(num_classes, activation=\"softmax\")\n ])\n\nmodel.summary()", "_____no_output_____" ] ], [ [ "## Compile and start training", "_____no_output_____" ] ], [ [ "epochs = 100\nbatch_size = 64\nsteps_per_epoch=1000\n\nmodel.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"])\n\ndef reshape_function(data, label):\n reshaped_data = tf.reshape(data, [-1, dim, 1])\n return reshaped_data, label\n\ntrain_data = train_data.map(reshape_function)\nvalidation_data = validation_data.map(reshape_function)\n\ntrain_data = train_data.batch(batch_size).repeat()\nvalidation_data = validation_data.batch(batch_size)\n\nlogdir = \"logs/fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\ntensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=logdir)\n\n# Uncomment the ines below if you like to see how training proceeds\n# %load_ext tensorboard\n# %tensorboard --logdir logdir\n\nmodel.fit(\n train_data,\n epochs=epochs,\n validation_data=validation_data,\n steps_per_epoch=steps_per_epoch,\n validation_steps=int((validation_length - 1) / batch_size + 1),\n callbacks=[tensorboard_callback])", "_____no_output_____" ] ], [ [ "## Evaluate the trained model on test dataset", "_____no_output_____" ] ], [ [ "test_data = test_data.map(reshape_function)\ntest_labels = np.zeros(test_length)\n\n# There is no easy function to get the labels back from the tf.data.Dataset :(\n# Need to iterate over dataset\nidx = 0\nfor data, label in test_data:\n test_labels[idx] = label.numpy()\n idx += 1\n \ntest_data = test_data.batch(batch_size)\n\nloss, acc = model.evaluate(test_data)\npred = np.argmax(model.predict(test_data), axis=1)\n\n# Create a confusion matrix to see how model predicts\nconfusion = tf.math.confusion_matrix(labels=tf.constant(test_labels), predictions=tf.constant(pred), num_classes=num_classes)\nprint(confusion)", "_____no_output_____" ] ], [ [ "## Convert model to TFLite format \n### Note: Currently quantized TFLite format does not work with TFLite Micro library", "_____no_output_____" ] ], [ [ "converter = tf.lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()\nopen(\"model.tflite\", \"wb\").write(tflite_model)\n\n# Convert the model to the TensorFlow Lite format with quantization\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\nconverter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\ntflite_model = converter.convert()\nopen(\"model_quantized.tflite\", \"wb\").write(tflite_model)\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" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af14dc58c0e93fd0f7a9a2985b5cb2d730a6767
11,741
ipynb
Jupyter Notebook
_notebooks/2020-02-20-PythonBestPractises.ipynb
SurendraRedd/Learnings2020
6646b6031bbfbec6061bd9d9865c10c4351b9a22
[ "Apache-2.0" ]
null
null
null
_notebooks/2020-02-20-PythonBestPractises.ipynb
SurendraRedd/Learnings2020
6646b6031bbfbec6061bd9d9865c10c4351b9a22
[ "Apache-2.0" ]
1
2022-02-26T09:59:14.000Z
2022-02-26T09:59:14.000Z
_notebooks/2020-02-20-PythonBestPractises.ipynb
SurendraRedd/Learnings2020
6646b6031bbfbec6061bd9d9865c10c4351b9a22
[ "Apache-2.0" ]
null
null
null
25.918322
97
0.505664
[ [ [ "## Best Practise 1 → Using enumerate() - Fetch elements from list", "_____no_output_____" ] ], [ [ "# List Variable\nexample = ['use','enumerate','instead','of','iteration']\n\n# Ideal Way\nfor i in range(len(example)):\n print(f\"# {i + 1}: {example[i]}\")\n \n# Pythonic way - enumerate\nfor i, value in enumerate(example, 1):\n print(f\"# {i}: {value}\")", "# 1: use\n# 2: enumerate\n# 3: instead\n# 4: of\n# 5: iteration\n# 1: use\n# 2: enumerate\n# 3: instead\n# 4: of\n# 5: iteration\n" ] ], [ [ "## Best Practise 2 → Using zip() - Fetch elements from multiple lists", "_____no_output_____" ] ], [ [ "# Lists \nEmployees = ['Employee1','Employee2','Employee3','Employee4']\nAge = [30,25,35,40]\n\n# Ideal Way\nfor i in range(len(Employees)):\n employee = Employees[i]\n age = Age[i]\n print(f\"Employee name is {employee} and age is {age}\")\n \n# Pythonic way - zip\nfor employee, age in zip(Employees, Age):\n print(f\"Employee name is {employee} and age is {age}\")", "Employee name is Employee1 and age is 30\nEmployee name is Employee2 and age is 25\nEmployee name is Employee3 and age is 35\nEmployee name is Employee4 and age is 40\nEmployee name is Employee1 and age is 30\nEmployee name is Employee2 and age is 25\nEmployee name is Employee3 and age is 35\nEmployee name is Employee4 and age is 40\n" ] ], [ [ "## Best Practise 3 → Using reversed() - Fetch elements reversly", "_____no_output_____" ] ], [ [ "# Lists \nEmployees = ['Employee1','Employee2','Employee3','Employee4']\n\n# Ideal way\nfor i in range(1,len(Employees) + 1):\n print(f\"Approach 1 - Employee came to office after covid 19 is {Employees[-i]}\")\nfor employee in Employees[::-1]:\n print(f\"Approach 2 - Employee came to office after covid 19 is {employee}\")\n \n# Pythonic way - reversed()\nfor employee in reversed(Employees):\n print(f\"Using revered - Employee came to office after covid 19 is {employee}\")", "Approach 1 - Employee came to office after covid 19 is Employee4\nApproach 1 - Employee came to office after covid 19 is Employee3\nApproach 1 - Employee came to office after covid 19 is Employee2\nApproach 1 - Employee came to office after covid 19 is Employee1\nApproach 2 - Employee came to office after covid 19 is Employee4\nApproach 2 - Employee came to office after covid 19 is Employee3\nApproach 2 - Employee came to office after covid 19 is Employee2\nApproach 2 - Employee came to office after covid 19 is Employee1\nUsing revered - Employee came to office after covid 19 is Employee4\nUsing revered - Employee came to office after covid 19 is Employee3\nUsing revered - Employee came to office after covid 19 is Employee2\nUsing revered - Employee came to office after covid 19 is Employee1\n" ] ], [ [ "## Best Practise 4 → Using filter() - Data Filtering", "_____no_output_____" ] ], [ [ "# List\nnumbers = [1,2,3,4,5,6,7,8,9,10]\n\n#Ideal way\nfor number in numbers:\n if number % 2:\n print(f\"Odd Number : {number}\")\n\n# Pythonic way - filter()\nfor number in filter(lambda x: x %2, numbers):\n print(f\"Odd Number : {number}\") ", "Odd Number : 1\nOdd Number : 3\nOdd Number : 5\nOdd Number : 7\nOdd Number : 9\nOdd Number : 1\nOdd Number : 3\nOdd Number : 5\nOdd Number : 7\nOdd Number : 9\n" ] ], [ [ "## Best Practise 5 → Using Chain() - Concatenate values from lists", "_____no_output_____" ] ], [ [ "from itertools import chain\n\n#Lists\noddValues = [1,3,5,7,9]\nevenValues = [2,4,6,8,10]\n\n# Ideal way\nvalues = oddValues + evenValues\nfor value in values:\n print(f\"value is : {value}\")\n\n# Pythonic way - chain()\nfor value in chain(oddValues, evenValues):\n print(f\"value is : {value}\")", "value is : 1\nvalue is : 3\nvalue is : 5\nvalue is : 7\nvalue is : 9\nvalue is : 2\nvalue is : 4\nvalue is : 6\nvalue is : 8\nvalue is : 10\nvalue is : 1\nvalue is : 3\nvalue is : 5\nvalue is : 7\nvalue is : 9\nvalue is : 2\nvalue is : 4\nvalue is : 6\nvalue is : 8\nvalue is : 10\n" ] ], [ [ "## Best Practise 6 → Using Dictionaries() - Retrieve keys & values from dictionary", "_____no_output_____" ] ], [ [ "# Dict\nEmployees = {\"Employee1\": 30, \"Employee2\": 35, \"Employee3\": 40, \"Employee4\": 45}\n\n#Ideal way\nfor key in Employees:\n print(f\"Employee Name is : {key}\")\nfor key in Employees.keys():\n print(f\"Employee Name is : {key}\")\nfor value in Employees.values():\n print(f\"Age is : {value}\")\nfor value in Employees:\n print(f\"Age is : {Employees[value]}\")\n \n#Pythonic way\nfor key, value in Employees.items():\n print(f\"Employee came to office after covid 19 is {key} and age is {value}\")\n ", "Employee Name is : Employee1\nEmployee Name is : Employee2\nEmployee Name is : Employee3\nEmployee Name is : Employee4\nEmployee Name is : Employee1\nEmployee Name is : Employee2\nEmployee Name is : Employee3\nEmployee Name is : Employee4\nAge is : 30\nAge is : 35\nAge is : 40\nAge is : 45\nAge is : 30\nAge is : 35\nAge is : 40\nAge is : 45\nEmployee came to office after covid 19 is Employee1 and age is 30\nEmployee came to office after covid 19 is Employee2 and age is 35\nEmployee came to office after covid 19 is Employee3 and age is 40\nEmployee came to office after covid 19 is Employee4 and age is 45\n" ] ], [ [ "## Best Practise 7 → Using Comprehension() - Comprehensions for lists, dictionaries & set", "_____no_output_____" ] ], [ [ "### list\nnumbers = [1,2,3,4,5,6,7,8,9,10]\n\n#Ideal way\nsquaredNumbers = list()\nfor square in numbers:\n squaredNumbers.append(square * square)\nprint(squaredNumbers)\n\n#Using list comprehension\nsquaredNumbers = [x * x for x in numbers]\nprint(squaredNumbers)\n\n#Ideal way\nsquaredNumbers = dict()\nfor square in numbers:\n squaredNumbers[square] = square * square\n \n#Using list comprehension\nsquaredNumbers = {x: x*x for x in numbers}\nprint(squaredNumbers)\n\n#Ideal way\nsquaredNumbers = set()\nfor square in numbers:\n squaredNumbers.add(square)\nprint(squaredNumbers)\n\n#Using list comprehension\nsquaredNumbers = [x*x for x in numbers]\nprint(squaredNumbers) ", "_____no_output_____" ] ], [ [ "## Best Practise 8 → Using else clause - For and While Loops", "_____no_output_____" ] ], [ [ "# For Loop\nfor n in range(2, 10):\n for x in range(2, n):\n if n % x == 0:\n print( n, 'equals', x, '*', n/x)\n break\n else:\n # loop fell through without finding a factor\n print(n, 'is a prime number')\n\n# While Loop\ncount = 2\nwhile (count < 1): \n count = count+1\n print(count) \n break\nelse: \n print(\"No Break\")", "2 is a prime number\n3 is a prime number\n4 equals 2 * 2.0\n5 is a prime number\n6 equals 2 * 3.0\n7 is a prime number\n8 equals 2 * 4.0\n9 equals 3 * 3.0\nNo Break\n" ] ], [ [ "## Best Practise 9 → **Using Ternary Opertor** - Ternary Opertor", "_____no_output_____" ] ], [ [ " #Traditional\n value = True\n if value:\n v = 1\n else:\n v = 0\n print(v)\n\n #Using ternary\n value = True\n v = 1 if value else 0\n print(v)", "1\n1\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" ] ]
4af150212a5e688abffef997053a31a977a772d8
401,173
ipynb
Jupyter Notebook
notebooks/MullerBrown_II.ipynb
schinavro/taps
c03b4e23ed299824c1b062225b837a0b7cfff216
[ "MIT" ]
null
null
null
notebooks/MullerBrown_II.ipynb
schinavro/taps
c03b4e23ed299824c1b062225b837a0b7cfff216
[ "MIT" ]
null
null
null
notebooks/MullerBrown_II.ipynb
schinavro/taps
c03b4e23ed299824c1b062225b837a0b7cfff216
[ "MIT" ]
null
null
null
677.657095
31,164
0.950116
[ [ [ "# Müller Brown II\n\n## Previously on Müller Brown I", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom taps.paths import Paths\nfrom taps.models import MullerBrown\nfrom taps.coords import Cartesian\nfrom taps.visualize import view\n\nN = 300\n\nx = np.linspace(-0.55822365, 0.6234994, N)\ny = np.linspace(1.44172582, 0.02803776, N)\n\ncoords = Cartesian(coords=np.array([x, y]))\nmodel = MullerBrown()\npaths = Paths(coords=coords, model=model)\nview(paths, viewer='MullerBrown')", "_____no_output_____" ] ], [ [ "## Müller Brown II\n Here, we introduce a less fun but more practical tools in TAPS, `Projector`. Optimizing a pathway of an atomic system requires vast amount of computational time on the configuration space searching which in many case unfeasible. `Projector` class manipulates the coordinates system into smaller (usually) dimension so that user can reduce the configuration space for searching. For example, user can use the `Mask` projector that effectively hide some atoms from the `PathFinder` object so that position of some atoms can be fixed while optimizing the pathway. Surface reaction may use it useful restriction for a slab. Or user can optimize only the sine components of the pathway so user can effectively reduce the space to search. Or one may want to do it both. In the `Projector` class, there are three keywords `domain`, `codomain`, and `pipeline`. Unfortunately, `domain` and `codomain` keywords are exists as future usage. They are intended to controls the class of the pathway while prjoection into one to the other but currently it only exists as a concept. The third keyword, `pipeline` binds the multiple `Projector` class into one so that user can use multiple projector like one. For example, user can put `Sine` projector into the `Mask`s pipeline so that some atoms are ignored and being fourie transformed. For simplicity, we are going to demonstrate only the `Sine` projector here. \n \n Unfortunately, using `Sine` projector is not an automatic procedure. User has to put 4 additional kewords, total length of the `coords`, $N$, a number of sine components $N_k$, image of initial step `init`, and final reactant `fin`. `Sine` projector uses `scipy.fftpack` to conduct fast fourier transform. `Sine` use type 1 sine transformation, where\n \n$$y_k = 2 \\sum_{n=0}^{N-1} x_n \\sin\\left(\\frac{\\pi(k+1)(n+1)}{N+1}\\right)$$\n\nWe have to fix the both end to 0. That gives us stability when removing high frequency components. Since it assumes the both end as 0, coordinate at both end should be given explcitley. Thus, user should manually specify the coordinate. Script below shows creation of the `Sine` projector and manipulate a sine components of that coordinate and visualize how it effected. ", "_____no_output_____" ] ], [ [ "from taps.projectors import Sine\n# We are going to use only the 30% of the coordinate information\nNk = N - 270\nprj = Sine(N=N, Nk=Nk, \n init=paths.coords.coords[..., 0].copy(), \n fin=paths.coords.coords[..., -1].copy())\nsine_coords = prj.x(paths.coords())\n\n# Sine component manipulation\nsine_coords.coords[:, 1] = -5\n\npaths.coords = prj.x_inv(sine_coords)\nview(paths, viewer='MullerBrown')", "_____no_output_____" ] ], [ [ "## Pathway optimization on the sine components.\n\n Previouse MB example was conducted on the 2D Cartesian coordinate directly. In this example, we are going to use `Sine` projector during optimization process. Setting and kewords are same with previous example, with additional `prj_search=True` and `prj=prj` keyword inserted in `DAO`. ", "_____no_output_____" ] ], [ [ "from taps.pathfinder import DAO\n\naction_kwargs = {\n 'Onsager Machlup':{ \n 'gam': 1.,\n },\n 'Energy Restraint':{\n 'muE': 1.,\n 'Et': -0.45\n }\n}\n\nsearch_kwargs = {\"method\":\"L-BFGS-B\"}\n\nfinder = DAO(action_kwargs=action_kwargs,\n search_kwargs=search_kwargs, \n prj=prj)\n\npaths.finder = finder\npaths.coords.epoch=6\npaths.search()\n", "=================================\n Parameters\n=================================\nOnsager Machlup\n gam : 1.0 \n \nEnergy Restraint\n muE : 1.0 \n Et : -0.45\n \n Iter nfev njev S dS_max\nConverge : 533 570 570 2.0390 0.0003\nConverge : 534 574 574 2.0390 0.0002\n\n=================================\n Results\n=================================\n Onsager Machlup : 1.4683296803914132\n Energy Restraint : 0.5706518224212558\n Total S : 2.038981502812669\n" ] ], [ [ "Below text is output of previous example, where cartesian coordinates were directly used as input $(N=300)$. But here we used only 10% $(Nk=30)$ of the coordinate information during optimization process. From that we get huge amount of gain in computatational cost but a little sacrifice of its accuracy without losing continuity required by action calculation. \n\n## Results in the previous example, Müller Brown I \n```\n=================================\n Parameters\n=================================\nOnsager Machlup\n gam : 1.0 \n \nEnergy Restraint\n muE : 1.0 \n Et : -0.45\n \n Iter nfev njev S dS_max\nConverge : 9784 10021 10021 1.8258 0.0070\nConverge : 9785 10040 10040 1.8258 0.0070\n\n=================================\n Results\n=================================\n Onsager Machlup : 1.2556032942672488\n Energy Restraint : 0.5702371630130022\n Total S : 1.825840457280251\n```\n", "_____no_output_____" ] ], [ [ "view(paths, viewer=\"MullerBrown\")", "_____no_output_____" ] ], [ [ "You can see through profile of the trajectory that it has lack of high frequency components. ", "_____no_output_____" ], [ "## Database construction\n\nTo utilize the data while we calculate the pathways, construction of proper database is postulated. `ImageData` class can save the calculation results of atomic or model system using below. \n\n```python\nfrom taps.db import ImageData\nimgdata = ImageData()\nimgdata.add_data(paths, coords=(DxN or 3xDxN)size array)\n```\n\n\n\nTAPS aims for string method pathway calculation more effcient manner. meaning we insert some muller. In order to use I had to made the data abse", "_____no_output_____" ] ], [ [ "from taps.db import ImageDatabase\nimgdata = ImageDatabase(filename=\"mullerbrown.db\")\nimgdata.add_data(paths, coords=paths.coords(index=[0, -1]))", "_____no_output_____" ] ], [ [ "## Gaussian Potential\n\nWith the data we constructed in this example, we are going to use it to construct Gaussian PES. Using only the 3 point of data, `init`, `fin` and middle point of the trajectory, We conconstruct the Gaussian Potential.\n\nKernel we are going to use here is standard (square exponential) kernel. Kernel looks like, \n\n$$ K(x_1, x_2) = \\sigma_f e^{(x_1-x_2)^2/2l^2}$$\n\nwith zero mean, expectation value and covariance of the potential is\n\n$$\\mu = K_* (K_y+\\sigma_n)^{-1} \\mathbf{Y} $$\n$$\\Sigma = K_{**} + K_* K_y^{-1} K_*^{-1}$$ \n\nIn the process of regression, where minimize the log likelihood. \n", "_____no_output_____" ] ], [ [ "from taps.models import Gaussian\n\npaths.imgdata = imgdata\n\nmodel = Gaussian(real_model=model)\npaths.model = model\n\npaths.add_data(index=[0, paths.coords.N // 2, -1])", "_____no_output_____" ], [ "paths.model.kernel.hyperparameters['sigma_f'] = 0.5\npaths.model.kernel.hyperparameters['l^2'] = 0.1\nview(paths, viewer=\"MullerBrown\", gaussian=True)", "_____no_output_____" ] ], [ [ "## $\\mu$ and $\\Sigma$ Maps\n\nYou can see the second and third map images that depicting mean expectation value, $\\mu$, and uncertainty map, $\\Sigma$ with additional information plotted on the map such as maximum uncertainty or maximum estimated potential. \n\n It looks totally different from real PES, the first map. We will shows you how we approximate the PES near the minimum energy pathway (MEP) to real one. We will finish this tutorial by optimizing the pathway based on the Gaussian PES. ", "_____no_output_____" ] ], [ [ "paths.finder.action_kwargs['Energy Restraint'].update({'Et': -1.2})\npaths.search()\nview(paths, viewer=\"MullerBrown\", gaussian=True)", "=================================\n Parameters\n=================================\nOnsager Machlup\n gam : 1.0 \n \nEnergy Restraint\n muE : 1.0 \n Et : -1.2 \n \n Iter nfev njev S dS_max\nConverge : 635 678 678 130.6496 0.0018\nConverge : 636 681 681 130.6496 0.0018\nsigma_f : 0.5\nl^2 : 0.1\nsigma_n^e : 0.5056707126957068\nsigma_n^f : -2.855272523688322\n=================================\n Results\n=================================\n Onsager Machlup : 1.1923132477354408\n Energy Restraint : 129.45729772544635\n Total S : 130.64961097318178\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4af153682ea41f7b1ec0709155bc21521b532024
66,851
ipynb
Jupyter Notebook
notebooks/Masterclass Hands-on-Questions.ipynb
MKB-Datalab/masterclass-basics-webscraping
bd37468def630d0c72f2e4d0638b6825f5ddcc9f
[ "MIT" ]
1
2022-03-28T16:45:35.000Z
2022-03-28T16:45:35.000Z
notebooks/Masterclass Hands-on-Questions.ipynb
MKB-Datalab/masterclass-basics-webscraping
bd37468def630d0c72f2e4d0638b6825f5ddcc9f
[ "MIT" ]
null
null
null
notebooks/Masterclass Hands-on-Questions.ipynb
MKB-Datalab/masterclass-basics-webscraping
bd37468def630d0c72f2e4d0638b6825f5ddcc9f
[ "MIT" ]
null
null
null
32.047459
2,594
0.351618
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Introduction\" data-toc-modified-id=\"Introduction-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Introduction</a></span><ul class=\"toc-item\"><li><span><a href=\"#Example-01:-Extract-text\" data-toc-modified-id=\"Example-01:-Extract-text-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Example 01: Extract text</a></span><ul class=\"toc-item\"><li><span><a href=\"#Write-the-code-for-the-main-steps-aiming-web-scraping\" data-toc-modified-id=\"Write-the-code-for-the-main-steps-aiming-web-scraping-1.1.1\"><span class=\"toc-item-num\">1.1.1&nbsp;&nbsp;</span>Write the code for the main steps aiming web scraping</a></span><ul class=\"toc-item\"><li><span><a href=\"#Send-request-and-catch-response\" data-toc-modified-id=\"Send-request-and-catch-response-1.1.1.1\"><span class=\"toc-item-num\">1.1.1.1&nbsp;&nbsp;</span>Send request and catch response</a></span></li><li><span><a href=\"#get-the-content-of-the-response\" data-toc-modified-id=\"get-the-content-of-the-response-1.1.1.2\"><span class=\"toc-item-num\">1.1.1.2&nbsp;&nbsp;</span>get the content of the response</a></span></li><li><span><a href=\"#parse-webpage\" data-toc-modified-id=\"parse-webpage-1.1.1.3\"><span class=\"toc-item-num\">1.1.1.3&nbsp;&nbsp;</span>parse webpage</a></span></li><li><span><a href=\"#Extra:-Use-prettify-to-have-a-'prettier'-view-of-the-page's-code\" data-toc-modified-id=\"Extra:-Use-prettify-to-have-a-'prettier'-view-of-the-page's-code-1.1.1.4\"><span class=\"toc-item-num\">1.1.1.4&nbsp;&nbsp;</span>Extra: Use prettify to have a 'prettier' view of the page's code</a></span></li></ul></li><li><span><a href=\"#Title?\" data-toc-modified-id=\"Title?-1.1.2\"><span class=\"toc-item-num\">1.1.2&nbsp;&nbsp;</span>Title?</a></span></li><li><span><a href=\"#Text-per-section-(e.g.-1.-What-is-cryptocurrency?)\" data-toc-modified-id=\"Text-per-section-(e.g.-1.-What-is-cryptocurrency?)-1.1.3\"><span class=\"toc-item-num\">1.1.3&nbsp;&nbsp;</span>Text per section (e.g. 1. What is cryptocurrency?)</a></span></li></ul></li><li><span><a href=\"#Example-02:-Extract-table-info\" data-toc-modified-id=\"Example-02:-Extract-table-info-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Example 02: Extract table info</a></span></li><li><span><a href=\"#Example-03:-Extract-information-from-hyperlink\" data-toc-modified-id=\"Example-03:-Extract-information-from-hyperlink-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Example 03: Extract information from hyperlink</a></span></li></ul></li></ul></div>", "_____no_output_____" ], [ "# Introduction", "_____no_output_____" ] ], [ [ "# importing packages\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd", "_____no_output_____" ] ], [ [ "## Example 01: Extract text", "_____no_output_____" ] ], [ [ "url_01 = \"https://www.nerdwallet.com/article/investing/cryptocurrency-7-things-to-know#:~:text=A%20cryptocurrency%20(or%20%E2%80%9Ccrypto%E2%80%9D,sell%20or%20trade%20them%20securely.\"", "_____no_output_____" ] ], [ [ "### Write the code for the main steps aiming web scraping \n\n#### Send request and catch response", "_____no_output_____" ] ], [ [ "# response = ", "_____no_output_____" ] ], [ [ "#### get the content of the response", "_____no_output_____" ] ], [ [ "# content = ", "_____no_output_____" ] ], [ [ "#### parse webpage", "_____no_output_____" ] ], [ [ "# parser = ", "_____no_output_____" ] ], [ [ "#### Extra: Use prettify to have a 'prettier' view of the page's code", "_____no_output_____" ], [ "`parser` is a `BeautifulSoup object`, which represents the document as a nested data structure.\n\nThe `prettify()` method will turn a Beautiful Soup parse tree into a nicely formatted Unicode string, making it much easy to visualize the tree structure.", "_____no_output_____" ] ], [ [ "def parse_website(url):\n \"\"\" \n Parse content of a website\n \n Args:\n url (str): url of the website of which we want to acess the content \n \n Return:\n parser: representation of the document as a nested data structure.\n \"\"\"\n # Send request and catch response\n response = requests.get(url)\n\n # get the content of the response\n content = response.content\n\n # parse webpage\n parser = BeautifulSoup(content, \"lxml\")\n \n return parser ", "_____no_output_____" ], [ "parser_01 = parse_website(url_01)", "_____no_output_____" ] ], [ [ "### Title?", "_____no_output_____" ] ], [ [ "# access title of the web page\n\n\n#obtain text between tags\n", "_____no_output_____" ] ], [ [ "### Text per section (e.g. 1. What is cryptocurrency?)\n\n1. Access subtitles (titles of sections e.g. \"Cryptocurrency definition\")\n\n![](../images/crypto_currency_section.png)", "_____no_output_____" ] ], [ [ "# subtitles = ", "_____no_output_____" ], [ "# texts = ", "_____no_output_____" ], [ "# text_01 = texts[0:6]", "_____no_output_____" ], [ "# text_01", "_____no_output_____" ] ], [ [ "Apply some cleaning to the piece of text bellow if you have time...", "_____no_output_____" ] ], [ [ "# text_01 = text_01[0:4]", "_____no_output_____" ] ], [ [ "## Example 02: Extract table info", "_____no_output_____" ] ], [ [ "url_02 = \"https://www.worldometers.info/population/countries-in-the-eu-by-population/\"", "_____no_output_____" ], [ "parser_02 = parse_website(url_02)", "_____no_output_____" ], [ "print(parser_02.prettify())", "<!DOCTYPE html>\n<!--[if IE 8]> <html lang=\"en\" class=\"ie8\"> <![endif]-->\n<!--[if IE 9]> <html lang=\"en\" class=\"ie9\"> <![endif]-->\n<!--[if !IE]><!-->\n<html lang=\"en\">\n <!--<![endif]-->\n <head>\n <meta charset=\"utf-8\"/>\n <meta content=\"IE=edge\" http-equiv=\"X-UA-Compatible\"/>\n <meta content=\"width=device-width, initial-scale=1\" name=\"viewport\"/>\n <title>\n Countries in the EU by Population (2022) - Worldometer\n </title>\n <meta content=\"List of countries the European Union ranked by population, from the most populous. Growth rate, median age, fertility rate, area, density, population density, urbanization, urban population, share of world population.\" name=\"description\"/>\n <link href=\"/favicon/favicon.ico\" rel=\"shortcut icon\" type=\"image/x-icon\"/>\n <link href=\"/favicon/apple-icon-57x57.png\" rel=\"apple-touch-icon\" sizes=\"57x57\"/>\n <link href=\"/favicon/apple-icon-60x60.png\" rel=\"apple-touch-icon\" sizes=\"60x60\"/>\n <link href=\"/favicon/apple-icon-72x72.png\" rel=\"apple-touch-icon\" sizes=\"72x72\"/>\n <link href=\"/favicon/apple-icon-76x76.png\" rel=\"apple-touch-icon\" sizes=\"76x76\"/>\n <link href=\"/favicon/apple-icon-114x114.png\" rel=\"apple-touch-icon\" sizes=\"114x114\"/>\n <link href=\"/favicon/apple-icon-120x120.png\" rel=\"apple-touch-icon\" sizes=\"120x120\"/>\n <link href=\"/favicon/apple-icon-144x144.png\" rel=\"apple-touch-icon\" sizes=\"144x144\"/>\n <link href=\"/favicon/apple-icon-152x152.png\" rel=\"apple-touch-icon\" sizes=\"152x152\"/>\n <link href=\"/favicon/apple-icon-180x180.png\" rel=\"apple-touch-icon\" sizes=\"180x180\"/>\n <link href=\"/favicon/android-icon-192x192.png\" rel=\"icon\" sizes=\"192x192\" type=\"image/png\"/>\n <link href=\"/favicon/favicon-32x32.png\" rel=\"icon\" sizes=\"32x32\" type=\"image/png\"/>\n <link href=\"/favicon/favicon-96x96.png\" rel=\"icon\" sizes=\"96x96\" type=\"image/png\"/>\n <link href=\"/favicon/favicon-16x16.png\" rel=\"icon\" sizes=\"16x16\" type=\"image/png\"/>\n <link href=\"/favicon/manifest.json\" rel=\"manifest\"/>\n <meta content=\"#ffffff\" name=\"msapplication-TileColor\"/>\n <meta content=\"/favicon/ms-icon-144x144.png\" name=\"msapplication-TileImage\"/>\n <meta content=\"#ffffff\" name=\"theme-color\"/>\n <meta content=\"http://www.worldometers.info/img/worldometers-fb.jpg\" property=\"og:image\"/>\n <link href=\"/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n <link href=\"/wm16.css\" rel=\"stylesheet\"/>\n <link href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css\" rel=\"stylesheet\"/>\n <!--[if lt IE 9]> <script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"></script> <script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script> <![endif]-->\n <script src=\"/js/jquery.min.js\">\n </script>\n <script src=\"/js/bootstrap.min.js\">\n </script>\n <script src=\"/js/ie10-viewport-bug-workaround.js\">\n </script>\n <link href=\"https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <script src=\"https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js\" type=\"text/javascript\">\n </script>\n <script src=\"https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js\" type=\"text/javascript\">\n </script>\n <script class=\"init\" type=\"text/javascript\">\n $.extend( $.fn.dataTable.defaults, { responsive: true\n} );\t$(document).ready(function() { $('#example2').dataTable( { \"scrollCollapse\": true,\t\"sDom\": '<\"bottom\"flp><\"clear\">', \"paging\": false } );\n} );\n </script>\n <script class=\"init\" type=\"text/javascript\">\n $.extend( $.fn.dataTable.defaults, { responsive: true\n} );\t$(document).ready(function() { $('#table3').dataTable( { \"scrollCollapse\": true, \"order\": [[ 1, 'desc' ]],\t\"sDom\": '<\"bottom\"flp><\"clear\">', \"paging\": false } );\n} );\n </script>\n <script class=\"init\" type=\"text/javascript\">\n $.extend( $.fn.dataTable.defaults, { responsive: true\n} );\t$(document).ready(function() { $('#example').dataTable( { \"scrollCollapse\": true,\t\"searching\": false,\t\"sDom\": '<\"top\">rt<\"bottom\"flp><\"clear\">', \"paging\": false } );\n} );\n </script>\n <script class=\"init\" type=\"text/javascript\">\n $(document).ready(function() {\t$('#popbycountry').dataTable();\n} );\n </script>\n <script data-cfasync=\"false\" type=\"text/javascript\">\n var freestar = freestar || {}; freestar.hitTime = Date.now(); freestar.queue = freestar.queue || []; freestar.config = freestar.config || {}; freestar.debug = window.location.search.indexOf('fsdebug') === -1 ? false : true; freestar.config.enabled_slots = []; !function(a,b){var c=b.getElementsByTagName(\"script\")[0],d=b.createElement(\"script\"),e=\"https://a.pub.network/worldometers-info\";e+=freestar.debug?\"/qa/pubfig.min.js\":\"/pubfig.min.js\",d.async=!0,d.src=e,c.parentNode.insertBefore(d,c)}(window,document); freestar.initCallback = function () { (freestar.config.enabled_slots.length === 0) ? freestar.initCallbackCalled = false : freestar.newAdSlots(freestar.config.enabled_slots) }\n </script>\n </head>\n <body>\n <script>\n (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-1438574-2', 'auto'); ga('send', 'pageview');\n </script>\n <script async=\"\" src=\"https://www.googletagmanager.com/gtag/js?id=UA-1438574-30\">\n </script>\n <script>\n window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-1438574-30');\n </script>\n <link href=\"//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.js\">\n </script>\n <script>\n window.addEventListener(\"load\", function(){\nwindow.cookieconsent.initialise({ \"palette\": { \"popup\": { \"background\": \"#efefef\", \"text\": \"#404040\" }, \"button\": { \"background\": \"#8ec760\", \"text\": \"#ffffff\" } }, \"theme\": \"classic\", \"content\": { \"href\": \"http://www.worldometers.info/policy/\" }\n})});\n </script>\n <style type=\"text/css\">\n .style1 { color: #666666 }\n </style>\n <div class=\"navbar navbar-default\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <div class=\"logo\">\n <a class=\"navbar-brand\" href=\"/\">\n <img border=\"0\" src=\"/img/worldometers-logo.gif\" title=\"Worldometer\"/>\n </a>\n </div>\n <button class=\"navbar-toggle\" data-target=\"#navbar-main\" data-toggle=\"collapse\" type=\"button\">\n <span class=\"icon-bar\">\n </span>\n <span class=\"icon-bar\">\n </span>\n <span class=\"icon-bar\">\n </span>\n </button>\n </div>\n <div class=\"navbar-collapse collapse\" id=\"navbar-main\">\n <ul class=\"nav navbar-nav\">\n <li>\n <a href=\"/coronavirus/\">\n <span style=\"color:#FF9900; font-weight:bold\">\n Coronavirus\n </span>\n </a>\n </li>\n <li>\n <a href=\"/population/\">\n Population\n </a>\n </li>\n </ul>\n </div>\n </div>\n </div>\n <div class=\"container\">\n <div class=\"row\">\n <div style=\"text-align:left; margin-bottom:10px\">\n <script async=\"\" src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\">\n </script>\n <ins class=\"adsbygoogle\" data-ad-client=\"ca-pub-3701697624350410\" data-ad-slot=\"3287840995\" style=\"display:inline-block;width:970px;height:90px\">\n </ins>\n <script>\n (adsbygoogle = window.adsbygoogle || []).push({});\n </script>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"content-inner\">\n <ul class=\"breadcrumb\">\n <li>\n <a href=\"/\">\n W\n </a>\n </li>\n <li>\n <a href=\"/population/\">\n Population\n </a>\n </li>\n <li>\n <a href=\"/population/world/\">\n World\n </a>\n </li>\n <li>\n <a href=\"/population/europe/\">\n Europe\n </a>\n </li>\n <li class=\"active\">\n Countries in the European Union by Population\n </li>\n </ul>\n <div class=\"row spacer-bottom\">\n <div class=\"col-md-12\">\n <h1>\n Countries in the EU by population (2022)\n </h1>\n <p>\n The European Union has 28 member countries. Click on each country to view current estimates (live population clock), historical data, and projected figures.\n </p>\n </div>\n </div>\n <div class=\"table-responsive\" style=\"font-size:14px; width:100%\">\n <table cellspacing=\"0\" class=\"table table-striped table-bordered\" id=\"example2\" width=\"100%\">\n <thead>\n <tr>\n <th>\n #\n </th>\n <th>\n Country (or dependency)\n </th>\n <th>\n Population\n <br/>\n (2020)\n </th>\n <th>\n Yearly\n <br/>\n Change\n </th>\n <th>\n Net\n <br/>\n Change\n </th>\n <th>\n Density\n <br/>\n (P/Km²)\n </th>\n <th>\n Land Area\n <br/>\n (Km²)\n </th>\n <th>\n Migrants\n <br/>\n (net)\n </th>\n <th>\n Fert.\n <br/>\n Rate\n </th>\n <th>\n Med.\n <br/>\n Age\n </th>\n <th>\n Urban\n <br/>\n Pop %\n </th>\n <th>\n World\n <br/>\n Share\n </th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n 1\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/germany-population/\">\n Germany\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 83,783,942\n </td>\n <td>\n 0.32 %\n </td>\n <td>\n 266,897\n </td>\n <td>\n 240\n </td>\n <td>\n 348,560\n </td>\n <td>\n 543,822\n </td>\n <td>\n 1.6\n </td>\n <td>\n 46\n </td>\n <td>\n 76 %\n </td>\n <td>\n 1.07 %\n </td>\n </tr>\n <tr>\n <td>\n 2\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/france-population/\">\n France\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 65,273,511\n </td>\n <td>\n 0.22 %\n </td>\n <td>\n 143,783\n </td>\n <td>\n 119\n </td>\n <td>\n 547,557\n </td>\n <td>\n 36,527\n </td>\n <td>\n 1.9\n </td>\n <td>\n 42\n </td>\n <td>\n 82 %\n </td>\n <td>\n 0.84 %\n </td>\n </tr>\n <tr>\n <td>\n 3\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/italy-population/\">\n Italy\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 60,461,826\n </td>\n <td>\n -0.15 %\n </td>\n <td>\n -88,249\n </td>\n <td>\n 206\n </td>\n <td>\n 294,140\n </td>\n <td>\n 148,943\n </td>\n <td>\n 1.3\n </td>\n <td>\n 47\n </td>\n <td>\n 69 %\n </td>\n <td>\n 0.78 %\n </td>\n </tr>\n <tr>\n <td>\n 4\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/spain-population/\">\n Spain\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 46,754,778\n </td>\n <td>\n 0.04 %\n </td>\n <td>\n 18,002\n </td>\n <td>\n 94\n </td>\n <td>\n 498,800\n </td>\n <td>\n 40,000\n </td>\n <td>\n 1.3\n </td>\n <td>\n 45\n </td>\n <td>\n 80 %\n </td>\n <td>\n 0.60 %\n </td>\n </tr>\n <tr>\n <td>\n 5\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/poland-population/\">\n Poland\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 37,846,611\n </td>\n <td>\n -0.11 %\n </td>\n <td>\n -41,157\n </td>\n <td>\n 124\n </td>\n <td>\n 306,230\n </td>\n <td>\n -29,395\n </td>\n <td>\n 1.4\n </td>\n <td>\n 42\n </td>\n <td>\n 60 %\n </td>\n <td>\n 0.49 %\n </td>\n </tr>\n <tr>\n <td>\n 6\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/romania-population/\">\n Romania\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 19,237,691\n </td>\n <td>\n -0.66 %\n </td>\n <td>\n -126,866\n </td>\n <td>\n 84\n </td>\n <td>\n 230,170\n </td>\n <td>\n -73,999\n </td>\n <td>\n 1.6\n </td>\n <td>\n 43\n </td>\n <td>\n 55 %\n </td>\n <td>\n 0.25 %\n </td>\n </tr>\n <tr>\n <td>\n 7\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/netherlands-population/\">\n Netherlands\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 17,134,872\n </td>\n <td>\n 0.22 %\n </td>\n <td>\n 37,742\n </td>\n <td>\n 508\n </td>\n <td>\n 33,720\n </td>\n <td>\n 16,000\n </td>\n <td>\n 1.7\n </td>\n <td>\n 43\n </td>\n <td>\n 92 %\n </td>\n <td>\n 0.22 %\n </td>\n </tr>\n <tr>\n <td>\n 8\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/belgium-population/\">\n Belgium\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 11,589,623\n </td>\n <td>\n 0.44 %\n </td>\n <td>\n 50,295\n </td>\n <td>\n 383\n </td>\n <td>\n 30,280\n </td>\n <td>\n 48,000\n </td>\n <td>\n 1.7\n </td>\n <td>\n 42\n </td>\n <td>\n 98 %\n </td>\n <td>\n 0.15 %\n </td>\n </tr>\n <tr>\n <td>\n 9\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/czech-republic-population/\">\n Czech Republic (Czechia)\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 10,708,981\n </td>\n <td>\n 0.18 %\n </td>\n <td>\n 19,772\n </td>\n <td>\n 139\n </td>\n <td>\n 77,240\n </td>\n <td>\n 22,011\n </td>\n <td>\n 1.6\n </td>\n <td>\n 43\n </td>\n <td>\n 74 %\n </td>\n <td>\n 0.14 %\n </td>\n </tr>\n <tr>\n <td>\n 10\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/greece-population/\">\n Greece\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 10,423,054\n </td>\n <td>\n -0.48 %\n </td>\n <td>\n -50,401\n </td>\n <td>\n 81\n </td>\n <td>\n 128,900\n </td>\n <td>\n -16,000\n </td>\n <td>\n 1.3\n </td>\n <td>\n 46\n </td>\n <td>\n 85 %\n </td>\n <td>\n 0.13 %\n </td>\n </tr>\n <tr>\n <td>\n 11\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/portugal-population/\">\n Portugal\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 10,196,709\n </td>\n <td>\n -0.29 %\n </td>\n <td>\n -29,478\n </td>\n <td>\n 111\n </td>\n <td>\n 91,590\n </td>\n <td>\n -6,000\n </td>\n <td>\n 1.3\n </td>\n <td>\n 46\n </td>\n <td>\n 66 %\n </td>\n <td>\n 0.13 %\n </td>\n </tr>\n <tr>\n <td>\n 12\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/sweden-population/\">\n Sweden\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 10,099,265\n </td>\n <td>\n 0.63 %\n </td>\n <td>\n 62,886\n </td>\n <td>\n 25\n </td>\n <td>\n 410,340\n </td>\n <td>\n 40,000\n </td>\n <td>\n 1.9\n </td>\n <td>\n 41\n </td>\n <td>\n 88 %\n </td>\n <td>\n 0.13 %\n </td>\n </tr>\n <tr>\n <td>\n 13\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/hungary-population/\">\n Hungary\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 9,660,351\n </td>\n <td>\n -0.25 %\n </td>\n <td>\n -24,328\n </td>\n <td>\n 107\n </td>\n <td>\n 90,530\n </td>\n <td>\n 6,000\n </td>\n <td>\n 1.5\n </td>\n <td>\n 43\n </td>\n <td>\n 72 %\n </td>\n <td>\n 0.12 %\n </td>\n </tr>\n <tr>\n <td>\n 14\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/austria-population/\">\n Austria\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 9,006,398\n </td>\n <td>\n 0.57 %\n </td>\n <td>\n 51,296\n </td>\n <td>\n 109\n </td>\n <td>\n 82,409\n </td>\n <td>\n 65,000\n </td>\n <td>\n 1.5\n </td>\n <td>\n 43\n </td>\n <td>\n 57 %\n </td>\n <td>\n 0.12 %\n </td>\n </tr>\n <tr>\n <td>\n 15\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/bulgaria-population/\">\n Bulgaria\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 6,948,445\n </td>\n <td>\n -0.74 %\n </td>\n <td>\n -51,674\n </td>\n <td>\n 64\n </td>\n <td>\n 108,560\n </td>\n <td>\n -4,800\n </td>\n <td>\n 1.6\n </td>\n <td>\n 45\n </td>\n <td>\n 76 %\n </td>\n <td>\n 0.09 %\n </td>\n </tr>\n <tr>\n <td>\n 16\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/denmark-population/\">\n Denmark\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 5,792,202\n </td>\n <td>\n 0.35 %\n </td>\n <td>\n 20,326\n </td>\n <td>\n 137\n </td>\n <td>\n 42,430\n </td>\n <td>\n 15,200\n </td>\n <td>\n 1.8\n </td>\n <td>\n 42\n </td>\n <td>\n 88 %\n </td>\n <td>\n 0.07 %\n </td>\n </tr>\n <tr>\n <td>\n 17\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/finland-population/\">\n Finland\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 5,540,720\n </td>\n <td>\n 0.15 %\n </td>\n <td>\n 8,564\n </td>\n <td>\n 18\n </td>\n <td>\n 303,890\n </td>\n <td>\n 14,000\n </td>\n <td>\n 1.5\n </td>\n <td>\n 43\n </td>\n <td>\n 86 %\n </td>\n <td>\n 0.07 %\n </td>\n </tr>\n <tr>\n <td>\n 18\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/slovakia-population/\">\n Slovakia\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 5,459,642\n </td>\n <td>\n 0.05 %\n </td>\n <td>\n 2,629\n </td>\n <td>\n 114\n </td>\n <td>\n 48,088\n </td>\n <td>\n 1,485\n </td>\n <td>\n 1.5\n </td>\n <td>\n 41\n </td>\n <td>\n 54 %\n </td>\n <td>\n 0.07 %\n </td>\n </tr>\n <tr>\n <td>\n 19\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/ireland-population/\">\n Ireland\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 4,937,786\n </td>\n <td>\n 1.13 %\n </td>\n <td>\n 55,291\n </td>\n <td>\n 72\n </td>\n <td>\n 68,890\n </td>\n <td>\n 23,604\n </td>\n <td>\n 1.8\n </td>\n <td>\n 38\n </td>\n <td>\n 63 %\n </td>\n <td>\n 0.06 %\n </td>\n </tr>\n <tr>\n <td>\n 20\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/croatia-population/\">\n Croatia\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 4,105,267\n </td>\n <td>\n -0.61 %\n </td>\n <td>\n -25,037\n </td>\n <td>\n 73\n </td>\n <td>\n 55,960\n </td>\n <td>\n -8,001\n </td>\n <td>\n 1.4\n </td>\n <td>\n 44\n </td>\n <td>\n 58 %\n </td>\n <td>\n 0.05 %\n </td>\n </tr>\n <tr>\n <td>\n 21\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/lithuania-population/\">\n Lithuania\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 2,722,289\n </td>\n <td>\n -1.35 %\n </td>\n <td>\n -37,338\n </td>\n <td>\n 43\n </td>\n <td>\n 62,674\n </td>\n <td>\n -32,780\n </td>\n <td>\n 1.7\n </td>\n <td>\n 45\n </td>\n <td>\n 71 %\n </td>\n <td>\n 0.03 %\n </td>\n </tr>\n <tr>\n <td>\n 22\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/slovenia-population/\">\n Slovenia\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 2,078,938\n </td>\n <td>\n 0.01 %\n </td>\n <td>\n 284\n </td>\n <td>\n 103\n </td>\n <td>\n 20,140\n </td>\n <td>\n 2,000\n </td>\n <td>\n 1.6\n </td>\n <td>\n 45\n </td>\n <td>\n 55 %\n </td>\n <td>\n 0.03 %\n </td>\n </tr>\n <tr>\n <td>\n 23\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/latvia-population/\">\n Latvia\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 1,886,198\n </td>\n <td>\n -1.08 %\n </td>\n <td>\n -20,545\n </td>\n <td>\n 30\n </td>\n <td>\n 62,200\n </td>\n <td>\n -14,837\n </td>\n <td>\n 1.7\n </td>\n <td>\n 44\n </td>\n <td>\n 69 %\n </td>\n <td>\n 0.02 %\n </td>\n </tr>\n <tr>\n <td>\n 24\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/estonia-population/\">\n Estonia\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 1,326,535\n </td>\n <td>\n 0.07 %\n </td>\n <td>\n 887\n </td>\n <td>\n 31\n </td>\n <td>\n 42,390\n </td>\n <td>\n 3,911\n </td>\n <td>\n 1.6\n </td>\n <td>\n 42\n </td>\n <td>\n 68 %\n </td>\n <td>\n 0.02 %\n </td>\n </tr>\n <tr>\n <td>\n 25\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/cyprus-population/\">\n Cyprus\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 1,207,359\n </td>\n <td>\n 0.73 %\n </td>\n <td>\n 8,784\n </td>\n <td>\n 131\n </td>\n <td>\n 9,240\n </td>\n <td>\n 5,000\n </td>\n <td>\n 1.3\n </td>\n <td>\n 37\n </td>\n <td>\n 67 %\n </td>\n <td>\n 0.02 %\n </td>\n </tr>\n <tr>\n <td>\n 26\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/luxembourg-population/\">\n Luxembourg\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 625,978\n </td>\n <td>\n 1.66 %\n </td>\n <td>\n 10,249\n </td>\n <td>\n 242\n </td>\n <td>\n 2,590\n </td>\n <td>\n 9,741\n </td>\n <td>\n 1.5\n </td>\n <td>\n 40\n </td>\n <td>\n 88 %\n </td>\n <td>\n 0.01 %\n </td>\n </tr>\n <tr>\n <td>\n 27\n </td>\n <td style=\"font-weight: bold; font-size:15px; text-align:left\">\n <a href=\"/world-population/malta-population/\">\n Malta\n </a>\n </td>\n <td style=\"font-weight: bold;\">\n 441,543\n </td>\n <td>\n 0.27 %\n </td>\n <td>\n 1,171\n </td>\n <td>\n 1,380\n </td>\n <td>\n 320\n </td>\n <td>\n 900\n </td>\n <td>\n 1.5\n </td>\n <td>\n 43\n </td>\n <td>\n 93 %\n </td>\n <td>\n 0.01 %\n </td>\n </tr>\n </tbody>\n </table>\n <br/>\n <div class=\"source-table\">\n Source:\n <strong>\n Worldometer\n </strong>\n (\n <a href=\"/\">\n www.Worldometers.info\n </a>\n )\n <div class=\"source-table-elab\">\n Elaboration of data by United Nations, Department of Economic and Social Affairs, Population Division.\n <a href=\"https://esa.un.org/unpd/wpp/\">\n World Population Prospects: The 2019 Revision\n </a>\n . (Medium-fertility variant).\n </div>\n </div>\n </div>\n <div align=\"center\" id=\"worldometers_728x90_970x90_BTF\">\n <script data-cfasync=\"false\" type=\"text/javascript\">\n freestar.config.enabled_slots.push({ placementName: \"worldometers_728x90_970x90_BTF\", slotId: \"worldometers_728x90_970x90_BTF\" });\n </script>\n </div>\n </div>\n </div>\n </div>\n <script async=\"\" src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\">\n </script>\n <ins class=\"adsbygoogle\" data-ad-client=\"ca-pub-3701697624350410\" data-ad-format=\"auto\" data-ad-slot=\"6995709761\" data-full-width-responsive=\"true\" style=\"display:block\">\n </ins>\n <script>\n (adsbygoogle = window.adsbygoogle || []).push({});\n </script>\n <div style=\"margin-top:40px\">\n </div>\n <script async=\"\" src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\">\n </script>\n <ins class=\"adsbygoogle\" data-ad-client=\"ca-pub-3701697624350410\" data-ad-format=\"auto\" data-ad-slot=\"1743383089\" data-full-width-responsive=\"true\" style=\"display:block\">\n </ins>\n <script>\n (adsbygoogle = window.adsbygoogle || []).push({});\n </script>\n </div>\n <footer>\n <div class=\"footerlinks\">\n <div style=\"margin-bottom:20px\">\n <a href=\"/\">\n <img border=\"0\" class=\"img-footer\" src=\"/img/worldometers-logo-footer.png\"/>\n </a>\n </div>\n <a href=\"/about/\">\n about\n </a>\n |\n <a href=\"/faq/\">\n faq\n </a>\n |\n <a href=\"/languages/\">\n languages\n </a>\n |\n <a href=\"/contact/\">\n contact\n </a>\n </div>\n <ul class=\"list-inline text-center socialbuttons\">\n <li>\n <a data-placement=\"bottom\" data-toggle=\"tooltip\" href=\"/newsletter-subscribe/\" title=\"Newsletter\">\n <i class=\"fa fa-bullhorn fa-round\">\n </i>\n </a>\n </li>\n <li>\n <a href=\"https://twitter.com/Worldometers\">\n <i class=\"fa fa-twitter fa-round\">\n </i>\n </a>\n </li>\n <li>\n <a href=\"https://www.facebook.com/Worldometers.info\">\n <i class=\"fa fa-facebook fa-round\">\n </i>\n </a>\n </li>\n </ul>\n <div class=\"copy\">\n © Copyright Worldometers.info - All rights reserved -\n <a href=\"/disclaimer/\">\n Disclaimer &amp; Privacy Policy\n </a>\n </div>\n </footer>\n <script async=\"async\" src=\"//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-54615fa823b2af68\" type=\"text/javascript\">\n </script>\n <script type=\"text/javascript\">\n (function() { function async_load(script_url){ var protocol = ('https:' == document.location.protocol ? 'https://' : 'http://'); var s = document.createElement('script'); s.src = protocol + script_url; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } bm_website_code = '7849CD9451D34931'; jQuery(document).ready(function(){async_load('asset.pagefair.com/measure.min.js')}); jQuery(document).ready(function(){async_load('asset.pagefair.net/ads.min.js')}); })();\n </script>\n <script type=\"text/javascript\">\n var _qevents = _qevents || [];\n(function() {\nvar elem = document.createElement('script');\nelem.src = (document.location.protocol == \"https:\" ? \"https://secure\" : \"http://edge\") + \".quantserve.com/quant.js\";\nelem.async = true;\nelem.type = \"text/javascript\";\nvar scpt = document.getElementsByTagName('script')[0];\nscpt.parentNode.insertBefore(elem, scpt);\n})();\n_qevents.push({\nqacct:\"p-Pd9JxUkvV0m7q\"\n});\n </script>\n <noscript>\n <div style=\"display:none;\">\n <img alt=\"Quantcast\" border=\"0\" height=\"1\" src=\"//pixel.quantserve.com/pixel/p-Pd9JxUkvV0m7q.gif\" width=\"1\"/>\n </div>\n </noscript>\n </body>\n</html>\n" ] ], [ [ "![](../images/population_EU.png)", "_____no_output_____" ] ], [ [ "# Obtain information from tag <table>\n# table = \n# table", "_____no_output_____" ], [ "# tip: prettify table to see better the information you are looking for\n", "_____no_output_____" ], [ "# Obtain column names within tag <th> with attribute col\n# list_col = \n# Clean text\n# list_col = \n# list_col", "_____no_output_____" ], [ "# Create a dataframe\n# EU_population_data = ", "_____no_output_____" ] ], [ [ "From the table prettify we see that the rows are located under tag <tr> and items are located under tag <td> . Use this info and fill your dataframe.", "_____no_output_____" ] ], [ [ "# Create a for loop to fill EU_population_data\n", "_____no_output_____" ], [ "# EU_population_data", "_____no_output_____" ] ], [ [ "## Example 03: Extract information from hyperlink\n\nApplying web scraping to [`https://jadsmkbdatalab.nl/voorbeeldcases/`](https://jadsmkbdatalab.nl/voorbeeldcases/).\n\nRight click to `inspect` element in the webpage. Notice that the information we look for is between h3's...\n\n![](../images/mkb_inspect_page.PNG)", "_____no_output_____" ], [ "In this example, you will face something new. Before doing as usual and using the parser function check the response using requests.\n\nWhich code did you get?\n\nTIP: Check this [stackoverflow answer](https://stackoverflow.com/questions/38489386/python-requests-403-forbidden)", "_____no_output_____" ] ], [ [ "url_03 = 'https://jadsmkbdatalab.nl/voorbeeldcases/'\n# response = \n# response", "_____no_output_____" ], [ "# Modify the steps we have learn to solve the issue\n\n# get response\n\n\n# get the content of the response\n\n\n# parse webpage\n", "_____no_output_____" ], [ "# print(parser_03.prettify())", "_____no_output_____" ], [ "# find hyperlinks\n# links = \n# links", "_____no_output_____" ], [ "# Obtain url of the links\n", "_____no_output_____" ] ], [ [ "Updating function to include headers...", "_____no_output_____" ] ], [ [ "def parse_website(url):\n \"\"\" \n Parse content of a website\n \n Args:\n url (str): url of the website of which we want to acess the content \n \n Return:\n parser: representation of the document as a nested data structure.\n \"\"\"\n # Send request and catch response\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)\"}\n response = requests.get(url, headers=headers)\n\n # get the content of the response\n content = response.content\n\n # parse webpage\n parser = BeautifulSoup(content, \"lxml\")\n \n return parser ", "_____no_output_____" ], [ "# parse and prettify one of the obtained urls\n# parser_03_0 = ", "_____no_output_____" ], [ "# find all paragraphs within parser_03_0\n# paragraphs = \n# paragraphs", "_____no_output_____" ], [ "# Obtain text of paragraphs\n", "_____no_output_____" ], [ "# saving the content of this page\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4af16df2d841eded3df08e8c4a0ecb7261c88a0e
97,783
ipynb
Jupyter Notebook
45_Neural_Machine_Translation_with_Translation/45_Neural_Machine_Translation_with_Translation.ipynb
mhuzaifadev/deeplearningmasterclass
c79217969b423f42c6800870dffd67cb6ebc2823
[ "MIT" ]
17
2020-12-03T09:47:53.000Z
2022-02-13T21:22:12.000Z
45_Neural_Machine_Translation_with_Translation/45_Neural_Machine_Translation_with_Translation.ipynb
mhuzaifadev/deeplearningmasterclass
c79217969b423f42c6800870dffd67cb6ebc2823
[ "MIT" ]
null
null
null
45_Neural_Machine_Translation_with_Translation/45_Neural_Machine_Translation_with_Translation.ipynb
mhuzaifadev/deeplearningmasterclass
c79217969b423f42c6800870dffd67cb6ebc2823
[ "MIT" ]
21
2020-12-05T15:21:16.000Z
2022-02-07T03:47:34.000Z
97,783
97,783
0.847918
[ [ [ "# **Neural machine translation with attention**", "_____no_output_____" ], [ "Today we will train a sequence to sequence (seq2seq) model for Spanish to English translation. This is an advanced example that assumes some knowledge of sequence to sequence models.\n\nAfter training the model in this notebook, you will be able to input a Spanish sentence, such as *\"¿todavia estan en casa?\"*, and return the English translation: *\"are you still at home?\"*\n\nThe translation quality is reasonable for a toy example, but the generated attention plot is perhaps more interesting. This shows which parts of the input sentence has the model's attention while translating:\n\n<img src=\"https://tensorflow.org/images/spanish-english.png\" alt=\"spanish-english attention plot\">\n\nNote: This example takes approximately 10 minutes to run on a single P100 GPU.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom sklearn.model_selection import train_test_split\n\nimport unicodedata\nimport re\nimport numpy as np\nimport os\nimport io\nimport time", "_____no_output_____" ] ], [ [ "## **Download and prepare the dataset**\n\nWe'll use a language dataset provided by http://www.manythings.org/anki/. This dataset contains language translation pairs in the format:\n\n```\nMay I borrow this book?\t¿Puedo tomar prestado este libro?\n```\n\nThere are a variety of languages available, but we'll use the English-Spanish dataset. For convenience, we've hosted a copy of this dataset on Google Cloud, but you can also download your own copy. After downloading the dataset, here are the steps we'll take to prepare the data:\n\n1. Add a *start* and *end* token to each sentence.\n2. Clean the sentences by removing special characters.\n3. Create a word index and reverse word index (dictionaries mapping from word → id and id → word).\n4. Pad each sentence to a maximum length.", "_____no_output_____" ] ], [ [ "# Download the file\npath_to_zip = tf.keras.utils.get_file(\n 'spa-eng.zip', origin='http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip',\n extract=True)\n\npath_to_file = os.path.dirname(path_to_zip)+\"/spa-eng/spa.txt\"", "Downloading data from http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip\n2646016/2638744 [==============================] - 0s 0us/step\n" ], [ "# Converts the unicode file to ascii\ndef unicode_to_ascii(s):\n return ''.join(c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn')\n\n\ndef preprocess_sentence(w):\n w = unicode_to_ascii(w.lower().strip())\n\n # creating a space between a word and the punctuation following it\n # eg: \"he is a boy.\" => \"he is a boy .\"\n # Reference:- https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation\n w = re.sub(r\"([?.!,¿])\", r\" \\1 \", w)\n w = re.sub(r'[\" \"]+', \" \", w)\n\n # replacing everything with space except (a-z, A-Z, \".\", \"?\", \"!\", \",\")\n w = re.sub(r\"[^a-zA-Z?.!,¿]+\", \" \", w)\n\n w = w.strip()\n\n # adding a start and an end token to the sentence\n # so that the model know when to start and stop predicting.\n w = '<start> ' + w + ' <end>'\n return w", "_____no_output_____" ], [ "en_sentence = u\"May I borrow this book?\"\nsp_sentence = u\"¿Puedo tomar prestado este libro?\"\nprint(preprocess_sentence(en_sentence))\nprint(preprocess_sentence(sp_sentence).encode('utf-8'))", "<start> may i borrow this book ? <end>\nb'<start> \\xc2\\xbf puedo tomar prestado este libro ? <end>'\n" ], [ "# 1. Remove the accents\n# 2. Clean the sentences\n# 3. Return word pairs in the format: [ENGLISH, SPANISH]\ndef create_dataset(path, num_examples):\n lines = io.open(path, encoding='UTF-8').read().strip().split('\\n')\n\n word_pairs = [[preprocess_sentence(w) for w in l.split('\\t')] for l in lines[:num_examples]]\n\n return zip(*word_pairs)", "_____no_output_____" ], [ "en, sp = create_dataset(path_to_file, None)\nprint(en[-1])\nprint(sp[-1])", "<start> if you want to sound like a native speaker , you must be willing to practice saying the same sentence over and over in the same way that banjo players practice the same phrase over and over until they can play it correctly and at the desired tempo . <end>\n<start> si quieres sonar como un hablante nativo , debes estar dispuesto a practicar diciendo la misma frase una y otra vez de la misma manera en que un musico de banjo practica el mismo fraseo una y otra vez hasta que lo puedan tocar correctamente y en el tiempo esperado . <end>\n" ], [ "def tokenize(lang):\n lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(filters='')\n lang_tokenizer.fit_on_texts(lang)\n\n tensor = lang_tokenizer.texts_to_sequences(lang)\n\n tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor,\n padding='post')\n\n return tensor, lang_tokenizer", "_____no_output_____" ], [ "def load_dataset(path, num_examples=None):\n # creating cleaned input, output pairs\n targ_lang, inp_lang = create_dataset(path, num_examples)\n\n input_tensor, inp_lang_tokenizer = tokenize(inp_lang)\n target_tensor, targ_lang_tokenizer = tokenize(targ_lang)\n\n return input_tensor, target_tensor, inp_lang_tokenizer, targ_lang_tokenizer", "_____no_output_____" ] ], [ [ "### **Limit the size of the dataset to experiment faster (optional)**\n\nTraining on the complete dataset of >100,000 sentences will take a long time. To train faster, we can limit the size of the dataset to 30,000 sentences (of course, translation quality degrades with less data):", "_____no_output_____" ] ], [ [ "# Try experimenting with the size of that dataset\nnum_examples = 100000\ninput_tensor, target_tensor, inp_lang, targ_lang = load_dataset(path_to_file, num_examples)\n\n# Calculate max_length of the target tensors\nmax_length_targ, max_length_inp = target_tensor.shape[1], input_tensor.shape[1]", "_____no_output_____" ], [ "# Creating training and validation sets using an 80-20 split\ninput_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)\n\n# Show length\nprint(len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val))", "80000 80000 20000 20000\n" ], [ "def convert(lang, tensor):\n for t in tensor:\n if t!=0:\n print (\"%d ----> %s\" % (t, lang.index_word[t]))", "_____no_output_____" ], [ "print (\"Input Language; index to word mapping\")\nconvert(inp_lang, input_tensor_train[0])\nprint ()\nprint (\"Target Language; index to word mapping\")\nconvert(targ_lang, target_tensor_train[0])", "Input Language; index to word mapping\n1 ----> <start>\n16 ----> me\n244 ----> dejo\n21 ----> una\n2938 ----> nota\n3 ----> .\n2 ----> <end>\n\nTarget Language; index to word mapping\n1 ----> <start>\n26 ----> she\n172 ----> left\n19 ----> me\n10 ----> a\n2603 ----> note\n3 ----> .\n2 ----> <end>\n" ] ], [ [ "### **Create a tf.data dataset**", "_____no_output_____" ] ], [ [ "BUFFER_SIZE = len(input_tensor_train)\nBATCH_SIZE = 64\nsteps_per_epoch = len(input_tensor_train)//BATCH_SIZE\nembedding_dim = 256\nunits = 1024 # better if embedding_dim*4 \nvocab_inp_size = len(inp_lang.word_index)+1\nvocab_tar_size = len(targ_lang.word_index)+1\n\ndataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)\ndataset = dataset.batch(BATCH_SIZE, drop_remainder=True)", "_____no_output_____" ], [ "example_input_batch, example_target_batch = next(iter(dataset))\nexample_input_batch.shape, example_target_batch.shape", "_____no_output_____" ] ], [ [ "## **Write the encoder and decoder model**\n\nImplement an encoder-decoder model with attention which you can read about in the TensorFlow [Neural Machine Translation (seq2seq) tutorial](https://github.com/tensorflow/nmt). This example uses a more recent set of APIs. This notebook implements the [attention equations](https://github.com/tensorflow/nmt#background-on-the-attention-mechanism) from the seq2seq tutorial. The following diagram shows that each input words is assigned a weight by the attention mechanism which is then used by the decoder to predict the next word in the sentence. The below picture and formulas are an example of attention mechanism from [Luong's paper](https://arxiv.org/abs/1508.04025v5). \n\n<img src=\"https://www.tensorflow.org/images/seq2seq/attention_mechanism.jpg\" width=\"500\" alt=\"attention mechanism\">\n\nThe input is put through an encoder model which gives us the encoder output of shape *(batch_size, max_length, hidden_size)* and the encoder hidden state of shape *(batch_size, hidden_size)*.\n\nHere are the equations that are implemented:\n\n<img src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_0.jpg\" alt=\"attention equation 0\" width=\"800\">\n<img src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_1.jpg\" alt=\"attention equation 1\" width=\"800\">\n\nThis tutorial uses [Bahdanau attention](https://arxiv.org/pdf/1409.0473.pdf) for the encoder. Let's decide on notation before writing the simplified form:\n\n* FC = Fully connected (dense) layer\n* EO = Encoder output\n* H = hidden state\n* X = input to the decoder\n\nAnd the pseudo-code:\n\n* `score = FC(tanh(FC(EO) + FC(H)))`\n* `attention weights = softmax(score, axis = 1)`. Softmax by default is applied on the last axis but here we want to apply it on the *1st axis*, since the shape of score is *(batch_size, max_length, hidden_size)*. `Max_length` is the length of our input. Since we are trying to assign a weight to each input, softmax should be applied on that axis.\n* `context vector = sum(attention weights * EO, axis = 1)`. Same reason as above for choosing axis as 1.\n* `embedding output` = The input to the decoder X is passed through an embedding layer.\n* `merged vector = concat(embedding output, context vector)`\n* This merged vector is then given to the GRU\n\nThe shapes of all the vectors at each step have been specified in the comments in the code:", "_____no_output_____" ] ], [ [ "class Encoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):\n super(Encoder, self).__init__()\n self.batch_sz = batch_sz\n self.enc_units = enc_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.enc_units,\n return_sequences=True,\n return_state=True,\n recurrent_initializer='glorot_uniform')\n\n def call(self, x, hidden):\n x = self.embedding(x)\n output, state = self.gru(x, initial_state = hidden)\n return output, state\n\n def initialize_hidden_state(self):\n return tf.zeros((self.batch_sz, self.enc_units))", "_____no_output_____" ], [ "encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n\n# sample input\nsample_hidden = encoder.initialize_hidden_state()\nsample_output, sample_hidden = encoder(example_input_batch, sample_hidden)\nprint ('Encoder output shape: (batch size, sequence length, units) {}'.format(sample_output.shape))\nprint ('Encoder Hidden state shape: (batch size, units) {}'.format(sample_hidden.shape))", "Encoder output shape: (batch size, sequence length, units) (64, 20, 1024)\nEncoder Hidden state shape: (batch size, units) (64, 1024)\n" ], [ "class BahdanauAttention(tf.keras.layers.Layer):\n def __init__(self, units):\n super(BahdanauAttention, self).__init__()\n self.W1 = tf.keras.layers.Dense(units)\n self.W2 = tf.keras.layers.Dense(units)\n self.V = tf.keras.layers.Dense(1)\n\n def call(self, query, values):\n # query hidden state shape == (batch_size, hidden size)\n # query_with_time_axis shape == (batch_size, 1, hidden size)\n # values shape == (batch_size, max_len, hidden size)\n # we are doing this to broadcast addition along the time axis to calculate the score\n query_with_time_axis = tf.expand_dims(query, 1)\n\n # score shape == (batch_size, max_length, 1)\n # we get 1 at the last axis because we are applying score to self.V\n # the shape of the tensor before applying self.V is (batch_size, max_length, units)\n score = self.V(tf.nn.tanh(\n self.W1(query_with_time_axis) + self.W2(values)))\n\n # attention_weights shape == (batch_size, max_length, 1)\n attention_weights = tf.nn.softmax(score, axis=1)\n\n # context_vector shape after sum == (batch_size, hidden_size)\n context_vector = attention_weights * values\n context_vector = tf.reduce_sum(context_vector, axis=1)\n\n return context_vector, attention_weights", "_____no_output_____" ], [ "attention_layer = BahdanauAttention(10)\nattention_result, attention_weights = attention_layer(sample_hidden, sample_output)\n\nprint(\"Attention result shape: (batch size, units) {}\".format(attention_result.shape))\nprint(\"Attention weights shape: (batch_size, sequence_length, 1) {}\".format(attention_weights.shape))", "Attention result shape: (batch size, units) (64, 1024)\nAttention weights shape: (batch_size, sequence_length, 1) (64, 20, 1)\n" ], [ "class Decoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):\n super(Decoder, self).__init__()\n self.batch_sz = batch_sz\n self.dec_units = dec_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.dec_units,\n return_sequences=True,\n return_state=True,\n recurrent_initializer='glorot_uniform')\n self.fc = tf.keras.layers.Dense(vocab_size)\n\n # used for attention\n self.attention = BahdanauAttention(self.dec_units)\n\n def call(self, x, hidden, enc_output):\n # enc_output shape == (batch_size, max_length, hidden_size)\n context_vector, attention_weights = self.attention(hidden, enc_output)\n\n # x shape after passing through embedding == (batch_size, 1, embedding_dim)\n x = self.embedding(x)\n\n # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)\n x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n\n # passing the concatenated vector to the GRU\n output, state = self.gru(x)\n\n # output shape == (batch_size * 1, hidden_size)\n output = tf.reshape(output, (-1, output.shape[2]))\n\n # output shape == (batch_size, vocab)\n x = self.fc(output)\n\n return x, state, attention_weights", "_____no_output_____" ], [ "decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)\n\nsample_decoder_output, _, _ = decoder(tf.random.uniform((BATCH_SIZE, 1)),\n sample_hidden, sample_output)\n\nprint ('Decoder output shape: (batch_size, vocab size) {}'.format(sample_decoder_output.shape))", "Decoder output shape: (batch_size, vocab size) (64, 10785)\n" ] ], [ [ "## **Define the optimizer and the loss function**", "_____no_output_____" ] ], [ [ "optimizer = tf.keras.optimizers.Adam()\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True, reduction='none')\n\ndef loss_function(real, pred):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_mean(loss_)", "_____no_output_____" ] ], [ [ "## **Checkpoints (Object-based saving)**", "_____no_output_____" ] ], [ [ "checkpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(optimizer=optimizer,\n encoder=encoder,\n decoder=decoder)", "_____no_output_____" ] ], [ [ "## **Training**\n\n1. Pass the *input* through the *encoder* which return *encoder output* and the *encoder hidden state*.\n2. The encoder output, encoder hidden state and the decoder input (which is the *start token*) is passed to the decoder.\n3. The decoder returns the *predictions* and the *decoder hidden state*.\n4. The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss.\n5. Use *teacher forcing* to decide the next input to the decoder.\n6. *Teacher forcing* is the technique where the *target word* is passed as the *next input* to the decoder.\n7. The final step is to calculate the gradients and apply it to the optimizer and backpropagate.", "_____no_output_____" ] ], [ [ "@tf.function\ndef train_step(inp, targ, enc_hidden):\n loss = 0\n\n with tf.GradientTape() as tape:\n enc_output, enc_hidden = encoder(inp, enc_hidden)\n\n dec_hidden = enc_hidden\n\n dec_input = tf.expand_dims([targ_lang.word_index['<start>']] * BATCH_SIZE, 1)\n\n # Teacher forcing - feeding the target as the next input\n for t in range(1, targ.shape[1]):\n # passing enc_output to the decoder\n predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)\n\n loss += loss_function(targ[:, t], predictions)\n\n # using teacher forcing\n dec_input = tf.expand_dims(targ[:, t], 1)\n\n batch_loss = (loss / int(targ.shape[1]))\n\n variables = encoder.trainable_variables + decoder.trainable_variables\n\n gradients = tape.gradient(loss, variables)\n\n optimizer.apply_gradients(zip(gradients, variables))\n\n return batch_loss", "_____no_output_____" ], [ "EPOCHS = 10\n\nfor epoch in range(EPOCHS):\n start = time.time()\n\n enc_hidden = encoder.initialize_hidden_state()\n total_loss = 0\n\n for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)):\n batch_loss = train_step(inp, targ, enc_hidden)\n total_loss += batch_loss\n\n if batch % 100 == 0:\n print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1,\n batch,\n batch_loss.numpy()))\n # saving (checkpoint) the model every 2 epochs\n if (epoch + 1) % 2 == 0:\n checkpoint.save(file_prefix = checkpoint_prefix)\n\n print('Epoch {} Loss {:.4f}'.format(epoch + 1,\n total_loss / steps_per_epoch))\n print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))", "Epoch 1 Batch 0 Loss 4.3101\nEpoch 1 Batch 100 Loss 2.1835\nEpoch 1 Batch 200 Loss 1.9136\nEpoch 1 Batch 300 Loss 1.7904\nEpoch 1 Batch 400 Loss 1.8162\nEpoch 1 Batch 500 Loss 1.6509\nEpoch 1 Batch 600 Loss 1.7724\nEpoch 1 Batch 700 Loss 1.5567\nEpoch 1 Batch 800 Loss 1.5459\nEpoch 1 Batch 900 Loss 1.5093\nEpoch 1 Batch 1000 Loss 1.5608\nEpoch 1 Batch 1100 Loss 1.5432\nEpoch 1 Batch 1200 Loss 1.3583\nEpoch 1 Loss 1.7478\nTime taken for 1 epoch 226.39287781715393 sec\n\nEpoch 2 Batch 0 Loss 1.4621\nEpoch 2 Batch 100 Loss 1.3572\nEpoch 2 Batch 200 Loss 1.4966\nEpoch 2 Batch 300 Loss 1.5324\nEpoch 2 Batch 400 Loss 1.3437\nEpoch 2 Batch 500 Loss 1.2058\nEpoch 2 Batch 600 Loss 1.2514\nEpoch 2 Batch 700 Loss 1.1602\nEpoch 2 Batch 800 Loss 1.3613\nEpoch 2 Batch 900 Loss 1.1640\nEpoch 2 Batch 1000 Loss 1.1508\nEpoch 2 Batch 1100 Loss 1.1516\nEpoch 2 Batch 1200 Loss 0.9188\nEpoch 2 Loss 1.2616\nTime taken for 1 epoch 203.60052490234375 sec\n\nEpoch 3 Batch 0 Loss 0.7583\nEpoch 3 Batch 100 Loss 0.8749\nEpoch 3 Batch 200 Loss 0.7527\nEpoch 3 Batch 300 Loss 0.8152\nEpoch 3 Batch 400 Loss 0.7485\nEpoch 3 Batch 500 Loss 0.6608\nEpoch 3 Batch 600 Loss 0.6249\nEpoch 3 Batch 700 Loss 0.6902\nEpoch 3 Batch 800 Loss 0.7010\nEpoch 3 Batch 900 Loss 0.6105\nEpoch 3 Batch 1000 Loss 0.6048\nEpoch 3 Batch 1100 Loss 0.6409\nEpoch 3 Batch 1200 Loss 0.5786\nEpoch 3 Loss 0.7268\nTime taken for 1 epoch 202.2330937385559 sec\n\nEpoch 4 Batch 0 Loss 0.4297\nEpoch 4 Batch 100 Loss 0.3452\nEpoch 4 Batch 200 Loss 0.4179\nEpoch 4 Batch 300 Loss 0.4041\nEpoch 4 Batch 400 Loss 0.4816\nEpoch 4 Batch 500 Loss 0.4958\nEpoch 4 Batch 600 Loss 0.3788\nEpoch 4 Batch 700 Loss 0.5111\nEpoch 4 Batch 800 Loss 0.4659\nEpoch 4 Batch 900 Loss 0.5376\nEpoch 4 Batch 1000 Loss 0.4476\nEpoch 4 Batch 1100 Loss 0.4792\nEpoch 4 Batch 1200 Loss 0.4094\nEpoch 4 Loss 0.4417\nTime taken for 1 epoch 204.70326709747314 sec\n\nEpoch 5 Batch 0 Loss 0.2785\nEpoch 5 Batch 100 Loss 0.2550\nEpoch 5 Batch 200 Loss 0.2812\nEpoch 5 Batch 300 Loss 0.2758\nEpoch 5 Batch 400 Loss 0.2687\nEpoch 5 Batch 500 Loss 0.2375\nEpoch 5 Batch 600 Loss 0.2610\nEpoch 5 Batch 700 Loss 0.2824\nEpoch 5 Batch 800 Loss 0.2989\nEpoch 5 Batch 900 Loss 0.4012\nEpoch 5 Batch 1000 Loss 0.2312\nEpoch 5 Batch 1100 Loss 0.2693\nEpoch 5 Batch 1200 Loss 0.2780\nEpoch 5 Loss 0.2935\nTime taken for 1 epoch 204.42119240760803 sec\n\nEpoch 6 Batch 0 Loss 0.2151\nEpoch 6 Batch 100 Loss 0.1535\nEpoch 6 Batch 200 Loss 0.2129\nEpoch 6 Batch 300 Loss 0.2031\nEpoch 6 Batch 400 Loss 0.2166\nEpoch 6 Batch 500 Loss 0.1861\nEpoch 6 Batch 600 Loss 0.2354\nEpoch 6 Batch 700 Loss 0.1620\nEpoch 6 Batch 800 Loss 0.2374\nEpoch 6 Batch 900 Loss 0.2232\nEpoch 6 Batch 1000 Loss 0.1962\nEpoch 6 Batch 1100 Loss 0.2356\nEpoch 6 Batch 1200 Loss 0.1989\nEpoch 6 Loss 0.2095\nTime taken for 1 epoch 205.0025978088379 sec\n\nEpoch 7 Batch 0 Loss 0.1371\nEpoch 7 Batch 100 Loss 0.1164\nEpoch 7 Batch 200 Loss 0.1277\nEpoch 7 Batch 300 Loss 0.1727\nEpoch 7 Batch 400 Loss 0.1305\nEpoch 7 Batch 500 Loss 0.1394\nEpoch 7 Batch 600 Loss 0.1328\nEpoch 7 Batch 700 Loss 0.1682\nEpoch 7 Batch 800 Loss 0.1840\nEpoch 7 Batch 900 Loss 0.1718\nEpoch 7 Batch 1000 Loss 0.1862\nEpoch 7 Batch 1100 Loss 0.1532\nEpoch 7 Batch 1200 Loss 0.1742\nEpoch 7 Loss 0.1574\nTime taken for 1 epoch 202.98309755325317 sec\n\nEpoch 8 Batch 0 Loss 0.1412\nEpoch 8 Batch 100 Loss 0.1007\nEpoch 8 Batch 200 Loss 0.1546\nEpoch 8 Batch 300 Loss 0.1411\nEpoch 8 Batch 400 Loss 0.0960\nEpoch 8 Batch 500 Loss 0.1044\nEpoch 8 Batch 600 Loss 0.1356\nEpoch 8 Batch 700 Loss 0.1345\nEpoch 8 Batch 800 Loss 0.1240\nEpoch 8 Batch 900 Loss 0.1104\nEpoch 8 Batch 1000 Loss 0.1065\nEpoch 8 Batch 1100 Loss 0.0834\nEpoch 8 Batch 1200 Loss 0.1322\nEpoch 8 Loss 0.1229\nTime taken for 1 epoch 202.54697346687317 sec\n\nEpoch 9 Batch 0 Loss 0.1107\nEpoch 9 Batch 100 Loss 0.0714\nEpoch 9 Batch 200 Loss 0.0895\nEpoch 9 Batch 300 Loss 0.1004\nEpoch 9 Batch 400 Loss 0.0790\nEpoch 9 Batch 500 Loss 0.1057\nEpoch 9 Batch 600 Loss 0.1001\nEpoch 9 Batch 700 Loss 0.1199\nEpoch 9 Batch 800 Loss 0.0900\nEpoch 9 Batch 900 Loss 0.1271\nEpoch 9 Batch 1000 Loss 0.1340\nEpoch 9 Batch 1100 Loss 0.1445\nEpoch 9 Batch 1200 Loss 0.1028\nEpoch 9 Loss 0.1008\nTime taken for 1 epoch 201.72758197784424 sec\n\nEpoch 10 Batch 0 Loss 0.0982\nEpoch 10 Batch 100 Loss 0.0788\nEpoch 10 Batch 200 Loss 0.0621\nEpoch 10 Batch 300 Loss 0.0951\nEpoch 10 Batch 400 Loss 0.0766\nEpoch 10 Batch 500 Loss 0.0659\nEpoch 10 Batch 600 Loss 0.0896\nEpoch 10 Batch 700 Loss 0.0786\nEpoch 10 Batch 800 Loss 0.1108\nEpoch 10 Batch 900 Loss 0.1249\nEpoch 10 Batch 1000 Loss 0.0978\nEpoch 10 Batch 1100 Loss 0.1432\nEpoch 10 Batch 1200 Loss 0.1067\nEpoch 10 Loss 0.0846\nTime taken for 1 epoch 202.13339138031006 sec\n\n" ] ], [ [ "## **Translate**\n\n* The evaluate function is similar to the training loop, except we don't use *teacher forcing* here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output.\n* Stop predicting when the model predicts the *end token*.\n* And store the *attention weights for every time step*.\n\nNote: The encoder output is calculated only once for one input.", "_____no_output_____" ] ], [ [ "def evaluate(sentence):\n attention_plot = np.zeros((max_length_targ, max_length_inp))\n\n sentence = preprocess_sentence(sentence)\n\n inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]\n inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],\n maxlen=max_length_inp,\n padding='post')\n inputs = tf.convert_to_tensor(inputs)\n\n result = ''\n\n hidden = [tf.zeros((1, units))]\n enc_out, enc_hidden = encoder(inputs, hidden)\n\n dec_hidden = enc_hidden\n dec_input = tf.expand_dims([targ_lang.word_index['<start>']], 0)\n\n for t in range(max_length_targ):\n predictions, dec_hidden, attention_weights = decoder(dec_input,\n dec_hidden,\n enc_out)\n\n # storing the attention weights to plot later on\n attention_weights = tf.reshape(attention_weights, (-1, ))\n attention_plot[t] = attention_weights.numpy()\n\n predicted_id = tf.argmax(predictions[0]).numpy()\n\n result += targ_lang.index_word[predicted_id] + ' '\n\n if targ_lang.index_word[predicted_id] == '<end>':\n return result, sentence, attention_plot\n\n # the predicted ID is fed back into the model\n dec_input = tf.expand_dims([predicted_id], 0)\n\n return result, sentence, attention_plot", "_____no_output_____" ], [ "# function for plotting the attention weights\ndef plot_attention(attention, sentence, predicted_sentence):\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1)\n ax.matshow(attention, cmap='viridis')\n\n fontdict = {'fontsize': 14}\n\n ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)\n ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)\n\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n plt.show()", "_____no_output_____" ], [ "def translate(sentence):\n result, sentence, attention_plot = evaluate(sentence)\n\n print('Input: %s' % (sentence))\n print('Predicted translation: {}'.format(result))\n\n attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]\n plot_attention(attention_plot, sentence.split(' '), result.split(' '))", "_____no_output_____" ] ], [ [ "## **Restore the latest checkpoint and test**", "_____no_output_____" ] ], [ [ "# restoring the latest checkpoint in checkpoint_dir\ncheckpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))", "_____no_output_____" ], [ "translate(u'hace mucho frio aqui.')", "Input: <start> hace mucho frio aqui . <end>\nPredicted translation: it s very cold . <end> \n" ], [ "translate(u'esta es mi vida.')", "Input: <start> esta es mi vida . <end>\nPredicted translation: this is my life . <end> \n" ], [ "translate(u'¿todavia estan en casa?')", "Input: <start> ¿ todavia estan en casa ? <end>\nPredicted translation: are you still at home ? <end> \n" ], [ "# as near translation\ntranslate(u'trata de averiguarlo.')", "Input: <start> trata de averiguarlo . <end>\nPredicted translation: try to figure it out . <end> \n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4af17e05abfc2adf471ee7e5a8a3a49108e700af
30,625
ipynb
Jupyter Notebook
compareSpacingSpell.ipynb
JeongCheck/SentimentAnalysis
57de4be4e9d73794270bb6cd7d63243d8f52bfae
[ "MIT" ]
2
2022-03-11T13:45:03.000Z
2022-03-21T13:25:37.000Z
compareSpacingSpell.ipynb
sonak-lll/SentimentAnalysis
1ba3c77b4552d21d3cdd09e7bf5c75413987101a
[ "MIT" ]
null
null
null
compareSpacingSpell.ipynb
sonak-lll/SentimentAnalysis
1ba3c77b4552d21d3cdd09e7bf5c75413987101a
[ "MIT" ]
5
2021-05-25T08:14:45.000Z
2021-06-16T06:53:23.000Z
27.689873
266
0.458057
[ [ [ "# Predict google map review dataset \n## model\n- kcbert\n- fine-tuned with naver shopping review dataset (200,000개)\n- train 5 epochs\n- 0.97 accuracy\n\n## dataset\n- google map review of tourist places in Daejeon, Korea ", "_____no_output_____" ] ], [ [ "import torch\nfrom torch import nn, Tensor\nfrom torch.optim import Optimizer\nfrom torch.utils.data import DataLoader, RandomSampler, DistributedSampler, random_split\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\nfrom torch.nn import CrossEntropyLoss\nfrom pytorch_lightning.core.lightning import LightningModule \nfrom pytorch_lightning import LightningModule, Trainer, seed_everything\nfrom pytorch_lightning.metrics.functional import accuracy, precision, recall\nfrom transformers import AdamW, BertForSequenceClassification, AdamW, BertConfig, AutoTokenizer, BertTokenizer, TrainingArguments\nfrom keras.preprocessing.sequence import pad_sequences\n\n\nimport random\nimport numpy as np \n\nimport time\nimport datetime\nimport pandas as pd\nimport os\nfrom tqdm import tqdm\n\n\nimport pandas as pd\nfrom transformers import AutoTokenizer, AutoModelWithLMHead\nfrom keras.preprocessing.sequence import pad_sequences", "_____no_output_____" ], [ "if torch.cuda.is_available(): \n device = torch.device(\"cuda\")\n\n print('There are %d GPU(s) available.' % torch.cuda.device_count())\n print('We will use the GPU:', torch.cuda.get_device_name(0))\n\nelse:\n print('No GPU available, using the CPU instead.')\n device = torch.device(\"cpu\")", "There are 1 GPU(s) available.\nWe will use the GPU: GeForce RTX 2070\n" ], [ "pj_path = os.getenv('HOME') + '/Projects/JeongCheck'\ndata_path = pj_path + '/compare'", "_____no_output_____" ], [ "data_list = os.listdir(data_path)\nprint(len(data_list))\ndata_list", "2\n" ], [ "file_list = os.listdir(data_path)\nfile_list", "_____no_output_____" ], [ "spacing = pd.read_csv(data_path + f'/{file_list[0]}')\nspell = pd.read_csv(data_path + f'/{file_list[1]}')", "_____no_output_____" ], [ "spacing.head()", "_____no_output_____" ], [ "spell.head()", "_____no_output_____" ], [ "len(spacing), len(spell)", "_____no_output_____" ], [ "print(spacing.isna().sum())\nprint('\\n')\nprint(spell.isna().sum())", "name 0\nratings 0\ndate 0\ncomment 0\nsearch 0\nkeyword 0\nlabel 0\ndtype: int64\n\n\nname 0\nratings 0\ndate 0\ncomment 0\nsearch 0\nkeyword 0\nlabel 0\ndtype: int64\n" ], [ "print(set(spacing.label))\nprint(set(spell.label))", "{0, 1, 2}\n{0, 1, 2}\n" ], [ "print(len(spacing[spacing.label==2]))\nprint(len(spell[spell.label==2]))", "32\n34\n" ], [ "test_spac = spacing.copy()\ntest_spel = spell.copy()\n\nprint(len(test_spac), len(test_spel))", "8421 8420\n" ] ], [ [ "중립 데이터 제외", "_____no_output_____" ] ], [ [ "test_spac = test_spac[test_spac.label != 2]\nprint(len(test_spac))", "8389\n" ], [ "test_spel = test_spel[test_spel.label != 2]\nprint(len(test_spel))", "8386\n" ], [ "from transformers import BertForSequenceClassification, AdamW, BertConfig\n\ntokenizer = AutoTokenizer.from_pretrained(\"beomi/kcbert-base\")", "_____no_output_____" ], [ "# Load BertForSequenceClassification, the pretrained BERT model with a single \n# linear classification layer on top. \nmodel = BertForSequenceClassification.from_pretrained(\n pj_path + \"/bert_model/checkpoint-2000\",\n num_labels = 2, \n \n output_attentions = False, # Whether the model returns attentions weights.\n output_hidden_states = False, # Whether the model returns all hidden-states.\n)", "_____no_output_____" ], [ "params = list(model.named_parameters())\n\nprint('The BERT model has {:} different named parameters.\\n'.format(len(params)))\n\nprint('==== Embedding Layer ====\\n')\n\nfor p in params[0:5]:\n print(\"{:<55} {:>12}\".format(p[0], str(tuple(p[1].size()))))\n\nprint('\\n==== First Transformer ====\\n')\n\nfor p in params[5:21]:\n print(\"{:<55} {:>12}\".format(p[0], str(tuple(p[1].size()))))\n\nprint('\\n==== Output Layer ====\\n')\n\nfor p in params[-4:]:\n print(\"{:<55} {:>12}\".format(p[0], str(tuple(p[1].size()))))", "The BERT model has 201 different named parameters.\n\n==== Embedding Layer ====\n\nbert.embeddings.word_embeddings.weight (30000, 768)\nbert.embeddings.position_embeddings.weight (300, 768)\nbert.embeddings.token_type_embeddings.weight (2, 768)\nbert.embeddings.LayerNorm.weight (768,)\nbert.embeddings.LayerNorm.bias (768,)\n\n==== First Transformer ====\n\nbert.encoder.layer.0.attention.self.query.weight (768, 768)\nbert.encoder.layer.0.attention.self.query.bias (768,)\nbert.encoder.layer.0.attention.self.key.weight (768, 768)\nbert.encoder.layer.0.attention.self.key.bias (768,)\nbert.encoder.layer.0.attention.self.value.weight (768, 768)\nbert.encoder.layer.0.attention.self.value.bias (768,)\nbert.encoder.layer.0.attention.output.dense.weight (768, 768)\nbert.encoder.layer.0.attention.output.dense.bias (768,)\nbert.encoder.layer.0.attention.output.LayerNorm.weight (768,)\nbert.encoder.layer.0.attention.output.LayerNorm.bias (768,)\nbert.encoder.layer.0.intermediate.dense.weight (3072, 768)\nbert.encoder.layer.0.intermediate.dense.bias (3072,)\nbert.encoder.layer.0.output.dense.weight (768, 3072)\nbert.encoder.layer.0.output.dense.bias (768,)\nbert.encoder.layer.0.output.LayerNorm.weight (768,)\nbert.encoder.layer.0.output.LayerNorm.bias (768,)\n\n==== Output Layer ====\n\nbert.pooler.dense.weight (768, 768)\nbert.pooler.dense.bias (768,)\nclassifier.weight (2, 768)\nclassifier.bias (2,)\n" ], [ "def convert_input_data(sentences):\n\n tokenized_texts = [tokenizer.tokenize(sent) for sent in sentences]\n MAX_LEN = 64\n\n # 토큰을 숫자 인덱스로 변환\n input_ids = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts]\n \n # 문장을 MAX_LEN 길이에 맞게 자르고, 모자란 부분을 패딩 0으로 채움\n input_ids = pad_sequences(input_ids, maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\n\n # 어텐션 마스크 초기화\n attention_masks = []\n\n # 어텐션 마스크를 패딩이 아니면 1, 패딩이면 0으로 설정\n for seq in input_ids:\n seq_mask = [float(i>0) for i in seq]\n attention_masks.append(seq_mask)\n \n inputs = torch.tensor(input_ids)\n masks = torch.tensor(attention_masks)\n\n return inputs, masks", "_____no_output_____" ], [ "def test_sentences(sentences):\n \n # 평가모드로 변경!!!!!\n model.eval()\n\n inputs, masks = convert_input_data(sentences)\n\n # 데이터를 GPU에 넣음\n b_input_ids = inputs.to(device)\n b_input_mask = masks.to(device)\n \n # 그래디언트 계산 안함\n with torch.no_grad(): \n # Forward 수행\n outputs = model(b_input_ids, \n token_type_ids=None, \n attention_mask=b_input_mask)\n\n # 로스 구함\n logits = outputs[0]\n\n # CPU로 데이터 이동\n logits = logits.detach().cpu().numpy()\n\n return logits", "_____no_output_____" ], [ "device = \"cuda:0\"\nmodel = model.to(device)", "_____no_output_____" ] ], [ [ "## 데이터 변환", "_____no_output_____" ] ], [ [ "def preprocessing(df):\n\n df.document=df.comment.replace('[^A-Za-zㄱ-ㅎㅏ-ㅣ가-힣]+','')\n\n return df\n\n# result = preprocessing(gr_data)\n# result = result.dropna()\n# print(result)", "_____no_output_____" ], [ "# 감성분석할 comment 추출 \ndef export_com(preprocessed_df):\n sens =[]\n for sen in preprocessed_df.comment:\n sens.append(sen)\n print('check lenght :', len(sens), len(preprocessed_df)) # 개수 확인 \n print('sample sentence :', sens[1])\n return sens", "_____no_output_____" ], [ "def make_predicted_label(sen):\n sen = [sen]\n score = test_sentences(sen)\n result = np.argmax(score)\n\n if result == 0: # negative \n return 0\n elif result == 1: # positive\n return 1", "_____no_output_____" ], [ "def predict_label(model, df, place_name):\n result = preprocessing(df)\n result = result.dropna()\n \n sens = export_com(result)\n \n scores_data=[]\n for sen in sens:\n scores_data.append(make_predicted_label(sen))\n \n df['pred'] = scores_data \n \n cor = df[df.label == df.pred]\n uncor = df[df.label != df.pred]\n \n print('correct prediction num :', len(cor))\n print('uncorrect prediction num :', len(uncor))\n print('correct label check :' ,set(cor.label))\n \n# df.to_csv(pj_path + f'/sentiment_data/{place_name}_pred_kcbert.csv')\n return df", "_____no_output_____" ], [ "print('### spacing ###')\npredict_spac = predict_label(model, test_spac, 'total')\nprint('### spell ###')\npredict_spel = predict_label(model, test_spel, 'total')", "### spacing ###\ncheck lenght : 8389 8389\nsample sentence : 코로나 때문에 너무 오랜만에 가본 예술의 전당이였고 공연도 너무 좋았습니다 직원 분들도 너무 친절했구요 있는 공연들 최대한 아이들과 많이 가보려구요 가시는 분들 모두 좋은 시간 보내세요\n" ] ], [ [ "## Loss (RMSE)", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nimport math", "_____no_output_____" ], [ "def rmse(y, y_pred):\n from sklearn.metrics import mean_squared_error\n import math\n print('lenght check (origin, prediction):', len(y), len(y_pred))\n\n rmse_label = math.sqrt(mean_squared_error(y, y_pred))\n print('rmse of label :', rmse_label)", "_____no_output_____" ] ], [ [ "## Accuracy", "_____no_output_____" ] ], [ [ "def acc(y, y_pred, total):\n correct = (y_pred == y).sum().item()\n\n print(f'Accuracy of the network on the {total} test text: %d %%' % (\n 100 * correct / total))", "_____no_output_____" ] ], [ [ "## f1-score", "_____no_output_____" ] ], [ [ "from sklearn.metrics import f1_score, classification_report", "_____no_output_____" ], [ "def f1(y, y_pred):\n score = f1_score(y, y_pred)\n report = classification_report(y, y_pred)\n \n print('f1 score :', score)\n print('===== classification report =====')\n print(report)", "_____no_output_____" ] ], [ [ "## calculate performance\n- RMSE\n- Accuracy\n- f1-score", "_____no_output_____" ] ], [ [ "def cal_perform(df):\n y = df.label\n y_pred = df.pred\n if len(y) == len(y_pred):\n total = len(y)\n print('label length :', total)\n else:\n print('It has different length !')\n \n rmse(y, y_pred)\n acc(y, y_pred, total)\n f1(y, y_pred)", "_____no_output_____" ], [ "print('===== spacing =====')\ncal_perform(predict_spac)\nprint('===== spell =====')\ncal_perform(predict_spel)", "===== spacing =====\nlabel length : 8389\nlenght check (origin, prediction): 8389 8389\nrmse of label : 0.44763986853418153\nAccuracy of the network on the 8389 test text: 79 %\nf1 score : 0.872699734948883\n===== classification report =====\n precision recall f1-score support\n\n 0 0.41 0.74 0.53 1274\n 1 0.95 0.81 0.87 7115\n\n accuracy 0.80 8389\n macro avg 0.68 0.78 0.70 8389\nweighted avg 0.86 0.80 0.82 8389\n\n===== spell =====\nlabel length : 8386\nlenght check (origin, prediction): 8386 8386\nrmse of label : 0.44638623696243956\nAccuracy of the network on the 8386 test text: 80 %\nf1 score : 0.8733035105011752\n===== classification report =====\n precision recall f1-score support\n\n 0 0.41 0.75 0.53 1276\n 1 0.95 0.81 0.87 7110\n\n accuracy 0.80 8386\n macro avg 0.68 0.78 0.70 8386\nweighted avg 0.87 0.80 0.82 8386\n\n" ] ] ]
[ "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", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4af17e790205bce6c9c04a183d08fcd50a71149c
71,203
ipynb
Jupyter Notebook
tests/.ipynb_aml_checkpoints/test-checkpoint2021-11-10-20-30-44Z.ipynb
adrianfz/ray-on-aml
91c17155c8fec6433038f70fe723b7fbe4e1aa4f
[ "MIT" ]
1
2021-12-15T22:03:21.000Z
2021-12-15T22:03:21.000Z
tests/.ipynb_aml_checkpoints/test-checkpoint2021-11-10-20-30-44Z.ipynb
adrianfz/ray-on-aml
91c17155c8fec6433038f70fe723b7fbe4e1aa4f
[ "MIT" ]
null
null
null
tests/.ipynb_aml_checkpoints/test-checkpoint2021-11-10-20-30-44Z.ipynb
adrianfz/ray-on-aml
91c17155c8fec6433038f70fe723b7fbe4e1aa4f
[ "MIT" ]
null
null
null
98.755895
5,317
0.587602
[ [ [ "### Testing for Interactive use case", "_____no_output_____" ] ], [ [ "import mlflow\nfrom azureml.core import Workspace, Experiment, Environment, Datastore, Dataset, ScriptRunConfig\nfrom azureml.core.runconfig import PyTorchConfiguration\n# from azureml.widgets import RunDetails\nfrom azureml.core.compute import ComputeTarget, AmlCompute\nfrom azureml.core.compute_target import ComputeTargetException\nfrom azureml.core.runconfig import PyTorchConfiguration\nfrom azureml.core.environment import Environment\nfrom azureml.core.conda_dependencies import CondaDependencies\nfrom IPython.display import clear_output\nimport time\nimport platform\n# from ray_on_azureml.ray_on_aml import getRay\nimport sys\nsys.path.append(\"../\") # go to parent dir\nimport importlib\n", "_____no_output_____" ], [ "from src.ray_on_azureml.ray_on_aml import Ray_On_AML\nws = Workspace.from_config()\nray_on_aml =Ray_On_AML(ws=ws, compute_cluster =\"worker-cpu-v3\")\n_, ray = ray_on_aml.getRay()\nray.cluster_resources()", "azureml_py38\n" ], [ "ray_on_aml.shutdown()\n# import ray\n# ray.shutdown()\n# ray.init()", "_____no_output_____" ] ], [ [ "### Testing with Dask on Ray", "_____no_output_____" ] ], [ [ "# import ray\n# ray.init()\nfrom ray.util.dask import ray_dask_get\nimport dask\nimport dask.array as da\nimport dask.dataframe as dd\nimport numpy as np\nimport pandas as pd\ndask.config.set(scheduler=ray_dask_get)\nd_arr = da.from_array(np.random.randint(0, 1000, size=(256, 256)))\n\n# The Dask scheduler submits the underlying task graph to Ray.\nd_arr.mean().compute(scheduler=ray_dask_get)\n\n# Set the scheduler to ray_dask_get in your config so you don't have to\n# specify it on each compute call.\n\ndf = dd.from_pandas(\n pd.DataFrame(\n np.random.randint(0, 10000, size=(1024, 2)), columns=[\"age\", \"grade\"]),\n npartitions=2)\ndf.groupby([\"age\"]).mean().compute()\n\n# ray.shutdown()", "_____no_output_____" ], [ "import dask.dataframe as dd\n\nstorage_options = {'account_name': 'azureopendatastorage'}\nddf = dd.read_parquet('az://nyctlc/green/puYear=2019/puMonth=*/*.parquet', storage_options=storage_options)\nddf.count().compute()", "_____no_output_____" ], [ "#dask\n\n# import ray\nfrom ray.util.dask import ray_dask_get\nimport dask\nimport dask.array as da\nimport dask.dataframe as dd\nimport numpy as np\nimport pandas as pd\nimport dask\nimport dask.dataframe as dd\nimport matplotlib.pyplot as plt\n\nfrom datetime import datetime\n\nfrom azureml.core import Workspace, Dataset, Model\nfrom adlfs import AzureBlobFileSystem\naccount_key = ws.get_default_keyvault().get_secret(\"adls7-account-key\")\naccount_name=\"adlsgen7\"\nabfs = AzureBlobFileSystem(account_name=\"adlsgen7\",account_key=account_key, container_name=\"mltraining\")\nabfs2 = AzureBlobFileSystem(account_name=\"azureopendatastorage\", container_name=\"isdweatherdatacontainer\")\n\n\nstorage_options={'account_name': account_name, 'account_key': account_key}\n\n# ddf = dd.read_parquet('az://mltraining/ISDWeatherDelta/year2008', storage_options=storage_options)\n\ndata = ray.data.read_parquet(\"az://isdweatherdatacontainer/ISDWeather/year=2009\", filesystem=abfs2)\ndata2 = ray.data.read_parquet(\"az://mltraining/ISDWeatherDelta/year2008\", filesystem=abfs)\ndata.count()", "_____no_output_____" ] ], [ [ "### Testing Ray Tune for distributed ML tunning", "_____no_output_____" ] ], [ [ "import numpy as np\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\n# import ray\nfrom ray import tune\nfrom ray.tune.schedulers import ASHAScheduler\nclass ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n # In this example, we don't change the model architecture\n # due to simplicity.\n self.conv1 = nn.Conv2d(1, 3, kernel_size=3)\n self.fc = nn.Linear(192, 10)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 3))\n x = x.view(-1, 192)\n x = self.fc(x)\n return F.log_softmax(x, dim=1)\n# Change these values if you want the training to run quicker or slower.\nEPOCH_SIZE = 512\nTEST_SIZE = 256\n\ndef train(model, optimizer, train_loader):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n # We set this just for the example to run quickly.\n if batch_idx * len(data) > EPOCH_SIZE:\n return\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n\n\ndef test(model, data_loader):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model.eval()\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (data, target) in enumerate(data_loader):\n # We set this just for the example to run quickly.\n if batch_idx * len(data) > TEST_SIZE:\n break\n data, target = data.to(device), target.to(device)\n outputs = model(data)\n _, predicted = torch.max(outputs.data, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n return correct / total\ndef train_mnist(config):\n # Data Setup\n mnist_transforms = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.1307, ), (0.3081, ))])\n\n train_loader = DataLoader(\n datasets.MNIST(\"~/data\", train=True, download=True, transform=mnist_transforms),\n batch_size=64,\n shuffle=True)\n test_loader = DataLoader(\n datasets.MNIST(\"~/data\", train=False, transform=mnist_transforms),\n batch_size=64,\n shuffle=True)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n model = ConvNet()\n model.to(device)\n\n optimizer = optim.SGD(\n model.parameters(), lr=config[\"lr\"], momentum=config[\"momentum\"])\n for i in range(10):\n train(model, optimizer, train_loader)\n acc = test(model, test_loader)\n\n # Send the current training result back to Tune\n tune.report(mean_accuracy=acc)\n\n if i % 5 == 0:\n # This saves the model to the trial directory\n torch.save(model.state_dict(), \"./model.pth\")\nsearch_space = {\n \"lr\": tune.sample_from(lambda spec: 10**(-10 * np.random.rand())),\n \"momentum\": tune.uniform(0.01, 0.09)\n}\n\n# Uncomment this to enable distributed execution\n# ray.shutdown()\n# ray.init(address=\"auto\",ignore_reinit_error=True)\n# ray.init(address =f'ray://{headnode_private_ip}:10001',allow_multiple=True,ignore_reinit_error=True )\n# Download the dataset first\ndatasets.MNIST(\"~/data\", train=True, download=True)\n\nanalysis = tune.run(train_mnist, config=search_space)\n", "_____no_output_____" ], [ " import sklearn.datasets\n import sklearn.metrics\n from sklearn.model_selection import train_test_split\n import xgboost as xgb\n\n from ray import tune\n\n\n def train_breast_cancer(config):\n # Load dataset\n data, labels = sklearn.datasets.load_breast_cancer(return_X_y=True)\n # Split into train and test set\n train_x, test_x, train_y, test_y = train_test_split(\n data, labels, test_size=0.25)\n # Build input matrices for XGBoost\n train_set = xgb.DMatrix(train_x, label=train_y)\n test_set = xgb.DMatrix(test_x, label=test_y)\n # Train the classifier\n results = {}\n xgb.train(\n config,\n train_set,\n evals=[(test_set, \"eval\")],\n evals_result=results,\n verbose_eval=False)\n # Return prediction accuracy\n accuracy = 1. - results[\"eval\"][\"error\"][-1]\n tune.report(mean_accuracy=accuracy, done=True)\n\n\n config = {\n \"objective\": \"binary:logistic\",\n \"eval_metric\": [\"logloss\", \"error\"],\n \"max_depth\": tune.randint(1, 9),\n \"min_child_weight\": tune.choice([1, 2, 3]),\n \"subsample\": tune.uniform(0.5, 1.0),\n \"eta\": tune.loguniform(1e-4, 1e-1)\n }\n analysis = tune.run(\n train_breast_cancer,\n resources_per_trial={\"cpu\": 1},\n config=config,\n num_samples=10)\n", "2021-12-10 03:24:19,734\tWARNING callback.py:114 -- The TensorboardX logger cannot be instantiated because either TensorboardX or one of it's dependencies is not installed. Please make sure you have the latest version of TensorboardX installed: `pip install -U tensorboardx`\n" ] ], [ [ "### Testing Spark on Ray", "_____no_output_____" ] ], [ [ "import ray\nimport raydp\nimport os\nray.shutdown()\nray.init()\nos.environ[\"PYSPARK_PYTHON\"]=\"/anaconda/envs/azureml_py38/bin/python3\"\n\n# ray.init(address ='ray://10.0.0.11:6379')\nspark = raydp.init_spark(\n app_name = \"example\",\n num_executors = 2,\n executor_cores = 1,\n executor_memory = \"1gb\"\n)\n\n# data =spark.read.format(\"csv\").option(\"header\", True).load(\"wasbs://ojsales-simulatedcontainer@azureopendatastorage.blob.core.windows.net/oj_sales_data/Store10*.csv\")\n\n\n# # normal data processesing with Spark\n# df = spark.createDataFrame([('look',), ('spark',), ('tutorial',), ('spark',), ('look', ), ('python', )], ['word'])\n# df.show()\n# word_count = df.groupBy('word').count()\n# word_count.show()\nimport pandas as pd\n\nfrom pyspark.sql.functions import col, pandas_udf\nfrom pyspark.sql.types import LongType\n\n# Declare the function and create the UDF\ndef multiply_func(a: pd.Series, b: pd.Series) -> pd.Series:\n return a * b\n\nmultiply = pandas_udf(multiply_func, returnType=LongType())\n\n# The function for a pandas_udf should be able to execute with local Pandas data\nx = pd.Series([1, 2, 3])\nprint(multiply_func(x, x))\n# 0 1\n# 1 4\n# 2 9\n# dtype: int64\n\n# Create a Spark DataFrame, 'spark' is an existing SparkSession\ndf = spark.createDataFrame(pd.DataFrame(x, columns=[\"x\"]))\n\n# Execute function as a Spark vectorized UDF\ndf.select(multiply(col(\"x\"), col(\"x\"))).show()\n# +-------------------+\n# |multiply_func(x, x)|\n# +-------------------+\n# | 1|\n# | 4|\n# | 9|\n# +-------------------+\n\n\n# stop the spark cluster\nraydp.stop_spark()\n", "2021-12-06 19:48:42,187\tINFO services.py:1338 -- View the Ray dashboard at \u001b[1m\u001b[32mhttp://127.0.0.1:8266\u001b[39m\u001b[22m\n" ], [ "raydp.stop_spark()\n", "_____no_output_____" ] ], [ [ "## Testing Ray on Job Cluster", "_____no_output_____" ] ], [ [ "# pyarrow >=6.0.1\n# dask >=2021.11.2\n# adlfs >=2021.10.0\n# fsspec==2021.10.1\n# ray[default]==1.9.0\nws = Workspace.from_config()\n\n# base_conda_dep =['adlfs>=2021.10.0','pytorch','matplotlib','torchvision','pip']\n# base_pip_dep = ['sklearn','xgboost','lightgbm','ray[default]==1.9.0', 'xgboost_ray', 'dask','pyarrow>=6.0.1', 'azureml-mlflow']\ncompute_cluster = 'worker-cpu-v3'\nmaxnode =5\nvm_size='STANDARD_DS3_V2'\nvnet='rayvnet'\nsubnet='default'\nexp ='ray_on_aml_job'\nws_detail = ws.get_details()\nws_rg = ws_detail['id'].split(\"/\")[4]\nvnet_rg=None\ntry:\n ray_cluster = ComputeTarget(workspace=ws, name=compute_cluster)\n\n print('Found existing cluster, use it.')\nexcept ComputeTargetException:\n if vnet_rg is None:\n vnet_rg = ws_rg\n compute_config = AmlCompute.provisioning_configuration(vm_size=vm_size,\n min_nodes=0, max_nodes=maxnode,\n vnet_resourcegroup_name=vnet_rg,\n vnet_name=vnet,\n subnet_name=subnet)\n ray_cluster = ComputeTarget.create(ws, compute_cluster, compute_config)\n\n ray_cluster.wait_for_completion(show_output=True)\n\n\n# python_version = [\"python=\"+platform.python_version()]\n\n\n\n# conda_packages = python_version+base_conda_dep\n# pip_packages = base_pip_dep \n\n# conda_dep = CondaDependencies()\n\n# rayEnv = Environment(name=\"rayEnv\")\nrayEnv = Environment.get(ws, \"rayEnv\", version=16)\n# for conda_package in conda_packages:\n# conda_dep.add_conda_package(conda_package)\n\n# for pip_package in pip_packages:\n# conda_dep.add_pip_package(pip_package)\n\n# # Adds dependencies to PythonSection of myenv\n# rayEnv.python.conda_dependencies=conda_dep\n\nsrc = ScriptRunConfig(source_directory='job',\n script='aml_job.py',\n environment=rayEnv,\n compute_target=ray_cluster,\n distributed_job_config=PyTorchConfiguration(node_count=maxnode),\n # arguments = [\"--master_ip\",master_ip]\n )\nrun = Experiment(ws, exp).submit(src)", "Found existing cluster, use it.\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4af18cb113e052d1ac6c707f9494a0f1d676ab8e
247,541
ipynb
Jupyter Notebook
Course-4-Convolutional-Neural-Networks/Assignments/Week3/Assignment-1/Autonomous+driving+application+-+Car+detection+-+v1.ipynb
mejanvijay/Deep-Learning-Specialization
11a9a94bece82b95281d5b1c8371e575d07802f5
[ "MIT" ]
null
null
null
Course-4-Convolutional-Neural-Networks/Assignments/Week3/Assignment-1/Autonomous+driving+application+-+Car+detection+-+v1.ipynb
mejanvijay/Deep-Learning-Specialization
11a9a94bece82b95281d5b1c8371e575d07802f5
[ "MIT" ]
null
null
null
Course-4-Convolutional-Neural-Networks/Assignments/Week3/Assignment-1/Autonomous+driving+application+-+Car+detection+-+v1.ipynb
mejanvijay/Deep-Learning-Specialization
11a9a94bece82b95281d5b1c8371e575d07802f5
[ "MIT" ]
null
null
null
177.959022
179,682
0.855131
[ [ [ "# Autonomous driving - Car detection\n\nWelcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: Redmon et al., 2016 (https://arxiv.org/abs/1506.02640) and Redmon and Farhadi, 2016 (https://arxiv.org/abs/1612.08242). \n\n**You will learn to**:\n- Use object detection on a car detection dataset\n- Deal with bounding boxes\n\nRun the following cell to load the packages and dependencies that are going to be useful for your journey!", "_____no_output_____" ] ], [ [ "import argparse\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imshow\nimport scipy.io\nimport scipy.misc\nimport numpy as np\nimport pandas as pd\nimport PIL\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.layers import Input, Lambda, Conv2D\nfrom keras.models import load_model, Model\nfrom yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes\nfrom yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes, yolo_loss, yolo_body\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "**Important Note**: As you can see, we import Keras's backend as K. This means that to use a Keras function in this notebook, you will need to write: `K.function(...)`.", "_____no_output_____" ], [ "## 1 - Problem Statement\n\nYou are working on a self-driving car. As a critical component of this project, you'd like to first build a car detection system. To collect data, you've mounted a camera to the hood (meaning the front) of the car, which takes pictures of the road ahead every few seconds while you drive around. \n\n<center>\n<video width=\"400\" height=\"200\" src=\"nb_images/road_video_compressed2.mp4\" type=\"video/mp4\" controls>\n</video>\n</center>\n\n<caption><center> Pictures taken from a car-mounted camera while driving around Silicon Valley. <br> We would like to especially thank [drive.ai](https://www.drive.ai/) for providing this dataset! Drive.ai is a company building the brains of self-driving vehicles.\n</center></caption>\n\n<img src=\"nb_images/driveai.png\" style=\"width:100px;height:100;\">\n\nYou've gathered all these images into a folder and have labelled them by drawing bounding boxes around every car you found. Here's an example of what your bounding boxes look like.\n\n<img src=\"nb_images/box_label.png\" style=\"width:500px;height:250;\">\n<caption><center> <u> **Figure 1** </u>: **Definition of a box**<br> </center></caption>\n\nIf you have 80 classes that you want YOLO to recognize, you can represent the class label $c$ either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) one component of which is 1 and the rest of which are 0. The video lectures had used the latter representation; in this notebook, we will use both representations, depending on which is more convenient for a particular step. \n\nIn this exercise, you will learn how YOLO works, then apply it to car detection. Because the YOLO model is very computationally expensive to train, we will load pre-trained weights for you to use. ", "_____no_output_____" ], [ "## 2 - YOLO", "_____no_output_____" ], [ "YOLO (\"you only look once\") is a popular algoritm because it achieves high accuracy while also being able to run in real-time. This algorithm \"only looks once\" at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes.\n\n### 2.1 - Model details\n\nFirst things to know:\n- The **input** is a batch of images of shape (m, 608, 608, 3)\n- The **output** is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers $(p_c, b_x, b_y, b_h, b_w, c)$ as explained above. If you expand $c$ into an 80-dimensional vector, each bounding box is then represented by 85 numbers. \n\nWe will use 5 anchor boxes. So you can think of the YOLO architecture as the following: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85).\n\nLets look in greater detail at what this encoding represents. \n\n<img src=\"nb_images/architecture.png\" style=\"width:700px;height:400;\">\n<caption><center> <u> **Figure 2** </u>: **Encoding architecture for YOLO**<br> </center></caption>\n\nIf the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object.", "_____no_output_____" ], [ "Since we are using 5 anchor boxes, each of the 19 x19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.\n\nFor simplicity, we will flatten the last two last dimensions of the shape (19, 19, 5, 85) encoding. So the output of the Deep CNN is (19, 19, 425).\n\n<img src=\"nb_images/flatten.png\" style=\"width:700px;height:400;\">\n<caption><center> <u> **Figure 3** </u>: **Flattening the last two last dimensions**<br> </center></caption>", "_____no_output_____" ], [ "Now, for each box (of each cell) we will compute the following elementwise product and extract a probability that the box contains a certain class.\n\n<img src=\"nb_images/probability_extraction.png\" style=\"width:700px;height:400;\">\n<caption><center> <u> **Figure 4** </u>: **Find the class detected by each box**<br> </center></caption>\n\nHere's one way to visualize what YOLO is predicting on an image:\n- For each of the 19x19 grid cells, find the maximum of the probability scores (taking a max across both the 5 anchor boxes and across different classes). \n- Color that grid cell according to what object that grid cell considers the most likely.\n\nDoing this results in this picture: \n\n<img src=\"nb_images/proba_map.png\" style=\"width:300px;height:300;\">\n<caption><center> <u> **Figure 5** </u>: Each of the 19x19 grid cells colored according to which class has the largest predicted probability in that cell.<br> </center></caption>\n\nNote that this visualization isn't a core part of the YOLO algorithm itself for making predictions; it's just a nice way of visualizing an intermediate result of the algorithm. \n", "_____no_output_____" ], [ "Another way to visualize YOLO's output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this: \n\n<img src=\"nb_images/anchor_map.png\" style=\"width:200px;height:200;\">\n<caption><center> <u> **Figure 6** </u>: Each cell gives you 5 boxes. In total, the model predicts: 19x19x5 = 1805 boxes just by looking once at the image (one forward pass through the network)! Different colors denote different classes. <br> </center></caption>\n\nIn the figure above, we plotted only boxes that the model had assigned a high probability to, but this is still too many boxes. You'd like to filter the algorithm's output down to a much smaller number of detected objects. To do so, you'll use non-max suppression. Specifically, you'll carry out these steps: \n- Get rid of boxes with a low score (meaning, the box is not very confident about detecting a class)\n- Select only one box when several boxes overlap with each other and detect the same object.\n\n", "_____no_output_____" ], [ "### 2.2 - Filtering with a threshold on class scores\n\nYou are going to apply a first filter by thresholding. You would like to get rid of any box for which the class \"score\" is less than a chosen threshold. \n\nThe model gives you a total of 19x19x5x85 numbers, with each box described by 85 numbers. It'll be convenient to rearrange the (19,19,5,85) (or (19,19,425)) dimensional tensor into the following variables: \n- `box_confidence`: tensor of shape $(19 \\times 19, 5, 1)$ containing $p_c$ (confidence probability that there's some object) for each of the 5 boxes predicted in each of the 19x19 cells.\n- `boxes`: tensor of shape $(19 \\times 19, 5, 4)$ containing $(b_x, b_y, b_h, b_w)$ for each of the 5 boxes per cell.\n- `box_class_probs`: tensor of shape $(19 \\times 19, 5, 80)$ containing the detection probabilities $(c_1, c_2, ... c_{80})$ for each of the 80 classes for each of the 5 boxes per cell.\n\n**Exercise**: Implement `yolo_filter_boxes()`.\n1. Compute box scores by doing the elementwise product as described in Figure 4. The following code may help you choose the right operator: \n```python\na = np.random.randn(19*19, 5, 1)\nb = np.random.randn(19*19, 5, 80)\nc = a * b # shape of c will be (19*19, 5, 80)\n```\n2. For each box, find:\n - the index of the class with the maximum box score ([Hint](https://keras.io/backend/#argmax)) (Be careful with what axis you choose; consider using axis=-1)\n - the corresponding box score ([Hint](https://keras.io/backend/#max)) (Be careful with what axis you choose; consider using axis=-1)\n3. Create a mask by using a threshold. As a reminder: `([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4)` returns: `[False, True, False, False, True]`. The mask should be True for the boxes you want to keep. \n4. Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep. ([Hint](https://www.tensorflow.org/api_docs/python/tf/boolean_mask))\n\nReminder: to call a Keras function, you should use `K.function(...)`.", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: yolo_filter_boxes\n\ndef yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6):\n \"\"\"Filters YOLO boxes by thresholding on object and class confidence.\n \n Arguments:\n box_confidence -- tensor of shape (19, 19, 5, 1)\n boxes -- tensor of shape (19, 19, 5, 4)\n box_class_probs -- tensor of shape (19, 19, 5, 80)\n threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box\n \n Returns:\n scores -- tensor of shape (None,), containing the class probability score for selected boxes\n boxes -- tensor of shape (None, 4), containing (b_x, b_y, b_h, b_w) coordinates of selected boxes\n classes -- tensor of shape (None,), containing the index of the class detected by the selected boxes\n \n Note: \"None\" is here because you don't know the exact number of selected boxes, as it depends on the threshold. \n For example, the actual output size of scores would be (10,) if there are 10 boxes.\n \"\"\"\n \n # Step 1: Compute box scores\n ### START CODE HERE ### (≈ 1 line)\n box_scores = box_confidence * box_class_probs\n ### END CODE HERE ###\n \n # Step 2: Find the box_classes thanks to the max box_scores, keep track of the corresponding score\n ### START CODE HERE ### (≈ 2 lines)\n box_classes = K.argmax(box_scores, axis=-1)\n box_class_scores = K.max(box_scores, axis=-1)\n ### END CODE HERE ###\n \n # Step 3: Create a filtering mask based on \"box_class_scores\" by using \"threshold\". The mask should have the\n # same dimension as box_class_scores, and be True for the boxes you want to keep (with probability >= threshold)\n ### START CODE HERE ### (≈ 1 line)\n filtering_mask = box_class_scores >= threshold\n ### END CODE HERE ###\n \n # Step 4: Apply the mask to scores, boxes and classes\n ### START CODE HERE ### (≈ 3 lines)\n scores = tf.boolean_mask(box_class_scores, filtering_mask)\n boxes = tf.boolean_mask(boxes, filtering_mask)\n classes = tf.boolean_mask(box_classes, filtering_mask)\n ### END CODE HERE ###\n \n return scores, boxes, classes", "_____no_output_____" ], [ "with tf.Session() as test_a:\n box_confidence = tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1)\n boxes = tf.random_normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)\n box_class_probs = tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)\n scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = 0.5)\n print(\"scores[2] = \" + str(scores[2].eval()))\n print(\"boxes[2] = \" + str(boxes[2].eval()))\n print(\"classes[2] = \" + str(classes[2].eval()))\n print(\"scores.shape = \" + str(scores.shape))\n print(\"boxes.shape = \" + str(boxes.shape))\n print(\"classes.shape = \" + str(classes.shape))", "scores[2] = 10.7506\nboxes[2] = [ 8.42653275 3.27136683 -0.5313437 -4.94137383]\nclasses[2] = 7\nscores.shape = (?,)\nboxes.shape = (?, 4)\nclasses.shape = (?,)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **scores[2]**\n </td>\n <td>\n 10.7506\n </td>\n </tr>\n <tr>\n <td>\n **boxes[2]**\n </td>\n <td>\n [ 8.42653275 3.27136683 -0.5313437 -4.94137383]\n </td>\n </tr>\n\n <tr>\n <td>\n **classes[2]**\n </td>\n <td>\n 7\n </td>\n </tr>\n <tr>\n <td>\n **scores.shape**\n </td>\n <td>\n (?,)\n </td>\n </tr>\n <tr>\n <td>\n **boxes.shape**\n </td>\n <td>\n (?, 4)\n </td>\n </tr>\n\n <tr>\n <td>\n **classes.shape**\n </td>\n <td>\n (?,)\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "### 2.3 - Non-max suppression ###\n\nEven after filtering by thresholding over the classes scores, you still end up a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS). ", "_____no_output_____" ], [ "<img src=\"nb_images/non-max-suppression.png\" style=\"width:500px;height:400;\">\n<caption><center> <u> **Figure 7** </u>: In this example, the model has predicted 3 cars, but it's actually 3 predictions of the same car. Running non-max suppression (NMS) will select only the most accurate (highest probabiliy) one of the 3 boxes. <br> </center></caption>\n", "_____no_output_____" ], [ "Non-max suppression uses the very important function called **\"Intersection over Union\"**, or IoU.\n<img src=\"nb_images/iou.png\" style=\"width:500px;height:400;\">\n<caption><center> <u> **Figure 8** </u>: Definition of \"Intersection over Union\". <br> </center></caption>\n\n**Exercise**: Implement iou(). Some hints:\n- In this exercise only, we define a box using its two corners (upper left and lower right): (x1, y1, x2, y2) rather than the midpoint and height/width.\n- To calculate the area of a rectangle you need to multiply its height (y2 - y1) by its width (x2 - x1)\n- You'll also need to find the coordinates (xi1, yi1, xi2, yi2) of the intersection of two boxes. Remember that:\n - xi1 = maximum of the x1 coordinates of the two boxes\n - yi1 = maximum of the y1 coordinates of the two boxes\n - xi2 = minimum of the x2 coordinates of the two boxes\n - yi2 = minimum of the y2 coordinates of the two boxes\n \nIn this code, we use the convention that (0,0) is the top-left corner of an image, (1,0) is the upper-right corner, and (1,1) the lower-right corner. ", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: iou\n\ndef iou(box1, box2):\n \"\"\"Implement the intersection over union (IoU) between box1 and box2\n \n Arguments:\n box1 -- first box, list object with coordinates (x1, y1, x2, y2)\n box2 -- second box, list object with coordinates (x1, y1, x2, y2)\n \"\"\"\n\n # Calculate the (y1, x1, y2, x2) coordinates of the intersection of box1 and box2. Calculate its Area.\n ### START CODE HERE ### (≈ 5 lines)\n xi1 = max(box1[0], box2[0])\n yi1 = max(box1[1], box2[1])\n xi2 = min(box1[2], box2[2])\n yi2 = min(box1[3], box2[3])\n inter_area = (yi2-yi1) * (xi2-xi1)\n ### END CODE HERE ### \n\n # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)\n ### START CODE HERE ### (≈ 3 lines)\n box1_area = (box1[3]-box1[1]) * (box1[2]-box1[0])\n box2_area = (box2[3]-box2[1]) * (box2[2]-box2[0])\n union_area = box1_area + box2_area - inter_area\n ### END CODE HERE ###\n \n # compute the IoU\n ### START CODE HERE ### (≈ 1 line)\n iou = float(inter_area) / float(union_area)\n ### END CODE HERE ###\n\n return iou", "_____no_output_____" ], [ "box1 = (2, 1, 4, 3)\nbox2 = (1, 2, 3, 4) \nprint(\"iou = \" + str(iou(box1, box2)))", "iou = 0.14285714285714285\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **iou = **\n </td>\n <td>\n 0.14285714285714285\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "You are now ready to implement non-max suppression. The key steps are: \n1. Select the box that has the highest score.\n2. Compute its overlap with all other boxes, and remove boxes that overlap it more than `iou_threshold`.\n3. Go back to step 1 and iterate until there's no more boxes with a lower score than the current selected box.\n\nThis will remove all boxes that have a large overlap with the selected boxes. Only the \"best\" boxes remain.\n\n**Exercise**: Implement yolo_non_max_suppression() using TensorFlow. TensorFlow has two built-in functions that are used to implement non-max suppression (so you don't actually need to use your `iou()` implementation):\n- [tf.image.non_max_suppression()](https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression)\n- [K.gather()](https://www.tensorflow.org/api_docs/python/tf/gather)", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: yolo_non_max_suppression\n\ndef yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5):\n \"\"\"\n Applies Non-max suppression (NMS) to set of boxes\n \n Arguments:\n scores -- tensor of shape (None,), output of yolo_filter_boxes()\n boxes -- tensor of shape (None, 4), output of yolo_filter_boxes() that have been scaled to the image size (see later)\n classes -- tensor of shape (None,), output of yolo_filter_boxes()\n max_boxes -- integer, maximum number of predicted boxes you'd like\n iou_threshold -- real value, \"intersection over union\" threshold used for NMS filtering\n \n Returns:\n scores -- tensor of shape (, None), predicted score for each box\n boxes -- tensor of shape (4, None), predicted box coordinates\n classes -- tensor of shape (, None), predicted class for each box\n \n Note: The \"None\" dimension of the output tensors has obviously to be less than max_boxes. Note also that this\n function will transpose the shapes of scores, boxes, classes. This is made for convenience.\n \"\"\"\n \n max_boxes_tensor = K.variable(max_boxes, dtype='int32') # tensor to be used in tf.image.non_max_suppression()\n K.get_session().run(tf.variables_initializer([max_boxes_tensor])) # initialize variable max_boxes_tensor\n \n # Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep\n ### START CODE HERE ### (≈ 1 line)\n nms_indices = tf.image.non_max_suppression(boxes, scores, max_boxes, iou_threshold = iou_threshold)\n ### END CODE HERE ###\n \n # Use K.gather() to select only nms_indices from scores, boxes and classes\n ### START CODE HERE ### (≈ 3 lines)\n scores = tf.gather(scores, nms_indices)\n boxes = tf.gather(boxes, nms_indices)\n classes = tf.gather(classes, nms_indices)\n ### END CODE HERE ###\n \n return scores, boxes, classes", "_____no_output_____" ], [ "with tf.Session() as test_b:\n scores = tf.random_normal([54,], mean=1, stddev=4, seed = 1)\n boxes = tf.random_normal([54, 4], mean=1, stddev=4, seed = 1)\n classes = tf.random_normal([54,], mean=1, stddev=4, seed = 1)\n scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)\n print(\"scores[2] = \" + str(scores[2].eval()))\n print(\"boxes[2] = \" + str(boxes[2].eval()))\n print(\"classes[2] = \" + str(classes[2].eval()))\n print(\"scores.shape = \" + str(scores.eval().shape))\n print(\"boxes.shape = \" + str(boxes.eval().shape))\n print(\"classes.shape = \" + str(classes.eval().shape))", "scores[2] = 6.9384\nboxes[2] = [-5.299932 3.13798141 4.45036697 0.95942086]\nclasses[2] = -2.24527\nscores.shape = (10,)\nboxes.shape = (10, 4)\nclasses.shape = (10,)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **scores[2]**\n </td>\n <td>\n 6.9384\n </td>\n </tr>\n <tr>\n <td>\n **boxes[2]**\n </td>\n <td>\n [-5.299932 3.13798141 4.45036697 0.95942086]\n </td>\n </tr>\n\n <tr>\n <td>\n **classes[2]**\n </td>\n <td>\n -2.24527\n </td>\n </tr>\n <tr>\n <td>\n **scores.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n <tr>\n <td>\n **boxes.shape**\n </td>\n <td>\n (10, 4)\n </td>\n </tr>\n\n <tr>\n <td>\n **classes.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "### 2.4 Wrapping up the filtering\n\nIt's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented. \n\n**Exercise**: Implement `yolo_eval()` which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions (which we have provided): \n\n```python\nboxes = yolo_boxes_to_corners(box_xy, box_wh) \n```\nwhich converts the yolo box coordinates (x,y,w,h) to box corners' coordinates (x1, y1, x2, y2) to fit the input of `yolo_filter_boxes`\n```python\nboxes = scale_boxes(boxes, image_shape)\n```\nYOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image--for example, the car detection dataset had 720x1280 images--this step rescales the boxes so that they can be plotted on top of the original 720x1280 image. \n\nDon't worry about these two functions; we'll show you where they need to be called. ", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: yolo_eval\n\ndef yolo_eval(yolo_outputs, image_shape = (720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5):\n \"\"\"\n Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes.\n \n Arguments:\n yolo_outputs -- output of the encoding model (for image_shape of (608, 608, 3)), contains 4 tensors:\n box_confidence: tensor of shape (None, 19, 19, 5, 1)\n box_xy: tensor of shape (None, 19, 19, 5, 2)\n box_wh: tensor of shape (None, 19, 19, 5, 2)\n box_class_probs: tensor of shape (None, 19, 19, 5, 80)\n image_shape -- tensor of shape (2,) containing the input shape, in this notebook we use (608., 608.) (has to be float32 dtype)\n max_boxes -- integer, maximum number of predicted boxes you'd like\n score_threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box\n iou_threshold -- real value, \"intersection over union\" threshold used for NMS filtering\n \n Returns:\n scores -- tensor of shape (None, ), predicted score for each box\n boxes -- tensor of shape (None, 4), predicted box coordinates\n classes -- tensor of shape (None,), predicted class for each box\n \"\"\"\n \n ### START CODE HERE ### \n \n # Retrieve outputs of the YOLO model (≈1 line)\n box_confidence, box_xy, box_wh, box_class_probs = yolo_outputs\n\n # Convert boxes to be ready for filtering functions \n boxes = yolo_boxes_to_corners(box_xy, box_wh)\n\n # Use one of the functions you've implemented to perform Score-filtering with a threshold of score_threshold (≈1 line)\n scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, score_threshold)\n \n # Scale boxes back to original image shape.\n boxes = scale_boxes(boxes, image_shape)\n\n # Use one of the functions you've implemented to perform Non-max suppression with a threshold of iou_threshold (≈1 line)\n scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes, max_boxes, iou_threshold)\n \n ### END CODE HERE ###\n \n return scores, boxes, classes", "_____no_output_____" ], [ "with tf.Session() as test_b:\n yolo_outputs = (tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1),\n tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1))\n scores, boxes, classes = yolo_eval(yolo_outputs)\n print(\"scores[2] = \" + str(scores[2].eval()))\n print(\"boxes[2] = \" + str(boxes[2].eval()))\n print(\"classes[2] = \" + str(classes[2].eval()))\n print(\"scores.shape = \" + str(scores.eval().shape))\n print(\"boxes.shape = \" + str(boxes.eval().shape))\n print(\"classes.shape = \" + str(classes.eval().shape))", "scores[2] = 138.791\nboxes[2] = [ 1292.32971191 -278.52166748 3876.98925781 -835.56494141]\nclasses[2] = 54\nscores.shape = (10,)\nboxes.shape = (10, 4)\nclasses.shape = (10,)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **scores[2]**\n </td>\n <td>\n 138.791\n </td>\n </tr>\n <tr>\n <td>\n **boxes[2]**\n </td>\n <td>\n [ 1292.32971191 -278.52166748 3876.98925781 -835.56494141]\n </td>\n </tr>\n\n <tr>\n <td>\n **classes[2]**\n </td>\n <td>\n 54\n </td>\n </tr>\n <tr>\n <td>\n **scores.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n <tr>\n <td>\n **boxes.shape**\n </td>\n <td>\n (10, 4)\n </td>\n </tr>\n\n <tr>\n <td>\n **classes.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "<font color='blue'>\n**Summary for YOLO**:\n- Input image (608, 608, 3)\n- The input image goes through a CNN, resulting in a (19,19,5,85) dimensional output. \n- After flattening the last two dimensions, the output is a volume of shape (19, 19, 425):\n - Each cell in a 19x19 grid over the input image gives 425 numbers. \n - 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes, as seen in lecture. \n - 85 = 5 + 80 where 5 is because $(p_c, b_x, b_y, b_h, b_w)$ has 5 numbers, and and 80 is the number of classes we'd like to detect\n- You then select only few boxes based on:\n - Score-thresholding: throw away boxes that have detected a class with a score less than the threshold\n - Non-max suppression: Compute the Intersection over Union and avoid selecting overlapping boxes\n- This gives you YOLO's final output. ", "_____no_output_____" ], [ "## 3 - Test YOLO pretrained model on images", "_____no_output_____" ], [ "In this part, you are going to use a pretrained model and test it on the car detection dataset. As usual, you start by **creating a session to start your graph**. Run the following cell.", "_____no_output_____" ] ], [ [ "sess = K.get_session()", "_____no_output_____" ] ], [ [ "### 3.1 - Defining classes, anchors and image shape.", "_____no_output_____" ], [ "Recall that we are trying to detect 80 classes, and are using 5 anchor boxes. We have gathered the information about the 80 classes and 5 boxes in two files \"coco_classes.txt\" and \"yolo_anchors.txt\". Let's load these quantities into the model by running the next cell. \n\nThe car detection dataset has 720x1280 images, which we've pre-processed into 608x608 images. ", "_____no_output_____" ] ], [ [ "class_names = read_classes(\"model_data/coco_classes.txt\")\nanchors = read_anchors(\"model_data/yolo_anchors.txt\")\nimage_shape = (720., 1280.) ", "_____no_output_____" ] ], [ [ "### 3.2 - Loading a pretrained model\n\nTraining a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. You are going to load an existing pretrained Keras YOLO model stored in \"yolo.h5\". (These weights come from the official YOLO website, and were converted using a function written by Allan Zelener. References are at the end of this notebook. Technically, these are the parameters from the \"YOLOv2\" model, but we will more simply refer to it as \"YOLO\" in this notebook.) Run the cell below to load the model from this file.", "_____no_output_____" ] ], [ [ "yolo_model = load_model(\"model_data/yolo.h5\")", "/opt/conda/lib/python3.6/site-packages/keras/models.py:251: UserWarning: No training configuration found in save file: the model was *not* compiled. Compile it manually.\n warnings.warn('No training configuration found in save file: '\n" ] ], [ [ "This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains.", "_____no_output_____" ] ], [ [ "yolo_model.summary()", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\ninput_1 (InputLayer) (None, 608, 608, 3) 0 \n____________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 608, 608, 32) 864 input_1[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_1 (BatchNorm (None, 608, 608, 32) 128 conv2d_1[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_1 (LeakyReLU) (None, 608, 608, 32) 0 batch_normalization_1[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 304, 304, 32) 0 leaky_re_lu_1[0][0] \n____________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 304, 304, 64) 18432 max_pooling2d_1[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_2 (BatchNorm (None, 304, 304, 64) 256 conv2d_2[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_2 (LeakyReLU) (None, 304, 304, 64) 0 batch_normalization_2[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_2 (MaxPooling2D) (None, 152, 152, 64) 0 leaky_re_lu_2[0][0] \n____________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 152, 152, 128) 73728 max_pooling2d_2[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_3 (BatchNorm (None, 152, 152, 128) 512 conv2d_3[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_3 (LeakyReLU) (None, 152, 152, 128) 0 batch_normalization_3[0][0] \n____________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 152, 152, 64) 8192 leaky_re_lu_3[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_4 (BatchNorm (None, 152, 152, 64) 256 conv2d_4[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_4 (LeakyReLU) (None, 152, 152, 64) 0 batch_normalization_4[0][0] \n____________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 152, 152, 128) 73728 leaky_re_lu_4[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_5 (BatchNorm (None, 152, 152, 128) 512 conv2d_5[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_5 (LeakyReLU) (None, 152, 152, 128) 0 batch_normalization_5[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_3 (MaxPooling2D) (None, 76, 76, 128) 0 leaky_re_lu_5[0][0] \n____________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 76, 76, 256) 294912 max_pooling2d_3[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_6 (BatchNorm (None, 76, 76, 256) 1024 conv2d_6[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_6 (LeakyReLU) (None, 76, 76, 256) 0 batch_normalization_6[0][0] \n____________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 76, 76, 128) 32768 leaky_re_lu_6[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_7 (BatchNorm (None, 76, 76, 128) 512 conv2d_7[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_7 (LeakyReLU) (None, 76, 76, 128) 0 batch_normalization_7[0][0] \n____________________________________________________________________________________________________\nconv2d_8 (Conv2D) (None, 76, 76, 256) 294912 leaky_re_lu_7[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_8 (BatchNorm (None, 76, 76, 256) 1024 conv2d_8[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_8 (LeakyReLU) (None, 76, 76, 256) 0 batch_normalization_8[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_4 (MaxPooling2D) (None, 38, 38, 256) 0 leaky_re_lu_8[0][0] \n____________________________________________________________________________________________________\nconv2d_9 (Conv2D) (None, 38, 38, 512) 1179648 max_pooling2d_4[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_9 (BatchNorm (None, 38, 38, 512) 2048 conv2d_9[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_9 (LeakyReLU) (None, 38, 38, 512) 0 batch_normalization_9[0][0] \n____________________________________________________________________________________________________\nconv2d_10 (Conv2D) (None, 38, 38, 256) 131072 leaky_re_lu_9[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_10 (BatchNor (None, 38, 38, 256) 1024 conv2d_10[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_10 (LeakyReLU) (None, 38, 38, 256) 0 batch_normalization_10[0][0] \n____________________________________________________________________________________________________\nconv2d_11 (Conv2D) (None, 38, 38, 512) 1179648 leaky_re_lu_10[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_11 (BatchNor (None, 38, 38, 512) 2048 conv2d_11[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_11 (LeakyReLU) (None, 38, 38, 512) 0 batch_normalization_11[0][0] \n____________________________________________________________________________________________________\nconv2d_12 (Conv2D) (None, 38, 38, 256) 131072 leaky_re_lu_11[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_12 (BatchNor (None, 38, 38, 256) 1024 conv2d_12[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_12 (LeakyReLU) (None, 38, 38, 256) 0 batch_normalization_12[0][0] \n____________________________________________________________________________________________________\nconv2d_13 (Conv2D) (None, 38, 38, 512) 1179648 leaky_re_lu_12[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_13 (BatchNor (None, 38, 38, 512) 2048 conv2d_13[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_13 (LeakyReLU) (None, 38, 38, 512) 0 batch_normalization_13[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_5 (MaxPooling2D) (None, 19, 19, 512) 0 leaky_re_lu_13[0][0] \n____________________________________________________________________________________________________\nconv2d_14 (Conv2D) (None, 19, 19, 1024) 4718592 max_pooling2d_5[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_14 (BatchNor (None, 19, 19, 1024) 4096 conv2d_14[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_14 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_14[0][0] \n____________________________________________________________________________________________________\nconv2d_15 (Conv2D) (None, 19, 19, 512) 524288 leaky_re_lu_14[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_15 (BatchNor (None, 19, 19, 512) 2048 conv2d_15[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_15 (LeakyReLU) (None, 19, 19, 512) 0 batch_normalization_15[0][0] \n____________________________________________________________________________________________________\nconv2d_16 (Conv2D) (None, 19, 19, 1024) 4718592 leaky_re_lu_15[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_16 (BatchNor (None, 19, 19, 1024) 4096 conv2d_16[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_16 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_16[0][0] \n____________________________________________________________________________________________________\nconv2d_17 (Conv2D) (None, 19, 19, 512) 524288 leaky_re_lu_16[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_17 (BatchNor (None, 19, 19, 512) 2048 conv2d_17[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_17 (LeakyReLU) (None, 19, 19, 512) 0 batch_normalization_17[0][0] \n____________________________________________________________________________________________________\nconv2d_18 (Conv2D) (None, 19, 19, 1024) 4718592 leaky_re_lu_17[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_18 (BatchNor (None, 19, 19, 1024) 4096 conv2d_18[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_18 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_18[0][0] \n____________________________________________________________________________________________________\nconv2d_19 (Conv2D) (None, 19, 19, 1024) 9437184 leaky_re_lu_18[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_19 (BatchNor (None, 19, 19, 1024) 4096 conv2d_19[0][0] \n____________________________________________________________________________________________________\nconv2d_21 (Conv2D) (None, 38, 38, 64) 32768 leaky_re_lu_13[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_19 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_19[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_21 (BatchNor (None, 38, 38, 64) 256 conv2d_21[0][0] \n____________________________________________________________________________________________________\nconv2d_20 (Conv2D) (None, 19, 19, 1024) 9437184 leaky_re_lu_19[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_21 (LeakyReLU) (None, 38, 38, 64) 0 batch_normalization_21[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_20 (BatchNor (None, 19, 19, 1024) 4096 conv2d_20[0][0] \n____________________________________________________________________________________________________\nspace_to_depth_x2 (Lambda) (None, 19, 19, 256) 0 leaky_re_lu_21[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_20 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_20[0][0] \n____________________________________________________________________________________________________\nconcatenate_1 (Concatenate) (None, 19, 19, 1280) 0 space_to_depth_x2[0][0] \n leaky_re_lu_20[0][0] \n____________________________________________________________________________________________________\nconv2d_22 (Conv2D) (None, 19, 19, 1024) 11796480 concatenate_1[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_22 (BatchNor (None, 19, 19, 1024) 4096 conv2d_22[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_22 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_22[0][0] \n____________________________________________________________________________________________________\nconv2d_23 (Conv2D) (None, 19, 19, 425) 435625 leaky_re_lu_22[0][0] \n====================================================================================================\nTotal params: 50,983,561\nTrainable params: 50,962,889\nNon-trainable params: 20,672\n____________________________________________________________________________________________________\n" ] ], [ [ "**Note**: On some computers, you may see a warning message from Keras. Don't worry about it if you do--it is fine.\n\n**Reminder**: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure (2).", "_____no_output_____" ], [ "### 3.3 - Convert output of the model to usable bounding box tensors\n\nThe output of `yolo_model` is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following cell does that for you.", "_____no_output_____" ] ], [ [ "yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))", "(<tf.Tensor 'Sigmoid_2:0' shape=(?, ?, ?, 5, 1) dtype=float32>, <tf.Tensor 'truediv_6:0' shape=(?, ?, ?, 5, 2) dtype=float32>, <tf.Tensor 'truediv_7:0' shape=(?, ?, ?, 5, 2) dtype=float32>, <tf.Tensor 'Reshape_14:0' shape=(?, ?, ?, 5, 80) dtype=float32>)\n" ] ], [ [ "You added `yolo_outputs` to your graph. This set of 4 tensors is ready to be used as input by your `yolo_eval` function.", "_____no_output_____" ], [ "### 3.4 - Filtering boxes\n\n`yolo_outputs` gave you all the predicted boxes of `yolo_model` in the correct format. You're now ready to perform filtering and select only the best boxes. Lets now call `yolo_eval`, which you had previously implemented, to do this. ", "_____no_output_____" ] ], [ [ "scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)", "_____no_output_____" ] ], [ [ "### 3.5 - Run the graph on an image\n\nLet the fun begin. You have created a (`sess`) graph that can be summarized as follows:\n\n1. <font color='purple'> yolo_model.input </font> is given to `yolo_model`. The model is used to compute the output <font color='purple'> yolo_model.output </font>\n2. <font color='purple'> yolo_model.output </font> is processed by `yolo_head`. It gives you <font color='purple'> yolo_outputs </font>\n3. <font color='purple'> yolo_outputs </font> goes through a filtering function, `yolo_eval`. It outputs your predictions: <font color='purple'> scores, boxes, classes </font>\n\n**Exercise**: Implement predict() which runs the graph to test YOLO on an image.\nYou will need to run a TensorFlow session, to have it compute `scores, boxes, classes`.\n\nThe code below also uses the following function:\n```python\nimage, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n```\nwhich outputs:\n- image: a python (PIL) representation of your image used for drawing boxes. You won't need to use it.\n- image_data: a numpy-array representing the image. This will be the input to the CNN.\n\n**Important note**: when a model uses BatchNorm (as is the case in YOLO), you will need to pass an additional placeholder in the feed_dict {K.learning_phase(): 0}.", "_____no_output_____" ] ], [ [ "def predict(sess, image_file):\n \"\"\"\n Runs the graph stored in \"sess\" to predict boxes for \"image_file\". Prints and plots the preditions.\n \n Arguments:\n sess -- your tensorflow/Keras session containing the YOLO graph\n image_file -- name of an image stored in the \"images\" folder.\n \n Returns:\n out_scores -- tensor of shape (None, ), scores of the predicted boxes\n out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes\n out_classes -- tensor of shape (None, ), class index of the predicted boxes\n \n Note: \"None\" actually represents the number of predicted boxes, it varies between 0 and max_boxes. \n \"\"\"\n\n # Preprocess your image\n image, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n\n # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.\n # You'll need to use feed_dict={yolo_model.input: ... , K.learning_phase(): 0})\n ### START CODE HERE ### (≈ 1 line)\n out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes], feed_dict={yolo_model.input: image_data, K.learning_phase(): 0}) \n ### END CODE HERE ###\n\n # Print predictions info\n print('Found {} boxes for {}'.format(len(out_boxes), image_file))\n # Generate colors for drawing bounding boxes.\n colors = generate_colors(class_names)\n # Draw bounding boxes on the image file\n draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n # Save the predicted bounding box on the image\n image.save(os.path.join(\"out\", image_file), quality=90)\n # Display the results in the notebook\n output_image = scipy.misc.imread(os.path.join(\"out\", image_file))\n imshow(output_image)\n \n return out_scores, out_boxes, out_classes", "_____no_output_____" ] ], [ [ "Run the following cell on the \"test.jpg\" image to verify that your function is correct.", "_____no_output_____" ] ], [ [ "out_scores, out_boxes, out_classes = predict(sess, \"test.jpg\")", "Found 7 boxes for test.jpg\ncar 0.60 (925, 285) (1045, 374)\ncar 0.66 (706, 279) (786, 350)\nbus 0.67 (5, 266) (220, 407)\ncar 0.70 (947, 324) (1280, 705)\ncar 0.74 (159, 303) (346, 440)\ncar 0.80 (761, 282) (942, 412)\ncar 0.89 (367, 300) (745, 648)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **Found 7 boxes for test.jpg**\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.60 (925, 285) (1045, 374)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.66 (706, 279) (786, 350)\n </td>\n </tr>\n <tr>\n <td>\n **bus**\n </td>\n <td>\n 0.67 (5, 266) (220, 407)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.70 (947, 324) (1280, 705)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.74 (159, 303) (346, 440)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.80 (761, 282) (942, 412)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.89 (367, 300) (745, 648)\n </td>\n </tr>\n</table>", "_____no_output_____" ], [ "The model you've just run is actually able to detect 80 different classes listed in \"coco_classes.txt\". To test the model on your own images:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Write your image's name in the cell above code\n 4. Run the code and see the output of the algorithm!\n\nIf you were to run your session in a for loop over all your images. Here's what you would get:\n\n<center>\n<video width=\"400\" height=\"200\" src=\"nb_images/pred_video_compressed2.mp4\" type=\"video/mp4\" controls>\n</video>\n</center>\n\n<caption><center> Predictions of the YOLO model on pictures taken from a camera while driving around the Silicon Valley <br> Thanks [drive.ai](https://www.drive.ai/) for providing this dataset! </center></caption>", "_____no_output_____" ], [ "<font color='blue'>\n**What you should remember**:\n- YOLO is a state-of-the-art object detection model that is fast and accurate\n- It runs an input image through a CNN which outputs a 19x19x5x85 dimensional volume. \n- The encoding can be seen as a grid where each of the 19x19 cells contains information about 5 boxes.\n- You filter through all the boxes using non-max suppression. Specifically: \n - Score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes\n - Intersection over Union (IoU) thresholding to eliminate overlapping boxes\n- Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise. ", "_____no_output_____" ], [ "**References**: The ideas presented in this notebook came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener's github repository. The pretrained weights used in this exercise came from the official YOLO website. \n- Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi - [You Only Look Once: Unified, Real-Time Object Detection](https://arxiv.org/abs/1506.02640) (2015)\n- Joseph Redmon, Ali Farhadi - [YOLO9000: Better, Faster, Stronger](https://arxiv.org/abs/1612.08242) (2016)\n- Allan Zelener - [YAD2K: Yet Another Darknet 2 Keras](https://github.com/allanzelener/YAD2K)\n- The official YOLO website (https://pjreddie.com/darknet/yolo/) ", "_____no_output_____" ], [ "**Car detection dataset**:\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/4.0/88x31.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" property=\"dct:title\">The Drive.ai Sample Dataset</span> (provided by drive.ai) is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>. We are especially grateful to Brody Huval, Chih Hu and Rahul Patel for collecting and providing this dataset. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af18e69ac70aa7c7c9e330eead5b1f1e9b29787
1,378
ipynb
Jupyter Notebook
notebooks/plantilla.ipynb
URJCDSLab/descansare
6aa4a76211e6ac50c7b5fe6ffcf793c6b9f527ba
[ "FTL" ]
null
null
null
notebooks/plantilla.ipynb
URJCDSLab/descansare
6aa4a76211e6ac50c7b5fe6ffcf793c6b9f527ba
[ "FTL" ]
null
null
null
notebooks/plantilla.ipynb
URJCDSLab/descansare
6aa4a76211e6ac50c7b5fe6ffcf793c6b9f527ba
[ "FTL" ]
null
null
null
18.621622
102
0.511611
[ [ [ "<img src=\"img/dslogo.png\" alt=\"title\" align=\"right\">", "_____no_output_____" ] ], [ [ "print(\"Hola, esto es código y no se muestra\")", "Hola, esto es código y no se muestra\n" ] ], [ [ "## Esto si se muestra y es markdown", "_____no_output_____" ] ], [ [ "#Guardar en HTML sin codigo\n!jupyter nbconvert plantilla.ipynb --to html --log-level WARN --no-input --output-dir='results/'", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af1a0660a3243c452893cd21806da3c17eab041
964,665
ipynb
Jupyter Notebook
10_Covid_Timeseries_Modelling.ipynb
BiBa-01/Capstone_Covid
3c1282bcd2e3bc6b24683fa0bb16665df2721e0b
[ "MIT" ]
null
null
null
10_Covid_Timeseries_Modelling.ipynb
BiBa-01/Capstone_Covid
3c1282bcd2e3bc6b24683fa0bb16665df2721e0b
[ "MIT" ]
2
2021-04-28T11:58:38.000Z
2021-04-29T07:12:24.000Z
10_Covid_Timeseries_Modelling.ipynb
BiBa-01/Capstone_Covid
3c1282bcd2e3bc6b24683fa0bb16665df2721e0b
[ "MIT" ]
2
2021-08-02T14:53:41.000Z
2021-08-30T13:33:12.000Z
508.253425
203,364
0.93038
[ [ [ "***\n# COVID-19 Vaccination Progress - Modelling \n****", "_____no_output_____" ] ], [ [ "#common imports:\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport os\nfrom itertools import permutations\n\n#import for visualization\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport matplotlib.colors\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n\n#for Modelling/timeseries:\nimport statsmodels.formula.api as smf\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom scipy.ndimage import gaussian_filter\n\n\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nfrom statsmodels.tsa.stattools import adfuller,kpss\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.arima_model import ARIMA\nimport statsmodels.api as sm\n\nfrom statsmodels.graphics.tsaplots import plot_pacf\n\n\nfrom pmdarima.arima import auto_arima\nimport statsmodels.graphics.tsaplots as tsaplot\nfrom statsmodels.tsa.holtwinters import Holt, ExponentialSmoothing, SimpleExpSmoothing\nfrom statsmodels.graphics.tsaplots import plot_pacf\nsns.set(rc={'figure.figsize':(20,15)})\n\n#suppress pandas future warnings:\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n# Where to save the figures\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"end_to_end_project\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\nos.makedirs(IMAGES_PATH, exist_ok=True)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)\n\n\n \nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV, KFold\nfrom sklearn import ensemble\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn import metrics", "_____no_output_____" ], [ "# load cleaned data time series:\ndf_time_m = pd.read_csv('timeseriesformodel.csv')", "_____no_output_____" ] ], [ [ "## Time series", "_____no_output_____" ], [ "For the vaccination progress we have daily observations points as daily vaccinations or people vaccinated per country. Our target is to predict how the vaccination progress will continue in the next weeks. ", "_____no_output_____" ] ], [ [ "#set DatetimeIndex as index for our DataFrame:\ndf_daily = pd.read_csv('df2.csv', index_col=None)\n#df_daily = df_daily.set_index('date')\ndf_daily['date'] = pd.to_datetime(df_daily['date'])\ndf_daily.head(3)", "_____no_output_____" ], [ "df_daily.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 7497 entries, 0 to 7496\nData columns (total 12 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 country 7497 non-null object \n 1 iso_code 7497 non-null object \n 2 date 7497 non-null datetime64[ns]\n 3 total_vaccinations 4523 non-null float64 \n 4 people_vaccinated 3983 non-null float64 \n 5 people_fully_vaccinated 7497 non-null float64 \n 6 daily_vaccinations 7491 non-null float64 \n 7 total_vaccinations_per_hundred 4523 non-null float64 \n 8 people_vaccinated_per_hundred 3983 non-null float64 \n 9 people_fully_vaccinated_per_hundred 7497 non-null float64 \n 10 daily_vaccinations_per_million 7491 non-null float64 \n 11 vaccines 7497 non-null object \ndtypes: datetime64[ns](1), float64(8), object(3)\nmemory usage: 703.0+ KB\n" ], [ "#df_daily.reset_index(inplace=True)", "_____no_output_____" ], [ "df_daily['day'] = df_daily['date'].dt.day\ndf_daily['month'] = df_daily['date'].dt.month\ndf_daily['year'] = df_daily['date'].dt.year\ndf_daily['weekday_name'] = df_daily['date'].dt.day_name()#day_of_week \n# Display a random sampling of 5 rows\ndf_daily.sample(5, random_state=0)", "_____no_output_____" ], [ "# Define plotting parameters and custom color palette \ncmaps_hex = ['#193251','#FF5A36','#1E4485', '#99D04A','#FF5A36', '#DB6668']\n#sns.set_palette(palette=cmaps_hex)\nsns_c = sns.color_palette(palette=cmaps_hex)\n\nplt.rcParams['figure.figsize'] = [15, 5]\nplt.rcParams['figure.dpi'] = 100", "_____no_output_____" ], [ "df_time = df_daily.copy()\ndf_time.set_index('date')\ndf_time = df_time[['date','country', 'daily_vaccinations', 'people_fully_vaccinated_per_hundred']]\ndf_time.sample(5)", "_____no_output_____" ], [ "#check for missing values\nmissing_values = pd.DataFrame(df_time.isnull().sum(), columns=['ID'])\nmissing_values", "_____no_output_____" ], [ "df_time.dropna(axis=0)", "_____no_output_____" ], [ "#check for missing values\nmissing_values = pd.DataFrame(df_time.isnull().sum(), columns=['ID'])\nmissing_values", "_____no_output_____" ], [ "df_time.isnull().any()", "_____no_output_____" ], [ "df_time.dropna(inplace = True)", "_____no_output_____" ], [ "#check for missing values in %\nround(100*(df_time.isnull().sum()/len(df_time.index)),0)", "_____no_output_____" ], [ "# plot the time series for daily vaccinations:\ndf_time1= df_time[['date','daily_vaccinations']]\ndf_time1.set_index('date', inplace=True)\nax1 = df_time1.plot()\n# Add title and axis names\n\nax1.ticklabel_format(useOffset=False, style='plain', axis='y')\nplt.title('Global daily vaccinations')\nplt.xlabel('Date')\nplt.ylabel('Daily vaccinations')\n\nplt.show()", "_____no_output_____" ] ], [ [ "## Modelling with data for the United States", "_____no_output_____" ] ], [ [ "#Select data for the United States only:\ndf_time_us = df_time[df_time.country == 'United States']\ndf_time_us", "_____no_output_____" ], [ "#df_time_us.set_index('date', inplace=True)\n\nax1 = df_time_us['daily_vaccinations'].plot()\n# Add title and axis names\n\nax1.ticklabel_format(useOffset=False, style='plain', axis='y')\nplt.title('Daily vaccinations in the US')\nplt.xlabel('Date')\nplt.ylabel('Daily vaccinations')\n\nplt.show();", "_____no_output_____" ] ], [ [ "## Check for Stationarity", "_____no_output_____" ], [ "Stationarity: A time series is stationary if its statistical properties (e.g. mean, variance, etc.) are the same throughout the series, independently of the point in time where they were observed. There are no long-term predictable patterns such as trend or seasonality. Plots will show a roughly horizontal trend with constant variance.\n\nWe use the decomposition method which allows us to separately view seasonality, trend and random which is the variability in the data set after removing the effects of the seasonality and trend.\n\nTrend: Increase and decrease in the value of the data. It can further be divided into global and local trends.\n\nSeasonality: Repetitive pattern of fixed frequency that is visible in the data.\n\nNoise/Resiudals: Random data that can be obtained after extracting the trend and seasonal component.", "_____no_output_____" ] ], [ [ "# Check decomposition of trend, seasonality and residue of original time series\n\ndecomposition = seasonal_decompose(x=df_time_us['daily_vaccinations'], period=10)# model='multiplicative',\n\nfig, ax = plt.subplots(4, 1, figsize=(12, 12), constrained_layout=True)\ndecomposition.observed.plot(c=sns_c[0], ax=ax[0])\nax[0].set(title='observed')\ndecomposition.trend.plot(c=sns_c[1], ax=ax[1])\nax[1].set(title='trend')\ndecomposition.seasonal.plot(c=sns_c[2], ax=ax[2])\nax[2].set(title='seasonal')\ndecomposition.resid.plot(c=sns_c[3], ax=ax[3])\nax[3].set(title='residual')\nfig.set_size_inches(20, 10);", "_____no_output_____" ] ], [ [ "The daily vaccinations for the United States have a clear increasing trend and a weekly seasonality. That means it is not stationary.\n\n----\n\nStatistical test: To confirm our visual observation on the above plot, we will use ADF and KPSS test:\n\n----\n\nADF (Augemented Dickey-Fuller):\n\nNull Hypothesis: The series is not stationary.\n\nAlternate Hypothesis: The series is stationary.\n\n----\n\nKPSS (Kwiatkowski-Phillips-Schmidt-Shin):\n\nNull Hypothesis: The series is stationary.\n\nAlternated Hypothesis: The series is not stationary.\n\n\n", "_____no_output_____" ] ], [ [ "def stationarity_test(daily_vaccinations):\n \n # Calculate rolling mean and rolling standard deviation\n rolling_mean = daily_vaccinations.rolling(7).mean()\n rolling_std_dev = daily_vaccinations.rolling(7).std()\n \n # Plot the statistics\n plt.figure(figsize=(24,6))\n plt.plot(rolling_mean, color='#FF5A36', label='Rolling Mean')\n plt.plot(rolling_std_dev, color='#1E4485', label = 'Rolling Std Dev')\n plt.plot(daily_vaccinations, color='#99D04A',label='Original Time Series')\n plt.xticks([])\n plt.legend(loc='best')\n plt.title('Rolling Mean and Standard Deviation')\n \n # ADF test\n print(\"ADF Test:\")\n adf_test = adfuller(daily_vaccinations,autolag='AIC')\n print('Null Hypothesis: Not Stationary')\n print('ADF Statistic: %f' % adf_test[0])\n print('p-value: %f' % adf_test[1])\n print('----'*10)\n \n # KPSS test\n print(\"KPSS Test:\")\n kpss_test = kpss(daily_vaccinations, regression='c', nlags=\"legacy\", store=False)\n print('Null Hypothesis: Stationary')\n print('KPSS Statistic: %f' % kpss_test[0])\n print('p-value: %f' % kpss_test[1])\n print('----'*10)\n \nstationarity_test(df_time_us['daily_vaccinations'])", "ADF Test:\nNull Hypothesis: Not Stationary\nADF Statistic: -0.520049\np-value: 0.888044\n----------------------------------------\nKPSS Test:\nNull Hypothesis: Stationary\nKPSS Statistic: 0.815044\np-value: 0.010000\n----------------------------------------\n" ] ], [ [ "The p-value of the ADF test is > 0.5 which tells us that we cannot decline the null-hypothesis that the time series is non-stationary and the p-value for the KPSS test is below 0.05 which means we can reject this null-hypothesis that it is stationary. Both tests indicates that it is not stationary.", "_____no_output_____" ], [ "We need to de-trend the time series and make the series stationary.", "_____no_output_____" ] ], [ [ "# De-trending the time series\ndf_time_us_diff = df_time_us['daily_vaccinations'].diff(periods =2).dropna()", "_____no_output_____" ], [ "#re-test stationarity:\ndef stationarity_test(daily_vaccinations):\n \n # Calculate rolling mean and rolling standard deviation\n rolling_mean = daily_vaccinations.rolling(30).mean()\n rolling_std_dev = daily_vaccinations.rolling(30).std()\n \n # Plot the statistics\n plt.figure(figsize=(24,6))\n plt.plot(rolling_mean, color='#FF5A36', label='Rolling Mean')\n plt.plot(rolling_std_dev, color='#1E4485', label = 'Rolling Std Dev')\n plt.plot(daily_vaccinations, color='#99D04A',label='De-Trended Time Series')\n plt.xticks([])\n plt.legend(loc='best')\n plt.title('Rolling Mean and Standard Deviation')\n \n # ADF test\n print(\"ADF Test:\")\n adf_test = adfuller(daily_vaccinations,autolag='AIC')\n print('Null Hypothesis: Not Stationary')\n print('ADF Statistic: %f' % adf_test[0])\n print('p-value: %f' % adf_test[1])\n print('----'*10)\n \n # KPSS test\n print(\"KPSS Test:\")\n kpss_test = kpss(daily_vaccinations, regression='c', nlags=\"legacy\", store=False)\n print('Null Hypothesis: Stationary')\n print('KPSS Statistic: %f' % kpss_test[0])\n print('p-value: %f' % kpss_test[1])\n print('----'*10)\n \n#stationarity_test(df_time_us['Dailyvac_Detrend'].dropna()) df_time_us_diff\nstationarity_test(df_time_us_diff) \n# Partial Autocorrelation Plot\n#pacf = plot_pacf(df_time_us['Dailyvac_Detrend'].dropna(), lags=30)\npacf = plot_pacf(df_time_us_diff, lags=30)", "ADF Test:\nNull Hypothesis: Not Stationary\nADF Statistic: -5.096813\np-value: 0.000014\n----------------------------------------\nKPSS Test:\nNull Hypothesis: Stationary\nKPSS Statistic: 0.057998\np-value: 0.100000\n----------------------------------------\n" ] ], [ [ "After de-trending the time series the AFD test as well as the KPSS test both indicate that our series is now stationary. Having a look at the partial autocorrelation plot suggests that correlation exists at certain lags.", "_____no_output_____" ], [ "## Split the Data", "_____no_output_____" ], [ "We will split our data and take the first part as our training set.", "_____no_output_____" ] ], [ [ "# Split data into train and test set\ndf_arima = df_time_us['daily_vaccinations']\ntrain_test_split_ratio = int(len(df_arima)*0.8)\ntrain_data, test_data = df_arima[:train_test_split_ratio], df_arima[train_test_split_ratio:]\n\n# Plotting the train and test set\nplt.figure(figsize=(10,6))\nplt.title('Daily Vaccinations United America')\nplt.xlabel('Date')\nplt.ylabel('Daily Vaccinations')\nplt.xticks([])\nplt.plot(train_data, 'red', label='Train data')\nplt.plot(test_data, 'black', label='Test data')\nplt.legend();", "_____no_output_____" ] ], [ [ "### Auto-Regressive Integrated Moving Average (ARIMA)\n\nARIMA model is a combination of Auto-Regressive and Moving Average model along with the Integration of differencing. Auto-Regressive model determines the relationship between an observation and a certain number of lagged observations. The Integrated part is the differencing of the actual observations to make the time series stationary. Moving Average determines the relationship between an observation and residual error obtained by using a moving average model on the lagged observations.\n\n* *Auto-Regressive (p)*: Number of lag observations in the model. Also called lag order.\n* *Integrated (d)*: Number of times the actual observations are differenced for stationarity. Also called degree of differencing.\n* *Moving Average (q)*: Size of moving average window. Also called the order of moving average.", "_____no_output_____" ] ], [ [ "# Auto ARIMA Method\narima_model = auto_arima(train_data,\n start_p=1, start_q=1,\n max_p=5, max_q=5,\n test='adf', \n trace=True,\n alpha=0.05,\n scoring='mse',\n suppress_warnings=True,\n seasonal = True,\n stepwise=True, with_intercept=False,\n )\n\n# Fit the final model with the order\nfitted_model = arima_model.fit(train_data) \nprint(fitted_model.summary())\n\n# Forecasting values\nforecast_values = fitted_model.predict(len(test_data), alpha=0.05) \nfcv_series = pd.Series(forecast_values[0], index=test_data.index)\n\n# Plot the predicted stock price and original price\nplt.figure(figsize=(12,5), dpi=100)\nplt.plot(train_data, label='training')\nplt.plot(test_data, label='Actual daily vaccinations in the US')\nplt.plot(fcv_series,label='Predicted daily vaccinations')\nplt.title('Prediction of daily vaccination progress in the US')\nplt.xlabel('Date')\nplt.ylabel('Daily vaccinations')\nplt.xticks([])\nplt.legend(loc='upper left', fontsize=8)\nplt.show()\n\n# Evaluate the model by calculating RMSE\nrms_auto_arima = sqrt(mean_squared_error(test_data.values, fcv_series))\nprint(\"Auto-Arima RMSE :- \" + str(round(rms_auto_arima,3)))", "Performing stepwise search to minimize aic\n ARIMA(1,2,1)(0,0,0)[0] : AIC=inf, Time=0.05 sec\n ARIMA(0,2,0)(0,0,0)[0] : AIC=1758.067, Time=0.01 sec\n ARIMA(1,2,0)(0,0,0)[0] : AIC=1749.903, Time=0.01 sec\n ARIMA(0,2,1)(0,0,0)[0] : AIC=1745.630, Time=0.01 sec\n ARIMA(0,2,2)(0,0,0)[0] : AIC=1747.536, Time=0.02 sec\n ARIMA(1,2,2)(0,0,0)[0] : AIC=inf, Time=0.11 sec\n ARIMA(0,2,1)(0,0,0)[0] intercept : AIC=1747.655, Time=0.02 sec\n\nBest model: ARIMA(0,2,1)(0,0,0)[0] \nTotal fit time: 0.234 seconds\n SARIMAX Results \n==============================================================================\nDep. Variable: y No. Observations: 75\nModel: SARIMAX(0, 2, 1) Log Likelihood -870.815\nDate: Sat, 24 Apr 2021 AIC 1745.630\nTime: 21:36:46 BIC 1750.211\nSample: 0 HQIC 1747.455\n - 75 \nCovariance Type: opg \n==============================================================================\n coef std err z P>|z| [0.025 0.975]\n------------------------------------------------------------------------------\nma.L1 -0.4918 0.112 -4.380 0.000 -0.712 -0.272\nsigma2 1.402e+09 1.27e-11 1.1e+20 0.000 1.4e+09 1.4e+09\n===================================================================================\nLjung-Box (L1) (Q): 0.09 Jarque-Bera (JB): 0.12\nProb(Q): 0.76 Prob(JB): 0.94\nHeteroskedasticity (H): 3.10 Skew: -0.01\nProb(H) (two-sided): 0.01 Kurtosis: 3.19\n===================================================================================\n\nWarnings:\n[1] Covariance matrix calculated using the outer product of gradients (complex-step).\n[2] Covariance matrix is singular or near-singular, with condition number inf. Standard errors may be unstable.\n" ], [ "# Plotting diagnostics of the ARIMA model\narima_model.plot_diagnostics(figsize=(15,8))\nplt.show()", "_____no_output_____" ] ], [ [ "Histogram plus estimated density plot: The red KDE line follows closely with the N(0,1) line. This is a good indication that the residuals are normally distributed.\n\nThe Q-Q-plot: Shows that the ordered distribution of residuals (blue dots) follows the linear trend of the samples taken from a standard normal distribution with N(0,1). This is an indication that the residuals are normally distributed.\n\nThe Correlogram plot: Shows that the time series residuals have low correlation with lagged versions of itself.", "_____no_output_____" ] ], [ [ "# Holt's Exponential Smoothing Method\npred_values = test_data.copy()\npred_values = pd.DataFrame(pred_values)\nHolt_smooth_df = pd.DataFrame(columns = ['RMS','Smoothing Level','Smoothing Slope'])\n\nperm = permutations(list(np.linspace(0.05,1,num=20)), 2)\nfor i in list(perm):\n fit_Holt_smooth = ExponentialSmoothing(np.asarray(train_data)).fit(smoothing_level = i[0],smoothing_slope=i[1])\n pred_values['Holt_smooth'] = fit_Holt_smooth.forecast(len(test_data))\n\n rms = round(sqrt(mean_squared_error(test_data.values, pred_values.Holt_smooth)),3)\n Holt_smooth_df = Holt_smooth_df.append(other = {'RMS' : rms , 'Smoothing Level' : i[0], 'Smoothing Slope':i[1]} , ignore_index=True)\n\nopt_values = Holt_smooth_df.loc[Holt_smooth_df['RMS'] == min(Holt_smooth_df['RMS']),['Smoothing Level','Smoothing Slope']].values\n\n\n# Using optimised values from the lists.\nfit_Holt_smooth = ExponentialSmoothing(np.asarray(train_data)).fit(smoothing_level = opt_values[0][0],smoothing_slope=opt_values[0][1])\npred_values['Holt_smooth'] = fit_Holt_smooth.forecast(len(test_data))\n\nplt.figure(figsize=(16,8))\nplt.plot(train_data, label='Train')\nplt.plot(test_data, label='Test')\nplt.plot(pred_values['Holt_smooth'], label='Holt_smooth')\nplt.xticks([])\nplt.legend(loc='best')\nplt.title('Holt Exponential Smoothing')\nplt.show()\n\nrms_holt_exp = sqrt(mean_squared_error(test_data.values, pred_values.Holt_smooth))\nprint(\"Holt’s Exponential Smoothing RMS :- \" + str(round(rms_holt_exp,3)) + \" & Smoothing Level :- \"+str(round(opt_values[0][0],3)) + \" & Smoothing Slope :- \"+str(round(opt_values[0][1],3)))", "_____no_output_____" ] ], [ [ "## Simple Exponential Smoothing", "_____no_output_____" ] ], [ [ "# Simple Exponential Smoothing Method\n\nsimple_exponential_df = pd.DataFrame(columns = ['RMS','Smoothing Level'])\n\nfrom itertools import permutations\nperm = permutations(list(np.linspace(0.05,1,num=20)), 1)\nfor i in list(perm):\n fit_sim_exp = SimpleExpSmoothing(np.asarray(train_data)).fit(smoothing_level = i[0])\n pred_values['Simple_Exponential'] = fit_sim_exp.forecast(len(test_data))\n\n rms = round(sqrt(mean_squared_error(test_data.values, pred_values.Simple_Exponential)),3)\n simple_exponential_df = simple_exponential_df.append(other = {'RMS' : rms , 'Smoothing Level' : i[0]} , ignore_index=True)\n\nopt_values = simple_exponential_df.loc[simple_exponential_df['RMS'] == min(simple_exponential_df['RMS']),['Smoothing Level']].values\n\n\n# Use optimised values from the lists\nfit_sim_exp = SimpleExpSmoothing(np.asarray(train_data)).fit(smoothing_level = opt_values[0][0])\npred_values['Simple_Exponential'] = fit_sim_exp.forecast(len(test_data))\n\nplt.figure(figsize=(16,8))\nplt.plot(train_data, label='Train')\nplt.plot(test_data, label='Test')\nplt.plot(pred_values['Simple_Exponential'], label='Simple_Exponential')\nplt.xticks([])\nplt.legend(loc='best')\nplt.show()\n\nrms_sim_exp = sqrt(mean_squared_error(test_data.values, pred_values.Simple_Exponential))\nprint(\"Simple Exponential Smoothing RMS :- \" + str(round(rms_sim_exp,3)) + \" & Smoothing Level :- \"+str(round(opt_values[0][0],3)))", "_____no_output_____" ] ], [ [ "## Evaluation of the Models\n\nTo evaluate the performance of the model, we will use Root Mean Squared Error (RMSE) and compare which model performed the best.", "_____no_output_____" ] ], [ [ "# Printing RMSE of all the methods\nprint(\"RMSE of all the methods\")\nprint(\"Auto-Arima: \", round(rms_auto_arima,3))\nprint(\"Simple Exponential Smoothing: \", round(rms_sim_exp,3))\nprint(\"Holt’s Exponential Smoothing: \", round(rms_holt_exp,3))", "RMSE of all the methods\nAuto-Arima: 271015.731\nSimple Exponential Smoothing: 312111.348\nHolt’s Exponential Smoothing: 312111.348\n" ] ], [ [ "From the three models we trained the Auto-Arima reached the smallest RSME but all three models do not deliver a good prediction yet.", "_____no_output_____" ], [ "## Future Work:\n- Tune models for better predictions\n- If required use other models\n- Use updated dataset for more data", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4af1a2b99a10e4ba90ee864409e71a4f52472878
359,673
ipynb
Jupyter Notebook
study_roadmaps/2_transfer_learning_roadmap/5_exploring_model_families/2_vgg/1.1) Intro to vgg network - mxnet backend.ipynb
shubham7169/monk_v1
2d63ba9665160cc7758ba0541baddf87c1cfa578
[ "Apache-2.0" ]
7
2020-07-26T08:37:29.000Z
2020-10-30T10:23:11.000Z
study_roadmaps/2_transfer_learning_roadmap/5_exploring_model_families/2_vgg/1.1) Intro to vgg network - mxnet backend.ipynb
aayush-fadia/monk_v1
4234eecede3427efc952461408e2d14ef5fa0e57
[ "Apache-2.0" ]
null
null
null
study_roadmaps/2_transfer_learning_roadmap/5_exploring_model_families/2_vgg/1.1) Intro to vgg network - mxnet backend.ipynb
aayush-fadia/monk_v1
4234eecede3427efc952461408e2d14ef5fa0e57
[ "Apache-2.0" ]
null
null
null
252.225105
253,804
0.91604
[ [ [ "<a href=\"https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/2_transfer_learning_roadmap/5_exploring_model_families/2_vgg/1.1)%20Intro%20to%20vgg%20network%20-%20mxnet%20backend.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Goals\n\n\n### Train a architectural heritage site classifier using vgg16\n\n### Understand what lies inside vgg network", "_____no_output_____" ], [ "# What is vgg\n\n## Readings on vgg\n\n 1) Points from https://towardsdatascience.com/vgg-neural-networks-the-next-step-after-alexnet-3f91fa9ffe2c\n - VGG addresses another very important aspect of CNNs: depth\n - All of VGG’s hidden layers use ReLU\n - Unlike 11x11 kernels of alexnet, it uses smaller ones 1x1 and 3x3 kernels\n\n\n 2) Points from https://becominghuman.ai/what-is-the-vgg-neural-network-a590caa72643\n - Intuitively, more layer is better. However, the authors found that VGG-16 is better than VGG-19\n - Authors introduce multi-scale evaluationin the paper\n \n \n 3) Read more here - \n - https://arxiv.org/abs/1409.1556\n - https://machinelearningmastery.com/use-pre-trained-vgg-model-classify-objects-photographs/\n - https://www.cs.toronto.edu/~frossard/post/vgg16/\n - https://d2l.ai/chapter_convolutional-modern/vgg.html\n", "_____no_output_____" ], [ "# Table of Contents\n\n\n## [0. Install](#0)\n\n\n## [1. Load experiment with vgg base architecture](#1)\n\n\n## [2. Visualize vgg](#2)\n\n\n## [3. Train the classifier](#3)\n\n\n## [4. Run inference on trained classifier](#5)", "_____no_output_____" ], [ "<a id='0'></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", "Cloning into 'monk_v1'...\nremote: Enumerating objects: 200, done.\u001b[K\nremote: Counting objects: 100% (200/200), done.\u001b[K\nremote: Compressing objects: 100% (146/146), done.\u001b[K\nremote: Total 2105 (delta 110), reused 116 (delta 53), pack-reused 1905\u001b[K\nReceiving objects: 100% (2105/2105), 73.71 MiB | 4.39 MiB/s, done.\nResolving deltas: 100% (1130/1130), done.\n" ], [ "# If using Colab install using the commands below\n!cd monk_v1/installation/Misc && pip install -r requirements_colab.txt\n\n# If using Kaggle uncomment the following command\n#!cd monk_v1/installation/Misc && pip install -r requirements_kaggle.txt\n\n# Select the requirements file as per OS and CUDA version when using a local system or cloud\n#!cd monk_v1/installation/Linux && pip install -r requirements_cu9.txt", "_____no_output_____" ] ], [ [ "## Dataset - Architectural Heritage site Classification\n - https://old.datahub.io/dataset/architectural-heritage-elements-image-dataset", "_____no_output_____" ] ], [ [ "! wget --load-cookies /tmp/cookies.txt \"https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1MFu7cnxwDM7LWKgeLggMLvWIBW_-YCWC' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\\1\\n/p')&id=1MFu7cnxwDM7LWKgeLggMLvWIBW_-YCWC\" -O architectural_heritage.zip && rm -rf /tmp/cookies.txt", "_____no_output_____" ], [ "! unzip -qq architectural_heritage.zip", "_____no_output_____" ] ], [ [ "# Imports", "_____no_output_____" ] ], [ [ "# Monk\nimport os\nimport sys\nsys.path.append(\"monk_v1/monk/\");", "_____no_output_____" ], [ "#Using mxnet-gluon backend \nfrom gluon_prototype import prototype", "_____no_output_____" ] ], [ [ "<a id='1'></a>\n# Load experiment with vgg base architecture", "_____no_output_____" ], [ "## Creating and managing experiments\n - Provide project name\n - Provide experiment name\n - For a specific data create a single project\n - Inside each project multiple experiments can be created\n - Every experiment can be have diferent hyper-parameters attached to it", "_____no_output_____" ] ], [ [ "gtf = prototype(verbose=1);\ngtf.Prototype(\"Project\", \"vgg-intro\");", "Mxnet Version: 1.5.0\n\nExperiment Details\n Project: Project\n Experiment: vgg-intro\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/change_post_num_layers/6_transfer_learning_model_params/1_exploring_model_families/2_vgg/workspace/Project/vgg-intro/\n\n" ] ], [ [ "### This creates files and directories as per the following structure\n \n \n workspace\n |\n |--------Project\n |\n |\n |-----vgg-intro\n |\n |-----experiment-state.json\n |\n |-----output\n |\n |------logs (All training logs and graphs saved here)\n |\n |------models (all trained models saved here)", "_____no_output_____" ], [ "## Set dataset and select the model", "_____no_output_____" ], [ "## Quick mode training\n\n - Using Default Function\n - dataset_path\n - model_name\n - freeze_base_network\n - num_epochs\n \n \n## Sample Dataset folder structure\n\n architectural_heritage\n |\n |-----train\n |------dome\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on)\n |------altal\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on) \n |------.... (and so on)\n |\n |\n |-----val\n |------dome\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on)\n |------altal\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on) \n |------.... (and so on)", "_____no_output_____" ] ], [ [ "gtf.Default(dataset_path=\"architectural_heritage/train\", \n model_name=\"vgg16\", \n freeze_base_network=False,\n num_epochs=5);", "Dataset Details\n Train path: architectural_heritage/train\n Val path: None\n CSV train path: None\n CSV val path: None\n\nDataset Params\n Input Size: 224\n Batch Size: 4\n Data Shuffle: True\n Processors: 4\n Train-val split: 0.7\n\nPre-Composed Train Transforms\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\n\nPre-Composed Val Transforms\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\n\nDataset Numbers\n Num train images: 7164\n Num val images: 3071\n Num classes: 10\n\nModel Params\n Model name: vgg16\n Use Gpu: True\n Use pretrained: True\n Freeze base network: False\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: vgg16\n Num of potentially trainable layers: 16\n Num of actual trainable layers: 16\n\nOptimizer\n Name: sgd\n Learning rate: 0.01\n Params: {'lr': 0.01, 'momentum': 0, 'weight_decay': 0, 'momentum_dampening_rate': 0, 'clipnorm': 0.0, 'clipvalue': 0.0}\n\n\n\nLearning rate scheduler\n Name: steplr\n Params: {'step_size': 1, 'gamma': 0.98, 'last_epoch': -1}\n\nLoss\n Name: softmaxcrossentropy\n Params: {'weight': None, 'batch_axis': 0, 'axis_to_sum_over': -1, 'label_as_categories': True, 'label_smoothing': False}\n\nTraining params\n Num Epochs: 5\n\nDisplay params\n Display progress: True\n Display progress realtime: True\n Save Training logs: True\n Save Intermediate models: True\n Intermediate model prefix: intermediate_model_\n\n" ] ], [ [ "## From the summary above\n\n - Model Params\n Model name: vgg16\n Num of potentially trainable layers: 16\n Num of actual trainable layers: 16", "_____no_output_____" ], [ "<a id='2'></a>\n# Visualize vgg", "_____no_output_____" ] ], [ [ "gtf.Visualize_With_Netron(data_shape=(3, 224, 224), port=8082);", "Using Netron To Visualize\nNot compatible on kaggle\nCompatible only for Jupyter Notebooks\n\nStopping http://localhost:8082\nServing 'model-symbol.json' at http://localhost:8082\n" ] ], [ [ "## vgg block - 1\n \n - Creating network and blocks using monk from scratch will be dealt in different roadmap series", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/vgg_block1_mxnet.png') ", "_____no_output_____" ] ], [ [ "## Properties\n\n - This block has 3 layers\n - conv -> relu", "_____no_output_____" ], [ "## vgg block - 2\n \n - Creating network and blocks using monk from scratch will be dealt in different roadmap series", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/vgg_block2_mxnet.png') ", "_____no_output_____" ] ], [ [ "## Properties\n\n - This block has 3 layers\n - conv -> relu -> max_pool", "_____no_output_____" ], [ "## vgg fully connected chain", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/vgg_block_fc_mxnet.png') ", "_____no_output_____" ] ], [ [ "## vgg Network\n\n - Creating network and blocks using monk from scratch will be dealt in different roadmap series", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/vgg16_mxnet.png') ", "_____no_output_____" ] ], [ [ "## Properties\n\n - This network \n - has 9 type-1 blocks\n - has 5 type-2 blocks\n - post these blocks the type-3 (fc) block exists\n", "_____no_output_____" ], [ "<a id='3'></a>\n# Train the classifier", "_____no_output_____" ] ], [ [ "#Start Training\ngtf.Train();\n\n#Read the training summary generated once you run the cell and training is completed", "Training Start\n Epoch 1/5\n ----------\n" ] ], [ [ "<a id='4'></a>\n# Run inference on trained classifier", "_____no_output_____" ] ], [ [ "gtf = prototype(verbose=1);\ngtf.Prototype(\"Project\", \"vgg-intro\", eval_infer=True);", "Mxnet Version: 1.5.0\n\nModel Details\n Loading model - workspace/Project/vgg-intro/output/models/final-symbol.json\n Model loaded!\n\nExperiment Details\n Project: Project\n Experiment: vgg-intro\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/change_post_num_layers/6_transfer_learning_model_params/1_exploring_model_families/2_vgg/workspace/Project/vgg-intro/\n\n" ], [ "output = gtf.Infer(img_name = \"architectural_heritage/test/test1.jpg\");\nfrom IPython.display import Image\nImage(filename='architectural_heritage/test/test1.jpg') ", "Prediction\n Image name: architectural_heritage/test/test1.jpg\n Predicted class: bell_tower\n Predicted score: 16.3840389251709\n\n" ], [ "output = gtf.Infer(img_name = \"architectural_heritage/test/test2.jpg\");\nfrom IPython.display import Image\nImage(filename='architectural_heritage/test/test2.jpg') ", "Prediction\n Image name: architectural_heritage/test/test2.jpg\n Predicted class: vault\n Predicted score: 9.485706329345703\n\n" ], [ "output = gtf.Infer(img_name = \"architectural_heritage/test/test3.jpg\");\nfrom IPython.display import Image\nImage(filename='architectural_heritage/test/test3.jpg') ", "Prediction\n Image name: architectural_heritage/test/test3.jpg\n Predicted class: dome(outer)\n Predicted score: 15.606271743774414\n\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4af1aa6c1acf3ebcf34aeee5c53c02140690a999
11,768
ipynb
Jupyter Notebook
cpd3.5/notebooks/python_sdk/deployments/pmml/Use PMML to predict iris species.ipynb
kwright15/watson-machine-learning-samples
fed00fa740d2a8f0e653a98c49d3d63a4788c472
[ "Apache-2.0" ]
27
2020-09-09T20:46:03.000Z
2021-11-29T20:13:35.000Z
cpd3.5/notebooks/python_sdk/deployments/pmml/Use PMML to predict iris species.ipynb
kwright15/watson-machine-learning-samples
fed00fa740d2a8f0e653a98c49d3d63a4788c472
[ "Apache-2.0" ]
6
2020-09-21T12:50:05.000Z
2021-01-09T14:06:41.000Z
cpd3.5/notebooks/python_sdk/deployments/pmml/Use PMML to predict iris species.ipynb
kwright15/watson-machine-learning-samples
fed00fa740d2a8f0e653a98c49d3d63a4788c472
[ "Apache-2.0" ]
55
2020-09-14T12:38:44.000Z
2022-03-18T13:28:34.000Z
26.38565
253
0.541723
[ [ [ "# Use PMML to predict iris species with `ibm-watson-machine-learning`", "_____no_output_____" ], [ "This notebook contains steps from storing sample PMML model to starting scoring new data. \n\nSome familiarity with python is helpful. This notebook uses Python 3.\n\nYou will use a **Iris** data set, which details measurements of iris perianth. Use the details of this data set to predict iris species.\n\n## Learning goals\n\nThe learning goals of this notebook are:\n\n- Working with the WML instance\n- Online deployment of PMML model\n- Scoring of deployed model\n\n\n## Contents\n\nThis notebook contains the following parts:\n\n1.\t[Setup](#setup)\n2.\t[Model upload](#upload) \n3.\t[Web service creation](#deploy)\n4.\t[Scoring](#score)\n5. [Clean up](#cleanup)\n6.\t[Summary and next steps](#summary)", "_____no_output_____" ], [ "<a id=\"setup\"></a>\n## 1. Set up the environment\n\nBefore you use the sample code in this notebook, you must perform the following setup tasks:\n\n- Contact with your Cloud Pack for Data administrator and ask him for your account credentials", "_____no_output_____" ], [ "### Connection to WML\n\nAuthenticate the Watson Machine Learning service on IBM Cloud Pack for Data. You need to provide platform `url`, your `username` and `password`.", "_____no_output_____" ] ], [ [ "wml_credentials = {\n \"username\": username,\n \"password\": password,\n \"url\": url,\n \"instance_id\": 'openshift',\n \"version\": '3.5'\n}", "_____no_output_____" ] ], [ [ "### Install and import the `ibm-watson-machine-learning` package\n**Note:** `ibm-watson-machine-learning` documentation can be found <a href=\"http://ibm-wml-api-pyclient.mybluemix.net/\" target=\"_blank\" rel=\"noopener no referrer\">here</a>.", "_____no_output_____" ] ], [ [ "!pip install -U ibm-watson-machine-learning", "_____no_output_____" ], [ "from ibm_watson_machine_learning import APIClient\n\nclient = APIClient(wml_credentials)", "_____no_output_____" ] ], [ [ "### Working with spaces\n\nFirst of all, you need to create a space that will be used for your work. If you do not have space already created, you can use `{PLATFORM_URL}/ml-runtime/spaces?context=icp4data` to create one.\n\n- Click New Deployment Space\n- Create an empty space\n- Go to space `Settings` tab\n- Copy `space_id` and paste it below\n\n**Tip**: You can also use SDK to prepare the space for your work. More information can be found [here](https://github.com/IBM/watson-machine-learning-samples/blob/master/cpd3.5/notebooks/python_sdk/instance-management/Space%20management.ipynb).\n\n**Action**: Assign space ID below", "_____no_output_____" ] ], [ [ "space_id = 'PASTE YOUR SPACE ID HERE'", "_____no_output_____" ] ], [ [ "You can use `list` method to print all existing spaces.", "_____no_output_____" ] ], [ [ "client.spaces.list(limit=10)", "_____no_output_____" ] ], [ [ "To be able to interact with all resources available in Watson Machine Learning, you need to set **space** which you will be using.", "_____no_output_____" ] ], [ [ "client.set.default_space(space_id)", "_____no_output_____" ] ], [ [ "<a id=\"upload\"></a>\n## 2. Upload model", "_____no_output_____" ], [ "In this section you will learn how to upload the model to the Cloud.", "_____no_output_____" ], [ "**Action**: Download sample PMML model from git project using wget.", "_____no_output_____" ] ], [ [ "import os\nfrom wget import download\n\nsample_dir = 'pmml_sample_model'\nif not os.path.isdir(sample_dir):\n os.mkdir(sample_dir)\n \nfilename=os.path.join(sample_dir, 'iris_chaid.xml')\nif not os.path.isfile(filename):\n filename = download('https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cpd3.5/models/pmml/iris-species/model/iris_chaid.xml', out=sample_dir)", "_____no_output_____" ] ], [ [ "Store downloaded file in Watson Machine Learning repository.", "_____no_output_____" ] ], [ [ "sw_spec_uid = client.software_specifications.get_uid_by_name(\"spark-mllib_2.4\")\n\nmeta_props = {\n client.repository.ModelMetaNames.NAME: \"pmmlmodel\",\n client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sw_spec_uid,\n client.repository.ModelMetaNames.TYPE: 'pmml_4.2.1'}", "_____no_output_____" ], [ "published_model = client.repository.store_model(model=filename, meta_props=meta_props)", "_____no_output_____" ] ], [ [ "**Note:** You can see that model is successfully stored in Watson Machine Learning Service.", "_____no_output_____" ] ], [ [ "client.repository.list_models()", "_____no_output_____" ] ], [ [ "<a id=\"deployment\"></a>\n## 3. Create online deployment", "_____no_output_____" ], [ "You can use commands bellow to create online deployment for stored model (web service).", "_____no_output_____" ] ], [ [ "model_uid = client.repository.get_model_uid(published_model)\ndeployment = client.deployments.create(\n artifact_uid=model_uid,\n meta_props={\n client.deployments.ConfigurationMetaNames.NAME: \"Test deployment\",\n client.deployments.ConfigurationMetaNames.ONLINE:{}}\n)", "\n\n#######################################################################################\n\nSynchronous deployment creation for uid: '462aeca7-cce1-4934-8f2e-47296906dea4' started\n\n#######################################################################################\n\n\ninitializing.....\nready\n\n\n------------------------------------------------------------------------------------------------\nSuccessfully finished deployment creation, deployment_uid='adefa69e-f646-4bfc-899d-34e26f2caddb'\n------------------------------------------------------------------------------------------------\n\n\n" ] ], [ [ "<a id=\"scoring\"></a>\n## 4. Scoring", "_____no_output_____" ], [ "You can send new scoring records to web-service deployment using `score` method.", "_____no_output_____" ] ], [ [ "deployment_id = client.deployments.get_id(deployment)\n\nscoring_data = {\n client.deployments.ScoringMetaNames.INPUT_DATA: [\n {\n 'fields': ['Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width'],\n 'values': [[5.1, 3.5, 1.4, 0.2]]\n }]\n}\n\npredictions = client.deployments.score(deployment_id, scoring_data)\nprint(predictions)", "{'predictions': [{'fields': ['$R-Species', '$RC-Species', '$RP-Species', '$RP-setosa', '$RP-versicolor', '$RP-virginica', '$RI-Species'], 'values': [['setosa', 1.0, 1.0, 1.0, 0.0, 0.0, '1']]}]}\n" ] ], [ [ "As we can see this is Iris Setosa flower.", "_____no_output_____" ], [ "<a id=\"cleanup\"></a>\n## 5. Clean up ", "_____no_output_____" ], [ "If you want to clean up all created assets:\n- experiments\n- trainings\n- pipelines\n- model definitions\n- models\n- functions\n- deployments\n\nplease follow up this sample [notebook](https://github.com/IBM/watson-machine-learning-samples/blob/master/cpd3.5/notebooks/python_sdk/instance-management/Machine%20Learning%20artifacts%20management.ipynb).", "_____no_output_____" ], [ "<a id=\"summary\"></a>\n## 6. Summary and next steps ", "_____no_output_____" ], [ " You successfully completed this notebook! You learned how to use Watson Machine Learning for PMML model deployment and scoring. \n \nCheck out our [Online Documentation](https://dataplatform.cloud.ibm.com/docs/content/analyze-data/wml-setup.html) for more samples, tutorials, documentation, how-tos, and blog posts. ", "_____no_output_____" ], [ "### Authors\n\n**Lukasz Cmielowski**, PhD, is a Software Architect and Data Scientist at IBM.", "_____no_output_____" ], [ "Copyright © 2020, 2021 IBM. This notebook and its source code are released under the terms of the MIT License.", "_____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" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af1ab4ec4bce577b57b6b675262f2cddfa67990
659,069
ipynb
Jupyter Notebook
.ipynb_checkpoints/map_cville_airbnbs-checkpoint.ipynb
philvarner/cville_airbnb
8644aab13d2b16bb1e2d9f532c4fe83773ece439
[ "MIT" ]
null
null
null
.ipynb_checkpoints/map_cville_airbnbs-checkpoint.ipynb
philvarner/cville_airbnb
8644aab13d2b16bb1e2d9f532c4fe83773ece439
[ "MIT" ]
null
null
null
.ipynb_checkpoints/map_cville_airbnbs-checkpoint.ipynb
philvarner/cville_airbnb
8644aab13d2b16bb1e2d9f532c4fe83773ece439
[ "MIT" ]
null
null
null
2,370.751799
649,084
0.961869
[ [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport geopandas as gpd", "_____no_output_____" ], [ "\n# read the AirBnB csv file into pandas, change all the addresses to be upper case to later match city data\nairbnb_list = pd.read_csv('data/cville_airbnb_locations.csv')\nairbnb_list['address'] = airbnb_list['address'].str.upper()\n", "_____no_output_____" ], [ "# read the city parcel data with geopandas, make a column for full address by combining Street Numer and Street Name making sure to put space in middle\ncville_parcels = gpd.read_file('https://opendata.arcgis.com/datasets/0e9946c2a77d4fc6ad16d9968509c588_72.geojson')\ncville_parcels['fulladdress'] = cville_parcels.StreetNumber+' '+cville_parcels.StreetName\n", "_____no_output_____" ], [ "# merge the AirBnB list and city parcels based on the address columns with number and street\nparcels_and_airbnb = pd.merge(airbnb_list, cville_parcels, left_on='address', right_on='fulladdress')\n\n#read the Cville Streets file to give things more context in the plot\ncville_streets = gpd.read_file('https://opendata.arcgis.com/datasets/e5a3e226dd9d4399aa014858f489852a_60.geojson')\n\n# find those addresses that show up post merge more than twice....those are probaby hotels, so change their type\nparcels_and_airbnb['address_count'] = parcels_and_airbnb.groupby('address').address.transform('count')\nparcels_and_airbnb.loc[parcels_and_airbnb['address_count'] > 2, 'type'] = 'hotel'\n\n# make it so we can map the merged data frame again\nairbnb_to_map = gpd.GeoDataFrame(parcels_and_airbnb, geometry ='geometry')\n\n# make pretty plot big enough to see with street and AirBnB addresses where color relates to type of rental. Give a legend, turn off plot axes\nfig, ax = plt.subplots(figsize=(30,30))\ncville_streets.plot(ax=ax, color='0.8')\nairbnb_to_map.plot(ax=ax, column='type', legend=True, legend_kwds={'fontsize':'x-large'})\nplt.axis('off')\nplt.show()\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4af1b2d6baa7c4f5f98958c468e8b3ca57171016
28,554
ipynb
Jupyter Notebook
tutorial/tutorial05_metadata_preprocessing.ipynb
farthur/melusine
121fbb17da221b12186a275d5843b466ce65d954
[ "Apache-2.0" ]
2
2019-11-14T14:19:56.000Z
2020-05-06T16:08:30.000Z
tutorial/tutorial05_metadata_preprocessing.ipynb
farthur/melusine
121fbb17da221b12186a275d5843b466ce65d954
[ "Apache-2.0" ]
null
null
null
tutorial/tutorial05_metadata_preprocessing.ipynb
farthur/melusine
121fbb17da221b12186a275d5843b466ce65d954
[ "Apache-2.0" ]
null
null
null
31.104575
172
0.395531
[ [ [ "# Metadata preprocessing tutorial", "_____no_output_____" ], [ "Melusine **prepare_data.metadata_engineering subpackage** provides classes to preprocess the metadata :\n- **MetaExtension :** a transformer which creates an 'extension' feature extracted from regex in metadata. It extracts the extensions of mail adresses.\n- **MetaDate :** a transformer which creates new features from dates such as: hour, minute, dayofweek.\n- **MetaAttachmentType :** a transformer which creates an 'attachment type' feature extracted from regex in metadata. It extracts the extensions of attached files.\n- **Dummifier :** a transformer to dummifies categorial features.\n\nAll the classes have **fit_transform** methods.", "_____no_output_____" ], [ "### Input dataframe", "_____no_output_____" ], [ "- To use a **MetaExtension** transformer : the dataframe requires a **from** column\n- To use a **MetaDate** transformer : the dataframe requires a **date** column\n- To use a **MetaAttachmentType** transformer : the dataframe requires a **attachment** column with the list of attached files", "_____no_output_____" ] ], [ [ "from melusine.data.data_loader import load_email_data\nimport ast\n\ndf_emails = load_email_data()\ndf_emails = df_emails[['from','date', 'attachment']]", "_____no_output_____" ], [ "df_emails['from']", "_____no_output_____" ], [ "df_emails['date']", "_____no_output_____" ], [ "df_emails['attachment'] = df_emails['attachment'].apply(ast.literal_eval)\ndf_emails['attachment']", "_____no_output_____" ] ], [ [ "### MetaExtension transformer", "_____no_output_____" ], [ "A **MetaExtension transformer** creates an *extension* feature extracted from regex in metadata. It extracts the extensions of mail adresses.", "_____no_output_____" ] ], [ [ "from melusine.prepare_email.metadata_engineering import MetaExtension\n\nmeta_extension = MetaExtension()", "_____no_output_____" ], [ "df_emails = meta_extension.fit_transform(df_emails)", "_____no_output_____" ], [ "df_emails.extension", "_____no_output_____" ] ], [ [ "### MetaDate transformer", "_____no_output_____" ], [ "A **MetaDate transformer** creates new features from dates : hour, minute and dayofweek", "_____no_output_____" ] ], [ [ "from melusine.prepare_email.metadata_engineering import MetaDate\n\nmeta_date = MetaDate()", "_____no_output_____" ], [ "df_emails = meta_date.fit_transform(df_emails)", "_____no_output_____" ], [ "df_emails.date[0]", "_____no_output_____" ], [ "df_emails.hour[0]", "_____no_output_____" ], [ "df_emails.loc[0,'min']", "_____no_output_____" ], [ "df_emails.dayofweek[0]", "_____no_output_____" ] ], [ [ "### MetaAttachmentType transformer", "_____no_output_____" ], [ "A **MetaAttachmentType transformer** creates an *attachment_type* feature extracted from an attachment names list. It extracts the extensions of attachments files.", "_____no_output_____" ] ], [ [ "from melusine.prepare_email.metadata_engineering import MetaAttachmentType\n\nmeta_pj = MetaAttachmentType()", "_____no_output_____" ], [ "df_emails = meta_pj.fit_transform(df_emails)", "_____no_output_____" ], [ "df_emails.attachment_type", "_____no_output_____" ] ], [ [ "### Dummifier transformer", "_____no_output_____" ], [ "A **Dummifier transformer** dummifies categorial features.\n\nIts arguments are :\n- **columns_to_dummify** : a list of the metadata columns to dummify.", "_____no_output_____" ] ], [ [ "from melusine.prepare_email.metadata_engineering import Dummifier\ndummifier = Dummifier(columns_to_dummify=['extension','attachment_type', 'dayofweek', 'hour', 'min'])", "_____no_output_____" ], [ "df_meta = dummifier.fit_transform(df_emails)", "_____no_output_____" ], [ "df_meta.columns", "_____no_output_____" ], [ "df_meta.head()", "_____no_output_____" ], [ "df_meta.to_csv('./data/metadata.csv', index=False, encoding='utf-8', sep=';')", "_____no_output_____" ] ], [ [ "### Custom metadata transformer", "_____no_output_____" ], [ "A custom transformer can be implemented to extract metadata from a column :", "_____no_output_____" ], [ "```python\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass MetaDataCustom(BaseEstimator, TransformerMixin):\n \"\"\"Transformer which creates custom matadata\n\n Compatible with scikit-learn API.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n arguments\n \"\"\"\n\n def fit(self, X, y=None):\n \"\"\" Fit method\"\"\"\n return self\n\n def transform(self, X):\n \"\"\"Transform method\"\"\"\n X['custom_metadata'] = X['column'].apply(self.get_metadata)\n return X\n```", "_____no_output_____" ], [ "The name of the output column can then be given as argument to a Dummifier transformer :", "_____no_output_____" ], [ "```python\ndummifier = Dummifier(columns_to_dummify=['custom_metadata'])\n```", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af1b7bd258bc01f12e7b6c1b1cafe9d7c71c079
375,044
ipynb
Jupyter Notebook
Labs/Lab 4 Python/Lab 4.1 Aplicaciones de la derivada.ipynb
bwcastillo/MN_1
c2bead62afc0f67e345544d71c0015eb7f4351c0
[ "MIT" ]
3
2020-06-11T23:45:15.000Z
2020-07-28T23:49:49.000Z
Labs/Lab 4 Python/Lab 4.1 Aplicaciones de la derivada.ipynb
DataOwl-Chile/MN_1
acfd9c466734d41e723633ce19c8e595704197c0
[ "MIT" ]
1
2020-06-18T22:47:48.000Z
2020-06-18T22:47:48.000Z
Labs/Lab 4 Python/Lab 4.1 Aplicaciones de la derivada.ipynb
bwcastillo/MN_1
c2bead62afc0f67e345544d71c0015eb7f4351c0
[ "MIT" ]
7
2020-06-08T23:12:54.000Z
2020-09-11T07:33:31.000Z
141.04701
86,507
0.815736
[ [ [ "<p><img alt=\"DataOwl\" width=150 src=\"http://gwsolutions.cl/Images/dataowl.png\", align=\"left\", hspace=0, vspace=5></p>\n\n<h1 align=\"center\">Aplicación de la derivada</h1>\n\n<h4 align=\"center\">Ecuaciones de una variable y Optimización</h4>\n<pre><div align=\"center\"> La idea de este notebook es que sirva para iniciarse en conceptos\nmatemáticos para aplicar la derivada numérica en la resolución\nde ecuaciones de una variable y optimización.</div>", "_____no_output_____" ], [ "# Aplicaciones de la derivada\n\n\nEn clases anteriores, abordamos el problema de encontrar dónde una función se anula. En este Notebook veremos que las derivadas también nos pueden ayudar en este desafío, además de poder aplicarse en otros problemas, como la aproximación de una función mediante polinomios y la optimización de una función.", "_____no_output_____" ], [ "## 4. Ecuaciones de una variable (continuación)\n\n### 4.1 Método de la Secante\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Secant_method.svg/450px-Secant_method.svg.png\" alt=\"Método de la secante\" width=280 align=\"center\" hspace=0 vspace=5 padding:5px />\n\nDe la clase anterior, sabemos que una función $f$ puede ser cortada en dos de sus puntos mediante una recta llamada *secante* Esta recta tiene una ecuación bien definida, esta vez dada por los puntos $(x_0,f(x_0))$, $(x_1,f(x_1))$ y la fórmula\n\n$$y\\ =\\ \\frac{f(x_1)-f(x_0)}{x_1-x_0}(x-x_1)+f(x_1)$$\n \nPara encontrar un valor $x$ en que $f(x)=0$, se puede aproximar el resultado esperado utilizando $y=0$ en la fórmula anterior. Esto da lugar a una solución parcial\n \n$$x = x_1-f(x_1)\\frac{x_1-x_0}{f(x_1)-f(x_0)}$$\n \nEsto se puede extender de forma iterativa, generando una sucesión de valores $x_n$ que se aproximan a la solución real:\n\n$$x_n = x_{n-1}-f(x_{n-1})\\frac{x_{n-1}-x_{n-2}}{f(x_{n-1})-f(x_{n-2})}$$\n\nEsto depende de la elección de dos puntos de inicio, $x_0$ y $x_1$, además de algunas propiedades que debe satisfacer $f$, que mencionaremos dentro de poco. Este método se conoce como **Método de la Secante**.\n\n### 4.2 Método de Newton-Raphson\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/NewtonIteration_Ani.gif/450px-NewtonIteration_Ani.gif\" width=450 alt=\"Método de Newton-Raphson\" align=\"center\"/> \n\nDel mismo modo, si la diferencia entre $x_{n-1}$ y $x_{n-2}$ es \"pequeña\", se puede aproximar la sucesión anterior a la fórmula\n\n$$x_n = x_{n-1}-\\frac{f(x_{n-1})}{f'(x_{n-1})}$$\n\ndonde ahora la recurrencia sólo depende de un paso anterior, por lo cual se requiere un solo punto $x_0$ de inicio. Además, este último método converge más rápido que el Método de la Secante, y se conoce como **Método de Newton-Raphson**.\n\n### 4.3 Hipótesis necesarias\n\nEs necesario notar que ambos métodos tienen sus limitaciones, siendo las más importante que haya **sólo un cero** (para el Método de la Secante), que $f'(x)\\neq0$ (para el Método de Newton-Raphson) y que la función sea continuamente dos veces derivable. \n\nEste último punto nos obliga a definir qué es ser \"continuamente dos veces derivable\". Sin embargo, la forma más inmediata de abordar esto, es simplemente decir que el método utilizado para calcular la derivada de $f$ lo usamos ahora para calcular la derivada de $f'$, y que el resultado es continuo, en el sentido que vimos en clases anteriores. Lo que se consigue es llamado **segunda derivada** de $f$, y se denota $\\frac{d^2f}{dx^2}(x)$ o $f''(x)$.", "_____no_output_____" ], [ "## 5. Optimización\n\nEl objetivo de esta rama de las Matemáticas es encontrar dónde las funciones alcanzan su valor máximo o mínimo, qué condiciones deben cumplirse para que éstos existan y de qué forma se puede aproximar dichos valores. En esta sección, veremos ideas básicas de optimización en funciones reales diferenciables con derivada continua, en problemas irrestrictos.\n\nRecordemos que la derivada de una función $f$ representa en un punto $x$ cuánto vale la pendiente de la recta tangente a su curva, en ese punto. Por lo tanto, cuando $f'(x)>0$, se dice que la función crece entorno a ese punto, y decrece cuando $f'(x)<0$. Como vimos en el ejercicio de encontrar ceros en una función continua, el hecho de que haya un cambio de signo en la función $f'$ implica que debe existir un valor $\\bar{x}$ en que $f(\\bar{x})=0$. Un punto $\\bar{x}$ con esta característica se llama **punto estacionario**, ya que ahí la función no crece ni decrece. Esto indica que, si encontramos dicho valor $\\bar{x}$, éste será un *candidato* a máximo o mínimo (¡existen los *puntos silla*!).\n\nYa conocemos formas de encontrar ceros de una función. Podemos aplicarlo en nuestra función $f'$ para encontrar, aproximadamente, dónde ésta se anula y así tener lo candidatos a óptimo. Para conocer mejor la naturaleza de el candidato $\\bar{x}$, será necesario calcular $f''(\\bar{x})$. Si se obtiene que $f''(\\bar{x})>0$, sin duda $\\bar{x}$ será **mínimo**, mientras que si $f''(\\bar{x})<0$, $\\bar{x}$ será **máximo**. El caso $f''(\\bar{x})=0$ es más problemático, aunque matemáticamente es abordable y visualmente lo es aún más.\n", "_____no_output_____" ] ], [ [ "# Importando las librerías\n%matplotlib notebook\nimport numpy as np\nimport matplotlib.colors as mcolors # Nos permite utilizar una paleta de colores más amplia\nimport matplotlib.pyplot as plt\nimport experimento5 as ex", "_____no_output_____" ], [ "def f(x): # Alguna función de ejemplo\n return 0.5 - np.sin(2 * x)\n\ndef g(x): # Alguna función de ejemplo\n return (np.exp(-x ** 2) - x) / ((x + 1) ** 2 + (x - 1) ** 2)\n\ndef h(x):\n return np.exp(x)", "_____no_output_____" ], [ "# Probamos nuestras funciones para calcular derivadas, con distintos tamaños de arreglo y dx\n\nx = np.linspace(-np.pi, np.pi, 1000)\ny = g(x)\ndydx1 = ex.derivadavec(x, y)\ndydx2 = ex.derivadafun(0, np.pi/2, g, 0.001)\n\nx2 = np.linspace(0, np.pi/2, len(dydx2))\n\nplt.plot(x, dydx1, color='gold', label='Derivada vector', zorder=0)\nplt.plot(x2, dydx2, color='crimson', label='Derivada función', zorder=1)\nplt.plot(x, y, color='gray', label='Función', zorder=2)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Comparación de cálculo de derivadas')\nplt.legend()\nplt.grid()\nplt.show()", "_____no_output_____" ], [ "# Buscamos los ceros de g(x)\n\nx0, y0 = ex.ceros(-3, 3, g)\nprint(x0)", "[0.65625]\n" ], [ "# Probamos nuestras funciones para calcular derivadas, con distintos tamaños de arreglo y dx\n\nx = np.linspace(-np.pi, np.pi, 10000)\ny = g(x)\ndydx = ex.derivadavec(x, y)\nd2ydx2 = ex.derivadavec(x, dydx)\n\nx0, y0 = ex.ceros(-5, 5, g, x[1]-x[0])\n\nplt.plot(x, y, color='gray', label='g(x)', zorder=0)\nplt.plot(x, dydx, color='red', label='g´(x)', zorder=1)\nplt.plot(x, d2ydx2, color='blue', label='g´´(x)', zorder=2)\nplt.plot(x0, y0, marker='*', color='green', label='Cero de g', linestyle='', zorder=3)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Función y sus derivadas')\nplt.legend()\nplt.grid()\nplt.show()", "_____no_output_____" ], [ "# Incluimos el cálculo de los x en que f(x)=0\n\nx1, y1 = ex.cerof(x, dydx, x[1]-x[0])\n\n# Probamos nuestras funciones para calcular derivadas, con distintos tamaños de arreglo y dx\n\nx = np.linspace(-np.pi, np.pi, 10000)\ny = g(x)\ndydx = ex.derivadavec(x, y)\nd2ydx2 = ex.derivadavec(x, dydx)\n\nplt.plot(x, y, color='gray', label='g(x)', zorder=0)\nplt.plot(x, dydx, color='red', label='g´(x)', zorder=1)\nplt.plot(x, d2ydx2, color='blue', label='g´´(x)', zorder=2)\nplt.plot(x1, y1, marker='*', color='green', label='Cero de g', linestyle='', zorder=3)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Función y sus derivadas')\nplt.legend()\nplt.grid()\nplt.show()", "_____no_output_____" ] ], [ [ "¿Cómo podríamos encontrar el valor de f''(x) en los valores x que encontramos?", "_____no_output_____" ], [ "## Ejercicios\n\n**1.-** Intente escribir un código para utilizar el Método de la Secante y el Método de Newton-Raphson y aplíquelo a alguna de las funciones vistas.\n\n**2.-** \n\n**a)** En relación con el problema de encontrar $x\\in[a,b]$ tal que $f(x)\\ =\\ 0$, busque (por ejemplo, en Wikipedia) información sobre el Método de Householder o *Householder's Method*. Note que el método de Newton-Raphson es uno de estos modelos, pero que hay casos en que se usa derivadas de orden superior. Intente escribir un algoritmo con alguno de esos métodos (incluso puede hacer un algoritmo que permita utilizar cualquiera de los métodos), y aplíquelo a la función\n\n$$f(x)\\ =\\ \\frac{e^{-x^2}-x^3}{(x+1)^2+(x-1)^2}$$\n\nPara ello, grafique esa función en algún intervalo en que se sepa que la función se anula. Puede ayudarse con el uso de una grilla, escribiendo\n```Python\nplt.grid() # Para desplegar la grilla\nplt.show() # Para mostrar el gráfico\n```\ny tome un valor inicial $x_0$ que visualmente se halle cercano a la solución.\n\n**b)** Haga lo mismo que antes, buscando información sobre el Método de Halley (o *Halley's Method*).\n\n**3.-** Utilice el Notebook y cualquiera de los métodos vistos o los definidos en clase para estudiar las siguientes funciones:\n <ol style=\"list-style-type:lower-alpha\">\n <li>$\\qquad f(x) = x^p,\\quad p\\in\\mathbb{R}$. Pruebe con distintos valores de $p$ (distinga entre $p\\ge0$ y $p<0$ <br><br></li>\n \n <li>$\\qquad g(x) = \\frac{x}{\\sqrt{x^2+1}}$ <br><br></li>\n \n <li>$\\qquad h(x) = \\frac{\\sin^2(x)}{x},\\quad x\\neq0$</li>\n </ol> \n\n **4.-** Intente programar un algoritmo para encontrar los mínimos y máximos de una función $f$, si los tiene.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
4af1bb2cd85931bb453aec09a8d50231c62fb1b7
4,120
ipynb
Jupyter Notebook
Small Assignments/Small Assignment 5/Small Assignment 5.ipynb
ds-modules/ENVECON-118-FA20
c4cbba63063ef0aeeb685b2ef67340deaa7b4cc4
[ "BSD-3-Clause" ]
null
null
null
Small Assignments/Small Assignment 5/Small Assignment 5.ipynb
ds-modules/ENVECON-118-FA20
c4cbba63063ef0aeeb685b2ef67340deaa7b4cc4
[ "BSD-3-Clause" ]
null
null
null
Small Assignments/Small Assignment 5/Small Assignment 5.ipynb
ds-modules/ENVECON-118-FA20
c4cbba63063ef0aeeb685b2ef67340deaa7b4cc4
[ "BSD-3-Clause" ]
1
2020-11-01T07:28:53.000Z
2020-11-01T07:28:53.000Z
27.651007
274
0.611893
[ [ [ "# Small Assignment 5\n\nUse the data in `givedirectly.csv` for this exercise.\n\n## Food security and the impact of Give Directly Cash Transfers in Kenya.\n\nHouseholds in Kenya often face food insecurity. In a 2016 paper, Johannes Haushofer and Jeremy Shapiro decided to work with a non-profit called Give Directly to evaluate the impact of simply giving cash to low-income Kenyan households - no strings attached. \n\nThe data `givedirectly.csv` consist of all households who were part of Haushofer and Shapiro's randomized control trial. The dataset includes the following variables:\n\ntreat: dummy variable equal to one if the household received the cash transfer.\n\nfemale: dummy variable equal to one if the woman in the household was the one to receive the cash transfer.\n\nmarried: dummy variable equal to one if the head of the household is married.\n\nnchildren: number of children the head of household has.\n\nhhsize: total number of people living in the houseohld.\n\neduc: years of education for the household head.\n\nchildren18: number of children under 18 living in the household.\n\nfullmeals: dummy variable equal to one if every member of the household eats at least two full meals every day.\n\n### 1. Estimate the impact of the program on food security. That is, estimate the impact of the program on the variable fullmeals. Interpret your estimate.\n\n", "_____no_output_____" ] ], [ [ "#Write your code here", "_____no_output_____" ] ], [ [ "Write your explanation here", "_____no_output_____" ], [ "### 2. What are the conditions for the validity of the method to measure the causal impact of the program? Proceed with the appropriate tests that support the validity of the randomization.\n\n", "_____no_output_____" ], [ "Write your explanation here", "_____no_output_____" ] ], [ [ "#Write your code here", "_____no_output_____" ] ], [ [ "Write your explanation here", "_____no_output_____" ], [ "### 3. Add variables that may influence the likelihood that every household member eats at least two full meals per day. Do they actually explain the food security variable? Do they affect the estimated coefficient of the program? Is that what you expected, and why?\n", "_____no_output_____" ] ], [ [ "#Write your code here", "_____no_output_____" ] ], [ [ "Write your explanation here", "_____no_output_____" ], [ "### 4. Now, write a simple equation (without unnecessary variables) that allows you to test whether the impact of program is equal for households where the household head was married versus those where the household head was not married. Report the result and comment.", "_____no_output_____" ] ], [ [ "#Write your code here", "_____no_output_____" ] ], [ [ "Write your explanation here", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4af1cfb67948a911ebd86fd55123be367ae51b2c
265,280
ipynb
Jupyter Notebook
examples/toy-examples/iris_multi_classification.ipynb
ahmed-mohamed-sn/ATgfe
93f983478340663444b2eb6baaf0879e88373580
[ "MIT" ]
16
2019-11-14T14:02:34.000Z
2022-02-15T17:39:03.000Z
examples/toy-examples/iris_multi_classification.ipynb
arita37/ATgfe
2c3a6516bd0ca0f78e7c3efbd0611fdaa91f8e96
[ "MIT" ]
1
2021-01-08T09:59:29.000Z
2021-01-08T10:20:01.000Z
examples/toy-examples/iris_multi_classification.ipynb
arita37/ATgfe
2c3a6516bd0ca0f78e7c3efbd0611fdaa91f8e96
[ "MIT" ]
5
2019-11-23T03:42:28.000Z
2021-12-02T19:30:56.000Z
239.422383
34,920
0.894474
[ [ [ "# Results summary", "_____no_output_____" ], [ "| Logistic Regression | LightGBM Classifier | Logistic Regression + ATgfe |\n|-------------------------------------------------------------------------|------------------------------------------------------------------------|--------------------------------------------------------------------|\n| <ul> <li>10-CV Accuracy: 0.926</li><li>Test-data Accuracy: 0.911</li><li>ROC_AUC: 0.99</li> </ul> | <ul> <li>10-CV Accuracy: 0.946</li><li>Test-data Accuracy: 0.977</li><li>ROC_AUC: 1.0</li> </ul> | <ul> <li>10-CV Accuracy: **0.98**</li><li>Test-data Accuracy: **1.0**</li><li>ROC_AUC: **1.0**</li> </ul> |", "_____no_output_____" ], [ "# Import packages", "_____no_output_____" ] ], [ [ "from atgfe.GeneticFeatureEngineer import GeneticFeatureEngineer\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.compose import make_column_transformer\nfrom sklearn.metrics import accuracy_score, make_scorer, balanced_accuracy_score, recall_score\nfrom yellowbrick.classifier import ClassificationReport, ConfusionMatrix, ROCAUC, PrecisionRecallCurve\nfrom lightgbm import LGBMClassifier\nfrom sklearn import datasets", "_____no_output_____" ], [ "def prepare_column_names(columns):\n return [col.replace(' ', '').replace('(cm)', '_cm') for col in columns]", "_____no_output_____" ], [ "sklearn_data = datasets.load_iris()\ncolumns = prepare_column_names(sklearn_data.feature_names)\ndf = pd.DataFrame(data=sklearn_data.data, columns=columns)\ndf['class'] = sklearn_data.target\ndf['class'] = df['class'].astype(str)\ndf.head()", "_____no_output_____" ], [ "target = 'class'\nX = df.drop(target, axis=1).copy()\nY = df.loc[:, target].copy()\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=42)", "_____no_output_____" ], [ "classes = ['setosa', 'versicolor', 'virginica']\nnumerical_features = X.columns.tolist()", "_____no_output_____" ], [ "def classification_report(model):\n visualizer = ClassificationReport(model, classes=classes, support=True)\n visualizer.fit(X_train, y_train) \n visualizer.score(X_test, y_test) \n visualizer.poof() ", "_____no_output_____" ], [ "def roc_auc(model):\n visualizer = ROCAUC(model, classes=classes)\n visualizer.fit(X_train, y_train) \n visualizer.score(X_test, y_test) \n visualizer.poof() ", "_____no_output_____" ], [ "def confusion_matrix(model):\n visualizer = ConfusionMatrix(model, classes=classes)\n visualizer.fit(X_train, y_train) \n visualizer.score(X_test, y_test) \n visualizer.poof() ", "_____no_output_____" ], [ "def precision_recall_curve(model):\n visualizer = PrecisionRecallCurve(model)\n visualizer.fit(X_train, y_train) \n visualizer.score(X_test, y_test) \n visualizer.poof() ", "_____no_output_____" ], [ "def score_model(model, X, y):\n evaluation_metric_scorer = make_scorer(balanced_accuracy_score, greater_is_better=True)\n scores = cross_val_score(estimator=model, X=X, y=y, cv=10, scoring=evaluation_metric_scorer, n_jobs=-1)\n scores_mean = scores.mean()\n score_std = scores.std()\n print('Mean of metric: {}, std: {}'.format(scores_mean, score_std))", "_____no_output_____" ], [ "def score_test_data_for_model(model, X_test, y_test):\n model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n print('Balanced Accuracy: {}'.format(balanced_accuracy_score(y_test, y_pred)))\n print('Accuracy: {}'.format(accuracy_score(y_test, y_pred)))", "_____no_output_____" ], [ "def create_new_model():\n model = make_pipeline(StandardScaler(), LogisticRegression(random_state=77, n_jobs=-1, solver='saga'))\n return model", "_____no_output_____" ] ], [ [ "# Using LightGBM", "_____no_output_____" ] ], [ [ "lgbm_model = LGBMClassifier(n_estimators=100, random_state=7)", "_____no_output_____" ], [ "score_model(lgbm_model, X, Y)", "Mean of metric: 0.9466666666666665, std: 0.040000000000000015\n" ], [ "classification_report(lgbm_model)", "_____no_output_____" ], [ "confusion_matrix(lgbm_model)", "_____no_output_____" ], [ "precision_recall_curve(lgbm_model)", "_____no_output_____" ], [ "roc_auc(lgbm_model)", "_____no_output_____" ], [ "lgbm_model.fit(X_train, y_train)\nscore_test_data_for_model(lgbm_model, X_test, y_test)", "Balanced Accuracy: 0.9743589743589745\nAccuracy: 0.9777777777777777\n" ] ], [ [ "# Using Logistic Regression", "_____no_output_____" ] ], [ [ "model = create_new_model()", "_____no_output_____" ], [ "score_model(model, X, Y)", "Mean of metric: 0.9266666666666665, std: 0.06289320754704404\n" ], [ "classification_report(model)", "_____no_output_____" ], [ "confusion_matrix(model)", "_____no_output_____" ], [ "precision_recall_curve(model)", "_____no_output_____" ], [ "roc_auc(model)", "_____no_output_____" ], [ "score_test_data_for_model(model, X_test, y_test)", "Balanced Accuracy: 0.8974358974358975\nAccuracy: 0.9111111111111111\n" ] ], [ [ "# Using ATgfe", "_____no_output_____" ] ], [ [ "model = create_new_model()", "_____no_output_____" ], [ "def micro_recall_score(y_true, y_pred):\n return recall_score(y_true, y_pred, average='micro')", "_____no_output_____" ], [ "gfe = GeneticFeatureEngineer(model, x_train=X_train, y_train=y_train, numerical_features=numerical_features,\n number_of_candidate_features=2, number_of_interacting_features=4,\n evaluation_metric=micro_recall_score, minimize_metric=False, enable_weights=True,\n n_jobs=62, cross_validation_in_objective_func=True, objective_func_cv=3)", "2019-11-27 14:11:36,342:INFO: New Engineer created with the following parameters: \n2019-11-27 14:11:36,343:INFO: \nModel type: <class 'sklearn.pipeline.Pipeline'>\nNumerical Features: ['sepallength_cm', 'sepalwidth_cm', 'petallength_cm', 'petalwidth_cm']\nNumber of candidate features: 2\nNumber of interacting features: 4\nEvaluation Metric: micro_recall_score\nMinimize metric is False \n" ], [ "gfe.fit(mu=10, lambda_=120, early_stopping_patience=5, mutation_probability=0.4, crossover_probability=0.6)", "Start of evolution\n \t \t fitness \n \t \t-------------------------------------------------------------------------------------------------------\ngen\tnevals\tavg \tbest_val_score\tgen\tgen_val_score\tmax \tmin \tnevals\tstd \ttime_in_seconds\n0 \t10 \t-1e+10\tnan \t0 \tnan \t0.941971\t-1e+11\t10 \t3e+10\tnan \n1 \t120 \t0.94017\t0.933081 \t1 \t0.933081 \t0.941971\t0.932167\t120 \t0.0036211\t2.49478 \n2 \t120 \t0.942952\t0.933081 \t2 \t0.933081 \t0.951775\t0.941971\t120 \t0.00294118\t2.61988 \n3 \t120 \t0.948914\t0.953283 \t3 \t0.953283 \t0.951775\t0.941971\t120 \t0.00437611\t2.57015 \n4 \t120 \t0.951775\t0.953283 \t4 \t0.953283 \t0.951775\t0.951775\t120 \t0 \t2.60284 \n5 \t120 \t0.951775\t0.953283 \t5 \t0.953283 \t0.951775\t0.951775\t120 \t0 \t2.55816 \n6 \t120 \t0.951775\t0.953283 \t6 \t0.953283 \t0.951775\t0.951775\t120 \t0 \t2.50075 \n7 \t120 \t0.951775\t0.953283 \t7 \t0.953283 \t0.951775\t0.951775\t120 \t0 \t2.49159 \n-- End of (successful) evolution --\nBest validation score: 0.9532828282828284\nAll columns: ['sepallength_cm', 'sepalwidth_cm', 'petallength_cm', 'petalwidth_cm', '0.543859649122807*squared(petallength_cm)/cube(sepalwidth_cm)', '0.147891891891892*squared(petallength_cm)*squared(petalwidth_cm)*log(sepallength_cm)/sepallength_cm']\n" ] ], [ [ "# Apply GFE", "_____no_output_____" ] ], [ [ "new_X = gfe.transform(X)", "_____no_output_____" ], [ "new_X.head(20)", "_____no_output_____" ], [ "model = create_new_model()", "_____no_output_____" ], [ "score_model(model, new_X, Y)", "Mean of metric: 0.9800000000000001, std: 0.04268749491621899\n" ], [ "X_train, X_test, y_train, y_test = train_test_split(new_X, Y, test_size=0.3, random_state=42)", "_____no_output_____" ], [ "classification_report(model)", "_____no_output_____" ], [ "confusion_matrix(model)", "_____no_output_____" ], [ "precision_recall_curve(model)", "_____no_output_____" ], [ "roc_auc(model)", "_____no_output_____" ], [ "score_test_data_for_model(model, X_test, y_test)", "Balanced Accuracy: 1.0\nAccuracy: 1.0\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "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", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af1d56663311712e6d80854f434a6f4ccc6bd88
33,830
ipynb
Jupyter Notebook
example/ottoGroup/.ipynb_checkpoints/otto-xgboost-checkpoint.ipynb
bikash/ML_Course
659f264b8f6f57513099af0b4ff7eb5ff03c1991
[ "Apache-2.0" ]
null
null
null
example/ottoGroup/.ipynb_checkpoints/otto-xgboost-checkpoint.ipynb
bikash/ML_Course
659f264b8f6f57513099af0b4ff7eb5ff03c1991
[ "Apache-2.0" ]
null
null
null
example/ottoGroup/.ipynb_checkpoints/otto-xgboost-checkpoint.ipynb
bikash/ML_Course
659f264b8f6f57513099af0b4ff7eb5ff03c1991
[ "Apache-2.0" ]
1
2021-07-29T09:54:41.000Z
2021-07-29T09:54:41.000Z
32.68599
186
0.509962
[ [ [ "# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom collections import Counter\nfrom sklearn import decomposition\nfrom sklearn.metrics import log_loss\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.model_selection import GridSearchCV \nimport imblearn\nfrom imblearn.over_sampling import RandomOverSampler\nfrom matplotlib import pyplot as plt\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"data\"))\n\n# Any results you write to the current directory are saved as output.", "['.DS_Store', 'test.csv', 'train.csv']\n" ], [ "!pip install imblearn", "Collecting imblearn\n Downloading imblearn-0.0-py2.py3-none-any.whl (1.9 kB)\nCollecting imbalanced-learn\n Downloading imbalanced_learn-0.7.0-py3-none-any.whl (167 kB)\n\u001b[K |████████████████████████████████| 167 kB 1.9 MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: scipy>=0.19.1 in /Users/bikash/python/anaconda3/lib/python3.7/site-packages (from imbalanced-learn->imblearn) (1.5.2)\nRequirement already satisfied: numpy>=1.13.3 in /Users/bikash/python/anaconda3/lib/python3.7/site-packages (from imbalanced-learn->imblearn) (1.19.1)\nRequirement already satisfied: joblib>=0.11 in /Users/bikash/python/anaconda3/lib/python3.7/site-packages (from imbalanced-learn->imblearn) (0.14.1)\nRequirement already satisfied: scikit-learn>=0.23 in /Users/bikash/python/anaconda3/lib/python3.7/site-packages (from imbalanced-learn->imblearn) (0.23.2)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /Users/bikash/python/anaconda3/lib/python3.7/site-packages (from scikit-learn>=0.23->imbalanced-learn->imblearn) (2.1.0)\nInstalling collected packages: imbalanced-learn, imblearn\nSuccessfully installed imbalanced-learn-0.7.0 imblearn-0.0\n" ], [ "# Read training data\ndata = pd.read_csv('data/train.csv')\nfrom sklearn.model_selection import train_test_split\ntrain_X = data.drop([\"target\",\"id\"], axis=1)", "_____no_output_____" ] ], [ [ "# Representation of the target with numerical values ", "_____no_output_____" ] ], [ [ "le = LabelEncoder()\nle.fit(data[\"target\"])\ntrain_y = le.transform(data[\"target\"])", "_____no_output_____" ] ], [ [ "# Splitting the data (train.csv)", "_____no_output_____" ] ], [ [ "# split train set into 2 parts with same distribution: 80% train, 20% validation\nsss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)\nfor train_index, test_index in sss.split(train_X.values, train_y):\n X_train = train_X.values[train_index]\n X_val = train_X.values[test_index]\n\n y_train = train_y[train_index]\n y_val = train_y[test_index]", "_____no_output_____" ] ], [ [ "# Preprocessing", "_____no_output_____" ], [ "## Null values ?", "_____no_output_____" ] ], [ [ "missing_val_count_by_column = (data.isnull().sum())\nprint(missing_val_count_by_column.sum())", "0\n" ], [ "data.describe()", "_____no_output_____" ] ], [ [ "## Balance in the class ?", "_____no_output_____" ] ], [ [ "data[\"target\"].value_counts().plot.bar()", "_____no_output_____" ], [ "data[\"target\"].value_counts()", "_____no_output_____" ], [ "ros = RandomOverSampler()\nX_ros, y_ros = ros.fit_sample(X_train, y_train)\n\nunique, counts = np.unique(y_ros, return_counts=True)\n\nprint(np.asarray((unique, counts)).T)", "_____no_output_____" ], [ "pd.Series(y_ros).value_counts().plot.bar()", "_____no_output_____" ] ], [ [ "## Scaling", "_____no_output_____" ] ], [ [ "scaler = StandardScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_val_scaled = scaler.transform(X_val)", "_____no_output_____" ], [ "test_data = pd.read_csv('../input/test.csv')\ntest_X = test_data.drop([\"id\"], axis=1)\nscaler_all = StandardScaler()\ntrain_X_scaled = scaler_all.fit_transform(train_X)\ntest_X_scaled = scaler.transform(test_X)", "_____no_output_____" ] ], [ [ "## PCA ?", "_____no_output_____" ] ], [ [ "pca = decomposition.PCA(n_components=20)\npca.fit(X_train_scaled)\n\nX_train_pca = pca.transform(X_train_scaled)\nprint(pca.explained_variance_ratio_)\nprint(pca.explained_variance_)", "_____no_output_____" ] ], [ [ "## Determine number of components", "_____no_output_____" ] ], [ [ "pca = decomposition.PCA()\npca.fit(X_train_scaled)\n\nX_train_pca = pca.transform(X_train_scaled)\n#print(np.cumsum(pca.explained_variance_ratio_))\nplt.plot(np.cumsum(pca.explained_variance_ratio_))\nplt.xlabel('number of components')\nplt.ylabel('cumulative explained variance');", "_____no_output_____" ] ], [ [ "At least 95% of the variance in the data can be explained by 77 components.", "_____no_output_____" ], [ "# XGBOOST", "_____no_output_____" ] ], [ [ "xgb = XGBClassifier()\nxgb.fit(X_train_scaled, y_train)\npreds = xgb.predict_proba(X_val_scaled)\nscore = log_loss(y_val, preds)\nprint(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ], [ "xgb.get_params", "_____no_output_____" ] ], [ [ "# Fitting and Tuning an Algorithm", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import GridSearchCV\n\n\"\"\"\nparam_test = {\n 'n_estimators': [300],\n 'n_jobs': [4], #Number of jobs to run in parallel. -1 means using all processors\n}\ngsearch = GridSearchCV(estimator = XGBClassifier(), param_grid = param_test, scoring='neg_log_loss', n_jobs=-1,iid=False, cv=3,verbose=1, return_train_score=True)\ngsearch.fit(X_train_scaled,y_train)\npd.DataFrame(gsearch.cv_results_)\n\"\"\"", "_____no_output_____" ], [ "scores = []\nn_estimators = [100,200,400,450,500,525,550,600,700]\n\nfor nes in n_estimators:\n xgb = XGBClassifier(learning_rate =0.1, n_estimators=nes, max_depth=7, min_child_weight=3, subsample=0.8, \n colsample_bytree=0.8, nthread=4, seed=42, objective='multi:softprob')\n xgb.fit(X_train_scaled, y_train)\n preds = xgb.predict_proba(X_val_scaled)\n score = log_loss(y_val, preds)\n scores.append(score)\n print(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ], [ "plt.plot(n_estimators,scores,'o-')\nplt.ylabel(log_loss)\nplt.xlabel(\"n_estimator\")\nprint(\"best n_estimator {}\".format(n_estimators[np.argmin(scores)]))", "_____no_output_____" ], [ "scores_md = []\nmax_depths = [1,3,5,6,7,8,10]\n\nfor md in max_depths:\n xgb = XGBClassifier(learning_rate =0.1, n_estimators=n_estimators[np.argmin(scores)], \n max_depth=md, min_child_weight=3, subsample=0.8, \n colsample_bytree=0.8, nthread=4, seed=42, objective='multi:softprob')\n xgb.fit(X_train_scaled, y_train)\n preds = xgb.predict_proba(X_val_scaled)\n score = log_loss(y_val, preds)\n scores_md.append(score)\n print(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ], [ "plt.plot(max_depths,scores_md,'o-')\nplt.ylabel(log_loss)\nplt.xlabel(\"max_depth\")\nprint(\"best max_depth {}\".format(max_depths[np.argmin(scores_md)]))", "_____no_output_____" ], [ "scores_mcw = []\nmin_child_weights = [1,2,3,4,5]\n\nfor mcw in min_child_weights:\n xgb = XGBClassifier(learning_rate =0.1, n_estimators=n_estimators[np.argmin(scores)],\n max_depth=max_depths[np.argmin(scores_md)], \n min_child_weight=mcw, subsample=0.8, \n colsample_bytree=0.8, nthread=4, seed=42, objective='multi:softprob')\n xgb.fit(X_train_scaled, y_train)\n preds = xgb.predict_proba(X_val_scaled)\n score = log_loss(y_val, preds)\n scores_mcw.append(score)\n print(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ], [ "plt.plot(min_child_weights,scores_mcw,\"o-\")\nplt.ylabel(log_loss)\nplt.xlabel(\"min_child_weight\")\nprint(\"best min_child_weight {}\".format(min_child_weights[np.argmin(scores_mcw)]))", "_____no_output_____" ], [ "scores_ss = []\nsubsamples = [0.5,0.6,0.7,0.8,0.9,1]\n\nfor ss in subsamples:\n xgb = XGBClassifier(learning_rate =0.1, n_estimators=n_estimators[np.argmin(scores)], \n max_depth=max_depths[np.argmin(scores_md)],\n min_child_weight=min_child_weights[np.argmin(scores_mcw)], subsample=ss, \n colsample_bytree=0.8, nthread=4, seed=42, objective='multi:softprob')\n xgb.fit(X_train_scaled, y_train)\n preds = xgb.predict_proba(X_val_scaled)\n score = log_loss(y_val, preds)\n scores_ss.append(score)\n print(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ], [ "plt.plot(subsamples,scores_ss,\"o-\")\nplt.ylabel(log_loss)\nplt.xlabel(\"subsample\")\nprint(\"best subsample {}\".format(subsamples[np.argmin(scores_ss)]))", "_____no_output_____" ], [ "scores_cb = []\ncolsample_bytrees = [0.5,0.6,0.7,0.8,0.9,1]\n\nfor cb in colsample_bytrees:\n xgb = XGBClassifier(learning_rate =0.1, n_estimators=n_estimators[np.argmin(scores)], \n max_depth=max_depths[np.argmin(scores_md)], \n min_child_weight=min_child_weights[np.argmin(scores_mcw)], \n subsample=subsamples[np.argmin(scores_ss)], \n colsample_bytree=cb, nthread=4, seed=42, objective='multi:softprob')\n xgb.fit(X_train_scaled, y_train)\n preds = xgb.predict_proba(X_val_scaled)\n score = log_loss(y_val, preds)\n scores_cb.append(score)\n print(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ], [ "plt.plot(colsample_bytrees,scores_cb,\"o-\")\nplt.ylabel(log_loss)\nplt.xlabel(\"colsample_bytree\")\nprint(\"best colsample_bytree {}\".format(colsample_bytrees[np.argmin(scores_cb)]))", "_____no_output_____" ], [ "scores_eta = []\netas = [0.001,0.01,0.1,0.2,0.3,0.5,1]\n\nfor eta in etas:\n xgb = XGBClassifier(learning_rate =eta, n_estimators=n_estimators[np.argmin(scores)], \n max_depth=max_depths[np.argmin(scores_md)], \n min_child_weight=min_child_weights[np.argmin(scores_mcw)], \n subsample=subsamples[np.argmin(scores_ss)], \n colsample_bytree=colsample_bytrees[np.argmin(scores_cb)], \n nthread=4, seed=42, objective='multi:softprob')\n xgb.fit(X_train_scaled, y_train)\n preds = xgb.predict_proba(X_val_scaled)\n score = log_loss(y_val, preds)\n scores_eta.append(score)\n print(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ], [ "plt.plot(etas,scores_eta,\"o-\")\nplt.ylabel(log_loss)\nplt.xlabel(\"eta\")\nprint(\"best eta {}\".format(etas[np.argmin(scores_eta)]))", "_____no_output_____" ], [ "xgb = XGBClassifier(learning_rate =eta, n_estimators=n_estimators[np.argmin(scores)], \n max_depth=max_depths[np.argmin(scores_md)], \n min_child_weight=min_child_weights[np.argmin(scores_mcw)], \n subsample=subsamples[np.argmin(scores_ss)], \n colsample_bytree=colsample_bytrees[np.argmin(scores_cb)], \n nthread=4, seed=42, objective='multi:softprob')\ncalibrated_xgb = CalibratedClassifierCV(xgb, cv=5, method='isotonic')\ncalibrated_xgb.fit(X_train_scaled, y_train)\npreds = calibrated_xgb.predict_proba(X_val_scaled)\nscore = log_loss(y_val, preds)\nscores_eta.append(score)\nprint(\"test data log loss eval : {}\".format(log_loss(y_val,preds)))", "_____no_output_____" ] ], [ [ "# submission", "_____no_output_____" ] ], [ [ "xgb = XGBClassifier(learning_rate =0.1, n_estimators=525, max_depth=8, min_child_weight=3, subsample=0.7, \n colsample_bytree=0.7, nthread=4, seed=42, objective='multi:softprob')\nmy_model = CalibratedClassifierCV(xgb, cv=5, method='isotonic')\nmy_model.fit(train_X_scaled,train_y)\ntest_preds = my_model.predict_proba(test_X_scaled)\noutput = pd.DataFrame(test_preds,columns=[\"Class_\"+str(i) for i in range(1,10)])\noutput.insert(loc=0, column='id', value=test_data.id)\noutput.to_csv('submission.csv', index=False)", "_____no_output_____" ], [ "test_data.head()", "_____no_output_____" ], [ "output.head()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4af1dd9a2af0a921187c4f9ee4c624d40e60a0a6
416,371
ipynb
Jupyter Notebook
WeatherPy.ipynb
Monkey-travels/python-api-challenge
7b1960b137b1c725c50e6564c10a98cf0149c7fd
[ "MIT" ]
null
null
null
WeatherPy.ipynb
Monkey-travels/python-api-challenge
7b1960b137b1c725c50e6564c10a98cf0149c7fd
[ "MIT" ]
null
null
null
WeatherPy.ipynb
Monkey-travels/python-api-challenge
7b1960b137b1c725c50e6564c10a98cf0149c7fd
[ "MIT" ]
null
null
null
254.350031
52,224
0.90808
[ [ [ "# WeatherPy\n----\n\n#### Note\n* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.", "_____no_output_____" ] ], [ [ "!pip install citipy ", "Requirement already satisfied: citipy in c:\\users\\flyto\\anaconda3\\lib\\site-packages (0.0.5)\nRequirement already satisfied: kdtree>=0.12 in c:\\users\\flyto\\anaconda3\\lib\\site-packages (from citipy) (0.16)\n" ], [ "# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport requests\nimport time\nfrom scipy.stats import linregress\n\n# Import API key\nfrom api_keys import weather_api_key\n\n# Incorporated citipy to determine city based on latitude and longitude\nfrom citipy import citipy\n\n# Output File (CSV)\noutput_data_file = \"output_data/cities.csv\"\n\n# Range of latitudes and longitudes\nlat_range = (-90, 90)\nlng_range = (-180, 180)", "_____no_output_____" ] ], [ [ "## Generate Cities List", "_____no_output_____" ] ], [ [ "# List for holding lat_lngs and cities\nlat_lngs = []\ncities = []\n\n# Create a set of random lat and lng combinations\nlats = np.random.uniform(low=-90.000, high=90.000, size=1500)\nlngs = np.random.uniform(low=-180.000, high=180.000, size=1500)\nlat_lngs = zip(lats, lngs)\n\n# Identify nearest city for each lat, lng combination\nfor lat_lng in lat_lngs:\n city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name\n \n # If the city is unique, then add it to a our cities list\n if city not in cities:\n cities.append(city)\n\n# Print the city count to confirm sufficient count\nlen(cities)", "_____no_output_____" ] ], [ [ "### Perform API Calls\n* Perform a weather check on each city using a series of successive API calls.\n* Include a print log of each city as it'sbeing processed (with the city number and city name).\n", "_____no_output_____" ] ], [ [ "#Starting URL for Weather Map API call\n\nurl = f\"http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID={weather_api_key}\"\n\n#list of city data\ncity_data = []\n\n#print to logger\nprint(\"Beginning Data Retrieval\")\nprint(\"-\" * 15)\n\n#create counters\nrecord_count = 1\nset_count = 1\n\n#loop through all the cities in the list \nfor index, city, in enumerate(cities):\n #group cities in sets of 50 for logging purpose\n if (index % 50 == 0 and index >= 50):\n set_count +=1\n record_count = 0\n #create endpoint URL with each city\n city_url = url + \"&q=\" + city \n \n #log the url record and set number\n print(f\"Processing Record {record_count} of set {set_count} | {city}\")\n \n record_count += 1\n \n #Run an API request for each of the cities\n try: \n #parse the JSON and retrieve data\n city_weather = requests.get(city_url).json()\n \n #extract out max temp humidity and cloudiness\n city_lat = city_weather[\"coord\"][\"lat\"]\n city_lng = city_weather[\"coord\"][\"lon\"]\n city_max_temp = city_weather[\"main\"][\"temp_max\"]\n city_humidity = city_weather[\"main\"][\"humidity\"]\n city_clouds = city_weather[\"clouds\"][\"all\"]\n city_wind = city_weather[\"wind\"][\"speed\"]\n city_country = city_weather[\"sys\"][\"country\"]\n city_date = city_weather[\"dt\"]\n \n #append the city info into city data\n city_data.append({\n \"City\": city,\n \"Lat\": city_lat,\n \"Lng\": city_lng,\n \"Max Temp\": city_max_temp,\n \"Humidity\": city_humidity,\n \"Cloudiness\": city_clouds,\n \"Wind Speed\": city_wind,\n \"Country\": city_country,\n \"Data\": city_data\n })\n except:\n print(\"City not found. Skipping...\")\n pass\n \n#indicate that data loading is complete\nprint(\"---------------\")\nprint(\"Data Retrieval Complete\")\nprint(\"---------------\")", "Beginning Data Retrieval\n---------------\nProcessing Record 1 of set 1 | yellowknife\nProcessing Record 2 of set 1 | berlevag\nProcessing Record 3 of set 1 | beloha\nProcessing Record 4 of set 1 | khatanga\nProcessing Record 5 of set 1 | namibe\nProcessing Record 6 of set 1 | codrington\nProcessing Record 7 of set 1 | bafata\nProcessing Record 8 of set 1 | cape town\nProcessing Record 9 of set 1 | faya\nProcessing Record 10 of set 1 | katsuura\nProcessing Record 11 of set 1 | albany\nProcessing Record 12 of set 1 | chokurdakh\nProcessing Record 13 of set 1 | rikitea\nProcessing Record 14 of set 1 | korla\nProcessing Record 15 of set 1 | namatanai\nProcessing Record 16 of set 1 | ust-tsilma\nProcessing Record 17 of set 1 | gerash\nProcessing Record 18 of set 1 | san patricio\nProcessing Record 19 of set 1 | geraldton\nProcessing Record 20 of set 1 | barrow\nProcessing Record 21 of set 1 | tilichiki\nProcessing Record 22 of set 1 | petropavlovsk-kamchatskiy\nProcessing Record 23 of set 1 | mataura\nProcessing Record 24 of set 1 | butaritari\nProcessing Record 25 of set 1 | arraial do cabo\nProcessing Record 26 of set 1 | hithadhoo\nProcessing Record 27 of set 1 | taolanaro\nCity not found. Skipping...\nProcessing Record 28 of set 1 | bethel\nProcessing Record 29 of set 1 | busselton\nProcessing Record 30 of set 1 | kaka\nProcessing Record 31 of set 1 | airai\nProcessing Record 32 of set 1 | mount isa\nProcessing Record 33 of set 1 | saint-augustin\nProcessing Record 34 of set 1 | olinda\nProcessing Record 35 of set 1 | zhigansk\nProcessing Record 36 of set 1 | qaanaaq\nProcessing Record 37 of set 1 | ushuaia\nProcessing Record 38 of set 1 | le port\nProcessing Record 39 of set 1 | atasu\nProcessing Record 40 of set 1 | punta arenas\nProcessing Record 41 of set 1 | lethem\nProcessing Record 42 of set 1 | bambous virieux\nProcessing Record 43 of set 1 | bathsheba\nProcessing Record 44 of set 1 | roskovec\nProcessing Record 45 of set 1 | sarab\nProcessing Record 46 of set 1 | intipuca\nProcessing Record 47 of set 1 | hami\nProcessing Record 48 of set 1 | skelleftea\nProcessing Record 49 of set 1 | alofi\nProcessing Record 50 of set 1 | samusu\nCity not found. Skipping...\nProcessing Record 0 of set 2 | mys shmidta\nCity not found. Skipping...\nProcessing Record 1 of set 2 | seymchan\nProcessing Record 2 of set 2 | gwembe\nProcessing Record 3 of set 2 | new norfolk\nProcessing Record 4 of set 2 | tasiilaq\nProcessing Record 5 of set 2 | bredasdorp\nProcessing Record 6 of set 2 | bluff\nProcessing Record 7 of set 2 | thompson\nProcessing Record 8 of set 2 | vaini\nProcessing Record 9 of set 2 | rudsar\nProcessing Record 10 of set 2 | hermanus\nProcessing Record 11 of set 2 | luderitz\nProcessing Record 12 of set 2 | mar del plata\nProcessing Record 13 of set 2 | severo-yeniseyskiy\nProcessing Record 14 of set 2 | hobart\nProcessing Record 15 of set 2 | port alfred\nProcessing Record 16 of set 2 | kodiak\nProcessing Record 17 of set 2 | guerrero negro\nProcessing Record 18 of set 2 | bushehr\nProcessing Record 19 of set 2 | cherskiy\nProcessing Record 20 of set 2 | jamestown\nProcessing Record 21 of set 2 | seoul\nProcessing Record 22 of set 2 | am timan\nProcessing Record 23 of set 2 | tsihombe\nCity not found. Skipping...\nProcessing Record 24 of set 2 | vila franca do campo\nProcessing Record 25 of set 2 | laguna\nProcessing Record 26 of set 2 | illoqqortoormiut\nCity not found. Skipping...\nProcessing Record 27 of set 2 | puerto ayora\nProcessing Record 28 of set 2 | olafsvik\nProcessing Record 29 of set 2 | mahebourg\nProcessing Record 30 of set 2 | bengkulu\nProcessing Record 31 of set 2 | lavrentiya\nProcessing Record 32 of set 2 | sao joao da barra\nProcessing Record 33 of set 2 | maputo\nProcessing Record 34 of set 2 | meulaboh\nProcessing Record 35 of set 2 | ambon\nProcessing Record 36 of set 2 | cidreira\nProcessing Record 37 of set 2 | hilo\nProcessing Record 38 of set 2 | caravelas\nProcessing Record 39 of set 2 | fortuna\nProcessing Record 40 of set 2 | san jose\nProcessing Record 41 of set 2 | inhambane\nProcessing Record 42 of set 2 | gallup\nProcessing Record 43 of set 2 | lompoc\nProcessing Record 44 of set 2 | castro\nProcessing Record 45 of set 2 | dikson\nProcessing Record 46 of set 2 | pevek\nProcessing Record 47 of set 2 | hamilton\nProcessing Record 48 of set 2 | grand gaube\nProcessing Record 49 of set 2 | barahona\nProcessing Record 0 of set 3 | aquin\nProcessing Record 1 of set 3 | san policarpo\nProcessing Record 2 of set 3 | yablonovo\nProcessing Record 3 of set 3 | sao filipe\nProcessing Record 4 of set 3 | prostejov\nProcessing Record 5 of set 3 | tuatapere\nProcessing Record 6 of set 3 | grand river south east\nCity not found. Skipping...\nProcessing Record 7 of set 3 | hobyo\nProcessing Record 8 of set 3 | yabucoa\nProcessing Record 9 of set 3 | bulgan\nProcessing Record 10 of set 3 | koosa\nProcessing Record 11 of set 3 | pagouria\nProcessing Record 12 of set 3 | te anau\nProcessing Record 13 of set 3 | tommot\nProcessing Record 14 of set 3 | srednekolymsk\nProcessing Record 15 of set 3 | koson\nProcessing Record 16 of set 3 | lopatino\nProcessing Record 17 of set 3 | port hedland\nProcessing Record 18 of set 3 | carnarvon\nProcessing Record 19 of set 3 | mizdah\nProcessing Record 20 of set 3 | tiksi\nProcessing Record 21 of set 3 | esperance\nProcessing Record 22 of set 3 | nizhneyansk\nCity not found. Skipping...\nProcessing Record 23 of set 3 | belton\nProcessing Record 24 of set 3 | evensk\nProcessing Record 25 of set 3 | chuy\nProcessing Record 26 of set 3 | sassandra\nProcessing Record 27 of set 3 | sentyabrskiy\nCity not found. Skipping...\nProcessing Record 28 of set 3 | nikolskoye\nProcessing Record 29 of set 3 | hasaki\nProcessing Record 30 of set 3 | ngukurr\nCity not found. Skipping...\nProcessing Record 31 of set 3 | vestbygda\nCity not found. Skipping...\nProcessing Record 32 of set 3 | college\nProcessing Record 33 of set 3 | georgetown\nProcessing Record 34 of set 3 | mnogovershinnyy\nProcessing Record 35 of set 3 | coquimbo\nProcessing Record 36 of set 3 | pula\nProcessing Record 37 of set 3 | huazolotitlan\nCity not found. Skipping...\nProcessing Record 38 of set 3 | pilar\nProcessing Record 39 of set 3 | atmakur\nProcessing Record 40 of set 3 | andapa\nProcessing Record 41 of set 3 | huilong\nProcessing Record 42 of set 3 | atuona\nProcessing Record 43 of set 3 | east london\nProcessing Record 44 of set 3 | ossora\nProcessing Record 45 of set 3 | kuche\nCity not found. Skipping...\nProcessing Record 46 of set 3 | cockburn town\nProcessing Record 47 of set 3 | knysna\nProcessing Record 48 of set 3 | sergeyevka\nProcessing Record 49 of set 3 | gambissara\nProcessing Record 0 of set 4 | tavricheskoye\nProcessing Record 1 of set 4 | constitucion\nProcessing Record 2 of set 4 | mareeba\nProcessing Record 3 of set 4 | daru\nProcessing Record 4 of set 4 | flinders\nProcessing Record 5 of set 4 | zabid\nProcessing Record 6 of set 4 | robertson\nProcessing Record 7 of set 4 | maloshuyka\nCity not found. Skipping...\nProcessing Record 8 of set 4 | severo-kurilsk\nProcessing Record 9 of set 4 | bolshegrivskoye\nCity not found. Skipping...\nProcessing Record 10 of set 4 | szydlowiec\nProcessing Record 11 of set 4 | upernavik\nProcessing Record 12 of set 4 | kaitangata\nProcessing Record 13 of set 4 | kilindoni\nProcessing Record 14 of set 4 | jutai\nProcessing Record 15 of set 4 | sosnovo-ozerskoye\nProcessing Record 16 of set 4 | carmen\nProcessing Record 17 of set 4 | grand centre\nCity not found. Skipping...\nProcessing Record 18 of set 4 | jablah\nProcessing Record 19 of set 4 | alihe\nProcessing Record 20 of set 4 | amderma\nCity not found. Skipping...\nProcessing Record 21 of set 4 | taltal\nProcessing Record 22 of set 4 | lata\nProcessing Record 23 of set 4 | coreau\nProcessing Record 24 of set 4 | saint-philippe\nProcessing Record 25 of set 4 | hare bay\nProcessing Record 26 of set 4 | bonavista\nProcessing Record 27 of set 4 | kahului\nProcessing Record 28 of set 4 | jiayuguan\nProcessing Record 29 of set 4 | bennettsville\nProcessing Record 30 of set 4 | saleaula\nCity not found. Skipping...\nProcessing Record 31 of set 4 | craig\nProcessing Record 32 of set 4 | aflu\nCity not found. Skipping...\nProcessing Record 33 of set 4 | ponta do sol\nProcessing Record 34 of set 4 | kampot\nProcessing Record 35 of set 4 | mackay\n" ] ], [ [ "### Convert Raw Data to DataFrame\n* Export the city data into a .csv.\n* Display the DataFrame", "_____no_output_____" ] ], [ [ "#convert array of JSON into Pandas\ncity_data_df = pd.DataFrame(city_data)\n\n#extract relevant fiels from the data frame\nlats = city_data_df[\"Lat\"]\nmax_temps = city_data_df[\"Max Temp\"]\nhumidity = city_data_df[\"Humidity\"]\ncloudiness = city_data_df[\"Cloudiness\"]\nwind_speed = city_data_df[\"Wind Speed\"]\n\ncity_data_df.to_csv(output_data_file, index_label = \"City_ID\")\n\ncity_data_df.count()", "_____no_output_____" ], [ "#display the city data frame\n\ncity_data_df.head()", "_____no_output_____" ] ], [ [ "### Plotting the Data\n* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.\n* Save the plotted figures as .pngs.", "_____no_output_____" ], [ "#### Latitude vs. Temperature Plot", "_____no_output_____" ] ], [ [ "#build scatter plot for latitude vs. temperature\nplt.scatter(lats,\n max_temps,\n edgecolor=\"black\", linewidth=1, marker=\"o\",\n alpha=0.5, label=\"Cities\")\n\n#incorporate the other graph properties\nplt.title(\"City Latitude vs. Max Temperature (%s)\" % time.strftime(\"%x\"))\nplt.ylabel(\"Max Temperature (F)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n \n#save the figure\nplt.savefig(\"output_data/Fig1.png\")\n\n#show plot\nplt.show()", "_____no_output_____" ] ], [ [ "#### Latitude vs. Humidity Plot", "_____no_output_____" ] ], [ [ "#build scatter plot for latitude vs. humidity\nplt.scatter(lats,\n humidity,\n edgecolor=\"black\", linewidth=1, marker=\"o\",\n alpha=0.5, label=\"Cities\")\n\n#incorporate the other graph properties\nplt.title(\"City Latitude vs. Humidity (%s)\" % time.strftime(\"%x\"))\nplt.ylabel(\"Humidity (%)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n \n#save the figure\nplt.savefig(\"output_data/Fig2.png\")\n\n#show plot\nplt.show()", "_____no_output_____" ] ], [ [ "#### Latitude vs. Cloudiness Plot", "_____no_output_____" ] ], [ [ "#build scatter plot for latitude vs. cloudiness\nplt.scatter(lats,\n cloudiness,\n edgecolor=\"black\", linewidth=1, marker=\"o\",\n alpha=0.5, label=\"Cities\")\n\n#incorporate the other graph properties\nplt.title(\"City Latitude vs. Cloudiness (%s)\" % time.strftime(\"%x\"))\nplt.ylabel(\"Cloudiness (%)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n \n#save the figure\nplt.savefig(\"output_data/Fig3.png\")\n\n#show plot\nplt.show()", "_____no_output_____" ] ], [ [ "#### Latitude vs. Wind Speed Plot", "_____no_output_____" ] ], [ [ "#build scatter plot for latitude vs. wind speed\nplt.scatter(lats,\n wind_speed,\n edgecolor=\"black\", linewidth=1, marker=\"o\",\n alpha=0.5, label=\"Cities\")\n\n#incorporate the other graph properties\nplt.title(\"City Latitude vs. Wind Speed (%s)\" % time.strftime(\"%x\"))\nplt.ylabel(\"Wind Speed (mph)\")\nplt.xlabel(\"Latitude\")\nplt.grid(True)\n \n#save the figure\nplt.savefig(\"output_data/Fig4.png\")\n\n#show plot\nplt.show()", "_____no_output_____" ] ], [ [ "## Linear Regression", "_____no_output_____" ] ], [ [ "# OPTIONAL: Create a function to create Linear Regression plots\ndef plot_linear_regression(x_values, y_values, title, text_coordinates):\n \n #run regression on souther hemisphere\n (slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)\n regress_values = x_values * slope + intercept\n line_eq = \"y = \" + str(round(slope,2)) + \"x + \" + str(round(intercept,2))\n \n #plot \n plt.scatter(x_values, y_values)\n plt.plot(x_values, regress_values, \"r-\")\n plt.annotate(line_eq, text_coordinates, fontsize=15, color=\"red\")\n plt.xlabel(\"Latitude\")\n plt.ylabel(title)\n print(f\"The r-squared is {rvalue}\")\n plt.show()", "_____no_output_____" ], [ "# Create Northern and Southern Hemisphere DataFrames\nnorthern_hemi_df = city_data_df.loc[(city_data_df[\"Lat\"] >= 0)]\nsouthern_hemi_df = city_data_df.loc[(city_data_df[\"Lat\"] < 0)]", "_____no_output_____" ] ], [ [ "#### Northern Hemisphere - Max Temp vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = northern_hemi_df[\"Lat\"]\ny_values = northern_hemi_df[\"Max Temp\"]\nplot_linear_regression(x_values, y_values, \"Max Temp\", (6,30))", "The r-squared is -0.8741574310924249\n" ] ], [ [ "#### Southern Hemisphere - Max Temp vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = southern_hemi_df[\"Lat\"]\ny_values = southern_hemi_df[\"Max Temp\"]\nplot_linear_regression(x_values, y_values, \"Max Temp\", (-30,40))", "The r-squared is 0.5077353537549943\n" ] ], [ [ "#### Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = northern_hemi_df[\"Lat\"]\ny_values = northern_hemi_df[\"Humidity\"]\nplot_linear_regression(x_values, y_values, \"Humidity\", (40,10))", "The r-squared is 0.4361200687336333\n" ] ], [ [ "#### Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = southern_hemi_df[\"Lat\"]\ny_values = southern_hemi_df[\"Humidity\"]\nplot_linear_regression(x_values, y_values, \"Humidity\", (-30,150))", "The r-squared is 0.2759397409147292\n" ] ], [ [ "#### Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = northern_hemi_df[\"Lat\"]\ny_values = northern_hemi_df[\"Cloudiness\"]\nplot_linear_regression(x_values, y_values, \"Cloudiness\", (40,30))", "The r-squared is 0.2701073392176925\n" ] ], [ [ "#### Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = southern_hemi_df[\"Lat\"]\ny_values = southern_hemi_df[\"Cloudiness\"]\nplot_linear_regression(x_values, y_values, \"Cloudiness\", (-30,30))", "The r-squared is 0.21072603746452342\n" ] ], [ [ "#### Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = northern_hemi_df[\"Lat\"]\ny_values = northern_hemi_df[\"Wind Speed\"]\nplot_linear_regression(x_values, y_values, \"Wind Speed\", (40,25))", "The r-squared is -0.03639154806204328\n" ] ], [ [ "#### Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression", "_____no_output_____" ] ], [ [ "x_values = southern_hemi_df[\"Lat\"]\ny_values = southern_hemi_df[\"Wind Speed\"]\nplot_linear_regression(x_values, y_values, \"Wind Speed\", (-30,30))", "The r-squared is -0.24397683029667944\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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af1e3d0ad72d77691b157c87ef98ca3bf1f76d9
34,028
ipynb
Jupyter Notebook
Performance.ipynb
df8/coria-hu-2018
ddb1b5fe4a876bf42ac73725a4aaf87849820953
[ "MIT" ]
null
null
null
Performance.ipynb
df8/coria-hu-2018
ddb1b5fe4a876bf42ac73725a4aaf87849820953
[ "MIT" ]
null
null
null
Performance.ipynb
df8/coria-hu-2018
ddb1b5fe4a876bf42ac73725a4aaf87849820953
[ "MIT" ]
null
null
null
170.994975
28,904
0.88242
[ [ [ "# Performance - example", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np", "_____no_output_____" ], [ "import networkx as nx\nimport numpy as np\nG = nx.DiGraph()\nG.add_node(1, capacity = 1)\nG.add_node(2, capacity = 1)\nG.add_node(3, capacity = 1)\nG.add_node(4, capacity = 1)\nG.add_node(5, capacity = 1)\n\n\nG.add_edge(1, 2, capacity=3)\nG.add_edge(2, 3, capacity=1)\nG.add_edge(3, 4, capacity=3)\nG.add_edge(4, 3, capacity=5)\nG.add_edge(4, 5, capacity=4)\nG.add_edge(1, 4, capacity=2)\nG.add_edge(3, 5, capacity=2)\nG.add_edge(5, 2, capacity=3)\nG.add_edge(1, 5, capacity=3)\n\nG = G.to_undirected()", "_____no_output_____" ], [ "Performance(G)", "_____no_output_____" ], [ "nx.draw(G,with_labels = True, node_size=1000,pos=nx.spring_layout(G))\nplt.show()", "_____no_output_____" ], [ "def Performance(G):\n def capacity_b(Graph):\n return np.array(np.repeat(1,len(Graph)))\n\n def get_max_flow_demand(G):\n results = []\n max_flow = 0\n for i in G:\n for j in G:\n if (i == j):\n continue\n else:\n flow = nx.maximum_flow_value(G,i,j)\n flow = int(flow)\n results.append(flow)\n return results\n\n\n def fill_routing_matrix(route_graph):\n routing_matrix = np.array(np.repeat(0, len(route_graph)))\n # for each node in the graph calculate their standard shortest path routing with dijkstra\n for n in route_graph:\n all_path = nx.single_source_dijkstra_path(route_graph, n) \n # for each shortest path for one node in the graph define an array with n elements\n # the element in the array is 1 when the shortest path flows through the node\n # otherwise 0\n for path in all_path:\n tmp = np.array(np.repeat(0, len(route_graph)))\n for path_element in all_path[path]:\n\n node_idx = 0\n for link in route_graph: \n if(path_element == link):\n tmp[node_idx] = 1\n continue \n node_idx += 1 \n # add each shortest path transformed into an array tmp to the routing matrix \n if len(tmp) == len(route_graph): \n routing_matrix = np.vstack([routing_matrix, tmp]) \n return routing_matrix\n\n\n b = capacity_b(G) \n R_fl = fill_routing_matrix(G) \n R_lf = np.transpose(R_fl)\n x = np.array(np.repeat(1, len(R_fl))) \n Rx = np.dot(R_lf,x)\n rho = 2\n x = get_max_flow_demand(G)\n Performance = rho*sum(x)\n return Performance", "_____no_output_____" ], [ "Performance(G)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4af1e8e9803b2e166fad2c094fcd152c80bcf894
23,284
ipynb
Jupyter Notebook
dz-datasets/insurance/caar/caar_branches_convert_to_csv.ipynb
enlight-me/geo-enabled-datasets
da4a3fa82bd05d8ee8302f449cce32afb18ce3ed
[ "CC0-1.0" ]
4
2021-02-26T21:09:08.000Z
2021-06-04T14:30:44.000Z
dz-datasets/insurance/caar/caar_branches_convert_to_csv.ipynb
jiro74/geo-enabled-datasets
da4a3fa82bd05d8ee8302f449cce32afb18ce3ed
[ "CC0-1.0" ]
null
null
null
dz-datasets/insurance/caar/caar_branches_convert_to_csv.ipynb
jiro74/geo-enabled-datasets
da4a3fa82bd05d8ee8302f449cce32afb18ce3ed
[ "CC0-1.0" ]
2
2021-06-04T14:31:40.000Z
2021-09-16T08:18:18.000Z
54.785882
3,287
0.453401
[ [ [ "# load packages\nimport pandas as pd\nimport geopandas as gpd\nimport unidecode ", "_____no_output_____" ], [ "pois_file_name = './caar_raw.geojson'\npois_df = gpd.read_file(pois_file_name)\npois_df.count()", "_____no_output_____" ], [ "pois_df.head()", "_____no_output_____" ], [ "pois_df['wilaya'] = [w[len(w)-1].strip() for w in pois_df['address'].str.split('-')]\npois_df.wilaya", "_____no_output_____" ], [ "pois_df['wilaya_maj'] = [unidecode.unidecode(w) for w in pois_df.wilaya.str.upper()]\npois_df.wilaya_maj", "_____no_output_____" ], [ "# Add Wilayas codes\n# Load Wilayas Features and calculate polygon centroids\nwilayas_gjson = '../../../dz-admin/wilayas_48.csv'\nwilayas_df = pd.read_csv(wilayas_gjson)\nwilayas_df = wilayas_df[['code', 'nom_maj']]\nwilayas_df = wilayas_df.rename(columns={'nom_maj': 'nom_wil', 'code': 'code_wil'})\nwilayas_df.head()", "_____no_output_____" ], [ "# Merge with Wialyas DataFrame\nmerged = pois_df.merge(wilayas_df, left_on='wilaya_maj', right_on='nom_wil', how='left')\n\nmerged[merged['code_wil'].isnull()]", "_____no_output_____" ], [ "merged.count()", "_____no_output_____" ], [ "merged['lat'] = merged['geometry'].y\nmerged['lon'] = merged['geometry'].x", "_____no_output_____" ], [ "merged.head()", "_____no_output_____" ], [ "final_df = merged.drop(columns=['wilaya_maj', \"wilaya\", 'nom_wil', 'position', 'geometry'], axis=1)\nfinal_df.rename_axis('num', inplace=True)\nfinal_df.head()", "_____no_output_____" ], [ "final_df.to_csv('./caar_branches_to_check.csv', header = True)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af1f0ff926e26fe82027e5191eac596f089db7c
142,277
ipynb
Jupyter Notebook
os4-nlp-google.ipynb
valerij1975/P_Onesoil
615133628c5d3bcf1256a9cd40dd9a3fb7a1d7d0
[ "Apache-2.0" ]
null
null
null
os4-nlp-google.ipynb
valerij1975/P_Onesoil
615133628c5d3bcf1256a9cd40dd9a3fb7a1d7d0
[ "Apache-2.0" ]
null
null
null
os4-nlp-google.ipynb
valerij1975/P_Onesoil
615133628c5d3bcf1256a9cd40dd9a3fb7a1d7d0
[ "Apache-2.0" ]
null
null
null
33.643178
8,177
0.523725
[ [ [ "**Данный ноутбук проводит анализ текста с использование Google Cloud Nature Library**\n\n**Расценки на использование данного API:**\n\nИспользование вами естественного языка рассчитывается в виде **«единиц»**, где каждый документ, отправляемый в API для анализа, представляет собой **как минимум одну единицу**. Документы, содержащие более 1000 символов Unicode (включая символы пробелов и любые символы разметки, такие как HTML или XML-теги), считаются несколькими единицами, **одна единица на 1000 символов**.\n\nЦены на использование естественного языка рассчитываются **ежемесячно** в зависимости от того, какую функцию API вы использовали, и сколько единиц оценивается с использованием этих функций. В таблице ниже указана цена за 1000 единиц на основе **общего количества единиц, проанализированных в течение расчетного месяца**.\n\n1. - Entity Analysis\tIdentify entities and label by types such as person, organization, location, events, products and media.\n- до 5 тыс единиц - бесплатно, от 5 тыс до 1 млн - 1 долл/1 тыс\n2. - Sentiment Analysis\tUnderstand the overall sentiment expressed in a block of text.\n- до 5 тыс единиц - бесплатно, от 5 тыс до 1 млн - 1 долл/1 тыс\n3. - Entity Sentiment Analysis\tUnderstand the sentiment for entities identified in a block of text.\n- до 5 тыс единиц - бесплатно, от 5 тыс до 1 млн - 2 долл/1 тыс\n4. - Syntax Analysis\tExtract tokens and sentences, identify parts of speech (PoS) and create dependency parse trees for each sentence.\n- до 5 тыс единиц - бесплатно, от 5 тыс до 1 млн - 0,5 долл/1 тыс\n5. - Content Classification\tIdentify content categories that apply to a block of text.\n- до 30 тыс единиц - бесплатно, от 5 тыс до 1 млн - 2 долл/1 тыс\n\nВ данной задаче мы будем использовать для анализа текстовых отзывов:\n- Sentiment Analysis (анализ настроений) - для оценки полярности и силы настроений;\n- Entity Analysis (анализ сущностей) - для выявления и классификации значимых слов;\n- Syntax Analysis (синтаксический анализ) - для разбиения на слова и предложения.\n\n- **После отработаки данного кода API key удален из текста кода в целях безопасности моего Google-аккаунта. Вся полученная в результате обработки инорфмациия сохранена в CSV-файл для дальнейшей работы**\n- **Датасет разбивал на мелкие подразделы, чтобы при случайном сбое не потерять данные, за получение которых произведена оплата использования API**\n- **Выгрузку полученных данных тоже сделал по частям, чтобы минимизировать размер отдельных файлов для загрузки на гитхаб**", "_____no_output_____" ], [ "# Импорт библиотек и настройки", "_____no_output_____" ] ], [ [ "import os\nimport numpy as np\nimport pandas as pd\nfrom google.cloud import language_v1\nfrom tqdm import tqdm\n\n# этот блок для отслеживания операций с Pandas\nfrom tqdm.notebook import tqdm_notebook\ntqdm_notebook.pandas()", "_____no_output_____" ], [ "PATH = \"./data\" # относительный путь к подпапке.\npd.set_option('display.max_columns', None)", "_____no_output_____" ], [ "df = pd.read_csv(os.path.join(PATH, 'order_reviews.csv'), sep=';')\ndf.shape", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "# Предобработка датасета. Прогнозирование затрат на обработку\n\n- Прогнозировали - 42706*3=128118 запросов и сумму расходов 94,3 долл.\n- Фактически - 128082 запроса и сумма расходов: 80.65 евро, в т.ч. entity analysis - 32.3 euro, sentimental - 32.3 euro, syntax - 16.13\n\n-", "_____no_output_____" ] ], [ [ "df['C']=df.progress_apply(lambda x: (\"\" if pd.isna(x['review_comment_title']) else str(x['review_comment_title']) + '. ')\\\n + (\"\" if pd.isna(x['review_comment_message']) else str(x['review_comment_message'])), axis=1)", "_____no_output_____" ], [ "count_reviews=df.apply(lambda x: 0 if x['C']==\"\" else 1, axis=1).sum()\nprint('Количество отзывов (единиц) для отправки в API: ', count_reviews)\nprint('Прогнозная стоимость обработки в API, долл: ', (count_reviews-5000)/1000*2.5)", "Количество отзывов (единиц) для отправки в API: 42706\nПрогнозная стоимость обработки в API, долл: 94.26500000000001\n" ] ], [ [ "# Функции обработки датасета", "_____no_output_____" ] ], [ [ "# фильтрует датасет и направляет для обработки в API ненулевые значения, чтобы не платить за пустые запросы.\n# и она же вызывает три функции API Google\ndef get_text_for_nlp(message):\n if len(message)<2:\n #print(0)\n return 0\n else:\n #print(message)\n sent_score, sent_magnitude=analyze_text_sentiment(message) # два значения \n entities_list=analyze_text_entities(message) # список со словарями сущностей\n sent_count, token_count, sentlist, tokenlist =analyze_text_syntax2(message) # синтаксический анализ\n return sent_score, sent_magnitude, entities_list, sent_count, token_count, sentlist, tokenlist", "_____no_output_____" ], [ "def analyze_text_sentiment(text):\n try:\n client = language_v1.LanguageServiceClient.from_service_account_json('celestial-digit-0000000000.json')\n document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)\n response = client.analyze_sentiment(document=document)\n sentiment = response.document_sentiment\n return sentiment.score, sentiment.magnitude\n except Exception:\n print('Ошибка в функции sentiment') \n return 'НЕТ', 'НЕТ'", "_____no_output_____" ], [ "def analyze_text_entities(text):\n try:\n client = language_v1.LanguageServiceClient.from_service_account_json('celestial-digit-00000000000.json')\n document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)\n response = client.analyze_entities(document=document)\n sss=[]\n for entity in response.entities:\n results = dict(\n name=entity.name,\n type=entity.type_.name,\n salience=entity.salience,\n wikipedia_url=entity.metadata.get(\"wikipedia_url\", \"-\"),\n mid=entity.metadata.get(\"mid\", \"-\"),\n )\n sss.append(results)\n\n return sss\n except Exception:\n print('Ошибка в функции entities') \n return 'НЕТ'", "_____no_output_____" ], [ "def analyze_text_syntax2(text):\n try:\n client = language_v1.LanguageServiceClient.from_service_account_json('celestial-digit-00000000000.json')\n document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)\n\n response = client.analyze_syntax(document=document)\n\n sent_count=len(response.sentences)\n token_count=len(response.tokens)\n sentlist=[]\n for sentence in response.sentences:\n sentlist.append(sentence.text.content)\n tokenlist=[] \n for token in response.tokens:\n results = dict(\n token_text=token.text.content,\n token_label=token.dependency_edge.label.name,\n token_head_index=token.dependency_edge.head_token_index,\n token_tag=token.part_of_speech.tag.name,\n token_gender=token.part_of_speech.gender.name,\n token_number=token.part_of_speech.number.name,\n token_proper=token.part_of_speech.proper.name,\n token_lemma=token.lemma,\n )\n tokenlist.append(results) \n return sent_count, token_count, sentlist, tokenlist\n except Exception:\n print('Ошибка в функции syntax2') \n return 'НЕТ', 'НЕТ','НЕТ','НЕТ'", "_____no_output_____" ] ], [ [ "# Запуск обработки\n\nТак как это долгий процесс на моем оборудовании, а также в связи с возникновением сбоев на стороне API и чтобы не потерять обработанную информацию, то датасет разбивал на очень маленькие разделы для отправления в обработку.\n\n**Итого обработка заняла почти сутки**", "_____no_output_____" ] ], [ [ "#for i in tqdm(range(1,43)):\ndf['tmp']=np.nan\nfor i in tqdm(range(1,43)): \n print('c ',(i-1)*1000, ' до включительно ',i*1000)\n print(df['review_id'][(i-1)*1000],'---',df['review_id'][i*1000],'---',df['review_id'][(i-1)*1000:i*1000].shape)\n df['tmp'][(i-1)*1000:i*1000] = df['C'][(i-1)*1000:i*1000].progress_apply(get_text_for_nlp)\n df5=df[['review_id','order_id','tmp']]\n filename1='tmp'+str(i)+'.csv'\n df5[(i-1)*1000:i*1000].to_csv(os.path.join(PATH, filename1), sep=';', header=True, index=False)", " 0%| | 0/42 [00:00<?, ?it/s]" ], [ "for i in tqdm(range(43,100)): \n print('c ',(i-1)*1000, ' до включительно ',i*1000)\n print(df['review_id'][(i-1)*1000],'---',df['review_id'][i*1000],'---',df['review_id'][(i-1)*1000:i*1000].shape)\n df['tmp'][(i-1)*1000:i*1000] = df['C'][(i-1)*1000:i*1000].progress_apply(get_text_for_nlp)\n df5=df[['review_id','order_id','tmp']]\n filename1='tmp'+str(i)+'.csv'\n df5[(i-1)*1000:i*1000].to_csv(os.path.join(PATH, filename1), sep=';', header=True, index=False)", " 0%| | 0/57 [00:00<?, ?it/s]" ], [ "#for i in tqdm(range(99000,99225)): \n# print('c ',(i-1), ' до включительно ',i)\n# print(df['review_id'][(i-1)],'---',df['review_id'][i],'---',df['review_id'][(i-1):i].shape)\ndf['tmp'][99000:99225] = df['C'][99000:99225].progress_apply(get_text_for_nlp)\ndf5=df[['review_id','order_id','tmp']]\nfilename1='tmp'+str(100)+'.csv'\ndf5[99000:99225].to_csv(os.path.join(PATH, filename1), sep=';', header=True, index=False)", "_____no_output_____" ] ], [ [ "# Сохраняем промежуточные результаты, разворачиваем полученные данные по столбцам, сохраняем в CSV-файлы в виде разных наборов полей", "_____no_output_____" ] ], [ [ "# сохраняем промежуточный результат от API во внешний файл, с привязкой к ключевым полям.\nfilename1='tmp_all.csv'\ndf5.to_csv(os.path.join(PATH, filename1), sep=';', header=True, index=False)", "_____no_output_____" ], [ "df[['C','tmp']][0:10]", "_____no_output_____" ], [ "# необработанные тексты отзывов. Это однобуквенные значения.\ndf[(df['C']!=\"\") & (df['tmp']==0)][['C','tmp']].shape", "_____no_output_____" ], [ "df5[['review_id','order_id','tmp']][15:21]", "_____no_output_____" ], [ "df3=df.tmp.progress_apply(pd.Series) # variant 2", "_____no_output_____" ], [ "df3.rename(columns={0:'sent_score',1:'sent_magnitude', 2:'entities_list',3:'sentences_count',4:'token_count',5:'sentlist',6:'tokenlist'}, inplace=True)", "_____no_output_____" ], [ "df3.shape", "_____no_output_____" ], [ "df3.to_csv(os.path.join(PATH, 'tmp_all_just.csv'), sep=';', header=True, index=False)", "_____no_output_____" ], [ "df3.head(4)", "_____no_output_____" ], [ "df4=pd.concat([df,df3],ignore_index=False, axis=1)\nprint(df4.shape)", "(99224, 16)\n" ] ], [ [ "## Это финальный файл для дальнейшей работы - ключевые поля 'review_id','order_id' и развернутые данные из API\n\nНа всякий случай сохраняю с двумя разными разделителями. А также полный файл и сокращенные. На гитхаб эти файлы в оригинальном виде не поместяться", "_____no_output_____" ] ], [ [ "columns_for_used=['review_id','order_id','sent_score','sent_magnitude', 'entities_list','sentences_count','token_count','sentlist','tokenlist']\ncolumns_for_used_num=['review_id','order_id','sent_score','sent_magnitude', 'sentences_count','token_count']\ncolumns_for_used_entit=['review_id','order_id','entities_list']\ncolumns_for_used_sent=['review_id','order_id','sentlist']\ncolumns_for_used_token=['review_id','order_id','tokenlist']", "_____no_output_____" ], [ "df4.to_csv(os.path.join(PATH, 'order_reviews_only_Google_full.csv'), sep=';', header=True, index=False)", "_____no_output_____" ], [ "df4.to_csv(os.path.join(PATH, 'order_reviews_only_Google_full2.csv'), sep='|', header=True, index=False)", "_____no_output_____" ], [ "df4[columns_for_used].to_csv(os.path.join(PATH, 'order_reviews_only_Google1.csv'), sep=';', header=True, index=False)", "_____no_output_____" ], [ "df4[columns_for_used].to_csv(os.path.join(PATH, 'order_reviews_only_Google2.csv'), sep='|', header=True, index=False)", "_____no_output_____" ], [ "df4[columns_for_used_num].to_csv(os.path.join(PATH, 'order_reviews_only_Google_num1.csv'), sep=';', header=True, index=False)\ndf4[columns_for_used_num].to_csv(os.path.join(PATH, 'order_reviews_only_Google_num2.csv'), sep='|', header=True, index=False)", "_____no_output_____" ], [ "df4[columns_for_used_entit].to_csv(os.path.join(PATH, 'order_reviews_only_Google_entit1.csv'), sep=';', header=True, index=False)\ndf4[columns_for_used_entit].to_csv(os.path.join(PATH, 'order_reviews_only_Google_entit2.csv'), sep='|', header=True, index=False)", "_____no_output_____" ], [ "df4[columns_for_used_sent].to_csv(os.path.join(PATH, 'order_reviews_only_Google_sent1.csv'), sep=';', header=True, index=False)\ndf4[columns_for_used_sent].to_csv(os.path.join(PATH, 'order_reviews_only_Google_sent2.csv'), sep='|', header=True, index=False)", "_____no_output_____" ], [ "df4[columns_for_used_token].to_csv(os.path.join(PATH, 'order_reviews_only_Google_token1.csv'), sep=';', header=True, index=False)\ndf4[columns_for_used_token].to_csv(os.path.join(PATH, 'order_reviews_only_Google_token2.csv'), sep='|', header=True, index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af2039a7509ecbbf0947e9788c2745606906f2c
196,000
ipynb
Jupyter Notebook
Machine-Learning-with-Python-master/H2O Higgs Boson.ipynb
m1016m/NN
9c523c739b7fdfac766549f4db5ecdbff731011f
[ "MIT" ]
1
2019-05-30T00:28:23.000Z
2019-05-30T00:28:23.000Z
Machine-Learning-with-Python-master/H2O Higgs Boson.ipynb
m1016m/NN
9c523c739b7fdfac766549f4db5ecdbff731011f
[ "MIT" ]
null
null
null
Machine-Learning-with-Python-master/H2O Higgs Boson.ipynb
m1016m/NN
9c523c739b7fdfac766549f4db5ecdbff731011f
[ "MIT" ]
1
2021-09-13T03:27:30.000Z
2021-09-13T03:27:30.000Z
83.58209
25,664
0.607327
[ [ [ "import h2o\nh2o.init(max_mem_size = 2) #uses all cores by default\nh2o.remove_all()\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom h2o.estimators.deeplearning import H2ODeepLearningEstimator", "Checking whether there is an H2O instance running at http://localhost:54321. connected.\n" ], [ "higgs = h2o.import_file('higgs_boston_train.csv')", "Parse progress: |█████████████████████████████████████████████████████████| 100%\n" ], [ "higgs.head()", "_____no_output_____" ], [ "higgs.shape", "_____no_output_____" ], [ "higgs_df = higgs.as_data_frame(use_pandas=True)", "_____no_output_____" ], [ "higgs_df['Label'].value_counts()", "_____no_output_____" ], [ "higgs.describe()", "Rows:250000\nCols:33\n\n\n" ], [ "train, valid, test = higgs.split_frame([0.6, 0.2], seed = 2019)\nhiggs_X = higgs.col_names[1: -1]\nhiggs_y = higgs.col_names[-1]", "_____no_output_____" ], [ "higgs_model_v1 = H2ODeepLearningEstimator(model_id = 'higgs_v1', epochs = 1, variable_importances = True)\nhiggs_model_v1.train(higgs_X, higgs_y, training_frame = train, validation_frame = valid)\nprint(higgs_model_v1)", "deeplearning Model Build progress: |██████████████████████████████████████| 100%\nModel Details\n=============\nH2ODeepLearningEstimator : Deep Learning\nModel Key: higgs_v1\n\n\nModelMetricsBinomial: deeplearning\n** Reported on train data. **\n\nMSE: 0.02404827265062027\nRMSE: 0.155075054894784\nLogLoss: 0.08511327601076424\nMean Per-Class Error: 0.027810905187065638\nAUC: 0.994862989427392\npr_auc: 0.9723869853229047\nGini: 0.9897259788547841\nConfusion Matrix (Act/Pred) for max f1 @ threshold = 0.4206674380278053: \n" ], [ "var_df = pd.DataFrame(higgs_model_v1.varimp(), columns = ['Variable', 'Relative Importance', 'Scaled Importance', 'Percentage'])\nprint(var_df.shape)", "(31, 4)\n" ], [ "var_df.head(10)", "_____no_output_____" ], [ "higgs_v1_df = higgs_model_v1.score_history()\nhiggs_v1_df", "_____no_output_____" ], [ "plt.plot(higgs_v1_df['training_classification_error'], label=\"training_classification_error\")\nplt.plot(higgs_v1_df['validation_classification_error'], label=\"validation_classification_error\")\nplt.title(\"Higgs Deep Learner\")\nplt.legend();", "_____no_output_____" ], [ "pred = higgs_model_v1.predict(test[1:-1]).as_data_frame(use_pandas=True)\ntest_actual = test.as_data_frame(use_pandas=True)['Label']\n(test_actual == pred['predict']).mean()", "deeplearning prediction progress: |███████████████████████████████████████| 100%\n" ], [ "higgs_model_v2 = H2ODeepLearningEstimator(model_id = 'higgs_v2', hidden = [32, 32, 32], epochs = 1000000,\n score_validation_samples = 10000, stopping_rounds = 2, stopping_metric = 'misclassification', \n stopping_tolerance = 0.01)\nhiggs_model_v2.train(higgs_X, higgs_y, training_frame = train, validation_frame = valid)", "deeplearning Model Build progress: |██████████████████████████████████████| 100%\n" ], [ "higgs_v2_df = higgs_model_v2.score_history()\nhiggs_v2_df", "_____no_output_____" ], [ "plt.plot(higgs_v2_df['training_classification_error'], label=\"training_classification_error\")\nplt.plot(higgs_v2_df['validation_classification_error'], label=\"validation_classification_error\")\nplt.title(\"Higgs Deep Learner (Early Stop)\")\nplt.legend();", "_____no_output_____" ], [ "pred = higgs_model_v2.predict(test[1:-1]).as_data_frame(use_pandas=True)\ntest_actual = test.as_data_frame(use_pandas=True)['Label']\n(test_actual == pred['predict']).mean()", "deeplearning prediction progress: |███████████████████████████████████████| 100%\n" ], [ "higgs_model_v2.varimp_plot();", "_____no_output_____" ], [ "from h2o.automl import H2OAutoML\n\naml = H2OAutoML(max_models = 10, max_runtime_secs=100, seed = 1)\naml.train(higgs_X, higgs_y, training_frame = train, validation_frame = valid)", "AutoML progress: |████████████████████████████████████████████████████████| 100%\n" ], [ "aml.leaderboard", "_____no_output_____" ] ], [ [ "AutoML has built 5 models inlcuding GLM, DRF (Distributed Random Forest) and XRT (Extremely Randomized Trees) and two stacked ensemble models (the 2nd and 3rd) and the best model is XRT.\n\nIt turns out, my proud deep learning models are not even on the leaderboard.", "_____no_output_____" ] ] ]
[ "code", "markdown" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4af20a6e19bd61b9b30c5cc1d5e73c7b61936c46
39,509
ipynb
Jupyter Notebook
008_networks_G_D.ipynb
chnghia/pytorch-lightning-gan
3e484ea8eca2a3365a6b209a979a95a5b2e4a6f2
[ "MIT" ]
3
2020-10-07T01:24:43.000Z
2021-04-13T15:03:19.000Z
008_networks_G_D.ipynb
chnghia/pytorch-lightning-gan
3e484ea8eca2a3365a6b209a979a95a5b2e4a6f2
[ "MIT" ]
null
null
null
008_networks_G_D.ipynb
chnghia/pytorch-lightning-gan
3e484ea8eca2a3365a6b209a979a95a5b2e4a6f2
[ "MIT" ]
null
null
null
46.867141
132
0.373409
[ [ [ "import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport functools\nfrom torchsummary import summary", "_____no_output_____" ], [ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # PyTorch v0.4.0", "_____no_output_____" ] ], [ [ "## Generators", "_____no_output_____" ] ], [ [ "input_nc = 3\noutput_nc = 3\nngf = 64\nnorm_layer=nn.BatchNorm2d\nuse_dropout=False", "_____no_output_____" ], [ "from models.networks.generator.resnet import ResnetGenerator", "_____no_output_____" ], [ "# resnet_9blocks\nnet = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)", "_____no_output_____" ], [ "print(net)", "ResnetGenerator(\n (model): Sequential(\n (0): ReflectionPad2d((3, 3, 3, 3))\n (1): Conv2d(3, 64, kernel_size=(7, 7), stride=(1, 1), bias=False)\n (2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (5): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (6): ReLU(inplace=True)\n (7): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (8): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (9): ReLU(inplace=True)\n (10): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (11): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (12): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (13): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (14): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (15): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (16): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (17): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (18): ResnetBlock(\n (conv_block): Sequential(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (3): ReLU(inplace=True)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), bias=False)\n (6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (19): ConvTranspose2d(256, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), output_padding=(1, 1), bias=False)\n (20): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (21): ReLU(inplace=True)\n (22): ConvTranspose2d(128, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), output_padding=(1, 1), bias=False)\n (23): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (24): ReLU(inplace=True)\n (25): ReflectionPad2d((3, 3, 3, 3))\n (26): Conv2d(64, 3, kernel_size=(7, 7), stride=(1, 1))\n (27): Tanh()\n )\n)\n" ], [ "net = net.to(device)\nsummary(net, input_size=(3, 256, 256))", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n ReflectionPad2d-1 [-1, 3, 262, 262] 0\n Conv2d-2 [-1, 64, 256, 256] 9,408\n BatchNorm2d-3 [-1, 64, 256, 256] 128\n ReLU-4 [-1, 64, 256, 256] 0\n Conv2d-5 [-1, 128, 128, 128] 73,728\n BatchNorm2d-6 [-1, 128, 128, 128] 256\n ReLU-7 [-1, 128, 128, 128] 0\n Conv2d-8 [-1, 256, 64, 64] 294,912\n BatchNorm2d-9 [-1, 256, 64, 64] 512\n ReLU-10 [-1, 256, 64, 64] 0\n ReflectionPad2d-11 [-1, 256, 66, 66] 0\n Conv2d-12 [-1, 256, 64, 64] 589,824\n BatchNorm2d-13 [-1, 256, 64, 64] 512\n ReLU-14 [-1, 256, 64, 64] 0\n ReflectionPad2d-15 [-1, 256, 66, 66] 0\n Conv2d-16 [-1, 256, 64, 64] 589,824\n BatchNorm2d-17 [-1, 256, 64, 64] 512\n ResnetBlock-18 [-1, 256, 64, 64] 0\n ReflectionPad2d-19 [-1, 256, 66, 66] 0\n Conv2d-20 [-1, 256, 64, 64] 589,824\n BatchNorm2d-21 [-1, 256, 64, 64] 512\n ReLU-22 [-1, 256, 64, 64] 0\n ReflectionPad2d-23 [-1, 256, 66, 66] 0\n Conv2d-24 [-1, 256, 64, 64] 589,824\n BatchNorm2d-25 [-1, 256, 64, 64] 512\n ResnetBlock-26 [-1, 256, 64, 64] 0\n ReflectionPad2d-27 [-1, 256, 66, 66] 0\n Conv2d-28 [-1, 256, 64, 64] 589,824\n BatchNorm2d-29 [-1, 256, 64, 64] 512\n ReLU-30 [-1, 256, 64, 64] 0\n ReflectionPad2d-31 [-1, 256, 66, 66] 0\n Conv2d-32 [-1, 256, 64, 64] 589,824\n BatchNorm2d-33 [-1, 256, 64, 64] 512\n ResnetBlock-34 [-1, 256, 64, 64] 0\n ReflectionPad2d-35 [-1, 256, 66, 66] 0\n Conv2d-36 [-1, 256, 64, 64] 589,824\n BatchNorm2d-37 [-1, 256, 64, 64] 512\n ReLU-38 [-1, 256, 64, 64] 0\n ReflectionPad2d-39 [-1, 256, 66, 66] 0\n Conv2d-40 [-1, 256, 64, 64] 589,824\n BatchNorm2d-41 [-1, 256, 64, 64] 512\n ResnetBlock-42 [-1, 256, 64, 64] 0\n ReflectionPad2d-43 [-1, 256, 66, 66] 0\n Conv2d-44 [-1, 256, 64, 64] 589,824\n BatchNorm2d-45 [-1, 256, 64, 64] 512\n ReLU-46 [-1, 256, 64, 64] 0\n ReflectionPad2d-47 [-1, 256, 66, 66] 0\n Conv2d-48 [-1, 256, 64, 64] 589,824\n BatchNorm2d-49 [-1, 256, 64, 64] 512\n ResnetBlock-50 [-1, 256, 64, 64] 0\n ReflectionPad2d-51 [-1, 256, 66, 66] 0\n Conv2d-52 [-1, 256, 64, 64] 589,824\n BatchNorm2d-53 [-1, 256, 64, 64] 512\n ReLU-54 [-1, 256, 64, 64] 0\n ReflectionPad2d-55 [-1, 256, 66, 66] 0\n Conv2d-56 [-1, 256, 64, 64] 589,824\n BatchNorm2d-57 [-1, 256, 64, 64] 512\n ResnetBlock-58 [-1, 256, 64, 64] 0\n ReflectionPad2d-59 [-1, 256, 66, 66] 0\n Conv2d-60 [-1, 256, 64, 64] 589,824\n BatchNorm2d-61 [-1, 256, 64, 64] 512\n ReLU-62 [-1, 256, 64, 64] 0\n ReflectionPad2d-63 [-1, 256, 66, 66] 0\n Conv2d-64 [-1, 256, 64, 64] 589,824\n BatchNorm2d-65 [-1, 256, 64, 64] 512\n ResnetBlock-66 [-1, 256, 64, 64] 0\n ReflectionPad2d-67 [-1, 256, 66, 66] 0\n Conv2d-68 [-1, 256, 64, 64] 589,824\n BatchNorm2d-69 [-1, 256, 64, 64] 512\n ReLU-70 [-1, 256, 64, 64] 0\n ReflectionPad2d-71 [-1, 256, 66, 66] 0\n Conv2d-72 [-1, 256, 64, 64] 589,824\n BatchNorm2d-73 [-1, 256, 64, 64] 512\n ResnetBlock-74 [-1, 256, 64, 64] 0\n ReflectionPad2d-75 [-1, 256, 66, 66] 0\n Conv2d-76 [-1, 256, 64, 64] 589,824\n BatchNorm2d-77 [-1, 256, 64, 64] 512\n ReLU-78 [-1, 256, 64, 64] 0\n ReflectionPad2d-79 [-1, 256, 66, 66] 0\n Conv2d-80 [-1, 256, 64, 64] 589,824\n BatchNorm2d-81 [-1, 256, 64, 64] 512\n ResnetBlock-82 [-1, 256, 64, 64] 0\n ConvTranspose2d-83 [-1, 128, 128, 128] 294,912\n BatchNorm2d-84 [-1, 128, 128, 128] 256\n ReLU-85 [-1, 128, 128, 128] 0\n ConvTranspose2d-86 [-1, 64, 256, 256] 73,728\n BatchNorm2d-87 [-1, 64, 256, 256] 128\n ReLU-88 [-1, 64, 256, 256] 0\n ReflectionPad2d-89 [-1, 64, 262, 262] 0\n Conv2d-90 [-1, 3, 256, 256] 9,411\n Tanh-91 [-1, 3, 256, 256] 0\n================================================================\nTotal params: 11,383,427\nTrainable params: 11,383,427\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.75\nForward/backward pass size (MB): 935.23\nParams size (MB): 43.42\nEstimated Total Size (MB): 979.40\n----------------------------------------------------------------\n" ], [ "# resnet_6blocks\nnet = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)", "_____no_output_____" ], [ "net = net.to(device)\nsummary(net, input_size=(3, 256, 256))", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n ReflectionPad2d-1 [-1, 3, 262, 262] 0\n Conv2d-2 [-1, 64, 256, 256] 9,408\n BatchNorm2d-3 [-1, 64, 256, 256] 128\n ReLU-4 [-1, 64, 256, 256] 0\n Conv2d-5 [-1, 128, 128, 128] 73,728\n BatchNorm2d-6 [-1, 128, 128, 128] 256\n ReLU-7 [-1, 128, 128, 128] 0\n Conv2d-8 [-1, 256, 64, 64] 294,912\n BatchNorm2d-9 [-1, 256, 64, 64] 512\n ReLU-10 [-1, 256, 64, 64] 0\n ReflectionPad2d-11 [-1, 256, 66, 66] 0\n Conv2d-12 [-1, 256, 64, 64] 589,824\n BatchNorm2d-13 [-1, 256, 64, 64] 512\n ReLU-14 [-1, 256, 64, 64] 0\n ReflectionPad2d-15 [-1, 256, 66, 66] 0\n Conv2d-16 [-1, 256, 64, 64] 589,824\n BatchNorm2d-17 [-1, 256, 64, 64] 512\n ResnetBlock-18 [-1, 256, 64, 64] 0\n ReflectionPad2d-19 [-1, 256, 66, 66] 0\n Conv2d-20 [-1, 256, 64, 64] 589,824\n BatchNorm2d-21 [-1, 256, 64, 64] 512\n ReLU-22 [-1, 256, 64, 64] 0\n ReflectionPad2d-23 [-1, 256, 66, 66] 0\n Conv2d-24 [-1, 256, 64, 64] 589,824\n BatchNorm2d-25 [-1, 256, 64, 64] 512\n ResnetBlock-26 [-1, 256, 64, 64] 0\n ReflectionPad2d-27 [-1, 256, 66, 66] 0\n Conv2d-28 [-1, 256, 64, 64] 589,824\n BatchNorm2d-29 [-1, 256, 64, 64] 512\n ReLU-30 [-1, 256, 64, 64] 0\n ReflectionPad2d-31 [-1, 256, 66, 66] 0\n Conv2d-32 [-1, 256, 64, 64] 589,824\n BatchNorm2d-33 [-1, 256, 64, 64] 512\n ResnetBlock-34 [-1, 256, 64, 64] 0\n ReflectionPad2d-35 [-1, 256, 66, 66] 0\n Conv2d-36 [-1, 256, 64, 64] 589,824\n BatchNorm2d-37 [-1, 256, 64, 64] 512\n ReLU-38 [-1, 256, 64, 64] 0\n ReflectionPad2d-39 [-1, 256, 66, 66] 0\n Conv2d-40 [-1, 256, 64, 64] 589,824\n BatchNorm2d-41 [-1, 256, 64, 64] 512\n ResnetBlock-42 [-1, 256, 64, 64] 0\n ReflectionPad2d-43 [-1, 256, 66, 66] 0\n Conv2d-44 [-1, 256, 64, 64] 589,824\n BatchNorm2d-45 [-1, 256, 64, 64] 512\n ReLU-46 [-1, 256, 64, 64] 0\n ReflectionPad2d-47 [-1, 256, 66, 66] 0\n Conv2d-48 [-1, 256, 64, 64] 589,824\n BatchNorm2d-49 [-1, 256, 64, 64] 512\n ResnetBlock-50 [-1, 256, 64, 64] 0\n ReflectionPad2d-51 [-1, 256, 66, 66] 0\n Conv2d-52 [-1, 256, 64, 64] 589,824\n BatchNorm2d-53 [-1, 256, 64, 64] 512\n ReLU-54 [-1, 256, 64, 64] 0\n ReflectionPad2d-55 [-1, 256, 66, 66] 0\n Conv2d-56 [-1, 256, 64, 64] 589,824\n BatchNorm2d-57 [-1, 256, 64, 64] 512\n ResnetBlock-58 [-1, 256, 64, 64] 0\n ConvTranspose2d-59 [-1, 128, 128, 128] 294,912\n BatchNorm2d-60 [-1, 128, 128, 128] 256\n ReLU-61 [-1, 128, 128, 128] 0\n ConvTranspose2d-62 [-1, 64, 256, 256] 73,728\n BatchNorm2d-63 [-1, 64, 256, 256] 128\n ReLU-64 [-1, 64, 256, 256] 0\n ReflectionPad2d-65 [-1, 64, 262, 262] 0\n Conv2d-66 [-1, 3, 256, 256] 9,411\n Tanh-67 [-1, 3, 256, 256] 0\n================================================================\nTotal params: 7,841,411\nTrainable params: 7,841,411\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.75\nForward/backward pass size (MB): 740.18\nParams size (MB): 29.91\nEstimated Total Size (MB): 770.85\n----------------------------------------------------------------\n" ], [ "from models.networks.generator.unet import UnetGenerator", "_____no_output_____" ], [ "# unet_128\nnet = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)", "_____no_output_____" ], [ "net = net.to(device)\nsummary(net, input_size=(3, 256, 256))", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 64, 128, 128] 3,072\n LeakyReLU-2 [-1, 64, 128, 128] 0\n Conv2d-3 [-1, 128, 64, 64] 131,072\n BatchNorm2d-4 [-1, 128, 64, 64] 256\n LeakyReLU-5 [-1, 128, 64, 64] 0\n Conv2d-6 [-1, 256, 32, 32] 524,288\n BatchNorm2d-7 [-1, 256, 32, 32] 512\n LeakyReLU-8 [-1, 256, 32, 32] 0\n Conv2d-9 [-1, 512, 16, 16] 2,097,152\n BatchNorm2d-10 [-1, 512, 16, 16] 1,024\n LeakyReLU-11 [-1, 512, 16, 16] 0\n Conv2d-12 [-1, 512, 8, 8] 4,194,304\n BatchNorm2d-13 [-1, 512, 8, 8] 1,024\n LeakyReLU-14 [-1, 512, 8, 8] 0\n Conv2d-15 [-1, 512, 4, 4] 4,194,304\n BatchNorm2d-16 [-1, 512, 4, 4] 1,024\n LeakyReLU-17 [-1, 512, 4, 4] 0\n Conv2d-18 [-1, 512, 2, 2] 4,194,304\n ReLU-19 [-1, 512, 2, 2] 0\n ConvTranspose2d-20 [-1, 512, 4, 4] 4,194,304\n BatchNorm2d-21 [-1, 512, 4, 4] 1,024\nUnetSkipConnectionBlock-22 [-1, 1024, 4, 4] 0\n ReLU-23 [-1, 1024, 4, 4] 0\n ConvTranspose2d-24 [-1, 512, 8, 8] 8,388,608\n BatchNorm2d-25 [-1, 512, 8, 8] 1,024\nUnetSkipConnectionBlock-26 [-1, 1024, 8, 8] 0\n ReLU-27 [-1, 1024, 8, 8] 0\n ConvTranspose2d-28 [-1, 512, 16, 16] 8,388,608\n BatchNorm2d-29 [-1, 512, 16, 16] 1,024\nUnetSkipConnectionBlock-30 [-1, 1024, 16, 16] 0\n ReLU-31 [-1, 1024, 16, 16] 0\n ConvTranspose2d-32 [-1, 256, 32, 32] 4,194,304\n BatchNorm2d-33 [-1, 256, 32, 32] 512\nUnetSkipConnectionBlock-34 [-1, 512, 32, 32] 0\n ReLU-35 [-1, 512, 32, 32] 0\n ConvTranspose2d-36 [-1, 128, 64, 64] 1,048,576\n BatchNorm2d-37 [-1, 128, 64, 64] 256\nUnetSkipConnectionBlock-38 [-1, 256, 64, 64] 0\n ReLU-39 [-1, 256, 64, 64] 0\n ConvTranspose2d-40 [-1, 64, 128, 128] 262,144\n BatchNorm2d-41 [-1, 64, 128, 128] 128\nUnetSkipConnectionBlock-42 [-1, 128, 128, 128] 0\n ReLU-43 [-1, 128, 128, 128] 0\n ConvTranspose2d-44 [-1, 3, 256, 256] 6,147\n Tanh-45 [-1, 3, 256, 256] 0\nUnetSkipConnectionBlock-46 [-1, 3, 256, 256] 0\n================================================================\nTotal params: 41,828,995\nTrainable params: 41,828,995\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.75\nForward/backward pass size (MB): 134.34\nParams size (MB): 159.56\nEstimated Total Size (MB): 294.66\n----------------------------------------------------------------\n" ], [ "# unet_256\nnet = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)", "_____no_output_____" ], [ "net = net.to(device)\nsummary(net, input_size=(3, 256, 256))", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 64, 128, 128] 3,072\n LeakyReLU-2 [-1, 64, 128, 128] 0\n Conv2d-3 [-1, 128, 64, 64] 131,072\n BatchNorm2d-4 [-1, 128, 64, 64] 256\n LeakyReLU-5 [-1, 128, 64, 64] 0\n Conv2d-6 [-1, 256, 32, 32] 524,288\n BatchNorm2d-7 [-1, 256, 32, 32] 512\n LeakyReLU-8 [-1, 256, 32, 32] 0\n Conv2d-9 [-1, 512, 16, 16] 2,097,152\n BatchNorm2d-10 [-1, 512, 16, 16] 1,024\n LeakyReLU-11 [-1, 512, 16, 16] 0\n Conv2d-12 [-1, 512, 8, 8] 4,194,304\n BatchNorm2d-13 [-1, 512, 8, 8] 1,024\n LeakyReLU-14 [-1, 512, 8, 8] 0\n Conv2d-15 [-1, 512, 4, 4] 4,194,304\n BatchNorm2d-16 [-1, 512, 4, 4] 1,024\n LeakyReLU-17 [-1, 512, 4, 4] 0\n Conv2d-18 [-1, 512, 2, 2] 4,194,304\n BatchNorm2d-19 [-1, 512, 2, 2] 1,024\n LeakyReLU-20 [-1, 512, 2, 2] 0\n Conv2d-21 [-1, 512, 1, 1] 4,194,304\n ReLU-22 [-1, 512, 1, 1] 0\n ConvTranspose2d-23 [-1, 512, 2, 2] 4,194,304\n BatchNorm2d-24 [-1, 512, 2, 2] 1,024\nUnetSkipConnectionBlock-25 [-1, 1024, 2, 2] 0\n ReLU-26 [-1, 1024, 2, 2] 0\n ConvTranspose2d-27 [-1, 512, 4, 4] 8,388,608\n BatchNorm2d-28 [-1, 512, 4, 4] 1,024\nUnetSkipConnectionBlock-29 [-1, 1024, 4, 4] 0\n ReLU-30 [-1, 1024, 4, 4] 0\n ConvTranspose2d-31 [-1, 512, 8, 8] 8,388,608\n BatchNorm2d-32 [-1, 512, 8, 8] 1,024\nUnetSkipConnectionBlock-33 [-1, 1024, 8, 8] 0\n ReLU-34 [-1, 1024, 8, 8] 0\n ConvTranspose2d-35 [-1, 512, 16, 16] 8,388,608\n BatchNorm2d-36 [-1, 512, 16, 16] 1,024\nUnetSkipConnectionBlock-37 [-1, 1024, 16, 16] 0\n ReLU-38 [-1, 1024, 16, 16] 0\n ConvTranspose2d-39 [-1, 256, 32, 32] 4,194,304\n BatchNorm2d-40 [-1, 256, 32, 32] 512\nUnetSkipConnectionBlock-41 [-1, 512, 32, 32] 0\n ReLU-42 [-1, 512, 32, 32] 0\n ConvTranspose2d-43 [-1, 128, 64, 64] 1,048,576\n BatchNorm2d-44 [-1, 128, 64, 64] 256\nUnetSkipConnectionBlock-45 [-1, 256, 64, 64] 0\n ReLU-46 [-1, 256, 64, 64] 0\n ConvTranspose2d-47 [-1, 64, 128, 128] 262,144\n BatchNorm2d-48 [-1, 64, 128, 128] 128\nUnetSkipConnectionBlock-49 [-1, 128, 128, 128] 0\n ReLU-50 [-1, 128, 128, 128] 0\n ConvTranspose2d-51 [-1, 3, 256, 256] 6,147\n Tanh-52 [-1, 3, 256, 256] 0\nUnetSkipConnectionBlock-53 [-1, 3, 256, 256] 0\n================================================================\nTotal params: 54,413,955\nTrainable params: 54,413,955\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.75\nForward/backward pass size (MB): 134.46\nParams size (MB): 207.57\nEstimated Total Size (MB): 342.78\n----------------------------------------------------------------\n" ] ], [ [ "## Discriminator", "_____no_output_____" ] ], [ [ "from models.networks.discriminator.nlayer_discriminator import NLayerDiscriminator", "_____no_output_____" ], [ "# params\nndf = 64", "_____no_output_____" ], [ "net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)", "_____no_output_____" ], [ "net = net.to(device)\nsummary(net, input_size=(3, 256, 256))", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 64, 128, 128] 3,136\n LeakyReLU-2 [-1, 64, 128, 128] 0\n Conv2d-3 [-1, 128, 64, 64] 131,072\n BatchNorm2d-4 [-1, 128, 64, 64] 256\n LeakyReLU-5 [-1, 128, 64, 64] 0\n Conv2d-6 [-1, 256, 32, 32] 524,288\n BatchNorm2d-7 [-1, 256, 32, 32] 512\n LeakyReLU-8 [-1, 256, 32, 32] 0\n Conv2d-9 [-1, 512, 31, 31] 2,097,152\n BatchNorm2d-10 [-1, 512, 31, 31] 1,024\n LeakyReLU-11 [-1, 512, 31, 31] 0\n Conv2d-12 [-1, 1, 30, 30] 8,193\n================================================================\nTotal params: 2,765,633\nTrainable params: 2,765,633\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.75\nForward/backward pass size (MB): 45.27\nParams size (MB): 10.55\nEstimated Total Size (MB): 56.57\n----------------------------------------------------------------\n" ], [ "from models.pix2pix.models import Discriminator", "_____no_output_____" ], [ "net = Discriminator()", "_____no_output_____" ], [ "net = net.to(device)\nsummary(net, [(3, 256, 256),(3, 256, 256)])", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 64, 128, 128] 6,208\n LeakyReLU-2 [-1, 64, 128, 128] 0\n Conv2d-3 [-1, 128, 64, 64] 131,200\n InstanceNorm2d-4 [-1, 128, 64, 64] 0\n LeakyReLU-5 [-1, 128, 64, 64] 0\n Conv2d-6 [-1, 256, 32, 32] 524,544\n InstanceNorm2d-7 [-1, 256, 32, 32] 0\n LeakyReLU-8 [-1, 256, 32, 32] 0\n Conv2d-9 [-1, 512, 16, 16] 2,097,664\n InstanceNorm2d-10 [-1, 512, 16, 16] 0\n LeakyReLU-11 [-1, 512, 16, 16] 0\n ZeroPad2d-12 [-1, 512, 17, 17] 0\n Conv2d-13 [-1, 1, 16, 16] 8,192\n================================================================\nTotal params: 2,767,808\nTrainable params: 2,767,808\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 147456.00\nForward/backward pass size (MB): 38.13\nParams size (MB): 10.56\nEstimated Total Size (MB): 147504.69\n----------------------------------------------------------------\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
4af20a9aeffceab57c91c54b0a9e857761509f5c
4,805
ipynb
Jupyter Notebook
exercises/1.11.ipynb
tokits/sicp-study
4ee62a3c83f8ec7ccdf2d0e87719f37a701f1039
[ "CC0-1.0" ]
null
null
null
exercises/1.11.ipynb
tokits/sicp-study
4ee62a3c83f8ec7ccdf2d0e87719f37a701f1039
[ "CC0-1.0" ]
null
null
null
exercises/1.11.ipynb
tokits/sicp-study
4ee62a3c83f8ec7ccdf2d0e87719f37a701f1039
[ "CC0-1.0" ]
null
null
null
20.891304
85
0.351925
[ [ [ "### 練習問題1.11\n関数$f$は次のように定義される。\n\n$\n f(n)=\\begin{cases}\n n & (n < 3) \\\\\n f(n-1) + 2 \\cdot f(n-2) + 3 \\cdot f(n - 3) & (n>=3)\n \\end{cases}\n$ \n\n$f$を表す⼿続きを再帰プロセスによって実装しなさい。 \nまた、$f$を表す⼿続きを反復プロセスによって実装しなさい。\n", "_____no_output_____" ] ], [ [ ";再帰プロセスによる実装\n(define (f n)\n (if (< n 3)\n (begin\n (display \"f(\")\n (display n)\n (display \")=\")\n (display n)\n (newline)\n n\n )\n (begin\n (display \"f(\")\n (display (- n 1))\n (display \")+2*f(\")\n (display (- n 2))\n (display \")+3*f(\")\n (display (- n 3))\n (display \")\")\n (newline)\n (+ (+ (f (- n 1)) (* 2 (f (- n 2)))) (* 3 (f (- n 3)))))\n )\n )", "_____no_output_____" ], [ "(display (f 0))\n(newline)\n(display (f 1))\n(newline)\n(display (f 2))\n(newline)\n(display (f 3))\n(newline)\n(display (f 4))\n(newline)\n(display (f 5))\n(newline)", "f(0)=0\n0\nf(1)=1\n1\nf(2)=2\n2\nf(2)+2*f(1)+3*f(0)\nf(2)=2\nf(1)=1\nf(0)=0\n4\nf(3)+2*f(2)+3*f(1)\nf(2)+2*f(1)+3*f(0)\nf(2)=2\nf(1)=1\nf(0)=0\nf(2)=2\nf(1)=1\n11\nf(4)+2*f(3)+3*f(2)\nf(3)+2*f(2)+3*f(1)\nf(2)+2*f(1)+3*f(0)\nf(2)=2\nf(1)=1\nf(0)=0\nf(2)=2\nf(1)=1\nf(2)+2*f(1)+3*f(0)\nf(2)=2\nf(1)=1\nf(0)=0\nf(2)=2\n25\n" ], [ "(display (f 5))\n(newline)", "f(4)+2*f(3)+3*f(2)\nf(3)+2*f(2)+3*f(1)\nf(2)+2*f(1)+3*f(0)\nf(2)=2\nf(1)=1\nf(0)=0\nf(2)=2\nf(1)=1\nf(2)+2*f(1)+3*f(0)\nf(2)=2\nf(1)=1\nf(0)=0\nf(2)=2\n25\n" ] ], [ [ "以下のように考えることで、反復プロセスで実装できる。\n\n$ a'_{n + 2} \\leftarrow a_{n + 2} + 2 \\cdot a_{n + 1} + 3 \\cdot a_{n} $ \n$ a'_{n + 1} \\leftarrow a_{n + 2} $ \n$ a'_{n} \\leftarrow a_{n + 1} $ \n\n$ a_{n + 3} \\leftarrow a_{n + 2} + 2 \\cdot a_{n + 1} + 3 \\cdot a_{n} $ \n\n$ A \\leftarrow A + 2 \\cdot B + 3 \\cdot C $ \n$ B \\leftarrow A $ \n$ C \\leftarrow B $ ", "_____no_output_____" ] ], [ [ "; 反復プロセスによる実装\n(define (f2 n)\n (f-iter 2 1 0 n))\n(define (f-iter a b c count)\n (if (= count 0)\n c\n (begin\n (display \"f-iter \")\n (display (+ a (* 2 b)(* 3 c)))\n (display \" \")\n (display a)\n (display \" \")\n (display b)\n (display \" \")\n (display (- count 1))\n (newline)\n (f-iter (+ a (* 2 b)(* 3 c)) a b (- count 1))\n )\n )\n )", "_____no_output_____" ], [ "(display (f2 5))\n(newline)", "f-iter 4 2 1 4\nf-iter 11 4 2 3\nf-iter 25 11 4 2\nf-iter 59 25 11 1\nf-iter 142 59 25 0\n25\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4af210331d6cd70192c4cf0074489b9c4ff0ca66
91,154
ipynb
Jupyter Notebook
Notebooks/Course 4 Conventional Neural Network/Residual_Networks.ipynb
JiningSong/Deep-Learning-Specialization-Study-Notes
12c4acd500893b636758aca805fca61f35ed6784
[ "MIT" ]
null
null
null
Notebooks/Course 4 Conventional Neural Network/Residual_Networks.ipynb
JiningSong/Deep-Learning-Specialization-Study-Notes
12c4acd500893b636758aca805fca61f35ed6784
[ "MIT" ]
null
null
null
Notebooks/Course 4 Conventional Neural Network/Residual_Networks.ipynb
JiningSong/Deep-Learning-Specialization-Study-Notes
12c4acd500893b636758aca805fca61f35ed6784
[ "MIT" ]
null
null
null
60.326936
1,553
0.617548
[ [ [ "# Residual Networks\n\nWelcome to the first assignment of this week! You'll be building a very deep convolutional network, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](https://arxiv.org/pdf/1512.03385.pdf), allow you to train much deeper networks than were previously feasible.\n\n**By the end of this assignment, you'll be able to:**\n\n- Implement the basic building blocks of ResNets in a deep neural network using Keras\n- Put together these building blocks to implement and train a state-of-the-art neural network for image classification\n- Implement a skip connection in your network\n\nFor this assignment, you'll use Keras. \n\nBefore jumping into the problem, run the cell below to load the required packages.", "_____no_output_____" ], [ "## Table of Content\n\n- [1 - Packages](#1)\n- [2 - The Problem of Very Deep Neural Networks](#2)\n- [3 - Building a Residual Network](#3)\n - [3.1 - The Identity Block](#3-1)\n - [Exercise 1 - identity_block](#ex-1)\n - [3.2 - The Convolutional Block](#3-2)\n - [Exercise 2 - convolutional_block](#ex-2)\n- [4 - Building Your First ResNet Model (50 layers)](#4)\n - [Exercise 3 - ResNet50](#ex-3)\n- [5 - Test on Your Own Image (Optional/Ungraded)](#5)\n- [6 - Bibliography](#6)", "_____no_output_____" ], [ "<a name='1'></a>\n## 1 - Packages", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nimport numpy as np\nimport scipy.misc\nfrom tensorflow.keras.applications.resnet_v2 import ResNet50V2\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet_v2 import preprocess_input, decode_predictions\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D\nfrom tensorflow.keras.models import Model, load_model\nfrom resnets_utils import *\nfrom tensorflow.keras.initializers import random_uniform, glorot_uniform, constant, identity\nfrom tensorflow.python.framework.ops import EagerTensor\nfrom matplotlib.pyplot import imshow\n\nfrom test_utils import summary, comparator\nimport public_tests\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "<a name='2'></a>\n## 2 - The Problem of Very Deep Neural Networks\n\nLast week, you built your first convolutional neural networks: first manually with numpy, then using Tensorflow and Keras. \n\nIn recent years, neural networks have become much deeper, with state-of-the-art networks evolving from having just a few layers (e.g., AlexNet) to over a hundred layers.\n\n* The main benefit of a very deep network is that it can represent very complex functions. It can also learn features at many different levels of abstraction, from edges (at the shallower layers, closer to the input) to very complex features (at the deeper layers, closer to the output). \n\n* However, using a deeper network doesn't always help. A huge barrier to training them is vanishing gradients: very deep networks often have a gradient signal that goes to zero quickly, thus making gradient descent prohibitively slow.\n\n* More specifically, during gradient descent, as you backpropagate from the final layer back to the first layer, you are multiplying by the weight matrix on each step, and thus the gradient can decrease exponentially quickly to zero (or, in rare cases, grow exponentially quickly and \"explode,\" from gaining very large values). \n\n* During training, you might therefore see the magnitude (or norm) of the gradient for the shallower layers decrease to zero very rapidly as training proceeds, as shown below: ", "_____no_output_____" ], [ "<img src=\"images/vanishing_grad_kiank.png\" style=\"width:450px;height:220px;\">\n<caption><center> <u> <font color='purple'> <b>Figure 1</b> </u><font color='purple'> : <b>Vanishing gradient</b> <br> The speed of learning decreases very rapidly for the shallower layers as the network trains </center></caption>\n\nNot to worry! You are now going to solve this problem by building a Residual Network!", "_____no_output_____" ], [ "<a name='3'></a>\n## 3 - Building a Residual Network\n\nIn ResNets, a \"shortcut\" or a \"skip connection\" allows the model to skip layers: \n\n<img src=\"images/skip_connection_kiank.png\" style=\"width:650px;height:200px;\">\n<caption><center> <u> <font color='purple'> <b>Figure 2</b> </u><font color='purple'> : A ResNet block showing a skip-connection <br> </center></caption>\n\nThe image on the left shows the \"main path\" through the network. The image on the right adds a shortcut to the main path. By stacking these ResNet blocks on top of each other, you can form a very deep network. \n\nThe lecture mentioned that having ResNet blocks with the shortcut also makes it very easy for one of the blocks to learn an identity function. This means that you can stack on additional ResNet blocks with little risk of harming training set performance. \n \nOn that note, there is also some evidence that the ease of learning an identity function accounts for ResNets' remarkable performance even more than skip connections help with vanishing gradients.\n\nTwo main types of blocks are used in a ResNet, depending mainly on whether the input/output dimensions are the same or different. You are going to implement both of them: the \"identity block\" and the \"convolutional block.\"", "_____no_output_____" ], [ "<a name='3-1'></a>\n### 3.1 - The Identity Block\n\nThe identity block is the standard block used in ResNets, and corresponds to the case where the input activation (say $a^{[l]}$) has the same dimension as the output activation (say $a^{[l+2]}$). To flesh out the different steps of what happens in a ResNet's identity block, here is an alternative diagram showing the individual steps:\n\n<img src=\"images/idblock2_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> <b>Figure 3</b> </u><font color='purple'> : <b>Identity block.</b> Skip connection \"skips over\" 2 layers. </center></caption>\n\nThe upper path is the \"shortcut path.\" The lower path is the \"main path.\" In this diagram, notice the CONV2D and ReLU steps in each layer. To speed up training, a BatchNorm step has been added. Don't worry about this being complicated to implement--you'll see that BatchNorm is just one line of code in Keras! \n\nIn this exercise, you'll actually implement a slightly more powerful version of this identity block, in which the skip connection \"skips over\" 3 hidden layers rather than 2 layers. It looks like this: \n\n<img src=\"images/idblock3_kiank.png\" style=\"width:650px;height:150px;\">\n <caption><center> <u> <font color='purple'> <b>Figure 4</b> </u><font color='purple'> : <b>Identity block.</b> Skip connection \"skips over\" 3 layers.</center></caption>", "_____no_output_____" ], [ "These are the individual steps:\n\nFirst component of main path: \n- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\". Use 0 as the seed for the random uniform initialization: `kernel_initializer = initializer(seed=0)`. \n- The first BatchNorm is normalizing the 'channels' axis.\n- Then apply the ReLU activation function. This has no hyperparameters. \n\nSecond component of main path:\n- The second CONV2D has $F_2$ filters of shape $(f,f)$ and a stride of (1,1). Its padding is \"same\". Use 0 as the seed for the random uniform initialization: `kernel_initializer = initializer(seed=0)`.\n- The second BatchNorm is normalizing the 'channels' axis.\n- Then apply the ReLU activation function. This has no hyperparameters.\n\nThird component of main path:\n- The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\". Use 0 as the seed for the random uniform initialization: `kernel_initializer = initializer(seed=0)`. \n- The third BatchNorm is normalizing the 'channels' axis.\n- Note that there is **no** ReLU activation function in this component. \n\nFinal step: \n- The `X_shortcut` and the output from the 3rd layer `X` are added together.\n- **Hint**: The syntax will look something like `Add()([var1,var2])`\n- Then apply the ReLU activation function. This has no hyperparameters. \n\n<a name='ex-1'></a>\n### Exercise 1 - identity_block\n\nImplement the ResNet identity block. The first component of the main path has been implemented for you already! First, you should read these docs carefully to make sure you understand what's happening. Then, implement the rest. \n- To implement the Conv2D step: [Conv2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D)\n- To implement BatchNorm: [BatchNormalization](https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization) `BatchNormalization(axis = 3)(X, training = training)`. If training is set to False, its weights are not updated with the new examples. I.e when the model is used in prediction mode.\n- For the activation, use: `Activation('relu')(X)`\n- To add the value passed forward by the shortcut: [Add](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Add)\n\nWe have added the initializer argument to our functions. This parameter receives an initializer function like the ones included in the package [tensorflow.keras.initializers](https://www.tensorflow.org/api_docs/python/tf/keras/initializers) or any other custom initializer. By default it will be set to [random_uniform](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/RandomUniform)\n\nRemember that these functions accept a `seed` argument that can be any value you want, but that in this notebook must set to 0 for **grading purposes**.", "_____no_output_____" ], [ " Here is where you're actually using the power of the Functional API to create a shortcut path: ", "_____no_output_____" ] ], [ [ "# UNQ_C1\n# GRADED FUNCTION: identity_block\n\ndef identity_block(X, f, filters, training=True, initializer=random_uniform):\n \"\"\"\n Implementation of the identity block as defined in Figure 4\n \n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n training -- True: Behave in training mode\n False: Behave in inference mode\n initializer -- to set up the initial weights of a layer. Equals to random uniform initializer\n \n Returns:\n X -- output of the identity block, tensor of shape (n_H, n_W, n_C)\n \"\"\"\n \n # Retrieve Filters\n F1, F2, F3 = filters\n \n # Save the input value. You'll need this later to add back to the main path. \n X_shortcut = X\n \n # First component of main path\n X = Conv2D(filters = F1, kernel_size = 1, strides = (1,1), padding = 'valid', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training = training) # Default axis\n X = Activation('relu')(X)\n \n ### START CODE HERE\n ## Second component of main path (≈3 lines)\n X = Conv2D(filters = F2, kernel_size = f, strides = (1,1), padding = 'same', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training = training) # Default axis\n X = Activation('relu')(X)\n \n\n ## Third component of main path (≈2 lines)\n X = Conv2D(filters = F3, kernel_size = 1, strides = (1,1), padding = 'valid', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training = training) # Default axis\n \n ## Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)\n X = Add()([X_shortcut, X])\n X = Activation('relu')(X)\n ### END CODE HERE\n\n return X", "_____no_output_____" ], [ "np.random.seed(1)\nX1 = np.ones((1, 4, 4, 3)) * -1\nX2 = np.ones((1, 4, 4, 3)) * 1\nX3 = np.ones((1, 4, 4, 3)) * 3\n\nX = np.concatenate((X1, X2, X3), axis = 0).astype(np.float32)\n\nA3 = identity_block(X, f=2, filters=[4, 4, 3],\n initializer=lambda seed=0:constant(value=1),\n training=False)\nprint('\\033[1mWith training=False\\033[0m\\n')\nA3np = A3.numpy()\nprint(np.around(A3.numpy()[:,(0,-1),:,:].mean(axis = 3), 5))\nresume = A3np[:,(0,-1),:,:].mean(axis = 3)\nprint(resume[1, 1, 0])\n\nprint('\\n\\033[1mWith training=True\\033[0m\\n')\nnp.random.seed(1)\nA4 = identity_block(X, f=2, filters=[3, 3, 3],\n initializer=lambda seed=0:constant(value=1),\n training=True)\nprint(np.around(A4.numpy()[:,(0,-1),:,:].mean(axis = 3), 5))\n\npublic_tests.identity_block_test(identity_block)", "\u001b[1mWith training=False\u001b[0m\n\n[[[ 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. ]]\n\n [[192.71234 192.71234 192.71234 96.85617]\n [ 96.85617 96.85617 96.85617 48.92808]]\n\n [[578.1371 578.1371 578.1371 290.5685 ]\n [290.5685 290.5685 290.5685 146.78426]]]\n96.85617\n\n\u001b[1mWith training=True\u001b[0m\n\n[[[0. 0. 0. 0. ]\n [0. 0. 0. 0. ]]\n\n [[0.40739 0.40739 0.40739 0.40739]\n [0.40739 0.40739 0.40739 0.40739]]\n\n [[4.99991 4.99991 4.99991 3.25948]\n [3.25948 3.25948 3.25948 2.40739]]]\n\u001b[32mAll tests passed!\u001b[0m\n" ] ], [ [ "**Expected value**\n\n```\nWith training=False\n\n[[[ 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. ]]\n\n [[192.71234 192.71234 192.71234 96.85617]\n [ 96.85617 96.85617 96.85617 48.92808]]\n\n [[578.1371 578.1371 578.1371 290.5685 ]\n [290.5685 290.5685 290.5685 146.78426]]]\n96.85617\n\nWith training=True\n\n[[[0. 0. 0. 0. ]\n [0. 0. 0. 0. ]]\n\n [[0.40739 0.40739 0.40739 0.40739]\n [0.40739 0.40739 0.40739 0.40739]]\n\n [[4.99991 4.99991 4.99991 3.25948]\n [3.25948 3.25948 3.25948 2.40739]]]\n```", "_____no_output_____" ], [ "<a name='3-2'></a>\n### 3.2 - The Convolutional Block\n\nThe ResNet \"convolutional block\" is the second block type. You can use this type of block when the input and output dimensions don't match up. The difference with the identity block is that there is a CONV2D layer in the shortcut path: \n\n<img src=\"images/convblock_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> <b>Figure 4</b> </u><font color='purple'> : <b>Convolutional block</b> </center></caption>\n\n* The CONV2D layer in the shortcut path is used to resize the input $x$ to a different dimension, so that the dimensions match up in the final addition needed to add the shortcut value back to the main path. (This plays a similar role as the matrix $W_s$ discussed in lecture.) \n* For example, to reduce the activation dimensions's height and width by a factor of 2, you can use a 1x1 convolution with a stride of 2. \n* The CONV2D layer on the shortcut path does not use any non-linear activation function. Its main role is to just apply a (learned) linear function that reduces the dimension of the input, so that the dimensions match up for the later addition step. \n* As for the previous exercise, the additional `initializer` argument is required for grading purposes, and it has been set by default to [glorot_uniform](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/GlorotUniform)\n\nThe details of the convolutional block are as follows. \n\nFirst component of main path:\n- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n- The first BatchNorm is normalizing the 'channels' axis.\n- Then apply the ReLU activation function. This has no hyperparameters. \n\nSecond component of main path:\n- The second CONV2D has $F_2$ filters of shape (f,f) and a stride of (1,1). Its padding is \"same\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n- The second BatchNorm is normalizing the 'channels' axis.\n- Then apply the ReLU activation function. This has no hyperparameters. \n\nThird component of main path:\n- The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n- The third BatchNorm is normalizing the 'channels' axis. Note that there is no ReLU activation function in this component. \n\nShortcut path:\n- The CONV2D has $F_3$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\". Use 0 as the `glorot_uniform` seed `kernel_initializer = initializer(seed=0)`.\n- The BatchNorm is normalizing the 'channels' axis. \n\nFinal step: \n- The shortcut and the main path values are added together.\n- Then apply the ReLU activation function. This has no hyperparameters. \n \n<a name='ex-2'></a> \n### Exercise 2 - convolutional_block\n \nImplement the convolutional block. The first component of the main path is already implemented; then it's your turn to implement the rest! As before, always use 0 as the seed for the random initialization, to ensure consistency with the grader.\n- [Conv2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D)\n- [BatchNormalization](https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization) (axis: Integer, the axis that should be normalized (typically the features axis)) `BatchNormalization(axis = 3)(X, training = training)`. If training is set to False, its weights are not updated with the new examples. I.e when the model is used in prediction mode.\n- For the activation, use: `Activation('relu')(X)`\n- [Add](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Add)\n \nWe have added the initializer argument to our functions. This parameter receives an initializer function like the ones included in the package [tensorflow.keras.initializers](https://www.tensorflow.org/api_docs/python/tf/keras/initializers) or any other custom initializer. By default it will be set to [random_uniform](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/RandomUniform)\n\nRemember that these functions accept a `seed` argument that can be any value you want, but that in this notebook must set to 0 for **grading purposes**.", "_____no_output_____" ] ], [ [ "# UNQ_C2\n# GRADED FUNCTION: convolutional_block\n\ndef convolutional_block(X, f, filters, s = 2, training=True, initializer=glorot_uniform):\n \"\"\"\n Implementation of the convolutional block as defined in Figure 4\n \n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n s -- Integer, specifying the stride to be used\n training -- True: Behave in training mode\n False: Behave in inference mode\n initializer -- to set up the initial weights of a layer. Equals to Glorot uniform initializer, \n also called Xavier uniform initializer.\n \n Returns:\n X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)\n \"\"\"\n \n # Retrieve Filters\n F1, F2, F3 = filters\n \n # Save the input value\n X_shortcut = X\n\n\n ##### MAIN PATH #####\n \n # First component of main path glorot_uniform(seed=0)\n X = Conv2D(filters = F1, kernel_size = 1, strides = (s, s), padding='valid', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training=training)\n X = Activation('relu')(X)\n\n ### START CODE HERE\n \n ## Second component of main path (≈3 lines)\n X = Conv2D(filters = F2, kernel_size = f, strides = (1, 1), padding='same', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training=training)\n X = Activation('relu')(X)\n\n ## Third component of main path (≈2 lines)\n X = Conv2D(filters = F3, kernel_size = 1, strides = (1, 1), padding='valid', kernel_initializer = initializer(seed=0))(X)\n X = BatchNormalization(axis = 3)(X, training=training)\n \n ##### SHORTCUT PATH ##### (≈2 lines)\n X_shortcut = Conv2D(filters = F3, kernel_size = 1, strides = (s, s), padding='valid', kernel_initializer = initializer(seed=0))(X_shortcut)\n X_shortcut = BatchNormalization(axis = 3)(X_shortcut, training=training)\n \n ### END CODE HERE\n\n # Final step: Add shortcut value to main path (Use this order [X, X_shortcut]), and pass it through a RELU activation\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n \n return X", "_____no_output_____" ], [ "from outputs import convolutional_block_output1, convolutional_block_output2\nnp.random.seed(1)\n#X = np.random.randn(3, 4, 4, 6).astype(np.float32)\nX1 = np.ones((1, 4, 4, 3)) * -1\nX2 = np.ones((1, 4, 4, 3)) * 1\nX3 = np.ones((1, 4, 4, 3)) * 3\n\nX = np.concatenate((X1, X2, X3), axis = 0).astype(np.float32)\n\nA = convolutional_block(X, f = 2, filters = [2, 4, 6], training=False)\n\nassert type(A) == EagerTensor, \"Use only tensorflow and keras functions\"\nassert tuple(tf.shape(A).numpy()) == (3, 2, 2, 6), \"Wrong shape.\"\nassert np.allclose(A.numpy(), convolutional_block_output1), \"Wrong values when training=False.\"\nprint(A[0])\n\nB = convolutional_block(X, f = 2, filters = [2, 4, 6], training=True)\nassert np.allclose(B.numpy(), convolutional_block_output2), \"Wrong values when training=True.\"\n\nprint('\\033[92mAll tests passed!')\n", "tf.Tensor(\n[[[0. 0.66683817 0. 0. 0.88853896 0.5274254 ]\n [0. 0.65053666 0. 0. 0.89592844 0.49965227]]\n\n [[0. 0.6312079 0. 0. 0.8636247 0.47643146]\n [0. 0.5688321 0. 0. 0.85534114 0.41709304]]], shape=(2, 2, 6), dtype=float32)\n\u001b[92mAll tests passed!\n" ] ], [ [ "**Expected value**\n\n```\ntf.Tensor(\n[[[0. 0.66683817 0. 0. 0.88853896 0.5274254 ]\n [0. 0.65053666 0. 0. 0.89592844 0.49965227]]\n\n [[0. 0.6312079 0. 0. 0.8636247 0.47643146]\n [0. 0.5688321 0. 0. 0.85534114 0.41709304]]], shape=(2, 2, 6), dtype=float32)\n```", "_____no_output_____" ], [ "<a name='4'></a> \n## 4 - Building Your First ResNet Model (50 layers)\n\nYou now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the architecture of this neural network. \"ID BLOCK\" in the diagram stands for \"Identity block,\" and \"ID BLOCK x3\" means you should stack 3 identity blocks together.\n\n<img src=\"images/resnet_kiank.png\" style=\"width:850px;height:150px;\">\n<caption><center> <u> <font color='purple'> <b>Figure 5</b> </u><font color='purple'> : <b>ResNet-50 model</b> </center></caption>\n\nThe details of this ResNet-50 model are:\n- Zero-padding pads the input with a pad of (3,3)\n- Stage 1:\n - The 2D Convolution has 64 filters of shape (7,7) and uses a stride of (2,2). \n - BatchNorm is applied to the 'channels' axis of the input.\n - ReLU activation is applied.\n - MaxPooling uses a (3,3) window and a (2,2) stride.\n- Stage 2:\n - The convolutional block uses three sets of filters of size [64,64,256], \"f\" is 3, and \"s\" is 1.\n - The 2 identity blocks use three sets of filters of size [64,64,256], and \"f\" is 3.\n- Stage 3:\n - The convolutional block uses three sets of filters of size [128,128,512], \"f\" is 3 and \"s\" is 2.\n - The 3 identity blocks use three sets of filters of size [128,128,512] and \"f\" is 3.\n- Stage 4:\n - The convolutional block uses three sets of filters of size [256, 256, 1024], \"f\" is 3 and \"s\" is 2.\n - The 5 identity blocks use three sets of filters of size [256, 256, 1024] and \"f\" is 3.\n- Stage 5:\n - The convolutional block uses three sets of filters of size [512, 512, 2048], \"f\" is 3 and \"s\" is 2.\n - The 2 identity blocks use three sets of filters of size [512, 512, 2048] and \"f\" is 3.\n- The 2D Average Pooling uses a window of shape (2,2).\n- The 'flatten' layer doesn't have any hyperparameters.\n- The Fully Connected (Dense) layer reduces its input to the number of classes using a softmax activation.\n\n \n<a name='ex-3'></a> \n### Exercise 3 - ResNet50 \n \nImplement the ResNet with 50 layers described in the figure above. We have implemented Stages 1 and 2. Please implement the rest. (The syntax for implementing Stages 3-5 should be quite similar to that of Stage 2) Make sure you follow the naming convention in the text above. \n\nYou'll need to use this function: \n- Average pooling [see reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/AveragePooling2D)\n\nHere are some other functions we used in the code below:\n- Conv2D: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D)\n- BatchNorm: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization) (axis: Integer, the axis that should be normalized (typically the features axis))\n- Zero padding: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/ZeroPadding2D)\n- Max pooling: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D)\n- Fully connected layer: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense)\n- Addition: [See reference](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Add)", "_____no_output_____" ] ], [ [ "# UNQ_C3\n# GRADED FUNCTION: ResNet50\n\ndef ResNet50(input_shape = (64, 64, 3), classes = 6):\n \"\"\"\n Stage-wise implementation of the architecture of the popular ResNet50:\n CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3\n -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> FLATTEN -> DENSE \n\n Arguments:\n input_shape -- shape of the images of the dataset\n classes -- integer, number of classes\n\n Returns:\n model -- a Model() instance in Keras\n \"\"\"\n \n # Define the input as a tensor with shape input_shape\n X_input = Input(input_shape)\n\n \n # Zero-Padding\n X = ZeroPadding2D((3, 3))(X_input)\n \n # Stage 1\n X = Conv2D(64, (7, 7), strides = (2, 2), kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis = 3)(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((3, 3), strides=(2, 2))(X)\n\n # Stage 2\n X = convolutional_block(X, f = 3, filters = [64, 64, 256], s = 1)\n X = identity_block(X, 3, [64, 64, 256])\n X = identity_block(X, 3, [64, 64, 256])\n\n ### START CODE HERE\n \n ## Stage 3 (≈4 lines)\n X = convolutional_block(X, f = 3, filters = [128, 128, 512], s = 2)\n X = identity_block(X, 3, [128,128,512])\n X = identity_block(X, 3, [128,128,512])\n X = identity_block(X, 3, [128,128,512])\n \n ## Stage 4 (≈6 lines)\n X = convolutional_block(X, f = 3, filters = [256, 256, 1024], s = 2)\n X = identity_block(X, 3, [256, 256, 1024])\n X = identity_block(X, 3, [256, 256, 1024])\n X = identity_block(X, 3, [256, 256, 1024])\n X = identity_block(X, 3, [256, 256, 1024])\n X = identity_block(X, 3, [256, 256, 1024])\n\n\n ## Stage 5 (≈3 lines)\n X = convolutional_block(X, f = 3, filters = [512, 512, 2048], s = 2)\n X = identity_block(X, 3, [512, 512, 2048])\n X = identity_block(X, 3, [512, 512, 2048])\n\n ## AVGPOOL (≈1 line). Use \"X = AveragePooling2D(...)(X)\"\n X = AveragePooling2D((2,2))(X)\n \n ### END CODE HERE\n\n # output layer\n X = Flatten()(X)\n X = Dense(classes, activation='softmax', kernel_initializer = glorot_uniform(seed=0))(X)\n \n \n # Create model\n model = Model(inputs = X_input, outputs = X)\n\n return model", "_____no_output_____" ] ], [ [ "Run the following code to build the model's graph. If your implementation is incorrect, you'll know it by checking your accuracy when running `model.fit(...)` below.", "_____no_output_____" ] ], [ [ "model = ResNet50(input_shape = (64, 64, 3), classes = 6)\nprint(model.summary())", "Model: \"functional_1\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) [(None, 64, 64, 3)] 0 \n__________________________________________________________________________________________________\nzero_padding2d (ZeroPadding2D) (None, 70, 70, 3) 0 input_1[0][0] \n__________________________________________________________________________________________________\nconv2d_92 (Conv2D) (None, 32, 32, 64) 9472 zero_padding2d[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_92 (BatchNo (None, 32, 32, 64) 256 conv2d_92[0][0] \n__________________________________________________________________________________________________\nactivation_83 (Activation) (None, 32, 32, 64) 0 batch_normalization_92[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 15, 15, 64) 0 activation_83[0][0] \n__________________________________________________________________________________________________\nconv2d_93 (Conv2D) (None, 15, 15, 64) 4160 max_pooling2d[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_93 (BatchNo (None, 15, 15, 64) 256 conv2d_93[0][0] \n__________________________________________________________________________________________________\nactivation_84 (Activation) (None, 15, 15, 64) 0 batch_normalization_93[0][0] \n__________________________________________________________________________________________________\nconv2d_94 (Conv2D) (None, 15, 15, 64) 36928 activation_84[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_94 (BatchNo (None, 15, 15, 64) 256 conv2d_94[0][0] \n__________________________________________________________________________________________________\nactivation_85 (Activation) (None, 15, 15, 64) 0 batch_normalization_94[0][0] \n__________________________________________________________________________________________________\nconv2d_95 (Conv2D) (None, 15, 15, 256) 16640 activation_85[0][0] \n__________________________________________________________________________________________________\nconv2d_96 (Conv2D) (None, 15, 15, 256) 16640 max_pooling2d[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_95 (BatchNo (None, 15, 15, 256) 1024 conv2d_95[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_96 (BatchNo (None, 15, 15, 256) 1024 conv2d_96[0][0] \n__________________________________________________________________________________________________\nadd_27 (Add) (None, 15, 15, 256) 0 batch_normalization_95[0][0] \n batch_normalization_96[0][0] \n__________________________________________________________________________________________________\nactivation_86 (Activation) (None, 15, 15, 256) 0 add_27[0][0] \n__________________________________________________________________________________________________\nconv2d_97 (Conv2D) (None, 15, 15, 64) 16448 activation_86[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_97 (BatchNo (None, 15, 15, 64) 256 conv2d_97[0][0] \n__________________________________________________________________________________________________\nactivation_87 (Activation) (None, 15, 15, 64) 0 batch_normalization_97[0][0] \n__________________________________________________________________________________________________\nconv2d_98 (Conv2D) (None, 15, 15, 64) 36928 activation_87[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_98 (BatchNo (None, 15, 15, 64) 256 conv2d_98[0][0] \n__________________________________________________________________________________________________\nactivation_88 (Activation) (None, 15, 15, 64) 0 batch_normalization_98[0][0] \n__________________________________________________________________________________________________\nconv2d_99 (Conv2D) (None, 15, 15, 256) 16640 activation_88[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_99 (BatchNo (None, 15, 15, 256) 1024 conv2d_99[0][0] \n__________________________________________________________________________________________________\nadd_28 (Add) (None, 15, 15, 256) 0 activation_86[0][0] \n batch_normalization_99[0][0] \n__________________________________________________________________________________________________\nactivation_89 (Activation) (None, 15, 15, 256) 0 add_28[0][0] \n__________________________________________________________________________________________________\nconv2d_100 (Conv2D) (None, 15, 15, 64) 16448 activation_89[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_100 (BatchN (None, 15, 15, 64) 256 conv2d_100[0][0] \n__________________________________________________________________________________________________\nactivation_90 (Activation) (None, 15, 15, 64) 0 batch_normalization_100[0][0] \n__________________________________________________________________________________________________\nconv2d_101 (Conv2D) (None, 15, 15, 64) 36928 activation_90[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_101 (BatchN (None, 15, 15, 64) 256 conv2d_101[0][0] \n__________________________________________________________________________________________________\nactivation_91 (Activation) (None, 15, 15, 64) 0 batch_normalization_101[0][0] \n__________________________________________________________________________________________________\nconv2d_102 (Conv2D) (None, 15, 15, 256) 16640 activation_91[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_102 (BatchN (None, 15, 15, 256) 1024 conv2d_102[0][0] \n__________________________________________________________________________________________________\nadd_29 (Add) (None, 15, 15, 256) 0 activation_89[0][0] \n batch_normalization_102[0][0] \n__________________________________________________________________________________________________\nactivation_92 (Activation) (None, 15, 15, 256) 0 add_29[0][0] \n__________________________________________________________________________________________________\nconv2d_103 (Conv2D) (None, 8, 8, 128) 32896 activation_92[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_103 (BatchN (None, 8, 8, 128) 512 conv2d_103[0][0] \n__________________________________________________________________________________________________\nactivation_93 (Activation) (None, 8, 8, 128) 0 batch_normalization_103[0][0] \n__________________________________________________________________________________________________\nconv2d_104 (Conv2D) (None, 8, 8, 128) 147584 activation_93[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_104 (BatchN (None, 8, 8, 128) 512 conv2d_104[0][0] \n__________________________________________________________________________________________________\nactivation_94 (Activation) (None, 8, 8, 128) 0 batch_normalization_104[0][0] \n__________________________________________________________________________________________________\nconv2d_105 (Conv2D) (None, 8, 8, 512) 66048 activation_94[0][0] \n__________________________________________________________________________________________________\nconv2d_106 (Conv2D) (None, 8, 8, 512) 131584 activation_92[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_105 (BatchN (None, 8, 8, 512) 2048 conv2d_105[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_106 (BatchN (None, 8, 8, 512) 2048 conv2d_106[0][0] \n__________________________________________________________________________________________________\nadd_30 (Add) (None, 8, 8, 512) 0 batch_normalization_105[0][0] \n batch_normalization_106[0][0] \n__________________________________________________________________________________________________\nactivation_95 (Activation) (None, 8, 8, 512) 0 add_30[0][0] \n__________________________________________________________________________________________________\nconv2d_107 (Conv2D) (None, 8, 8, 128) 65664 activation_95[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_107 (BatchN (None, 8, 8, 128) 512 conv2d_107[0][0] \n__________________________________________________________________________________________________\nactivation_96 (Activation) (None, 8, 8, 128) 0 batch_normalization_107[0][0] \n__________________________________________________________________________________________________\nconv2d_108 (Conv2D) (None, 8, 8, 128) 147584 activation_96[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_108 (BatchN (None, 8, 8, 128) 512 conv2d_108[0][0] \n__________________________________________________________________________________________________\nactivation_97 (Activation) (None, 8, 8, 128) 0 batch_normalization_108[0][0] \n__________________________________________________________________________________________________\nconv2d_109 (Conv2D) (None, 8, 8, 512) 66048 activation_97[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_109 (BatchN (None, 8, 8, 512) 2048 conv2d_109[0][0] \n__________________________________________________________________________________________________\nadd_31 (Add) (None, 8, 8, 512) 0 activation_95[0][0] \n batch_normalization_109[0][0] \n__________________________________________________________________________________________________\nactivation_98 (Activation) (None, 8, 8, 512) 0 add_31[0][0] \n__________________________________________________________________________________________________\nconv2d_110 (Conv2D) (None, 8, 8, 128) 65664 activation_98[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_110 (BatchN (None, 8, 8, 128) 512 conv2d_110[0][0] \n__________________________________________________________________________________________________\nactivation_99 (Activation) (None, 8, 8, 128) 0 batch_normalization_110[0][0] \n__________________________________________________________________________________________________\nconv2d_111 (Conv2D) (None, 8, 8, 128) 147584 activation_99[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_111 (BatchN (None, 8, 8, 128) 512 conv2d_111[0][0] \n__________________________________________________________________________________________________\nactivation_100 (Activation) (None, 8, 8, 128) 0 batch_normalization_111[0][0] \n__________________________________________________________________________________________________\nconv2d_112 (Conv2D) (None, 8, 8, 512) 66048 activation_100[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_112 (BatchN (None, 8, 8, 512) 2048 conv2d_112[0][0] \n__________________________________________________________________________________________________\nadd_32 (Add) (None, 8, 8, 512) 0 activation_98[0][0] \n batch_normalization_112[0][0] \n__________________________________________________________________________________________________\nactivation_101 (Activation) (None, 8, 8, 512) 0 add_32[0][0] \n__________________________________________________________________________________________________\nconv2d_113 (Conv2D) (None, 8, 8, 128) 65664 activation_101[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_113 (BatchN (None, 8, 8, 128) 512 conv2d_113[0][0] \n__________________________________________________________________________________________________\nactivation_102 (Activation) (None, 8, 8, 128) 0 batch_normalization_113[0][0] \n__________________________________________________________________________________________________\nconv2d_114 (Conv2D) (None, 8, 8, 128) 147584 activation_102[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_114 (BatchN (None, 8, 8, 128) 512 conv2d_114[0][0] \n__________________________________________________________________________________________________\nactivation_103 (Activation) (None, 8, 8, 128) 0 batch_normalization_114[0][0] \n__________________________________________________________________________________________________\nconv2d_115 (Conv2D) (None, 8, 8, 512) 66048 activation_103[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_115 (BatchN (None, 8, 8, 512) 2048 conv2d_115[0][0] \n__________________________________________________________________________________________________\nadd_33 (Add) (None, 8, 8, 512) 0 activation_101[0][0] \n batch_normalization_115[0][0] \n__________________________________________________________________________________________________\nactivation_104 (Activation) (None, 8, 8, 512) 0 add_33[0][0] \n__________________________________________________________________________________________________\nconv2d_116 (Conv2D) (None, 4, 4, 256) 131328 activation_104[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_116 (BatchN (None, 4, 4, 256) 1024 conv2d_116[0][0] \n__________________________________________________________________________________________________\nactivation_105 (Activation) (None, 4, 4, 256) 0 batch_normalization_116[0][0] \n__________________________________________________________________________________________________\nconv2d_117 (Conv2D) (None, 4, 4, 256) 590080 activation_105[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_117 (BatchN (None, 4, 4, 256) 1024 conv2d_117[0][0] \n__________________________________________________________________________________________________\nactivation_106 (Activation) (None, 4, 4, 256) 0 batch_normalization_117[0][0] \n__________________________________________________________________________________________________\nconv2d_118 (Conv2D) (None, 4, 4, 1024) 263168 activation_106[0][0] \n__________________________________________________________________________________________________\nconv2d_119 (Conv2D) (None, 4, 4, 1024) 525312 activation_104[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_118 (BatchN (None, 4, 4, 1024) 4096 conv2d_118[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_119 (BatchN (None, 4, 4, 1024) 4096 conv2d_119[0][0] \n__________________________________________________________________________________________________\nadd_34 (Add) (None, 4, 4, 1024) 0 batch_normalization_118[0][0] \n batch_normalization_119[0][0] \n__________________________________________________________________________________________________\nactivation_107 (Activation) (None, 4, 4, 1024) 0 add_34[0][0] \n__________________________________________________________________________________________________\nconv2d_120 (Conv2D) (None, 4, 4, 256) 262400 activation_107[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_120 (BatchN (None, 4, 4, 256) 1024 conv2d_120[0][0] \n__________________________________________________________________________________________________\nactivation_108 (Activation) (None, 4, 4, 256) 0 batch_normalization_120[0][0] \n__________________________________________________________________________________________________\nconv2d_121 (Conv2D) (None, 4, 4, 256) 590080 activation_108[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_121 (BatchN (None, 4, 4, 256) 1024 conv2d_121[0][0] \n__________________________________________________________________________________________________\nactivation_109 (Activation) (None, 4, 4, 256) 0 batch_normalization_121[0][0] \n__________________________________________________________________________________________________\nconv2d_122 (Conv2D) (None, 4, 4, 1024) 263168 activation_109[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_122 (BatchN (None, 4, 4, 1024) 4096 conv2d_122[0][0] \n__________________________________________________________________________________________________\nadd_35 (Add) (None, 4, 4, 1024) 0 activation_107[0][0] \n batch_normalization_122[0][0] \n__________________________________________________________________________________________________\nactivation_110 (Activation) (None, 4, 4, 1024) 0 add_35[0][0] \n__________________________________________________________________________________________________\nconv2d_123 (Conv2D) (None, 4, 4, 256) 262400 activation_110[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_123 (BatchN (None, 4, 4, 256) 1024 conv2d_123[0][0] \n__________________________________________________________________________________________________\nactivation_111 (Activation) (None, 4, 4, 256) 0 batch_normalization_123[0][0] \n__________________________________________________________________________________________________\nconv2d_124 (Conv2D) (None, 4, 4, 256) 590080 activation_111[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_124 (BatchN (None, 4, 4, 256) 1024 conv2d_124[0][0] \n__________________________________________________________________________________________________\nactivation_112 (Activation) (None, 4, 4, 256) 0 batch_normalization_124[0][0] \n__________________________________________________________________________________________________\nconv2d_125 (Conv2D) (None, 4, 4, 1024) 263168 activation_112[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_125 (BatchN (None, 4, 4, 1024) 4096 conv2d_125[0][0] \n__________________________________________________________________________________________________\nadd_36 (Add) (None, 4, 4, 1024) 0 activation_110[0][0] \n batch_normalization_125[0][0] \n__________________________________________________________________________________________________\nactivation_113 (Activation) (None, 4, 4, 1024) 0 add_36[0][0] \n__________________________________________________________________________________________________\nconv2d_126 (Conv2D) (None, 4, 4, 256) 262400 activation_113[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_126 (BatchN (None, 4, 4, 256) 1024 conv2d_126[0][0] \n__________________________________________________________________________________________________\nactivation_114 (Activation) (None, 4, 4, 256) 0 batch_normalization_126[0][0] \n__________________________________________________________________________________________________\nconv2d_127 (Conv2D) (None, 4, 4, 256) 590080 activation_114[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_127 (BatchN (None, 4, 4, 256) 1024 conv2d_127[0][0] \n__________________________________________________________________________________________________\nactivation_115 (Activation) (None, 4, 4, 256) 0 batch_normalization_127[0][0] \n__________________________________________________________________________________________________\nconv2d_128 (Conv2D) (None, 4, 4, 1024) 263168 activation_115[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_128 (BatchN (None, 4, 4, 1024) 4096 conv2d_128[0][0] \n__________________________________________________________________________________________________\nadd_37 (Add) (None, 4, 4, 1024) 0 activation_113[0][0] \n batch_normalization_128[0][0] \n__________________________________________________________________________________________________\nactivation_116 (Activation) (None, 4, 4, 1024) 0 add_37[0][0] \n__________________________________________________________________________________________________\nconv2d_129 (Conv2D) (None, 4, 4, 256) 262400 activation_116[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_129 (BatchN (None, 4, 4, 256) 1024 conv2d_129[0][0] \n__________________________________________________________________________________________________\nactivation_117 (Activation) (None, 4, 4, 256) 0 batch_normalization_129[0][0] \n__________________________________________________________________________________________________\nconv2d_130 (Conv2D) (None, 4, 4, 256) 590080 activation_117[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_130 (BatchN (None, 4, 4, 256) 1024 conv2d_130[0][0] \n__________________________________________________________________________________________________\nactivation_118 (Activation) (None, 4, 4, 256) 0 batch_normalization_130[0][0] \n__________________________________________________________________________________________________\nconv2d_131 (Conv2D) (None, 4, 4, 1024) 263168 activation_118[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_131 (BatchN (None, 4, 4, 1024) 4096 conv2d_131[0][0] \n__________________________________________________________________________________________________\nadd_38 (Add) (None, 4, 4, 1024) 0 activation_116[0][0] \n batch_normalization_131[0][0] \n__________________________________________________________________________________________________\nactivation_119 (Activation) (None, 4, 4, 1024) 0 add_38[0][0] \n__________________________________________________________________________________________________\nconv2d_132 (Conv2D) (None, 4, 4, 256) 262400 activation_119[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_132 (BatchN (None, 4, 4, 256) 1024 conv2d_132[0][0] \n__________________________________________________________________________________________________\nactivation_120 (Activation) (None, 4, 4, 256) 0 batch_normalization_132[0][0] \n__________________________________________________________________________________________________\nconv2d_133 (Conv2D) (None, 4, 4, 256) 590080 activation_120[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_133 (BatchN (None, 4, 4, 256) 1024 conv2d_133[0][0] \n__________________________________________________________________________________________________\nactivation_121 (Activation) (None, 4, 4, 256) 0 batch_normalization_133[0][0] \n__________________________________________________________________________________________________\nconv2d_134 (Conv2D) (None, 4, 4, 1024) 263168 activation_121[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_134 (BatchN (None, 4, 4, 1024) 4096 conv2d_134[0][0] \n__________________________________________________________________________________________________\nadd_39 (Add) (None, 4, 4, 1024) 0 activation_119[0][0] \n batch_normalization_134[0][0] \n__________________________________________________________________________________________________\nactivation_122 (Activation) (None, 4, 4, 1024) 0 add_39[0][0] \n__________________________________________________________________________________________________\nconv2d_135 (Conv2D) (None, 2, 2, 512) 524800 activation_122[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_135 (BatchN (None, 2, 2, 512) 2048 conv2d_135[0][0] \n__________________________________________________________________________________________________\nactivation_123 (Activation) (None, 2, 2, 512) 0 batch_normalization_135[0][0] \n__________________________________________________________________________________________________\nconv2d_136 (Conv2D) (None, 2, 2, 512) 2359808 activation_123[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_136 (BatchN (None, 2, 2, 512) 2048 conv2d_136[0][0] \n__________________________________________________________________________________________________\nactivation_124 (Activation) (None, 2, 2, 512) 0 batch_normalization_136[0][0] \n__________________________________________________________________________________________________\nconv2d_137 (Conv2D) (None, 2, 2, 2048) 1050624 activation_124[0][0] \n__________________________________________________________________________________________________\nconv2d_138 (Conv2D) (None, 2, 2, 2048) 2099200 activation_122[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_137 (BatchN (None, 2, 2, 2048) 8192 conv2d_137[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_138 (BatchN (None, 2, 2, 2048) 8192 conv2d_138[0][0] \n__________________________________________________________________________________________________\nadd_40 (Add) (None, 2, 2, 2048) 0 batch_normalization_137[0][0] \n batch_normalization_138[0][0] \n__________________________________________________________________________________________________\nactivation_125 (Activation) (None, 2, 2, 2048) 0 add_40[0][0] \n__________________________________________________________________________________________________\nconv2d_139 (Conv2D) (None, 2, 2, 512) 1049088 activation_125[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_139 (BatchN (None, 2, 2, 512) 2048 conv2d_139[0][0] \n__________________________________________________________________________________________________\nactivation_126 (Activation) (None, 2, 2, 512) 0 batch_normalization_139[0][0] \n__________________________________________________________________________________________________\nconv2d_140 (Conv2D) (None, 2, 2, 512) 2359808 activation_126[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_140 (BatchN (None, 2, 2, 512) 2048 conv2d_140[0][0] \n__________________________________________________________________________________________________\nactivation_127 (Activation) (None, 2, 2, 512) 0 batch_normalization_140[0][0] \n__________________________________________________________________________________________________\nconv2d_141 (Conv2D) (None, 2, 2, 2048) 1050624 activation_127[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_141 (BatchN (None, 2, 2, 2048) 8192 conv2d_141[0][0] \n__________________________________________________________________________________________________\nadd_41 (Add) (None, 2, 2, 2048) 0 activation_125[0][0] \n batch_normalization_141[0][0] \n__________________________________________________________________________________________________\nactivation_128 (Activation) (None, 2, 2, 2048) 0 add_41[0][0] \n__________________________________________________________________________________________________\nconv2d_142 (Conv2D) (None, 2, 2, 512) 1049088 activation_128[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_142 (BatchN (None, 2, 2, 512) 2048 conv2d_142[0][0] \n__________________________________________________________________________________________________\nactivation_129 (Activation) (None, 2, 2, 512) 0 batch_normalization_142[0][0] \n__________________________________________________________________________________________________\nconv2d_143 (Conv2D) (None, 2, 2, 512) 2359808 activation_129[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_143 (BatchN (None, 2, 2, 512) 2048 conv2d_143[0][0] \n__________________________________________________________________________________________________\nactivation_130 (Activation) (None, 2, 2, 512) 0 batch_normalization_143[0][0] \n__________________________________________________________________________________________________\nconv2d_144 (Conv2D) (None, 2, 2, 2048) 1050624 activation_130[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_144 (BatchN (None, 2, 2, 2048) 8192 conv2d_144[0][0] \n__________________________________________________________________________________________________\nadd_42 (Add) (None, 2, 2, 2048) 0 activation_128[0][0] \n batch_normalization_144[0][0] \n__________________________________________________________________________________________________\nactivation_131 (Activation) (None, 2, 2, 2048) 0 add_42[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d (AveragePooli (None, 1, 1, 2048) 0 activation_131[0][0] \n__________________________________________________________________________________________________\nflatten (Flatten) (None, 2048) 0 average_pooling2d[0][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 6) 12294 flatten[0][0] \n==================================================================================================\nTotal params: 23,600,006\nTrainable params: 23,546,886\nNon-trainable params: 53,120\n__________________________________________________________________________________________________\nNone\n" ], [ "from outputs import ResNet50_summary\n\nmodel = ResNet50(input_shape = (64, 64, 3), classes = 6)\n\ncomparator(summary(model), ResNet50_summary)\n", "\u001b[32mAll tests passed!\u001b[0m\n" ] ], [ [ "As shown in the Keras Tutorial Notebook, prior to training a model, you need to configure the learning process by compiling the model.", "_____no_output_____" ] ], [ [ "model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])", "_____no_output_____" ] ], [ [ "The model is now ready to be trained. The only thing you need now is a dataset!", "_____no_output_____" ], [ "Let's load your old friend, the SIGNS dataset.\n\n<img src=\"images/signs_data_kiank.png\" style=\"width:450px;height:250px;\">\n<caption><center> <u> <font color='purple'> <b>Figure 6</b> </u><font color='purple'> : <b>SIGNS dataset</b> </center></caption>\n", "_____no_output_____" ] ], [ [ "X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\n\n# Normalize image vectors\nX_train = X_train_orig / 255.\nX_test = X_test_orig / 255.\n\n# Convert training and test labels to one hot matrices\nY_train = convert_to_one_hot(Y_train_orig, 6).T\nY_test = convert_to_one_hot(Y_test_orig, 6).T\n\nprint (\"number of training examples = \" + str(X_train.shape[0]))\nprint (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape))\nprint (\"Y_train shape: \" + str(Y_train.shape))\nprint (\"X_test shape: \" + str(X_test.shape))\nprint (\"Y_test shape: \" + str(Y_test.shape))", "number of training examples = 1080\nnumber of test examples = 120\nX_train shape: (1080, 64, 64, 3)\nY_train shape: (1080, 6)\nX_test shape: (120, 64, 64, 3)\nY_test shape: (120, 6)\n" ] ], [ [ "Run the following cell to train your model on 10 epochs with a batch size of 32. On a GPU, it should take less than 2 minutes. ", "_____no_output_____" ] ], [ [ "model.fit(X_train, Y_train, epochs = 10, batch_size = 32)", "Epoch 1/10\n34/34 [==============================] - 1s 28ms/step - loss: 2.5615 - accuracy: 0.3898\nEpoch 2/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.9022 - accuracy: 0.7417\nEpoch 3/10\n34/34 [==============================] - 1s 23ms/step - loss: 1.1018 - accuracy: 0.7685\nEpoch 4/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.9599 - accuracy: 0.7907\nEpoch 5/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.5874 - accuracy: 0.8519\nEpoch 6/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.2928 - accuracy: 0.9157\nEpoch 7/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.6573 - accuracy: 0.8426\nEpoch 8/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.4026 - accuracy: 0.8759\nEpoch 9/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.2198 - accuracy: 0.9343\nEpoch 10/10\n34/34 [==============================] - 1s 23ms/step - loss: 0.1045 - accuracy: 0.9620\n" ] ], [ [ "**Expected Output**:\n\n```\nEpoch 1/10\n34/34 [==============================] - 1s 34ms/step - loss: 1.9241 - accuracy: 0.4620\nEpoch 2/10\n34/34 [==============================] - 2s 57ms/step - loss: 0.6403 - accuracy: 0.7898\nEpoch 3/10\n34/34 [==============================] - 1s 24ms/step - loss: 0.3744 - accuracy: 0.8731\nEpoch 4/10\n34/34 [==============================] - 2s 44ms/step - loss: 0.2220 - accuracy: 0.9231\nEpoch 5/10\n34/34 [==============================] - 2s 57ms/step - loss: 0.1333 - accuracy: 0.9583\nEpoch 6/10\n34/34 [==============================] - 2s 52ms/step - loss: 0.2243 - accuracy: 0.9444\nEpoch 7/10\n34/34 [==============================] - 2s 48ms/step - loss: 0.2913 - accuracy: 0.9102\nEpoch 8/10\n34/34 [==============================] - 1s 30ms/step - loss: 0.2269 - accuracy: 0.9306\nEpoch 9/10\n34/34 [==============================] - 2s 46ms/step - loss: 0.1113 - accuracy: 0.9630\nEpoch 10/10\n34/34 [==============================] - 2s 57ms/step - loss: 0.0709 - accuracy: 0.9778\n```\n\nThe exact values could not match, but don't worry about that. The important thing that you must see is that the loss value decreases, and the accuracy increases for the firsts 5 epochs.", "_____no_output_____" ], [ "Let's see how this model (trained on only two epochs) performs on the test set.", "_____no_output_____" ] ], [ [ "preds = model.evaluate(X_test, Y_test)\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))", "4/4 [==============================] - 0s 7ms/step - loss: 0.1936 - accuracy: 0.9167\nLoss = 0.193569153547287\nTest Accuracy = 0.9166666865348816\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n <b>Test Accuracy</b>\n </td>\n <td>\n >0.80\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "For the purposes of this assignment, you've been asked to train the model for just two epochs. You can see that it performs pretty poorly, but that's ok! The online grader will only run your code for a small number of epochs as well. Please go ahead and submit your assignment as is. ", "_____no_output_____" ], [ "After you have finished this official (graded) part of this assignment, you can also optionally train the ResNet for more iterations, if you want. It tends to get much better performance when trained for ~20 epochs, but this does take more than an hour when training on a CPU. \n\nUsing a GPU, this ResNet50 model's weights were trained on the SIGNS dataset. You can load and run the trained model on the test set in the cells below. It may take ≈1min to load the model. Have fun! ", "_____no_output_____" ] ], [ [ "pre_trained_model = tf.keras.models.load_model('resnet50.h5')", "_____no_output_____" ], [ "preds = pre_trained_model.evaluate(X_test, Y_test)\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))", "_____no_output_____" ] ], [ [ "**Congratulations** on finishing this assignment! You've now implemented a state-of-the-art image classification system! Woo hoo! \n\nResNet50 is a powerful model for image classification when it's trained for an adequate number of iterations. Hopefully, from this point, you can use what you've learned and apply it to your own classification problem to perform state-of-the-art accuracy.", "_____no_output_____" ], [ "<font color = 'blue'>\n\n**What you should remember**:\n\n- Very deep \"plain\" networks don't work in practice because vanishing gradients make them hard to train. \n- Skip connections help address the Vanishing Gradient problem. They also make it easy for a ResNet block to learn an identity function. \n- There are two main types of blocks: The **identity block** and the **convolutional block**. \n- Very deep Residual Networks are built by stacking these blocks together.", "_____no_output_____" ], [ "<a name='5'></a> \n## 5 - Test on Your Own Image (Optional/Ungraded)", "_____no_output_____" ], [ "If you wish, you can also take a picture of your own hand and see the output of the model. To do this:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Write your image's name in the following code\n 4. Run the code and check if the algorithm is right! ", "_____no_output_____" ] ], [ [ "img_path = 'images/my_image.jpg'\nimg = image.load_img(img_path, target_size=(64, 64))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = x/255.0\nprint('Input image shape:', x.shape)\nimshow(img)\nprediction = pre_trained_model.predict(x)\nprint(\"Class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = \", prediction)\nprint(\"Class:\", np.argmax(prediction))\n", "_____no_output_____" ] ], [ [ "You can also print a summary of your model by running the following code.", "_____no_output_____" ] ], [ [ "pre_trained_model.summary()", "_____no_output_____" ] ], [ [ "<a name='6'></a> \n## 6 - Bibliography\n\nThis notebook presents the ResNet algorithm from He et al. (2015). The implementation here also took significant inspiration and follows the structure given in the GitHub repository of Francois Chollet: \n\n- Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun - [Deep Residual Learning for Image Recognition (2015)](https://arxiv.org/abs/1512.03385)\n- Francois Chollet's GitHub repository: https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py\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", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4af213f86b692493fd644316252aab637a458e9a
894
ipynb
Jupyter Notebook
classroom-code/examples/gf_clearZone.ipynb
CoderDojoTC/python-minecraft
d78ff6d30e47b887f5db12f23de81dd716576c0b
[ "MIT" ]
31
2015-01-30T22:30:55.000Z
2022-02-12T17:10:26.000Z
classroom-code/examples/gf_clearZone.ipynb
CoderDojoTC/python-minecraft
d78ff6d30e47b887f5db12f23de81dd716576c0b
[ "MIT" ]
16
2015-01-20T23:56:43.000Z
2016-01-03T04:14:04.000Z
classroom-code/examples/gf_clearZone.ipynb
CoderDojoTC/python-minecraft
d78ff6d30e47b887f5db12f23de81dd716576c0b
[ "MIT" ]
24
2015-02-21T22:52:43.000Z
2021-12-14T00:18:34.000Z
27.090909
76
0.534676
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af21878e0655acc09263d25c1315c469c6c578e
25,104
ipynb
Jupyter Notebook
02_Crawler_Sample.ipynb
neo4dev/crawler_from_scratch
f8cdbea349bf2fe6618fcbb1394eb8a8cc17ea41
[ "Apache-2.0" ]
2
2021-04-20T12:43:12.000Z
2021-12-20T03:26:38.000Z
02_Crawler_Sample.ipynb
neo4dev/crawler_from_scratch
f8cdbea349bf2fe6618fcbb1394eb8a8cc17ea41
[ "Apache-2.0" ]
2
2020-03-02T12:35:52.000Z
2021-09-28T00:47:16.000Z
02_Crawler_Sample.ipynb
neo4dev/crawler_from_scratch
f8cdbea349bf2fe6618fcbb1394eb8a8cc17ea41
[ "Apache-2.0" ]
3
2021-04-20T12:43:14.000Z
2022-02-20T15:30:34.000Z
43.060034
127
0.468133
[ [ [ "%reload_ext autoreload\n%autoreload 2", "_____no_output_____" ] ], [ [ "# 批量爬取网页\n> 批量爬bilibili视频,并存储和分析", "_____no_output_____" ] ], [ [ "# export\nimport pandas as pd\nimport requests,json,re\nfrom bs4 import BeautifulSoup,Tag,NavigableString\nfrom collections import Counter\nfrom crawler_from_scratch.utils import *", "_____no_output_____" ] ], [ [ "## 批量爬数据", "_____no_output_____" ] ], [ [ "data = {}\n\nfor page in range(1,51):\n url = f'https://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page={page}'\n print(url)\n res = requests.get(url,headers={'user-agent':'Mozilla/5.0'})\n if res.status_code == 200:\n soup = BeautifulSoup(res.text)\n else:\n print(res,res.text)\n \n main_content = soup.body.find(class_='video-list')\n \n for c in get_children(main_content):\n item_data = get_data(c)\n a_title_url = item_data['a_title_url']\n id = re.search(r'av\\d+',a_title_url).group()\n data[id] = item_data\n ", "https://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=1\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=2\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=3\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=4\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=5\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=6\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=7\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=8\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=9\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=10\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=11\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=12\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=13\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=14\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=15\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=16\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=17\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=18\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=19\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=20\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=21\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=22\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=23\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=24\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=25\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=26\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=27\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=28\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=29\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=30\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=31\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=32\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=33\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=34\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=35\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=36\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=37\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=38\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=39\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=40\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=41\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=42\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=43\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=44\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=45\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=46\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=47\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=48\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=49\nhttps://search.bilibili.com/all?keyword=%E5%85%AC%E5%BC%80%E8%AF%BE&from_source=banner_search&page=50\n" ] ], [ [ "## 数据存取", "_____no_output_____" ] ], [ [ "with open('./data/02_bilibili.json', 'w') as f:\n json.dump(data,f)", "_____no_output_____" ], [ "with open('./data/02_bilibili.json', 'r') as f:\n data = json.loads(f.read())", "_____no_output_____" ], [ "len(data.keys())", "_____no_output_____" ] ], [ [ "## 数据分析", "_____no_output_____" ] ], [ [ "dataframe = pd.DataFrame.from_dict(data,orient='index')", "_____no_output_____" ], [ "# hide\ndataframe.head()", "_____no_output_____" ], [ "# hide\ndataframe.describe()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4af224ec62087c689ade03a8c64e05e4de72522d
27,826
ipynb
Jupyter Notebook
gesture/Explore Data.ipynb
nesl/TheMagicFinger
9350754c921eb5e42c9ee3265154d92af94081bc
[ "MIT" ]
1
2019-04-04T09:43:31.000Z
2019-04-04T09:43:31.000Z
gesture/Explore Data.ipynb
nesl/TheMagicFinger
9350754c921eb5e42c9ee3265154d92af94081bc
[ "MIT" ]
null
null
null
gesture/Explore Data.ipynb
nesl/TheMagicFinger
9350754c921eb5e42c9ee3265154d92af94081bc
[ "MIT" ]
null
null
null
77.943978
207
0.682851
[ [ [ "import os\nimport numpy as np\n\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n%matplotlib inline", "_____no_output_____" ], [ "import sklearn\nfrom sklearn import linear_model\nfrom sklearn import svm\nfrom sklearn import cross_validation", "_____no_output_____" ], [ "import exp_loader", "_____no_output_____" ], [ "all_experiments = exp_loader.load_all_experiments()", "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0001/wear_20160920_102418_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0002/wear_20160920_101414_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0003/wear_20160920_101756_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0004/wear_20160920_102342_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0005/wear_20160920_102406_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0006/wear_20160920_102436_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0007/wear_20160920_102453_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0008/wear_20160920_101650_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0009/wear_20160920_102330_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0010/wear_20160920_102317_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0011/wear_20160920_102348_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0012/wear_20160920_102430_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0013/wear_20160920_101424_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0014/wear_20160920_102459_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0015/wear_20160920_101505_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0016/wear_20160920_101656_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0017/wear_20160920_101702_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0018/wear_20160920_101514_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0019/wear_20160920_101459_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0020/wear_20160920_101406_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0021/wear_20160920_101736_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0022/wear_20160920_101723_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0023/wear_20160920_102400_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0024/wear_20160920_101452_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0025/wear_20160920_102505_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0026/wear_20160920_102354_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0027/wear_20160920_101444_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0028/wear_20160920_102411_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0029/wear_20160920_101432_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0030/wear_20160920_101710_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0031/wear_20160920_101802_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0032/wear_20160920_101750_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0033/wear_20160920_102424_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0034/wear_20160920_102310_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0035/wear_20160920_101520_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0036/wear_20160920_102447_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0037/wear_20160920_101716_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0038/wear_20160920_101526_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0039/wear_20160920_102323_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0040/wear_20160920_102441_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0041/wear_20160920_101730_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0042/wear_20160920_101743_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s0/u1/0043/wear_20160920_102336_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0001/wear_20160920_111121_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0002/wear_20160920_110937_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0003/wear_20160920_111102_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0004/wear_20160920_111109_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0005/wear_20160920_110955_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0006/wear_20160920_110943_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0007/wear_20160920_111012_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0008/wear_20160920_110859_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0009/wear_20160920_111127_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0010/wear_20160920_111115_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0011/wear_20160920_110932_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0012/wear_20160920_110913_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0013/wear_20160920_111001_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0014/wear_20160920_110853_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0015/wear_20160920_111007_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0016/wear_20160920_111056_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0017/wear_20160920_111017_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0018/wear_20160920_111043_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0019/wear_20160920_110926_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0020/wear_20160920_111050_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0021/wear_20160920_110919_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0022/wear_20160920_110847_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0023/wear_20160920_110906_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0024/wear_20160920_110949_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0025/wear_20160920_111603_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0026/wear_20160920_111614_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0027/wear_20160920_111441_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0028/wear_20160920_111457_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0029/wear_20160920_111541_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0030/wear_20160920_111531_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0031/wear_20160920_111536_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0032/wear_20160920_111558_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0033/wear_20160920_111514_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0034/wear_20160920_111608_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0035/wear_20160920_111552_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0036/wear_20160920_111519_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0037/wear_20160920_111452_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0038/wear_20160920_111446_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0039/wear_20160920_111509_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0040/wear_20160920_111526_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0041/wear_20160920_111503_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/npyio.py:893: UserWarning: loadtxt: Empty input file: \"data/signs/s1/u1/0042/wear_20160920_111547_mag.csv\"\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname)\n" ], [ "s0_exp = [x for x in all_experiments if x['sign'] == 's0']\ns1_exp = [x for x in all_experiments if x['sign'] == 's1'] \n", "_____no_output_____" ], [ "def compute_features(experiments_list):\n features_list = []\n labels_list = []\n for exp in experiments_list:\n exp_acc = exp['acc']\n f0 = np.percentile(exp_acc[:,1], 25)\n f1 = np.percentile(exp_acc[:,1], 50)\n f2 = np.percentile(exp_acc[:,1], 75)\n f3 = np.percentile(exp_acc[:,2], 25)\n f4 = np.percentile(exp_acc[:,2], 50)\n f5 = np.percentile(exp_acc[:,2], 75)\n f6 = np.percentile(exp_acc[:,3], 25)\n f7 = np.percentile(exp_acc[:,3], 50)\n f8 = np.percentile(exp_acc[:,3], 75)\n \n features_list.append([f0, f1, f2, f3, f4, f5, f6, f7, f8])\n if exp['sign']=='s0':\n labels_list.append(0)\n else:\n labels_list.append(1)\n return (np.array(features_list), np.array(labels_list))\n\n\n", "_____no_output_____" ], [ "X, y = compute_features(all_experiments)", "_____no_output_____" ], [ "\nclf = linear_model.LogisticRegression(penalty='l2', C=0.0000000000001)#svm.SVC(kernel='rbf', C=1, gamma=0.0001)\nscores = cross_validation.cross_val_score(clf, X, y , cv=5)\nprint(scores)\nprint(np.mean(scores))", "[ 0.66666667 0.77777778 0.47058824 0.75 0.8125 ]\n0.695506535948\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af22662fb75bd5fa1dfca890364fa2d24f790db
14,957
ipynb
Jupyter Notebook
.ipynb_checkpoints/SentimentAnalysisRNN-checkpoint.ipynb
sakshiAgrawal64/Sentiment-Analysis-RNN
e15edc99345cbc532c8ca1087ed2232bb459a186
[ "MIT" ]
null
null
null
.ipynb_checkpoints/SentimentAnalysisRNN-checkpoint.ipynb
sakshiAgrawal64/Sentiment-Analysis-RNN
e15edc99345cbc532c8ca1087ed2232bb459a186
[ "MIT" ]
1
2021-08-23T20:44:19.000Z
2021-08-23T20:44:19.000Z
SentimentAnalysisRNN.ipynb
sakshiAgrawal64/Sentiment-Analysis-RNN
e15edc99345cbc532c8ca1087ed2232bb459a186
[ "MIT" ]
null
null
null
56.870722
4,564
0.533262
[ [ [ "# Sentiment Analysis", "_____no_output_____" ] ], [ [ "from keras.datasets import imdb # import the built-in imdb dataset in Keras\n\n# Set the vocabulary size\nvocabulary_size = 5000\n\n# Load in training and test data (note the difference in convention compared to scikit-learn)\n(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=vocabulary_size)\nprint(\"Loaded dataset with {} training samples, {} test samples\".format(len(X_train), len(X_test)))", "Using TensorFlow backend.\n" ], [ "# Inspect a sample review and its label\nprint(\"--- Review ---\")\nprint(X_train[7])\nprint(\"--- Label ---\")\nprint(y_train[7])", "--- Review ---\n[1, 4, 2, 716, 4, 65, 7, 4, 689, 4367, 2, 2343, 4804, 2, 2, 2, 2, 2315, 2, 2, 2, 2, 4, 2, 628, 2, 37, 9, 150, 4, 2, 4069, 11, 2909, 4, 2, 847, 313, 6, 176, 2, 9, 2, 138, 9, 4434, 19, 4, 96, 183, 26, 4, 192, 15, 27, 2, 799, 2, 2, 588, 84, 11, 4, 3231, 152, 339, 2, 42, 4869, 2, 2, 345, 4804, 2, 142, 43, 218, 208, 54, 29, 853, 659, 46, 4, 882, 183, 80, 115, 30, 4, 172, 174, 10, 10, 1001, 398, 1001, 1055, 526, 34, 3717, 2, 2, 2, 17, 4, 2, 1094, 871, 64, 85, 22, 2030, 1109, 38, 230, 9, 4, 4324, 2, 251, 2, 1034, 195, 301, 14, 16, 31, 7, 4, 2, 8, 783, 2, 33, 4, 2945, 103, 465, 2, 42, 845, 45, 446, 11, 1895, 19, 184, 76, 32, 4, 2, 207, 110, 13, 197, 4, 2, 16, 601, 964, 2152, 595, 13, 258, 4, 1730, 66, 338, 55, 2, 4, 550, 728, 65, 1196, 8, 1839, 61, 1546, 42, 2, 61, 602, 120, 45, 2, 6, 320, 786, 99, 196, 2, 786, 2, 4, 225, 4, 373, 1009, 33, 4, 130, 63, 69, 72, 1104, 46, 1292, 225, 14, 66, 194, 2, 1703, 56, 8, 803, 1004, 6, 2, 155, 11, 4, 2, 3231, 45, 853, 2029, 8, 30, 6, 117, 430, 19, 6, 2, 9, 15, 66, 424, 8, 2337, 178, 9, 15, 66, 424, 8, 1465, 178, 9, 15, 66, 142, 15, 9, 424, 8, 28, 178, 662, 44, 12, 17, 4, 130, 898, 1686, 9, 6, 2, 267, 185, 430, 4, 118, 2, 277, 15, 4, 1188, 100, 216, 56, 19, 4, 357, 114, 2, 367, 45, 115, 93, 788, 121, 4, 2, 79, 32, 68, 278, 39, 8, 818, 162, 4165, 237, 600, 7, 98, 306, 8, 157, 549, 628, 11, 6, 2, 13, 824, 15, 4104, 76, 42, 138, 36, 774, 77, 1059, 159, 150, 4, 229, 497, 8, 1493, 11, 175, 251, 453, 19, 2, 189, 12, 43, 127, 6, 394, 292, 7, 2, 4, 107, 8, 4, 2826, 15, 1082, 1251, 9, 906, 42, 1134, 6, 66, 78, 22, 15, 13, 244, 2519, 8, 135, 233, 52, 44, 10, 10, 466, 112, 398, 526, 34, 4, 1572, 4413, 2, 1094, 225, 57, 599, 133, 225, 6, 227, 7, 541, 4323, 6, 171, 139, 7, 539, 2, 56, 11, 6, 3231, 21, 164, 25, 426, 81, 33, 344, 624, 19, 6, 4617, 7, 2, 2, 6, 2, 4, 22, 9, 1082, 629, 237, 45, 188, 6, 55, 655, 707, 2, 956, 225, 1456, 841, 42, 1310, 225, 6, 2493, 1467, 2, 2828, 21, 4, 2, 9, 364, 23, 4, 2228, 2407, 225, 24, 76, 133, 18, 4, 189, 2293, 10, 10, 814, 11, 2, 11, 2642, 14, 47, 15, 682, 364, 352, 168, 44, 12, 45, 24, 913, 93, 21, 247, 2441, 4, 116, 34, 35, 1859, 8, 72, 177, 9, 164, 8, 901, 344, 44, 13, 191, 135, 13, 126, 421, 233, 18, 259, 10, 10, 4, 2, 2, 4, 2, 3074, 7, 112, 199, 753, 357, 39, 63, 12, 115, 2, 763, 8, 15, 35, 3282, 1523, 65, 57, 599, 6, 1916, 277, 1730, 37, 25, 92, 202, 6, 2, 44, 25, 28, 6, 22, 15, 122, 24, 4171, 72, 33, 32]\n--- Label ---\n0\n" ] ], [ [ "Notice that the label is an integer (0 for negative, 1 for positive), and the review itself is stored as a sequence of integers. These are word IDs that have been preassigned to individual words. To map them back to the original words, you can use the dictionary returned by `imdb.get_word_index()`.", "_____no_output_____" ] ], [ [ "# Map word IDs back to words\nword2id = imdb.get_word_index()\nid2word = {i: word for word, i in word2id.items()}\nprint(\"--- Review (with words) ---\")\nprint([id2word.get(i, \" \") for i in X_train[7]])\nprint(\"--- Label ---\")\nprint(y_train[7])", "--- Review (with words) ---\n['the', 'of', 'and', 'local', 'of', 'their', 'br', 'of', 'attention', 'widow', 'and', 'captures', 'parties', 'and', 'and', 'and', 'and', 'excitement', 'and', 'and', 'and', 'and', 'of', 'and', 'english', 'and', 'like', 'it', 'years', 'of', 'and', 'unintentional', 'this', 'hitchcock', 'of', 'and', 'learn', 'everyone', 'is', 'quite', 'and', 'it', 'and', 'such', 'it', 'bonus', 'film', 'of', 'too', 'seems', 'he', 'of', 'enough', 'for', 'be', 'and', 'editing', 'and', 'and', 'please', 'great', 'this', 'of', 'shoots', 'thing', '3', 'and', \"it's\", 'mentioning', 'and', 'and', 'given', 'parties', 'and', 'back', 'out', 'interesting', 'times', 'no', 'all', 'average', 'talking', 'some', 'of', 'nor', 'seems', 'into', 'best', 'at', 'of', 'every', 'cast', 'i', 'i', 'inside', 'keep', 'inside', 'large', 'viewer', 'who', 'obscure', 'and', 'and', 'and', 'movie', 'of', 'and', 'entirely', \"you've\", 'see', 'because', 'you', 'deals', 'successful', 'her', 'anything', 'it', 'of', 'dedicated', 'and', 'hard', 'and', 'further', \"that's\", 'takes', 'as', 'with', 'by', 'br', 'of', 'and', 'in', 'minute', 'and', 'they', 'of', 'westerns', 'watch', 'seemed', 'and', \"it's\", 'lee', 'if', 'oh', 'this', 'japan', 'film', 'around', 'get', 'an', 'of', 'and', 'always', 'life', 'was', 'between', 'of', 'and', 'with', 'group', 'rate', 'code', \"film's\", 'was', 'although', 'of', 'arts', 'had', 'death', 'time', 'and', 'of', 'anyway', 'romantic', 'their', 'won', 'in', 'kevin', 'only', 'flying', \"it's\", 'and', 'only', 'cut', 'show', 'if', 'and', 'is', 'star', 'stay', 'movies', 'both', 'and', 'stay', 'and', 'of', 'music', 'of', 'tell', 'missing', 'they', 'of', 'here', 'really', 'me', 'we', 'value', 'some', 'silent', 'music', 'as', 'had', 'thought', 'and', 'realized', 'she', 'in', 'sorry', 'reasons', 'is', 'and', '10', 'this', 'of', 'and', 'shoots', 'if', 'average', 'remembered', 'in', 'at', 'is', 'over', 'worse', 'film', 'is', 'and', 'it', 'for', 'had', 'absolutely', 'in', 'naive', 'want', 'it', 'for', 'had', 'absolutely', 'in', 'j', 'want', 'it', 'for', 'had', 'back', 'for', 'it', 'absolutely', 'in', 'one', 'want', 'shots', 'has', 'that', 'movie', 'of', 'here', 'write', 'whatsoever', 'it', 'is', 'and', 'set', 'got', 'worse', 'of', 'where', 'and', 'once', 'for', 'of', 'accent', 'after', 'saw', 'she', 'film', 'of', 'rest', 'little', 'and', 'camera', 'if', 'best', 'way', 'elements', 'know', 'of', 'and', 'also', 'an', 'were', 'sense', 'or', 'in', 'realistic', 'actually', 'satan', \"he's\", 'score', 'br', 'any', 'himself', 'in', 'another', 'type', 'english', 'this', 'is', 'and', 'was', 'tom', 'for', 'dating', 'get', \"it's\", 'such', 'from', 'fantastic', 'will', 'pace', 'new', 'years', 'of', 'guy', 'game', 'in', 'murders', 'this', 'us', 'hard', 'lives', 'film', 'and', 'fact', 'that', 'out', 'end', 'is', 'getting', 'together', 'br', 'and', 'of', 'seen', 'in', 'of', 'jail', 'for', 'sees', 'utterly', 'it', 'meet', \"it's\", 'depth', 'is', 'had', 'do', 'you', 'for', 'was', 'rather', 'convince', 'in', 'why', 'last', 'very', 'has', 'i', 'i', 'throughout', 'never', 'keep', 'viewer', 'who', 'of', 'becoming', 'switch', 'and', 'entirely', 'music', 'even', 'interest', 'scene', 'music', 'is', 'far', 'br', 'voice', 'riveting', 'is', 'again', 'something', 'br', 'decent', 'and', 'she', 'this', 'is', 'shoots', 'not', 'director', 'have', 'against', 'people', 'they', 'line', 'cinematography', 'film', 'is', 'couples', 'br', 'and', 'and', 'is', 'and', 'of', 'you', 'it', 'sees', 'hero', \"he's\", 'if', \"can't\", 'is', 'time', 'husband', 'silly', 'and', 'result', 'music', 'image', 'sequences', \"it's\", 'chase', 'music', 'is', 'veteran', 'include', 'and', 'freeman', 'not', 'of', 'and', 'it', 'along', 'are', 'of', 'hearing', 'cutting', 'music', 'his', 'get', 'scene', 'but', 'of', 'fact', 'correct', 'i', 'i', 'means', 'this', 'and', 'this', 'blockbuster', 'as', 'there', 'for', 'disappointed', 'along', 'wrong', 'few', 'has', 'that', 'if', 'his', 'weird', 'way', 'not', 'girl', 'display', 'of', 'love', 'who', 'so', 'friendship', 'in', 'we', 'down', 'it', 'director', 'in', 'situation', 'line', 'has', 'was', 'big', 'why', 'was', 'your', 'supposed', 'last', 'but', 'especially', 'i', 'i', 'of', 'and', 'and', 'of', 'and', 'internet', 'br', 'never', 'give', 'theme', 'rest', 'or', 'really', 'that', 'best', 'and', 'release', 'in', 'for', 'so', 'multi', 'random', 'their', 'even', 'interest', 'is', 'judge', 'once', 'arts', 'like', 'have', 'then', 'own', 'is', 'and', 'has', 'have', 'one', 'is', 'you', 'for', 'off', 'his', 'dutch', 'we', 'they', 'an']\n--- Label ---\n0\n" ], [ "from keras.preprocessing import sequence\n\n# Set the maximum number of words per document (for both training and testing)\nmax_words = 500\n\n#Pad sequences in X_train and X_test\nX_train = sequence.pad_sequences(X_train, maxlen=max_words)\nX_test = sequence.pad_sequences(X_test, maxlen=max_words)", "_____no_output_____" ], [ "from keras.models import Sequential\nfrom keras.layers import Embedding, LSTM, Dense, Dropout\n\n# TODO: Design your model\nembedding_size = 32\nmodel = Sequential()\nmodel.add(Embedding(vocabulary_size, embedding_size, input_length=max_words))\nmodel.add(LSTM(100))\nmodel.add(Dense(1, activation='sigmoid'))\n\nprint(model.summary())", "WARNING:tensorflow:From C:\\Users\\rakap\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_1 (Embedding) (None, 500, 32) 160000 \n_________________________________________________________________\nlstm_1 (LSTM) (None, 100) 53200 \n_________________________________________________________________\ndense_1 (Dense) (None, 1) 101 \n=================================================================\nTotal params: 213,301\nTrainable params: 213,301\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ], [ "# TODO: Compile your model, specifying a loss function, optimizer, and metrics\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])", "_____no_output_____" ], [ "# TODO: Specify training parameters: batch size and number of epochs\nbatch_size = 64\nnum_epochs = 3\n\n# TODO(optional): Reserve/specify some training data for validation (not to be used for training)\nX_valid, y_valid = X_train[:batch_size], y_train[:batch_size] # first batch_size samples\nX_train2, y_train2 = X_train[batch_size:], y_train[batch_size:] # rest for training\n\n# TODO: Train your model\nmodel.fit(X_train2, y_train2,\n validation_data=(X_valid, y_valid),\n batch_size=batch_size, epochs=num_epochs)", "WARNING:tensorflow:From C:\\Users\\rakap\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\ops\\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nTrain on 24936 samples, validate on 64 samples\nEpoch 1/3\n24936/24936 [==============================] - 156s 6ms/step - loss: 0.4404 - acc: 0.7899 - val_loss: 0.2229 - val_acc: 0.9531\nEpoch 2/3\n24936/24936 [==============================] - 162s 6ms/step - loss: 0.2991 - acc: 0.8796 - val_loss: 0.2539 - val_acc: 0.9219\nEpoch 3/3\n24936/24936 [==============================] - 160s 6ms/step - loss: 0.2435 - acc: 0.9042 - val_loss: 0.2260 - val_acc: 0.9375\n" ], [ "# Evaluate your model on the test set\nscores = model.evaluate(X_test, y_test, verbose=0) # returns loss and other metrics specified in model.compile()\nprint(\"Test accuracy:\", scores[1]) # scores[1] should correspond to accuracy if you passed in metrics=['accuracy']\n", "Test accuracy: 0.87116\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4af22a6e241c519603b1cf99a6189810e229f6fd
210,716
ipynb
Jupyter Notebook
StockPricePrediction/StockPricePrediction_v1b_xgboost.ipynb
clairvoyant/Stocks
ea1a75494dd9015d2cd9dace39105007d3f3ed96
[ "Apache-2.0" ]
265
2019-02-11T05:41:42.000Z
2022-03-31T17:10:29.000Z
StockPricePrediction/StockPricePrediction_v1b_xgboost.ipynb
clairvoyant/Stocks
ea1a75494dd9015d2cd9dace39105007d3f3ed96
[ "Apache-2.0" ]
12
2020-09-26T00:59:56.000Z
2022-03-12T00:26:14.000Z
StockPricePrediction/StockPricePrediction_v1b_xgboost.ipynb
clairvoyant/Stocks
ea1a75494dd9015d2cd9dace39105007d3f3ed96
[ "Apache-2.0" ]
213
2019-02-05T11:20:02.000Z
2022-03-31T06:25:45.000Z
120.754155
43,092
0.816991
[ [ [ "# Objective\n* 20181225: \n * Predict stock price in next day using XGBoost\n * Given prices and other features for the last N days, we do prediction for day N+1\n * Here we split 3 years of data into train(60%), dev(20%) and test(20%)\n* 20190110 - Diff from StockPricePrediction_v1_xgboost.ipynb:\n * Here we scale the train set to have mean 0 and variance 1, and apply the same transformation to dev and test sets\n* 20190111 - Diff from StockPricePrediction_v1a_xgboost.ipynb:\n * Here for the past N values for the dev set, we scale them to have mean 0 and variance 1, and do prediction on them", "_____no_output_____" ] ], [ [ "import math\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport time\n\nfrom matplotlib import pyplot as plt\nfrom pylab import rcParams\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\nfrom tqdm import tqdm_notebook\nfrom xgboost import XGBRegressor\n\n%matplotlib inline\n\n#### Input params ##################\nstk_path = \"./data/VTI.csv\"\ntest_size = 0.2 # proportion of dataset to be used as test set\ncv_size = 0.2 # proportion of dataset to be used as cross-validation set\nN = 7 # for feature at day t, we use lags from t-1, t-2, ..., t-N as features\n\nn_estimators = 100 # for the initial model before tuning. default = 100\nmax_depth = 3 # for the initial model before tuning. default = 3\nlearning_rate = 0.1 # for the initial model before tuning. default = 0.1\nmin_child_weight = 1 # for the initial model before tuning. default = 1\nsubsample = 1 # for the initial model before tuning. default = 1\ncolsample_bytree = 1 # for the initial model before tuning. default = 1\ncolsample_bylevel = 1 # for the initial model before tuning. default = 1\ntrain_test_split_seed = 111 # 111\nmodel_seed = 100\n\nfontsize = 14\nticklabelsize = 14\n####################################", "_____no_output_____" ] ], [ [ "# Load data", "_____no_output_____" ] ], [ [ "df = pd.read_csv(stk_path, sep = \",\")\n\n# Convert Date column to datetime\ndf.loc[:, 'Date'] = pd.to_datetime(df['Date'],format='%Y-%m-%d')\n\n# Change all column headings to be lower case, and remove spacing\ndf.columns = [str(x).lower().replace(' ', '_') for x in df.columns]\n\n# Get month of each sample\ndf['month'] = df['date'].dt.month\n\n# Sort by datetime\ndf.sort_values(by='date', inplace=True, ascending=True)\n\ndf.head()", "_____no_output_____" ], [ "# Plot adjusted close over time\nrcParams['figure.figsize'] = 10, 8 # width 10, height 8\n\nax = df.plot(x='date', y='adj_close', style='b-', grid=True)\nax.set_xlabel(\"date\")\nax.set_ylabel(\"USD\")", "_____no_output_____" ] ], [ [ "# Split into train, dev and test set", "_____no_output_____" ] ], [ [ "# Get sizes of each of the datasets\nnum_cv = int(cv_size*len(df))\nnum_test = int(test_size*len(df))\nnum_train = len(df) - num_cv - num_test\nprint(\"num_train = \" + str(num_train))\nprint(\"num_cv = \" + str(num_cv))\nprint(\"num_test = \" + str(num_test))\n\n# Split into train, cv, and test\ntrain = df[:num_train]\ncv = df[num_train:num_train+num_cv]\ntrain_cv = df[:num_train+num_cv]\ntest = df[num_train+num_cv:]\n\nprint(\"train.shape = \" + str(train.shape))\nprint(\"cv.shape = \" + str(cv.shape))\nprint(\"train_cv.shape = \" + str(train_cv.shape))\nprint(\"test.shape = \" + str(test.shape))", "num_train = 453\nnum_cv = 151\nnum_test = 151\ntrain.shape = (453, 8)\ncv.shape = (151, 8)\ntrain_cv.shape = (604, 8)\ntest.shape = (151, 8)\n" ] ], [ [ "# Scale the train, dev and test set and combine them to do feature engineering", "_____no_output_____" ] ], [ [ "# Converting dataset into x_train and y_train\n# Here we only scale the train dataset, and not the entire dataset to prevent information leak\nscaler = StandardScaler()\ntrain_scaled = scaler.fit_transform(train[['open', 'high', 'low', 'close', 'adj_close', 'volume']])\nprint(\"scaler.mean_ = \" + str(scaler.mean_))\nprint(\"scaler.var_ = \" + str(scaler.var_))\nprint(\"train_scaled.shape = \" + str(train_scaled.shape))\n\n# Convert the numpy array back into pandas dataframe\ntrain_scaled = pd.DataFrame(train_scaled, columns=['open', 'high', 'low', 'close', 'adj_close', 'volume'])\ntrain_scaled[['date', 'month']] = train[['date', 'month']]\nprint(\"train_scaled.shape = \" + str(train_scaled.shape))\ntrain_scaled.head()", "scaler.mean_ = [1.13179757e+02 1.13586225e+02 1.12691545e+02 1.13190088e+02\n 1.09092171e+02 2.59281148e+06]\nscaler.var_ = [8.18020920e+01 7.97106998e+01 8.39537740e+01 8.15594150e+01\n 9.51990222e+01 1.88602129e+12]\ntrain_scaled.shape = (453, 6)\ntrain_scaled.shape = (453, 8)\n" ], [ "# Do scaling for dev set\ncv_scaled = scaler.transform(cv[['open', 'high', 'low', 'close', 'adj_close', 'volume']])\n\n# Convert the numpy array back into pandas dataframe\ncv_scaled = pd.DataFrame(cv_scaled, columns=['open', 'high', 'low', 'close', 'adj_close', 'volume'])\ncv_scaled[['date', 'month']] = cv.reset_index()[['date', 'month']]\nprint(\"cv_scaled.shape = \" + str(cv_scaled.shape))\ncv_scaled.head()", "cv_scaled.shape = (151, 8)\n" ], [ "# Do scaling for test set\ntest_scaled = scaler.transform(test[['open', 'high', 'low', 'close', 'adj_close', 'volume']])\n\n# Convert the numpy array back into pandas dataframe\ntest_scaled = pd.DataFrame(test_scaled, columns=['open', 'high', 'low', 'close', 'adj_close', 'volume'])\ntest_scaled[['date', 'month']] = test.reset_index()[['date', 'month']]\nprint(\"test_scaled.shape = \" + str(test_scaled.shape))\ntest_scaled.head()", "test_scaled.shape = (151, 8)\n" ], [ "# Combine back train_scaled, cv_scaled, test_scaled together\ndf_scaled = pd.concat([train_scaled, cv_scaled, test_scaled], axis=0)\ndf_scaled.head()", "_____no_output_____" ] ], [ [ "# Feature Engineering", "_____no_output_____" ], [ "We will generate the following features:\n* Mean 'adj_close' of each month\n* Difference between high and low of each day\n* Difference between open and close of each day\n* Mean volume of each month", "_____no_output_____" ] ], [ [ "# Get difference between high and low of each day\ndf_scaled['range_hl'] = df_scaled['high'] - df_scaled['low']\ndf_scaled.drop(['high', 'low'], axis=1, inplace=True)\n\n# Get difference between open and close of each day\ndf_scaled['range_oc'] = df_scaled['open'] - df_scaled['close']\ndf_scaled.drop(['open', 'close'], axis=1, inplace=True)\n\ndf_scaled.head()", "_____no_output_____" ] ], [ [ "Now we use lags up to N number of days to use as features.", "_____no_output_____" ] ], [ [ "# Add a column 'order_day' to indicate the order of the rows by date\ndf_scaled['order_day'] = [x for x in list(range(len(df_scaled)))]\n\n# merging_keys\nmerging_keys = ['order_day']\n\n# List of columns that we will use to create lags\nlag_cols = ['adj_close', 'range_hl', 'range_oc', 'volume']\nlag_cols", "_____no_output_____" ], [ "shift_range = [x+1 for x in range(N)]\n\nfor shift in tqdm_notebook(shift_range):\n train_shift = df_scaled[merging_keys + lag_cols].copy()\n \n # E.g. order_day of 0 becomes 1, for shift = 1.\n # So when this is merged with order_day of 1 in df_scaled, this will represent lag of 1.\n train_shift['order_day'] = train_shift['order_day'] + shift\n \n foo = lambda x: '{}_lag_{}'.format(x, shift) if x in lag_cols else x\n train_shift = train_shift.rename(columns=foo)\n\n df_scaled = pd.merge(df_scaled, train_shift, on=merging_keys, how='left') #.fillna(0)\n \ndel train_shift\n\n# Remove the first N rows which contain NaNs\ndf_scaled = df_scaled[N:]\n \ndf_scaled.head()", "_____no_output_____" ], [ "df_scaled.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 748 entries, 7 to 754\nData columns (total 35 columns):\nadj_close 748 non-null float64\nvolume 748 non-null float64\ndate 748 non-null datetime64[ns]\nmonth 748 non-null int64\nrange_hl 748 non-null float64\nrange_oc 748 non-null float64\norder_day 748 non-null int64\nadj_close_lag_1 748 non-null float64\nrange_hl_lag_1 748 non-null float64\nrange_oc_lag_1 748 non-null float64\nvolume_lag_1 748 non-null float64\nadj_close_lag_2 748 non-null float64\nrange_hl_lag_2 748 non-null float64\nrange_oc_lag_2 748 non-null float64\nvolume_lag_2 748 non-null float64\nadj_close_lag_3 748 non-null float64\nrange_hl_lag_3 748 non-null float64\nrange_oc_lag_3 748 non-null float64\nvolume_lag_3 748 non-null float64\nadj_close_lag_4 748 non-null float64\nrange_hl_lag_4 748 non-null float64\nrange_oc_lag_4 748 non-null float64\nvolume_lag_4 748 non-null float64\nadj_close_lag_5 748 non-null float64\nrange_hl_lag_5 748 non-null float64\nrange_oc_lag_5 748 non-null float64\nvolume_lag_5 748 non-null float64\nadj_close_lag_6 748 non-null float64\nrange_hl_lag_6 748 non-null float64\nrange_oc_lag_6 748 non-null float64\nvolume_lag_6 748 non-null float64\nadj_close_lag_7 748 non-null float64\nrange_hl_lag_7 748 non-null float64\nrange_oc_lag_7 748 non-null float64\nvolume_lag_7 748 non-null float64\ndtypes: datetime64[ns](1), float64(32), int64(2)\nmemory usage: 210.4 KB\n" ], [ "# # Get mean of adj_close of each month\n# df_gb = df.groupby(['month'], as_index=False).agg({'adj_close':'mean'})\n# df_gb = df_gb.rename(columns={'adj_close':'adj_close_mean'})\n# df_gb\n\n# # Merge to main df\n# df = df.merge(df_gb, \n# left_on=['month'], \n# right_on=['month'],\n# how='left').fillna(0)\n\n# # Merge to main df\n# shift_range = [x+1 for x in range(2)]\n\n# for shift in tqdm_notebook(shift_range):\n# train_shift = df[merging_keys + lag_cols].copy()\n \n# # E.g. order_day of 0 becomes 1, for shift = 1.\n# # So when this is merged with order_day of 1 in df, this will represent lag of 1.\n# train_shift['order_day'] = train_shift['order_day'] + shift\n \n# foo = lambda x: '{}_lag_{}'.format(x, shift) if x in lag_cols else x\n# train_shift = train_shift.rename(columns=foo)\n\n# df = pd.merge(df, train_shift, on=merging_keys, how='left') #.fillna(0)\n \n# del train_shift\n \n# df", "_____no_output_____" ], [ "# # Get mean of volume of each month\n# df_gb = df.groupby(['month'], as_index=False).agg({'volume':'mean'})\n# df_gb = df_gb.rename(columns={'volume':'volume_mean'})\n# df_gb\n\n# # Merge to main df\n# df = df.merge(df_gb, \n# left_on=['month'], \n# right_on=['month'],\n# how='left').fillna(0)\n\n# df.head()", "_____no_output_____" ] ], [ [ "# Split the scaled features back into train, dev and test set", "_____no_output_____" ] ], [ [ "features = [\n\"adj_close_lag_1\",\n\"range_hl_lag_1\",\n\"range_oc_lag_1\",\n\"volume_lag_1\",\n\"adj_close_lag_2\",\n\"range_hl_lag_2\",\n\"range_oc_lag_2\",\n\"volume_lag_2\",\n\"adj_close_lag_3\",\n\"range_hl_lag_3\",\n\"range_oc_lag_3\",\n\"volume_lag_3\",\n\"adj_close_lag_4\",\n\"range_hl_lag_4\",\n\"range_oc_lag_4\",\n\"volume_lag_4\",\n\"adj_close_lag_5\",\n\"range_hl_lag_5\",\n\"range_oc_lag_5\",\n\"volume_lag_5\",\n\"adj_close_lag_6\",\n\"range_hl_lag_6\",\n\"range_oc_lag_6\",\n\"volume_lag_6\",\n\"adj_close_lag_7\",\n\"range_hl_lag_7\",\n\"range_oc_lag_7\",\n\"volume_lag_7\"\n]\n\ntarget = \"adj_close\"\n\n# Split into train, cv, and test\ntrain = df_scaled[:num_train]\ncv = df_scaled[num_train:num_train+num_cv]\ntrain_cv = df_scaled[:num_train+num_cv]\ntest = df_scaled[num_train+num_cv:]\n\n# Split into X and y\nX_train = train[features]\ny_train = train[target]\nX_cv = cv[features]\ny_cv = cv[target]\nX_train_cv = train_cv[features]\ny_train_cv = train_cv[target]\nX_sample = test[features]\ny_sample = test[target]\nprint(\"X_train.shape = \" + str(X_train.shape))\nprint(\"y_train.shape = \" + str(y_train.shape))\nprint(\"X_cv.shape = \" + str(X_cv.shape))\nprint(\"y_cv.shape = \" + str(y_cv.shape))\nprint(\"X_train_cv.shape = \" + str(X_train_cv.shape))\nprint(\"y_train_cv.shape = \" + str(y_train_cv.shape))\nprint(\"X_sample.shape = \" + str(X_sample.shape))\nprint(\"y_sample.shape = \" + str(y_sample.shape))", "X_train.shape = (453, 28)\ny_train.shape = (453,)\nX_cv.shape = (151, 28)\ny_cv.shape = (151,)\nX_train_cv.shape = (604, 28)\ny_train_cv.shape = (604,)\nX_sample.shape = (144, 28)\ny_sample.shape = (144,)\n" ] ], [ [ "# EDA", "_____no_output_____" ] ], [ [ "# Plot adjusted close over time\nrcParams['figure.figsize'] = 10, 8 # width 10, height 8\n\nax = train.plot(x='date', y='adj_close', style='b-', grid=True)\nax = cv.plot(x='date', y='adj_close', style='y-', grid=True, ax=ax)\nax = test.plot(x='date', y='adj_close', style='g-', grid=True, ax=ax)\nax.legend(['train', 'dev', 'test'])\nax.set_xlabel(\"date\")\nax.set_ylabel(\"USD (scaled)\")", "_____no_output_____" ] ], [ [ "# Train the model using XGBoost", "_____no_output_____" ] ], [ [ "# Create the model\nmodel = XGBRegressor(seed=model_seed,\n n_estimators=n_estimators,\n max_depth=max_depth,\n learning_rate=learning_rate,\n min_child_weight=min_child_weight)\n\n# Train the regressor\nmodel.fit(X_train, y_train)", "_____no_output_____" ] ], [ [ "# Predict on train set", "_____no_output_____" ] ], [ [ "# Do prediction on train set\nest = model.predict(X_train)\n\n# Calculate RMSE\nmath.sqrt(mean_squared_error(y_train, est))", "_____no_output_____" ], [ "# Plot adjusted close over time\nrcParams['figure.figsize'] = 10, 8 # width 10, height 8\n\nest_df = pd.DataFrame({'est': est, \n 'date': train['date']})\n\nax = train.plot(x='date', y='adj_close', style='b-', grid=True)\nax = cv.plot(x='date', y='adj_close', style='y-', grid=True, ax=ax)\nax = test.plot(x='date', y='adj_close', style='g-', grid=True, ax=ax)\nax = est_df.plot(x='date', y='est', style='r-', grid=True, ax=ax)\nax.legend(['train', 'dev', 'test', 'est'])\nax.set_xlabel(\"date\")\nax.set_ylabel(\"USD (scaled)\")", "_____no_output_____" ] ], [ [ "# Predict on dev set", "_____no_output_____" ] ], [ [ "# Do prediction on test set\nest = model.predict(X_cv)\n\n# Calculate RMSE\nmath.sqrt(mean_squared_error(y_cv, est))", "_____no_output_____" ], [ "# Plot adjusted close over time\nrcParams['figure.figsize'] = 10, 8 # width 10, height 8\n\nest_df = pd.DataFrame({'est': est, \n 'y_cv': y_cv,\n 'date': cv['date']})\n\nax = train.plot(x='date', y='adj_close', style='b-', grid=True)\nax = cv.plot(x='date', y='adj_close', style='y-', grid=True, ax=ax)\nax = test.plot(x='date', y='adj_close', style='g-', grid=True, ax=ax)\nax = est_df.plot(x='date', y='est', style='r-', grid=True, ax=ax)\nax.legend(['train', 'dev', 'test', 'est'])\nax.set_xlabel(\"date\")\nax.set_ylabel(\"USD (scaled)\")", "_____no_output_____" ] ], [ [ "# Findings\n* Doesn't work well\n* Likely because the model was trained on prices below ~1.7 and so when it saw prices above 1.7 for the dev set, it could not generalize 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" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4af22bd5d8fee950335677ff6ebc05fd4b83d248
97,807
ipynb
Jupyter Notebook
04. Making it work on Small Data - Part 2.ipynb
NirantK/keras-practice
6610b1212b4747452fab36cb27d7cfd39d8d71ba
[ "MIT" ]
12
2018-03-03T06:03:03.000Z
2019-08-08T06:53:56.000Z
04. Making it work on Small Data - Part 2.ipynb
NirantK/keras-practice
6610b1212b4747452fab36cb27d7cfd39d8d71ba
[ "MIT" ]
null
null
null
04. Making it work on Small Data - Part 2.ipynb
NirantK/keras-practice
6610b1212b4747452fab36cb27d7cfd39d8d71ba
[ "MIT" ]
13
2018-03-02T16:41:55.000Z
2021-11-06T15:51:29.000Z
116.298454
19,766
0.822354
[ [ [ "## In this notebook:\n- Using a pre-trained convnet to do feature extraction\n - Use ConvBase only for feature extraction, and use a separate machine learning classifier\n - Adding ```Dense``` layers to top of a frozen ConvBase, allowing us to leverage data augmentation \n- Fine-tuning a pre-trained convnet (Skipped, because I am tired now) \n\n### In previous notebook: \n- Training your own small convnets from scratch\n- Using data augmentation to mitigate overfitting", "_____no_output_____" ] ], [ [ "from datetime import date\ndate.today()", "_____no_output_____" ], [ "author = \"NirantK. https://github.com/NirantK/keras-practice\"\nprint(author)", "NirantK. https://github.com/NirantK/keras-practice\n" ], [ "import keras\nprint('Keras Version:', keras.__version__)\nimport os\nif os.name=='nt':\n print('We are on Windows')", "Using TensorFlow backend.\n" ], [ "import os, shutil", "_____no_output_____" ], [ "pwd = os.getcwd()", "_____no_output_____" ] ], [ [ "Feature extraction\n---\nThis consists of using the representations learned by a previous network to extract interesting features from new samples. These features are then run through a new classifier, which is trained from scratch.\n![](https://dpzbhybb2pdcj.cloudfront.net/chollet/v-6/Figures/swapping_fc_classifier.png)", "_____no_output_____" ], [ "Warning: The line below triggers a download. You need good speed Internet!", "_____no_output_____" ] ], [ [ "from keras.applications import VGG16\n\nconv_base = VGG16(weights='imagenet',\n include_top=False,\n input_shape=(150, 150, 3))", "_____no_output_____" ] ], [ [ "We passed three arguments to the constructor:\n\n- **```weights```**, to specify which weight checkpoint to initialize the model from\n- **```include_top```**, which refers to including or not the densely-connected classifier on top of the network. By default, this densely-connected classifier would correspond to the 1000 classes from ImageNet. Since we intend to use our own densely-connected classifier (with only two classes, cat and dog), we don’t need to include it.\n- **```input_shape```**, the shape of the image tensors that we will feed to the network. This argument is purely optional: if we don’t pass it, then the network will be able to process inputs of any size.\n\n(from *Deep Learning in Python by F. Chollet*)", "_____no_output_____" ], [ "What does the **VGG16** thing look like? ", "_____no_output_____" ] ], [ [ "conv_base.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) (None, 150, 150, 3) 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 150, 150, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 150, 150, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 75, 75, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 75, 75, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 75, 75, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 37, 37, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 37, 37, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 37, 37, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 37, 37, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 18, 18, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 18, 18, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 18, 18, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 18, 18, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 9, 9, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 9, 9, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 9, 9, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 9, 9, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 4, 4, 512) 0 \n=================================================================\nTotal params: 14,714,688\nTrainable params: 14,714,688\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "Feature Extraction\n---\nPros: \n- Fast, and cheap\n- Works on CPU\n\nCons: \n- Does not allow us to use data augmentation\n - Because we do feature extraction and classification in separate steps", "_____no_output_____" ] ], [ [ "import os\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\n\nbase_dir = os.path.join(pwd, 'data/cats_and_dogs_small/')\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\ntest_dir = os.path.join(base_dir, 'test')\n\ndatagen = ImageDataGenerator(rescale=1./255)\nbatch_size = 1\n\ndef extract_features(directory, sample_count):\n features = np.zeros(shape=(sample_count, 4, 4, 512))\n labels = np.zeros(shape=(sample_count))\n generator = datagen.flow_from_directory(\n directory,\n target_size=(150, 150),\n batch_size=batch_size,\n class_mode='binary')\n i = 0\n for inputs_batch, labels_batch in generator:\n features_batch = conv_base.predict(inputs_batch)\n try:\n features[i * batch_size : (i + 1) * batch_size] = features_batch\n except ValueError:\n print(i)\n raise ValueError\n labels[i * batch_size : (i + 1) * batch_size] = labels_batch\n i += 1\n if i * batch_size >= sample_count:\n # Note that since generators yield data indefinitely in a loop,\n # we must `break` after every image has been seen once.\n break\n return features, labels", "_____no_output_____" ], [ "%time train_features, train_labels = extract_features(train_dir, 2000)", "Found 2000 images belonging to 2 classes.\nCPU times: user 14.5 s, sys: 1.46 s, total: 15.9 s\nWall time: 14.9 s\n" ], [ "%time validation_features, validation_labels = extract_features(validation_dir, 1000)\n%time test_features, test_labels = extract_features(test_dir, 1000)", "Found 1000 images belonging to 2 classes.\nCPU times: user 6.9 s, sys: 816 ms, total: 7.72 s\nWall time: 7.26 s\nFound 1000 images belonging to 2 classes.\nCPU times: user 6.96 s, sys: 692 ms, total: 7.65 s\nWall time: 7.19 s\n" ], [ "train_features = np.reshape(train_features, (2000, 4 * 4 * 512))\nvalidation_features = np.reshape(validation_features, (1000, 4 * 4 * 512))\ntest_features = np.reshape(test_features, (1000, 4 * 4 * 512))", "_____no_output_____" ] ], [ [ "**Model Training:**", "_____no_output_____" ] ], [ [ "from keras import models\nfrom keras import layers\nfrom keras import optimizers\n\nmodel = models.Sequential()\nmodel.add(layers.Dense(256, activation='relu', input_dim=4 * 4 * 512))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer=optimizers.RMSprop(lr=2e-5),\n loss='binary_crossentropy',\n metrics=['acc'])", "_____no_output_____" ], [ "%time history = model.fit(train_features, train_labels, epochs=15, batch_size=20, validation_data=(validation_features, validation_labels))", "Train on 2000 samples, validate on 1000 samples\nEpoch 1/15\n2000/2000 [==============================] - 0s - loss: 0.5994 - acc: 0.6720 - val_loss: 0.4453 - val_acc: 0.8340\nEpoch 2/15\n2000/2000 [==============================] - 0s - loss: 0.4348 - acc: 0.8055 - val_loss: 0.3698 - val_acc: 0.8590\nEpoch 3/15\n2000/2000 [==============================] - 0s - loss: 0.3642 - acc: 0.8525 - val_loss: 0.3216 - val_acc: 0.8800\nEpoch 4/15\n2000/2000 [==============================] - 0s - loss: 0.3161 - acc: 0.8730 - val_loss: 0.3152 - val_acc: 0.8660\nEpoch 5/15\n2000/2000 [==============================] - 0s - loss: 0.2930 - acc: 0.8810 - val_loss: 0.2828 - val_acc: 0.8950\nEpoch 6/15\n2000/2000 [==============================] - 0s - loss: 0.2616 - acc: 0.9010 - val_loss: 0.2719 - val_acc: 0.8910\nEpoch 7/15\n2000/2000 [==============================] - 0s - loss: 0.2449 - acc: 0.9115 - val_loss: 0.2609 - val_acc: 0.8940\nEpoch 8/15\n2000/2000 [==============================] - 0s - loss: 0.2437 - acc: 0.9040 - val_loss: 0.2609 - val_acc: 0.8950\nEpoch 9/15\n2000/2000 [==============================] - 0s - loss: 0.2282 - acc: 0.9095 - val_loss: 0.2561 - val_acc: 0.8970\nEpoch 10/15\n2000/2000 [==============================] - 0s - loss: 0.2139 - acc: 0.9185 - val_loss: 0.2500 - val_acc: 0.8960\nEpoch 11/15\n2000/2000 [==============================] - 0s - loss: 0.2020 - acc: 0.9235 - val_loss: 0.2474 - val_acc: 0.8970\nEpoch 12/15\n2000/2000 [==============================] - 0s - loss: 0.1946 - acc: 0.9295 - val_loss: 0.2409 - val_acc: 0.9080\nEpoch 13/15\n2000/2000 [==============================] - 0s - loss: 0.1807 - acc: 0.9315 - val_loss: 0.2367 - val_acc: 0.9060\nEpoch 14/15\n2000/2000 [==============================] - 0s - loss: 0.1753 - acc: 0.9395 - val_loss: 0.2350 - val_acc: 0.9050\nEpoch 15/15\n2000/2000 [==============================] - 0s - loss: 0.1636 - acc: 0.9380 - val_loss: 0.2432 - val_acc: 0.8970\nCPU times: user 7.89 s, sys: 700 ms, total: 8.59 s\nWall time: 5.27 s\n" ], [ "model.save('cats_and_dogs_small_feature_extraction.h5')", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()", "_____no_output_____" ] ], [ [ "This is Overfitting!\n---\nWe can see that the training and validation accuracy curve diverge from each other rather quickly. This alone is might not be a sure shot sign of overfitting. We also observe that the training loss drops smoothly while validation loss actually increases. These two graphs in conjunction with each other indicate overfittig. \n\n**Why did this overfit despite dropout?**\n\nWe did *NOT* do data augmentation", "_____no_output_____" ], [ "Extending the ConvBase Model!\n---\nPros: \n- Better performance (accuracy)\n- Better Generalization (less overfitting) \n - Because we can use data augmentation\n \nCons:\n- Expensive compute\n\n**Warning: Do not attempt this without a GPU. Your Python process can/will crash after a few hours**", "_____no_output_____" ] ], [ [ "from keras import models\nfrom keras import layers\n\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))", "_____no_output_____" ], [ "model.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nvgg16 (Model) (None, 4, 4, 512) 14714688 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 8192) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 256) 2097408 \n_________________________________________________________________\ndense_4 (Dense) (None, 1) 257 \n=================================================================\nTotal params: 16,812,353\nTrainable params: 16,812,353\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### Freezing ConvBase model: VGG16\n\nFreezing means we do not update the layer weights in those particular layers. This is important for our present application.", "_____no_output_____" ] ], [ [ "print('This is the number of trainable weights '\n 'before freezing the conv base:', len(model.trainable_weights))\nconv_base.trainable = False\nprint('This is the number of trainable weights '\n 'after freezing the conv base:', len(model.trainable_weights))", "This is the number of trainable weights before freezing the conv base: 30\nThis is the number of trainable weights after freezing the conv base: 4\n" ], [ "model.summary()\n# compare the Trainable Params value from the previous model summary", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nvgg16 (Model) (None, 4, 4, 512) 14714688 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 8192) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 256) 2097408 \n_________________________________________________________________\ndense_4 (Dense) (None, 1) 257 \n=================================================================\nTotal params: 16,812,353\nTrainable params: 2,097,665\nNon-trainable params: 14,714,688\n_________________________________________________________________\n" ], [ "from keras.preprocessing.image import ImageDataGenerator\n# Note that the validation data should not be augmented!\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\n\n\ntrain_generator = train_datagen.flow_from_directory(\n # This is the target directory\n train_dir,\n # All images will be resized to 150x150\n target_size=(150, 150),\n batch_size=20,\n # Since we use binary_crossentropy loss, we need binary labels\n class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size=(150, 150),\n batch_size=20,\n class_mode='binary')\n\nmodel.compile(loss='binary_crossentropy',\n optimizer=optimizers.RMSprop(lr=2e-5),\n metrics=['acc'])\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=30,\n validation_data=validation_generator,\n validation_steps=50)", "Found 2000 images belonging to 2 classes.\nFound 1000 images belonging to 2 classes.\nEpoch 1/30\n100/100 [==============================] - 21s - loss: 0.4502 - acc: 0.7765 - val_loss: 0.3897 - val_acc: 0.8300\nEpoch 2/30\n100/100 [==============================] - 19s - loss: 0.2768 - acc: 0.8850 - val_loss: 0.2452 - val_acc: 0.8800\nEpoch 3/30\n100/100 [==============================] - 19s - loss: 0.2206 - acc: 0.9125 - val_loss: 0.1886 - val_acc: 0.9290\nEpoch 4/30\n100/100 [==============================] - 19s - loss: 0.1859 - acc: 0.9220 - val_loss: 0.0935 - val_acc: 0.9620\nEpoch 5/30\n100/100 [==============================] - 19s - loss: 0.1645 - acc: 0.9345 - val_loss: 0.0932 - val_acc: 0.9690\nEpoch 6/30\n100/100 [==============================] - 19s - loss: 0.1491 - acc: 0.9360 - val_loss: 0.1048 - val_acc: 0.9640\nEpoch 7/30\n100/100 [==============================] - 19s - loss: 0.1274 - acc: 0.9510 - val_loss: 0.0913 - val_acc: 0.9600\nEpoch 8/30\n100/100 [==============================] - 19s - loss: 0.1197 - acc: 0.9600 - val_loss: 0.2025 - val_acc: 0.9240\nEpoch 9/30\n100/100 [==============================] - 19s - loss: 0.1120 - acc: 0.9575 - val_loss: 0.0896 - val_acc: 0.9600\nEpoch 10/30\n100/100 [==============================] - 19s - loss: 0.0969 - acc: 0.9645 - val_loss: 0.0948 - val_acc: 0.9590\nEpoch 11/30\n100/100 [==============================] - 19s - loss: 0.0805 - acc: 0.9705 - val_loss: 0.1518 - val_acc: 0.9630\nEpoch 12/30\n100/100 [==============================] - 19s - loss: 0.0906 - acc: 0.9665 - val_loss: 0.0750 - val_acc: 0.9780\nEpoch 13/30\n100/100 [==============================] - 19s - loss: 0.0781 - acc: 0.9740 - val_loss: 0.0910 - val_acc: 0.9740\nEpoch 14/30\n100/100 [==============================] - 19s - loss: 0.0626 - acc: 0.9730 - val_loss: 0.0805 - val_acc: 0.9750\nEpoch 15/30\n100/100 [==============================] - 19s - loss: 0.0741 - acc: 0.9700 - val_loss: 0.1032 - val_acc: 0.9670\nEpoch 16/30\n100/100 [==============================] - 19s - loss: 0.0604 - acc: 0.9745 - val_loss: 0.0912 - val_acc: 0.9730\nEpoch 17/30\n100/100 [==============================] - 19s - loss: 0.0565 - acc: 0.9800 - val_loss: 0.1325 - val_acc: 0.9600\nEpoch 18/30\n100/100 [==============================] - 19s - loss: 0.0779 - acc: 0.9730 - val_loss: 0.1325 - val_acc: 0.9470\nEpoch 19/30\n100/100 [==============================] - 19s - loss: 0.0506 - acc: 0.9830 - val_loss: 0.2574 - val_acc: 0.9420\nEpoch 20/30\n100/100 [==============================] - 19s - loss: 0.0556 - acc: 0.9765 - val_loss: 0.1630 - val_acc: 0.9590\nEpoch 21/30\n100/100 [==============================] - 19s - loss: 0.0495 - acc: 0.9850 - val_loss: 0.0704 - val_acc: 0.9720\nEpoch 22/30\n100/100 [==============================] - 19s - loss: 0.0425 - acc: 0.9865 - val_loss: 0.0982 - val_acc: 0.9700\nEpoch 23/30\n100/100 [==============================] - 19s - loss: 0.0599 - acc: 0.9795 - val_loss: 0.1049 - val_acc: 0.9640\nEpoch 24/30\n100/100 [==============================] - 19s - loss: 0.0484 - acc: 0.9845 - val_loss: 0.0848 - val_acc: 0.9750\nEpoch 25/30\n100/100 [==============================] - 19s - loss: 0.0443 - acc: 0.9840 - val_loss: 0.1009 - val_acc: 0.9740\nEpoch 26/30\n100/100 [==============================] - 19s - loss: 0.0521 - acc: 0.9865 - val_loss: 0.1626 - val_acc: 0.9570\nEpoch 27/30\n100/100 [==============================] - 19s - loss: 0.0503 - acc: 0.9815 - val_loss: 0.1116 - val_acc: 0.9570\nEpoch 28/30\n100/100 [==============================] - 19s - loss: 0.0444 - acc: 0.9835 - val_loss: 0.1664 - val_acc: 0.9530\nEpoch 29/30\n100/100 [==============================] - 19s - loss: 0.0513 - acc: 0.9810 - val_loss: 0.0908 - val_acc: 0.9770\nEpoch 30/30\n100/100 [==============================] - 19s - loss: 0.0370 - acc: 0.9890 - val_loss: 0.1158 - val_acc: 0.9720\n" ], [ "acc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()", "_____no_output_____" ], [ "# just for reference, let's calculate the test accuracy\ntest_generator = test_datagen.flow_from_directory(\n test_dir,\n target_size=(150, 150),\n batch_size=20,\n class_mode='binary')\n\n%time test_loss, test_acc = model.evaluate_generator(test_generator, steps=50)\nprint('test acc:', test_acc)", "Found 1000 images belonging to 2 classes.\nCPU times: user 2.2 s, sys: 48 ms, total: 2.24 s\nWall time: 2.63 s\ntest acc: 0.960999994278\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4af22c2faed349801b75a057e5c5f0eb7d33801f
6,812
ipynb
Jupyter Notebook
_notebooks/2021-11-22-{derivation_test}.ipynb
chchin33/violet
048b4c2d3898252bc2dcf01dbf6e8e603509eb3c
[ "Apache-2.0" ]
null
null
null
_notebooks/2021-11-22-{derivation_test}.ipynb
chchin33/violet
048b4c2d3898252bc2dcf01dbf6e8e603509eb3c
[ "Apache-2.0" ]
null
null
null
_notebooks/2021-11-22-{derivation_test}.ipynb
chchin33/violet
048b4c2d3898252bc2dcf01dbf6e8e603509eb3c
[ "Apache-2.0" ]
null
null
null
19.918129
97
0.5069
[ [ [ "import torch\nimport numpy as np", "_____no_output_____" ], [ "ones = torch.ones(5)\nx = torch.tensor([11., 12., 13., 14., 15.])\nX = torch.vstack([ones,x]).T\ny = torch.tensor([17.7, 18.5, 21.2, 23.6, 24.2])", "_____no_output_____" ], [ "W = torch.tensor([3.0,3.0])", "_____no_output_____" ], [ "u = X @ W\nv = y - u\nloss = v.T @ v", "_____no_output_____" ], [ "loss", "_____no_output_____" ], [ "X.T @ -torch.eye(5) @ (2*v)", "_____no_output_____" ], [ "_W = torch.tensor([3. , 3.], requires_grad = True)", "_____no_output_____" ], [ "_loss = (y - X@_W).T @ (y - X@_W)", "_____no_output_____" ], [ "_loss.backward()", "_____no_output_____" ], [ "_W.grad.data", "_____no_output_____" ], [ "v", "_____no_output_____" ], [ "_v = torch.tensor([-18.3000, -20.5000, -20.8000, -21.4000, -23.8000], requires_grad = True)", "_____no_output_____" ], [ "_loss = _v.T @ _v", "_____no_output_____" ], [ "_loss.backward()", "_____no_output_____" ], [ "_v.grad.data, 2*v", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af23ffc3a169af448fb4a4bf250d5c863554a47
2,102
ipynb
Jupyter Notebook
STREAM_SQL_Practice_02.ipynb
sunujh6/spark_practice
f0d0b2cdda91b81a25dfd1f2638e471e67210f58
[ "Apache-2.0" ]
2
2019-07-23T06:24:02.000Z
2020-11-20T14:11:01.000Z
STREAM_SQL_Practice_02.ipynb
sunujh6/spark_practice
f0d0b2cdda91b81a25dfd1f2638e471e67210f58
[ "Apache-2.0" ]
11
2020-03-24T17:28:10.000Z
2022-03-11T23:56:39.000Z
STREAM_SQL_Practice_02.ipynb
sunujh6/spark_practice
f0d0b2cdda91b81a25dfd1f2638e471e67210f58
[ "Apache-2.0" ]
1
2020-04-01T08:24:13.000Z
2020-04-01T08:24:13.000Z
19.64486
58
0.484301
[ [ [ "from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import explode\nfrom pyspark.sql.functions import split\n\nspark = SparkSession \\\n .builder \\\n .appName(\"StructuredStreamingTest\") \\\n .getOrCreate()", "_____no_output_____" ], [ "lines = spark \\\n .readStream \\\n .format(\"socket\") \\\n .option(\"host\", \"localhost\") \\\n .option(\"port\", 9999) \\\n .load()", "_____no_output_____" ], [ "lines.printSchema()", "root\n |-- value: string (nullable = true)\n\n" ], [ "lines.createOrReplaceTempView(\"words\")", "_____no_output_____" ], [ "sqlDF = spark.sql(\"SELECT count(*) FROM words\")\nquery=sqlDF \\\n.writeStream \\\n .outputMode(\"complete\") \\\n .format(\"console\") \\\n .start()", "_____no_output_____" ], [ "query.awaitTermination()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
4af2475445ad28b572a1972a87b131a79f2c8ba7
15,467
ipynb
Jupyter Notebook
notebooks/T11A_Gradient_Descent_In_DL.ipynb
rjl910/sta-663-2021
d9dd12144b7baaf56f235018ac36dd42722035e1
[ "MIT" ]
18
2021-01-19T16:35:54.000Z
2022-01-01T02:12:30.000Z
notebooks/T11A_Gradient_Descent_In_DL.ipynb
rjl910/sta-663-2021
d9dd12144b7baaf56f235018ac36dd42722035e1
[ "MIT" ]
null
null
null
notebooks/T11A_Gradient_Descent_In_DL.ipynb
rjl910/sta-663-2021
d9dd12144b7baaf56f235018ac36dd42722035e1
[ "MIT" ]
24
2021-01-19T16:26:13.000Z
2022-03-15T05:10:14.000Z
27.326855
823
0.504235
[ [ [ "# Gradient Descent Optimizations\n\nMini-batch and stochastic gradient descent is widely used in deep learning, where the large number of parameters and limited memory make the use of more sophisticated optimization methods impractical. Many methods have been proposed to accelerate gradient descent in this context, and here we sketch the ideas behind some of the most popular algorithms.", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimport numpy as np", "_____no_output_____" ] ], [ [ "## Smoothing with exponentially weighted averages", "_____no_output_____" ] ], [ [ "n = 50\nx = np.arange(n) * np.pi\ny = np.cos(x) * np.exp(x/100) - 10*np.exp(-0.01*x)", "_____no_output_____" ] ], [ [ "### Exponentially weighted average\n\nThe exponentially weighted average adds a fraction $\\beta$ of the current value to a leaky running sum of past values. Effectively, the contribution from the $t-n$th value is scaled by\n\n$$\n\\beta^n(1 - \\beta)\n$$\n\nFor example, here are the contributions to the current value after 5 iterations (iteration 5 is the current iteration)\n\n| iteration | contribution |\n| --- | --- |\n| 1 | $\\beta^4(1 - \\beta)$ |\n| 2 | $\\beta^3(1 - \\beta)$ |\n| 3 | $\\beta^2(1 - \\beta)$ |\n| 4 | $\\beta^1(1 - \\beta)$ |\n| 5 | $(1 - \\beta)$ |\n\nSince $\\beta \\lt 1$, the contribution decreases exponentially with the passage of time. Effectively, this acts as a smoother for a function.", "_____no_output_____" ] ], [ [ "def ewa(y, beta):\n \"\"\"Exponentially weighted average.\"\"\"\n \n n = len(y)\n zs = np.zeros(n)\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zs[i] = z\n return zs", "_____no_output_____" ] ], [ [ "### Exponentially weighted average with bias correction\n\nSince the EWA starts from 0, there is an initial bias. This can be corrected by scaling with \n\n$$\n\\frac{1}{1 - \\beta^t}\n$$\n\nwhere $t$ is the iteration number.", "_____no_output_____" ] ], [ [ "def ewabc(y, beta):\n \"\"\"Exponentially weighted average with bias correction.\"\"\"\n \n n = len(y)\n zs = np.zeros(n)\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zc = z/(1 - beta**(i+1))\n zs[i] = zc\n return zs", "_____no_output_____" ], [ "beta = 0.9\n\nplt.plot(x, y, 'o-')\nplt.plot(x, ewa(y, beta), c='red', label='EWA')\nplt.plot(x, ewabc(y, beta), c='orange', label='EWA with bias correction')\nplt.legend()\npass", "_____no_output_____" ] ], [ [ "## Momentum in 1D\n\nMomentum comes from physics, where the contribution of the gradient is to the velocity, not the position. Hence we create an accessory variable $v$ and increment it with the gradient. The position is then updated with the velocity in place of the gradient. The analogy is that we can think of the parameter $x$ as a particle in an energy well with potential energy $U = mgh$ where $h$ is given by our objective function $f$. The force generated is a function of the rat of change of potential energy $F \\propto \\nabla U \\propto \\nabla f$, and we use $F = ma$ to get that the acceleration $a \\propto \\nabla f$. Finally, we integrate $a$ over time to get the velocity $v$ and integrate $v$ to get the displacement $x$. Note that we need to damp the velocity otherwise the particle would just oscillate forever.\n\nWe use a version of the update that simply treats the velocity as an exponentially weighted average popularized by Andrew Ng in his Coursera course. This is the same as the momentum scheme motivated by physics with some rescaling of constants.", "_____no_output_____" ] ], [ [ "def f(x):\n return x**2", "_____no_output_____" ], [ "def grad(x):\n return 2*x", "_____no_output_____" ], [ "def gd(x, grad, alpha, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1] = x\n return xs", "_____no_output_____" ], [ "def gd_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1] = x\n return xs", "_____no_output_____" ] ], [ [ "### Gradient descent with moderate step size", "_____no_output_____" ] ], [ [ "alpha = 0.1\nx0 = 1\nxs = gd(x0, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass", "_____no_output_____" ] ], [ [ "### Gradient descent with large step size\n\nWhen the step size is too large, gradient descent can oscillate and even diverge.", "_____no_output_____" ] ], [ [ "alpha = 0.95\nxs = gd(1, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x*1.2, y, i,\n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass", "_____no_output_____" ] ], [ [ "### Gradient descent with momentum\n\nMomentum results in cancellation of gradient changes in opposite directions, and hence damps out oscillations while amplifying consistent changes in the same direction. This is perhaps clearer in the 2D example below.", "_____no_output_____" ] ], [ [ "alpha = 0.95\nxs = gd_momentum(1, grad, alpha, beta=0.9)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass", "_____no_output_____" ] ], [ [ "## Momentum and RMSprop in 2D", "_____no_output_____" ] ], [ [ "def f2(x):\n return x[0]**2 + 100*x[1]**2", "_____no_output_____" ], [ "def grad2(x):\n return np.array([2*x[0], 200*x[1]])", "_____no_output_____" ], [ "x = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\npass", "_____no_output_____" ], [ "def gd2(x, grad, alpha, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0,:] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1,:] = x\n return xs", "_____no_output_____" ], [ "def gd2_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1, :] = x\n return xs", "_____no_output_____" ] ], [ [ "### Gradient descent with large step size\n\nWe get severe oscillations.", "_____no_output_____" ] ], [ [ "alpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2(x0, grad2, alpha, max_iter=75)", "_____no_output_____" ], [ "x = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Vanilla gradient descent')\npass", "_____no_output_____" ] ], [ [ "### Gradient descent with momentum\n\nThe damping effect is clear.", "_____no_output_____" ] ], [ [ "alpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2_momentum(x0, grad2, alpha, beta=0.9, max_iter=75)", "_____no_output_____" ], [ "x = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradieent descent with momentum')\npass", "_____no_output_____" ] ], [ [ "### Gradient descent with RMSprop\n\nRMSprop scales the learning rate in each direction by the square root of the exponentially weighted sum of squared gradients. Near a saddle or any plateau, there are directions where the gradient is very small - RMSporp encourages larger steps in those directions, allowing faster escape.", "_____no_output_____" ] ], [ [ "def gd2_rmsprop(x, grad, alpha, beta=0.9, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)**2\n x = x - alpha * grad(x) / (eps + np.sqrt(v))\n xs[i+1, :] = x\n return xs", "_____no_output_____" ], [ "alpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_rmsprop(x0, grad2, alpha, beta=0.9, max_iter=10)", "_____no_output_____" ], [ "x = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass", "_____no_output_____" ] ], [ [ "### ADAM\n\nADAM (Adaptive Moment Estimation) combines the ideas of momentum, RMSprop and bias correction. It is probably the most popular gradient descent method in current deep learning practice.", "_____no_output_____" ] ], [ [ "def gd2_adam(x, grad, alpha, beta1=0.9, beta2=0.999, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n m = 0\n v = 0\n for i in range(max_iter):\n m = beta1*m + (1-beta1)*grad(x)\n v = beta2*v + (1-beta2)*grad(x)**2\n mc = m/(1+beta1**(i+1))\n vc = v/(1+beta2**(i+1))\n x = x - alpha * m / (eps + np.sqrt(vc))\n xs[i+1, :] = x\n return xs", "_____no_output_____" ], [ "alpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_adam(x0, grad2, alpha, beta1=0.9, beta2=0.9, max_iter=10)", "_____no_output_____" ], [ "x = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4af24af1fc92586a52dea397c82a1b851f3e6af6
102,906
ipynb
Jupyter Notebook
examples/notebooks/geometry/stick_and_ball.ipynb
s-lunowa/OpenPNM
f176ea2cd76f7879edc7eabe13115a6ba9a8b18e
[ "MIT" ]
1
2021-12-06T03:20:55.000Z
2021-12-06T03:20:55.000Z
examples/notebooks/geometry/stick_and_ball.ipynb
s-lunowa/OpenPNM
f176ea2cd76f7879edc7eabe13115a6ba9a8b18e
[ "MIT" ]
2
2020-06-26T19:58:23.000Z
2021-12-14T07:16:41.000Z
examples/notebooks/geometry/stick_and_ball.ipynb
s-lunowa/OpenPNM
f176ea2cd76f7879edc7eabe13115a6ba9a8b18e
[ "MIT" ]
null
null
null
39.793503
471
0.427069
[ [ [ "# The Stick and Ball Geometry\n\nThe ``SpheresAndCylinders`` class contains an assortment of pore-scale models that generate geometrical information assuming the pores are spherical and throats are cylindrical. \n\nThe ``SpheresAndCylinders`` is a perfect starting point for generating your own custom geometry. In fact, it's likely that only the calculation of 'pore.diameter' would need to be changed. By default the 'pore.diameter' values are drawn from a random distribution which is not very realistic. Luckily, it's easy to update the model used to calculate diameter, and then propagate this change to all the dependent values (i.e. 'pore.volume'), as illustrated below.", "_____no_output_____" ] ], [ [ "import openpnm as op\n%config InlineBackend.figure_formats = ['svg']\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "pn = op.network.Cubic(shape=[20, 20, 20], spacing=100)", "_____no_output_____" ] ], [ [ "> The spacing of the above network is in um for this example to make values easier to read, but in general you should always use SI", "_____no_output_____" ], [ "Now we can create a geometry object based on the ``SpheresAndCylinders``:", "_____no_output_____" ] ], [ [ "geo = op.geometry.SpheresAndCylinders(network=pn, pores=pn.Ps, throats=pn.Ts)", "_____no_output_____" ] ], [ [ "As can be seen by printing it, there are quite a few geometrical properties already added to this object. Defining these manually would have been a pain, so it's a good idea to start with this class then alter the few models that need it:", "_____no_output_____" ] ], [ [ "print(geo)", "――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\nopenpnm.geometry.SpheresAndCylinders : geo_01\n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n# Properties Valid Values\n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n1 pore.area 8000 / 8000 \n2 pore.diameter 8000 / 8000 \n3 pore.max_size 8000 / 8000 \n4 pore.seed 8000 / 8000 \n5 pore.volume 8000 / 8000 \n6 throat.area 22800 / 22800\n7 throat.conduit_lengths.pore1 22800 / 22800\n8 throat.conduit_lengths.pore2 22800 / 22800\n9 throat.conduit_lengths.throat 22800 / 22800\n10 throat.diameter 22800 / 22800\n11 throat.endpoints.head 22800 / 22800\n12 throat.endpoints.tail 22800 / 22800\n13 throat.length 22800 / 22800\n14 throat.max_size 22800 / 22800\n15 throat.surface_area 22800 / 22800\n16 throat.volume 22800 / 22800\n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n# Labels Assigned Locations\n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n1 pore.all 8000 \n2 throat.all 22800 \n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n" ] ], [ [ "The pore size distribution on the ``SpheresAndCylinders`` is probably the more likely thing to change, since it is a random (i.e. uniform distribution) as shown below:", "_____no_output_____" ] ], [ [ "fig = plt.hist(geo['pore.diameter'], bins=25, edgecolor='k')", "_____no_output_____" ] ], [ [ "The models on the ``geo`` object can be seen by printing them:", "_____no_output_____" ] ], [ [ "print(geo.models)", "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n# Property Name Parameter Value\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n1 pore.seed model: random\n element: pore\n num_range: [0.2, 0.7]\n seed: None\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n2 pore.max_size model: largest_sphere\n iters: 10\n fixed_diameter: pore.fixed_diameter\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n3 pore.diameter model: product\n prop1: pore.max_size\n prop2: pore.seed\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n4 pore.area model: sphere\n pore_diameter: pore.diameter\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n5 pore.volume model: sphere\n pore_diameter: pore.diameter\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n6 throat.max_size model: from_neighbor_pores\n mode: min\n prop: pore.diameter\n ignore_nans: True\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n7 throat.diameter model: scaled\n factor: 0.5\n prop: throat.max_size\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n8 throat.endpoints model: spherical_pores\n pore_diameter: pore.diameter\n throat_diameter: throat.diameter\n throat_centroid: throat.centroid\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n9 throat.length model: piecewise\n throat_endpoints: throat.endpoints\n throat_centroid: throat.centroid\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n10 throat.surface_area model: cylinder\n throat_diameter: throat.diameter\n throat_length: throat.length\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n11 throat.volume model: cylinder\n throat_diameter: throat.diameter\n throat_length: throat.length\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n12 throat.area model: cylinder\n throat_diameter: throat.diameter\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n13 throat.conduit_lengths model: conduit_lengths\n throat_endpoints: throat.endpoints\n throat_length: throat.length\n throat_centroid: throat.centroid\n regeneration mode: normal\n―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n" ] ], [ [ "In this tutorial we will change how pore sizes are calculated. We can do this by assigning a new pore-scale model for 'pore.diameter'. Let's use Gaussian distribution:", "_____no_output_____" ] ], [ [ "f = op.models.geometry.pore_size.normal\ngeo.add_model(propname='pore.diameter', \n model=f,\n loc=50, scale=10)", "_____no_output_____" ] ], [ [ "This model is automatically run when it's assigned, so we can inspect the new pore diameter values:", "_____no_output_____" ] ], [ [ "fig = plt.hist(geo['pore.diameter'], bins=25, edgecolor='k')", "_____no_output_____" ] ], [ [ "The above distribution does not look very much like a Gaussian distribution. This is because the 'pore.seed' values are truncated between 0.2 and 0.7:", "_____no_output_____" ] ], [ [ "print(geo.models['pore.seed'])", "――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\nProperty Name Parameter Value\n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\npore.seed model: random\n element: pore\n num_range: [0.2, 0.7]\n seed: None\n regeneration mode: normal\n――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\n" ] ], [ [ "We should change this to a wider range to capture more pores on the \"tails\", then call ``regenerate_models``, which will not only regenerate the random numbers, but all the other properties that depend on it such as 'pore.diameter', 'pore.volume', and so on:", "_____no_output_____" ] ], [ [ "geo.models['pore.seed']['num_range'] = [0.001, 0.999]\ngeo.regenerate_models()\nfig = plt.hist(geo['pore.diameter'], bins=25, edgecolor='k')", "_____no_output_____" ] ], [ [ "A detailed example of adjusting pore-size distributions is given [here](./adjusting_pore_size_distributions.ipynb)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4af24f05f817694280c2e0a2f673b2b596444127
341,129
ipynb
Jupyter Notebook
Missing Values.ipynb
Y-hatter/Customer_satisfaction_airline
557aa408b9d859a67e5eeb1c03f02a1795d67def
[ "MIT" ]
null
null
null
Missing Values.ipynb
Y-hatter/Customer_satisfaction_airline
557aa408b9d859a67e5eeb1c03f02a1795d67def
[ "MIT" ]
null
null
null
Missing Values.ipynb
Y-hatter/Customer_satisfaction_airline
557aa408b9d859a67e5eeb1c03f02a1795d67def
[ "MIT" ]
null
null
null
77.021675
34,376
0.661137
[ [ [ "import os\nos.chdir('D:/IIM/Competitions/Resolvr') # changing working directory to required file location\nos.getcwd()", "_____no_output_____" ], [ "# Importing libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\npal = ['#009786','#7CCC4E', '#1E2A39']\nsns.set(style=\"white\", color_codes=True)\nsns.set_palette(pal)\n%matplotlib inline\n\n\nimport warnings # current version of seaborn generates a bunch of warnings that we'll ignore\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "raw_data = pd.read_excel('Worksheet in Analytics_Case_Resolvr2020.xlsx', sheet_name =\"Case Study 2020\")\nraw_data.head().T", "_____no_output_____" ], [ "raw_data.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 129880 entries, 0 to 129879\nData columns (total 23 columns):\nGender 129880 non-null object\nCustomer Type 129880 non-null object\nAge 129880 non-null int64\nType of Travel 129880 non-null object\nClass 129880 non-null object\nFlight Distance 129880 non-null int64\nInflight wifi service 129876 non-null float64\nDeparture/Arrival time convenient 129876 non-null float64\nEase of Online booking 129877 non-null float64\nGate location 129872 non-null float64\nFood and drink 129875 non-null float64\nOnline boarding 129874 non-null float64\nSeat comfort 129879 non-null float64\nInflight entertainment 129876 non-null float64\nOn-board service 129877 non-null float64\nLeg room service 129878 non-null float64\nBaggage handling 129878 non-null float64\nCheckin service 129877 non-null float64\nInflight service 129879 non-null float64\nCleanliness 129878 non-null float64\nDeparture Delay in Minutes 129880 non-null int64\nArrival Delay in Minutes 129487 non-null float64\nsatisfaction 129880 non-null int64\ndtypes: float64(15), int64(4), object(4)\nmemory usage: 22.8+ MB\n" ], [ "raw_data = raw_data.drop('Customer ID', axis = 1) # insignificant column", "_____no_output_____" ] ], [ [ "### Missing Value Analysis", "_____no_output_____" ] ], [ [ "# Finding proportion of missing variables - overall\n\n# Size and shape of the dataframe\nprint(\"Size of the dataframe:\", raw_data.size)\nprint(\"Shape of the dataframe:\", raw_data.shape)\n\n\n# Overall dataframe\nprint(\"Count of all missing values in dataframe: \", raw_data.isnull().sum().sum())\n\n# Overall % of missing values in the dataframe\nprint(\"% of missing values in dataframe: \", round((raw_data.isnull().sum().sum()/raw_data.size)*100,2),\"%\")\n\n# Overall missing values is < 10%", "Size of the dataframe: 2987240\nShape of the dataframe: (129880, 23)\nCount of all missing values in dataframe: 441\n% of missing values in dataframe: 0.01 %\n" ], [ "# Finding proportion of missing cases\n\n# number of rows\nprint(len(raw_data.index))\n\n# number of rows with missing values\nraw_data.isnull().any(axis=1).sum() # Axis 1 = Rows\n\n# proportion of rows with missing values\nraw_data.isnull().any(axis=1).sum()/len(raw_data.index)*100\n\n# Overall cases with misisng values is < 10%", "129880\n" ], [ "print(\"Percentage of Missing values in each Row (Case):\")\nprint(np.array(raw_data.isnull().mean(axis=1)))\nprint(\"\")\n\n\n# Extracting cases (rows) with missing values\nvalues = np.array(raw_data.isnull().mean(axis=1)*100)\nprint(\"Rows with more than 10% percent\")\nprint(np.where(values > 10))\nprint(\"\")\n\nprint(\"Values in Rows with more than 10% percent\")\nprint(values[values > 10])\n\n# Inference\n# None of the rows have missing value more than 10%", "Percentage of Missing values in each Row (Case):\n[0. 0. 0. ... 0. 0. 0.]\n\nRows with more than 10% percent\n(array([], dtype=int64),)\n\nValues in Rows with more than 10% percent\n[]\n" ], [ "def missing_values_table(df):\n # Total missing values\n mis_val = df.isnull().sum()\n \n # Percentage of missing values\n mis_val_percent = 100 * df.isnull().sum() / len(df)\n \n # Make a table with the results\n mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)\n \n # Rename the columns\n mis_val_table_ren_columns = mis_val_table.rename(\n columns = {0 : 'Missing Values', 1 : '% of Total Values'})\n \n # Sort the table by percentage of missing descending\n mis_val_table_ren_columns = mis_val_table_ren_columns[\n mis_val_table_ren_columns.iloc[:,1] != 0].sort_values(\n '% of Total Values', ascending=False).round(1)\n \n # Print some summary information\n print (\"The selected dataframe has \" + str(df.shape[1]) + \" columns.\\n\" \n \"There are \" + str(mis_val_table_ren_columns.shape[0]) +\n \" columns that have missing values.\")\n \n # Return the dataframe with missing information\n return mis_val_table_ren_columns", "_____no_output_____" ], [ "raw_data_missing= missing_values_table(raw_data)\nraw_data_missing", "The selected dataframe has 23 columns.\nThere are 15 columns that have missing values.\n" ] ], [ [ "The % of missing values is very low, the maximum being 0.3% in Arrival Delay in Minutes", "_____no_output_____" ] ], [ [ "raw_data_nmv = raw_data.dropna() # preparing a dataset with no missing values to perform correlation test", "_____no_output_____" ], [ "from scipy.stats import pearsonr\n\n#Null hypothesis: There is no relation between departure and arrival delay\n#Alt hypothesis: There is relation between departure and arrival delay\n\n# Plotting Scatterplot\nplt.scatter(x = raw_data_nmv['Departure Delay in Minutes'], y = raw_data_nmv['Arrival Delay in Minutes']);\nplt.xlabel('dep');\nplt.ylabel('arr');\nplt.show()\n\n\ncorr, p_val = pearsonr(raw_data_nmv['Departure Delay in Minutes'], raw_data_nmv['Arrival Delay in Minutes'])\nprint(corr,p_val)\nif p_val < 0.05:\n print ('Reject Null Hypothesis')\nelse:\n print ('Retain Null Hypothesis')", "_____no_output_____" ], [ "eq= raw_data_nmv['Departure Delay in Minutes'] == raw_data_nmv['Arrival Delay in Minutes']", "_____no_output_____" ], [ "eq.value_counts() # Approximately 50%", "_____no_output_____" ], [ "raw_data_nmv['diff'] = raw_data_nmv['Arrival Delay in Minutes'] - raw_data_nmv['Departure Delay in Minutes']", "_____no_output_____" ], [ "raw_data_nmv['diff'].describe()", "_____no_output_____" ], [ "raw_data_nmv['diff'].hist(bins=20,range = [-54,54],figsize=(12,8))", "_____no_output_____" ], [ "sns.scatterplot(raw_data_nmv['Departure Delay in Minutes'], raw_data_nmv['diff'])", "_____no_output_____" ], [ "arr_delay_eq = raw_data_nmv.loc[(raw_data_nmv['Departure Delay in Minutes'] == 0) \n & (raw_data_nmv['Arrival Delay in Minutes'] == 0)]\nlen(arr_delay_eq.index)\nprint(\"% of rows where Depature Delay and Arrival delay equal to zero:\", round(len(arr_delay_eq.index)/len(raw_data_nmv.index)*100,2),\"%\")", "% of rows where Depature Delay and Arrival delay equal to zero: 45.84 %\n" ], [ "arr_delay_eq['Flight Distance'].mean()", "_____no_output_____" ], [ "arr_delay_eq['Flight Distance'].describe()", "_____no_output_____" ], [ "arr_delay_mv = raw_data.loc[(raw_data['Departure Delay in Minutes'] == 0) & (raw_data['Arrival Delay in Minutes'].isnull())]\narr_delay_mv[arr_delay_mv['Flight Distance'] <= 1169]", "_____no_output_____" ], [ "# Imputing Arrival Delay with zero where flight distance <= 1169\nidx = np.where((raw_data['Departure Delay in Minutes'] == 0) & (raw_data['Flight Distance'] <= 1169) \n & (raw_data['Arrival Delay in Minutes'].isnull()))\ndata_imp_0 = raw_data.copy()\ndata_imp_0['Arrival Delay in Minutes'].loc[idx] = data_imp_0['Arrival Delay in Minutes'].loc[idx].fillna(0)", "_____no_output_____" ], [ "raw_data_missing= missing_values_table(data_imp_0)\nraw_data_missing\n# 97 missing values in arrival delay imputed with 0", "The selected dataframe has 23 columns.\nThere are 15 columns that have missing values.\n" ], [ "# predicting arrival delay based on departure delay\nfrom sklearn.linear_model import LinearRegression\nX = raw_data_nmv['Departure Delay in Minutes'].values.reshape(-1,1)\nY = raw_data_nmv['Arrival Delay in Minutes'].values.reshape(-1,1)\nlinreg = LinearRegression()\nmodel = linreg.fit(X,Y)\nYhat = model.predict(X)\n\nfrom sklearn.metrics import r2_score\nprint(\"The R-squared for the imputer is :\", round(r2_score(Y, Yhat),2))", "The R-squared for the imputer is : 0.93\n" ], [ "idx = np.where(data_imp_0['Arrival Delay in Minutes'].isnull())\nX_dep = data_imp_0['Departure Delay in Minutes'].loc[idx].values.reshape(-1,1)\nY_pred = model.predict(X_dep)\narr_pred = Y_pred.reshape(296,)", "_____no_output_____" ], [ "plt.scatter(X,Y)\nfig = plt.plot(X_dep,Y_pred, lw=4, c='orange', label ='regression line')\nplt.xlabel('Departure Delay',fontsize=20)\nplt.ylabel('Arrival Delay',fontsize=20)\nplt.show()", "_____no_output_____" ], [ "# our imputer will do fine as the model is a great fit", "_____no_output_____" ], [ "my_list = map(lambda x: x[0], Y_pred)\narr = pd.Series(my_list)", "_____no_output_____" ], [ "arr_val = pd.DataFrame({'Predicted Arrival': arr[:]})\narr_val.head()", "_____no_output_____" ], [ "# imputing with predictions according to linreg\ndata_imp_0['Arrival Delay in Minutes'].loc[idx] = arr_pred", "_____no_output_____" ], [ "data_imp_0['Arrival Delay in Minutes'].isnull().sum()", "_____no_output_____" ], [ "# dropping rest of the missing values\ndata_nmv = data_imp_0.dropna()\ndata_nmv.isnull().sum()", "_____no_output_____" ], [ "data_nmv.head().T", "_____no_output_____" ], [ "data_nmv.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 129840 entries, 0 to 129879\nData columns (total 23 columns):\nGender 129840 non-null object\nCustomer Type 129840 non-null object\nAge 129840 non-null int64\nType of Travel 129840 non-null object\nClass 129840 non-null object\nFlight Distance 129840 non-null int64\nInflight wifi service 129840 non-null float64\nDeparture/Arrival time convenient 129840 non-null float64\nEase of Online booking 129840 non-null float64\nGate location 129840 non-null float64\nFood and drink 129840 non-null float64\nOnline boarding 129840 non-null float64\nSeat comfort 129840 non-null float64\nInflight entertainment 129840 non-null float64\nOn-board service 129840 non-null float64\nLeg room service 129840 non-null float64\nBaggage handling 129840 non-null float64\nCheckin service 129840 non-null float64\nInflight service 129840 non-null float64\nCleanliness 129840 non-null float64\nDeparture Delay in Minutes 129840 non-null int64\nArrival Delay in Minutes 129840 non-null float64\nsatisfaction 129840 non-null int64\ndtypes: float64(15), int64(4), object(4)\nmemory usage: 23.8+ MB\n" ], [ "data_nmv.describe().T", "_____no_output_____" ], [ "# segregating on the basis of measurement scale\nratio = data_nmv[['Age','Flight Distance','Departure Delay in Minutes', 'Arrival Delay in Minutes']]\nnominal = data_nmv[['Gender','Customer Type','Type of Travel']]\nordinal = data_nmv[['Class']]\ninterval = data_nmv.iloc[:,6:20]", "_____no_output_____" ], [ "data_nmv[ratio.columns] = data_nmv[ratio.columns].astype('int64')", "_____no_output_____" ] ], [ [ "### Exploratory Data Analysis", "_____no_output_____" ] ], [ [ "sns.FacetGrid(data_nmv, hue=\"satisfaction\", size=7) \\\n.map(plt.hist, \"Inflight wifi service\") \\\n.add_legend()\nplt.title('Good Inflight wifi service - more satisfied customers')\nplt.show()", "_____no_output_____" ], [ "ratio.hist(bins=50,figsize = (14,8))", "_____no_output_____" ], [ "fig, ax = plt.subplots(2, 2, figsize=(14, 8))\nfor variable, subplot in zip(ratio, ax.flatten()):\n sns.boxplot(y = ratio[variable], ax=subplot)", "_____no_output_____" ], [ "# Apart from age all others have outliers. Number of outliers is huge in Departure and Arrival Delay.", "_____no_output_____" ], [ "sns.boxplot(data_nmv['satisfaction'],data_nmv['Departure Delay in Minutes'])", "_____no_output_____" ], [ "x = np.log10((data_nmv['Departure Delay in Minutes'])+1)", "_____no_output_____" ], [ "sns.boxplot(x)", "_____no_output_____" ], [ "#data_nmv['ln(Departure Delay in Minutes)'] = np.log10((data_nmv['Departure Delay in Minutes'])+1)", "_____no_output_____" ], [ "box = plt.boxplot(x , patch_artist=True);\nplt.xlabel('Departure delay', fontsize=10);\nplt.grid();", "_____no_output_____" ], [ "[whiskers.get_ydata()[0] for whiskers in box[\"whiskers\"]]", "_____no_output_____" ], [ "[item.get_ydata()[0] for item in box['caps']]", "_____no_output_____" ], [ "[median.get_ydata()[0] for median in box[\"medians\"]]", "_____no_output_____" ], [ "[flier.get_ydata()[0] for flier in box[\"fliers\"]]", "_____no_output_____" ], [ "[flier.get_ydata() for flier in box[\"fliers\"]]", "_____no_output_____" ], [ "#sns.distplot(data_nmv[data_nmv['satisfaction'] == 1]['ln(Departure Delay in Minutes)'],color = 'y',label = 'satisfaction: Yes')\n#sns.distplot(data_nmv[data_nmv['satisfaction'] == 0]['ln(Departure Delay in Minutes)'],color = 'r',label = 'satisfaction: No');\n#plt.legend();", "_____no_output_____" ], [ "data_nmv.to_csv(\"resolvr.csv\", index = False)", "_____no_output_____" ], [ "counts = data_nmv.groupby(['Class', 'satisfaction']).satisfaction.count().unstack()\ncounts.plot(kind='bar', stacked=True,figsize = (10,8), fontsize = 12)\nplt.xticks(rotation=0,fontsize = 15)\nplt.xlabel('Class', fontsize=18)\nplt.rcParams['legend.title_fontsize'] = 'xx-large'\nplt.legend(title=\"satisfaction\",fontsize = \"x-large\",loc = 1)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "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" ] ]
4af27238a13875b16f4bd472043c3a0fd8118ed6
7,352
ipynb
Jupyter Notebook
tutorials/04_train_and_query_language_model.ipynb
ikou-austin/exkaldi
437dd8a121baf8e682850374df3eade5ae53fda4
[ "Apache-2.0" ]
1
2020-10-14T13:55:53.000Z
2020-10-14T13:55:53.000Z
tutorials/04_train_and_query_language_model.ipynb
ikou-austin/exkaldi
437dd8a121baf8e682850374df3eade5ae53fda4
[ "Apache-2.0" ]
null
null
null
tutorials/04_train_and_query_language_model.ipynb
ikou-austin/exkaldi
437dd8a121baf8e682850374df3eade5ae53fda4
[ "Apache-2.0" ]
null
null
null
23.947883
256
0.573449
[ [ [ "# Welcome to Exkaldi\n\nIn this section, we will train a n-grams language model and query it.\n\nAlthrough __Srilm__ is avaliable in exkaldi, we recommend __Kenlm__ toolkit.", "_____no_output_____" ] ], [ [ "import exkaldi\n\nimport os\ndataDir = \"librispeech_dummy\"", "_____no_output_____" ] ], [ [ "Firstly, prepare the lexicons. We have generated and saved a __LexiconBank__ object in file already (3_prepare_lexicons). So restorage it directly.", "_____no_output_____" ] ], [ [ "lexFile = os.path.join(dataDir, \"exp\", \"lexicons.lex\")\n\nlexicons = exkaldi.load_lex(lexFile)\n\nlexicons", "_____no_output_____" ] ], [ [ "We will use training text corpus to train LM model. Even though we have prepared a transcription file in the data directory, we do not need the utterance-ID information at the head of each line, so we must take a bit of work to produce a new text.\n\nWe can lend a hand of the exkaldi __Transcription__ class.", "_____no_output_____" ] ], [ [ "textFile = os.path.join(dataDir, \"train\", \"text\")\n\ntrans = exkaldi.load_transcription(textFile)\n\ntrans", "_____no_output_____" ], [ "newTextFile = os.path.join(dataDir, \"exp\", \"train_lm_text\")\n\ntrans.save(fileName=newTextFile, discardUttID=True)", "_____no_output_____" ] ], [ [ "But actually, you don't need do this. If you use a __Transcription__ object to train the language model, the information of utterance ID will be discarded automatically.", "_____no_output_____" ], [ "Now we train a 2-grams model with __Kenlm__ backend. (__srilm__ backend is also avaliable.)", "_____no_output_____" ] ], [ [ "arpaFile = os.path.join(dataDir, \"exp\", \"2-gram.arpa\")\n\nexkaldi.lm.train_ngrams_kenlm(lexicons, order=2, text=trans, outFile=arpaFile, config={\"-S\":\"20%\"})", "_____no_output_____" ] ], [ [ "ARPA model can be transform to binary format in order to accelerate loading and reduce memory cost. \nAlthough __KenLm__ Python API supports reading ARPA format, but in exkaldi, we only expected KenLM Binary format.", "_____no_output_____" ] ], [ [ "binaryLmFile = os.path.join(dataDir, \"exp\", \"2-gram.binary\")\n\nexkaldi.lm.arpa_to_binary(arpaFile, binaryLmFile)", "_____no_output_____" ] ], [ [ "Use the binary LM file to initialize a Python KenLM n-grams object.", "_____no_output_____" ] ], [ [ "model = exkaldi.lm.KenNGrams(binaryLmFile)\n\nmodel", "_____no_output_____" ] ], [ [ "__KenNGrams__ is simple wrapper of KenLM python Model. Check model information:", "_____no_output_____" ] ], [ [ "model.info", "_____no_output_____" ] ], [ [ "You can query this model with a sentence.", "_____no_output_____" ] ], [ [ "model.score_sentence(\"HELLO WORLD\", bos=True, eos=True)", "_____no_output_____" ] ], [ [ "There is a example to compute the perplexity of test corpus in order to evaluate the language model.", "_____no_output_____" ] ], [ [ "evalTrans = exkaldi.load_transcription( os.path.join(dataDir, \"test\", \"text\") )\n\nscore = model.perplexity(evalTrans)\n\nscore", "_____no_output_____" ], [ "type(score)", "_____no_output_____" ] ], [ [ "___score___ is an exkaldi __Metric__ (a subclass of Python dict) object. \n\nWe design a group of classes to hold Kaldi text format table and exkaldi own text format data:\n\n__ListTable__: spk2utt, utt2spk, words, phones and so on. \n__Transcription__: transcription corpus, n-best decoding result and so on. \n__Metric__: AM score, LM score, LM perplexity, Sentence lengthes and so on. \n__ArkIndexTable__: The index of binary data. \n__WavSegment__: The wave information. \n\nAll these classes are subclasses of Python dict. They have some common and respective methods and attributes. \n\nIn this case, for example, we can compute the average value of __Metric__.", "_____no_output_____" ] ], [ [ "score.mean()", "_____no_output_____" ] ], [ [ "More precisely, the weighted average by the length os sentences.", "_____no_output_____" ] ], [ [ "score.mean( weight= evalTrans.sentence_length() )", "_____no_output_____" ] ], [ [ "Back to Language Model. If you want to use query ARPA model directly. You can use this function.", "_____no_output_____" ] ], [ [ "model = exkaldi.load_ngrams(arpaFile)\n\nmodel.info", "_____no_output_____" ] ], [ [ "As the termination of this section, we generate the Grammar fst for futher steps.", "_____no_output_____" ] ], [ [ "Gfile = os.path.join(dataDir, \"exp\", \"G.fst\")\n\nexkaldi.decode.graph.make_G(lexicons, arpaFile, outFile=Gfile, order=2)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af279aaaac906be441b1209d62ccac0b6328229
557,114
ipynb
Jupyter Notebook
manuscript/1.0_panels-F4.ipynb
ggirelli/deconwolf-in-situ-transcriptomics
bd3f99e849c2a7476f97e49ad57d6d237bb04256
[ "MIT" ]
null
null
null
manuscript/1.0_panels-F4.ipynb
ggirelli/deconwolf-in-situ-transcriptomics
bd3f99e849c2a7476f97e49ad57d6d237bb04256
[ "MIT" ]
null
null
null
manuscript/1.0_panels-F4.ipynb
ggirelli/deconwolf-in-situ-transcriptomics
bd3f99e849c2a7476f97e49ad57d6d237bb04256
[ "MIT" ]
null
null
null
620.394209
209,988
0.930029
[ [ [ "require(cowplot)\nrequire(data.table)\nrequire(ggplot2)\nrequire(ggpubr)\nrequire(pbapply)\npboptions(type=\"timer\")", "Loading required package: cowplot\n\nLoading required package: data.table\n\nLoading required package: ggplot2\n\nLoading required package: ggpubr\n\n\nAttaching package: ‘ggpubr’\n\n\nThe following object is masked from ‘package:cowplot’:\n\n get_legend\n\n\nLoading required package: pbapply\n\n" ], [ "nthreads=10\nx_breaks = c(0, .01, .02, .03, .05, .07, .1, .2, .3, .5, .7, 1, 2, 3, 5, 7, 10, 20, 30, 50)", "_____no_output_____" ] ], [ [ "# Read spot data", "_____no_output_____" ] ], [ [ "thresholds = c(seq(0, .1, by=.01), seq(.2, 1, by=.1), seq(2, 50))\ndw__root = \"../data/single_FoV_different_thresholds/data/dw/\"\nraw_root = \"../data/single_FoV_different_thresholds/data/raw/\"", "_____no_output_____" ], [ "dw__data = rbindlist(pblapply(thresholds, function(thr) {\n d = fread(file.path(dw__root, sprintf(\"new_decoded_human_cortex_threshold_%05.2f_with_QC_metrics_type_of_unassigned.csv.gz\", thr)))\n d$thr = thr\n d$image_type = \"dw\"\n return(d)\n}, cl=nthreads))", " |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=05s \n" ], [ "raw_data = rbindlist(pblapply(thresholds, function(thr) {\n d = fread(file.path(raw_root, sprintf(\"new_decoded_human_cortex_before_deconvolution_threshold_%05.2f_with_QC_metrics_type_of_unassigned.csv.gz\", thr)))\n d$thr = thr\n d$image_type = \"raw\"\n return(d)\n}, cl=nthreads))", " |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=04s \n" ], [ "ddata = rbindlist(list(dw__data, raw_data))\nddata[, V1 := NULL]\nddata[, target_assigned := \"unassigned\"]\nddata['nan' != target, target_assigned := \"assigned\"]", "_____no_output_____" ], [ "colnames(ddata)", "_____no_output_____" ], [ "gene_counts = dcast(ddata[\"assigned\" == target_assigned, .N, by=c(\"image_type\", \"target\", \"thr\")],\n target+thr~image_type, value.var=\"N\")[order(dw, decreasing=T)]\ncolnames(gene_counts)", "_____no_output_____" ] ], [ [ "# Read strip data", "_____no_output_____" ] ], [ [ "cell_data = rbindlist(pblapply(c(\"dw\", \"raw\"), function(image_type) {\n d = fread(file.path(\"../data/strip_of_tissue\", image_type, \"MP_snRNAseq_filt_subclass.csv\"))\n d$image_type = image_type\n return(d)\n}, cl=nthreads))\ncell_data[, V1 := NULL]\ncell_data[, annotated := \"unannotated\"]\ncell_data[\"Zero\" != ClassName, annotated := \"annotated\"]\ncell_data[\"dw\" == image_type, image_type := \"DW\"]\ncolnames(cell_data)", " |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=00s \n" ] ], [ [ "# Panel 4A\nCounts of assigned/unassigned/total dots per threshold.", "_____no_output_____" ] ], [ [ "pdata = rbindlist(list(\n ddata[, .N, by=c(\"image_type\", \"thr\", \"target_assigned\")],\n ddata[, .(target_assigned=\"total\", .N), by=c(\"image_type\", \"thr\")]\n))\nsetnames(pdata, \"target_assigned\", \"variable\")\npdata[, variable := factor(variable, levels=c(\"total\", \"assigned\", \"unassigned\"))]\npdata[\"dw\" == image_type, image_type := \"DW\"]", "_____no_output_____" ], [ "options(repr.plot.width=9, repr.plot.height=6)\np = ggplot(pdata[variable != \"total\"], aes(x=thr+.001, y=N, linetype=variable, color=image_type)) +\n geom_vline(xintercept=c(2), color=\"orange\", linetype=\"solid\") +\n geom_line() + geom_point(size=.5) +\n theme_bw() + scale_y_log10() + scale_x_log10(breaks=x_breaks+.001, labels=x_breaks) +\n theme(axis.text.x=element_text(angle=90, hjust=1, vjust=.5), legend.position=\"top\") +\n scale_fill_grey() + labs(x=\"Threshold\", y=\"Absolute dot count\", linetype=\"Dot type\", color=\"Image type\") +\n scale_color_brewer(palette=\"Set1\") +\n geom_vline(xintercept=c(.15, 1.5), color=\"black\", linetype=\"dotted\")\nprint(p)", "_____no_output_____" ], [ "ggsave(plot=p, file=\"panels/fig_4a.png\", width=4, height=4)\nsaveRDS(p, \"panels_rds/fig_4a.rds\")", "_____no_output_____" ] ], [ [ "# Panel 4b-c\nVisualization of transcript spots in a field of view, RAW and DW.\nField #13, with highest delta (804). ALL transcripts, QC_score > .6.", "_____no_output_____" ] ], [ [ "pdata = ddata[thr==2]", "_____no_output_____" ], [ "pdata[, target := factor(target)]\npdata[, target_nr := as.numeric(target)]", "_____no_output_____" ], [ "require(viridis)\noptions(repr.plot.width=6, repr.plot.height=6)\npB = ggplot(pdata[FOV %in% sprintf(\"fov_%03d\", c(3)) & QC_score >= .6 & !is.na(target) & image_type == \"raw\", .(x, y, target_nr, FOV, image_type)],\n aes(x=x, y=y, color=target_nr)) + geom_point(size=1) +\n theme_bw() + theme(\n legend.position=\"top\",\n panel.grid.major=element_blank(), panel.grid.minor=element_blank(),\n panel.background=element_rect(fill=\"black\"),\n axis.ticks.x=element_blank(), axis.ticks.y=element_blank(),\n axis.text.x=element_blank(), axis.text.y=element_blank()\n ) +\n labs(x=\"\", y=\"\", color=\"Transcript Nr.\") +\n coord_fixed() + scale_color_gradient(low=\"white\", high=\"red\") +\n guides(color=guide_colorbar(title.position=\"top\", barwidth=20))\nprint(pB)", "Loading required package: viridis\n\nLoading required package: viridisLite\n\n" ], [ "ggsave(plot=pB, file=\"panels/fig_4b.png\", width=4, height=4)\nsaveRDS(pB, \"panels_rds/fig_4b.rds\")", "_____no_output_____" ], [ "require(viridis)\noptions(repr.plot.width=6, repr.plot.height=6)\npC = ggplot(pdata[FOV %in% sprintf(\"fov_%03d\", c(3)) & QC_score >= .6 & !is.na(target) & image_type == \"dw\", .(x, y, target_nr, FOV, image_type)],\n aes(x=x, y=y, color=target_nr)) + geom_point(size=1) +\n theme_bw() + theme(\n legend.position=\"top\",\n panel.grid.major=element_blank(), panel.grid.minor=element_blank(),\n panel.background=element_rect(fill=\"black\"),\n axis.ticks.x=element_blank(), axis.ticks.y=element_blank(),\n axis.text.x=element_blank(), axis.text.y=element_blank()\n ) +\n labs(x=\"\", y=\"\", color=\"Transcript Nr.\") +\n coord_fixed() + scale_color_gradient(low=\"white\", high=\"red\") +\n guides(color=guide_colorbar(title.position=\"top\", barwidth=20))\nprint(pC)", "_____no_output_____" ], [ "ggsave(plot=pC, file=\"panels/fig_4c.png\", width=4, height=4)\nsaveRDS(pC, \"panels_rds/fig_4c.rds\")", "_____no_output_____" ] ], [ [ "# Panel 4d\nTranscript counts of DW vs Raw.", "_____no_output_____" ] ], [ [ "options(repr.plot.width=6, repr.plot.height=6)\np = ggplot(gene_counts[thr==2], aes(raw, dw)) + geom_point() +\n scale_x_log10() + scale_y_log10() + theme_bw() +\n geom_abline(slope=1, linetype=\"dashed\", color=\"red\") +\n labs(x=\"Absolute transcript count (raw)\", y=\"Absolute transcript count (DW)\")\nprint(p)", "Warning message:\n“Removed 10 rows containing missing values (geom_point).”\n" ], [ "ggsave(plot=p, file=\"panels/fig_4d.png\", width=4, height=4)\nsaveRDS(p, \"panels_rds/fig_4d.rds\")", "Warning message:\n“Removed 10 rows containing missing values (geom_point).”\n" ], [ "summary(gene_counts[thr==2, (dw/raw-1)*100])\nsummary(gene_counts[thr==2 & dw/raw>1, (dw/raw-1)*100])\ngene_counts[thr==2 & dw/raw>1, .N]\ngene_counts[thr==2 & dw/raw==1, .N]\ngene_counts[thr==2 & dw/raw<1, .N]\ngene_counts[thr==2 & is.na(dw/raw)]", "_____no_output_____" ] ], [ [ "# Panel 4e\nNumber of un/annotated cells", "_____no_output_____" ] ], [ [ "cell_data[, .N, by=c(\"annotated\", \"image_type\")][, .(image_type, annotated, N, N/2183)]", "_____no_output_____" ], [ "options(repr.plot.width=6, repr.plot.height=4)\np = ggplot(cell_data[, .N, by=c(\"annotated\", \"image_type\")], aes(x=annotated, y=N, fill=image_type)) +\n geom_col(position=\"dodge\", color=\"#323232\") +\n theme_bw() + theme(legend.position=\"bottom\") +\n scale_fill_brewer(\"Image type\", palette=\"Set2\") +\n labs(x=\"Cell type\", y=\"Absolute cell count\")\nprint(p)", "_____no_output_____" ], [ "ggsave(plot=p, file=\"panels/fig_4e.png\", width=4, height=4)\nsaveRDS(p, \"panels_rds/fig_4e.rds\")", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4af279b0367fabefa4de541c54c9792721a09ad1
129,657
ipynb
Jupyter Notebook
coding snippets/lecture_8_snippets/Lecture 8.ipynb
marctollis/INF110-Discovering-Informatics
bb80c14f7a56a694b1c134d372ad359d62a471d4
[ "MIT" ]
null
null
null
coding snippets/lecture_8_snippets/Lecture 8.ipynb
marctollis/INF110-Discovering-Informatics
bb80c14f7a56a694b1c134d372ad359d62a471d4
[ "MIT" ]
null
null
null
coding snippets/lecture_8_snippets/Lecture 8.ipynb
marctollis/INF110-Discovering-Informatics
bb80c14f7a56a694b1c134d372ad359d62a471d4
[ "MIT" ]
null
null
null
281.251627
52,340
0.890773
[ [ [ "from datascience import *\nimport numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plots\nplots.style.use('fivethirtyeight')\n", "_____no_output_____" ] ], [ [ "# Actors\n\nWe want to load a table with gross income and number of movies", "_____no_output_____" ] ], [ [ "actors = Table().read_table(\"actors.csv\")\nactors", "_____no_output_____" ], [ "actors.scatter(\"Number of Movies\", \"Total Gross\")", "_____no_output_____" ], [ "movies = Table().read_table(\"movies_by_year.csv\")\nmovies", "_____no_output_____" ], [ "movies.plot(\"Year\", \"Number of Movies\")", "_____no_output_____" ], [ "movie_cat = Table().read_table(\"movie_cat.csv\")\nmovie_cat", "_____no_output_____" ], [ "movie_cat.barh(\"Kind\", \"Number\")", "_____no_output_____" ], [ "movies = Table().read_table(\"top_movies.csv\")\nmovies", "_____no_output_____" ], [ "movies_by_studio = movies.group(\"Studio\")\nmovies_by_studio", "_____no_output_____" ], [ "movies_by_studio.sort(\"count\", descending=True).barh(\"Studio\", \"count\")", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af2984e4ab61eee246d8a4ddae8bf678e483842
996
ipynb
Jupyter Notebook
src/extract_demo.ipynb
brando90/isabelle-gym
f4d231cb9f625422e873aa2c9c2c6f22b7da4b27
[ "MIT" ]
null
null
null
src/extract_demo.ipynb
brando90/isabelle-gym
f4d231cb9f625422e873aa2c9c2c6f22b7da4b27
[ "MIT" ]
1
2021-06-22T15:34:13.000Z
2021-06-22T15:34:13.000Z
src/extract_demo.ipynb
brando90/isabelle-gym
f4d231cb9f625422e873aa2c9c2c6f22b7da4b27
[ "MIT" ]
null
null
null
17.172414
76
0.504016
[ [ [ "import proof_extract", "_____no_output_____" ], [ "proof_extract.open_isar_file(\"../isabelle_theories/mp1.thy\",\"mp1\")", "ok\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4af29cab3949d66e3d9c33ab01a4f4727987c839
1,138
ipynb
Jupyter Notebook
_00_rethink_stats_week9.ipynb
danhphan/bayesian_inferences
d5976f7fde560b0d0bd47c0144d87724d4ac96b3
[ "Apache-2.0" ]
null
null
null
_00_rethink_stats_week9.ipynb
danhphan/bayesian_inferences
d5976f7fde560b0d0bd47c0144d87724d4ac96b3
[ "Apache-2.0" ]
null
null
null
_00_rethink_stats_week9.ipynb
danhphan/bayesian_inferences
d5976f7fde560b0d0bd47c0144d87724d4ac96b3
[ "Apache-2.0" ]
null
null
null
21.471698
98
0.561511
[ [ [ "import arviz as az\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pymc3 as pm\n\nfrom scipy import stats\nfrom scipy.special import expit as logistic\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\n%config InlineBackend.figure_format = 'retina'\nRANDOM_SEED = 8927\nnp.random.seed(RANDOM_SEED)\naz.style.use(\"arviz-darkgrid\")\n%matplotlib inline", "WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
4af2c4eab824f962ebbbe790a956e53734618c7b
13,713
ipynb
Jupyter Notebook
.ipynb_checkpoints/Chapter 2 | Text Normalization-checkpoint.ipynb
samacker77/NLP-Starter-Bundle
bb7d1acc99e0d91e750e50cdff2f40b938f1c0f7
[ "Apache-2.0" ]
60
2020-06-28T12:40:16.000Z
2022-03-08T21:02:20.000Z
.ipynb_checkpoints/Chapter 2 | Text Normalization-checkpoint.ipynb
samacker77/NLP-Starter-Bundle
bb7d1acc99e0d91e750e50cdff2f40b938f1c0f7
[ "Apache-2.0" ]
null
null
null
.ipynb_checkpoints/Chapter 2 | Text Normalization-checkpoint.ipynb
samacker77/NLP-Starter-Bundle
bb7d1acc99e0d91e750e50cdff2f40b938f1c0f7
[ "Apache-2.0" ]
21
2020-06-28T20:27:25.000Z
2021-06-08T10:24:00.000Z
28.10041
314
0.543645
[ [ [ " <h1 style=\"text-align:center\">Chapter 2</h1>\n \n ---", "_____no_output_____" ], [ "###### Words\n---\n\nTake a look at this sentence :\n\n'The quick brown fox jumps over the lazy fox, and took his meal.'\n\n* The sentence has 13 _Words_ if you don't count punctuations, and 15 if you count punctions. \n\n* To count punctuation as a word or not depends on the task in hand.\n\n* For some tasks like P-O-S tagging & speech synthesis, punctuations are treated as words. (Hello! and Hello? are different in speech synthesis)", "_____no_output_____" ] ], [ [ "len('The quick brown fox jumps over the lazy fox, and took his meal.'.split())", "_____no_output_____" ] ], [ [ "##### Utterance\n\n> An utterance is a spoken correlate of a sentence. (Speaking a sentence is utterance)\n\nTake a look at this sentence:\n\n'I am goi- going to the market to buy ummm fruits.'\n\n* This utterance has two kinds of <strong>disfluencies</strong>(disorder in smooth flow).\n\n1. Fragment - The broken off word 'goi' is a fragment.\n2. Fillers - Words like ummm, uhhh, are called fillers or filled pauses.\n", "_____no_output_____" ], [ "##### Lemma\n\n> A lemma is a set of lexical forms having the same stem, the same major part-of-speech, and the same word sense.\n\n* Wordform is the full inflected or derived form of the word.\n\nExample,\n\nWordforms - cats,cat\n\nLemma - cat\n\nWordforms - Moving, move\n\nLemma - move", "_____no_output_____" ], [ "##### Vocabulary, Wordtypes, and Wordtokens\n\n* Vocabulary - It is the set of distinct words in a corpus.\n\n* Wordtypes - It is the size of the vocabulary V i.e. |V|\n\n* Wordtokens - It is the total number of running words.\n\nTake a look at this sentence:\n\n'They picnicked by the pool, then lay back on the grass and looked at the stars.'\n\nHere,\n\n* Vocabulary = V = {They, picnicked, by, the, pool, then, lay, back, on, grass, and, looked, at, stars}\n\n* Wordtypes = |V| = 14\n\n* Wordtokens(ignoring punctuation) = 16", "_____no_output_____" ] ], [ [ "def vocTypeToken(sentence):\n tokens = sentence.split()\n vocabulary = list(set(tokens))\n wordtypes = len(vocabulary)\n wordtokens = len(tokens)\n print(\"Sentence = {}\\n\".format(sentence))\n print(\"Tokens = {}\\n\".format(tokens))\n print(\"Vocabulary = {}\\n\".format(sorted(vocabulary)))\n print(\"Wordtypes = {}\\n\".format(wordtypes))\n print(\"Wordtokens = {}\".format(wordtokens))", "_____no_output_____" ], [ "sentence = 'They picnicked by the pool, then lay back on the grass and looked at the stars.'\nvocTypeToken(sentence)", "Sentence = They picnicked by the pool, then lay back on the grass and looked at the stars.\n\nTokens = ['They', 'picnicked', 'by', 'the', 'pool,', 'then', 'lay', 'back', 'on', 'the', 'grass', 'and', 'looked', 'at', 'the', 'stars.']\n\nVocabulary = ['They', 'and', 'at', 'back', 'by', 'grass', 'lay', 'looked', 'on', 'picnicked', 'pool,', 'stars.', 'the', 'then']\n\nWordtypes = 14\n\nWordtokens = 16\n" ] ], [ [ "###### Herdan's Law\n\n> The larger the corpora we look at, the more wordtypes we find. The relationsip between wordtypes and tokens is called <strong>Herdan's Law</strong>\n\n\\begin{equation*}\n|V| = kN^\\beta \n\\end{equation*}\n, k and \\\\(\\beta\\\\) are positive consonants.\n\nThe value of \\\\(\\beta\\\\) depends on the corpus size and is in the range of 0 to 1.\n\n* We can say that the vocabulary size for a text goes up significantly faster than the square root of its length in words.\n---\n\n- Another rough measure of number of words in a corpus is the number of lemmas.", "_____no_output_____" ], [ "##### Code switching\n\n> The phenonmenon of changing lanugage while reading or writing is called code switching.\n\nExample,\n\n'Tu mera dost hai or rahega, don't worry.'", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "## Text Normalization\n---", "_____no_output_____" ], [ "Before any type of natural language processing, the text has to be brought a normal condition or state.\n\nThe below mentioned three tasks are common for almost every normalization process.\n\n1. Tokenizing ( breaking into words )\n2. Normalizing word formats\n3. Segmenting sentences", "_____no_output_____" ], [ "### Word tokenization\n---", "_____no_output_____" ], [ "> The task of segmenting text into words.\n\n<p style=\"color:red\">Why you should not use split() for tokenizaiton.</p>\n\nIf using split() on the text, the words like 'Mr. Randolf', emails like '[email protected]' may be broken down as ['Mr.','Randolf'], emails may be broken down as ['hello','@','internet','.','com'].\n\nThis is not what we generally want, hence special tokenization algorithms must be used.\n\n* Commas are generally used as word boundaries but also in large numbers (540,000).\n* Periods are generally used as sentence boundaries but also in emails, urls, salutation.", "_____no_output_____" ], [ "##### Clitic\n\n> Clitics are words that can't stand on their own. They are attached to other words. Tokenizer can be used to expand clitics.\n\nExample of clitics,\n\nWhat're, Who's, You're.\n\n\n- Tokenization algorithms can also be used to tokenize multiwords like 'New York', 'rock N roll'.\n\nThis tokenization is used in conjunction with <strong>Named Entity Detection</strong> (the task of detecting name, places, dates, organizations)\n\n\nPython code for tokenization below", "_____no_output_____" ] ], [ [ "from nltk.tokenize import word_tokenize", "_____no_output_____" ], [ "text = 'The San Francisco-based restaurant,\" they said, \"doesn’t charge $10\".'", "_____no_output_____" ], [ "print(word_tokenize(text))", "['The', 'San', 'Francisco-based', 'restaurant', ',', \"''\", 'they', 'said', ',', '``', 'doesn', '’', 't', 'charge', '$', '10', \"''\", '.']\n" ], [ "from nltk.tokenize import wordpunct_tokenize", "_____no_output_____" ], [ "print(wordpunct_tokenize(text))", "['The', 'San', 'Francisco', '-', 'based', 'restaurant', ',\"', 'they', 'said', ',', '\"', 'doesn', '’', 't', 'charge', '$', '10', '\".']\n" ] ], [ [ "Since tokenization needs to run before any language processing, it needs to be fast.\n\nRegex based tokenization is fast but not that smart while handling punctuations, and language dilemma. \nThere are many tokenization algorithms like ByteLevelBPETokenizer, CharBPETokenizer, SentencePieceBPETokenizer.\n\nBelow excercise shows step by step guide to modern way of tokenization using [huggingface's](https://huggingface.co/) ultrafast tokenization library - [Tokenizer](https://github.com/huggingface/tokenizers)\n \n---", "_____no_output_____" ], [ "#### Notice the speed of huggingface tokenizer and nltk tokenizer", "_____no_output_____" ] ], [ [ "!python3 -m pip install tokenizers #install tokenizer", "Requirement already satisfied: tokenizers in /opt/anaconda3/lib/python3.7/site-packages (0.7.0)\r\n" ], [ "from tokenizers import (BertWordPieceTokenizer)\ntokenizer = BertWordPieceTokenizer(\"bert-base-uncased-vocab.txt\", lowercase=True)", "_____no_output_____" ], [ "from datetime import datetime\ndef textTokenizer(text):\n start = (datetime.now())\n print(tokenizer.encode(text).tokens)\n end = (datetime.now())\n print(\"Time taken - {}\".format((end-start).total_seconds()))\n \n ", "_____no_output_____" ], [ "textTokenizer('Number expressions introduce other complications as well; while commas nor- mally appear at word boundaries, commas are used inside numbers in English, every three digits.')", "['[CLS]', 'number', 'expressions', 'introduce', 'other', 'complications', 'as', 'well', ';', 'while', 'com', '##mas', 'nor', '-', 'mall', '##y', 'appear', 'at', 'word', 'boundaries', ',', 'com', '##mas', 'are', 'used', 'inside', 'numbers', 'in', 'english', ',', 'every', 'three', 'digits', '.', '[SEP]']\nTime taken - 0.00062\n" ] ], [ [ "* We will discuss about [CLS] and [SEP] later", "_____no_output_____" ] ], [ [ "from datetime import datetime\ndef nltkTokenizer(text):\n start = (datetime.now())\n print(word_tokenize(text))\n end = (datetime.now())\n print(\"Time taken - {}\".format((end-start).total_seconds()))\n \n ", "_____no_output_____" ], [ "nltkTokenizer('Number expressions introduce other complications as well; while commas nor- mally appear at word boundaries, commas are used inside numbers in English, every three digits.')", "['Number', 'expressions', 'introduce', 'other', 'complications', 'as', 'well', ';', 'while', 'commas', 'nor-', 'mally', 'appear', 'at', 'word', 'boundaries', ',', 'commas', 'are', 'used', 'inside', 'numbers', 'in', 'English', ',', 'every', 'three', 'digits', '.']\nTime taken - 0.002232\n" ] ], [ [ "##### Word segmentation\n\n> Some languages(like Chinese) don't have words seperated by spaces, hence tokenization is not easily done. So word segmentation is done using sequence models trained on hand seperated datasets.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4af2c914e69e30cd216fdefba80534937c64d36f
181,732
ipynb
Jupyter Notebook
notebooks/Bayesian Linear Regression_SFS_comp.ipynb
franciscovargas/ControlledFollmerDrift
608d20912cf6503502322fc759abb5216b9e1227
[ "MIT" ]
2
2021-12-07T14:53:43.000Z
2021-12-23T13:27:11.000Z
notebooks/Bayesian Linear Regression_SFS_comp.ipynb
franciscovargas/ControlledFollmerDrift
608d20912cf6503502322fc759abb5216b9e1227
[ "MIT" ]
null
null
null
notebooks/Bayesian Linear Regression_SFS_comp.ipynb
franciscovargas/ControlledFollmerDrift
608d20912cf6503502322fc759abb5216b9e1227
[ "MIT" ]
null
null
null
109.411198
24,044
0.822684
[ [ [ "import torch\nimport torch.nn.functional as F\nimport torchsde\n\nfrom torchvision import datasets, transforms\n\nimport math\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom torchvision.transforms import ToTensor\nfrom torch.utils.data import DataLoader\nimport functorch\n\nimport matplotlib.pyplot as plt\n\nimport cfollmer.functional as functional\nfrom cfollmer.objectives import relative_entropy_control_cost\nfrom cfollmer.drifts import SimpleForwardNet, SimpleForwardNetBN, ResNetScoreNetwork\nfrom cfollmer.sampler_utils import FollmerSDE", "_____no_output_____" ], [ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"", "_____no_output_____" ], [ "class DNN(torch.nn.Module):\n \n def __init__(self, input_dim=1, output_dim=1):\n super(DNN, self).__init__()\n \n self.output_dim = output_dim\n self.input_dim = input_dim\n \n self.nn = torch.nn.Sequential(\n torch.nn.Linear(input_dim, 100),\n torch.nn.ReLU(),\n torch.nn.Linear(100, 100),\n torch.nn.ReLU(),\n torch.nn.Linear(100, output_dim)\n )\n \n def forward(self, x):\n return self.nn(x)\n\n \nclass LinModel(torch.nn.Module):\n \n def __init__(self, input_dim=1, output_dim=1):\n super(LinModel, self).__init__()\n \n self.output_dim = output_dim\n self.input_dim = input_dim\n \n self.nn = torch.nn.Sequential(\n torch.nn.Linear(input_dim, 1),\n )\n \n def forward(self, x):\n return self.nn(x)", "_____no_output_____" ], [ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n\n\ndef lin_reg_data_gen(dim, sigma_n, device, num_samps=30):\n\n w = np.ones((dim,1))\n b = 1\n\n func = lambda x: np.dot(x, w) + 1\n\n # Test inputs\n num_test_samples = 30\n\n if dim == 1:\n X_test = np.linspace(-16, 16, num_samps).reshape(num_samps,1)\n X_train = np.linspace(-3.5, 3.5, num_samps).reshape(-1,1)\n else:\n X_test = np.random.randn(num_samps, dim)\n X_train = np.random.randn(num_samps, dim)\n\n # Noise free training inputs\n\n #f_train = np.cos(X_train) \n f_train = func(X_train)\n\n # Noise-free training outputs\n #f = np.cos(X_test)\n f = func(X_test)\n y_test = f\n\n # Noisy training Inputs with additive Gaussian noise (zero-mean, variance sigma_n)\n\n mu = np.zeros(X_train.size)\n epsilon = np.random.multivariate_normal(mu, sigma_n**2 * np.eye(X_train.size))\n\n # Noisy targets\n y_train = f_train + epsilon.reshape(X_train.size,1)\n \n return X_train, y_train, X_test, y_test, f\n\ndim = dim_data = 1\nsigma_n = 0.5\n\nX_train, y_train, X_test, y_test, f = lin_reg_data_gen(dim, sigma_n, device)\n\nN_train , _ = X_train.shape\nN_test , _ = X_test.shape\n\n# if dim == 1:\n# Noisy observations\nfig, ax = plt.subplots(figsize=(6, 4), tight_layout=True)\nax.plot(X_test[:,[0]], f, 'b', label = 'f(x)')\nax.plot(X_train[:,[0]], y_train,\".\", label = 'y(x) = f(x) + $\\epsilon$')\nax.legend(loc = 'upper left')\nax.set_title('Target function with noisy observations ')\n\nplt.show()", "_____no_output_____" ], [ "X_train = torch.tensor(X_train, device=device, dtype=torch.float)\nX_test = torch.tensor(X_test, device=device, dtype=torch.float)\n\ny_train = torch.tensor(y_train, device=device, dtype=torch.float)\ny_test = torch.tensor(y_test, device=device, dtype=torch.float)", "_____no_output_____" ], [ "# dim", "_____no_output_____" ], [ "model = LinModel().to(device)\nfunc_model, params = functorch.make_functional(model)\nsize_list = functional.params_to_size_tuples(params)\ndim = functional.get_number_of_params(size_list)\n\nsigma2 = 1\n\ndef log_prior(params):\n return -torch.sum(params**2) / (2 * sigma2)\n\ndef log_likelihood(x, y, params):\n preds = func_model(functional.get_params_from_array(params, size_list), x)\n diff = preds - y\n \n return - torch.sum(diff**2) / (2 * sigma_n**2)\n\ndef log_likelihood_batch(x, y, params_batch):\n func = lambda params: log_likelihood(x, y, params)\n func = functorch.vmap(func)\n return func(params_batch)\n\ndef log_posterior(x, y, params):\n return log_prior(params) + (N_train / x.shape[0]) * log_likelihood(x, y, params)\n\ndef log_posterior_batch(x, y, params_batch):\n func = lambda params: log_posterior(x, y, params)\n func = functorch.vmap(func)\n return func(params_batch)", "_____no_output_____" ], [ "gamma = 0.1**2\n\nn_steps = 300\ndata_batch_size = 50\nparam_batch_size = 32", "_____no_output_____" ], [ "def train(gamma, n_steps, data_batch_size, param_batch_size, dt=0.05, stl=False):\n sde = FollmerSDE(gamma, SimpleForwardNetBN(input_dim=dim, width=300)).to(device)\n optimizer = torch.optim.Adam(sde.parameters(), lr=1e-4)\n \n losses = []\n\n for _ in tqdm(range(n_steps)):\n perm = torch.randperm(N_train)\n x = X_train[perm[:data_batch_size], :]\n y = y_train[perm[:data_batch_size], :]\n\n optimizer.zero_grad()\n \n partial_log_p = lambda params_batch: log_posterior_batch(x, y, params_batch)\n \n loss = relative_entropy_control_cost(sde, partial_log_p, param_batch_size=param_batch_size, dt=dt, device=device)\n loss.backward()\n \n losses.append(loss.detach().cpu().numpy())\n optimizer.step()\n \n if stl: # double check theres no references left\n sde.drift_network_detatched.load_state_dict((sde.drift_network.state_dict()))\n \n losses = np.array(losses)\n \n return sde, losses", "_____no_output_____" ], [ "def predict(param_samples, x, y):\n with torch.no_grad():\n predict_func = lambda params : func_model(functional.get_params_from_array(params, size_list), x)\n predict_func = functorch.vmap(predict_func)\n\n preds = predict_func(param_samples)\n\n std, mean = torch.std_mean(preds, dim=0)\n mse = torch.mean((y_test - mean)**2)\n logp = torch.mean(log_likelihood_batch(x, y, param_samples))\n \n return std, mean, logp, mse", "_____no_output_____" ], [ "def plot_fit(mean, std, title=\"\", fn=None):\n x = X_test.cpu().squeeze()\n std = std.cpu().squeeze()\n mean = mean.cpu().squeeze()\n \n plt.plot(x, mean)\n plt.fill_between(x, mean - 2 * std, mean + 2 * std, alpha=0.2)\n plt.plot(X_train.cpu(), y_train.cpu(), 'kP', ms = 9)\n plt.title(title)\n plt.legend([\"mean prediction\", \"data\", r\"$\\pm 2\\sigma^2$\"], loc=\"upper left\")\n if fn is not None:\n plt.savefig(fn, bbox_inches=\"tight\", dpi=600)\n plt.close()", "_____no_output_____" ], [ "sde, losses = train(gamma, n_steps, data_batch_size, param_batch_size)", " 0%| | 0/300 [00:00<?, ?it/s]/home/fav25/.conda/envs/functorch/lib/python3.9/site-packages/torch/nn/functional.py:2282: UserWarning: There is a performance drop because we have not yet implemented the batching rule for aten::batch_norm. Please file us an issue on GitHub so that we can prioritize its implementation. (Triggered internally at /tmp/pip-req-build-jk216yxu/functorch/csrc/BatchedFallback.cpp:106.)\n return torch.batch_norm(\n100%|██████████| 300/300 [00:14<00:00, 20.70it/s]\n" ], [ "plt.plot(losses)", "_____no_output_____" ], [ "param_samples = sde.sample(100, dt=0.01, device=device)\nstd, mean, logp, mse = predict(param_samples, X_test, y_test)\n\nstd = torch.sqrt(std**2 + sigma_n**2)\nplot_fit(mean, std, title=\"SBP fit\", fn=None)\nplt.show()\nplot_fit(mean, std, title=\"SBP fit\", fn=\"plots/step_func/sbp_fit.png\")\n# plt.show()", "_____no_output_____" ], [ "param_samples.std(dim=0), sfs_samps.std(dim=0)", "_____no_output_____" ], [ "class MCFollmerDrift:\n \n def __init__(self, log_posterior, X,y, dim, device, n_samp=300, gamma=torch.tensor(1), debug=False):\n self.log_posterior = log_posterior\n self.debug = debug\n self.log_posterior = log_posterior\n self.device = device\n self.X = X\n self.dim = dim\n self.y = y\n self.gamma = gamma\n self.n_samp = n_samp\n self.distrib = torch.distributions.multivariate_normal.MultivariateNormal(\n loc=torch.zeros(dim),\n covariance_matrix=torch.eye(dim) * torch.sqrt(gamma)\n )\n \n def g(self, thet):\n func = lambda params: self.log_posterior(self.X, self.y, params)\n func = functorch.vmap(func)\n lp = func(thet)\n reg = 0.5 * (thet**2).sum(dim=-1) / self.gamma\n \n# if torch.any(torch.isinf(torch.exp(lp + reg))):\n\n out = torch.exp(lp + reg)\n isnan = torch.isinf(torch.abs(out)) | torch.isnan(out)\n if self.debug and torch.any(isnan):\n import pdb; pdb.set_trace()\n# import pdb; pdb.set_trace()\n return out # nans exp(reg)\n\n def ln_g(self, thet):\n func = lambda params: self.log_posterior(self.X, self.y, params)\n func = functorch.vmap(func)\n lp = func(thet)\n reg = 0.5 * (thet**2).sum(dim=-1) / self.gamma\n \n out = lp + reg\n isnan = torch.isinf(torch.abs(out)) | torch.isnan(out)\n if self.debug and torch.any(isnan):\n import pdb; pdb.set_trace()\n \n return out # nans exp(reg)\n \n def mc_follmer_drift_(self, t, params, Z):\n # Using Stein Estimator for SFS drift\n\n g_YZt = self.g(params[None, ...] + torch.sqrt(1-t) * Z)\n num = (Z * g_YZt[..., None]).mean(dim=0)\n denom = torch.sqrt(1-t) * (g_YZt).mean(dim=0)\n \n out = num / denom[...,None]\n \n isnan = torch.isinf(torch.abs(out)) | torch.isnan(out)\n \n return out\n \n def mc_follmer_drift_stable(self, t, params, Z):\n # Using Stein Estimator for SFS drift\n N, d = Z.shape\n lnN = torch.log(torch.tensor(N)).to(self.device)\n \n ln_g_YZt = self.ln_g(params[None, ...] + torch.sqrt(1-t) * Z)\n \n Z_plus = torch.nn.functional.relu(Z)\n Z_minus = torch.nn.functional.relu(-Z) \n \n ln_num_plus = torch.logsumexp(\n (torch.log(Z_plus) + ln_g_YZt[..., None]) - lnN,\n dim=0,\n )\n ln_num_minus = torch.logsumexp(\n (torch.log(Z_minus) + ln_g_YZt[..., None]) - lnN,\n dim=0\n )\n \n ln_denom = torch.logsumexp(\n torch.log(torch.sqrt(1-t)) + (ln_g_YZt) - lnN,\n dim=0\n )\n \n out = torch.exp(ln_num_plus-ln_denom) - torch.exp(ln_num_minus-ln_denom)\n \n \n isnan = torch.isinf(torch.abs(out)) | torch.isnan(out)\n \n return out \n \n def mc_follmer_drift_debug(self, t, params):\n # Using Stein Estimator for SFS drift\n \n \n Z = self.distrib.rsample((self.n_samp,)).to(self.device)\n params = params[0]\n\n g_YZt = self.g(params[None, ...] + torch.sqrt(1-t) * Z)\n num = (Z * g_YZt[..., None]).mean(dim=0)\n denom = torch.sqrt(1-t) * (g_YZt).mean(dim=0)\n \n out = num / denom[...,None]\n \n isnan = torch.isinf(torch.abs(out)) | torch.isnan(out)\n \n if self.debug and torch.any(isnan):\n import pdb; pdb.set_trace()\n \n return out.reshape(1,-1)\n \n def mc_follmer_drift(self, t , params_batch):\n Z = self.distrib.rsample((params_batch.shape[0], self.n_samp)).to(self.device)\n \n func = lambda params, z: self.mc_follmer_drift_stable(t, params, z)\n func = functorch.vmap(func, in_dims=(0,0) )\n out = func(params_batch, Z)\n# import pdb; pdb.set_trace()\n return out\n\n \n\nclass MCFollmerSDE(torch.nn.Module):\n\n def __init__(self, gamma, dim, log_posterior, X_train, y_train, device, debug=False):\n super().__init__()\n\n self.noise_type = 'diagonal'\n self.sde_type = 'ito'\n self.gamma = gamma\n if debug:\n self.drift = MCFollmerDrift(log_posterior, X_train, y_train, dim, device, gamma=gamma, debug=debug).mc_follmer_drift_debug\n else:\n self.drift = MCFollmerDrift(log_posterior, X_train, y_train, dim, device, gamma=gamma).mc_follmer_drift\n self.dim = dim\n \n def f(self, t, y, detach=False):\n return self.drift(t, y)\n \n def g(self, t, y):\n return torch.sqrt(self.gamma )* torch.ones_like(y)\n\n def sample_trajectory(self, batch_size, dt=0.05, device=None):\n param_init = torch.zeros((batch_size, self.dim), device=device)\n\n n_steps = int(1.0 / dt)\n\n ts = torch.linspace(0, 1, n_steps, device=device)\n\n param_trajectory = torchsde.sdeint(self, param_init, ts, method=\"euler\", dt=dt)\n\n return param_trajectory, ts\n\n def sample(self, batch_size, dt=0.05, device=None):\n return self.sample_trajectory(batch_size, dt=dt, device=device)[0] [-1]#[-1]\n \n\n# mcfol = MCFollmerDrift(log_posterior, X_train, y_train, dim, device)\nsde_sfs = MCFollmerSDE(torch.tensor(gamma), dim, log_posterior, X_train, y_train, device)", "_____no_output_____" ], [ "# sfs_samps", "_____no_output_____" ], [ "sfs_samps = sde_sfs.sample(130, dt=0.01, device=device)", "/tmp/ipykernel_553292/3622056387.py:40: UserWarning: There is a performance drop because we have not yet implemented the batching rule for aten::__or__.Tensor. Please file us an issue on GitHub so that we can prioritize its implementation. (Triggered internally at /tmp/pip-req-build-jk216yxu/functorch/csrc/BatchedFallback.cpp:106.)\n isnan = torch.isinf(torch.abs(out)) | torch.isnan(out)\n/tmp/ipykernel_553292/3622056387.py:87: UserWarning: There is a performance drop because we have not yet implemented the batching rule for aten::__or__.Tensor. Please file us an issue on GitHub so that we can prioritize its implementation. (Triggered internally at /tmp/pip-req-build-jk216yxu/functorch/csrc/BatchedFallback.cpp:106.)\n isnan = torch.isinf(torch.abs(out)) | torch.isnan(out)\n" ], [ "sfs_samps", "_____no_output_____" ], [ "(~torch.isnan(sfs_samps).sum(dim=1).bool()).sum()", "_____no_output_____" ], [ "sfs_samps = sfs_samps[~torch.isnan(sfs_samps).sum(dim=1).bool()]\n\nstd_sfs, mean_sfs, logp_sfs, mse_sfs = predict(sfs_samps, X_test, y_test)\n\nstd_sfs = torch.sqrt(std_sfs**2 + sigma_n**2)\nplot_fit(mean_sfs, std_sfs, title=\"SBP fit\", fn=None)\n# plot_fit(mean, std, title=\"SBP fit\", fn=None)\n# plot_fit(torch.tensor(mean_true), torch.tensor(std_true), title=\"Exact fit\", fn=None)\nplt.show()\nplot_fit(mean_sfs, std_sfs, title=\"SBP fit\", fn=\"plots/step_func/sbp_sfs_mc_fit.png\")", "_____no_output_____" ], [ "def pred_true_std(X_train, X_test, sigma_n, sigma2, dim):\n # https://github.com/probml/pml-book/releases/latest/download/book1.pdf\n # See Eq 11.124 in the above link page 430 on pdf viewer (page 400 on page number in pdf)\n\n X_trainnp = X_train.cpu().detach().numpy()\n n_, d = X_trainnp.shape\n\n X_trainnp = np.concatenate((X_trainnp, np.ones((n_, 1))), axis=1)\n\n X_testnp = X_test.cpu().detach().numpy()\n n_, d = X_testnp.shape\n\n X_testnp = np.concatenate((X_testnp, np.ones((n_, 1))), axis=1)\n\n\n print(X_trainnp.shape)\n\n Sigma_post = sigma_n**2 * np.linalg.inv(sigma_n**2 * np.eye(dim) / sigma2 + np.dot(X_trainnp.T,X_trainnp))\n \n sigma_pred = []\n for i in range(n_):\n sigma_pred += [np.dot(X_testnp[i,:].dot(Sigma_post), X_testnp[i,:]) + sigma_n**2 ]\n\n std_true = np.sqrt(sigma_pred)\n return std_true\n\nstd_true = pred_true_std(X_train, X_test, sigma_n, sigma2, dim)", "(30, 2)\n" ], [ "def pred_true_mean(y_train, X_train, X_test, sigma_n, sigma2, dim):\n # https://github.com/probml/pml-book/releases/latest/download/book1.pdf\n # See Eq 11.124 in the above link page 430 on pdf viewer (page 400 on page number in pdf)\n\n X_trainnp = X_train.cpu().detach().numpy()\n n_, d = X_trainnp.shape\n \n lambda_ = sigma_n**2 / sigma2 \n\n X_trainnp = np.concatenate((X_trainnp, np.ones((n_, 1))), axis=1)\n\n X_testnp = X_test.cpu().detach().numpy()\n n_, d = X_testnp.shape\n\n X_testnp = np.concatenate((X_testnp, np.ones((n_, 1))), axis=1)\n\n Xty = np.dot(X_trainnp.T, y_train)\n\n Sigma_post = np.linalg.inv(sigma_n**2 * np.eye(dim) / sigma2 + np.dot(X_trainnp.T,X_trainnp))\n \n w = np.dot(Sigma_post, Xty)\n \n print(w.shape)\n return np.dot(X_testnp,w)\n\nmean_true = pred_true_mean(y_train.detach().cpu(), X_train, X_test, sigma_n, sigma2, dim)", "(2, 1)\n" ], [ "mean_true.shape", "_____no_output_____" ], [ "param_samples = sde.sample(100, dt=0.01, device=device)\n\nplot_fit(torch.tensor(mean_true), torch.tensor(std_true), title=\"Exact fit\", fn=None)\nplt.show()\n# plot_fit(mean, std, title=\"SBP fit\", fn=\"plots/step_func/sbp_fit.png\")", "_____no_output_____" ], [ "np.abs(std_sfs.detach().cpu().numpy()- std_true).mean(), np.abs(std.detach().cpu().numpy()- std_true).mean()", "_____no_output_____" ], [ "np.abs(mean_sfs.detach().cpu().numpy()- mean_true).mean(), np.abs(mean.detach().cpu().numpy()- mean_true).mean()", "_____no_output_____" ], [ "std_sfs = torch.sqrt(std_sfs**2 + sigma_n**2)\nplot_fit(mean_sfs, std_sfs, title=\"SBP fit\", fn=None)\nplot_fit(mean, std, title=\"SBP fit\", fn=None)\nplot_fit(torch.tensor(mean_true), torch.tensor(std_true), title=\"Exact fit\", fn=None)\nplt.show()\nplot_fit(mean_sfs, std_sfs, title=\"SBP fit\", fn=\"plots/step_func/sbp_sfs_mc_fit.png\")", "_____no_output_____" ], [ "# plot_fit(mean_sfs, std_sfs, title=\"SBP fit\", fn=None)\nplot_fit(mean, std_sfs, title=\"SBP fit\", fn=None)\nplot_fit(torch.tensor(mean_true), torch.tensor(std_true), title=\"Exact fit\", fn=None)", "_____no_output_____" ], [ "n_runs = 5\n\nsbp_mse = []\nsbp_logp = []\n\nfor i in range(n_runs):\n sde, losses = train(gamma, n_steps, data_batch_size, param_batch_size)\n \n with torch.no_grad():\n param_samples = sde.sample(100, dt=0.01, device=device)\n \n \n \n std, mean, logp, mse = predict(param_samples, X_test, y_test)\n \n std = torch.sqrt(std**2 + sigma_n**2)\n plot_fit(mean, std, title=\"SBP fit\", fn=None)\n plt.show()\n \n plot_fit(mean, std, title=\"SBP fit #{}\".format(i+1), fn=\"plots/step_func/sbp_fit_#{:d}.png\".format(i+1))\n \n sbp_mse.append(mse.cpu().numpy())\n sbp_logp.append(logp.cpu().numpy())\n \nsbp_mse = np.array(sbp_mse)\nsbp_logp = np.array(sbp_logp)", " 0%| | 0/300 [00:00<?, ?it/s]/home/fav25/.conda/envs/functorch/lib/python3.9/site-packages/torch/nn/functional.py:2282: UserWarning: There is a performance drop because we have not yet implemented the batching rule for aten::batch_norm. Please file us an issue on GitHub so that we can prioritize its implementation. (Triggered internally at /tmp/pip-req-build-jk216yxu/functorch/csrc/BatchedFallback.cpp:106.)\n return torch.batch_norm(\n100%|██████████| 300/300 [00:27<00:00, 10.76it/s]\n 0%| | 0/300 [00:00<?, ?it/s]/home/fav25/.conda/envs/functorch/lib/python3.9/site-packages/torch/nn/functional.py:2282: UserWarning: There is a performance drop because we have not yet implemented the batching rule for aten::batch_norm. Please file us an issue on GitHub so that we can prioritize its implementation. (Triggered internally at /tmp/pip-req-build-jk216yxu/functorch/csrc/BatchedFallback.cpp:106.)\n return torch.batch_norm(\n100%|██████████| 300/300 [00:28<00:00, 10.63it/s]\n 0%| | 0/300 [00:00<?, ?it/s]/home/fav25/.conda/envs/functorch/lib/python3.9/site-packages/torch/nn/functional.py:2282: UserWarning: There is a performance drop because we have not yet implemented the batching rule for aten::batch_norm. Please file us an issue on GitHub so that we can prioritize its implementation. (Triggered internally at /tmp/pip-req-build-jk216yxu/functorch/csrc/BatchedFallback.cpp:106.)\n return torch.batch_norm(\n100%|██████████| 300/300 [00:28<00:00, 10.52it/s]\n 0%| | 0/300 [00:00<?, ?it/s]/home/fav25/.conda/envs/functorch/lib/python3.9/site-packages/torch/nn/functional.py:2282: UserWarning: There is a performance drop because we have not yet implemented the batching rule for aten::batch_norm. Please file us an issue on GitHub so that we can prioritize its implementation. (Triggered internally at /tmp/pip-req-build-jk216yxu/functorch/csrc/BatchedFallback.cpp:106.)\n return torch.batch_norm(\n 99%|█████████▉| 297/300 [00:27<00:00, 10.42it/s]" ], [ "@torch.enable_grad()\ndef gradient(x, y, params):\n params_ = params.clone().requires_grad_(True)\n loss = log_posterior(x, y, params_)\n grad, = torch.autograd.grad(loss, params_)\n return loss.detach().cpu().numpy(), grad", "_____no_output_____" ], [ "def step_size(n):\n return 1e-4/ (1 + n)**0.1", "_____no_output_____" ], [ "def sgld(n_steps, last_n, data_batch_size):\n losses = []\n param_samples = []\n \n params = torch.zeros(dim).float().to(device)\n \n for step in tqdm(range(n_steps)):\n perm = torch.randperm(N_train)\n x = X_train[perm[:data_batch_size], :]\n y = y_train[perm[:data_batch_size], :]\n\n eps = step_size(step)\n loss, grad = gradient(x, y, params)\n params = params + 0.5 * eps * grad + np.sqrt(eps) * torch.randn_like(params)\n \n if n_steps <= step + last_n:\n param_samples.append(params)\n losses.append(loss)\n \n param_samples = torch.stack(param_samples)\n \n return param_samples, losses", "_____no_output_____" ], [ "param_samples, losses = sgld(10000, 2000, data_batch_size)", "_____no_output_____" ], [ "plt.plot(losses)", "_____no_output_____" ], [ "std, mean, logp, mse = predict(param_samples[:100], X_test, y_test)\n\nstd = torch.sqrt(std**2 + sigma_n**2)\n", "_____no_output_____" ], [ "plot_fit(mean, std, title=\"SBP fit\", fn=None)\nplt.show()\n\nplot_fit(mean, std, title=\"SGLD fit\", fn=\"plots/step_func/sgld_fit.png\")", "_____no_output_____" ], [ "n_runs = 5\nn_steps = 10000\n\nsgld_mse = []\nsgld_logp = []\n\nfor i in range(n_runs):\n param_samples, losses = sgld(n_steps, 1000, data_batch_size)\n \n std, mean, logp, mse = predict(param_samples[:100], X_test, y_test)\n plot_fit(mean, std, title=\"SGLD fit #{} (100 samples)\".format(i+1), fn=\"plots/step_func/sgld_fit_#{:d}_100.png\".format(i+1))\n \n std, mean, _, _ = predict(param_samples[:500], X_test, y_test)\n plot_fit(mean, std, title=\"SGLD fit #{} (500 samples)\".format(i+1), fn=\"plots/step_func/sgld_fit_#{:d}_500.png\".format(i+1))\n \n std, mean, _, _ = predict(param_samples, X_test, y_test)\n plot_fit(mean, std, title=\"SGLD fit #{} (1000 samples)\".format(i+1), fn=\"plots/step_func/sgld_fit_#{:d}_1000.png\".format(i+1))\n \n sgld_mse.append(mse.cpu().numpy())\n sgld_logp.append(logp.cpu().numpy())\n \nsgld_mse = np.array(sgld_mse)\nsgld_logp = np.array(sgld_logp)", "100%|████████████████████████████████████████████████████████| 10000/10000 [00:07<00:00, 1280.44it/s]\n100%|████████████████████████████████████████████████████████| 10000/10000 [00:07<00:00, 1291.47it/s]\n100%|████████████████████████████████████████████████████████| 10000/10000 [00:07<00:00, 1285.05it/s]\n100%|████████████████████████████████████████████████████████| 10000/10000 [00:07<00:00, 1284.32it/s]\n100%|████████████████████████████████████████████████████████| 10000/10000 [00:07<00:00, 1284.46it/s]\n" ], [ "SBP_df = pd.DataFrame({\"mse\": sbp_mse, \"logp\": sbp_logp})\nSGLD_df = pd.DataFrame({\"mse\": sgld_mse, \"logp\": sgld_logp})", "_____no_output_____" ], [ "SBP_df", "_____no_output_____" ], [ "SBP_df.describe()", "_____no_output_____" ], [ "SGLD_df", "_____no_output_____" ], [ "SGLD_df.describe()", "_____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", "code" ] ]
4af2dce53a7455ac5eff61b3a208b066e164fd68
186,740
ipynb
Jupyter Notebook
Project/Sample Based Learning/Assignment2-v2.ipynb
Niangmohamed/Reinforcement-Learning
737bbc3bed078ccaed62746f205783f0ef015734
[ "MIT" ]
5
2020-02-01T21:03:28.000Z
2020-10-10T07:58:56.000Z
Project/Sample Based Learning/Assignment2-v2.ipynb
Niangmohamed/Reinforcement-Learning-Specialization
b68c414ecaf9b416f2bba02a829e9e461b339214
[ "MIT" ]
null
null
null
Project/Sample Based Learning/Assignment2-v2.ipynb
Niangmohamed/Reinforcement-Learning-Specialization
b68c414ecaf9b416f2bba02a829e9e461b339214
[ "MIT" ]
7
2021-04-07T02:28:26.000Z
2022-03-23T01:49:12.000Z
127.034014
85,605
0.853775
[ [ [ "# Assignment 2 - Q-Learning and Expected Sarsa", "_____no_output_____" ], [ "Welcome to Course 2 Programming Assignment 2. In this notebook, you will:\n\n- Implement Q-Learning with $\\epsilon$-greedy action selection\n- Implement Expected Sarsa with $\\epsilon$-greedy action selection\n- Investigate how these two algorithms behave on Cliff World (described on page 132 of the textbook)\n\nWe will provide you with the environment and infrastructure to run an experiment (called the experiment program in RL-Glue). This notebook will provide all the code you need to run your experiment and visualise learning performance.\n\nThis assignment will be graded automatically by comparing the behavior of your agent to our implementations of Expected Sarsa and Q-learning. The random seed will be set to avoid different behavior due to randomness. **You should not call any random functions in this notebook.** It will affect the agent's random state and change the results.", "_____no_output_____" ], [ "## Packages", "_____no_output_____" ], [ "You will need the following libraries for this assignment. We are using:\n1. numpy: the fundamental package for scientific computing with Python.\n2. scipy: a Python library for scientific and technical computing.\n3. matplotlib: library for plotting graphs in Python.\n4. RL-Glue: library for reinforcement learning experiments.\n\n**Please do not import other libraries** — this will break the autograder.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nfrom scipy.stats import sem\nimport matplotlib.pyplot as plt\nfrom rl_glue import RLGlue\nimport agent\nimport cliffworld_env\nfrom tqdm import tqdm\nimport pickle", "_____no_output_____" ], [ "plt.rcParams.update({'font.size': 15})\nplt.rcParams.update({'figure.figsize': [10,5]})", "_____no_output_____" ] ], [ [ "## Section 1: Q-Learning", "_____no_output_____" ], [ "In this section you will implement and test a Q-Learning agent with $\\epsilon$-greedy action selection (Section 6.5 in the textbook). ", "_____no_output_____" ], [ "### Implementation", "_____no_output_____" ], [ "Your job is to implement the updates in the methods agent_step and agent_end. We provide detailed comments in each method describing what your code should do.", "_____no_output_____" ] ], [ [ "# [Graded]\n# Q-Learning agent here\nclass QLearningAgent(agent.BaseAgent):\n def agent_init(self, agent_init_info):\n \"\"\"Setup for the agent called when the experiment first starts.\n \n Args:\n agent_init_info (dict), the parameters used to initialize the agent. The dictionary contains:\n {\n num_states (int): The number of states,\n num_actions (int): The number of actions,\n epsilon (float): The epsilon parameter for exploration,\n step_size (float): The step-size,\n discount (float): The discount factor,\n }\n \n \"\"\"\n # Store the parameters provided in agent_init_info.\n self.num_actions = agent_init_info[\"num_actions\"]\n self.num_states = agent_init_info[\"num_states\"]\n self.epsilon = agent_init_info[\"epsilon\"]\n self.step_size = agent_init_info[\"step_size\"]\n self.discount = agent_init_info[\"discount\"]\n self.rand_generator = np.random.RandomState(agent_info[\"seed\"])\n \n # Create an array for action-value estimates and initialize it to zero.\n self.q = np.zeros((self.num_states, self.num_actions)) # The array of action-value estimates.\n\n \n def agent_start(self, state):\n \"\"\"The first method called when the episode starts, called after\n the environment starts.\n Args:\n state (int): the state from the\n environment's evn_start function.\n Returns:\n action (int): the first action the agent takes.\n \"\"\"\n \n # Choose action using epsilon greedy.\n current_q = self.q[state,:]\n if self.rand_generator.rand() < self.epsilon:\n action = self.rand_generator.randint(self.num_actions)\n else:\n action = self.argmax(current_q)\n self.prev_state = state\n self.prev_action = action\n return action\n \n def agent_step(self, reward, state):\n \"\"\"A step taken by the agent.\n Args:\n reward (float): the reward received for taking the last action taken\n state (int): the state from the\n environment's step based on where the agent ended up after the\n last step.\n Returns:\n action (int): the action the agent is taking.\n \"\"\"\n \n # Choose action using epsilon greedy.\n current_q = self.q[state, :]\n if self.rand_generator.rand() < self.epsilon:\n action = self.rand_generator.randint(self.num_actions)\n else:\n action = self.argmax(current_q)\n \n # Perform an update (1 line)\n ### START CODE HERE ###\n self.q[self.prev_state,self.prev_action] = self.q[self.prev_state,self.prev_action] + self.step_size*( \n reward + self.discount*np.max(self.q[state,:]) - self.q[self.prev_state,self.prev_action] )\n ### END CODE HERE ###\n \n self.prev_state = state\n self.prev_action = action\n return action\n \n def agent_end(self, reward):\n \"\"\"Run when the agent terminates.\n Args:\n reward (float): the reward the agent received for entering the\n terminal state.\n \"\"\"\n # Perform the last update in the episode (1 line)\n ### START CODE HERE ###\n self.q[self.prev_state,self.prev_action] = self.q[self.prev_state,self.prev_action] + self.step_size*( \n reward - self.q[self.prev_state,self.prev_action] )\n ### END CODE HERE ###\n \n def argmax(self, q_values):\n \"\"\"argmax with random tie-breaking\n Args:\n q_values (Numpy array): the array of action-values\n Returns:\n action (int): an action with the highest value\n \"\"\"\n top = float(\"-inf\")\n ties = []\n\n for i in range(len(q_values)):\n if q_values[i] > top:\n top = q_values[i]\n ties = []\n\n if q_values[i] == top:\n ties.append(i)\n\n return self.rand_generator.choice(ties)", "_____no_output_____" ] ], [ [ "### Test", "_____no_output_____" ], [ "Run the cells below to test the implemented methods. The output of each cell should match the expected output.\n\nNote that passing this test does not guarantee correct behavior on the Cliff World.", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\n## Test Code for agent_start() ##\n\nagent_info = {\"num_actions\": 4, \"num_states\": 3, \"epsilon\": 0.1, \"step_size\": 0.1, \"discount\": 1.0, \"seed\": 0}\ncurrent_agent = QLearningAgent()\ncurrent_agent.agent_init(agent_info)\naction = current_agent.agent_start(0)\nprint(\"Action Value Estimates: \\n\", current_agent.q)\nprint(\"Action:\", action)", "Action Value Estimates: \n [[0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]]\nAction: 1\n" ] ], [ [ "**Expected Output:**\n\n```\nAction Value Estimates: \n [[0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]]\nAction: 1\n```", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\n## Test Code for agent_step() ##\n\nactions = []\nagent_info = {\"num_actions\": 4, \"num_states\": 3, \"epsilon\": 0.1, \"step_size\": 0.1, \"discount\": 1.0, \"seed\": 0}\ncurrent_agent = QLearningAgent()\ncurrent_agent.agent_init(agent_info)\nactions.append(current_agent.agent_start(0))\nactions.append(current_agent.agent_step(2, 1))\nactions.append(current_agent.agent_step(0, 0))\nprint(\"Action Value Estimates: \\n\", current_agent.q)\nprint(\"Actions:\", actions)", "Action Value Estimates: \n [[0. 0.2 0. 0. ]\n [0. 0. 0. 0.02]\n [0. 0. 0. 0. ]]\nActions: [1, 3, 1]\n" ] ], [ [ "**Expected Output:**\n\n```\nAction Value Estimates: \n [[ 0. 0.2 0. 0. ]\n [ 0. 0. 0. 0.02]\n [ 0. 0. 0. 0. ]]\nActions: [1, 3, 1]\n```", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\n## Test Code for agent_end() ##\n\nactions = []\nagent_info = {\"num_actions\": 4, \"num_states\": 3, \"epsilon\": 0.1, \"step_size\": 0.1, \"discount\": 1.0, \"seed\": 0}\ncurrent_agent = QLearningAgent()\ncurrent_agent.agent_init(agent_info)\nactions.append(current_agent.agent_start(0))\nactions.append(current_agent.agent_step(2, 1))\ncurrent_agent.agent_end(1)\nprint(\"Action Value Estimates: \\n\", current_agent.q)\nprint(\"Actions:\", actions)", "Action Value Estimates: \n [[0. 0.2 0. 0. ]\n [0. 0. 0. 0.1]\n [0. 0. 0. 0. ]]\nActions: [1, 3]\n" ] ], [ [ "**Expected Output:**\n\n```\nAction Value Estimates: \n [[0. 0.2 0. 0. ]\n [0. 0. 0. 0.1]\n [0. 0. 0. 0. ]]\nActions: [1, 3]\n```", "_____no_output_____" ], [ "## Section 2: Expected Sarsa", "_____no_output_____" ], [ "In this section you will implement an Expected Sarsa agent with $\\epsilon$-greedy action selection (Section 6.6 in the textbook). ", "_____no_output_____" ], [ "### Implementation", "_____no_output_____" ], [ "Your job is to implement the updates in the methods agent_step and agent_end. We provide detailed comments in each method describing what your code should do.", "_____no_output_____" ] ], [ [ "# [Graded]\n# Expected Sarsa agent here\nclass ExpectedSarsaAgent(agent.BaseAgent):\n def agent_init(self, agent_init_info):\n \"\"\"Setup for the agent called when the experiment first starts.\n \n Args:\n agent_init_info (dict), the parameters used to initialize the agent. The dictionary contains:\n {\n num_states (int): The number of states,\n num_actions (int): The number of actions,\n epsilon (float): The epsilon parameter for exploration,\n step_size (float): The step-size,\n discount (float): The discount factor,\n }\n \n \"\"\"\n # Store the parameters provided in agent_init_info.\n self.num_actions = agent_init_info[\"num_actions\"]\n self.num_states = agent_init_info[\"num_states\"]\n self.epsilon = agent_init_info[\"epsilon\"]\n self.step_size = agent_init_info[\"step_size\"]\n self.discount = agent_init_info[\"discount\"]\n self.rand_generator = np.random.RandomState(agent_info[\"seed\"])\n \n # Create an array for action-value estimates and initialize it to zero.\n self.q = np.zeros((self.num_states, self.num_actions)) # The array of action-value estimates.\n\n \n def agent_start(self, state):\n \"\"\"The first method called when the episode starts, called after\n the environment starts.\n Args:\n state (int): the state from the\n environment's evn_start function.\n Returns:\n action (int): the first action the agent takes.\n \"\"\"\n \n # Choose action using epsilon greedy.\n current_q = self.q[state, :]\n if self.rand_generator.rand() < self.epsilon:\n action = self.rand_generator.randint(self.num_actions)\n else:\n action = self.argmax(current_q)\n self.prev_state = state\n self.prev_action = action\n return action\n \n def agent_step(self, reward, state):\n \"\"\"A step taken by the agent.\n Args:\n reward (float): the reward received for taking the last action taken\n state (int): the state from the\n environment's step based on where the agent ended up after the\n last step.\n Returns:\n action (int): the action the agent is taking.\n \"\"\"\n \n # Choose action using epsilon greedy.\n current_q = self.q[state,:]\n if self.rand_generator.rand() < self.epsilon:\n action = self.rand_generator.randint(self.num_actions)\n else:\n action = self.argmax(current_q)\n \n \"\"\"\n \n pi(any action) = epsilon / num_actions # any action might be chosen in the non-greedy case\n pi(greedy action) = pi(any action) + (1 - epsilon) / num_greedy_actions\n \"\"\"\n # Perform an update (~5 lines)\n ### START CODE HERE ###\n max_q = np.max(current_q)\n num_greedy_actions = np.sum(current_q==max_q)\n \n non_greedy_actions_prob = (self.epsilon / self.num_actions)\n greedy_actions_prob = ((1 - self.epsilon) / num_greedy_actions) + (self.epsilon / self.num_actions)\n \n expected_q = 0 \n for a in range(self.num_actions):\n if current_q[a] == max_q: # This is a greedy action\n expected_q += current_q[a] * greedy_actions_prob\n else: # This is a non-greedy action\n expected_q += current_q[a] * non_greedy_actions_prob\n \n self.q[self.prev_state,self.prev_action] = self.q[self.prev_state,self.prev_action] + self.step_size*(\n reward + self.discount*expected_q - self.q[self.prev_state,self.prev_action] )\n ### END CODE HERE ###\n \n self.prev_state = state\n self.prev_action = action\n return action\n \n def agent_end(self, reward):\n \"\"\"Run when the agent terminates.\n Args:\n reward (float): the reward the agent received for entering the\n terminal state.\n \"\"\"\n # Perform the last update in the episode (1 line)\n ### START CODE HERE ###\n self.q[self.prev_state,self.prev_action] = self.q[self.prev_state,self.prev_action] + self.step_size*(\n reward - self.q[self.prev_state,self.prev_action] )\n ### END CODE HERE ###\n \n def argmax(self, q_values):\n \"\"\"argmax with random tie-breaking\n Args:\n q_values (Numpy array): the array of action-values\n Returns:\n action (int): an action with the highest value\n \"\"\"\n top = float(\"-inf\")\n ties = []\n\n for i in range(len(q_values)):\n if q_values[i] > top:\n top = q_values[i]\n ties = []\n\n if q_values[i] == top:\n ties.append(i)\n\n return self.rand_generator.choice(ties)", "_____no_output_____" ] ], [ [ "### Test", "_____no_output_____" ], [ "Run the cells below to test the implemented methods. The output of each cell should match the expected output.\n\nNote that passing this test does not guarantee correct behavior on the Cliff World.", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\n## Test Code for agent_start() ##\n\nagent_info = {\"num_actions\": 4, \"num_states\": 3, \"epsilon\": 0.1, \"step_size\": 0.1, \"discount\": 1.0, \"seed\": 0}\ncurrent_agent = ExpectedSarsaAgent()\ncurrent_agent.agent_init(agent_info)\naction = current_agent.agent_start(0)\nprint(\"Action Value Estimates: \\n\", current_agent.q)\nprint(\"Action:\", action)", "Action Value Estimates: \n [[0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]]\nAction: 1\n" ] ], [ [ "**Expected Output:**\n\n```\nAction Value Estimates: \n [[0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]]\nAction: 1\n```", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\n## Test Code for agent_step() ##\n\nactions = []\nagent_info = {\"num_actions\": 4, \"num_states\": 3, \"epsilon\": 0.1, \"step_size\": 0.1, \"discount\": 1.0, \"seed\": 0}\ncurrent_agent = ExpectedSarsaAgent()\ncurrent_agent.agent_init(agent_info)\nactions.append(current_agent.agent_start(0))\nactions.append(current_agent.agent_step(2, 1))\nactions.append(current_agent.agent_step(0, 0))\nprint(\"Action Value Estimates: \\n\", current_agent.q)\nprint(\"Actions:\", actions)", "Action Value Estimates: \n [[0. 0.2 0. 0. ]\n [0. 0. 0. 0.0185]\n [0. 0. 0. 0. ]]\nActions: [1, 3, 1]\n" ] ], [ [ "**Expected Output:**\n\n```\nAction Value Estimates: \n [[0. 0.2 0. 0. ]\n [0. 0. 0. 0.0185]\n [0. 0. 0. 0. ]]\nActions: [1, 3, 1]\n```", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\n## Test Code for agent_end() ##\n\nactions = []\nagent_info = {\"num_actions\": 4, \"num_states\": 3, \"epsilon\": 0.1, \"step_size\": 0.1, \"discount\": 1.0, \"seed\": 0}\ncurrent_agent = ExpectedSarsaAgent()\ncurrent_agent.agent_init(agent_info)\nactions.append(current_agent.agent_start(0))\nactions.append(current_agent.agent_step(2, 1))\ncurrent_agent.agent_end(1)\nprint(\"Action Value Estimates: \\n\", current_agent.q)\nprint(\"Actions:\", actions)", "Action Value Estimates: \n [[0. 0.2 0. 0. ]\n [0. 0. 0. 0.1]\n [0. 0. 0. 0. ]]\nActions: [1, 3]\n" ] ], [ [ "**Expected Output:**\n\n```\nAction Value Estimates: \n [[0. 0.2 0. 0. ]\n [0. 0. 0. 0.1]\n [0. 0. 0. 0. ]]\nActions: [1, 3]\n```", "_____no_output_____" ], [ "## Section 3: Solving the Cliff World", "_____no_output_____" ], [ "We described the Cliff World environment in the video \"Expected Sarsa in the Cliff World\" in Lesson 3. This is an undiscounted episodic task and thus we set $\\gamma$=1. The agent starts in the bottom left corner of the gridworld below and takes actions that move it in the four directions. Actions that would move the agent off of the cliff incur a reward of -100 and send the agent back to the start state. The reward for all other transitions is -1. An episode terminates when the agent reaches the bottom right corner. ", "_____no_output_____" ], [ "<img src=\"cliffworld.png\" alt=\"Drawing\" style=\"width: 600px;\"/>\n", "_____no_output_____" ], [ "Using the experiment program in the cell below we now compare the agents on the Cliff World environment and plot the sum of rewards during each episode for the two agents.\n\nThe result of this cell will be graded. If you make any changes to your algorithms, you have to run this cell again before submitting the assignment.", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\nagents = {\n \"Q-learning\": QLearningAgent,\n \"Expected Sarsa\": ExpectedSarsaAgent\n}\nenv = cliffworld_env.Environment\nall_reward_sums = {} # Contains sum of rewards during episode\nall_state_visits = {} # Contains state visit counts during the last 10 episodes\nagent_info = {\"num_actions\": 4, \"num_states\": 48, \"epsilon\": 0.1, \"step_size\": 0.5, \"discount\": 1.0}\nenv_info = {}\nnum_runs = 100 # The number of runs\nnum_episodes = 500 # The number of episodes in each run\n\nfor algorithm in [\"Q-learning\", \"Expected Sarsa\"]:\n all_reward_sums[algorithm] = []\n all_state_visits[algorithm] = []\n for run in tqdm(range(num_runs)):\n agent_info[\"seed\"] = run\n rl_glue = RLGlue(env, agents[algorithm])\n rl_glue.rl_init(agent_info, env_info)\n\n reward_sums = []\n state_visits = np.zeros(48)\n# last_episode_total_reward = 0\n for episode in range(num_episodes):\n if episode < num_episodes - 10:\n # Runs an episode\n rl_glue.rl_episode(0) \n else: \n # Runs an episode while keeping track of visited states\n state, action = rl_glue.rl_start()\n state_visits[state] += 1\n is_terminal = False\n while not is_terminal:\n reward, state, action, is_terminal = rl_glue.rl_step()\n state_visits[state] += 1\n \n reward_sums.append(rl_glue.rl_return())\n# last_episode_total_reward = rl_glue.rl_return()\n \n all_reward_sums[algorithm].append(reward_sums)\n all_state_visits[algorithm].append(state_visits)\n\n# save results\nimport os\nimport shutil\nos.makedirs('results', exist_ok=True)\nnp.save('results/q_learning.npy', all_reward_sums['Q-learning'])\nnp.save('results/expected_sarsa.npy', all_reward_sums['Expected Sarsa'])\nshutil.make_archive('results', 'zip', '.', 'results')\n\n \nfor algorithm in [\"Q-learning\", \"Expected Sarsa\"]:\n plt.plot(np.mean(all_reward_sums[algorithm], axis=0), label=algorithm)\nplt.xlabel(\"Episodes\")\nplt.ylabel(\"Sum of\\n rewards\\n during\\n episode\",rotation=0, labelpad=40)\nplt.xlim(0,500)\nplt.ylim(-100,0)\nplt.legend()\nplt.show()", "100%|██████████| 100/100 [00:26<00:00, 3.73it/s]\n100%|██████████| 100/100 [00:44<00:00, 2.25it/s]\n" ] ], [ [ "To see why these two agents behave differently, let's inspect the states they visit most. Run the cell below to generate plots showing the number of timesteps that the agents spent in each state over the last 10 episodes.", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\nfor algorithm, position in [(\"Q-learning\", 211), (\"Expected Sarsa\", 212)]:\n plt.subplot(position)\n average_state_visits = np.array(all_state_visits[algorithm]).mean(axis=0)\n grid_state_visits = average_state_visits.reshape((4,12))\n grid_state_visits[0,1:-1] = np.nan\n plt.pcolormesh(grid_state_visits, edgecolors='gray', linewidth=2)\n plt.title(algorithm)\n plt.axis('off')\n cm = plt.get_cmap()\n cm.set_bad('gray')\n\n plt.subplots_adjust(bottom=0.0, right=0.7, top=1.0)\n cax = plt.axes([0.85, 0.0, 0.075, 1.])\ncbar = plt.colorbar(cax=cax)\ncbar.ax.set_ylabel(\"Visits during\\n the last 10\\n episodes\", rotation=0, labelpad=70)\nplt.show()", "_____no_output_____" ] ], [ [ "The Q-learning agent learns the optimal policy, one that moves along the cliff and reaches the goal in as few steps as possible. However, since the agent does not follow the optimal policy and uses $\\epsilon$-greedy exploration, it occasionally falls off the cliff. The Expected Sarsa agent takes exploration into account and follows a safer path. Note this is different from the book. The book shows Sarsa learns the even safer path\n\n\nPreviously we used a fixed step-size of 0.5 for the agents. What happens with other step-sizes? Does this difference in performance persist?\n\nIn the next experiment we will try 10 different step-sizes from 0.1 to 1.0 and compare the sum of rewards per episode averaged over the first 100 episodes (similar to the interim performance curves in Figure 6.3 of the textbook). Shaded regions show standard errors.\n\nThis cell takes around 10 minutes to run. The result of this cell will be graded. If you make any changes to your algorithms, you have to run this cell again before submitting the assignment.", "_____no_output_____" ] ], [ [ "# Do not modify this cell!\n\nagents = {\n \"Q-learning\": QLearningAgent,\n \"Expected Sarsa\": ExpectedSarsaAgent\n}\nenv = cliffworld_env.Environment\nall_reward_sums = {}\nstep_sizes = np.linspace(0.1,1.0,10)\nagent_info = {\"num_actions\": 4, \"num_states\": 48, \"epsilon\": 0.1, \"discount\": 1.0}\nenv_info = {}\nnum_runs = 100\nnum_episodes = 100\nall_reward_sums = {}\n\nfor algorithm in [\"Q-learning\", \"Expected Sarsa\"]:\n for step_size in step_sizes:\n all_reward_sums[(algorithm, step_size)] = []\n agent_info[\"step_size\"] = step_size\n for run in tqdm(range(num_runs)):\n agent_info[\"seed\"] = run\n rl_glue = RLGlue(env, agents[algorithm])\n rl_glue.rl_init(agent_info, env_info)\n\n return_sum = 0\n for episode in range(num_episodes):\n rl_glue.rl_episode(0)\n return_sum += rl_glue.rl_return()\n all_reward_sums[(algorithm, step_size)].append(return_sum/num_episodes)\n \n\nfor algorithm in [\"Q-learning\", \"Expected Sarsa\"]:\n algorithm_means = np.array([np.mean(all_reward_sums[(algorithm, step_size)]) for step_size in step_sizes])\n algorithm_stds = np.array([sem(all_reward_sums[(algorithm, step_size)]) for step_size in step_sizes])\n plt.plot(step_sizes, algorithm_means, marker='o', linestyle='solid', label=algorithm)\n plt.fill_between(step_sizes, algorithm_means + algorithm_stds, algorithm_means - algorithm_stds, alpha=0.2)\n\nplt.legend()\nplt.xlabel(\"Step-size\")\nplt.ylabel(\"Sum of\\n rewards\\n per episode\",rotation=0, labelpad=50)\nplt.xticks(step_sizes)\nplt.show()", "100%|██████████| 100/100 [00:22<00:00, 4.49it/s]\n100%|██████████| 100/100 [00:15<00:00, 6.23it/s]\n100%|██████████| 100/100 [00:12<00:00, 7.55it/s]\n100%|██████████| 100/100 [00:10<00:00, 8.33it/s]\n100%|██████████| 100/100 [00:09<00:00, 9.58it/s]\n100%|██████████| 100/100 [00:08<00:00, 10.70it/s]\n100%|██████████| 100/100 [00:08<00:00, 11.02it/s]\n100%|██████████| 100/100 [00:08<00:00, 12.21it/s]\n100%|██████████| 100/100 [00:07<00:00, 11.98it/s]\n100%|██████████| 100/100 [00:07<00:00, 12.77it/s]\n100%|██████████| 100/100 [00:37<00:00, 2.81it/s]\n100%|██████████| 100/100 [00:25<00:00, 3.87it/s]\n100%|██████████| 100/100 [00:20<00:00, 4.70it/s]\n100%|██████████| 100/100 [00:17<00:00, 5.53it/s]\n100%|██████████| 100/100 [00:15<00:00, 6.24it/s]\n100%|██████████| 100/100 [00:14<00:00, 6.49it/s]\n100%|██████████| 100/100 [00:14<00:00, 7.04it/s]\n100%|██████████| 100/100 [00:13<00:00, 7.26it/s]\n100%|██████████| 100/100 [00:13<00:00, 7.83it/s]\n100%|██████████| 100/100 [00:12<00:00, 8.12it/s]\n" ] ], [ [ "## Wrapping up", "_____no_output_____" ], [ "Expected Sarsa shows an advantage over Q-learning in this problem across a wide range of step-sizes.\n\nCongratulations! Now you have:\n\n- implemented Q-Learning with $\\epsilon$-greedy action selection\n- implemented Expected Sarsa with $\\epsilon$-greedy action selection\n- investigated the behavior of these two algorithms on Cliff World", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4af2eab8a41982119b0999900eab86144956b125
30,646
ipynb
Jupyter Notebook
notes/index-solution.ipynb
jigsawlabs-student/cte-lab
e846edf25c6395a8c0cccdecec4b67bfe43d990a
[ "MIT" ]
null
null
null
notes/index-solution.ipynb
jigsawlabs-student/cte-lab
e846edf25c6395a8c0cccdecec4b67bfe43d990a
[ "MIT" ]
null
null
null
notes/index-solution.ipynb
jigsawlabs-student/cte-lab
e846edf25c6395a8c0cccdecec4b67bfe43d990a
[ "MIT" ]
null
null
null
28.884072
383
0.427331
[ [ [ "# CTEs Products Lab ", "_____no_output_____" ], [ "### Introduction", "_____no_output_____" ], [ "In this lesson, we'll practice working with CTEs. As we know CTEs allow to break our queries into multiple steps by creating a temporary table. And we perform our CTEs with the following syntax:", "_____no_output_____" ], [ "```SQL\nWITH table_name AS (\n SELECT ...\n)\n\nSELECT ... FROM table_name;\n```", "_____no_output_____" ], [ "Ok, let's get started.", "_____no_output_____" ], [ "### Getting set up", "_____no_output_____" ], [ "In this lesson we'll work with the northwind database, which is a sample ecommerce database.", "_____no_output_____" ], [ "We'll start by connecting to the database.", "_____no_output_____" ] ], [ [ "import sqlite3\nconn = sqlite3.connect('Northwind_small.sqlite')\ncursor = conn.cursor()", "_____no_output_____" ] ], [ [ "And then can see the various tables with the following.", "_____no_output_____" ] ], [ [ "cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\ncursor.fetchall()", "_____no_output_____" ] ], [ [ "Now we we'll only use a subset of the above tables -- focusing on the `Product`, `Supplier` and `Category` table. Ok, let's take a look at those tables.", "_____no_output_____" ] ], [ [ "import pandas as pd\npd.read_sql('SELECT * FROM Product LIMIT 2;', conn)", "_____no_output_____" ], [ "pd.read_sql(\"SELECT * FROM supplier LIMIT 2;\", conn)", "_____no_output_____" ], [ "pd.read_sql(\"SELECT * FROM category LIMIT 2;\", conn)", "_____no_output_____" ] ], [ [ "### Our First CTEs", "_____no_output_____" ], [ "Ok, now it's time to write our first CTE. Let's use a CTE to find the highest average unit price by category and supplier.\n\nIn doing so first create a temporary table called `avg_category_supplier` that computes the average unit prices, and then find the category and supplier combination with the highest average price.", "_____no_output_____" ] ], [ [ "sql = \"\"\"\nWITH avg_category_supplier as (\n SELECT CategoryId, SupplierId, AVG(UnitPrice) as avg_price \n FROM Product GROUP BY CategoryId, SupplierId\n)\n\nSELECT CategoryId, SupplierId, max(avg_price) as highest_avg_price from avg_category_supplier;\n\"\"\"", "_____no_output_____" ], [ "pd.read_sql(sql, conn)", "_____no_output_____" ] ], [ [ "Now let's use a CTE to find just the category with the lowest average price.", "_____no_output_____" ] ], [ [ "sql = \"\"\"\nWITH avg_category as (\n SELECT CategoryId, AVG(UnitPrice) as avg_price, AVG(UnitsInStock) as avg_units_stocked \n FROM Product GROUP BY CategoryId\n)\n\nSELECT CategoryId, min(avg_price) as lowest_avg_price from avg_category;\n\"\"\"", "_____no_output_____" ], [ "pd.read_sql(sql, conn)", "_____no_output_____" ] ], [ [ "Ok, so in this section, we used CTEs to perform multiple aggregations. We did so by using CTEs to perform an initial aggregation in a temporary table, and then queried from that temporary table. ", "_____no_output_____" ], [ "### CTEs for Preprocessing", "_____no_output_____" ], [ "Another use case for CTEs in queries is when joining together multiple tables. Remember that in general, when coding, we often perform some initial pre-processing, and then act on that preprocessed data. With CTEs, this may mean using temporary tables to first selecting just the columns that we need from a couple individual tables, and then performing the query from there.", "_____no_output_____" ], [ "For example, if we want to find the different categories of products made in the `British Isles` we only need a few columns from eahc table. So we'll use CTEs to first select columns from each of those individual tables, and then from there combine these temporary tables together. ", "_____no_output_____" ] ], [ [ "pd.read_sql(\"SELECT * FROM supplier LIMIT 2;\", conn)", "_____no_output_____" ], [ "sql = \"\"\"\nWITH select_supplier as (\n SELECT Id, CompanyName, Region FROM supplier\n), \n\nselect_category as (\n SELECT Id, CategoryName as name FROM Category\n),\n\nselect_product as (\n SELECT SupplierId, CategoryId, UnitPrice FROM Product\n)\n\nSELECT * FROM select_product \nJOIN select_supplier ON select_product.SupplierId = select_supplier.Id\nJOIN select_category ON select_product.CategoryId = select_category.Id\nWHERE Region = 'British Isles';\"\"\"", "_____no_output_____" ], [ "pd.read_sql(sql, conn)", "_____no_output_____" ] ], [ [ "So we can see that we the products made in the British Isles are Beverages, Condiments and Confections.", "_____no_output_____" ], [ "Now, take another look at the CTE above. Notice that there is only a single `WITH` statement, and we separate each temporary table by a comma.", "_____no_output_____" ], [ "```SQL\nWITH select_supplier as (\n SELECT Id, CompanyName, Region FROM supplier\n), \n\nselect_category as ( ...\n```", "_____no_output_____" ], [ "Ok, so now it's your turn to practice with using CTEs in this pattern. Use CTEs to find the the average product price per city, and order from most highest product price to lowest.\n\nSo the first step is to use CTEs to select just the necessary columns from each of the needed tables. And then from there we can join the tables together and perform the aggregation.", "_____no_output_____" ] ], [ [ "sql = \"\"\"\nWITH select_supplier as (\n SELECT Id, City FROM supplier\n), \n\nselect_product as (\n SELECT SupplierId, UnitPrice FROM Product\n)\n\nSELECT City, AVG(UnitPrice) as avg_price FROM select_supplier \nJOIN select_product ON select_supplier.Id = select_product.SupplierId\nGROUP BY City ORDER BY avg_price DESC LIMIT 5\n\"\"\"", "_____no_output_____" ], [ "pd.read_sql(sql, conn)", "_____no_output_____" ] ], [ [ "### Summary", "_____no_output_____" ], [ "In this lesson we practiced using CTEs. We use CTEs to create one or more temporary tables, and we then query from those tables. We saw two use cases for CTEs. With the first one, we use CTEs when chaining aggregate queries.\n\nAnd with the second one, we used the temporary tables for a sort of pre-processing on each table, before then joining these tables together. We separated each of the temporary tables with a comma.", "_____no_output_____" ], [ "```sql\nWITH select_supplier as (\n SELECT Id, CompanyName, Region FROM supplier\n), \n\nselect_category as ( ...\n```", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
4af2f27ed355918ebbc9f2d32b6d3d30ab976eaa
45,140
ipynb
Jupyter Notebook
CMa02.ipynb
kyagrd/grad-compiler2020
019ce1629803a95bef2db1181abc1bb02939772c
[ "MIT" ]
3
2020-09-02T07:32:40.000Z
2020-12-03T06:22:21.000Z
CMa02.ipynb
hnu-pl/grad-compiler2020
019ce1629803a95bef2db1181abc1bb02939772c
[ "MIT" ]
null
null
null
CMa02.ipynb
hnu-pl/grad-compiler2020
019ce1629803a95bef2db1181abc1bb02939772c
[ "MIT" ]
null
null
null
32.948905
426
0.462074
[ [ [ "# 2. Imperative Programming Languages\n\n우선 2.5까지 나오는 내용 중에서 빼고 살펴보는데, 지난번에 `CMa01.ipynb`에 작성했던 컴파일러 코드에서 문제점을 수정해 보자.", "_____no_output_____" ], [ "---\n컴파일 타겟이 되는 VM의 단순화된 버전을 하스켈로 구현", "_____no_output_____" ] ], [ [ "-- {-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n\ndata Instr pa\n = HALT | NEG | ADD | SUB | MUL | DIV\n | AND | OR | EQU | NEQ | GR | GEQ | LE | LEQ\n | POP | DUP\n | LOADc Int | LOAD -- | LOADr | LOADrc\n | STORE -- | STOREr\n | JUMP pa | JUMPz pa | JUMPi pa\n -- | CALL | RETURN | ENTER | ALLOC | SLIDE | MARK\n -- | NEW\n deriving (Eq, Ord, Show, Functor)\n\ntype CMa = (Code, Stack)\n\ntype Stack = [Value]\ntype Value = Int\n\n-- stack address as reverse index of stack\ntype SA = Int\n\ntype Code = [Instr PA]\n\n-- program address representation\nnewtype PA = PA Code deriving (Eq,Ord,Show)", "_____no_output_____" ], [ "import Data.List\n\ndata DotDotDot = DotDotDot\n\ninstance Show DotDotDot where\n show _ = \"...\"\n\n-- to prevent infinite printing\ninstance {-# OVERLAPS #-} Show Code where\n show is = \"[\"++intercalate \",\" (show . fmap (\\(PA _) -> DotDotDot) <$> is)++\"]\"\n\n-- to prevent infinite printing\ninstance {-# OVERLAPS #-} Show CMa where\n show (is,vs) = \"{ stack = \"++show vs++\"\\n , code = \"++show is++\" }\"", "_____no_output_____" ], [ "-- load and store operation for Stack\nload :: SA -> Stack -> Value\nload i vs = reverse vs !! i\n\nstore :: SA -> Value -> Stack -> Stack\nstore i x vs = vs1++x:vs2\n where\n (vs1,_:vs2) = splitAt (length vs - 1 - i) vs", "_____no_output_____" ], [ "import Data.Bits\n\nstep :: CMa -> CMa\nstep (HALT : _, vs) = ([], vs)\nstep (NEG : is, v : vs) = (is, (-v):vs)\nstep (ADD : is, v2:v1:vs) = (is, v1 + v2 : vs)\nstep (SUB : is, v2:v1:vs) = (is, v1 - v2 : vs)\nstep (MUL : is, v2:v1:vs) = (is, v1 * v2 : vs)\nstep (DIV : is, v2:v1:vs) = (is, v1 `div` v2 : vs)\nstep (AND : is, v2:v1:vs) = (is, (v1 .&. v2) : vs)\nstep (OR : is, v2:v1:vs) = (is, (v1 .|. v2) : vs)\nstep (EQU : is, v2:v1:vs) = (is, b2i(v1 == v2) : vs)\nstep (NEQ : is, v2:v1:vs) = (is, b2i(v1 /= v2) : vs)\nstep (GR : is, v2:v1:vs) = (is, b2i(v1 > v2) : vs)\nstep (GEQ : is, v2:v1:vs) = (is, b2i(v1 >= v2) : vs)\nstep (LE : is, v2:v1:vs) = (is, b2i(v1 < v2) : vs)\nstep (LEQ : is, v2:v1:vs) = (is, b2i(v1 <= v2) : vs)\nstep (POP : is, _:vs) = (is, vs)\nstep (DUP : is, v:vs) = (is, v:v:vs)\nstep (LOADc v : is, vs) = (is, v:vs)\nstep (LOAD : is, a:vs) = (is, v:vs) where v = load a vs \nstep (STORE : is, a:n:vs) = (is, n:vs') where vs' = store a n vs\nstep (JUMP (PA c) : _, vs) = (c, vs)\nstep (JUMPz (PA c) : _, 0:vs) = (c, vs)\nstep (JUMPz _ : is, _:vs) = (is, vs)\nstep vm = error $ \"VM is stuck: \"++show vm\n\ni2b 0 = False\ni2b 1 = True\n\nb2i False = 0\nb2i True = 1\n\nexec :: CMa -> [CMa]\nexec vm@([],_) = [vm]\nexec vm = vm : exec (step vm)\n\nrun :: CMa -> CMa\nrun = last . exec", "_____no_output_____" ], [ "type LabeledCode = [LabeledInstr]\ndata LabeledInstr = Label :. Instr Label deriving Show\ntype Label = String\n\nlbis1 :: LabeledCode\nlbis1 =\n [ \"\" :. LOADc 3\n , \"loop\" :. LOADc 1\n , \"\" :. SUB\n , \"\" :. DUP\n , \"\" :. JUMPz \"end\"\n , \"\" :. JUMP \"loop\"\n , \"end\" :. HALT\n ]", "_____no_output_____" ], [ "import Data.Maybe\n\nassemble :: LabeledCode -> Code\nassemble lbis = is'\n where\n is' = map (fmap lb2a) is\n (lbs,is) = unzip [(lb,i) | lb :. i <- lbis]\n lb2a \"\" = error \"empty string label\"\n lb2a lb = PA $ tails is' !! elemIndex' lb lbs\n\nelemIndex' x xs = fromJust (elemIndex x xs)", "_____no_output_____" ], [ "is1 :: Code\nis1 = [ LOADc 3 ] ++ loop\nloop = [ LOADc 1\n , SUB\n , DUP\n , JUMPz (PA end)\n , JUMP (PA loop) ] ++ end\nend = [ HALT ]", "_____no_output_____" ], [ "assemble lbis1\nis1", "_____no_output_____" ], [ "mapM_ print . exec $ (is1,[])", "_____no_output_____" ], [ "mapM_ print . exec $ (assemble lbis1,[])", "_____no_output_____" ] ], [ [ "<br>\n\n이제 책 Fig.2.8 (p.13) 에 나온 C언어 코드를 CMa 명령 코드으로 컴파일하는 함수들을 직접 구현해 보자.\n**식**(expression)을 컴파일하는 `codeR` 및 `codeL`과\n**문**(statement)을 컴파일하는 `code`를 하스켈로 작성해 보자.", "_____no_output_____" ] ], [ [ "data Expr\n = Lit Int -- n (integer literal)\n | Var String -- x\n | Neg Expr -- -e\n | Add Expr Expr -- e1 + 2e\n | Sub Expr Expr -- e1 - e2\n | Mul Expr Expr -- e1 * e2\n | Div Expr Expr -- e1 / e2\n | And Expr Expr -- e1 + e2\n | Or Expr Expr -- e1 || e2\n | Equ Expr Expr -- e1 == e2\n | Neq Expr Expr -- e1 /= e2\n | Gr Expr Expr -- e1 > e2\n | Geq Expr Expr -- e1 >= e2\n | Le Expr Expr -- e1 <= e2\n | Leq Expr Expr -- e1 < e2\n | Assign Expr Expr -- eL <- eR (assignment expression. 실제 C문법으로는 eL = eR)\n deriving (Eq,Ord,Show)\n\ndata Stmt\n = EStmt Expr -- e; (expression as statement)\n | Block [Stmt] -- { s1; ...; sn; }\n | If Expr Stmt (Maybe Stmt) -- if (e) s 또는 if (e) s1 else s0\n | While Expr Stmt -- while (e) s\n | For (Expr,Expr,Expr) Stmt -- for (e1;e2;e3) s\n deriving (Eq,Ord,Show)", "_____no_output_____" ], [ "[1,2,3] ++ [4,5,6]", "_____no_output_____" ], [ "(4 :) [5,6,7]", "_____no_output_____" ], [ "import Data.Map (Map, (!), (!?))\nimport qualified Data.Map as Map\n\ntype AEnv = Map String SA\n\ncodeR :: Expr -> AEnv -> (Code -> Code)\ncodeR (Lit q) _ = (LOADc q :)\ncodeR (Var x) ρ = codeL (Var x) ρ . (LOAD :)\ncodeR (Neg e) ρ = codeR e ρ . (NEG :)\ncodeR (Add e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (ADD :)\ncodeR (Sub e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (SUB :)\ncodeR (Mul e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (MUL :)\ncodeR (Div e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (DIV :)\ncodeR (And e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (AND :)\ncodeR (Or e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (OR :)\ncodeR (Equ e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (EQU :)\ncodeR (Neq e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (NEQ :)\ncodeR (Gr e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (GR :)\ncodeR (Geq e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (GEQ :)\ncodeR (Le e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (LE :)\ncodeR (Leq e1 e2) ρ = codeR e1 ρ . codeR e2 ρ . (LEQ :)\ncodeR (Assign eL eR) ρ = codeR eR ρ . codeL eL ρ . (STORE :)\ncodeR e _ = error $ \"R-value not defined: \"++show e\n\ncodeL :: Expr -> AEnv -> (Code -> Code)\ncodeL (Var x) ρ = (LOADc (ρ ! x) :)\ncodeL e _ = error $ \"L-value not defined: \"++show e\n\ncode :: Stmt -> AEnv -> (Code -> Code)\ncode (EStmt e) ρ = codeR e ρ . (POP :)\ncode (Block ss) ρ = foldr (.) id [code s ρ | s <- ss]\ncode (If e s Nothing) ρ =\n \\k -> codeR e ρ . (JUMPz (PA k) :)\n . code s ρ\n $ k\ncode (If e s1 (Just s0)) ρ =\n \\k -> codeR e ρ . (JUMPz (PA (c0 k)) :)\n . c1 . (JUMP (PA k) :)\n . c0\n $ k\n where\n c1 = code s1 ρ\n c0 = code s0 ρ\ncode (While e s) ρ = c\n where\n c = \\k -> codeR e ρ\n . (JUMPz (PA k) :)\n . code s ρ\n . (JUMP (PA (c k)) :)\n $ k\ncode (For (e1,e2,e3) s) ρ = code (Block ss) ρ\n where ss = [ EStmt e1\n , While e2 $ Block [s, EStmt e3]\n ] ", "_____no_output_____" ] ], [ [ "지금은 변수 메모리 공간은 미리 할당되어 있다고 가정한다.\n즉, 적절한 *주소환경*(address environment)과 그에 맞는 크기의 stack으로 시작한다고 가정한다는 말이다.\n\n예컨대, 아래 코드를 컴파일한다면\n$\\rho = \\{x\\mapsto 0,\\, i\\mapsto 1\\}$라는 주소환경으로\n$x$와 $i$에 값을 저장할 주소를 미리 정해 놓고 초기 스택도 그에\n맞춰 미리 크기를 잡아 놓고 시작하기로 하자. \n\n```c\nint x = 1000;\nint i = 1;\n\nx <- x + i;\ni <- i + 1;\n```\n\n주소환경과 초기 스택을 적절하게 구성해 놓은 상태로 시작한다면 위 코드는 사실상 아래와 같은 코드를 컴파일하는 것과 같다.\n\n```c\nx <- 1000;\ni <- 1;\n\nx <- x + i;\ni <- i + 1;\n```", "_____no_output_____" ] ], [ [ "stmt3 = Block \n [ EStmt $ Assign (Var \"x\") (Lit 1000)\n , EStmt $ Assign (Var \"i\") (Lit 1)\n , EStmt $ Assign (Var \"x\") (Add (Var \"x\") (Var \"i\"))\n , EStmt $ Assign (Var \"i\") (Add (Var \"i\") (Lit 1))\n ]", "_____no_output_____" ], [ "is3 = code stmt3 (Map.fromList [(\"x\",0),(\"i\",1)])", "_____no_output_____" ], [ "is3 []\nis3 [HALT]\nis3 [DUP,POP,HALT]", "_____no_output_____" ], [ "mapM_ print $ exec (is3 [],[0,0])", "_____no_output_____" ], [ "run (is3 [],[1,1000])", "_____no_output_____" ] ], [ [ "<br>\n\n이번엔 이 프로그램을 컴파일해 보자.\n\n```c\nint x = 1000;\nint i = 1;\nwhile (i < 5) {\n x <- x + i;\n i <- i + 1;\n}\n```\n\n마찬가지로 $x$와 $i$에 대한 적절한 주소환경 $\\{x\\mapsto 0,\\,i\\mapsto 1\\}$과 초기 스택으로 시작한다고 가정한다면 아래 코드를 컴파일하면 되는 것이다.\n```c\nx <- 1000;\ni <- 1;\nwhile (i < 5) {\n x <- x + i;\n i <- i + 1;\n}\n```", "_____no_output_____" ] ], [ [ "stmt41 = Block \n [ EStmt $ Assign (Var \"x\") (Lit 1000) -- x <- 1000;\n , EStmt $ Assign (Var \"i\") (Lit 1) -- i <- 1;\n ]\n\nstmt42 = Block\n [ While (Le (Var \"i\") (Lit 5)) $ Block -- while (i < 5) {\n [ EStmt $ Assign (Var \"x\") (Add (Var \"x\") (Var \"i\")) -- x <- x + i;\n , EStmt $ Assign (Var \"i\") (Add (Var \"i\") (Lit 1)) -- i <- i + 1;\n ] -- }\n ]\n\nstmt43 = Block\n [ EStmt $ Assign (Var \"x\") (Add (Var \"x\") (Lit 100)) -- x <- x + 100;\n , EStmt $ Assign (Var \"i\") (Add (Var \"i\") (Lit 100)) -- i <- i + 100;\n ]", "_____no_output_____" ], [ "rho4 = Map.fromList [(\"x\",0),(\"i\",1)]\nis41 = code stmt41 rho4\nis42 = code stmt42 rho4\nis43 = code stmt43 rho4", "_____no_output_____" ], [ "is41 . is42 $ []\nis41 . is42 . is43 $ []", "_____no_output_____" ], [ "run (is41 . is41 $ [], [0,0])", "_____no_output_____" ], [ "run (is41 . is42 $ [], [0,0])", "_____no_output_____" ], [ "run (is41 . is42 . is43 $ [], [0,0])", "_____no_output_____" ], [ "run (is41 . is43 . is43 $ [], [0,0]) -- stmt43을 두번 실행했으므로 100을 두번씩 더해 200씩 증가", "_____no_output_____" ] ], [ [ "<br>\n\n정리하자면, 컴파일 함수 `codeR`, `codeL`, `code`가 *식*(`Expr`) 또는 *문*(`Stmt`)과 *주소환경*(`AEnv`)을 받아 고정된 코드(`Code`)를 결과로 계산하는 대신,\n뒤이어 오는 **나머지 할 일** 코드를 인자로 받아 전체 코드를 계산해내는 코드 변환 함수(`Code -> Code`)를 결과로 계산하도록 수정하였다.\n이렇게 함으로써 조건문이나 반복문에서 그 다음 뒤이어 아직 정해지지 않은 코드 위치로 이동하는 코드를 작성하기에 용이해진다.\n\n이렇게 **나머지 할 일**이라는 개념을 전문용어로는 continuation이라고 한다. 순차적으로 진행되지 않는 계산을 표현하기 위한 개념으로 다양한 곳에 활용된다.", "_____no_output_____" ] ], [ [ "stmt5 = Block \n [ EStmt $ Assign (Var \"i\") (Lit 1) -- i <- 1;\n , While (Le (Var \"i\") (Lit 5)) $ -- while (i < 5)\n EStmt $ Assign (Var \"i\") (Add (Var \"i\") (Lit 1)) -- i <- i + 1;\n , EStmt $ Assign (Var \"i\") (Add (Var \"i\") (Lit 1)) -- i <- i + 1;\n ]", "_____no_output_____" ], [ "c5 = code stmt5 (Map.fromList [(\"i\",0)])", "_____no_output_____" ], [ ":type c5", "_____no_output_____" ], [ "c5 [HALT]", "_____no_output_____" ], [ "mapM_ print $ exec (c5 [HALT], [0])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4af2f9952f1e00a464ebcf499a4d81ed5caefaa1
6,115
ipynb
Jupyter Notebook
Kaggle/New York City Taxi Fare Prediction/How to clean and pre process large csv files.ipynb
dimitreOliveira/MachineLearning
ae5907ef1bf2620b62a33176fa1ef5208ed3bb91
[ "MIT" ]
13
2019-03-11T17:53:02.000Z
2022-03-10T14:18:17.000Z
Kaggle/New York City Taxi Fare Prediction/How to clean and pre process large csv files.ipynb
dimitreOliveira/MachineLearning
ae5907ef1bf2620b62a33176fa1ef5208ed3bb91
[ "MIT" ]
1
2019-03-04T14:18:13.000Z
2019-03-05T20:56:22.000Z
Kaggle/New York City Taxi Fare Prediction/How to clean and pre process large csv files.ipynb
dimitreOliveira/MachineLearning
ae5907ef1bf2620b62a33176fa1ef5208ed3bb91
[ "MIT" ]
6
2019-03-01T12:57:43.000Z
2021-12-20T01:04:08.000Z
135.888889
4,590
0.596075
[ [ [ "## Hi, i was having a hard time trying to load this huge data set as a pandas data frame on my pc, so i searched for alternative ways of doing this as i don't want to pay for cloud services and don't have access to better machines.\n### actually the solution was pretty simple, so i'm sharing what i ended up with, maybe i can help other struggling with the same problem.\nobs: this approach won't let you analyse or summarize the data as pandas data frames would (at least not easily),\nany criticism or tips are welcomed.", "_____no_output_____" ] ], [ [ "import csv\nfrom datetime import datetime\n\n\ndef clean_data(input_data_path='../input/train.csv', output_data_path='../data/train_cleaned.csv'):\n \"\"\"\n Clean the data set, removing any row with missing values,\n delimiter longitudes and latitudes to fit only NY city values,\n only fare amount greater than 0,\n and passenger count greater than 0 and lesser than 7,\n i also removed the header as i'm using tensorflow to load data.\n :param input_data_path: path containing the raw data set.\n :param output_data_path: path to write the cleaned data.\n \"\"\"\n with open(input_data_path, 'r') as inp, open(output_data_path, 'w', newline='') as out:\n writer = csv.writer(out)\n count = 0\n for row in csv.reader(inp):\n # Remove header\n if count > 0:\n # Only rows with non-null values\n if len(row) == 8:\n try:\n fare_amount = float(row[1])\n pickup_longitude = float(row[3])\n pickup_latitude = float(row[4])\n dropoff_longitude = float(row[5])\n dropoff_latitude = float(row[6])\n passenger_count = float(row[7])\n if ((-76 <= pickup_longitude <= -72) and (-76 <= dropoff_longitude <= -72) and\n (38 <= pickup_latitude <= 42) and (38 <= dropoff_latitude <= 42) and\n (1 <= passenger_count <= 6) and fare_amount > 0):\n writer.writerow(row)\n except:\n pass\n count += 1\n\n\ndef pre_process_train_data(input_data_path='data/train_cleaned.csv', output_data_path='data/train_processed.csv'):\n \"\"\"\n Pre process the train data, deriving, year, month, day and hour for each row.\n :param input_data_path: path containing the full data set.\n :param output_data_path: path to write the pre processed set.\n \"\"\"\n with open(input_data_path, 'r') as inp, open(output_data_path, 'w', newline='') as out:\n writer = csv.writer(out)\n for row in csv.reader(inp):\n pickup_datetime = datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S %Z')\n row.append(pickup_datetime.year)\n row.append(pickup_datetime.month)\n row.append(pickup_datetime.day)\n row.append(pickup_datetime.hour)\n row.append(pickup_datetime.weekday())\n writer.writerow(row)\n\n\ndef pre_process_test_data(input_data_path='data/test.csv', output_data_path='data/test_processed.csv'):\n \"\"\"\n Pre process the test data, deriving, year, month, day and hour for each row.\n :param input_data_path: path containing the full data set.\n :param output_data_path: path to write the pre processed set.\n \"\"\"\n with open(input_data_path, 'r') as inp, open(output_data_path, 'w', newline='') as out:\n writer = csv.writer(out)\n count = 0\n for row in csv.reader(inp):\n if count > 0:\n pickup_datetime = datetime.strptime(row[1], '%Y-%m-%d %H:%M:%S %Z')\n row.append(pickup_datetime.year)\n row.append(pickup_datetime.month)\n row.append(pickup_datetime.day)\n row.append(pickup_datetime.hour)\n row.append(pickup_datetime.weekday())\n writer.writerow(row)\n else:\n # Only the header\n writer.writerow(row)\n count += 1\n\n\ndef split_data(input_data_path, train_data_path, validation_data_path, ratio=30):\n \"\"\"\n Splits the csv file (meant to generate train and validation sets).\n :param input_data_path: path containing the full data set.\n :param train_data_path: path to write the train set.\n :param validation_data_path: path to write the validation set.\n :param ratio: ration to split train and validation sets, (default: 1 of every 30 rows will be validation or 0,033%)\n \"\"\"\n with open(input_data_path, 'r') as inp, open(train_data_path, 'w', newline='') as out1, \\\n open(validation_data_path, 'w', newline='') as out2:\n writer1 = csv.writer(out1)\n writer2 = csv.writer(out2)\n count = 0\n for row in csv.reader(inp):\n if count % ratio == 0:\n writer2.writerow(row)\n else:\n writer1.writerow(row)\n count += 1\n", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
4af2feebf7ee62a460515984c5572e93a3d07e9b
392,549
ipynb
Jupyter Notebook
Traffic_Sign_Classifier.ipynb
vivek7mehta/CarND-Traffic-Sign-Classifier
76012d55c3063c5c52e69d3053a896d8e23e7c3d
[ "MIT" ]
null
null
null
Traffic_Sign_Classifier.ipynb
vivek7mehta/CarND-Traffic-Sign-Classifier
76012d55c3063c5c52e69d3053a896d8e23e7c3d
[ "MIT" ]
null
null
null
Traffic_Sign_Classifier.ipynb
vivek7mehta/CarND-Traffic-Sign-Classifier
76012d55c3063c5c52e69d3053a896d8e23e7c3d
[ "MIT" ]
null
null
null
483.434729
169,542
0.926659
[ [ [ "# Self-Driving Car Engineer Nanodegree\n\n## Deep Learning\n\n### Project: Build a Traffic Sign Recognition Classifier", "_____no_output_____" ], [ "---\n### Step 0: Imports", "_____no_output_____" ] ], [ [ "# imported pacakges which are being used in project\nimport pickle\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.contrib.layers import flatten\nimport matplotlib.pyplot as plt\nimport cv2\nfrom scipy import ndimage, misc\nimport numpy as np\nfrom collections import Counter\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ] ], [ [ "### Step 1: Load the data", "_____no_output_____" ] ], [ [ "training_file = './traffic-signs-data/train.p'\nvalidation_file='./traffic-signs-data/valid.p'\ntesting_file = './traffic-signs-data/test.p'\n\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\nwith open(validation_file, mode='rb') as f:\n valid = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n test = pickle.load(f)\n \nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']", "_____no_output_____" ] ], [ [ "### Step 2: Dataset Summary", "_____no_output_____" ] ], [ [ "n_train = len(X_train)\nn_validation = len(X_valid)\nn_test = len(X_test)\nimage_shape = X_train[0].shape\nn_classes = len(set(train['labels']))\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)", "Number of training examples = 34799\nNumber of testing examples = 12630\nImage data shape = (32, 32, 3)\nNumber of classes = 43\n" ] ], [ [ "### Step 3: Exploratory Visualization of data", "_____no_output_____" ] ], [ [ "%matplotlib inline\nl = Counter(y_train)\nprint()\nplt.figure(figsize=(13, 6))\nplt.ylabel('Training examples',rotation='horizontal')\nplt.title('Graphical representation of number of training example of each classes')\nplt.xlabel('Classes')\nfor i in range(n_classes):\n plt.bar(i,l.get(i),0.8)", "\n" ], [ "fig=plt.figure(figsize=(15, 6))\ncolumns = 5\nrows = 4\nprint()\nplt.title('Visualization of different images from training set')\nfor i in range(1, columns*rows +1):\n #img = np.random.randint(10, size=(h,w))\n fig.add_subplot(rows, columns, i)\n plt.imshow(X_train[np.where(y_train==i)[0][0]])\nplt.show()", "\n" ] ], [ [ "* In first visulization we can see that training set is distributed propperly for various classes.\n* Second visulization shows traffic signs from different classes.", "_____no_output_____" ], [ "### Step 4: Architecture Design", "_____no_output_____" ], [ "#### Pre-process the Data Set", "_____no_output_____" ] ], [ [ "#Pre-processing training data\n\nX_train = 0.299*X_train[:,:,:,0] + 0.587*X_train[:,:,:,1] + 0.114*X_train[:,:,:,2]\nX_train = X_train.reshape(X_train.shape + (1,))\nX_train = (X_train - 128.0) / 128.0\n\n#Pre-processing validation data\n\nX_valid = 0.299*X_valid[:,:,:,0] + 0.587*X_valid[:,:,:,1] + 0.114*X_valid[:,:,:,2]\nX_valid = X_valid.reshape(X_valid.shape + (1,))\nX_valid = (X_valid - 128.0) / 128.0\n\n#Pre-processing test data\n\nX_test = 0.299*X_test[:,:,:,0] + 0.587*X_test[:,:,:,1] + 0.114*X_test[:,:,:,2]\nX_test = X_test.reshape(X_test.shape + (1,))\nX_test = (X_test - 128.0) / 128.0\n\n#Shuffling training set\nX_train,y_train = shuffle(X_train,y_train)", "_____no_output_____" ] ], [ [ "#### Model Architecture", "_____no_output_____" ] ], [ [ "EPOCHS = 40\nBATCH_SIZE = 128\n\ndef LeNet(x,keep_prob): \n # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer\n mu = 0\n sigma = 0.1\n \n # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.\n conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma))\n conv1_b = tf.Variable(tf.zeros(6))\n conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b\n\n # SOLUTION: Activation.\n conv1 = tf.nn.relu(conv1)\n\n # SOLUTION: Pooling. Input = 32x32x6. Output = 14x14x6.\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n \n # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.\n conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))\n conv2_b = tf.Variable(tf.zeros(16))\n conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\n \n # SOLUTION: Activation.\n conv2 = tf.nn.relu(conv2)\n\n # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # SOLUTION: Flatten. Input = 5x5x16. Output = 400.\n fc0 = flatten(conv2)\n #fc0 = tf.nn.dropout(fc0,0.5)\n \n # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.\n fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))\n fc1_b = tf.Variable(tf.zeros(120))\n fc1 = tf.matmul(fc0, fc1_W) + fc1_b\n \n # SOLUTION: Activation.\n fc1 = tf.nn.relu(fc1)\n \n fc1 = tf.nn.dropout(fc1,keep_prob)\n \n # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.\n fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))\n fc2_b = tf.Variable(tf.zeros(84))\n fc2 = tf.matmul(fc1, fc2_W) + fc2_b\n \n # SOLUTION: Activation.\n fc2 = tf.nn.relu(fc2)\n #fc2 = tf.nn.dropout(fc2,0.5)\n \n # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.\n fc3_W = tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = mu, stddev = sigma))\n fc3_b = tf.Variable(tf.zeros(n_classes))\n logits = tf.matmul(fc2, fc3_W) + fc3_b\n \n return logits", "_____no_output_____" ] ], [ [ "#### Defining operations", "_____no_output_____" ] ], [ [ "x = tf.placeholder(tf.float32, (None, 32, 32, 1))\ny = tf.placeholder(tf.int32, (None))\nkeep_prob = tf.placeholder(tf.float32, (None))\none_hot_y = tf.one_hot(y, n_classes)\n\nrate = 0.002\n\nlogits = LeNet(x,keep_prob)\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\nloss_operation = tf.reduce_mean(cross_entropy)\noptimizer = tf.train.AdamOptimizer(learning_rate = rate)\ntraining_operation = optimizer.minimize(loss_operation)\ncorrect_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))", "_____no_output_____" ] ], [ [ "### Step 5: Train and test", "_____no_output_____" ], [ "#### Evaluating a model", "_____no_output_____" ] ], [ [ "saver = tf.train.Saver()\ndef evaluate(X_data, y_data):\n num_examples = len(X_data)\n total_accuracy = 0\n sess = tf.get_default_session()\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:1})\n total_accuracy += (accuracy * len(batch_x))\n return total_accuracy / num_examples", "_____no_output_____" ] ], [ [ "#### Training a model", "_____no_output_____" ] ], [ [ "with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n num_examples = len(X_train)\n print(\"Training...\")\n print()\n plt.figure(figsize=(15, 6))\n for i in range(EPOCHS):\n X_train, y_train = shuffle(X_train, y_train)\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_x, batch_y = X_train[offset:end], y_train[offset:end]\n sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:0.5})\n \n validation_accuracy = evaluate(X_valid, y_valid)\n train = evaluate(X_train, y_train)\n \n plt.plot(i,validation_accuracy,'ro')\n plt.plot(i,train,'b+')\n print(\"EPOCH {} ...\".format(i+1))\n print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n print(\"Train_acc: \", validation_accuracy)\n print()\n saver.save(sess, './lenet')\n print(\"Model saved\")", "Training...\n\nEPOCH 1 ...\nValidation Accuracy = 0.798\nTrain_acc: 0.798185940557\n\nEPOCH 2 ...\nValidation Accuracy = 0.902\nTrain_acc: 0.90226757321\n\nEPOCH 3 ...\nValidation Accuracy = 0.909\nTrain_acc: 0.909070295055\n\nEPOCH 4 ...\nValidation Accuracy = 0.932\nTrain_acc: 0.931972789143\n\nEPOCH 5 ...\nValidation Accuracy = 0.933\nTrain_acc: 0.933106575964\n\nEPOCH 6 ...\nValidation Accuracy = 0.948\nTrain_acc: 0.948072562629\n\nEPOCH 7 ...\nValidation Accuracy = 0.945\nTrain_acc: 0.944897959184\n\nEPOCH 8 ...\nValidation Accuracy = 0.954\nTrain_acc: 0.953741496599\n\nEPOCH 9 ...\nValidation Accuracy = 0.957\nTrain_acc: 0.957369614512\n\nEPOCH 10 ...\nValidation Accuracy = 0.948\nTrain_acc: 0.948299319728\n\nEPOCH 11 ...\nValidation Accuracy = 0.959\nTrain_acc: 0.958503401361\n\nEPOCH 12 ...\nValidation Accuracy = 0.955\nTrain_acc: 0.954648526077\n\nEPOCH 13 ...\nValidation Accuracy = 0.955\nTrain_acc: 0.954875283447\n\nEPOCH 14 ...\nValidation Accuracy = 0.949\nTrain_acc: 0.949433106576\n\nEPOCH 15 ...\nValidation Accuracy = 0.965\nTrain_acc: 0.965079365079\n\nEPOCH 16 ...\nValidation Accuracy = 0.946\nTrain_acc: 0.945804988662\n\nEPOCH 17 ...\nValidation Accuracy = 0.947\nTrain_acc: 0.94716553288\n\nEPOCH 18 ...\nValidation Accuracy = 0.956\nTrain_acc: 0.956235827664\n\nEPOCH 19 ...\nValidation Accuracy = 0.963\nTrain_acc: 0.963038548753\n\nEPOCH 20 ...\nValidation Accuracy = 0.961\nTrain_acc: 0.961451247166\n\nEPOCH 21 ...\nValidation Accuracy = 0.955\nTrain_acc: 0.955328798186\n\nEPOCH 22 ...\nValidation Accuracy = 0.964\nTrain_acc: 0.963718820862\n\nEPOCH 23 ...\nValidation Accuracy = 0.956\nTrain_acc: 0.955782312682\n\nEPOCH 24 ...\nValidation Accuracy = 0.956\nTrain_acc: 0.956235827664\n\nEPOCH 25 ...\nValidation Accuracy = 0.960\nTrain_acc: 0.960317460317\n\nEPOCH 26 ...\nValidation Accuracy = 0.961\nTrain_acc: 0.960544217687\n\nEPOCH 27 ...\nValidation Accuracy = 0.966\nTrain_acc: 0.966213152198\n\nEPOCH 28 ...\nValidation Accuracy = 0.963\nTrain_acc: 0.96281179114\n\nEPOCH 29 ...\nValidation Accuracy = 0.969\nTrain_acc: 0.969387755372\n\nEPOCH 30 ...\nValidation Accuracy = 0.958\nTrain_acc: 0.957823129522\n\nEPOCH 31 ...\nValidation Accuracy = 0.948\nTrain_acc: 0.947619047619\n\nEPOCH 32 ...\nValidation Accuracy = 0.964\nTrain_acc: 0.963945578231\n\nEPOCH 33 ...\nValidation Accuracy = 0.962\nTrain_acc: 0.962358276644\n\nEPOCH 34 ...\nValidation Accuracy = 0.969\nTrain_acc: 0.968707482993\n\nEPOCH 35 ...\nValidation Accuracy = 0.964\nTrain_acc: 0.964399092971\n\nEPOCH 36 ...\nValidation Accuracy = 0.967\nTrain_acc: 0.966666666937\n\nEPOCH 37 ...\nValidation Accuracy = 0.956\nTrain_acc: 0.956009070295\n\nEPOCH 38 ...\nValidation Accuracy = 0.964\nTrain_acc: 0.963718820862\n\nEPOCH 39 ...\nValidation Accuracy = 0.973\nTrain_acc: 0.973015873286\n\nEPOCH 40 ...\nValidation Accuracy = 0.947\nTrain_acc: 0.947392290249\n\nModel saved\n" ] ], [ [ "#### Testing pipeline", "_____no_output_____" ] ], [ [ "with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n test_accuracy = evaluate(X_test, y_test)\n print(\"Test Accuracy = {:.3f}\".format(test_accuracy))", "Test Accuracy = 0.944\n" ] ], [ [ "### Step 6: Test a Model on New Images", "_____no_output_____" ], [ "#### Load and Output the Images", "_____no_output_____" ] ], [ [ "X_new = []\nfor i in range(1,9):\n im = cv2.imread(\"./examples/Image\"+str(i)+\".jpg\")\n im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)\n im = misc.imresize(im, (32, 32))\n X_new.append(im)\n \nX_new = np.asarray(X_new)", "_____no_output_____" ], [ "fig=plt.figure(figsize=(15, 6))\ncolumns = 4\nrows = 2\nplt.title('New data set')\nj = 0\nfor i in range(1, columns*rows +1):\n fig.add_subplot(rows, columns, i)\n plt.imshow(X_new[j])\n j+=1\nplt.show()\n\n#pre-process\n\nX_newt = 0.299*X_new[:,:,:,0] + 0.587*X_new[:,:,:,1] + 0.114*X_new[:,:,:,2]\nX_newt = X_newt.reshape(X_newt.shape + (1,))\nX_newt = (X_newt - 128.0) / 128.0", "_____no_output_____" ] ], [ [ "#### Predict the Sign Type for Each Image", "_____no_output_____" ] ], [ [ "#y_new = [13,33,25,28,44,]\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n scores = sess.run(logits, feed_dict={x: X_newt, keep_prob:1})\n scores = tf.nn.softmax(scores)\n scores = tf.nn.top_k(scores,k=5)\n scores = sess.run(scores)", "_____no_output_____" ] ], [ [ "#### Analyze Performance", "_____no_output_____" ] ], [ [ "#Importing CSV file\n\nimport csv\nwith open('signnames.csv', mode='r') as infile:\n reader = csv.reader(infile)\n mydict = {rows[0]:rows[1] for rows in reader}", "_____no_output_____" ] ], [ [ "#### Output Top 5 Softmax Probabilities For Each Image Found on the Web", "_____no_output_____" ] ], [ [ "fig=plt.figure(figsize=(20, 15))\ncolumns = 4\nrows = 2\nj = 0\nfor i in range(1, columns*rows +1):\n fig.add_subplot(rows, columns, i)\n plt.title('Top Predicted : '+str(mydict[str(scores[1][j][0])])+' \\n\\n top 5 softmax probabilities'\n + '\\n' + str(scores[0][j][0]) + ' : ' +str(mydict[str(scores[1][j][0])])\n +'\\n' + str(scores[0][j][1]) + ' : ' +str(mydict[str(scores[1][j][1])])\n +'\\n'+ str(scores[0][j][2]) + ' : ' +str(mydict[str(scores[1][j][2])])\n +'\\n'+ str(scores[0][j][3]) + ' : ' +str(mydict[str(scores[1][j][3])])\n +'\\n'+ str(scores[0][j][4])+ ' : ' +str(mydict[str(scores[1][j][4])])\n )\n plt.imshow(X_new[j])\n j+=1\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af3248ae34941007154272a3329999e6ce0549b
112,279
ipynb
Jupyter Notebook
European_soccer_data_analyse_with_SQLit.ipynb
SSaberipouya/SQL_projects
9045fd9f267dde4dc0f71a5f33bb89cb34837b5a
[ "MIT" ]
null
null
null
European_soccer_data_analyse_with_SQLit.ipynb
SSaberipouya/SQL_projects
9045fd9f267dde4dc0f71a5f33bb89cb34837b5a
[ "MIT" ]
null
null
null
European_soccer_data_analyse_with_SQLit.ipynb
SSaberipouya/SQL_projects
9045fd9f267dde4dc0f71a5f33bb89cb34837b5a
[ "MIT" ]
null
null
null
34.346589
302
0.334987
[ [ [ "# European Soccer Database for data analysis Using SQLite,\n- In this report, I will analyse the Europeon Soccer Dataset to answer some questions. This dataset comes from Kaggle and is well suited for data analysis and machine learning. It contains data for 25k+ soccer matches, 10k+ players, and teams from several European countries from 2008 to 2016.\nhttps://www.kaggle.com/hugomathien/soccer", "_____no_output_____" ] ], [ [ "import sqlite3\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "### Data Wrangeling", "_____no_output_____" ] ], [ [ "conn= sqlite3.connect('European_soccer_database.sqlite')", "_____no_output_____" ], [ "dataframe= pd.read_sql(\"\"\"SELECT * FROM sqlite_master\n GROUP BY tbl_name;\"\"\", conn)", "_____no_output_____" ], [ "dataframe", "_____no_output_____" ], [ "dataframe.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 8 entries, 0 to 7\nData columns (total 5 columns):\ntype 8 non-null object\nname 8 non-null object\ntbl_name 8 non-null object\nrootpage 8 non-null int64\nsql 8 non-null object\ndtypes: int64(1), object(4)\nmemory usage: 448.0+ bytes\n" ], [ "dataframe.describe()", "_____no_output_____" ], [ "df_table= pd.read_sql(\"\"\"SELECT * FROM sqlite_master\n WHERE TYPE='table';\"\"\", conn)", "_____no_output_____" ], [ "df_table", "_____no_output_____" ], [ "df_country= pd.read_sql(\"\"\"SELECT * FROM Country;\"\"\", conn)\ndf_country", "_____no_output_____" ], [ "df_player= pd.read_sql(\"\"\"SELECT * FROM Player;\"\"\", conn)\ndf_player", "_____no_output_____" ] ], [ [ "### Now I want to joint two tables 'Country' and 'Player' to see how many players we have from each country", "_____no_output_____" ] ], [ [ "df_country_player= pd.read_sql(\"\"\" SELECT * FROM Player\n JOIN Country ON Country.id= Player.id;\"\"\", conn)\ndf_country_player", "_____no_output_____" ], [ "# rename the column name to country \ndf_country_player.rename(columns={'name': 'country'})", "_____no_output_____" ], [ "df_player_attribute= pd.read_sql(\"\"\"SELECT * FROM Player_Attributes\n LIMIT 10;\"\"\", conn)\ndf_player_attribute", "_____no_output_____" ], [ "# List of teams\ndf_team= pd.read_sql(\"\"\"SELECT * FROM Team ;\"\"\", conn)\ndf_team", "_____no_output_____" ], [ "df_league= pd.read_sql(\"\"\"SELECT * FROM League;\"\"\", conn)\ndf_league", "_____no_output_____" ], [ "df_match= pd.read_sql(\"\"\"SELECT * FROM Match;\"\"\", conn)\ndf_match", "_____no_output_____" ], [ "df_league_matches= pd.read_sql(\"\"\"SELECT * FROM Match \n JOIN League ON League.id= Match.id \n ORDER BY season DESC\n \"\"\", conn)\ndf_league_matches", "_____no_output_____" ] ], [ [ "## Obtaining Basic Information About DataFrame", "_____no_output_____" ] ], [ [ "#data frame index\ndf_league_matches.index", "_____no_output_____" ], [ "df_league_matches.info", "_____no_output_____" ], [ "# name of columns\ndf_league_matches.columns", "_____no_output_____" ] ], [ [ "### SQLite foreign key constraint actions; https://www.sqlitetutorial.net/sqlite-foreign-key/\nNow, I will get the foreign key list of each table", "_____no_output_____" ] ], [ [ "pd.read_sql(\"PRAGMA foreign_key_list(Team);\",conn)", "_____no_output_____" ], [ "pd.read_sql(\"PRAGMA foreign_key_list(Match);\",conn)", "_____no_output_____" ] ], [ [ "### Now lets get the details of matches in Belgium", "_____no_output_____" ] ], [ [ "pd.read_sql(\"\"\"SELECT Match.id, \nCountry.name AS country_name, \nLeague.name AS league_name, \nseason, \nstage, \ndate,\nHT.team_long_name AS home_team,\nAT.team_long_name AS away_team,\nhome_team_goal, \naway_team_goal \nFROM Match\nJOIN Country on Country.id = Match.country_id\nJOIN League on League.id = Match.league_id\nLEFT JOIN Team AS HT on HT.team_api_id = Match.home_team_api_id\nLEFT JOIN Team AS AT on AT.team_api_id = Match.away_team_api_id\nWHERE country_name = 'Belgium'\nORDER by date\nLIMIT 10;\"\"\", conn)\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4af327b2e26a93cec8e807b82fbf7125de0e4de6
37,490
ipynb
Jupyter Notebook
xgboost/train_xgboost_serverless.ipynb
marcelonyc/demos
00451b64816a2ab32d2b4b5307f1dd3c80c2d4e6
[ "Apache-2.0" ]
null
null
null
xgboost/train_xgboost_serverless.ipynb
marcelonyc/demos
00451b64816a2ab32d2b4b5307f1dd3c80c2d4e6
[ "Apache-2.0" ]
null
null
null
xgboost/train_xgboost_serverless.ipynb
marcelonyc/demos
00451b64816a2ab32d2b4b5307f1dd3c80c2d4e6
[ "Apache-2.0" ]
null
null
null
33.533095
265
0.489437
[ [ [ "# Train XGboost Model With Hyper-Params Using Serverless Functions", "_____no_output_____" ] ], [ [ "# nuclio: ignore\nimport nuclio", "_____no_output_____" ] ], [ [ "### Define function dependencies", "_____no_output_____" ] ], [ [ "%%nuclio cmd \npip install sklearn\npip install xgboost\npip install matplotlib\npip install mlrun", "_____no_output_____" ], [ "%nuclio config spec.build.baseImage = \"python:3.6-jessie\"", "%nuclio: setting spec.build.baseImage to 'python:3.6-jessie'\n" ] ], [ [ "### Function code", "_____no_output_____" ] ], [ [ "import xgboost as xgb\nimport os\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\nfrom mlrun.artifacts import TableArtifact, PlotArtifact\nimport pandas as pd\n\n\ndef iris_generator(context, target=''):\n iris = load_iris()\n iris_dataset = pd.DataFrame(data=iris.data, columns=iris.feature_names)\n iris_labels = pd.DataFrame(data=iris.target, columns=['label'])\n iris_dataset = pd.concat([iris_dataset, iris_labels], axis=1)\n context.logger.info('saving iris dataframe to {}'.format(target))\n context.log_artifact(TableArtifact('iris_dataset', df=iris_dataset, target_path=target))\n \n\ndef xgb_train(context, \n dataset='',\n model_name='model.bst',\n max_depth=6,\n num_class=10,\n eta=0.2,\n gamma=0.1,\n steps=20):\n\n df = pd.read_csv(dataset)\n X = df.drop(['label'], axis=1)\n y = df['label']\n \n X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2)\n dtrain = xgb.DMatrix(X_train, label=Y_train)\n dtest = xgb.DMatrix(X_test, label=Y_test)\n\n # Get params from event\n param = {\"max_depth\": max_depth,\n \"eta\": eta, \"nthread\": 4,\n \"num_class\": num_class,\n \"gamma\": gamma,\n \"objective\": \"multi:softprob\"}\n\n # Train model\n xgb_model = xgb.train(param, dtrain, steps)\n\n preds = xgb_model.predict(dtest)\n best_preds = np.asarray([np.argmax(line) for line in preds])\n\n # log results and artifacts\n context.log_result('accuracy', float(accuracy_score(Y_test, best_preds)))\n context.log_artifact('model', body=bytes(xgb_model.save_raw()), \n target_path=model_name, labels={'framework': 'xgboost'})\n \n \nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom io import BytesIO\n\ndef plot_iter(context, iterations, col='accuracy', num_bins=10):\n df = pd.read_csv(BytesIO(iterations.get()))\n x = df['output.{}'.format(col)]\n fig, ax = plt.subplots(figsize=(6,6))\n n, bins, patches = ax.hist(x, num_bins, density=1)\n ax.set_xlabel('Accuraccy')\n ax.set_ylabel('Count')\n context.log_artifact(PlotArtifact('myfig', body=fig))", "_____no_output_____" ], [ "# nuclio: end-code\n# marks the end of a code section", "_____no_output_____" ] ], [ [ "## Import MLRUN, and run the data collection and training locally", "_____no_output_____" ] ], [ [ "from mlrun import new_function, code_to_function, NewTask, mount_v3io, new_model_server, mlconf, get_run_db\n# for local DB path use 'User/mlrun' instead \nmlconf.dbpath = 'http://mlrun-db:8080'", "_____no_output_____" ] ], [ [ "### Generate the iris dataset and store in a CSV", "_____no_output_____" ] ], [ [ "df_path = '/User/mlrun/df.csv'\ngen = new_function().run(name='iris_gen', handler=iris_generator, params={'target': df_path})", "[mlrun] 2019-11-18 12:02:55,255 starting run iris_gen uid=d04439c48b5d4708977cfa5b53ea2996 -> http://mlrun-db:8080\n[mlrun] 2019-11-18 12:02:55,384 saving iris dataframe to /User/mlrun/df.csv\n\n" ] ], [ [ "### Define a training task with Hyper parameters (GridSearch) and run locally", "_____no_output_____" ] ], [ [ "# create a task and test our function locally with multiple parameters\nparameters = {\n \"eta\": [0.05, 0.10, 0.20],\n \"max_depth\": [3, 4, 6, 8, 10],\n \"gamma\": [0.0, 0.1, 0.3],\n }\n\ntask = NewTask(handler=xgb_train, out_path='/User/mlrun/data', inputs={'dataset': df_path}).with_hyper_params(parameters, 'max.accuracy')", "_____no_output_____" ], [ "run = new_function().run(task)", "[mlrun] 2019-11-18 12:03:10,209 starting run xgb_train uid=141cedd49d074792934da530076ddc63 -> http://mlrun-db:8080\n" ] ], [ [ "## Deploy XGB function to Nuclio (with paralelism), and run remotely ", "_____no_output_____" ] ], [ [ "# create the function from the notebook code + annotations, add volumes and parallel HTTP trigger\nxgbfn = code_to_function('xgb', runtime='nuclio:mlrun')\nxgbfn.add_volume('User','~/').with_http(workers=16).with_v3io()", "_____no_output_____" ], [ "# deploy the function to the cluster\nxgbfn.deploy(project='iris')", "[mlrun] 2019-11-18 12:14:05,432 deploy started\n[nuclio.deploy] 2019-11-18 12:14:06,506 (info) Building processor image\n[nuclio.deploy] 2019-11-18 12:14:11,547 (info) Build complete\n[nuclio.deploy] 2019-11-18 12:14:20,010 (info) Function deploy complete\n[nuclio.deploy] 2019-11-18 12:14:20,022 done updating xgb, function address: 3.133.112.240:32290\n" ], [ "nrun = xgbfn.run(task, handler='xgb_train')", "[mlrun] 2019-11-18 12:11:57,449 starting run xgb_train uid=42e9c80152664a948f62e7a0b5fbb67a -> http://mlrun-db:8080\n" ] ], [ [ "## Create a multi-stage KubeFlow Pipeline from our functions\n* Load Iris dataset into a CSV\n* Train a model using XGBoost with Hyper-parameter\n* Deploy the model using Nuclio-serving\n* Generate a plot of the training results", "_____no_output_____" ] ], [ [ "import kfp\nfrom kfp import dsl", "_____no_output_____" ], [ "artifacts_path = 'v3io:///users/admin/mlrun/kfp/{{workflow.uid}}/'", "_____no_output_____" ], [ "@dsl.pipeline(\n name='My XGBoost training pipeline',\n description='Shows how to use mlrun.'\n)\ndef xgb_pipeline(\n eta = [0.1, 0.2, 0.3], gamma = [0.0, 0.1, 0.2, 0.3]\n):\n\n ingest = xgbfn.as_step(name='ingest_iris', handler='iris_generator',\n params = {'target': df_path},\n outputs=['iris_dataset'], out_path=artifacts_path).apply(mount_v3io())\n\n \n train = xgbfn.as_step(name='xgb_train', handler='xgb_train',\n hyperparams = {'eta': eta, 'gamma': gamma},\n selector='max.accuracy',\n inputs = {'dataset': ingest.outputs['iris_dataset']}, \n outputs=['model'], out_path=artifacts_path).apply(mount_v3io())\n\n \n plot = xgbfn.as_step(name='plot', handler='plot_iter',\n inputs={'iterations': train.outputs['iteration_results']},\n outputs=['iris_dataset'], out_path=artifacts_path).apply(mount_v3io())\n\n\n # define a nuclio-serving functions, generated from a notebook file\n srvfn = new_model_server('iris-serving', model_class='XGBoostModel', filename='nuclio_serving.ipynb')\n \n # deploy the model serving function with inputs from the training stage\n deploy = srvfn.with_v3io('User','~/').deploy_step(project = 'iris', models={'iris_v1': train.outputs['model']})", "_____no_output_____" ] ], [ [ "### Create a KubeFlow client and submit the pipeline with parameters", "_____no_output_____" ] ], [ [ "# for debug generate the pipeline dsl\n#kfp.compiler.Compiler().compile(xgb_pipeline, 'mlrunpipe.yaml')", "_____no_output_____" ], [ "client = kfp.Client(namespace='default-tenant')\narguments = {'eta': [0.05, 0.10, 0.30], 'gamma': [0.0, 0.1, 0.2, 0.3]}\nrun_result = client.create_run_from_pipeline_func(xgb_pipeline, arguments, run_name='xgb 1', experiment_name='xgb')", "_____no_output_____" ], [ "# connect to the run db \ndb = get_run_db().connect()", "_____no_output_____" ], [ "# query the DB with filter on workflow ID (only show this workflow) \ndb.list_runs('', labels=f'workflow={run_result.run_id}').show()", "_____no_output_____" ], [ "# use this to supress XGB FutureWarning\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4af32888f525dbd7b2e58b88226eb0ead8bab441
18,852
ipynb
Jupyter Notebook
Master_HCCI_classification.ipynb
kiranyalamanchi/ML-HCCI
00945952c317133af3fc4f864834054280b30237
[ "Apache-2.0" ]
null
null
null
Master_HCCI_classification.ipynb
kiranyalamanchi/ML-HCCI
00945952c317133af3fc4f864834054280b30237
[ "Apache-2.0" ]
null
null
null
Master_HCCI_classification.ipynb
kiranyalamanchi/ML-HCCI
00945952c317133af3fc4f864834054280b30237
[ "Apache-2.0" ]
null
null
null
31.790894
141
0.526628
[ [ [ "# KNN - Accuracy estimation", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport csv\nfrom sklearn.model_selection import GridSearchCV, KFold\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn import metrics\npd.options.mode.chained_assignment = None\n\n# Load dataset\ndf = pd.read_excel('HCCI CFR data.xlsx', sheet_name = 'Data Compiled', index_col=0)\ntarget = df['Output']\nfeatures = df[df.columns[0:9]]\n\n# Define search space\nn_neighbors = [2,3,5,6,7,9,10,11,13,14,15,17,18,19]\n\n# Setup the grid to be searched over\nparam_grid = dict(n_neighbors=n_neighbors)\n\n# Define outer folds\nkFolds = KFold(n_splits=10, shuffle=True, random_state=1).split(X=features.values, y=target.values)\n\n# Define inner folds\ngrid_search = GridSearchCV(KNeighborsClassifier(weights='uniform'), param_grid, cv=KFold(n_splits=10, shuffle=True, random_state=1),\n n_jobs=19, verbose=1, scoring='precision_micro')\n\n# Open results file and write out headers\nout_file = open(\"grid_search_KNN.csv\", 'w')\nwr = csv.writer(out_file, dialect='excel')\nheaders = ['neighbours', 'micro_precision']\nwr.writerow(headers)\nout_file.flush()\n\nKNN_file = open(\"KNN_results.csv\", 'w',newline='')\nwrr = csv.writer(KNN_file, dialect='excel')\nheaders = ['Actual', 'Predicted']\nwrr.writerow(headers)\nKNN_file.flush()\n\n\nfor index_train, index_test in kFolds:\n \n # Get train and test splits\n x_train, x_test = features.iloc[index_train].values, features.iloc[index_test].values\n y_train, y_test = target.iloc[index_train].values, target.iloc[index_test].values\n\n # Apply min max normalization\n scaler = MinMaxScaler().fit(x_train)\n x_train = scaler.transform(x_train)\n x_test = scaler.transform(x_test)\n\n # Fit\n grid_search.fit(x_train, y_train)\n\n # Get best params\n best_params = grid_search.best_params_\n \n ##Testing\n knn = KNeighborsClassifier(n_neighbors=best_params['n_neighbors'], weights='uniform')\n knn.fit(x_train, y_train)\n Y_pred = knn.predict(x_test)\n print(\"precision:\",metrics.precision_score(Y_pred, y_test, average='micro'))\n\n # Write results\n row = [best_params['n_neighbors'], metrics.precision_score(Y_pred, y_test, average='micro')]\n wr.writerow(row)\n out_file.flush()\n \n # Write results\n for i in range(len(y_test)):\n row = (y_test[i], Y_pred[i])\n wrr.writerow(row)\n KNN_file.flush()\n \nout_file.close()\nKNN_file.close()", "Fitting 10 folds for each of 14 candidates, totalling 140 fits\n" ] ], [ [ "# SVM - Accuracy estimation", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport csv\nimport pickle\nfrom sklearn.model_selection import GridSearchCV, KFold\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn import metrics\npd.options.mode.chained_assignment = None\n\n# Load dataset\ndf = pd.read_excel('HCCI CFR data.xlsx', sheet_name = 'Data Compiled', index_col=0)\ntarget = df['Output']\n# features = df[df.columns[0:7]]\n#for sensitivity analysis remove a feature and run this block -- repeat this for all the seven features\nfeatures = df[['RON','S','Fuel rate','O2','Intake Temperature','Intake Pressure','Compression ratio']]\n# Define search space\nC = [1, 10, 100, 1000, 10000]\n\n# Setup the grid to be searched over\nparam_grid = dict(C=C)\n\n####Test sets accuracy \n\n# Define outer folds\nkFolds = KFold(n_splits=10, shuffle=True, random_state=1).split(X=features.values, y=target.values)\n\n# Define inner folds\ngrid_search = GridSearchCV(SVC(gamma='auto', kernel = 'rbf'), param_grid, cv=KFold(n_splits=10, shuffle=True, random_state=1),\n n_jobs=19, verbose=1, scoring='precision_micro')\n\n# Open results file and write out headers\nout_file = open(\"grid_search_SVM.csv\", 'w')\nwr = csv.writer(out_file, dialect='excel')\nheaders = ['C', 'micro_precision']\nwr.writerow(headers)\nout_file.flush()\n\nSVM_file = open(\"SVM_results.csv\", 'w',newline='')\nwrr = csv.writer(SVM_file, dialect='excel')\nheaders = ['Actual', 'Predicted']\nwrr.writerow(headers)\nSVM_file.flush()\n\nfor index_train, index_test in kFolds:\n # Get train and test splits\n x_train, x_test = features.iloc[index_train].values, features.iloc[index_test].values\n y_train, y_test = target.iloc[index_train].values, target.iloc[index_test].values\n\n # Apply min max normalization\n scaler = MinMaxScaler().fit(x_train)\n x_train = scaler.transform(x_train)\n x_test = scaler.transform(x_test)\n\n # Fit\n grid_search.fit(x_train, y_train)\n\n # Get best params\n best_params = grid_search.best_params_\n \n ##Testing\n svm = SVC(gamma='auto', kernel = 'rbf', C=best_params['C'])\n svm.fit(x_train, y_train)\n Y_pred = svm.predict(x_test)\n print(\"precision:\",metrics.precision_score(Y_pred, y_test, average='micro'))\n\n # Write results\n row = [best_params['C'], metrics.precision_score(Y_pred, y_test, average='micro')]\n wr.writerow(row)\n out_file.flush()\n\n # Write results\n for i in range(len(y_test)):\n row = (y_test[i], Y_pred[i])\n wrr.writerow(row)\n SVM_file.flush()\n\nout_file.close()\nSVM_file.close()\n", "Fitting 10 folds for each of 5 candidates, totalling 50 fits\n" ] ], [ [ "# SVM - Final Model", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport csv\nimport pickle\nfrom sklearn.model_selection import GridSearchCV, KFold\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn import metrics\npd.options.mode.chained_assignment = None\n\n# Load dataset\ndf = pd.read_excel('HCCI CFR data.xlsx', sheet_name = 'Data Compiled', index_col=0)\ntarget = df['Output']\n# features = df[df.columns[0:9]]\nfeatures = df[['RON','S','Fuel rate','O2','Intake Temperature','Intake Pressure','Compression ratio']]\n# features = df[['RON','S','Fuel rate','O2','Intake Temperature','Intake Pressure','Compression ratio', 'M.W', 'LHV(KJ/kg)']]\n# Define search space\nC = [1, 10, 100, 1000, 10000]\n\n# Setup the grid to be searched over\nparam_grid = dict(C=C)\n\n\n#####Save Final Model\n\n# Define grid search\ngrid_search = GridSearchCV(SVC(kernel='rbf', gamma='auto'), param_grid, cv=KFold(n_splits=10, shuffle=True, random_state=1),\n n_jobs=19, verbose=1, scoring='precision_micro')\n\n# Split data in to features and target\nx_train = features.values\ny_train = target.values\n\n# Apply min max normalization\nscaler = MinMaxScaler().fit(x_train)\nx_train = scaler.transform(x_train)\n\n# Find best parameters\ngrid_search.fit(x_train, y_train)\nprint(grid_search.best_params_)\nprint(grid_search.best_score_)\n\n# Retrain model with best parameters found from grid search\nbest_params = grid_search.best_params_\nmodel = SVC(kernel='rbf', gamma='auto', C=best_params['C'])\nmodel.fit(x_train, y_train)\n\n# save the model\nfilename = 'final_SVR_model.sav'\npickle.dump(model, open(filename, 'wb'))\n", "_____no_output_____" ] ], [ [ "# Data for contour diagrams", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport pickle\nimport csv\nfrom keras.models import load_model\n\n# Load SVR model\nfilename = 'final_SVR_model.sav'\nmodel = pickle.load(open(filename, 'rb'))\n\nout_file = open(\"Counter_diagram_data.csv\", 'w')\nwr = csv.writer(out_file, dialect='excel', lineterminator = '\\n')\nheaders = ['RON','S','Fuel rate','O2','Intake Temperature','Intake Pressure','CR','MW','LHV','Output']\nwr.writerow(headers)\nout_file.flush()\n\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0,0]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0,0.3333]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0,0.6666]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0,1]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0.2,0]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0.2,0.3333]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0.2,0.6666]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\nfor i in range(0,101,1):\n for j in range (0,101,1):\n inp = [[i/100,0.34,j/100,1,0.3333,0.2,1]]\n res = model.predict(inp)\n #Write results\n row = [inp[0][0],inp[0][1],inp[0][2],inp[0][3],inp[0][4],inp[0][5],inp[0][6],res[0]]\n wr.writerow(row)\n out_file.flush()\n\nout_file.close()", "Using TensorFlow backend.\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af32a0f0f524a5cc3c42620a5271657049b027c
44,376
ipynb
Jupyter Notebook
Data-Science-HYD-2k19/Topic-Wise/NLP/2. CORPUS from nltk.ipynb
Sanjay9921/Python
05ac161dd46f9b4731a5c14ff5ef52adb705e8e6
[ "MIT" ]
null
null
null
Data-Science-HYD-2k19/Topic-Wise/NLP/2. CORPUS from nltk.ipynb
Sanjay9921/Python
05ac161dd46f9b4731a5c14ff5ef52adb705e8e6
[ "MIT" ]
null
null
null
Data-Science-HYD-2k19/Topic-Wise/NLP/2. CORPUS from nltk.ipynb
Sanjay9921/Python
05ac161dd46f9b4731a5c14ff5ef52adb705e8e6
[ "MIT" ]
null
null
null
24.571429
2,259
0.484969
[ [ [ "# [ NLP DAY 2 ] : ", "_____no_output_____" ] ], [ [ "import nltk #natural language tool kit", "_____no_output_____" ] ], [ [ "1. Preprocessing:\n\n a. segmentation\n \n b. tokenization\n \n c. POS tagging (parts of speech)\n \n2. Word level processing:\n\n a. wordnet\n \n b. lemmatization\n \n c. stemming\n \n d. NGrams\n \n3. Utilities:\n\n a. Tree\n \n b. FreqDist\n \n c. ConditionalFreqDist\n \n d. Streaming CorpusReaders\n \n4. Classification:\n\n a. Maximum Entropy\n \n b. Naive Bayes\n \n c. Decision Tree\n \n5. Chunking\n6. Named Entity Recognition\n7. Parsers Galorel", "_____no_output_____" ], [ "# Corpus from ntlk ", "_____no_output_____" ] ], [ [ "for name in dir(nltk.corpus):\n print(name)\n if name.islower() and not name.startswith('_'):\n print(name)", "_LazyModule__lazymodule_globals\n_LazyModule__lazymodule_import\n_LazyModule__lazymodule_init\n_LazyModule__lazymodule_loaded\n_LazyModule__lazymodule_locals\n_LazyModule__lazymodule_name\n__class__\n__delattr__\n__dict__\n__dir__\n__doc__\n__eq__\n__format__\n__ge__\n__getattr__\n__getattribute__\n__gt__\n__hash__\n__init__\n__init_subclass__\n__le__\n__lt__\n__module__\n__name__\n__ne__\n__new__\n__reduce__\n__reduce_ex__\n__repr__\n__setattr__\n__sizeof__\n__str__\n__subclasshook__\n__weakref__\n" ], [ "len(dir(nltk))", "_____no_output_____" ] ], [ [ "# Changing the property of Jupyter notebook to print all the intermediatrary variables: ", "_____no_output_____" ] ], [ [ "from IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"", "_____no_output_____" ], [ "a,b = 10,20\na\nb", "_____no_output_____" ] ], [ [ "### Here, the nb has printed both a and b, else it would print only b if print() wasn't given to the a ", "_____no_output_____" ], [ "# Text files which the nltk corpus provides by default: ", "_____no_output_____" ] ], [ [ "nltk.corpus.gutenberg.fileids()", "_____no_output_____" ], [ "nltk.corpus.shakespeare.fileids()", "_____no_output_____" ] ], [ [ "# Create variables to read the default corpus text files: ", "_____no_output_____" ], [ "### 1. Get the individual words of the text in a list format: ", "_____no_output_____" ] ], [ [ "nltk.corpus.gutenberg.words(\"shakespeare-hamlet.txt\")", "_____no_output_____" ] ], [ [ "### 2. Create the variable: ", "_____no_output_____" ] ], [ [ "hamlet = nltk.text.Text(nltk.corpus.gutenberg.words(\"shakespeare-hamlet.txt\"))", "_____no_output_____" ], [ "hamlet", "_____no_output_____" ] ], [ [ "# Searching :\n\nWord-Search: \"king\"\n\nWord-Limit: 55\n\nLine-Limit: 10", "_____no_output_____" ] ], [ [ "hamlet.concordance(\"king\",55,10)", "Displaying 10 of 172 matches:\nelfe Bar . Long liue the King Fran . Barnardo ? Bar . \ne same figure , like the King that ' s dead Mar . Thou\n. Lookes it not like the King ? Marke it Horatio Hora \nMar . Is it not like the King ? Hor . As thou art to t\nisper goes so : Our last King , Whose Image euen but n\nmpetent Was gaged by our King : which had return ' d T\nSecunda . Enter Claudius King of Denmarke , Gertrude t\nelia , Lords Attendant . King . Though yet of Hamlet o\ner To businesse with the King , more then the scope Of\n , will we shew our duty King . We doubt it nothing , \n" ], [ "hamlet.concordance(\"king\",1,1)", "Displaying 1 of 172 matches:\n King \n" ], [ "hamlet.concordance(\"king\",55,1)", "Displaying 1 of 172 matches:\nelfe Bar . Long liue the King Fran . Barnardo ? Bar . \n" ], [ "len(\" elfe Bar . Long liue the King Fran . Barnardo ? Bar . \")", "_____no_output_____" ] ], [ [ "# [NLP DAY 3]", "_____no_output_____" ] ], [ [ "import nltk", "_____no_output_____" ], [ "import os", "_____no_output_____" ], [ "dir(nltk)", "_____no_output_____" ], [ "len(dir(nltk))", "_____no_output_____" ], [ "nltk.corpus.gutenberg.fileids()", "_____no_output_____" ] ], [ [ "# 1. Finds the zip files of corpora: ", "_____no_output_____" ] ], [ [ "print(os.listdir(nltk.data.find(\"corpora\")))", "['abc', 'abc.zip', 'alpino', 'alpino.zip', 'biocreative_ppi', 'biocreative_ppi.zip', 'brown', 'brown.zip', 'brown_tei', 'brown_tei.zip', 'cess_cat', 'cess_cat.zip', 'cess_esp', 'cess_esp.zip', 'chat80', 'chat80.zip', 'city_database', 'city_database.zip', 'cmudict', 'cmudict.zip', 'comparative_sentences', 'comparative_sentences.zip', 'comtrans.zip', 'conll2000', 'conll2000.zip', 'conll2002', 'conll2002.zip', 'conll2007.zip', 'crubadan', 'crubadan.zip', 'dependency_treebank', 'dependency_treebank.zip', 'dolch', 'dolch.zip', 'europarl_raw', 'europarl_raw.zip', 'floresta', 'floresta.zip', 'framenet_v15', 'framenet_v15.zip', 'framenet_v17', 'framenet_v17.zip', 'gazetteers', 'gazetteers.zip', 'genesis', 'genesis.zip', 'gutenberg', 'gutenberg.zip', 'ieer', 'ieer.zip', 'inaugural', 'inaugural.zip', 'indian', 'indian.zip', 'jeita.zip', 'kimmo', 'kimmo.zip', 'knbc.zip', 'lin_thesaurus', 'lin_thesaurus.zip', 'machado.zip', 'mac_morpho', 'mac_morpho.zip', 'masc_tagged.zip', 'movie_reviews', 'movie_reviews.zip', 'names', 'names.zip', 'nombank.1.0.zip', 'nps_chat', 'nps_chat.zip', 'omw', 'omw.zip', 'opinion_lexicon', 'opinion_lexicon.zip', 'paradigms', 'paradigms.zip', 'pil', 'pil.zip', 'pl196x', 'pl196x.zip', 'ppattach', 'ppattach.zip', 'problem_reports', 'problem_reports.zip', 'product_reviews_1', 'product_reviews_1.zip', 'product_reviews_2', 'product_reviews_2.zip', 'propbank.zip', 'pros_cons', 'pros_cons.zip', 'ptb', 'ptb.zip', 'qc', 'qc.zip', 'reuters.zip', 'rte', 'rte.zip', 'semcor.zip', 'senseval', 'senseval.zip', 'sentence_polarity', 'sentence_polarity.zip', 'sentiwordnet', 'sentiwordnet.zip', 'shakespeare', 'shakespeare.zip', 'sinica_treebank', 'sinica_treebank.zip', 'smultron', 'smultron.zip', 'state_union', 'state_union.zip', 'stopwords', 'stopwords.zip', 'subjectivity', 'subjectivity.zip', 'swadesh', 'swadesh.zip', 'switchboard', 'switchboard.zip', 'timit', 'timit.zip', 'toolbox', 'toolbox.zip', 'treebank', 'treebank.zip', 'twitter_samples', 'twitter_samples.zip', 'udhr', 'udhr.zip', 'udhr2', 'udhr2.zip', 'unicode_samples', 'unicode_samples.zip', 'universal_treebanks_v20.zip', 'verbnet', 'verbnet.zip', 'verbnet3', 'verbnet3.zip', 'webtext', 'webtext.zip', 'wordnet', 'wordnet.zip', 'wordnet_ic', 'wordnet_ic.zip']\n" ] ], [ [ "# Get the text xml file in a variable: ", "_____no_output_____" ] ], [ [ "hamlet = nltk.corpus.gutenberg.words(\"shakespeare-hamlet.txt\")", "_____no_output_____" ], [ "hamlet", "_____no_output_____" ] ], [ [ "# Get the first 500 words: ", "_____no_output_____" ] ], [ [ "for i in hamlet[:500]:\n print(i,sep=\" \", end = \" \")", "[ The Tragedie of Hamlet by William Shakespeare 1599 ] Actus Primus . Scoena Prima . Enter Barnardo and Francisco two Centinels . Barnardo . Who ' s there ? Fran . Nay answer me : Stand & vnfold your selfe Bar . Long liue the King Fran . Barnardo ? Bar . He Fran . You come most carefully vpon your houre Bar . ' Tis now strook twelue , get thee to bed Francisco Fran . For this releefe much thankes : ' Tis bitter cold , And I am sicke at heart Barn . Haue you had quiet Guard ? Fran . Not a Mouse stirring Barn . Well , goodnight . If you do meet Horatio and Marcellus , the Riuals of my Watch , bid them make hast . Enter Horatio and Marcellus . Fran . I thinke I heare them . Stand : who ' s there ? Hor . Friends to this ground Mar . And Leige - men to the Dane Fran . Giue you good night Mar . O farwel honest Soldier , who hath relieu ' d you ? Fra . Barnardo ha ' s my place : giue you goodnight . Exit Fran . Mar . Holla Barnardo Bar . Say , what is Horatio there ? Hor . A peece of him Bar . Welcome Horatio , welcome good Marcellus Mar . What , ha ' s this thing appear ' d againe to night Bar . I haue seene nothing Mar . Horatio saies , ' tis but our Fantasie , And will not let beleefe take hold of him Touching this dreaded sight , twice seene of vs , Therefore I haue intreated him along With vs , to watch the minutes of this Night , That if againe this Apparition come , He may approue our eyes , and speake to it Hor . Tush , tush , ' twill not appeare Bar . Sit downe a - while , And let vs once againe assaile your eares , That are so fortified against our Story , What we two Nights haue seene Hor . Well , sit we downe , And let vs heare Barnardo speake of this Barn . Last night of all , When yond same Starre that ' s Westward from the Pole Had made his course t ' illume that part of Heauen Where now it burnes , Marcellus and my selfe , The Bell then beating one Mar . Peace , breake thee of : Enter the Ghost . Looke where it comes againe Barn . In the same figure , like the King that ' s dead Mar . Thou art a Scholler ; speake to it Horatio Barn . Lookes it not like the King ? Marke it Horatio Hora . Most like : It harrowes me with fear & wonder Barn . It would be spoke too Mar . Question it Horatio Hor . What art " ], [ "for i in hamlet[:10]:\n print(i,sep=\" \",end = \" \")", "[ The Tragedie of Hamlet by William Shakespeare 1599 ] " ], [ "ai = \"How are you Hello I am awesome bro How are you I am straight up not having a good time bro\"", "_____no_output_____" ], [ "type(ai)", "_____no_output_____" ] ], [ [ "# Topic: Tokenization: ", "_____no_output_____" ], [ "## word_tokenize ", "_____no_output_____" ] ], [ [ "from nltk.tokenize import word_tokenize", "_____no_output_____" ], [ "ai_tokens = word_tokenize(ai)", "_____no_output_____" ], [ "ai_tokens", "_____no_output_____" ], [ "len(hamlet)", "_____no_output_____" ], [ "type(hamlet)", "_____no_output_____" ] ], [ [ "# Check the frequency of the words in the tokens: ", "_____no_output_____" ] ], [ [ "from nltk.probability import FreqDist\nfdist = FreqDist()", "_____no_output_____" ], [ "for i in ai_tokens:\n fdist[i.lower()]+=1", "_____no_output_____" ], [ "fdist", "_____no_output_____" ], [ "type(fdist)", "_____no_output_____" ] ], [ [ "## Indexing and Slicing: ", "_____no_output_____" ] ], [ [ "fdist[\"bro\"]", "_____no_output_____" ] ], [ [ "# Check : The most common words in the object text file", "_____no_output_____" ] ], [ [ "fdist_top2 = fdist.most_common(2)\nfdist_top2", "_____no_output_____" ], [ "ai = \"Bro help bro \\n no bro this is hopeless \\n bro be optimistic bro \\n ok bro\"\nai_tokens = word_tokenize(ai)", "_____no_output_____" ], [ "fdist2 = FreqDist()\nfor i in ai_tokens:\n fdist2[i.lower()]+=1", "_____no_output_____" ], [ "fdist2", "_____no_output_____" ], [ "fdist2_top2 = fdist2.most_common(2)\nfdist2_top2", "_____no_output_____" ] ], [ [ "# Check the number of paragraphs:", "_____no_output_____" ] ], [ [ "from nltk.tokenize import blankline_tokenize\nai_blank = blankline_tokenize(ai)\nlen(hamlet_blank)", "_____no_output_____" ] ], [ [ "# TOPIC: Bigrams, Trigrams, ngrams ", "_____no_output_____" ], [ "## USES: chatbots, search engines, etc ", "_____no_output_____" ], [ "Google uses ngrams concept for their search engine", "_____no_output_____" ] ], [ [ "from nltk.util import bigrams,trigrams,ngrams", "_____no_output_____" ], [ "string = \"The Tragedie of Hamlet by William Shakespeare 1599 Actus Primus . Scoena Prima \"", "_____no_output_____" ], [ "quotes_token = nltk.word_tokenize(string)", "_____no_output_____" ], [ "quotes_token", "_____no_output_____" ] ], [ [ "## Bigrams: ", "_____no_output_____" ] ], [ [ "quotes_bigrams = nltk.bigrams(quotes_token)", "_____no_output_____" ], [ "bi = list(quotes_bigrams)", "_____no_output_____" ], [ "bi", "_____no_output_____" ] ], [ [ "## Trigrams: ", "_____no_output_____" ] ], [ [ "quotes_trigrams = nltk.trigrams(quotes_token)", "_____no_output_____" ], [ "tri = list(quotes_trigrams)", "_____no_output_____" ], [ "tri", "_____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", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4af32b1e90314e98e5b4122d8b75587141cb69a4
41,352
ipynb
Jupyter Notebook
python/python-part-03.ipynb
Duke-GCB/GCB-Academy-2015-02-05
261c185e0caee6704c2b4bad5285448c197806b0
[ "CC-BY-4.0" ]
1
2015-02-04T01:21:05.000Z
2015-02-04T01:21:05.000Z
python/python-part-03.ipynb
Duke-GCB/GCB-Academy-2015-02-05
261c185e0caee6704c2b4bad5285448c197806b0
[ "CC-BY-4.0" ]
null
null
null
python/python-part-03.ipynb
Duke-GCB/GCB-Academy-2015-02-05
261c185e0caee6704c2b4bad5285448c197806b0
[ "CC-BY-4.0" ]
null
null
null
34.778806
383
0.496856
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af338f1348411260b90e24f3933c7f61c580508
127,220
ipynb
Jupyter Notebook
content/ch-quantum-hardware/randomized-benchmarking.ipynb
rajat709/qiskit-textbook
28e8eed49536e06d42111436eeb537cfe030a2cb
[ "Apache-2.0" ]
1
2021-07-09T14:53:17.000Z
2021-07-09T14:53:17.000Z
content/ch-quantum-hardware/randomized-benchmarking.ipynb
epelaaez/qiskit-textbook
ec45c38bb8080eed95904654ca106b3b329c0d82
[ "Apache-2.0" ]
null
null
null
content/ch-quantum-hardware/randomized-benchmarking.ipynb
epelaaez/qiskit-textbook
ec45c38bb8080eed95904654ca106b3b329c0d82
[ "Apache-2.0" ]
null
null
null
45.081502
445
0.515367
[ [ [ "# Randomized Benchmarking", "_____no_output_____" ], [ "## Contents\n \n1. [Introduction](#intro) \n2. [The Randomized Benchmarking Protocol](#protocol) \n3. [The Intuition Behind RB](#intuition) \n4. [Simultaneous Randomized Benchmarking](#simultaneousrb) \n5. [Predicted Gate Fidelity](#predicted-gate-fidelity) \n6. [References](#references) \n\n## 1. Introduction <a id='intro'></a>\n\nOne of the main challenges in building a quantum information processor is the non-scalability of completely\ncharacterizing the noise affecting a quantum system via process tomography. In addition, process tomography is sensitive to noise in the pre- and post rotation gates plus the measurements (SPAM errors). Gateset tomography can take these errors into account, but the scaling is even worse. A complete characterization\nof the noise is useful because it allows for the determination of good error-correction schemes, and thus\nthe possibility of reliable transmission of quantum information.\n\nSince complete process tomography is infeasible for large systems, there is growing interest in scalable\nmethods for partially characterizing the noise affecting a quantum system. A scalable (in the number $n$ of qubits comprising the system) and robust algorithm for benchmarking the full set of Clifford gates by a single parameter using randomization techniques was presented in [1]. The concept of using randomization methods for benchmarking quantum gates is commonly called **Randomized Benchmarking\n(RB)**.\n\n## 2. The Randomized Benchmarking Protocol <a id='protocol'></a>\n\nWe should first import the relevant qiskit classes for the demonstration:", "_____no_output_____" ] ], [ [ "# Import general libraries (needed for functions)\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython import display\n\n# Import the RB Functions\nimport qiskit.ignis.verification.randomized_benchmarking as rb\n\n# Import Qiskit classes \nimport qiskit\nfrom qiskit import assemble, transpile\nfrom qiskit.providers.aer.noise import NoiseModel\nfrom qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error", "_____no_output_____" ] ], [ [ "A RB protocol (see [1,2]) consists of the following steps:\n\n### Step 1: Generate RB sequences\n\nThe RB sequences consist of random Clifford elements chosen uniformly from the Clifford group on $n$-qubits, \nincluding a computed reversal element,\nthat should return the qubits to the initial state.\n\nMore precisely, for each length $m$, we choose $K_m$ RB sequences. \nEach such sequence contains $m$ random elements $C_{i_j}$ chosen uniformly from the Clifford group on $n$-qubits, and the $m+1$ element is defined as follows: $C_{i_{m+1}} = (C_{i_1}\\cdot ... \\cdot C_{i_m})^{-1}$. It can be found efficiently by the Gottesmann-Knill theorem.\n\nFor example, we generate below several sequences of 2-qubit Clifford circuits.", "_____no_output_____" ] ], [ [ "# Generate RB circuits (2Q RB)\n\n# number of qubits\nnQ = 2 \nrb_opts = {}\n#Number of Cliffords in the sequence\nrb_opts['length_vector'] = [1, 10, 20, 50, 75, 100, 125, 150, 175, 200]\n# Number of seeds (random sequences)\nrb_opts['nseeds'] = 5\n# Default pattern\nrb_opts['rb_pattern'] = [[0, 1]]\n\nrb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts)", "_____no_output_____" ] ], [ [ "As an example, we print the circuit corresponding to the first RB sequence", "_____no_output_____" ] ], [ [ "rb_circs[0][0].draw()", "_____no_output_____" ] ], [ [ "One can verify that the Unitary representing each RB circuit should be the identity (with a global phase). \nWe simulate this using Aer unitary simulator.", "_____no_output_____" ] ], [ [ "# Create a new circuit without the measurement\nqregs = rb_circs[0][-1].qregs\ncregs = rb_circs[0][-1].cregs\nqc = qiskit.QuantumCircuit(*qregs, *cregs)\nfor i in rb_circs[0][-1][0:-nQ]:\n qc.data.append(i)", "_____no_output_____" ], [ "# The Unitary is an identity (with a global phase)\nsim = qiskit.Aer.get_backend('aer_simulator')\nbasis_gates = ['u1','u2','u3','cx'] # use U,CX for now\nqc.save_unitary()\nunitary = sim.run(qc).result().get_unitary()\nfrom qiskit.visualization import array_to_latex\narray_to_latex(unitary, prefix=\"\\\\text{Unitary} = \")", "_____no_output_____" ] ], [ [ "### Step 2: Execute the RB sequences (with some noise)\n\nWe can execute the RB sequences either using Qiskit Aer Simulator (with some noise model) or using IBMQ provider, and obtain a list of results.\n\nBy assumption each operation $C_{i_j}$ is allowed to have some error, represented by $\\Lambda_{i_j,j}$, and each sequence can be modeled by the operation:\n\n\n$$\\textit{S}_{\\textbf{i}_\\textbf{m}} = \\bigcirc_{j=1}^{m+1} (\\Lambda_{i_j,j} \\circ C_{i_j})$$\n\n\nwhere ${\\textbf{i}_\\textbf{m}} = (i_1,...,i_m)$ and $i_{m+1}$ is uniquely determined by ${\\textbf{i}_\\textbf{m}}$.", "_____no_output_____" ] ], [ [ "# Run on a noisy simulator\nnoise_model = NoiseModel()\n\n# Depolarizing error on the gates u2, u3 and cx (assuming the u1 is virtual-Z gate and no error)\np1Q = 0.002\np2Q = 0.01\n\nnoise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2')\nnoise_model.add_all_qubit_quantum_error(depolarizing_error(2 * p1Q, 1), 'u3')\nnoise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx')\n\nbackend = qiskit.Aer.get_backend('aer_simulator')", "_____no_output_____" ] ], [ [ "### Step 3: Get statistics about the survival probabilities\n\nFor each of the $K_m$ sequences the survival probability $Tr[E_\\psi \\textit{S}_{\\textbf{i}_\\textbf{m}}(\\rho_\\psi)]$\nis measured. \nHere $\\rho_\\psi$ is the initial state taking into account preparation errors and $E_\\psi$ is the\nPOVM element that takes into account measurement errors.\nIn the ideal (noise-free) case $\\rho_\\psi = E_\\psi = | \\psi {\\rangle} {\\langle} \\psi |$. \n\nIn practice one can measure the probability to go back to the exact initial state, i.e. all the qubits in the ground state $ {|} 00...0 {\\rangle}$ or just the probability for one of the qubits to return back to the ground state. Measuring the qubits independently can be more convenient if a correlated measurement scheme is not possible. Both measurements will fit to the same decay parameter according to the properties of the *twirl*. ", "_____no_output_____" ], [ "### Step 4: Find the averaged sequence fidelity\n\nAverage over the $K_m$ random realizations of the sequence to find the averaged sequence **fidelity**,\n\n\n$$F_{seq}(m,|\\psi{\\rangle}) = Tr[E_\\psi \\textit{S}_{K_m}(\\rho_\\psi)]$$\n\n\nwhere \n\n\n$$\\textit{S}_{K_m} = \\frac{1}{K_m} \\sum_{\\textbf{i}_\\textbf{m}} \\textit{S}_{\\textbf{i}_\\textbf{m}}$$\n\n\nis the average sequence operation.", "_____no_output_____" ], [ "### Step 5: Fit the results\n\nRepeat Steps 1 through 4 for different values of $m$ and fit the results for the averaged sequence fidelity to the model:\n\n\n$$ \\textit{F}_{seq}^{(0)} \\big(m,{|}\\psi {\\rangle} \\big) = A_0 \\alpha^m +B_0$$\n\n\nwhere $A_0$ and $B_0$ absorb state preparation and measurement errors as well as an edge effect from the\nerror on the final gate.\n\n$\\alpha$ determines the average error-rate $r$, which is also called **Error per Clifford (EPC)** \naccording to the relation \n\n$$ r = 1-\\alpha-\\frac{1-\\alpha}{2^n} = \\frac{2^n-1}{2^n}(1-\\alpha)$$\n\n\n(where $n=nQ$ is the number of qubits).\n\nAs an example, we calculate the average sequence fidelity for each of the RB sequences, fit the results to the exponential curve, and compute the parameters $\\alpha$ and EPC.", "_____no_output_____" ] ], [ [ "# Create the RB fitter\nbackend = qiskit.Aer.get_backend('aer_simulator')\nbasis_gates = ['u1','u2','u3','cx'] \nshots = 200\ntranspiled_circs_list = []\nrb_fit = rb.RBFitter(None, xdata, rb_opts['rb_pattern'])\nfor rb_seed, rb_circ_seed in enumerate(rb_circs):\n print(f'Compiling seed {rb_seed}')\n new_rb_circ_seed = qiskit.compiler.transpile(rb_circ_seed, basis_gates=basis_gates)\n transpiled_circs_list.append(new_rb_circ_seed)\n print(f'Simulating seed {rb_seed}')\n qobj = assemble(new_rb_circ_seed, shots=shots)\n job = backend.run(qobj,\n noise_model=noise_model,\n max_parallel_experiments=0)\n # Add data to the fitter\n rb_fit.add_data(job.result())\n print('After seed %d, alpha: %f, EPC: %f'%(rb_seed,rb_fit.fit[0]['params'][1], rb_fit.fit[0]['epc']))", "Compiling seed 0\nSimulating seed 0\nAfter seed 0, alpha: 0.982790, EPC: 0.012908\nCompiling seed 1\nSimulating seed 1\nAfter seed 1, alpha: 0.978354, EPC: 0.016234\nCompiling seed 2\nSimulating seed 2\nAfter seed 2, alpha: 0.980195, EPC: 0.014854\nCompiling seed 3\nSimulating seed 3\nAfter seed 3, alpha: 0.980407, EPC: 0.014694\nCompiling seed 4\nSimulating seed 4\nAfter seed 4, alpha: 0.979808, EPC: 0.015144\n" ] ], [ [ "### Extra Step: Plot the results", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(8, 6))\nax = plt.subplot(1, 1, 1)\n\n# Plot the essence by calling plot_rb_data\nrb_fit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False)\n \n# Add title and label\nax.set_title('%d Qubit RB'%(nQ), fontsize=18)\n\nplt.show()", "_____no_output_____" ] ], [ [ "## 3. The Intuition Behind RB <a id='intuition'></a>\n\nThe depolarizing quantum channel has a parameter $\\alpha$, and works like this: with probability $\\alpha$, the state remains the same as before; with probability $1-\\alpha$, the state becomes the totally mixed state, namely:\n\n\n\n$$\\rho_f = \\alpha \\rho_i + \\frac{1-\\alpha}{2^n} * \\mathbf{I}$$\n\n\n\nSuppose that we have a sequence of $m$ gates, not necessarily Clifford gates, \nwhere the error channel of the gates is a depolarizing channel with parameter $\\alpha$ \n(same $\\alpha$ for all the gates). \nThen with probability $\\alpha^m$ the state is correct at the end of the sequence, \nand with probability $1-\\alpha^m$ it becomes the totally mixed state, therefore:\n\n\n\n$$\\rho_f^m = \\alpha^m \\rho_i + \\frac{1-\\alpha^m}{2^n} * \\mathbf{I}$$\n\n\n\nNow suppose that in addition we start with the ground state; \nthat the entire sequence amounts to the identity; \nand that we measure the state at the end of the sequence with the standard basis. \nWe derive that the probability of success at the end of the sequence is:\n\n\n\n$$\\alpha^m + \\frac{1-\\alpha^m}{2^n} = \\frac{2^n-1}{2^n}\\alpha^m + \\frac{1}{2^n} = A_0\\alpha^m + B_0$$\n\n\n\nIt follows that the probability of success, aka fidelity, decays exponentially with the sequence length, with exponent $\\alpha$.\n\nThe last statement is not necessarily true when the channel is other than the depolarizing channel. However, it turns out that if the gates are uniformly-randomized Clifford gates, then the noise of each gate behaves on average as if it was the depolarizing channel, with some parameter that can be computed from the channel, and we obtain the exponential decay of the fidelity.\n\nFormally, taking an average over a finite group $G$ (like the Clifford group) of a quantum channel $\\bar \\Lambda$ is also called a *twirl*:\n\n\n$$ W_G(\\bar \\Lambda) \\frac{1}{|G|} \\sum_{u \\in G} U^{\\dagger} \\circ \\bar \\Lambda \\circ U$$\n\n\nTwirling over the entire unitary group yields exactly the same result as the Clifford group. The Clifford group is a *2-design* of the unitary group.", "_____no_output_____" ], [ "## 4. Simultaneous Randomized Benchmarking <a id='simultaneousrb'></a>\n\n\nRB is designed to address fidelities in multiqubit systems in two ways. For one, RB over the full $n$-qubit space\ncan be performed by constructing sequences from the $n$-qubit Clifford group. Additionally, the $n$-qubit space\ncan be subdivided into sets of qubits $\\{n_i\\}$ and $n_i$-qubit RB performed in each subset simultaneously [4]. \nBoth methods give metrics of fidelity in the $n$-qubit space. \n\nFor example, it is common to perform 2Q RB on the subset of two-qubits defining a CNOT gate while the other qubits are quiescent. As explained in [4], this RB data will not necessarily decay exponentially because the other qubit subspaces are not twirled. Subsets are more rigorously characterized by simultaneous RB, which also measures some level of crosstalk error since all qubits are active.\n\nAn example of simultaneous RB (1Q RB and 2Q RB) can be found in: \nhttps://github.com/Qiskit/qiskit-tutorials/blob/master/tutorials/noise/4_randomized_benchmarking.ipynb", "_____no_output_____" ], [ "## 5. Predicted Gate Fidelity <a id='predicted-gate-fidelity'></a>\n\nIf we know the errors on the underlying gates (the gateset) we can predict the EPC without running RB experiment. This calculation verifies that your RB experiment followed by fitting yields correct EPC value. First we need to count the number of these gates per Clifford.\n\nThen, the two qubit Clifford gate error function ``calculate_2q_epc`` gives the error per 2Q Clifford. It assumes that the error in the underlying gates is depolarizing. This function is derived in the supplement to [5]. ", "_____no_output_____" ] ], [ [ "# count the number of single and 2Q gates in the 2Q Cliffords\nqubits = rb_opts['rb_pattern'][0]\n\ngate_per_cliff = rb.rb_utils.gates_per_clifford(\n transpiled_circuits_list=transpiled_circs_list,\n clifford_lengths=xdata[0],\n basis=basis_gates,\n qubits=qubits)\n\nfor basis_gate in basis_gates:\n print(\"Number of %s gates per Clifford: %f\"%(\n basis_gate,\n np.mean([gate_per_cliff[qubit][basis_gate] for qubit in qubits])))", "Number of u1 gates per Clifford: 0.120197\nNumber of u2 gates per Clifford: 1.653712\nNumber of u3 gates per Clifford: 0.171834\nNumber of cx gates per Clifford: 1.489301\n" ], [ "# convert from depolarizing error to epg (1Q)\nepg_q0 = {'u1': 0, 'u2': p1Q/2, 'u3': 2 * p1Q/2}\nepg_q1 = {'u1': 0, 'u2': p1Q/2, 'u3': 2 * p1Q/2}\n\n# convert from depolarizing error to epg (2Q)\nepg_q01 = 3/4 * p2Q\n\n# calculate the predicted epc from underlying gate errors \npred_epc = rb.rb_utils.calculate_2q_epc(\n gate_per_cliff=gate_per_cliff,\n epg_2q=epg_q01,\n qubit_pair=qubits,\n list_epgs_1q=[epg_q0, epg_q1])\n\nprint(\"Predicted 2Q Error per Clifford: %e (qasm simulator result: %e)\" % (pred_epc, rb_fit.fit[0]['epc']))", "Predicted 2Q Error per Clifford: 1.585392e-02 (qasm simulator result: 1.514424e-02)\n" ] ], [ [ "On the other hand, we can calculate the errors on the underlying gates (the gateset) from the experimentally obtained EPC. Given that we know the errors on the every single-qubit gates in the RB sequence, we can predict 2Q gate error from the EPC of two qubit RB experiment.\n\nThe two qubit gate error function ``calculate_2q_epg`` gives the estimate of error per 2Q gate. In this section we prepare single-qubit errors using the deporalizing error model. If the error model is unknown, EPGs of those gates, for example [``u1``, ``u2``, ``u3``], can be estimated with a separate 1Q RB experiment with the utility function ``calculate_1q_epg``.", "_____no_output_____" ] ], [ [ "# use 2Q EPC from qasm simulator result and 1Q EPGs from depolarizing error model\npred_epg = rb.rb_utils.calculate_2q_epg(\n gate_per_cliff=gate_per_cliff,\n epc_2q=rb_fit.fit[0]['epc'],\n qubit_pair=qubits,\n list_epgs_1q=[epg_q0, epg_q1])\n\nprint(\"Predicted 2Q Error per gate: %e (gate error model: %e)\" % (pred_epg, epg_q01))", "Predicted 2Q Error per gate: 7.002046e-03 (gate error model: 7.500000e-03)\n" ] ], [ [ "## 6. References <a id='references'></a>\n\n1. Easwar Magesan, J. M. Gambetta, and Joseph Emerson, *Robust randomized benchmarking of quantum processes*,\nhttps://arxiv.org/pdf/1009.3639\n\n2. Easwar Magesan, Jay M. Gambetta, and Joseph Emerson, *Characterizing Quantum Gates via Randomized Benchmarking*,\nhttps://arxiv.org/pdf/1109.6887\n\n3. A. D. C'orcoles, Jay M. Gambetta, Jerry M. Chow, John A. Smolin, Matthew Ware, J. D. Strand, B. L. T. Plourde, and M. Steffen, *Process verification of two-qubit quantum gates by randomized benchmarking*, https://arxiv.org/pdf/1210.7011\n\n4. Jay M. Gambetta, A. D. C´orcoles, S. T. Merkel, B. R. Johnson, John A. Smolin, Jerry M. Chow,\nColm A. Ryan, Chad Rigetti, S. Poletto, Thomas A. Ohki, Mark B. Ketchen, and M. Steffen,\n*Characterization of addressability by simultaneous randomized benchmarking*, https://arxiv.org/pdf/1204.6308\n\n5. David C. McKay, Sarah Sheldon, John A. Smolin, Jerry M. Chow, and Jay M. Gambetta, *Three Qubit Randomized Benchmarking*, https://arxiv.org/pdf/1712.06550", "_____no_output_____" ] ], [ [ "import qiskit.tools.jupyter\n%qiskit_version_table", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af3436798e0d547909858b1980140f2def6a24b
56,507
ipynb
Jupyter Notebook
05a_Result_Summary.ipynb
jsantoso2/Household_Amenity_Detection
dd05fe86f31b3eb3478f7675080ebc0f59ef0b6c
[ "Apache-2.0" ]
null
null
null
05a_Result_Summary.ipynb
jsantoso2/Household_Amenity_Detection
dd05fe86f31b3eb3478f7675080ebc0f59ef0b6c
[ "Apache-2.0" ]
4
2021-06-08T21:48:00.000Z
2022-03-12T00:35:22.000Z
05a_Result_Summary.ipynb
jsantoso2/Household_Amenity_Detection
dd05fe86f31b3eb3478f7675080ebc0f59ef0b6c
[ "Apache-2.0" ]
null
null
null
104.449168
36,576
0.771373
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## R50-FPN-3x", "_____no_output_____" ] ], [ [ "test_results = {'AP': 30.183924421787978,\n 'AP-Bathtub': 53.39773724295068,\n 'AP-Bed': 52.754509322305175,\n 'AP-Billiard table': 67.45412317841321,\n 'AP-Ceiling fan': 23.310566361650434,\n 'AP-Coffeemaker': 51.375885917263,\n 'AP-Couch': 25.679265150881648,\n 'AP-Countertop': 11.176039237004812,\n 'AP-Dishwasher': 0.0,\n 'AP-Fireplace': 23.42211115504908,\n 'AP-Fountain': 38.38767930113601,\n 'AP-Gas stove': 12.07564382601228,\n 'AP-Jacuzzi': 0.0,\n 'AP-Kitchen & dining room table': 13.75287501981837,\n 'AP-Microwave oven': 40.84644399475737,\n 'AP-Mirror': 35.00769838477773,\n 'AP-Oven': 25.496395102413526,\n 'AP-Pillow': 20.544141258990937,\n 'AP-Porch': 4.3426715044379485,\n 'AP-Refrigerator': 55.40458899535102,\n 'AP-Shower': 9.888904481361353,\n 'AP-Sink': 19.07946534850723,\n 'AP-Sofa bed': 50.07526874397189,\n 'AP-Stairs': 22.491392352723764,\n 'AP-Swimming pool': 72.9971033812601,\n 'AP-Television': 60.842008749251285,\n 'AP-Toilet': 48.78555603130734,\n 'AP-Towel': 27.24336336476925,\n 'AP-Tree house': 0.0,\n 'AP-Washing machine': 28.857248056840657,\n 'AP-Wine rack': 10.829047190433332,\n 'AP50': 48.5871640675183,\n 'AP75': 32.5724886725335,\n 'APl': 30.740800398603614,\n 'APm': 4.45571372903077,\n 'APs': 0.0}\n\nval_results = {'AP': 29.035,\n 'AP-Bathtub': 24.578,\n 'AP-Bed': 51.695,\n 'AP-Billiard table': 66.619,\n 'AP-Ceiling fan': 33.442,\n 'AP-Coffeemaker': 38.939,\n 'AP-Couch': 28.291,\n 'AP-Countertop': 14.857,\n 'AP-Dishwasher': 0.0,\n 'AP-Fireplace': 27.116,\n 'AP-Fountain': 43.165,\n 'AP-Gas stove': 15.449,\n 'AP-Jacuzzi': 0.0,\n 'AP-Kitchen & dining room table': 12.335,\n 'AP-Microwave oven': 34.291,\n 'AP-Mirror': 40.240,\n 'AP-Oven': 19.135,\n 'AP-Pillow': 18.432,\n 'AP-Porch': 6.291,\n 'AP-Refrigerator': 65.017,\n 'AP-Shower': 0.356,\n 'AP-Sink': 30.484,\n 'AP-Sofa bed': 47.172,\n 'AP-Stairs': 22.639,\n 'AP-Swimming pool': 66.461,\n 'AP-Television': 62.537,\n 'AP-Toilet': 40.841,\n 'AP-Towel': 21.892,\n 'AP-Tree house': 0.0,\n 'AP-Washing machine': 26.884,\n 'AP-Wine rack': 11.881,\n 'AP50': 47.212,\n 'AP75': 29.823,\n 'APl': 29.521,\n 'APm': 8.174,\n 'APs': 0.0}", "_____no_output_____" ] ], [ [ "## R101-FPN-3x", "_____no_output_____" ] ], [ [ "test_results = {'AP': 28.766909850927302,\n 'AP-Bathtub': 52.8782402573615,\n 'AP-Bed': 50.70832689983663,\n 'AP-Billiard table': 66.13464702811605,\n 'AP-Ceiling fan': 27.428841247258944,\n 'AP-Coffeemaker': 47.91662006356297,\n 'AP-Couch': 24.70202737120508,\n 'AP-Countertop': 13.138098151057076,\n 'AP-Dishwasher': 0.0,\n 'AP-Fireplace': 24.470721462337696,\n 'AP-Fountain': 36.17654043036692,\n 'AP-Gas stove': 12.488702772678968,\n 'AP-Jacuzzi': 0.0,\n 'AP-Kitchen & dining room table': 14.653719514085903,\n 'AP-Microwave oven': 40.50083273011718,\n 'AP-Mirror': 38.41435891370926,\n 'AP-Oven': 20.873738830025143,\n 'AP-Pillow': 20.05872752064416,\n 'AP-Porch': 3.4498669435768674,\n 'AP-Refrigerator': 58.293186422096944,\n 'AP-Shower': 7.062300368552515,\n 'AP-Sink': 18.582545225580418,\n 'AP-Sofa bed': 45.59211340725856,\n 'AP-Stairs': 23.649185867447596,\n 'AP-Swimming pool': 66.10703995176956,\n 'AP-Television': 51.687249913558084,\n 'AP-Toilet': 55.12556639625279,\n 'AP-Towel': 15.76906387979253,\n 'AP-Tree house': 0.0,\n 'AP-Washing machine': 20.827402196393372,\n 'AP-Wine rack': 6.317631763176316,\n 'AP50': 46.61545312066519,\n 'AP75': 31.415690542064546,\n 'APl': 29.406371855761982,\n 'APm': 5.212065007401241,\n 'APs': 0.0}\n\nval_results = {'AP': 29.029,\n 'AP-Bathtub': 19.976,\n 'AP-Bed': 48.495,\n 'AP-Billiard table': 61.895,\n 'AP-Ceiling fan': 26.736,\n 'AP-Coffeemaker': 38.939,\n 'AP-Couch': 21.837,\n 'AP-Countertop': 16.060,\n 'AP-Dishwasher': 0.0,\n 'AP-Fireplace': 29.547,\n 'AP-Fountain': 44.420,\n 'AP-Gas stove': 20.592,\n 'AP-Jacuzzi': 0.0,\n 'AP-Kitchen & dining room table': 10.273,\n 'AP-Microwave oven': 40.946,\n 'AP-Mirror': 41.844,\n 'AP-Oven': 24.474,\n 'AP-Pillow': 14.924,\n 'AP-Porch': 10.364,\n 'AP-Refrigerator': 71.404,\n 'AP-Shower': 1.814,\n 'AP-Sink': 23.286,\n 'AP-Sofa bed': 36.370,\n 'AP-Stairs': 25.209,\n 'AP-Swimming pool': 64.806,\n 'AP-Television': 58.349,\n 'AP-Toilet': 57.587,\n 'AP-Towel': 18.631,\n 'AP-Tree house': 0.0,\n 'AP-Washing machine': 30.103,\n 'AP-Wine rack': 14.851,\n 'AP50': 46.871,\n 'AP75': 29.029,\n 'APl': 29.522,\n 'APm': 7.737,\n 'APs': 0.0}", "_____no_output_____" ] ], [ [ "## RN-50-3x", "_____no_output_____" ] ], [ [ "test_results = {'AP': 38.492384449355676,\n 'AP-Bathtub': 60.115406677858815,\n 'AP-Bed': 57.83057924335149,\n 'AP-Billiard table': 75.51729046140261,\n 'AP-Ceiling fan': 45.18986833756713,\n 'AP-Coffeemaker': 51.970384613792795,\n 'AP-Couch': 23.824464499510597,\n 'AP-Countertop': 7.5333804114591345,\n 'AP-Dishwasher': 0.2611187892244602,\n 'AP-Fireplace': 42.060241857955674,\n 'AP-Fountain': 44.873704286774775,\n 'AP-Gas stove': 16.439547201431257,\n 'AP-Jacuzzi': 15.70258672546233,\n 'AP-Kitchen & dining room table': 11.599905718477451,\n 'AP-Microwave oven': 45.02085736870218,\n 'AP-Mirror': 43.812744467203615,\n 'AP-Oven': 42.11172757937511,\n 'AP-Pillow': 27.273736611804427,\n 'AP-Porch': 5.555847755821968,\n 'AP-Refrigerator': 75.04729718629045,\n 'AP-Shower': 10.573880914087361,\n 'AP-Sink': 26.0970404108146,\n 'AP-Sofa bed': 53.07206951762474,\n 'AP-Stairs': 30.971772175630193,\n 'AP-Swimming pool': 74.96574053773193,\n 'AP-Television': 65.65506318778338,\n 'AP-Toilet': 56.7543593099767,\n 'AP-Towel': 33.37522247440722,\n 'AP-Tree house': 15.550969305550783,\n 'AP-Washing machine': 39.793207405905434,\n 'AP-Wine rack': 56.221518447691665,\n 'AP50': 56.20747908075276,\n 'AP75': 40.936661522293235,\n 'APl': 39.232677787456346,\n 'APm': 7.138823519721613,\n 'APs': 0.0}\n\nval_results = {'AP': 39.412,\n 'AP-Bathtub': 17.3,\n 'AP-Bed': 57.507,\n 'AP-Billiard table': 69.881,\n 'AP-Ceiling fan': 74.183,\n 'AP-Coffeemaker': 54.816,\n 'AP-Couch': 26.903,\n 'AP-Countertop': 7.952,\n 'AP-Dishwasher': 3.922,\n 'AP-Fireplace': 35.853,\n 'AP-Fountain': 44.115,\n 'AP-Gas stove': 22.093,\n 'AP-Jacuzzi': 12.610,\n 'AP-Kitchen & dining room table': 10.115,\n 'AP-Microwave oven': 52.319,\n 'AP-Mirror': 56.331,\n 'AP-Oven': 40.307,\n 'AP-Pillow': 23.396,\n 'AP-Porch': 12.546,\n 'AP-Refrigerator': 70.455,\n 'AP-Shower': 2.472,\n 'AP-Sink': 33.583,\n 'AP-Sofa bed': 55.140,\n 'AP-Stairs': 28.852,\n 'AP-Swimming pool': 71.250,\n 'AP-Television': 63.350,\n 'AP-Toilet': 53.052,\n 'AP-Towel': 42.210,\n 'AP-Tree house': 46.378,\n 'AP-Washing machine': 39.166,\n 'AP-Wine rack': 54.297,\n 'AP50': 58.921,\n 'AP75': 45.521,\n 'APl': 39.918,\n 'APm': 11.587,\n 'APs': 0.0}", "_____no_output_____" ] ], [ [ "## RN-101-3x", "_____no_output_____" ] ], [ [ "test_results = {'AP': 38.629005503971094,\n 'AP-Bathtub': 57.88445796297448,\n 'AP-Bed': 59.37857224325405,\n 'AP-Billiard table': 76.94003410603575,\n 'AP-Ceiling fan': 43.559413116751685,\n 'AP-Coffeemaker': 48.989599570274635,\n 'AP-Couch': 28.408037999550057,\n 'AP-Countertop': 9.371518046833943,\n 'AP-Dishwasher': 0.3057563835101482,\n 'AP-Fireplace': 33.22536116260668,\n 'AP-Fountain': 51.67562280533134,\n 'AP-Gas stove': 12.330097602716778,\n 'AP-Jacuzzi': 12.350546301821613,\n 'AP-Kitchen & dining room table': 18.68710022505696,\n 'AP-Microwave oven': 53.34352009331587,\n 'AP-Mirror': 42.89079611781959,\n 'AP-Oven': 36.861902837366436,\n 'AP-Pillow': 27.396564938073226,\n 'AP-Porch': 5.103006680850462,\n 'AP-Refrigerator': 76.09240465640137,\n 'AP-Shower': 13.597115846657411,\n 'AP-Sink': 21.370478428246212,\n 'AP-Sofa bed': 52.38685348876891,\n 'AP-Stairs': 25.14933002641884,\n 'AP-Swimming pool': 78.33067628089339,\n 'AP-Television': 66.9673571851024,\n 'AP-Toilet': 59.34648419020555,\n 'AP-Towel': 30.715535811238592,\n 'AP-Tree house': 16.56763331964142,\n 'AP-Washing machine': 49.20082443485014,\n 'AP-Wine rack': 50.44356325656495,\n 'AP50': 56.89461825223869,\n 'AP75': 40.42469217370782,\n 'APl': 39.27304034450038,\n 'APm': 8.877459691321537,\n 'APs': 0.0}\n\nval_results = {'AP': 38.994,\n 'AP-Bathtub': 21.001,\n 'AP-Bed': 58.507,\n 'AP-Billiard table': 74.140,\n 'AP-Ceiling fan': 58.704,\n 'AP-Coffeemaker': 56.840,\n 'AP-Couch': 31.043,\n 'AP-Countertop': 11.130,\n 'AP-Dishwasher': 1.226,\n 'AP-Fireplace': 38.402,\n 'AP-Fountain': 52.095,\n 'AP-Gas stove': 18.639,\n 'AP-Jacuzzi': 5.965,\n 'AP-Kitchen & dining room table': 12.709,\n 'AP-Microwave oven': 58.799,\n 'AP-Mirror': 49.530,\n 'AP-Oven': 32.037,\n 'AP-Pillow': 18.782,\n 'AP-Porch': 16.070,\n 'AP-Refrigerator': 79.243,\n 'AP-Shower': 2.042,\n 'AP-Sink': 27.710,\n 'AP-Sofa bed': 47.664,\n 'AP-Stairs': 25.455,\n 'AP-Swimming pool': 73.408,\n 'AP-Television': 69.934,\n 'AP-Toilet': 49.344,\n 'AP-Towel': 48.058,\n 'AP-Tree house': 39.197,\n 'AP-Washing machine': 46.957,\n 'AP-Wine rack': 45.206,\n 'AP50': 58.644,\n 'AP75': 41.617,\n 'APl': 39.375,\n 'APm': 11.715,\n 'APs': 0.0}", "_____no_output_____" ] ], [ [ "## Plotting", "_____no_output_____" ] ], [ [ "result = pd.DataFrame([test_results], index=[0])\nresult = result.T\nresult.columns = ['result']\nresult.sort_values('result',inplace=True, ascending = True)\nresult.head()", "_____no_output_____" ], [ "plotted = []\nfor i in result.index:\n if i not in ['APl', 'APm', 'APs', 'AP50', 'AP75']:\n plotted.append(i)\n\nplt.figure(figsize=(10,8))\nchart = plt.barh([i.split('-')[1] if i not in ['AP'] else i for i in plotted], result.loc[plotted,'result'])\nchart[plotted.index('AP')].set_color('orange')\n\nplt.title('Average Precision by Class for RN-101-3x (Test Evaluation)')\nplt.xlabel('Average Precision')\nplt.ylabel('Classes')\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4af34a97772fee06e3d31b6cad9fd85d8fa0d636
126,998
ipynb
Jupyter Notebook
nbs/03-datasets.ipynb
KeremTurgutlu/tse
c08bd33dc40a61db3a57355e8580bf38ad8304be
[ "Apache-2.0" ]
1
2020-05-19T15:35:45.000Z
2020-05-19T15:35:45.000Z
nbs/03-datasets.ipynb
KeremTurgutlu/tse
c08bd33dc40a61db3a57355e8580bf38ad8304be
[ "Apache-2.0" ]
2
2021-09-28T01:31:04.000Z
2022-02-26T07:05:37.000Z
nbs/03-datasets.ipynb
KeremTurgutlu/tse
c08bd33dc40a61db3a57355e8580bf38ad8304be
[ "Apache-2.0" ]
null
null
null
52.348722
155
0.587923
[ [ [ "# default_exp datasets", "_____no_output_____" ], [ "#export\nfrom fastai.text import *\nfrom tse.preprocessing import *\nfrom tse.tokenizers import *", "tokenizers: 0.7.0\nfastai: 1.0.60\n" ] ], [ [ "### Prepare Data Inputs for Q/A\n\n\nFollowing for each input for training is needed:\n\n`input_ids`, `attention_mask`, `token_type_ids`, `offsets`, `answer_text`, `start_tok_idx`, `end_tok_idx`", "_____no_output_____" ], [ "Preprocess", "_____no_output_____" ] ], [ [ "train_df = pd.read_csv(\"../data/train.csv\").dropna().reset_index(drop=True)\ntest_df = pd.read_csv(\"../data/test.csv\")", "_____no_output_____" ], [ "strip_text(train_df, \"text\")\nstrip_text(train_df, \"selected_text\")\nstrip_text(test_df, \"text\")", "_____no_output_____" ], [ "replace_whitespace(train_df, \"text\")\nreplace_whitespace(train_df, \"selected_text\")\nreplace_whitespace(test_df, \"text\")", "_____no_output_____" ], [ "replace_URLs(train_df, \"text\")\nreplace_URLs(train_df, \"selected_text\")\nreplace_URLs(test_df, \"text\")", "_____no_output_____" ], [ "replace_user(train_df, \"text\")\nreplace_user(train_df, \"selected_text\")\nreplace_user(test_df, \"text\")", "_____no_output_____" ], [ "is_wrong = train_df.apply(lambda o: is_wrong_selection(o['text'], o['selected_text']), 1)\ntrain_df = train_df[~is_wrong].reset_index(drop=True)", "_____no_output_____" ], [ "list(train_df['text'])", "_____no_output_____" ], [ "train_df.shape", "_____no_output_____" ] ], [ [ "Tokenizer", "_____no_output_____" ] ], [ [ "tokenizer = init_roberta_tokenizer(\"../roberta-base/vocab.json\", \"../roberta-base/merges.txt\", max_length=192)", "_____no_output_____" ], [ "train_df.head()", "_____no_output_____" ], [ "#export\ndef get_start_end_idxs(context, answer):\n \"Get string start and end char for answer span\"\n len_a = len(answer)\n for i, _ in enumerate(context):\n if context[i:i+len_a] == answer: \n start_idx, end_idx = i, i+len_a-1\n return start_idx, end_idx\n raise Exception(\"No overlapping segment found\")", "_____no_output_____" ], [ "#export\ndef get_start_end_tok_idxs(offsets, start_idx, end_idx):\n \"Generate target from tokens - first 4 tokens belong to question\"\n start_tok_idx, end_tok_idx = None, None\n for tok_idx, off in enumerate(offsets[4:]):\n if (off[0] <= start_idx) & (off[1] > start_idx): start_tok_idx = tok_idx + 4\n if (off[0] <= end_idx) & (off[1] > end_idx): end_tok_idx = tok_idx + 4\n return (start_tok_idx, end_tok_idx)", "_____no_output_____" ], [ "trn_stxt, trn_txt, trn_sent = train_df.selected_text.values, train_df.text.values, train_df.sentiment\ntest_txt, test_sent = test_df.text.values, test_df.sentiment.values", "_____no_output_____" ], [ "train_tok_input = list(tuple(zip(trn_sent, trn_txt)))\ntest_tok_input = list(tuple(zip(test_sent, test_txt)))", "_____no_output_____" ], [ "# encode batch\ntrain_outputs = tokenizer.encode_batch(train_tok_input)\ntest_outputs = tokenizer.encode_batch(test_tok_input)", "_____no_output_____" ], [ "start_end_idxs = [get_start_end_idxs(s1,s2) for (s1,s2) in zip(trn_txt, trn_stxt)]", "_____no_output_____" ], [ "#export\nclass QAInputGenerator:\n def __init__(self, contexts, questions, text_ids=None, answers=None, tokenizer=None):\n self.contexts, self.questions, self.answers = contexts, questions, answers\n self.outputs = tokenizer.encode_batch(list(tuple(zip(questions, contexts))))\n if text_ids is not None: self.text_ids = text_ids\n if self.answers is not None:\n self.start_end_idxs = [get_start_end_idxs(s1,s2) for (s1,s2) in zip(self.contexts, self.answers)]\n \n \n @classmethod\n def from_df(cls, df, \n ctx_col='text', q_col='sentiment', id_col='textID', ans_col='selected_text', \n is_test=False, tokenizer=None):\n contexts = df[ctx_col].values\n questions = df[q_col].values\n text_ids = None if id_col is None else df[id_col].values\n answers = None if is_test else df[ans_col].values\n return cls(contexts, questions, text_ids, answers, tokenizer)\n \n \n def __getitem__(self, i):\n \n input_ids = array(self.outputs[i].ids)\n attention_mask = array(self.outputs[i].attention_mask)\n offsets = array(self.outputs[i].offsets)\n tokens = array(self.outputs[i].tokens)\n res = {\"input_ids\": input_ids, \"attention_mask\": attention_mask, \"offsets\": offsets, \n \"tokens\": tokens, \"context_text\": self.contexts[i]}\n \n if self.answers is not None:\n answer_text = self.answers[i]\n start_tok_idx, end_tok_idx = get_start_end_tok_idxs(offsets, *self.start_end_idxs[i])\n res[\"answer_text\"] = answer_text\n res[\"start_end_tok_idxs\"] = (start_tok_idx, end_tok_idx)\n\n if self.text_ids is not None:\n text_id = self.text_ids[i]\n res[\"text_id\"] = text_id\n \n return res\n \n def __len__(self): return len(self.contexts)", "_____no_output_____" ], [ "train_inputs = QAInputGenerator.from_df(train_df, tokenizer=tokenizer)", "_____no_output_____" ], [ "test_inputs = QAInputGenerator.from_df(test_df, is_test=True, tokenizer=tokenizer)", "_____no_output_____" ], [ "i = np.random.choice(range(len(train_inputs)))\nprint(train_inputs[i].keys())\nprint(train_inputs[i]['tokens'][train_inputs[i]['start_end_tok_idxs'][0]:train_inputs[i]['start_end_tok_idxs'][1]+1])\nprint(train_inputs[i]['answer_text'])", "dict_keys(['input_ids', 'attention_mask', 'offsets', 'tokens', 'context_text', 'answer_text', 'start_end_tok_idxs', 'text_id'])\n['Ġterrible']\nterrible\n" ], [ "i = np.random.choice(range(len(test_inputs)))\nprint(test_inputs[i].keys())\nprint(test_inputs[i]['tokens'][test_inputs[i]['attention_mask'].astype(bool)])", "dict_keys(['input_ids', 'attention_mask', 'offsets', 'tokens', 'context_text', 'text_id'])\n['<s>' 'Ġnegative' '</s>' '</s>' 'Ġand' 'Ġim' 'Ġjust' 'Ġgoing' 'Ġinto' 'Ġwork' '...' 'Ġif' 'Ġwe' 'Ġwere' 'Ġmarried' ','\n 'Ġwe' 'Ġw' 'ud' 'Ġnever' 'Ġsee' 'Ġeach' 'Ġother' '</s>']\n" ], [ "train_inputs = list(train_inputs)\ntest_inputs = list(test_inputs)", "_____no_output_____" ], [ "len(train_inputs), len(test_inputs)", "_____no_output_____" ] ], [ [ "### TSEDataAugmentor\n\n#### 1) Random Left - Right Truncate\n\n```\n-> tok3 anstok anstok anstok tok7 (rand left and right idxs)\n-> tok3 anstok anstok anstok tok7 tok8 (rand left idx)\n-> Tok1 tok2 tok3 anstok anstok anstok tok7 (rand right idx)\n```\n\n\n#### 2) Random Mask\n\n```\n-> Tok1 tok2 <MASK> anstok anstok anstok tok7 <MASK>\n-> Tok1 tok2 <UNK> anstok anstok anstok tok7 <UNK>\n```\n\n#### 3) Replace with pseudolabel\n", "_____no_output_____" ] ], [ [ "#export\nclass TSEDataAugmentor:\n def __init__(self, tokenizer, input_ids, attention_mask, start_position, end_position): \n\n self.tokenizer = tokenizer \n self.input_ids = input_ids\n self.attention_mask = attention_mask\n \n # initial answer start and end positions\n self.ans_start_pos, self.ans_end_pos = start_position.item(), end_position.item()\n \n # context token start and end excluding bos - eos tokens\n self.context_start_pos = 4\n self.context_end_pos = torch.where(attention_mask)[0][-1].item() - 1\n \n\n \n \n # left and right indexes excluding answer tokens and eos token\n @property\n def left_idxs(self): return np.arange(self.context_start_pos, self.ans_start_pos)\n \n @property\n def right_idxs(self): return np.arange(self.ans_end_pos+1, self.context_end_pos+1)\n \n @property\n def left_right_idxs(self): return np.concatenate([self.left_idxs, self.right_idxs])\n \n @property\n def rand_left_idx(self): return np.random.choice(self.left_idxs) if self.left_idxs.size > 0 else None\n \n @property\n def rand_right_idx(self): return np.random.choice(self.right_idxs) if self.right_idxs.size > 0 else None\n \n \n \n def right_truncate(self, right_idx):\n \"\"\"\n Truncate context from random right index to beginning, answer pos doesn't change\n Note: token_type_ids NotImplemented\n \"\"\"\n if not right_idx: raise Exception(\"Right index can't be None\")\n \n # clone for debugging\n new_input_ids = self.input_ids.clone()\n nopad_input_ids = new_input_ids[self.attention_mask.bool()]\n \n # truncate from right idx to beginning - add eos_token_id to end\n truncated = torch.cat([nopad_input_ids[:right_idx+1], tensor([self.tokenizer.eos_token_id])])\n \n # pad new context until size are equal\n # replace original input context with new\n n_pad = len(nopad_input_ids) - len(truncated)\n new_context = F.pad(truncated, (0,n_pad), value=self.tokenizer.pad_token_id)\n new_input_ids[:self.context_end_pos+2] = new_context\n \n \n # find new attention mask, update new context end position (exclude eos token)\n # Note: context start doesn't change since we don't manipulate question\n new_attention_mask = tensor([1 if i != 1 else 0 for i in new_input_ids])\n new_context_end_pos = torch.where(new_attention_mask)[0][-1].item() - 1 \n self.context_end_pos = new_context_end_pos\n \n # update input_ids and attention_masks\n self.input_ids = new_input_ids\n self.attention_mask = new_attention_mask\n \n return self.input_ids, self.attention_mask, (tensor(self.ans_start_pos), tensor(self.ans_end_pos))\n\n def random_right_truncate(self):\n right_idx = self.rand_right_idx\n if right_idx: self.right_truncate(right_idx)\n \n \n def left_truncate(self, left_idx):\n \"\"\"\n Truncate context from random left index to end, answer pos changes too\n Note: token_type_ids NotImplemented\n \"\"\"\n \n if not left_idx: raise Exception(\"Left index can't be None\")\n \n # clone for debugging\n new_input_ids = self.input_ids.clone()\n \n # pad new context until size are equal\n # replace original input context with new\n\n n_pad = len(new_input_ids[self.context_start_pos:]) - len(new_input_ids[left_idx:])\n \n new_context = F.pad(new_input_ids[left_idx:], (0,n_pad), value=self.tokenizer.pad_token_id)\n \n new_input_ids[self.context_start_pos:] = new_context\n \n \n # find new attention mask, update new context end position (exclude eos token)\n # Note: context start doesn't change since we don't manipulate question\n new_attention_mask = tensor([1 if i != 1 else 0 for i in new_input_ids])\n new_context_end_pos = torch.where(new_attention_mask)[0][-1].item() - 1\n self.context_end_pos = new_context_end_pos\n \n # find new answer start and end positions\n # update new answer start and end positions\n ans_shift = left_idx - self.context_start_pos\n self.ans_start_pos, self.ans_end_pos = self.ans_start_pos-ans_shift, self.ans_end_pos-ans_shift\n \n \n # update input_ids and attention_masks\n self.input_ids = new_input_ids\n self.attention_mask = new_attention_mask\n \n return self.input_ids, self.attention_mask, (tensor(self.ans_start_pos), tensor(self.ans_end_pos))\n \n def random_left_truncate(self):\n left_idx = self.rand_left_idx\n if left_idx: self.left_truncate(left_idx)\n \n \n def replace_with_mask(self, idxs_to_mask):\n \"\"\"\n Replace given input ids with tokenizer.mask_token_id\n \"\"\"\n # clone for debugging\n new_input_ids = self.input_ids.clone()\n new_input_ids[idxs_to_mask] = tensor([self.tokenizer.mask_token_id]*len(idxs_to_mask))\n self.input_ids = new_input_ids\n\n \n def random_replace_with_mask(self, mask_p=0.2):\n \"\"\"\n mask_p: Proportion of tokens to replace with mask token id\n \"\"\"\n idxs_to_mask = np.random.choice(self.left_right_idxs, int(len(self.left_right_idxs)*mask_p))\n if idxs_to_mask.size > 0: self.replace_with_mask(idxs_to_mask)\n \n ", "_____no_output_____" ], [ "i = np.random.choice(range(len(train_inputs)))\n\ninput_ids = tensor(train_inputs[i]['input_ids'])\nattention_mask = tensor(train_inputs[i]['attention_mask'])\nstart_position, end_position = train_inputs[i]['start_end_tok_idxs']\nstart_position, end_position = tensor(start_position), tensor(end_position)\n\nanswer_text = train_inputs[i]['answer_text']\ncontext_text = train_inputs[i]['context_text']\noffsets = train_inputs[i]['offsets']", "_____no_output_____" ], [ "input_ids[attention_mask.bool()]", "_____no_output_____" ], [ "start_position, end_position", "_____no_output_____" ], [ "answer_text, context_text, start_position.item(), end_position.item()", "_____no_output_____" ], [ "\" \".join([tokenizer.id_to_token(o) for o in input_ids[attention_mask.bool()]])", "_____no_output_____" ], [ "\" \".join([tokenizer.id_to_token(o) for o in input_ids[start_position.item(): end_position.item()+1]])", "_____no_output_____" ], [ "char_start = min(np.concatenate([offsets[start_position.item()], offsets[end_position.item()]]))\nchar_end = max(np.concatenate([offsets[start_position.item()], offsets[end_position.item()]]))", "_____no_output_____" ], [ "context_text[char_start:char_end]", "_____no_output_____" ], [ "def convert_ids_to_tokens(toks):\n return [tokenizer.id_to_token(o) for o in toks]\n\ntokenizer.convert_ids_to_tokens = convert_ids_to_tokens", "_____no_output_____" ] ], [ [ "### demo right truncate", "_____no_output_____" ] ], [ [ "da = TSEDataAugmentor(tokenizer, input_ids, attention_mask, start_position, end_position)\nda.random_right_truncate()\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.attention_mask.bool()])))\nprint()\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.ans_start_pos :da.ans_end_pos+1])))", "<s> Ġneutral </s> </s> Ġpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug Ġ; d </s>\n\nĠpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug\n" ] ], [ [ "### demo left truncate", "_____no_output_____" ] ], [ [ "da = TSEDataAugmentor(tokenizer, input_ids, attention_mask, start_position, end_position)\nda.random_left_truncate()\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.attention_mask.bool()])))\nprint()\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.ans_start_pos :da.ans_end_pos+1])))", "<s> Ġneutral </s> </s> Ġpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug Ġ; d </s>\n\nĠpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug\n" ], [ "da.ans_start_pos, da.ans_end_pos", "_____no_output_____" ] ], [ [ "### demo replace with mask", "_____no_output_____" ] ], [ [ "da = TSEDataAugmentor(tokenizer, input_ids, attention_mask, start_position, end_position)\nda.random_replace_with_mask(0.2)\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.attention_mask.bool()])))\nprint()\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.ans_start_pos :da.ans_end_pos+1])))", "<s> Ġneutral </s> </s> Ġpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug Ġ; d </s>\n\nĠpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug\n" ], [ "da.left_idxs, da.right_idxs", "_____no_output_____" ] ], [ [ "### demo all", "_____no_output_____" ] ], [ [ "da = TSEDataAugmentor(tokenizer, input_ids, attention_mask, start_position, end_position)\n\nda.random_left_truncate()\nda.random_right_truncate()\nda.random_replace_with_mask(0.3)\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.attention_mask.bool()])))\nprint()\nprint(\" \".join(tokenizer.convert_ids_to_tokens(da.input_ids[da.ans_start_pos :da.ans_end_pos+1])))", "<s> Ġneutral </s> </s> Ġpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug Ġ; d </s>\n\nĠpoor Ġyou Ġif Ġi Ġwas Ġwith Ġyou Ġright Ġnow ; Ġi Ġwould Ġprobably Ġgive Ġyou Ġa Ġhug\n" ] ], [ [ "### TSEDataset", "_____no_output_____" ] ], [ [ "#export\ndo_tfms = {}\ndo_tfms[\"random_left_truncate\"] = {\"p\":.3}\ndo_tfms[\"random_right_truncate\"] = {\"p\":.3}\ndo_tfms[\"random_replace_with_mask\"] = {\"p\":.3, \"mask_p\":0.2}\ndo_tfms[\"random_replace_with_pseudo\"] = {\"p\":.3}\ndo_tfms", "_____no_output_____" ], [ "pseudo_df = pd.read_csv(\"../data/pseudo_labels/pseudo_labelled_sample.csv\")\npseudo_df = pseudo_df[['ids', 'text', 'target', 'predicted_answer']]\npseudo_df.head()", "_____no_output_____" ], [ "pseudo_df.shape", "_____no_output_____" ], [ "#export\nclass TSEDataset(Dataset):\n def __init__(self, inputs, tokenizer=None, is_test=False, do_tfms:Dict=None, pseudo_inputs=None):\n\n # eval\n self.inputs = inputs\n\n # augmentation\n self.is_test = is_test\n self.tokenizer = tokenizer\n self.do_tfms = do_tfms\n self.pseudo_inputs = pseudo_inputs\n if self.pseudo_inputs: self.pseudo_idxs = list(range(len(self.pseudo_inputs)))\n \n def __getitem__(self, i):\n 'fastai requires (xb, yb) to return'\n \n input_ids = tensor(self.inputs[i]['input_ids'])\n attention_mask = tensor(self.inputs[i]['attention_mask'])\n \n if not self.is_test: \n start_position, end_position = self.inputs[i]['start_end_tok_idxs']\n start_position, end_position = tensor(start_position), tensor(end_position)\n \n if self.do_tfms: \n if self.pseudo_inputs and (np.random.uniform() < self.do_tfms[\"random_replace_with_pseudo\"][\"p\"]):\n rand_idx = np.random.choice(self.pseudo_idxs)\n \n input_ids = tensor(self.pseudo_inputs[rand_idx]['input_ids'])\n attention_mask = tensor(self.pseudo_inputs[rand_idx]['attention_mask'])\n start_position, end_position = self.pseudo_inputs[rand_idx]['start_end_tok_idxs']\n start_position, end_position = tensor(start_position), tensor(end_position)\n \n else:\n augmentor = TSEDataAugmentor(self.tokenizer, \n input_ids,\n attention_mask,\n start_position, end_position)\n \n if np.random.uniform() < self.do_tfms[\"random_left_truncate\"][\"p\"]:\n augmentor.random_left_truncate()\n if np.random.uniform() < self.do_tfms[\"random_right_truncate\"][\"p\"]:\n augmentor.random_right_truncate()\n if np.random.uniform() < self.do_tfms[\"random_replace_with_mask\"][\"p\"]:\n augmentor.random_replace_with_mask(self.do_tfms[\"random_replace_with_mask\"][\"mask_p\"])\n\n input_ids = augmentor.input_ids\n attention_mask = augmentor.attention_mask\n start_position, end_position = tensor(augmentor.ans_start_pos), tensor(augmentor.ans_end_pos)\n \n \n xb = (input_ids, attention_mask)\n if not self.is_test: yb = (start_position, end_position)\n else: yb = (0,0)\n \n return xb, yb\n \n def __len__(self): return len(self.inputs)", "_____no_output_____" ], [ "#export\ndo_tfms = {}\ndo_tfms[\"random_left_truncate\"] = {\"p\":.3}\ndo_tfms[\"random_right_truncate\"] = {\"p\":.3}\ndo_tfms[\"random_replace_with_mask\"] = {\"p\":.3, \"mask_p\":0.2}\ndo_tfms[\"random_replace_with_pseudo\"] = {\"p\":1.}\ndo_tfms", "_____no_output_____" ], [ "pseudo_inputs = QAInputGenerator.from_df(pseudo_df, \n tokenizer=tokenizer,\n q_col='target', id_col='ids', ans_col='predicted_answer')", "_____no_output_____" ], [ "len(pseudo_inputs)", "_____no_output_____" ], [ "train_ds = TSEDataset(train_inputs, tokenizer, is_test=False, do_tfms=do_tfms, pseudo_inputs=pseudo_inputs)\ntest_ds = TSEDataset(test_inputs, tokenizer, is_test=True, do_tfms=None)", "_____no_output_____" ], [ "do_tfms", "_____no_output_____" ], [ "(input_ids, att_masks), (start_idx, end_idx) = train_ds[0]\n\" \".join(tokenizer.convert_ids_to_tokens(input_ids[att_masks.bool()]))", "_____no_output_____" ], [ "\" \".join(tokenizer.convert_ids_to_tokens(input_ids[att_masks.bool()][start_idx:end_idx+1]))", "_____no_output_____" ], [ "# ### `predict_answer_text`\n\n# TODO: Migrate to proper notebook\n\n# #export\n# def predict_answer_text(start_logits, end_logits, attention_mask,\n# context_text, char_to_word_offset, token_to_orig_map): \n# \"Find best answer from context\"\n# # find best start and end\n# context_start, context_end = min(token_to_orig_map), max(token_to_orig_map)\n# truncated_start_logits = start_logits[attention_mask.bool()][context_start:context_end+1]\n# truncated_end_logits = end_logits[attention_mask.bool()][context_start:context_end+1]\n# best_start_idx, best_end_idx = find_best_start_end_idxs(truncated_start_logits, truncated_end_logits)\n \n# # generate answer\n# tok_orig_char_start = token_to_orig_map[best_start_idx+context_start] \n# tok_orig_char_end = token_to_orig_map[best_end_idx+context_start]\n# return answer_from_orig_context(context_text, char_to_word_offset, tok_orig_char_start, tok_orig_char_end)\n\n# predict_answer_text(start_logits, end_logits, attention_mask, \n# context_text, char_to_word_offset, token_to_orig_map)", "_____no_output_____" ] ], [ [ "### export", "_____no_output_____" ] ], [ [ "from nbdev.export import notebook2script\nnotebook2script()", "Converted 00_core.ipynb.\nConverted 01-preprocessing.ipynb.\nConverted 01-squad-utils.ipynb.\nConverted 02-tokenizers.ipynb.\nConverted 03-datasets.ipynb.\nConverted 04-models.ipynb.\nConverted post-process.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown", "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4af34d669743149082ff9ebd57813cae562033ab
29,673
ipynb
Jupyter Notebook
ml/cc/exercises/ko/feature_sets.ipynb
prafullkotecha/eng-edu
d23f81c9a8f39dc399233544cacfe27ae62b63e3
[ "Apache-2.0" ]
null
null
null
ml/cc/exercises/ko/feature_sets.ipynb
prafullkotecha/eng-edu
d23f81c9a8f39dc399233544cacfe27ae62b63e3
[ "Apache-2.0" ]
null
null
null
ml/cc/exercises/ko/feature_sets.ipynb
prafullkotecha/eng-edu
d23f81c9a8f39dc399233544cacfe27ae62b63e3
[ "Apache-2.0" ]
null
null
null
40.815681
786
0.540323
[ [ [ "#### Copyright 2017 Google LLC.", "_____no_output_____" ] ], [ [ "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ] ], [ [ " # 특성 세트", "_____no_output_____" ], [ " **학습 목표:** 복잡한 특성 세트만큼 좋은 성능을 발휘하는 최소한의 특성 세트를 만듭니다.", "_____no_output_____" ], [ " 지금까지는 모델에 모든 특성을 집어넣었습니다. 그러나 모델에 포함된 특성이 적을수록 리소스 사용이 감소하며 유지보수도 쉬워집니다. 이제부터는 주택 관련 특성을 최소한으로 사용하면서 데이터 세트의 모든 특성을 사용하는 모델과 동등한 성능을 발휘하는 모델을 만들 수 있는지를 살펴보겠습니다.", "_____no_output_____" ], [ " ## 설정\n\n이전과 마찬가지로 캘리포니아 주택 데이터를 로드하고 준비하겠습니다.", "_____no_output_____" ] ], [ [ "import math\n\nfrom IPython import display\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nimport tensorflow as tf\nfrom tensorflow.python.data import Dataset\n\ntf.logging.set_verbosity(tf.logging.ERROR)\npd.options.display.max_rows = 10\npd.options.display.float_format = '{:.1f}'.format\n\ncalifornia_housing_dataframe = pd.read_csv(\"https://storage.googleapis.com/mledu-datasets/california_housing_train.csv\", sep=\",\")\n\ncalifornia_housing_dataframe = california_housing_dataframe.reindex(\n np.random.permutation(california_housing_dataframe.index))", "_____no_output_____" ], [ "def preprocess_features(california_housing_dataframe):\n \"\"\"Prepares input features from California housing data set.\n\n Args:\n california_housing_dataframe: A Pandas DataFrame expected to contain data\n from the California housing data set.\n Returns:\n A DataFrame that contains the features to be used for the model, including\n synthetic features.\n \"\"\"\n selected_features = california_housing_dataframe[\n [\"latitude\",\n \"longitude\",\n \"housing_median_age\",\n \"total_rooms\",\n \"total_bedrooms\",\n \"population\",\n \"households\",\n \"median_income\"]]\n processed_features = selected_features.copy()\n # Create a synthetic feature.\n processed_features[\"rooms_per_person\"] = (\n california_housing_dataframe[\"total_rooms\"] /\n california_housing_dataframe[\"population\"])\n return processed_features\n\ndef preprocess_targets(california_housing_dataframe):\n \"\"\"Prepares target features (i.e., labels) from California housing data set.\n\n Args:\n california_housing_dataframe: A Pandas DataFrame expected to contain data\n from the California housing data set.\n Returns:\n A DataFrame that contains the target feature.\n \"\"\"\n output_targets = pd.DataFrame()\n # Scale the target to be in units of thousands of dollars.\n output_targets[\"median_house_value\"] = (\n california_housing_dataframe[\"median_house_value\"] / 1000.0)\n return output_targets", "_____no_output_____" ], [ "# Choose the first 12000 (out of 17000) examples for training.\ntraining_examples = preprocess_features(california_housing_dataframe.head(12000))\ntraining_targets = preprocess_targets(california_housing_dataframe.head(12000))\n\n# Choose the last 5000 (out of 17000) examples for validation.\nvalidation_examples = preprocess_features(california_housing_dataframe.tail(5000))\nvalidation_targets = preprocess_targets(california_housing_dataframe.tail(5000))\n\n# Double-check that we've done the right thing.\nprint \"Training examples summary:\"\ndisplay.display(training_examples.describe())\nprint \"Validation examples summary:\"\ndisplay.display(validation_examples.describe())\n\nprint \"Training targets summary:\"\ndisplay.display(training_targets.describe())\nprint \"Validation targets summary:\"\ndisplay.display(validation_targets.describe())", "_____no_output_____" ] ], [ [ " ## 작업 1: 효율적인 특성 세트 개발\n\n**특성을 2~3개만 사용하면서 성능을 어디까지 올릴 수 있을까요?**\n\n**상관행렬**은 각 특성을 타겟과 비교한 결과 및 각 특성을 서로 비교한 결과에 따라 쌍의 상관성을 보여줍니다.\n\n여기에서는 상관성을 [피어슨 상관계수](https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient)로 정의합니다. 이 실습을 위해 자세한 수학적 원리를 이해할 필요는 없습니다.\n\n상관성 값의 의미는 다음과 같습니다.\n\n * `-1.0`: 완벽한 음의 상관성\n * `0.0`: 상관성 없음\n * `1.0`: 완벽한 양의 상관성", "_____no_output_____" ] ], [ [ "correlation_dataframe = training_examples.copy()\ncorrelation_dataframe[\"target\"] = training_targets[\"median_house_value\"]\n\ncorrelation_dataframe.corr()", "_____no_output_____" ] ], [ [ " 타겟과 상관성이 높은 특성을 찾아야 합니다.\n\n또한 각 특성이 서로 독립적인 정보를 추가하도록 서로간의 상관성이 높지 않은 특성을 찾는 것이 좋습니다.\n\n이 정보를 참고하여 특성을 삭제해 보세요. 두 가지 원시 특성의 비율과 같은 합성 특성을 추가로 만들어 볼 수도 있습니다.\n\n편의를 위해 이전 실습의 학습 코드를 포함해 두었습니다.", "_____no_output_____" ] ], [ [ "def construct_feature_columns(input_features):\n \"\"\"Construct the TensorFlow Feature Columns.\n\n Args:\n input_features: The names of the numerical input features to use.\n Returns:\n A set of feature columns\n \"\"\" \n return set([tf.feature_column.numeric_column(my_feature)\n for my_feature in input_features])", "_____no_output_____" ], [ "def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n \"\"\"Trains a linear regression model of one feature.\n \n Args:\n features: pandas DataFrame of features\n targets: pandas DataFrame of targets\n batch_size: Size of batches to be passed to the model\n shuffle: True or False. Whether to shuffle the data.\n num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n Returns:\n Tuple of (features, labels) for next data batch\n \"\"\"\n \n # Convert pandas data into a dict of np arrays\n features = {key:np.array(value) for key,value in dict(features).items()} \n \n # Construct a dataset, and configure batching/repeating\n ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n ds = ds.batch(batch_size).repeat(num_epochs)\n\n # Shuffle the data, if specified\n if shuffle:\n ds = ds.shuffle(10000)\n \n # Return the next batch of data\n features, labels = ds.make_one_shot_iterator().get_next()\n return features, labels", "_____no_output_____" ], [ "def train_model(\n learning_rate,\n steps,\n batch_size,\n training_examples,\n training_targets,\n validation_examples,\n validation_targets):\n \"\"\"Trains a linear regression model.\n \n In addition to training, this function also prints training progress information,\n as well as a plot of the training and validation loss over time.\n \n Args:\n learning_rate: A `float`, the learning rate.\n steps: A non-zero `int`, the total number of training steps. A training step\n consists of a forward and backward pass using a single batch.\n batch_size: A non-zero `int`, the batch size.\n training_examples: A `DataFrame` containing one or more columns from\n `california_housing_dataframe` to use as input features for training.\n training_targets: A `DataFrame` containing exactly one column from\n `california_housing_dataframe` to use as target for training.\n validation_examples: A `DataFrame` containing one or more columns from\n `california_housing_dataframe` to use as input features for validation.\n validation_targets: A `DataFrame` containing exactly one column from\n `california_housing_dataframe` to use as target for validation.\n \n Returns:\n A `LinearRegressor` object trained on the training data.\n \"\"\"\n\n periods = 10\n steps_per_period = steps / periods\n\n # Create a linear regressor object.\n my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n linear_regressor = tf.estimator.LinearRegressor(\n feature_columns=construct_feature_columns(training_examples),\n optimizer=my_optimizer\n )\n \n # Create input functions\n training_input_fn = lambda: my_input_fn(training_examples, \n training_targets[\"median_house_value\"], \n batch_size=batch_size)\n predict_training_input_fn = lambda: my_input_fn(training_examples, \n training_targets[\"median_house_value\"], \n num_epochs=1, \n shuffle=False)\n predict_validation_input_fn = lambda: my_input_fn(validation_examples, \n validation_targets[\"median_house_value\"], \n num_epochs=1, \n shuffle=False)\n\n # Train the model, but do so inside a loop so that we can periodically assess\n # loss metrics.\n print \"Training model...\"\n print \"RMSE (on training data):\"\n training_rmse = []\n validation_rmse = []\n for period in range (0, periods):\n # Train the model, starting from the prior state.\n linear_regressor.train(\n input_fn=training_input_fn,\n steps=steps_per_period,\n )\n # Take a break and compute predictions.\n training_predictions = linear_regressor.predict(input_fn=predict_training_input_fn)\n training_predictions = np.array([item['predictions'][0] for item in training_predictions])\n \n validation_predictions = linear_regressor.predict(input_fn=predict_validation_input_fn)\n validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])\n \n # Compute training and validation loss.\n training_root_mean_squared_error = math.sqrt(\n metrics.mean_squared_error(training_predictions, training_targets))\n validation_root_mean_squared_error = math.sqrt(\n metrics.mean_squared_error(validation_predictions, validation_targets))\n # Occasionally print the current loss.\n print \" period %02d : %0.2f\" % (period, training_root_mean_squared_error)\n # Add the loss metrics from this period to our list.\n training_rmse.append(training_root_mean_squared_error)\n validation_rmse.append(validation_root_mean_squared_error)\n print \"Model training finished.\"\n\n \n # Output a graph of loss metrics over periods.\n plt.ylabel(\"RMSE\")\n plt.xlabel(\"Periods\")\n plt.title(\"Root Mean Squared Error vs. Periods\")\n plt.tight_layout()\n plt.plot(training_rmse, label=\"training\")\n plt.plot(validation_rmse, label=\"validation\")\n plt.legend()\n\n return linear_regressor", "_____no_output_____" ] ], [ [ " 5분 동안 효율적인 특성 세트 및 학습 매개변수를 찾아보세요. 그런 다음 해결 방법을 확인하여 모범 답안을 알아보세요. 특성마다 필요한 학습 매개변수가 다를 수 있다는 점에 유의하시기 바랍니다.", "_____no_output_____" ] ], [ [ "#\n# Your code here: add your features of choice as a list of quoted strings.\n#\nminimal_features = [\n]\n\nassert minimal_features, \"You must select at least one feature!\"\n\nminimal_training_examples = training_examples[minimal_features]\nminimal_validation_examples = validation_examples[minimal_features]\n\n#\n# Don't forget to adjust these parameters.\n#\ntrain_model(\n learning_rate=0.001,\n steps=500,\n batch_size=5,\n training_examples=minimal_training_examples,\n training_targets=training_targets,\n validation_examples=minimal_validation_examples,\n validation_targets=validation_targets)", "_____no_output_____" ] ], [ [ " ### 해결 방법\n\n해결 방법을 보려면 아래를 클릭하세요.", "_____no_output_____" ] ], [ [ "minimal_features = [\n \"median_income\",\n \"latitude\",\n]\n\nminimal_training_examples = training_examples[minimal_features]\nminimal_validation_examples = validation_examples[minimal_features]\n\n_ = train_model(\n learning_rate=0.01,\n steps=500,\n batch_size=5,\n training_examples=minimal_training_examples,\n training_targets=training_targets,\n validation_examples=minimal_validation_examples,\n validation_targets=validation_targets)", "_____no_output_____" ] ], [ [ " ## 작업 2: 위도 활용 고도화\n\n`latitude`와 `median_house_value`로 그래프를 그리면 선형 관계가 없다는 점이 드러납니다.\n\n대신, 로스앤젤레스 및 샌프란시스코에 해당하는 위치 부근에 마루가 나타납니다.", "_____no_output_____" ] ], [ [ "plt.scatter(training_examples[\"latitude\"], training_targets[\"median_house_value\"])", "_____no_output_____" ] ], [ [ " **위도를 더 잘 활용할 수 있는 합성 특성을 만들어 보세요.**\n\n예를 들어 `latitude`를 `|latitude - 38|`의 값에 매핑하는 특성을 만들고 이름을 `distance_from_san_francisco`로 지정할 수 있습니다.\n\n또는 공간을 10개의 버킷으로 나눌 수 있습니다. `latitude_32_to_33`, `latitude_33_to_34` 등의 특성을 만들고 `latitude`가 해당 버킷의 범위에 포함되면 `1.0` 값을, 그렇지 않으면 `0.0` 값을 표시하면 됩니다.\n\n상관행렬을 개발에 참고하면서 적절한 특성이 발견되면 모델에 추가하세요.\n\n검증 성능을 최대 어느 정도까지 높일 수 있나요?", "_____no_output_____" ] ], [ [ "#\n# YOUR CODE HERE: Train on a new data set that includes synthetic features based on latitude.\n#", "_____no_output_____" ] ], [ [ " ### 해결 방법\n\n해결 방법을 보려면 아래를 클릭하세요.", "_____no_output_____" ], [ " `latitude` 이외에 `median_income`도 유지하여 이전 결과와 비교하겠습니다.\n\n위도를 버킷화하기로 결정했습니다. Pandas에서 `Series.apply`를 사용하면 되므로 매우 간단합니다.", "_____no_output_____" ] ], [ [ "LATITUDE_RANGES = zip(xrange(32, 44), xrange(33, 45))\n\ndef select_and_transform_features(source_df):\n selected_examples = pd.DataFrame()\n selected_examples[\"median_income\"] = source_df[\"median_income\"]\n for r in LATITUDE_RANGES:\n selected_examples[\"latitude_%d_to_%d\" % r] = source_df[\"latitude\"].apply(\n lambda l: 1.0 if l >= r[0] and l < r[1] else 0.0)\n return selected_examples\n\nselected_training_examples = select_and_transform_features(training_examples)\nselected_validation_examples = select_and_transform_features(validation_examples)", "_____no_output_____" ], [ "_ = train_model(\n learning_rate=0.01,\n steps=500,\n batch_size=5,\n training_examples=selected_training_examples,\n training_targets=training_targets,\n validation_examples=selected_validation_examples,\n validation_targets=validation_targets)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
4af365d908c2bd80b2449a8ff42b6b0456e3561d
12,900
ipynb
Jupyter Notebook
how-to-use-azureml/automated-machine-learning/dataprep/auto-ml-dataprep.ipynb
hning86/MachineLearningNotebooks
35afd43193a8987a09784b28188fe287304edac6
[ "MIT" ]
1
2019-05-27T06:37:36.000Z
2019-05-27T06:37:36.000Z
how-to-use-azureml/automated-machine-learning/dataprep/auto-ml-dataprep.ipynb
hning86/MachineLearningNotebooks
35afd43193a8987a09784b28188fe287304edac6
[ "MIT" ]
null
null
null
how-to-use-azureml/automated-machine-learning/dataprep/auto-ml-dataprep.ipynb
hning86/MachineLearningNotebooks
35afd43193a8987a09784b28188fe287304edac6
[ "MIT" ]
null
null
null
31.463415
283
0.525736
[ [ [ "Copyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the MIT License.", "_____no_output_____" ], [ "# Automated Machine Learning\n_**Prepare Data using `azureml.dataprep` for Local Execution**_\n\n## Contents\n1. [Introduction](#Introduction)\n1. [Setup](#Setup)\n1. [Data](#Data)\n1. [Train](#Train)\n1. [Results](#Results)\n1. [Test](#Test)", "_____no_output_____" ], [ "## Introduction\nIn this example we showcase how you can use the `azureml.dataprep` SDK to load and prepare data for AutoML. `azureml.dataprep` can also be used standalone; full documentation can be found [here](https://github.com/Microsoft/PendletonDocs).\n\nMake sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n\nIn this notebook you will learn how to:\n1. Define data loading and preparation steps in a `Dataflow` using `azureml.dataprep`.\n2. Pass the `Dataflow` to AutoML for a local run.\n3. Pass the `Dataflow` to AutoML for a remote run.", "_____no_output_____" ], [ "## Setup\n\nCurrently, Data Prep only supports __Ubuntu 16__ and __Red Hat Enterprise Linux 7__. We are working on supporting more linux distros.", "_____no_output_____" ], [ "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments.", "_____no_output_____" ] ], [ [ "import logging\n\nimport pandas as pd\n\nimport azureml.core\nfrom azureml.core.experiment import Experiment\nfrom azureml.core.workspace import Workspace\nimport azureml.dataprep as dprep\nfrom azureml.train.automl import AutoMLConfig", "_____no_output_____" ], [ "ws = Workspace.from_config()\n \n# choose a name for experiment\nexperiment_name = 'automl-dataprep-local'\n# project folder\nproject_folder = './sample_projects/automl-dataprep-local'\n \nexperiment = Experiment(ws, experiment_name)\n \noutput = {}\noutput['SDK version'] = azureml.core.VERSION\noutput['Subscription ID'] = ws.subscription_id\noutput['Workspace Name'] = ws.name\noutput['Resource Group'] = ws.resource_group\noutput['Location'] = ws.location\noutput['Project Directory'] = project_folder\noutput['Experiment Name'] = experiment.name\npd.set_option('display.max_colwidth', -1)\noutputDf = pd.DataFrame(data = output, index = [''])\noutputDf.T", "_____no_output_____" ] ], [ [ "## Data", "_____no_output_____" ] ], [ [ "# You can use `auto_read_file` which intelligently figures out delimiters and datatypes of a file.\n# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n# and convert column types manually.\nexample_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\ndflow = dprep.auto_read_file(example_data).skip(1) # Remove the header row.\ndflow.get_profile()", "_____no_output_____" ], [ "# As `Primary Type` is our y data, we need to drop the values those are null in this column.\ndflow = dflow.drop_nulls('Primary Type')\ndflow.head(5)", "_____no_output_____" ] ], [ [ "### Review the Data Preparation Result\n\nYou can peek the result of a Dataflow at any range using `skip(i)` and `head(j)`. Doing so evaluates only `j` records for all the steps in the Dataflow, which makes it fast even against large datasets.\n\n`Dataflow` objects are immutable and are composed of a list of data preparation steps. A `Dataflow` object can be branched at any point for further usage.", "_____no_output_____" ] ], [ [ "X = dflow.drop_columns(columns=['Primary Type', 'FBI Code'])\ny = dflow.keep_columns(columns=['Primary Type'], validate_column_exists=True)", "_____no_output_____" ] ], [ [ "## Train\n\nThis creates a general AutoML settings object applicable for both local and remote runs.", "_____no_output_____" ] ], [ [ "automl_settings = {\n \"iteration_timeout_minutes\" : 10,\n \"iterations\" : 2,\n \"primary_metric\" : 'AUC_weighted',\n \"preprocess\" : True,\n \"verbosity\" : logging.INFO\n}", "_____no_output_____" ] ], [ [ "### Pass Data with `Dataflow` Objects\n\nThe `Dataflow` objects captured above can be passed to the `submit` method for a local run. AutoML will retrieve the results from the `Dataflow` for model training.", "_____no_output_____" ] ], [ [ "automl_config = AutoMLConfig(task = 'classification',\n debug_log = 'automl_errors.log',\n X = X,\n y = y,\n **automl_settings)", "_____no_output_____" ], [ "local_run = experiment.submit(automl_config, show_output = True)", "_____no_output_____" ], [ "local_run", "_____no_output_____" ] ], [ [ "## Results", "_____no_output_____" ], [ "#### Widget for Monitoring Runs\n\nThe widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n\n**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details.", "_____no_output_____" ] ], [ [ "from azureml.widgets import RunDetails\nRunDetails(local_run).show()", "_____no_output_____" ] ], [ [ "#### Retrieve All Child Runs\nYou can also use SDK methods to fetch all the child runs and see individual metrics that we log.", "_____no_output_____" ] ], [ [ "children = list(local_run.get_children())\nmetricslist = {}\nfor run in children:\n properties = run.get_properties()\n metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n metricslist[int(properties['iteration'])] = metrics\n \nrundata = pd.DataFrame(metricslist).sort_index(1)\nrundata", "_____no_output_____" ] ], [ [ "### Retrieve the Best Model\n\nBelow we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*.", "_____no_output_____" ] ], [ [ "best_run, fitted_model = local_run.get_output()\nprint(best_run)\nprint(fitted_model)", "_____no_output_____" ] ], [ [ "#### Best Model Based on Any Other Metric\nShow the run and the model that has the smallest `log_loss` value:", "_____no_output_____" ] ], [ [ "lookup_metric = \"log_loss\"\nbest_run, fitted_model = local_run.get_output(metric = lookup_metric)\nprint(best_run)\nprint(fitted_model)", "_____no_output_____" ] ], [ [ "#### Model from a Specific Iteration\nShow the run and the model from the first iteration:", "_____no_output_____" ] ], [ [ "iteration = 0\nbest_run, fitted_model = local_run.get_output(iteration = iteration)\nprint(best_run)\nprint(fitted_model)", "_____no_output_____" ] ], [ [ "## Test\n\n#### Load Test Data\nFor the test data, it should have the same preparation step as the train data. Otherwise it might get failed at the preprocessing step.", "_____no_output_____" ] ], [ [ "dflow_test = dprep.auto_read_file(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv').skip(1)\ndflow_test = dflow_test.drop_nulls('Primary Type')", "_____no_output_____" ] ], [ [ "#### Testing Our Best Fitted Model\nWe will use confusion matrix to see how our model works.", "_____no_output_____" ] ], [ [ "from pandas_ml import ConfusionMatrix\n\ny_test = dflow_test.keep_columns(columns=['Primary Type']).to_pandas_dataframe()\nX_test = dflow_test.drop_columns(columns=['Primary Type', 'FBI Code']).to_pandas_dataframe()\n\nypred = fitted_model.predict(X_test)\n\ncm = ConfusionMatrix(y_test['Primary Type'], ypred)\n\nprint(cm)\n\ncm.plot()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af36a27c99d6d1c9fa0f67f83c59869bf071ab2
9,243
ipynb
Jupyter Notebook
jupyter/hello/hello.ipynb
lijun99/altar2-documentation
37cae9d0776cd991fe8062c8676061fb2360248c
[ "FSFAP" ]
8
2019-12-18T22:15:05.000Z
2022-02-13T04:58:21.000Z
jupyter/hello/hello.ipynb
kanglcn/altar2-documentation
c90a4a14ce7366203385fa6133fc93aef68b0c81
[ "FSFAP" ]
null
null
null
jupyter/hello/hello.ipynb
kanglcn/altar2-documentation
c90a4a14ce7366203385fa6133fc93aef68b0c81
[ "FSFAP" ]
6
2020-02-20T20:07:31.000Z
2021-11-25T07:44:27.000Z
33.610909
453
0.601969
[ [ [ "\n# Introduction to AlTar/Pyre applications\n", "_____no_output_____" ], [ "### 1. Introduction\n\nAn AlTar application is based on the [pyre](https://github.com/pyre/pyre) framework. Compared with traditional Python programming, the `pyre` framework provides enhanced features for developing high performance scientific applications, including\n\n- It introduces a new programming model based on configurable components. A configurable component can be an attribute/parameter, or a method/protocol which may have different implementations. The latter will be especially helpful for users to swap between different algorithms/methods for a given procedure at runtime.\n\n- Configurable components also offer users an easy way to configure parameters and settings in an application. To pass parameters through command line (e.g, by `argparse`) and property `setter` is usually a formidable task for applications with a large parameter set. In pyre, this can be done by one `json`-type configuration file.\n\n- An AlTar/pyre application can deploy itself automatically to different computing platforms, such as a standalone computer, GPU workstations, computer clusters or clouds, with a simple change of the `shell` configuration, a configurable component.\n\n- Pyre also integrates high performance scientific libraries such as [GNU Scientific Library](https://www.gnu.org/software/gsl/) (for linear algebra and statistics), and [CUDA](https://developer.nvidia.com/cuda-downloads) (for GPU accelerated computing). It also offers an easy procedure for users to develop their own applications with mixed Python/C/C++/Fortran/CUDA programming, to achieve both high performance and user-friendly interfaces.\n\nIn this tutorial, we will use a `Hello world!` application to demonstrate how an AlTar application, with configurable components, is constructed and runs slightly differently from conventional Python scripts.", "_____no_output_____" ], [ "### 2. The Hello application\n\nWe create below an application to say \"Hello\" to someone (attribute `who`) several times (attribute `times`).", "_____no_output_____" ] ], [ [ "# import the altar module\nimport altar\n\n# create an application based on altar.application\nclass HelloApp(altar.application, family='altar.applications.hello'):\n \"\"\"\n A specialized AlTar application to say hello \n \"\"\"\n \n # user configurable components\n who = altar.properties.str(default='world')\n who.doc = \"the person to say hello to\"\n \n times = altar.properties.int(default=1)\n times.validators = altar.constraints.isPositive()\n times.doc = \"how many times you want to say hello\"\n \n # define methods\n def main(self):\n \"\"\"\n The main method\n \"\"\"\n for i in range(self.times):\n print(f\"Hello {self.who}!\")\n # all done\n return", "_____no_output_____" ] ], [ [ "The `HelloApp` application is derived from the `altar.application` base class in order to inherit various features offered by the pyre framework. It has two attributes, `who` and `times`, which are defined as configurable compnents. A component can be one of the basic Python data types, specified by altar.properties.[int, float, str, list, dict ...], or a user-defined component class.\n\nTo run the HelloApp, we create an instance with a name='hello'. We pass the settings of `who` and `times` by a configuration file [hello.pfg](hello.pfg) (in default, the app instance searches for a `NAME.pfg` configuration file with `NAME` the same as the instance name): \n\n```\n; application instance name\nhello:\n ; components configuration\n who = AlTar users ; no start/end quotes for strings are needed in pfg file\n times = 3\n```\nIn a `pfg` (pyre config) configuration file, indents are used to show the hierarchy of each configurable component. An alternative is to use the dot notation in Python, e.g., \n\n```\n; an alternative way to write configurations\nhello.who = AlTar users\nhello.times = 3\n```\n", "_____no_output_____" ] ], [ [ "# create a HelloApp instance with a name\nhelloapp = HelloApp(name='hello')\n# when it is created, it searches for settings in hello.pfg to initialize configurable components\n\n# run the instance main method\nhelloapp.run()", "Hello AlTar users!\nHello AlTar users!\nHello AlTar users!\n" ] ], [ [ "Once an instance is created(registered), all its components are processed to be regular Python objects which you may access/modify.", "_____no_output_____" ] ], [ [ "print(f\"'{helloapp.who}' is going to be changed\")\nhelloapp.who='pyre users'\nhelloapp.main()", "'AlTar users' is going to be changed\nHello pyre users!\nHello pyre users!\nHello pyre users!\n" ] ], [ [ "You may also modify the [hello.pfg](hello.pfg) file for new configurations and re-run the program. Caveat: for jupyter/ipython, you may need to restart the kernel for new settings to be accepted.", "_____no_output_____" ], [ "### 3. Run HelloApp from command line\n\nAlTar/pyre applications are designed to run as regular shell applications, which offer more options to run with command line arguments. We create a [hello.py](hello.py) script to include the `HelloApp` class definition as well as to define a `__main__` method to create an instance and call `main()`.\n\n```\n# bootstrap\nif __name__ == \"__main__\":\n # build an instance of the default app\n app = HelloApp(name=\"hello\")\n # invoke the main entry point\n status = app.main()\n # share\n raise SystemExit(status)\n```", "_____no_output_____" ] ], [ [ "# run hello app from a shell with cmdLine settings\n!python3 hello.py --who=\"World\" --times=1", "Hello World!\r\n" ] ], [ [ "By default, the app instance searches for the configuration file named `hello.pfg` as its name='hello'. It is also possible to use a different configuration file by a ``--config`` option. \n```\n; hello2.pfg \n; application instance name (still need to be the same as the instance name)\nhello:\n ; configurations\n who = pyre users\n times = 1\n```", "_____no_output_____" ] ], [ [ "# run hello app with a specified configuration file\n!python3 hello.py --config=hello2.pfg", "Hello pyre users!\r\n" ], [ "# run hello app with both a configuration file and cmdLine settings\n# pfg file settings will be overriden by the cmdLine ones\n!python3 hello.py --config=hello2.pfg --times=2", "Hello pyre users!\r\nHello pyre users!\r\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4af374a9309c0d7e5e2f6235351458f6c6b49a96
48,509
ipynb
Jupyter Notebook
examples/speech_audio_corrector/notebooks/test_get_sac_specific_features.ipynb
jonojace/fairseq
ce287a3ca25fb26e65ae4d12614bbf174371eaa9
[ "MIT" ]
null
null
null
examples/speech_audio_corrector/notebooks/test_get_sac_specific_features.ipynb
jonojace/fairseq
ce287a3ca25fb26e65ae4d12614bbf174371eaa9
[ "MIT" ]
null
null
null
examples/speech_audio_corrector/notebooks/test_get_sac_specific_features.ipynb
jonojace/fairseq
ce287a3ca25fb26e65ae4d12614bbf174371eaa9
[ "MIT" ]
null
null
null
32.103905
817
0.507493
[ [ [ "import os\nimport random", "_____no_output_____" ] ], [ [ "# get speech reps for all utts in lj", "_____no_output_____" ] ], [ [ "fp = \"/home/s1785140/fairseq/examples/speech_audio_corrector/lj_speech_quantized.txt\"\n\n# load file contents\nwith open(fp, 'r') as f:\n lines = f.readlines()\n\n# return dict mapping from id to speech rep codes\n\nids2speechreps = {}\n\nfor l in lines:\n utt_id, codes = l.split('|')\n codes = codes.rstrip() # strip trailing newline char\n codes = [int(s) for s in codes.split(' ')] # convert from str of ints to list of ints\n ids2speechreps[utt_id] = codes", "_____no_output_____" ], [ "len(ids2speechreps['LJ004-0001'])", "_____no_output_____" ] ], [ [ "# get all word alignments", "_____no_output_____" ] ], [ [ "import textgrid\nfrom collections import Counter\n\ndef get_word_alignments(\n textgrid_path,\n utt_dur_from_last_word=False,\n ignore_list=['<unk>'],\n):\n \"\"\"\n extract word alignments from textgrid file corresponding to one utterance\n \n utt_dur_from_last_word: whether to set utt_dur to end timestamp of last real wordtype, or from \n the very last alignment in the utterance (likely corresponding to silence)\n \"\"\"\n tg = textgrid.TextGrid.fromFile(textgrid_path)\n words_intervaltier, _phones_intervaltier = tg\n words = []\n counter = Counter()\n\n for word in words_intervaltier: \n if word.mark and word.mark not in ignore_list: # if word.mark is False then it is SILENCE\n counter[word.mark] += 1\n words.append({\n \"wordtype\": word.mark,\n \"utt_id\": textgrid_path.split('/')[-1].split('.')[0],\n \"example_no\": counter[word.mark], # the number of times we have seen this word in this utterance\n \"start\": word.minTime,\n \"end\": word.maxTime,\n })\n \n if utt_dur_from_last_word:\n # use last real word end time as the utt_dur\n utt_dur = words[-1]['end']\n else:\n # at this point word is the last item in words_intervaltier (most likely sil / None)\n utt_dur = word.maxTime\n \n # add utt_dur to all words\n for w in words:\n w[\"utt_dur\"] = utt_dur\n\n return words", "_____no_output_____" ], [ "alignment_dir = \"/home/s1785140/data/ljspeech_MFA_alignments_from_fb\"\n\ncount = 0\n\nMAX_TO_PROCESS = 100\nids = list(ids2speechreps.keys())[:MAX_TO_PROCESS]\n\nids2word_alignments = {}\n\nfor utt_id in ids:\n words_align = get_word_alignments(textgrid_path=f\"{alignment_dir}/{utt_id}.TextGrid\", utt_dur_from_last_word=False)\n ids2word_alignments[utt_id] = words_align\n \n \n # check for words that contain non alphabet chars such as <unk> token\n # print(words_align)\n \n for w in words_align:\n if '<' in w['wordtype']:\n # print(w, words_align)\n if w['wordtype'] != '<unk>':\n print(\"not <unk>:\", w['wordtype'])\n count += 1\n \n if not w['wordtype']:\n print('word is FALSE', w, words_align)\n\nprint(\"count is\", count)", "count is 0\n" ], [ "len(ids2word_alignments)", "_____no_output_____" ] ], [ [ "# create wordtype to speech aligned feats data structure", "_____no_output_____" ] ], [ [ "def get_wordlevel_reprs(speechreps, word_align):\n \"\"\"\n extract subsequence of 'repr' that corresponds to a particular word\n function expects input to be of dimension 2: (timesteps, hidden_size)\n \"\"\"\n start_fraction = word_align['start'] / word_align['utt_dur']\n end_fraction = word_align['end'] / word_align['utt_dur']\n timesteps = len(speechreps)\n start_idx = round(start_fraction * timesteps)\n end_idx = round(end_fraction * timesteps)\n return speechreps[start_idx:end_idx]\n\nword2speechreps = {}\n\nfor utt_id in ids:\n speech_reps = ids2speechreps[utt_id]\n word_aligns = ids2word_alignments[utt_id]\n \n for word_align in word_aligns:\n word_align['speech_reps'] = get_wordlevel_reprs(speech_reps, word_align)\n \n # following info to debug whether alignments are consistent in len\n # word_align['speech_reps_len'] = len(word_align['speech_reps'])\n # word_align['speech_reps_len_dur_ratio'] = word_align['speech_reps_len'] / (word_align['end']-word_align['start'])\n \n wordtype = word_align['wordtype']\n example_no = word_align['example_no']\n unique_id = utt_id + '|' + str(example_no)\n \n if wordtype not in word2speechreps:\n word2speechreps[wordtype] = {}\n word2speechreps[wordtype][unique_id] = word_align['speech_reps']", "_____no_output_____" ] ], [ [ "# implement fn to get position of each word in the text seq", "_____no_output_____" ] ], [ [ "def get_mfa_text(word_align):\n return \" \".join(w['wordtype'] for w in word_align)\n\ndef get_mfa_text_from_utt_id(utt_id):\n word_align = ids2word_alignments[utt_id]\n return get_mfa_text(word_align)", "_____no_output_____" ], [ "tg = textgrid.TextGrid.fromFile(f\"{alignment_dir}/{utt_id}.TextGrid\")\nwords_intervaltier, _phones_intervaltier = tg\nwords_intervaltier", "_____no_output_____" ], [ "mfa_text = get_mfa_text(word_aligns)", "_____no_output_____" ], [ "mfa_text", "_____no_output_____" ], [ "def get_word_pos_2(text, whitespace_tok=\"_\", boundary_same_pos=True, with_eos=True, boundary_pos=0):\n \"\"\"\n return words and their word pos\n \n and also word pos of each grapheme in the seq\n \"\"\"\n graphemes = text.split(' ')\n \n # double check that we are dealing with a seq output by bpe tokenizer\n assert graphemes[0] == whitespace_tok \n \n word_count = 0\n word_and_word_pos = []\n word_pos_of_graphemes = []\n current_word = \"\"\n \n for i, c in enumerate(graphemes):\n # reached the last char of the utt\n if i == len(graphemes) - 1: \n current_word += c # add last char\n word_and_word_pos.append((current_word, word_count)) # add last word\n word_pos_of_graphemes.append(word_count)\n \n # whitespace\n elif c == whitespace_tok: \n if current_word: # at a whitespace token AFTER processing at least one word\n word_and_word_pos.append((current_word, word_count))\n current_word = \"\"\n if boundary_same_pos:\n word_pos_of_graphemes.append(boundary_pos)\n else:\n word_count += 1 # because we count each whitespace_tok as a new word position\n word_pos_of_graphemes.append(word_count)\n \n # processing a grapheme in a word\n else: \n if graphemes[i-1] == whitespace_tok:\n word_count += 1 # only increment word position if we are at the beginning of a new word, not within it\n word_pos_of_graphemes.append(word_count)\n current_word += c\n \n if with_eos:\n word_pos_of_graphemes.append(word_count+1) \n \n return word_and_word_pos, word_pos_of_graphemes\n \nwords = [\"how\" , \"are\", \"you\"]\ntxt = \"_\"+ \"_\".join(words)\ntxt = \" \".join([c for c in txt])\nprint(txt)\nget_word_pos_2(txt, whitespace_tok=\"_\", boundary_same_pos=True, with_eos=True, boundary_pos=0)", "_ h o w _ a r e _ y o u\n" ], [ "# create some input text for testing\nwords = [\"how\" , \"are\", \"you\"]\ntxt = \"_\"+ \"_\".join(words)\ntxt = \" \".join([c for c in txt])\ntxt", "_____no_output_____" ], [ "get_word_pos_2(txt, boundary_same_pos=True, with_eos=False)", "_____no_output_____" ], [ "get_word_pos_2(txt, boundary_same_pos=True, with_eos=True)", "_____no_output_____" ], [ "get_word_pos_2(txt, boundary_same_pos=False, with_eos=False)", "_____no_output_____" ], [ "get_word_pos_2(txt, boundary_same_pos=False, with_eos=True)", "_____no_output_____" ] ], [ [ "# implement getting speech reps for words in an utterance \n\nAlso add ability for regularisation:\n * shuffling word examples\n * removing duplicates", "_____no_output_____" ] ], [ [ "def run_len_encoding(seq):\n \"\"\"encode a seq using run length encoding\n \n e.g. [1,2,2,2,2,2,3,3,3,3,3] -> [(1, 1), (2, 5), (3, 5)]\n \"\"\"\n encoding = []\n prev_char = ''\n count = 1\n\n if not seq: return []\n\n for char in seq:\n # If the prev and current characters\n # don't match...\n if char != prev_char:\n # ...then add the count and character\n # to our encoding\n if prev_char:\n encoding.append((prev_char, count))\n count = 1\n prev_char = char\n else:\n # Or increment our counter\n # if the characters do match\n count += 1\n else:\n # Finish off the encoding\n encoding.append((prev_char, count))\n return encoding\n \n\nspeechreps = [1,2,2,2,2,2,3,3,3,3,3]\nrun_len_encoding(speechreps)", "_____no_output_____" ], [ "def remove_dups_random(rle, min_count=1):\n \"\"\"return a rle where each char's count is reduced a random amount\"\"\"\n compressed_rle = []\n for char, count in rle:\n new_count = random.randint(min_count, count)\n compressed_rle.append((char, new_count))\n return compressed_rle\n\nspeechreps = [1,2,2,2,2,2,3,3,3,3,3]\nrle = run_len_encoding(speechreps)\nremove_dups_random(rle)", "_____no_output_____" ], [ "def expand_rle(rle):\n \"\"\"expand an RLE back to a list\"\"\"\n expanded_rle = []\n for char, count in rle:\n expanded_rle.extend(count*[char])\n return expanded_rle\n\nspeechreps = [1,2,2,2,2,2,3,3,3,3,3]\nrle = run_len_encoding(speechreps)\nprint(\"compressed\", rle)\nexpand_rle(rle)", "compressed [(1, 1), (2, 5), (3, 5)]\n" ], [ "def collapse_dups(speechreps, remove_dup_prob, remove_dup_rand_num):\n \"\"\"take a list of elements and remove duplicates\n \n optionally do not remove all duplicates but remove a random amount\n \n TODO add option of sometimes ADDING codes? to make neural model more robust to duration changes\n \"\"\"\n if remove_dup_prob > 0.0 and random.random() > (1.0 - remove_dup_prob):\n rle = run_len_encoding(speechreps)\n if remove_dup_rand_num:\n compressed_rle = remove_dups_random(rle)\n else:\n # remove all duplicates for each code (i.e. set count to 0)\n compressed_rle = [(char, 1) for char, count in rle]\n speechreps = expand_rle(compressed_rle)\n return speechreps\n\nspeechreps = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3]\nprint(\"original\", speechreps)\nfor _ in range(10):\n collapse_dups(speechreps, remove_dup_prob=0.5, remove_dup_rand_num=False)\n ", "original [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]\n" ], [ "def dropout_timesteps(seq, p):\n \"\"\"randomly dropout timesteps seq\"\"\"\n if p > 0.0 :\n new_seq = []\n for c in seq:\n if random.random() < (1.0 - p):\n new_seq.append(c)\n else:\n pass\n return new_seq\n else:\n return seq\n ", "_____no_output_____" ], [ "def get_speechreps_for_word(word, utt_id, count_of_word, word2speechreps, randomise, \n remove_dup_prob, remove_dup_rand_num, dropout_p):\n \"\"\"return the speechreps for a wordtype\n \n optionally remove duplicates\"\"\"\n unique_id = f\"{utt_id}|{count_of_word}\"\n \n # get speechreps corresponding to word\n if not randomise and unique_id in word2speechreps[word]:\n word_reps = word2speechreps[word][unique_id]\n else:\n random_unique_id = random.sample(word2speechreps[word].keys(), k=1)[0]\n word_reps = word2speechreps[word][random_unique_id]\n \n # optionally collapse duplicate codes\n word_reps = collapse_dups(word_reps, remove_dup_prob=remove_dup_prob, remove_dup_rand_num=remove_dup_rand_num)\n \n # optionally randomly dropout codes\n word_reps = dropout_timesteps(word_reps, p=dropout_p)\n \n return word_reps\n\nword = \"the\"\nutt_id = \"LJ033-0206\"\ncount_of_word = 1\n# unique_id = \"LJ033-0206\" + \"|\" + \"1\"\nget_speechreps_for_word(word, utt_id, count_of_word, word2speechreps, randomise=False, \n remove_dup_prob=0.0, remove_dup_rand_num=False, dropout_p=0.0)", "_____no_output_____" ], [ "def get_speechreps_for_utt(word_and_word_pos, utt_id, word2speechreps, \n randomise_examples=False, remove_dup_prob=0.0, \n remove_dup_rand_num=False, dropout_p=0.0):\n \"\"\"\n get speech reps for all the words in an utterance\n \n optionally:\n - randomly retrieve speech reps for different examples of the word\n - remove duplicate codes\n - dropout codes\n \"\"\"\n speechreps, speechreps_word_pos, word_counter = [], [], Counter()\n \n for word, word_pos in word_and_word_pos:\n word_counter[word] += 1\n word_speechreps = get_speechreps_for_word(word, utt_id, word_counter[word], word2speechreps, randomise=randomise_examples, \n remove_dup_prob=remove_dup_prob, remove_dup_rand_num=remove_dup_rand_num, \n dropout_p=dropout_p)\n speechreps.extend(word_speechreps)\n speechreps_word_pos.extend(len(word_speechreps)*[word_pos])\n \n # TODO add interword separator tokens \n # TODO <sep> or \"_\" according to tgt_dict\n \n return speechreps, speechreps_word_pos\n \n \nutt_id = \"LJ033-0206\"\nmfa_text = get_mfa_text_from_utt_id(utt_id)\nprint(mfa_text)\nmfa_text = mfa_text.split(\" \")\nmfa_text = \"_\"+ \"_\".join(mfa_text)\nmfa_text = \" \".join([c for c in mfa_text])\nprint(mfa_text)\nword_and_word_pos, word_pos_of_graphemes = get_word_pos_2(mfa_text, boundary_same_pos=True, with_eos=False)\nprint(word_and_word_pos)\nprint(word_pos_of_graphemes)\nspeechreps, speechreps_word_pos = get_speechreps_for_utt(word_and_word_pos, utt_id, word2speechreps, \n randomise_examples=False, remove_dup_prob=1.0, remove_dup_rand_num=True)\n\nprint(speechreps_word_pos)", "confirmed that the rifle could have picked up fibers from the blanket and transferred them to the paper bag\n_ c o n f i r m e d _ t h a t _ t h e _ r i f l e _ c o u l d _ h a v e _ p i c k e d _ u p _ f i b e r s _ f r o m _ t h e _ b l a n k e t _ a n d _ t r a n s f e r r e d _ t h e m _ t o _ t h e _ p a p e r _ b a g\n[('confirmed', 1), ('that', 2), ('the', 3), ('rifle', 4), ('could', 5), ('have', 6), ('picked', 7), ('up', 8), ('fibers', 9), ('from', 10), ('the', 11), ('blanket', 12), ('and', 13), ('transferred', 14), ('them', 15), ('to', 16), ('the', 17), ('paper', 18), ('bag', 19)]\n[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 2, 2, 0, 3, 3, 3, 0, 4, 4, 4, 4, 4, 0, 5, 5, 5, 5, 5, 0, 6, 6, 6, 6, 0, 7, 7, 7, 7, 7, 7, 0, 8, 8, 0, 9, 9, 9, 9, 9, 9, 0, 10, 10, 10, 10, 0, 11, 11, 11, 0, 12, 12, 12, 12, 12, 12, 12, 0, 13, 13, 13, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 15, 15, 15, 15, 0, 16, 16, 0, 17, 17, 17, 0, 18, 18, 18, 18, 18, 0, 19, 19, 19]\n[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19]\n" ] ], [ [ "# helpers for dictionary encoding of speech reps", "_____no_output_____" ] ], [ [ "def prep_speechreps_for_dict_encoding(speechreps):\n \"\"\"\n take hubert codes (int from 0 to K-1 where K is number of k-means clusters)\n return a string version suitable for dictionary encoding\n \"\"\"\n new_speechreps = []\n for x in speechreps:\n new_speechreps.append(f\"HUB{x}\")\n return \" \".join(new_speechreps)\n \nprep_speechreps_for_dict_encoding([1,2,3,2,3,2,2,2,2,1,2,3])", "_____no_output_____" ] ], [ [ "# helpers for generating word masks", "_____no_output_____" ] ], [ [ "def two_random_partitions(indices, p=0.5):\n \"\"\"given a list of indices (indicating word positions)\n partition into two sets\n p is probability of entering set1\n \"\"\"\n set1, set2 = set(), set()\n for idx in indices:\n if random.random() > (1.0 - p):\n set1.add(idx)\n else:\n set2.add(idx)\n return set1, set2\n\ntwo_random_partitions(list(range(1,11)))", "_____no_output_____" ], [ "def get_word_pos(graphemes, padding_idx, bpe_whitespace_tok=\"▁\", boundary_same_pos=True,\n append_eos=False, eos_symbol = \"</s>\", boundary_start_pos=None):\n \"\"\"\n for some space delimited sequence of symbols (e.g. text)\n\n return words and their word pos\n\n and also word pos of each grapheme in the seq (a list of the same length,\n of ints representing the words that each symbol / whitespace corresponds to)\n \n by default the boundary start position is initiated as padding_idx + 1\n and then word counts start from that value\n\n args:\n text: str of space delimited graphemes in the utterance ('_' denotes whitespace in the original utterance)\n e.g. \"_ h o w _ a r e _ y o u\" this is the format returned by sentence piece tokeniser\n\n e.g.\n _ h o w _ a r e _ y o u\n padding_idx == 1\n boundary_start_pos == 2\n boundary_same_pos == True\n \n before padding:\n [('how', 3), ('are', 4), ('you', 5)]\n [2, 3, 3, 3, 2, 4, 4, 4, 2, 5, 5, 5, 6]\n after concat with speechreps and padding (not performed in this fn, performed in SAC dataset collater):\n [2, 3, 3, 3, 2, 4, 4, 4, 2, 5, 5, 5, 6, <speechreps>, 1, 1, 1, ...]\n \n _ h o w _ a r e _ y o u\n padding_idx == 1\n boundary_start_pos == 2\n boundary_same_pos == False\n \n before padding:\n [('how', 3), ('are', 5), ('you', 7)]\n [2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8]\n after concat with speechreps and padding (not performed in this fn, performed in SAC dataset collater):\n [2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8, <speechreps>, 1, 1, 1, ...]\n \"\"\"\n # double check that we are dealing with a seq output by bpe tokenizer\n assert graphemes[0] == bpe_whitespace_tok, f\"graphemes == {graphemes}\"\n \n if boundary_start_pos is None:\n boundary_start_pos = padding_idx + 1\n\n if boundary_same_pos:\n word_count = boundary_start_pos\n else:\n word_count = padding_idx\n \n word_and_word_pos = []\n word_pos_of_graphemes = []\n current_word = \"\"\n\n for i, c in enumerate(graphemes):\n # reached the last symbol of the utt\n if c == eos_symbol:\n word_and_word_pos.append((current_word, word_count)) # add last word\n word_pos_of_graphemes.append(word_count+1)\n\n # whitespace\n elif c == bpe_whitespace_tok:\n if current_word: # at a whitespace token AFTER processing at least one word\n word_and_word_pos.append((current_word, word_count))\n current_word = \"\"\n if boundary_same_pos:\n word_pos_of_graphemes.append(boundary_start_pos)\n else:\n word_count += 1 # because we count each whitespace_tok as a new word position\n word_pos_of_graphemes.append(word_count)\n\n # processing a grapheme in a word\n else:\n if graphemes[i - 1] == bpe_whitespace_tok:\n word_count += 1 # only increment word position if we are at the beginning of a new word, not within it\n word_pos_of_graphemes.append(word_count)\n current_word += c\n\n if append_eos:\n word_pos_of_graphemes.append(word_count + 1)\n\n return word_and_word_pos, word_pos_of_graphemes", "_____no_output_____" ], [ "graphemes = '▁ h o w ▁ a r e ▁ y o u </s>'.split(' ')\nprint(graphemes)\n\npadding_idx = 1\n\nget_word_pos(graphemes, padding_idx=padding_idx, bpe_whitespace_tok=\"▁\", boundary_same_pos=True,\n append_eos=False, eos_symbol = \"</s>\")", "['▁', 'h', 'o', 'w', '▁', 'a', 'r', 'e', '▁', 'y', 'o', 'u', '</s>']\n" ], [ "get_word_pos(graphemes, padding_idx=padding_idx, bpe_whitespace_tok=\"▁\", boundary_same_pos=False,\n append_eos=False, eos_symbol = \"</s>\")", "_____no_output_____" ], [ "print(\"should be [2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8]\")", "should be [2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8]\n" ] ], [ [ "# adapt sinusoidal positional embedding to take in positions as an argument rather than just build then one per timestep", "_____no_output_____" ] ], [ [ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\nfrom typing import Any, Optional\n\nimport torch\nimport torch.onnx.operators\nfrom fairseq import utils\nfrom torch import Tensor, nn\n\n\nclass SinusoidalPositionalEmbedding(nn.Module):\n \"\"\"This module produces sinusoidal positional embeddings of any length.\n\n Padding symbols are ignored.\n \"\"\"\n\n def __init__(self, embedding_dim, padding_idx, init_size=1024):\n super().__init__()\n self.embedding_dim = embedding_dim\n self.padding_idx = padding_idx if padding_idx is not None else 0\n self.weights = SinusoidalPositionalEmbedding.get_embedding(\n init_size, embedding_dim, padding_idx\n )\n self.onnx_trace = False\n self.register_buffer(\"_float_tensor\", torch.FloatTensor(1))\n self.max_positions = int(1e5)\n\n def prepare_for_onnx_export_(self):\n self.onnx_trace = True\n\n @staticmethod\n def get_embedding(\n num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None\n ):\n \"\"\"Build sinusoidal embeddings.\n\n This matches the implementation in tensor2tensor, but differs slightly\n from the description in Section 3.5 of \"Attention Is All You Need\".\n \"\"\"\n half_dim = embedding_dim // 2\n emb = math.log(10000) / (half_dim - 1)\n emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)\n emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(\n 1\n ) * emb.unsqueeze(0)\n emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(\n num_embeddings, -1\n )\n if embedding_dim % 2 == 1:\n # zero pad\n emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)\n if padding_idx is not None:\n emb[padding_idx, :] = 0\n return emb\n\n def forward(\n self,\n input,\n incremental_state: Optional[Any] = None,\n timestep: Optional[Tensor] = None,\n positions: Optional[Any] = None,\n ):\n \"\"\"Input is expected to be of size [bsz x seqlen].\"\"\"\n bspair = torch.onnx.operators.shape_as_tensor(input)\n bsz, seq_len = bspair[0], bspair[1]\n max_pos = self.padding_idx + 1 + seq_len\n if self.weights is None or max_pos > self.weights.size(0):\n # recompute/expand embeddings if needed\n self.weights = SinusoidalPositionalEmbedding.get_embedding(\n max_pos, self.embedding_dim, self.padding_idx\n )\n self.weights = self.weights.to(self._float_tensor)\n\n if incremental_state is not None:\n # positions is the same for every token when decoding a single step\n pos = timestep.view(-1)[0] + 1 if timestep is not None else seq_len\n if self.onnx_trace:\n return (\n self.weights.index_select(index=self.padding_idx + pos, dim=0)\n .unsqueeze(1)\n .repeat(bsz, 1, 1)\n )\n return self.weights[self.padding_idx + pos, :].expand(bsz, 1, -1)\n\n if positions is None:\n positions = utils.make_positions(\n input, self.padding_idx, onnx_trace=self.onnx_trace\n )\n\n if self.onnx_trace:\n flat_embeddings = self.weights.detach().index_select(0, positions.view(-1))\n embedding_shape = torch.cat(\n (bsz.view(1), seq_len.view(1), torch.tensor([-1], dtype=torch.long))\n )\n embeddings = torch.onnx.operators.reshape_from_tensor_shape(\n flat_embeddings, embedding_shape\n )\n return embeddings\n return (\n self.weights.index_select(0, positions.view(-1))\n .view(bsz, seq_len, -1)\n .detach()\n )\n", "_____no_output_____" ], [ "padding_idx = 1\nmax_source_positions = 1024\nnum_embeddings = max_source_positions\npos_emb = SinusoidalPositionalEmbedding(embedding_dim=128, padding_idx=padding_idx, init_size=num_embeddings + padding_idx + 1,)", "_____no_output_____" ], [ "positions = torch.Tensor([2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8, 1, 1, 1]).long()", "_____no_output_____" ], [ "positions.size()", "_____no_output_____" ], [ "# introduce batch dim\npositions = positions.unsqueeze(0)", "_____no_output_____" ], [ "positions.size()", "_____no_output_____" ], [ "positions.view(-1)", "_____no_output_____" ], [ "rv = pos_emb(positions, positions=positions)", "tensor([[2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8, 1, 1, 1]])\n" ], [ "rv", "_____no_output_____" ], [ "rv.size()", "_____no_output_____" ], [ "rv[0,:,0]", "_____no_output_____" ], [ "rv[0,:,1]", "_____no_output_____" ], [ "def make_positions(tensor, padding_idx: int, onnx_trace: bool = False):\n \"\"\"Replace non-padding symbols with their position numbers.\n\n Position numbers begin at padding_idx+1. Padding symbols are ignored.\n \"\"\"\n # The series of casts and type-conversions here are carefully\n # balanced to both work with ONNX export and XLA. In particular XLA\n # prefers ints, cumsum defaults to output longs, and ONNX doesn't know\n # how to handle the dtype kwarg in cumsum.\n mask = tensor.ne(padding_idx).int()\n return (torch.cumsum(mask, dim=1).type_as(mask) * mask).long() + padding_idx", "_____no_output_____" ], [ "make_positions(positions, 1)", "_____no_output_____" ], [ "positions = torch.Tensor([2,2,2,2,2,2,2,2,2]).long()\npositions = positions.unsqueeze(0)\npos_emb(positions, positions=positions)[0,:,:]", "tensor([[2, 2, 2, 2, 2, 2, 2, 2, 2]])\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "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", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af37bc8def4b3a647fa1b2a2fbb35fade9a950f
23,182
ipynb
Jupyter Notebook
_notebooks/2020-12-19-Hacking_fasterRcnn.ipynb
akashprakas/My-blog
0611c35b1f117cc21b8640376eb1d185b862639f
[ "Apache-2.0" ]
1
2021-11-11T14:29:17.000Z
2021-11-11T14:29:17.000Z
_notebooks/2020-12-19-Hacking_fasterRcnn.ipynb
akashprakas/My-blog
0611c35b1f117cc21b8640376eb1d185b862639f
[ "Apache-2.0" ]
4
2021-05-20T14:09:35.000Z
2021-09-28T01:07:39.000Z
_notebooks/2020-12-19-Hacking_fasterRcnn.ipynb
akashprakas/My-blog
0611c35b1f117cc21b8640376eb1d185b862639f
[ "Apache-2.0" ]
null
null
null
32.975818
628
0.597403
[ [ [ "# Hacking Into FasterRcnn in Pytorch\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [jupyter]\n- image: images/chart-preview.png", "_____no_output_____" ], [ "# Brief Intro\nIn the post I will show how to tweak some of the internals of FaterRcnn in Pytorch. I am assuming the reader is someone who already have trained an object detection model using pytorch. If not there is and excellent tutorial in [pytorch website](https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html).", "_____no_output_____" ], [ "## Small Insight into the model\n\nBasically Faster Rcnn is a two stage detector\n1. The first stage is the Region proposal network which is resposible for knowing the objectness and corresponding bounding boxes. So essentially the RegionProposalNetwork will give the proposals of whether and object is there or not\n2. These proposals will be used by the RoIHeads which outputs the detections .\n * Inside the RoIHeads roi align is done\n * There will be a box head and box predictor\n * The losses for the predictions\n3. In this post i will try to show how we can add custom parts to the torchvision FasterRcnn", "_____no_output_____" ] ], [ [ "#collapse-hide\nimport torch\nimport torchvision\nfrom torchvision.models.detection import FasterRCNN\nfrom torchvision.models.detection.rpn import AnchorGenerator\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nprint(f'torch version {torch.__version__}')\nprint(f'torchvision version {torchvision.__version__}')", "torch version 1.7.0\ntorchvision version 0.8.1\n" ] ], [ [ "# Custom Backone\n1. The backbone can be without FeaturePyramidNetwork\n2. With FeaturePyramidNetwork", "_____no_output_____" ], [ "## Custom Backbone without FPN\nThis is pretty well written in the pytorch tutorials section, i will add some comments to it additionally", "_____no_output_____" ] ], [ [ "backbone = torchvision.models.mobilenet_v2(pretrained=True).features\n#we need to specify an outchannel of this backone specifically because this outchannel will be\n#used as an inchannel for the RPNHEAD which is producing the out of RegionProposalNetwork\n#we can know the number of outchannels by looking into the backbone \"backbone??\"\nbackbone.out_channels = 1280\n#by default the achor generator FasterRcnn assign will be for a FPN backone, so\n#we need to specify a different anchor generator\nanchor_generator = AnchorGenerator(sizes=((128, 256, 512),),\n aspect_ratios=((0.5, 1.0, 2.0),))\n#here at each position in the grid there will be 3x3=9 anchors\n#and if our backbone is not FPN then the forward method will assign the name '0' to feature map\n#so we need to specify '0 as feature map name'\nroi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],\n output_size=9,\n sampling_ratio=2)\n#the output size is the output shape of the roi pooled features which will be used by the box head\nmodel = FasterRCNN(backbone,num_classes=2,rpn_anchor_generator=anchor_generator)", "_____no_output_____" ], [ "model.eval()\nx = [torch.rand(3, 300, 400), torch.rand(3, 500, 600)]\npredictions = model(x)", "_____no_output_____" ] ], [ [ "## Custom Backbone with FPN", "_____no_output_____" ], [ "The Resnet50Fpn available in torchvision", "_____no_output_____" ] ], [ [ "# load a model pre-trained pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\n\n# replace the classifier with a new one, that has\n# num_classes which is user-defined\nnum_classes = 2 # 1 class (person) + background\n# get number of input features for the classifier\nin_features = model.roi_heads.box_predictor.cls_score.in_features\n# replace the pre-trained head with a new one\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)", "_____no_output_____" ], [ "model.eval()\nx = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]\npredictions = model(x)", "_____no_output_____" ] ], [ [ "### Adding a different resenet backbone\n1. Just change to a different resenet\n1. Shows how we should change roi_pooler and anchor_generator along with the backbone changes if we are not using all the layers from FPN", "_____no_output_____" ], [ "### Using all layers from FPN", "_____no_output_____" ] ], [ [ "#hte returned layers are layer1,layer2,layer3,layer4 in returned_layers\nbackbone = torchvision.models.detection.backbone_utils.resnet_fpn_backbone('resnet101',pretrained=True)\nmodel = FasterRCNN(backbone,num_classes=2) ", "_____no_output_____" ], [ "model.eval()\nx = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]\npredictions = model(x)", "_____no_output_____" ] ], [ [ "### Using not all layers from FPN", "_____no_output_____" ], [ "The size of the last fature map in a Resnet50.Later i will show the sizes of the feature maps we use when we use FPN.", "_____no_output_____" ] ], [ [ "#collapse-hide\n#just to show what will be out of of a normal resnet without fpn\nres = torchvision.models.resnet50()\npure = nn.Sequential(*list(res.children())[:-2])\ntemp = torch.rand(1,3,400,400)\npure(temp).shape", "_____no_output_____" ] ], [ [ "The required layers can be obtained by specifying the returned layers parameters.Also the resnet backbone of different depth can be used.", "_____no_output_____" ] ], [ [ "#the returned layers are layer1,layer2,layer3,layer4 in returned_layers\nbackbone = torchvision.models.detection.backbone_utils.resnet_fpn_backbone('resnet101',pretrained=True,\n returned_layers=[2,3,4])", "_____no_output_____" ] ], [ [ "Here we are using feature maps of the following shapes.", "_____no_output_____" ] ], [ [ "#collapse-hide\nout = backbone(temp)\nfor i in out.keys():\n print(i,' ',out[i].shape)", "0 torch.Size([1, 256, 50, 50])\n1 torch.Size([1, 256, 25, 25])\n2 torch.Size([1, 256, 13, 13])\npool torch.Size([1, 256, 7, 7])\n" ], [ "#from the above we can see that the feature are feat maps should be 0,1,2,pool\n#where pool comes from the default extra block\nroi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0','1','2','pool'],\n output_size=7,\n sampling_ratio=2)", "_____no_output_____" ] ], [ [ "So essentially what we did was we selected the last three layers in FPN by specifying them in the returned layers, by default, the backbone will add a pool layer on top of the last layer. So we are left with four layers. Now the RoIAlign need to be done in these four layers. If we dnt specify the RoIAlign it will use the by default assume we have used all layers from FPN in torchvision. So we need to specifically give the feauture maps that we used. The usage of feature maps can be our application specific, some time you might need to detect small objects sometimes the object of interest will be large objects only.", "_____no_output_____" ] ], [ [ "#we will need to give anchor_generator because the deafault anchor generator assumes we use all layers in fpn \n#since we have four layers in fpn here we need to specify 4 anchors\nanchor_sizes = ((32), (64), (128),(256) ) \naspect_ratios = ((0.5,1.0, 1.5,2.0,)) * len(anchor_sizes)\nanchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios)", "_____no_output_____" ] ], [ [ "Since we have four layers in our FPN we need to specify the anchors. So here each feature map will have 4 anchors at each position.So the first feature map will have anchor size 32 and four of them will be there at each position in the feature map of aspect_ratios (0.5,1.0, 1.5,2.0). Now we can pass these to the FasterRCNN class", "_____no_output_____" ] ], [ [ "model = FasterRCNN(backbone,num_classes=2,rpn_anchor_generator=anchor_generator,box_roi_pool=roi_pooler)", "_____no_output_____" ], [ "model.eval()\nx = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]\npredictions = model(x)", "_____no_output_____" ] ], [ [ "# Custom Predictor\nThe predictor is what that outputs the classes and the corresponding bboxes . By default these have two layers one for class and one for bboxes,but we can add more before it if we want to,so if you have a ton of data this might come handy,(remember there is already a box head before the predictor head, so you might not need this)", "_____no_output_____" ] ], [ [ "class Custom_predictor(nn.Module):\n def __init__(self,in_channels,num_classes):\n super(Custom_predictor,self).__init__()\n self.additional_layer = nn.Linear(in_channels,in_channels) #this is the additional layer \n self.cls_score = nn.Linear(in_channels, num_classes)\n self.bbox_pred = nn.Linear(in_channels, num_classes * 4)\n \n \n def forward(self,x):\n if x.dim() == 4:\n assert list(x.shape[2:]) == [1, 1]\n x = x.flatten(start_dim=1)\n x = self.additional_layer(x)\n scores = self.cls_score(x)\n bbox_deltas = self.bbox_pred(x)\n return scores, bbox_deltas", "_____no_output_____" ], [ "model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\n#we need the out channels of the box head to pass tpp custom predictor\nin_features = model.roi_heads.box_head.fc7.out_features\n#now we can add the custom predictor to the model\nnum_classes =2\nmodel.roi_heads.box_predictor = Custom_predictor(in_features,num_classes)", "_____no_output_____" ], [ "model.eval()\nx = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]\npredictions = model(x)", "_____no_output_____" ] ], [ [ "# Custom BoxHead\nThe ouptuts of the roi_align are first passed through the box head before they are passed to the Predictor, there are two linear layers and we can customize them as we want, be careful with the dimensions since they can break the pipeline", "_____no_output_____" ] ], [ [ "model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)", "_____no_output_____" ], [ "class CustomHead(nn.Module):\n def __init__(self,in_channels,roi_outshape,representation_size):\n super(CustomHead,self).__init__()\n \n self.conv = nn.Conv2d(in_channels,in_channels,kernel_size=3,padding=1)#this is teh additional layer adde\n #we will be sending a flattened layer, the size will eb in_channels*w*h, here roi_outshape represents it\n \n self.fc6 = nn.Linear(in_channels*roi_outshape**2, representation_size)\n self.fc7 = nn.Linear(representation_size, representation_size)\n \n def forward(self,x):\n # breakpoint()\n \n x = self.conv(x)\n x = x.flatten(start_dim=1)\n import torch.nn.functional as F\n x = F.relu(self.fc6(x))\n x = F.relu(self.fc7(x))\n return x", "_____no_output_____" ] ], [ [ "1. We need in_channels and representation size, remember the output of this is the input of box_predictor, so we can get the representation size of box_head from the input of box_predictor.\n2. The in_channels can be got from the backbone out channels.\n3. After the flattening the width and height also need to be considered which we wil get from roi_pool output.", "_____no_output_____" ] ], [ [ "in_channels = model.backbone.out_channels \nroi_outshape = model.roi_heads.box_roi_pool.output_size[0]\nrepresentation_size=model.roi_heads.box_predictor.cls_score.in_features", "_____no_output_____" ], [ "model.roi_heads.box_head = CustomHead(in_channels,roi_outshape,representation_size)", "_____no_output_____" ], [ "num_classes=2\nmodel.roi_heads.box_predictor = FastRCNNPredictor(representation_size, num_classes)", "_____no_output_____" ], [ "model.eval()\nx = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]\npredictions = model(x)", "_____no_output_____" ] ], [ [ "# CustomLoss Function", "_____no_output_____" ], [ "This is the modification for loss of FasterRcnn Predictor.\n1. You can modify the loss by defining the fastrcnn_loss and making chages where you want.\n2. Then pass as say model.roi_heads.fastrcnn_loss = Custom_loss\n3. Usually we replace the F.crossentropy loss by say Focal loss or label smoothing loss", "_____no_output_____" ] ], [ [ "import torchvision.models.detection._utils as det_utils\nimport torch.nn.functional as F", "_____no_output_____" ] ], [ [ "The below loss function is taken from [Aman Aroras blog](https://amaarora.github.io/2020/07/18/label-smoothing.html).", "_____no_output_____" ] ], [ [ "\n# Helper functions from fastai\ndef reduce_loss(loss, reduction='mean'):\n return loss.mean() if reduction=='mean' else loss.sum() if reduction=='sum' else loss\n\n\n# Implementation from fastai https://github.com/fastai/fastai2/blob/master/fastai2/layers.py#L338\nclass LabelSmoothingCrossEntropy(nn.Module):\n def __init__(self, ε:float=0.1, reduction='mean'):\n super().__init__()\n self.ε,self.reduction = ε,reduction\n \n def forward(self, output, target):\n # number of classes\n c = output.size()[-1]\n log_preds = F.log_softmax(output, dim=-1)\n loss = reduce_loss(-log_preds.sum(dim=-1), self.reduction)\n nll = F.nll_loss(log_preds, target, reduction=self.reduction)\n # (1-ε)* H(q,p) + ε*H(u,p)\n return (1-self.ε)*nll + self.ε*(loss/c) ", "_____no_output_____" ], [ "custom_loss = LabelSmoothingCrossEntropy()\n#torchvision.models.detection.roi_heads.fastrcnn_loss??", "_____no_output_____" ], [ "def custom_fastrcnn_loss(class_logits, box_regression, labels, regression_targets):\n # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[Tensor, Tensor]\n \"\"\"\n Computes the loss for Faster R-CNN.\n\n Arguments:\n class_logits (Tensor)\n box_regression (Tensor)\n labels (list[BoxList])\n regression_targets (Tensor)\n\n Returns:\n classification_loss (Tensor)\n box_loss (Tensor)\n \"\"\"\n \n labels = torch.cat(labels, dim=0)\n regression_targets = torch.cat(regression_targets, dim=0)\n\n classification_loss = custom_loss(class_logits, labels) #ADDING THE CUSTOM LOSS HERE\n\n # get indices that correspond to the regression targets for\n # the corresponding ground truth labels, to be used with\n # advanced indexing\n sampled_pos_inds_subset = torch.where(labels > 0)[0]\n labels_pos = labels[sampled_pos_inds_subset]\n N, num_classes = class_logits.shape\n box_regression = box_regression.reshape(N, -1, 4)\n\n box_loss = det_utils.smooth_l1_loss(\n box_regression[sampled_pos_inds_subset, labels_pos],\n regression_targets[sampled_pos_inds_subset],\n beta=1 / 9,\n size_average=False,\n )\n box_loss = box_loss / labels.numel()\n\n return classification_loss, box_loss", "_____no_output_____" ] ], [ [ "# Note on how to vary the anchor generator", "_____no_output_____" ], [ "The way in which anchor generators are assigned when we use backbone with and without fpn is different. When we are not using FPN there will be only one feature map and for that feature map we need to specify anchors of different shapes.", "_____no_output_____" ] ], [ [ "anchor_generator = AnchorGenerator(sizes=((128, 256, 512),),\n aspect_ratios=((0.5, 1.0, 2.0),))", "_____no_output_____" ] ], [ [ "In the above case suppose we have a feature map of shape 7x7, then at each cell in it there will be 9 anchors,three each of shapes 128,256 and 512,with the corresponding aspect rations. But when we are using FPN we have different feature maps, so its more effective we use different feature maps for different layers. Small sized objects are deteted using the earlier feature maps and thus for those we can specify a small sized anchor say 32 and for the later layers we can specify larger anchors.", "_____no_output_____" ] ], [ [ "anchor_sizes = ((32), (64), (128),(256) ) \naspect_ratios = ((0.5,1.0, 1.5,2.0,)) * len(anchor_sizes)\nanchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios)", "_____no_output_____" ] ], [ [ "In the above i am using the same aspect ratio for all the sizes so i am just multiplying by the lenght of the anchor_sizes, but if we want to specify different aspect ratios its totally possible. But be carefull to specifiy the same number of aspect ratios for each anchor sizes", "_____no_output_____" ], [ "# Credits", "_____no_output_____" ], [ "All the above hacks are just modification of the existing wonderful torchvision library.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
4af38c185d53865b8b7bc5836f2eee7536a8025a
58,695
ipynb
Jupyter Notebook
doc/pub/week9/ipynb/.ipynb_checkpoints/week9-checkpoint.ipynb
Shield94/Physics321
9875a3bf840b0fa164b865a3cb13073aff9094ca
[ "CC0-1.0" ]
20
2020-01-09T17:41:16.000Z
2022-03-09T00:48:58.000Z
doc/pub/week9/ipynb/.ipynb_checkpoints/week9-checkpoint.ipynb
Shield94/Physics321
9875a3bf840b0fa164b865a3cb13073aff9094ca
[ "CC0-1.0" ]
6
2020-01-08T03:47:53.000Z
2020-12-15T15:02:57.000Z
doc/pub/week9/ipynb/.ipynb_checkpoints/week9-checkpoint.ipynb
Shield94/Physics321
9875a3bf840b0fa164b865a3cb13073aff9094ca
[ "CC0-1.0" ]
33
2020-01-10T20:40:55.000Z
2022-02-11T20:28:41.000Z
29.915902
405
0.530267
[ [ [ "<!-- dom:TITLE: PHY321: Harmonic Oscillations, Damping, Resonances and time-dependent Forces -->\n# PHY321: Harmonic Oscillations, Damping, Resonances and time-dependent Forces\n<!-- dom:AUTHOR: [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/) at Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA & Department of Physics, University of Oslo, Norway -->\n<!-- Author: --> \n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA and Department of Physics, University of Oslo, Norway\n\nDate: **Mar 1, 2021**\n\nCopyright 1999-2021, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n## Aims and Overarching Motivation\n\n### Monday\n\nDamped oscillations. Analytical and numerical solutions\n**Reading suggestion**: Taylor sections 5.4-5.5. \n\n\n### Wednesday\n\nNo lecture, study day\n\n### Friday\n\nDriven oscillations and resonances with examples.\n**Reading suggestion**: Taylor sections 5.5-5.6. \n\n\n## Damped Oscillators\n\nWe consider only the case where the damping force is proportional to\nthe velocity. This is counter to dragging friction, where the force is\nproportional in strength to the normal force and independent of\nvelocity, and is also inconsistent with wind resistance, where the\nmagnitude of the drag force is proportional the square of the\nvelocity. Rolling resistance does seem to be mainly proportional to\nthe velocity. However, the main motivation for considering damping\nforces proportional to the velocity is that the math is more\nfriendly. This is because the differential equation is linear,\ni.e. each term is of order $x$, $\\dot{x}$, $\\ddot{x}\\cdots$, or even\nterms with no mention of $x$, and there are no terms such as $x^2$ or\n$x\\ddot{x}$. The equations of motion for a spring with damping force\n$-b\\dot{x}$ are", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto1\"></div>\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$", "_____no_output_____" ], [ "## Harmonic Oscillator, Damping\n\nJust to make the solution a bit less messy, we rewrite this equation as", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:dampeddiffyq\"></div>\n\n$$\n\\begin{equation}\n\\label{eq:dampeddiffyq} \\tag{2}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=0,~~~~\\beta\\equiv b/2m,~\\omega_0\\equiv\\sqrt{k/m}.\n\\end{equation}\n$$", "_____no_output_____" ], [ "Both $\\beta$ and $\\omega$ have dimensions of inverse time. To find solutions (see appendix C in the text) you must make an educated guess at the form of the solution. To do this, first realize that the solution will need an arbitrary normalization $A$ because the equation is linear. Secondly, realize that if the form is", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto2\"></div>\n\n$$\n\\begin{equation}\nx=Ae^{rt}\n\\label{_auto2} \\tag{3}\n\\end{equation}\n$$", "_____no_output_____" ], [ "that each derivative simply brings out an extra power of $r$. This\nmeans that the $Ae^{rt}$ factors out and one can simply solve for an\nequation for $r$. Plugging this form into Eq. ([2](#eq:dampeddiffyq)),", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto3\"></div>\n\n$$\n\\begin{equation}\nr^2+2\\beta r+\\omega_0^2=0.\n\\label{_auto3} \\tag{4}\n\\end{equation}\n$$", "_____no_output_____" ], [ "## Harmonic Oscillator, Solutions of Damped Motion\n\nBecause this is a quadratic equation there will be two solutions,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto4\"></div>\n\n$$\n\\begin{equation}\nr=-\\beta\\pm\\sqrt{\\beta^2-\\omega_0^2}.\n\\label{_auto4} \\tag{5}\n\\end{equation}\n$$", "_____no_output_____" ], [ "We refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto5\"></div>\n\n$$\n\\begin{equation}\nx=A_1e^{r_1t}+A_2e^{r_2t},\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$", "_____no_output_____" ], [ "where the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nThe roots listed above, $\\sqrt{\\omega_0^2-\\beta_0^2}$, will be\nimaginary if the damping is small and $\\beta<\\omega_0$. In that case,\n$r$ is complex and the factor $\\exp{(rt)}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. There are three cases:\n\n\n## Underdamped: $\\beta<\\omega_0$", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nx&=&A_1e^{-\\beta t}e^{i\\omega't}+A_2e^{-\\beta t}e^{-i\\omega't},~~\\omega'\\equiv\\sqrt{\\omega_0^2-\\beta^2}\\\\\n\\nonumber\n&=&(A_1+A_2)e^{-\\beta t}\\cos\\omega't+i(A_1-A_2)e^{-\\beta t}\\sin\\omega't.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "Here we have made use of the identity\n$e^{i\\omega't}=\\cos\\omega't+i\\sin\\omega't$. Because the constants are\narbitrary, and because the real and imaginary parts are both solutions\nindividually, we can simply consider the real part of the solution\nalone:", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:homogsolution\"></div>\n\n$$\n\\begin{eqnarray}\n\\label{eq:homogsolution} \\tag{7}\nx&=&B_1e^{-\\beta t}\\cos\\omega't+B_2e^{-\\beta t}\\sin\\omega't,\\\\\n\\nonumber \n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "## Critical dampling: $\\beta=\\omega_0$\n\nIn this case the two terms involving $r_1$ and $r_2$ are identical\nbecause $\\omega'=0$. Because we need to arbitrary constants, there\nneeds to be another solution. This is found by simply guessing, or by\ntaking the limit of $\\omega'\\rightarrow 0$ from the underdamped\nsolution. The solution is then", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:criticallydamped\"></div>\n\n$$\n\\begin{equation}\n\\label{eq:criticallydamped} \\tag{8}\nx=Ae^{-\\beta t}+Bte^{-\\beta t}.\n\\end{equation}\n$$", "_____no_output_____" ], [ "The critically damped solution is interesting because the solution\napproaches zero quickly, but does not oscillate. For a problem with\nzero initial velocity, the solution never crosses zero. This is a good\nchoice for designing shock absorbers or swinging doors.\n\n## Overdamped: $\\beta>\\omega_0$", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nx&=&A_1\\exp{-(\\beta+\\sqrt{\\beta^2-\\omega_0^2})t}+A_2\\exp{-(\\beta-\\sqrt{\\beta^2-\\omega_0^2})t}\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "This solution will also never pass the origin more than once, and then\nonly if the initial velocity is strong and initially toward zero.\n\n\n\n\nGiven $b$, $m$ and $\\omega_0$, find $x(t)$ for a particle whose\ninitial position is $x=0$ and has initial velocity $v_0$ (assuming an\nunderdamped solution).\n\nThe solution is of the form,", "_____no_output_____" ], [ "$$\n\\begin{eqnarray*}\nx&=&e^{-\\beta t}\\left[A_1\\cos(\\omega' t)+A_2\\sin\\omega't\\right],\\\\\n\\dot{x}&=&-\\beta x+\\omega'e^{-\\beta t}\\left[-A_1\\sin\\omega't+A_2\\cos\\omega't\\right].\\\\\n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2},~~~\\beta\\equiv b/2m.\n\\end{eqnarray*}\n$$", "_____no_output_____" ], [ "From the initial conditions, $A_1=0$ because $x(0)=0$ and $\\omega'A_2=v_0$. So", "_____no_output_____" ], [ "$$\nx=\\frac{v_0}{\\omega'}e^{-\\beta t}\\sin\\omega't.\n$$", "_____no_output_____" ], [ "## Harmonic Oscillator, Solutions\n\nConsider a single solution with no arbitrary constants, which we will\ncall a **particular solution**, $x_p(t)$. It should be emphasized\nthat this is **A** particular solution, because there exists an\ninfinite number of such solutions because the general solution should\nhave two arbitrary constants. Now consider solutions to the same\nequation without the driving term, which include two arbitrary\nconstants. These are called either **homogenous solutions** or \n**complementary solutions**, and were given in the previous section,\ne.g. Eq. ([7](#eq:homogsolution)) for the underdamped case. The\nhomogenous solution already incorporates the two arbitrary constants,\nso any sum of a homogenous solution and a particular solution will\nrepresent the **general solution** of the equation. The general\nsolution incorporates the two arbitrary constants $A$ and $B$ to\naccommodate the two initial conditions. One could have picked a\ndifferent particular solution, i.e. the original particular solution\nplus any homogenous solution with the arbitrary constants $A_p$ and\n$B_p$ chosen at will. When one adds in the homogenous solution, which\nhas adjustable constants with arbitrary constants $A'$ and $B'$, to\nthe new particular solution, one can get the same general solution by\nsimply adjusting the new constants such that $A'+A_p=A$ and\n$B'+B_p=B$. Thus, the choice of $A_p$ and $B_p$ are irrelevant, and\nwhen choosing the particular solution it is best to make the simplest\nchoice possible.\n\n## Harmonic Oscillator, Particular Solution\n\nTo find a particular solution, one first guesses at the form,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:partform\"></div>\n\n$$\n\\begin{equation}\n\\label{eq:partform} \\tag{9}\nx_p(t)=D\\cos(\\omega t-\\delta),\n\\end{equation}\n$$", "_____no_output_____" ], [ "and rewrite the differential equation as", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto6\"></div>\n\n$$\n\\begin{equation}\nD\\left\\{-\\omega^2\\cos(\\omega t-\\delta)-2\\beta\\omega\\sin(\\omega t-\\delta)+\\omega_0^2\\cos(\\omega t-\\delta)\\right\\}=\\frac{F_0}{m}\\cos(\\omega t).\n\\label{_auto6} \\tag{10}\n\\end{equation}\n$$", "_____no_output_____" ], [ "One can now use angle addition formulas to get", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nD\\left\\{(-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta)\\cos(\\omega t)\\right.&&\\\\\n\\nonumber\n\\left.+(-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta)\\sin(\\omega t)\\right\\}\n&=&\\frac{F_0}{m}\\cos(\\omega t).\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "Both the $\\cos$ and $\\sin$ terms need to equate if the expression is to hold at all times. Thus, this becomes two equations", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta\\right\\}&=&\\frac{F_0}{m}\\\\\n\\nonumber\n-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta&=&0.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "After dividing by $\\cos\\delta$, the lower expression leads to", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto7\"></div>\n\n$$\n\\begin{equation}\n\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto7} \\tag{11}\n\\end{equation}\n$$", "_____no_output_____" ], [ "## Solving with Driven Oscillations\n\n\nUsing the identities $\\tan^2+1=\\csc^2$ and $\\sin^2+\\cos^2=1$, one can also express $\\sin\\delta$ and $\\cos\\delta$,", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\n\\sin\\delta&=&\\frac{2\\beta\\omega}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}},\\\\\n\\nonumber\n\\cos\\delta&=&\\frac{(\\omega_0^2-\\omega^2)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "Inserting the expressions for $\\cos\\delta$ and $\\sin\\delta$ into the expression for $D$,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:Ddrive\"></div>\n\n$$\n\\begin{equation}\n\\label{eq:Ddrive} \\tag{12}\nD=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}.\n\\end{equation}\n$$", "_____no_output_____" ], [ "For a given initial condition, e.g. initial displacement and velocity,\none must add the homogenous solution then solve for the two arbitrary\nconstants. However, because the homogenous solutions decay with time\nas $e^{-\\beta t}$, the particular solution is all that remains at\nlarge times, and is therefore the steady state solution. Because the\narbitrary constants are all in the homogenous solution, all memory of\nthe initial conditions are lost at large times, $t>>1/\\beta$.\n\nThe amplitude of the motion, $D$, is linearly proportional to the\ndriving force ($F_0/m$), but also depends on the driving frequency\n$\\omega$. For small $\\beta$ the maximum will occur at\n$\\omega=\\omega_0$. This is referred to as a resonance. In the limit\n$\\beta\\rightarrow 0$ the amplitude at resonance approaches infinity.\n\n## Alternative Derivation for Driven Oscillators\n\nHere, we derive the same expressions as in Equations ([9](#eq:partform)) and ([12](#eq:Ddrive)) but express the driving forces as", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nF(t)&=&F_0e^{i\\omega t},\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "rather than as $F_0\\cos\\omega t$. The real part of $F$ is the same as before. For the differential equation,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:compdrive\"></div>\n\n$$\n\\begin{eqnarray}\n\\label{eq:compdrive} \\tag{13}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x&=&\\frac{F_0}{m}e^{i\\omega t},\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "one can treat $x(t)$ as an imaginary function. Because the operations\n$d^2/dt^2$ and $d/dt$ are real and thus do not mix the real and\nimaginary parts of $x(t)$, Eq. ([13](#eq:compdrive)) is effectively 2\nequations. Because $e^{\\omega t}=\\cos\\omega t+i\\sin\\omega t$, the real\npart of the solution for $x(t)$ gives the solution for a driving force\n$F_0\\cos\\omega t$, and the imaginary part of $x$ corresponds to the\ncase where the driving force is $F_0\\sin\\omega t$. It is rather easy\nto solve for the complex $x$ in this case, and by taking the real part\nof the solution, one finds the answer for the $\\cos\\omega t$ driving\nforce.\n\nWe assume a simple form for the particular solution", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto8\"></div>\n\n$$\n\\begin{equation}\nx_p=De^{i\\omega t},\n\\label{_auto8} \\tag{14}\n\\end{equation}\n$$", "_____no_output_____" ], [ "where $D$ is a complex constant.\n\nFrom Eq. ([13](#eq:compdrive)) one inserts the form for $x_p$ above to get", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2+2i\\beta\\omega+\\omega_0^2\\right\\}e^{i\\omega t}=(F_0/m)e^{i\\omega t},\\\\\n\\nonumber\nD=\\frac{F_0/m}{(\\omega_0^2-\\omega^2)+2i\\beta\\omega}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "The norm and phase for $D=|D|e^{-i\\delta}$ can be read by inspection,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto9\"></div>\n\n$$\n\\begin{equation}\n|D|=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}},~~~~\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto9} \\tag{15}\n\\end{equation}\n$$", "_____no_output_____" ], [ "This is the same expression for $\\delta$ as before. One then finds $x_p(t)$,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:fastdriven1\"></div>\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven1} \\tag{16}\nx_p(t)&=&\\Re\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\cos(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "This is the same answer as before.\nIf one wished to solve for the case where $F(t)= F_0\\sin\\omega t$, the imaginary part of the solution would work", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:fastdriven2\"></div>\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven2} \\tag{17}\nx_p(t)&=&\\Im\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "## Damped and Driven Oscillator\n\nConsider the damped and driven harmonic oscillator worked out above. Given $F_0, m,\\beta$ and $\\omega_0$, solve for the complete solution $x(t)$ for the case where $F=F_0\\sin\\omega t$ with initial conditions $x(t=0)=0$ and $v(t=0)=0$. Assume the underdamped case.\n\nThe general solution including the arbitrary constants includes both the homogenous and particular solutions,", "_____no_output_____" ], [ "$$\n\\begin{eqnarray*}\nx(t)&=&\\frac{F_0}{m}\\frac{\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\n+A\\cos\\omega't e^{-\\beta t}+B\\sin\\omega't e^{-\\beta t}.\n\\end{eqnarray*}\n$$", "_____no_output_____" ], [ "The quantities $\\delta$ and $\\omega'$ are given earlier in the\nsection, $\\omega'=\\sqrt{\\omega_0^2-\\beta^2},\n\\delta=\\tan^{-1}(2\\beta\\omega/(\\omega_0^2-\\omega^2)$. Here, solving\nthe problem means finding the arbitrary constants $A$ and\n$B$. Satisfying the initial conditions for the initial position and\nvelocity:", "_____no_output_____" ], [ "$$\n\\begin{eqnarray*}\nx(t=0)=0&=&-\\eta\\sin\\delta+A,\\\\\nv(t=0)=0&=&\\omega\\eta\\cos\\delta-\\beta A+\\omega'B,\\\\\n\\eta&\\equiv&\\frac{F_0}{m}\\frac{1}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray*}\n$$", "_____no_output_____" ], [ "The problem is now reduced to 2 equations and 2 unknowns, $A$ and $B$. The solution is", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nA&=& \\eta\\sin\\delta ,~~~B=\\frac{-\\omega\\eta\\cos\\delta+\\beta\\eta\\sin\\delta}{\\omega'}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "## Resonance Widths; the $Q$ factor\n\nFrom the previous two sections, the particular solution for a driving force, $F=F_0\\cos\\omega t$, is", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\\cos(\\omega_t-\\delta),\\\\\n\\nonumber\n\\delta&=&\\tan^{-1}\\left(\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}\\right).\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "If one fixes the driving frequency $\\omega$ and adjusts the\nfundamental frequency $\\omega_0=\\sqrt{k/m}$, the maximum amplitude\noccurs when $\\omega_0=\\omega$ because that is when the term from the\ndenominator $(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2$ is at a\nminimum. This is akin to dialing into a radio station. However, if one\nfixes $\\omega_0$ and adjusts the driving frequency one minimize with\nrespect to $\\omega$, e.g. set", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto10\"></div>\n\n$$\n\\begin{equation}\n\\frac{d}{d\\omega}\\left[(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2\\right]=0,\n\\label{_auto10} \\tag{18}\n\\end{equation}\n$$", "_____no_output_____" ], [ "and one finds that the maximum amplitude occurs when\n$\\omega=\\sqrt{\\omega_0^2-2\\beta^2}$. If $\\beta$ is small relative to\n$\\omega_0$, one can simply state that the maximum amplitude is", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto11\"></div>\n\n$$\n\\begin{equation}\nx_{\\rm max}\\approx\\frac{F_0}{2m\\beta \\omega_0}.\n\\label{_auto11} \\tag{19}\n\\end{equation}\n$$", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\n\\frac{4\\omega^2\\beta^2}{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}=\\frac{1}{2}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "For small damping this occurs when $\\omega=\\omega_0\\pm \\beta$, so the $FWHM\\approx 2\\beta$. For the purposes of tuning to a specific frequency, one wants the width to be as small as possible. The ratio of $\\omega_0$ to $FWHM$ is known as the _quality_factor, or $Q$ factor,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto12\"></div>\n\n$$\n\\begin{equation}\nQ\\equiv \\frac{\\omega_0}{2\\beta}.\n\\label{_auto12} \\tag{20}\n\\end{equation}\n$$", "_____no_output_____" ], [ "## Numerical Studies of Driven Oscillations\n\nSolving the problem of driven oscillations numerically gives us much\nmore flexibility to study different types of driving forces. We can\nreuse our earlier code by simply adding a driving force. If we stay in\nthe $x$-direction only this can be easily done by adding a term\n$F_{\\mathrm{ext}}(x,t)$. Note that we have kept it rather general\nhere, allowing for both a spatial and a temporal dependence.\n\nBefore we dive into the code, we need to briefly remind ourselves\nabout the equations we started with for the case with damping, namely", "_____no_output_____" ], [ "$$\nm\\frac{d^2x}{dt^2} + b\\frac{dx}{dt}+kx(t) =0,\n$$", "_____no_output_____" ], [ "with no external force applied to the system.\n\nLet us now for simplicty assume that our external force is given by", "_____no_output_____" ], [ "$$\nF_{\\mathrm{ext}}(t) = F_0\\cos{(\\omega t)},\n$$", "_____no_output_____" ], [ "where $F_0$ is a constant (what is its dimension?) and $\\omega$ is the frequency of the applied external driving force.\n**Small question:** would you expect energy to be conserved now?\n\n\nIntroducing the external force into our lovely differential equation\nand dividing by $m$ and introducing $\\omega_0^2=\\sqrt{k/m}$ we have", "_____no_output_____" ], [ "$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =\\frac{F_0}{m}\\cos{(\\omega t)},\n$$", "_____no_output_____" ], [ "Thereafter we introduce a dimensionless time $\\tau = t\\omega_0$\nand a dimensionless frequency $\\tilde{\\omega}=\\omega/\\omega_0$. We have then", "_____no_output_____" ], [ "$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\frac{F_0}{m\\omega_0^2}\\cos{(\\tilde{\\omega}\\tau)},\n$$", "_____no_output_____" ], [ "Introducing a new amplitude $\\tilde{F} =F_0/(m\\omega_0^2)$ (check dimensionality again) we have", "_____no_output_____" ], [ "$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$", "_____no_output_____" ], [ "Our final step, as we did in the case of various types of damping, is\nto define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as", "_____no_output_____" ], [ "$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$", "_____no_output_____" ], [ "This is the equation we will code below using the Euler-Cromer method.", "_____no_output_____" ] ], [ [ "DeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions as one-dimensional arrays of time\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.2\nOmegatilde = 0.5\nFtilde = 1.0\n# Start integrating using Euler-Cromer's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n a = -2*gamma*v[i]-x[i]+Ftilde*cos(t[i]*Omegatilde)\n # update velocity, time and position\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"ForcedBlockEulerCromer\")\nplt.show()", "_____no_output_____" ] ], [ [ "In the above example we have focused on the Euler-Cromer method. This\nmethod has a local truncation error which is proportional to $\\Delta t^2$\nand thereby a global error which is proportional to $\\Delta t$.\nWe can improve this by using the Runge-Kutta family of\nmethods. The widely popular Runge-Kutta to fourth order or just **RK4**\nhas indeed a much better truncation error. The RK4 method has a global\nerror which is proportional to $\\Delta t$.\n\nLet us revisit this method and see how we can implement it for the above example.\n\n\n## Differential Equations, Runge-Kutta methods\n\nRunge-Kutta (RK) methods are based on Taylor expansion formulae, but yield\nin general better algorithms for solutions of an ordinary differential equation.\nThe basic philosophy is that it provides an intermediate step in the computation of $y_{i+1}$.\n\nTo see this, consider first the following definitions", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto13\"></div>\n\n$$\n\\begin{equation}\n\\frac{dy}{dt}=f(t,y), \n\\label{_auto13} \\tag{21}\n\\end{equation}\n$$", "_____no_output_____" ], [ "and", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto14\"></div>\n\n$$\n\\begin{equation}\ny(t)=\\int f(t,y) dt, \n\\label{_auto14} \\tag{22}\n\\end{equation}\n$$", "_____no_output_____" ], [ "and", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto15\"></div>\n\n$$\n\\begin{equation}\ny_{i+1}=y_i+ \\int_{t_i}^{t_{i+1}} f(t,y) dt.\n\\label{_auto15} \\tag{23}\n\\end{equation}\n$$", "_____no_output_____" ], [ "To demonstrate the philosophy behind RK methods, let us consider\nthe second-order RK method, RK2.\nThe first approximation consists in Taylor expanding $f(t,y)$\naround the center of the integration interval $t_i$ to $t_{i+1}$,\nthat is, at $t_i+h/2$, $h$ being the step.\nUsing the midpoint formula for an integral, \ndefining $y(t_i+h/2) = y_{i+1/2}$ and \n$t_i+h/2 = t_{i+1/2}$, we obtain", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto16\"></div>\n\n$$\n\\begin{equation}\n\\int_{t_i}^{t_{i+1}} f(t,y) dt \\approx hf(t_{i+1/2},y_{i+1/2}) +O(h^3).\n\\label{_auto16} \\tag{24}\n\\end{equation}\n$$", "_____no_output_____" ], [ "This means in turn that we have", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto17\"></div>\n\n$$\n\\begin{equation}\ny_{i+1}=y_i + hf(t_{i+1/2},y_{i+1/2}) +O(h^3).\n\\label{_auto17} \\tag{25}\n\\end{equation}\n$$", "_____no_output_____" ], [ "However, we do not know the value of $y_{i+1/2}$. Here comes thus the next approximation, namely, we use Euler's\nmethod to approximate $y_{i+1/2}$. We have then", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto18\"></div>\n\n$$\n\\begin{equation}\ny_{(i+1/2)}=y_i + \\frac{h}{2}\\frac{dy}{dt}=y(t_i) + \\frac{h}{2}f(t_i,y_i).\n\\label{_auto18} \\tag{26}\n\\end{equation}\n$$", "_____no_output_____" ], [ "This means that we can define the following algorithm for \nthe second-order Runge-Kutta method, RK2.", "_____no_output_____" ], [ "4\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto20\"></div>\n\n$$\n\\begin{equation}\nk_2=hf(t_{i+1/2},y_i+k_1/2),\n\\label{_auto20} \\tag{28}\n\\end{equation}\n$$", "_____no_output_____" ], [ "with the final value", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto21\"></div>\n\n$$\n\\begin{equation} \ny_{i+i}\\approx y_i + k_2 +O(h^3). \n\\label{_auto21} \\tag{29}\n\\end{equation}\n$$", "_____no_output_____" ], [ "The difference between the previous one-step methods \nis that we now need an intermediate step in our evaluation,\nnamely $t_i+h/2 = t_{(i+1/2)}$ where we evaluate the derivative $f$. \nThis involves more operations, but the gain is a better stability\nin the solution.\n\nThe fourth-order Runge-Kutta, RK4, has the following algorithm", "_____no_output_____" ], [ "4\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK", "_____no_output_____" ], [ "$$\nk_3=hf(t_i+h/2,y_i+k_2/2)\\hspace{0.5cm} k_4=hf(t_i+h,y_i+k_3)\n$$", "_____no_output_____" ], [ "with the final result", "_____no_output_____" ], [ "$$\ny_{i+1}=y_i +\\frac{1}{6}\\left( k_1 +2k_2+2k_3+k_4\\right).\n$$", "_____no_output_____" ], [ "Thus, the algorithm consists in first calculating $k_1$ \nwith $t_i$, $y_1$ and $f$ as inputs. Thereafter, we increase the step\nsize by $h/2$ and calculate $k_2$, then $k_3$ and finally $k_4$. The global error goes as $O(h^4)$.\n\n\nHowever, at this stage, if we keep adding different methods in our\nmain program, the code will quickly become messy and ugly. Before we\nproceed thus, we will now introduce functions that enbody the various\nmethods for solving differential equations. This means that we can\nseparate out these methods in own functions and files (and later as classes and more\ngeneric functions) and simply call them when needed. Similarly, we\ncould easily encapsulate various forces or other quantities of\ninterest in terms of functions. To see this, let us bring up the code\nwe developed above for the simple sliding block, but now only with the simple forward Euler method. We introduce\ntwo functions, one for the simple Euler method and one for the\nforce.\n\nNote that here the forward Euler method does not know the specific force function to be called.\nIt receives just an input the name. We can easily change the force by adding another function.", "_____no_output_____" ] ], [ [ "def ForwardEuler(v,x,t,n,Force):\n for i in range(n-1):\n v[i+1] = v[i] + DeltaT*Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT", "_____no_output_____" ], [ "def SpringForce(v,x,t):\n# note here that we have divided by mass and we return the acceleration\n return -2*gamma*v-x+Ftilde*cos(t*Omegatilde)", "_____no_output_____" ] ], [ [ "It is easy to add a new method like the Euler-Cromer", "_____no_output_____" ] ], [ [ "def ForwardEulerCromer(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT", "_____no_output_____" ] ], [ [ "and the Velocity Verlet method (be careful with time-dependence here, it is not an ideal method for non-conservative forces))", "_____no_output_____" ] ], [ [ "def VelocityVerlet(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]+0.5*a\n anew = Force(v[i],x[i+1],t[i+1])\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT", "_____no_output_____" ] ], [ [ "Finally, we can now add the Runge-Kutta2 method via a new function", "_____no_output_____" ] ], [ [ "def RK2(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Final result\n x[i+1] = x[i]+k2x\n v[i+1] = v[i]+k2v\n\tt[i+1] = t[i]+DeltaT", "_____no_output_____" ] ], [ [ "Finally, we can now add the Runge-Kutta2 method via a new function", "_____no_output_____" ] ], [ [ "def RK4(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k3\n vv = v[i]+k2v*0.5\n xx = x[i]+k2x*0.5\n k3x = DeltaT*vv\n k3v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k4\n vv = v[i]+k3v\n xx = x[i]+k3x\n k4x = DeltaT*vv\n k4v = DeltaT*Force(vv,xx,t[i]+DeltaT)\n# Final result\n x[i+1] = x[i]+(k1x+2*k2x+2*k3x+k4x)/6.\n v[i+1] = v[i]+(k1v+2*k2v+2*k3v+k4v)/6.\n t[i+1] = t[i] + DeltaT", "_____no_output_____" ] ], [ [ "The Runge-Kutta family of methods are particularly useful when we have a time-dependent acceleration.\nIf we have forces which depend only the spatial degrees of freedom (no velocity and/or time-dependence), then energy conserving methods like the Velocity Verlet or the Euler-Cromer method are preferred. As soon as we introduce an explicit time-dependence and/or add dissipitave forces like friction or air resistance, then methods like the family of Runge-Kutta methods are well suited for this. \nThe code below uses the Runge-Kutta4 methods.", "_____no_output_____" ] ], [ [ "DeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions (can change to more than one dim)\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.2\nOmegatilde = 0.5\nFtilde = 1.0\n# Start integrating using Euler's method\n# Note that we define the force function as a SpringForce\nRK4(v,x,t,n,SpringForce)\n\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"ForcedBlockRK4\")\nplt.show()", "_____no_output_____" ] ], [ [ "<!-- !split -->\n## Principle of Superposition and Periodic Forces (Fourier Transforms)\n\nIf one has several driving forces, $F(t)=\\sum_n F_n(t)$, one can find\nthe particular solution to each $F_n$, $x_{pn}(t)$, and the particular\nsolution for the entire driving force is", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto22\"></div>\n\n$$\n\\begin{equation}\nx_p(t)=\\sum_nx_{pn}(t).\n\\label{_auto22} \\tag{30}\n\\end{equation}\n$$", "_____no_output_____" ], [ "This is known as the principal of superposition. It only applies when\nthe homogenous equation is linear. If there were an anharmonic term\nsuch as $x^3$ in the homogenous equation, then when one summed various\nsolutions, $x=(\\sum_n x_n)^2$, one would get cross\nterms. Superposition is especially useful when $F(t)$ can be written\nas a sum of sinusoidal terms, because the solutions for each\nsinusoidal (sine or cosine) term is analytic, as we saw above.\n\nDriving forces are often periodic, even when they are not\nsinusoidal. Periodicity implies that for some time $\\tau$", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nF(t+\\tau)=F(t). \n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "One example of a non-sinusoidal periodic force is a square wave. Many\ncomponents in electric circuits are non-linear, e.g. diodes, which\nmakes many wave forms non-sinusoidal even when the circuits are being\ndriven by purely sinusoidal sources.\n\nThe code here shows a typical example of such a square wave generated using the functionality included in the **scipy** Python package. We have used a period of $\\tau=0.2$.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport numpy as np\nimport math\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n# number of points \nn = 500\n# start and final times \nt0 = 0.0\ntn = 1.0\n# Period \nt = np.linspace(t0, tn, n, endpoint=False)\nSqrSignal = np.zeros(n)\nSqrSignal = 1.0+signal.square(2*np.pi*5*t)\nplt.plot(t, SqrSignal)\nplt.ylim(-0.5, 2.5)\nplt.show()", "_____no_output_____" ] ], [ [ "For the sinusoidal example studied in the previous subsections the\nperiod is $\\tau=2\\pi/\\omega$. However, higher harmonics can also\nsatisfy the periodicity requirement. In general, any force that\nsatisfies the periodicity requirement can be expressed as a sum over\nharmonics,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto23\"></div>\n\n$$\n\\begin{equation}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0} f_n\\cos(2n\\pi t/\\tau)+g_n\\sin(2n\\pi t/\\tau).\n\\label{_auto23} \\tag{31}\n\\end{equation}\n$$", "_____no_output_____" ], [ "From the previous subsection, one can write down the answer for\n$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$ into Eq.s\n([16](#eq:fastdriven1)) or ([17](#eq:fastdriven2)) respectively. By\nwriting each factor $2n\\pi t/\\tau$ as $n\\omega t$, with $\\omega\\equiv\n2\\pi/\\tau$,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:fourierdef1\"></div>\n\n$$\n\\begin{equation}\n\\label{eq:fourierdef1} \\tag{32}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0}f_n\\cos(n\\omega t)+g_n\\sin(n\\omega t).\n\\end{equation}\n$$", "_____no_output_____" ], [ "The solutions for $x(t)$ then come from replacing $\\omega$ with\n$n\\omega$ for each term in the particular solution in Equations\n([9](#eq:partform)) and ([12](#eq:Ddrive)),", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{f_0}{2k}+\\sum_{n>0} \\alpha_n\\cos(n\\omega t-\\delta_n)+\\beta_n\\sin(n\\omega t-\\delta_n),\\\\\n\\nonumber\n\\alpha_n&=&\\frac{f_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\beta_n&=&\\frac{g_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\delta_n&=&\\tan^{-1}\\left(\\frac{2\\beta n\\omega}{\\omega_0^2-n^2\\omega^2}\\right).\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "Because the forces have been applied for a long time, any non-zero\ndamping eliminates the homogenous parts of the solution, so one need\nonly consider the particular solution for each $n$.\n\nThe problem will considered solved if one can find expressions for the\ncoefficients $f_n$ and $g_n$, even though the solutions are expressed\nas an infinite sum. The coefficients can be extracted from the\nfunction $F(t)$ by", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:fourierdef2\"></div>\n\n$$\n\\begin{eqnarray}\n\\label{eq:fourierdef2} \\tag{33}\nf_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\cos(2n\\pi t/\\tau),\\\\\n\\nonumber\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\sin(2n\\pi t/\\tau).\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "To check the consistency of these expressions and to verify\nEq. ([33](#eq:fourierdef2)), one can insert the expansion of $F(t)$ in\nEq. ([32](#eq:fourierdef1)) into the expression for the coefficients in\nEq. ([33](#eq:fourierdef2)) and see whether", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~\\left\\{\n\\frac{f_0}{2}+\\sum_{m>0}f_m\\cos(m\\omega t)+g_m\\sin(m\\omega t)\n\\right\\}\\cos(n\\omega t).\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "Immediately, one can throw away all the terms with $g_m$ because they\nconvolute an even and an odd function. The term with $f_0/2$\ndisappears because $\\cos(n\\omega t)$ is equally positive and negative\nover the interval and will integrate to zero. For all the terms\n$f_m\\cos(m\\omega t)$ appearing in the sum, one can use angle addition\nformulas to see that $\\cos(m\\omega t)\\cos(n\\omega\nt)=(1/2)(\\cos[(m+n)\\omega t]+\\cos[(m-n)\\omega t]$. This will integrate\nto zero unless $m=n$. In that case the $m=n$ term gives", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto24\"></div>\n\n$$\n\\begin{equation}\n\\int_{-\\tau/2}^{\\tau/2}dt~\\cos^2(m\\omega t)=\\frac{\\tau}{2},\n\\label{_auto24} \\tag{34}\n\\end{equation}\n$$", "_____no_output_____" ], [ "and", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2\\\\\n\\nonumber\n&=&f_n~\\checkmark.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "The same method can be used to check for the consistency of $g_n$.\n\n\nConsider the driving force:", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"_auto25\"></div>\n\n$$\n\\begin{equation}\nF(t)=At/\\tau,~~-\\tau/2<t<\\tau/2,~~~F(t+\\tau)=F(t).\n\\label{_auto25} \\tag{35}\n\\end{equation}\n$$", "_____no_output_____" ], [ "Find the Fourier coefficients $f_n$ and $g_n$ for all $n$ using Eq. ([33](#eq:fourierdef2)).\n\nOnly the odd coefficients enter by symmetry, i.e. $f_n=0$. One can find $g_n$ integrating by parts,", "_____no_output_____" ], [ "<!-- Equation labels as ordinary links -->\n<div id=\"eq:fouriersolution\"></div>\n\n$$\n\\begin{eqnarray}\n\\label{eq:fouriersolution} \\tag{36}\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2}dt~\\sin(n\\omega t) \\frac{At}{\\tau}\\\\\n\\nonumber\nu&=&t,~dv=\\sin(n\\omega t)dt,~v=-\\cos(n\\omega t)/(n\\omega),\\\\\n\\nonumber\ng_n&=&\\frac{-2A}{n\\omega \\tau^2}\\int_{-\\tau/2}^{\\tau/2}dt~\\cos(n\\omega t)\n+\\left.2A\\frac{-t\\cos(n\\omega t)}{n\\omega\\tau^2}\\right|_{-\\tau/2}^{\\tau/2}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "The first term is zero because $\\cos(n\\omega t)$ will be equally\npositive and negative over the interval. Using the fact that\n$\\omega\\tau=2\\pi$,", "_____no_output_____" ], [ "$$\n\\begin{eqnarray}\ng_n&=&-\\frac{2A}{2n\\pi}\\cos(n\\omega\\tau/2)\\\\\n\\nonumber\n&=&-\\frac{A}{n\\pi}\\cos(n\\pi)\\\\\n\\nonumber\n&=&\\frac{A}{n\\pi}(-1)^{n+1}.\n\\end{eqnarray}\n$$", "_____no_output_____" ], [ "## Fourier Series\n\nMore text will come here, chpater 5.7-5.8 of Taylor are discussed\nduring the lectures. The code here uses the Fourier series discussed\nin chapter 5.7 for a square wave signal. The equations for the\ncoefficients are are discussed in Taylor section 5.7, see Example\n5.4. The code here visualizes the various approximations given by\nFourier series compared with a square wave with period $T=0.2$, witth\n$0.1$ and max value $F=2$. We see that when we increase the number of\ncomponents in the Fourier series, the Fourier series approximation gets closes and closes to the square wave signal.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport math\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n# number of points \nn = 500\n# start and final times \nt0 = 0.0\ntn = 1.0\n# Period \nT =0.2\n# Max value of square signal \nFmax= 2.0\n# Width of signal \nWidth = 0.1\nt = np.linspace(t0, tn, n, endpoint=False)\nSqrSignal = np.zeros(n)\nFourierSeriesSignal = np.zeros(n)\nSqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)\na0 = Fmax*Width/T\nFourierSeriesSignal = a0\nFactor = 2.0*Fmax/np.pi\nfor i in range(1,500):\n FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)\nplt.plot(t, SqrSignal)\nplt.plot(t, FourierSeriesSignal)\nplt.ylim(-0.5, 2.5)\nplt.show()", "_____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", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "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" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
4af392c2b1d9c9d4b0476084eae846c41b989e18
12,556
ipynb
Jupyter Notebook
Adding_AI_to_your_app.ipynb
sahanbull/chaitech-ai-in-your-app
bd369a0010c7b7427ac97ac78ed39e26f7752b08
[ "MIT" ]
null
null
null
Adding_AI_to_your_app.ipynb
sahanbull/chaitech-ai-in-your-app
bd369a0010c7b7427ac97ac78ed39e26f7752b08
[ "MIT" ]
null
null
null
Adding_AI_to_your_app.ipynb
sahanbull/chaitech-ai-in-your-app
bd369a0010c7b7427ac97ac78ed39e26f7752b08
[ "MIT" ]
null
null
null
33.393617
736
0.627031
[ [ [ "# Adding AI to Your App\n\nThere are multiple approaches one can use to leverage AI and ML in their business idea. \n1. Building your own proprietary model\n2. Using a pre-trained model within your application\n3. Leverage Cloud providers to support AI functions in your application\n\nThese different approaches have pros and cons. Approach 1 gives most degree of control to you as a business in terms of ***taking ownership*** and ***being independent***. \n\nThis notebook provides code examples in going about building your proprietary ML model in part 1. Then in part 2, we look at an example of how a model can be evaluated. This function is quite important as model evaluation is critical for a business regardless the model is built in-house or provided by a an external vendor. ", "_____no_output_____" ], [ "# Part 1: Building your Proprietary AI model\n\nIn this section, we look at how a ML model can be by built from scratch for your organisation. As seen from the example, this appears to be the more complex approach to leveraging ML as it entails costs relating to sourcing the relevant data and expertise required to building and maintaining your in-house model. In a strategic perspective, this approach is more preferable as it adds true value to the business as the ML model becomes the intellectual property of your business and gives the competitive edge. It also frees your business from having to rely on 3rd party licensing restrictions and terms of service agreements that are governed by the true owners of the AI/ML models that may become critical to your business. ", "_____no_output_____" ], [ "## Installing the Python Libraries\n\nThe first step is to install the python libraries that are needed for training our own ML model. There are many off-the-shelf machine learning libraries that are available in majority of programming languages to use well tested ML algorithms to train models with your own data. These libraries often come with favorable licenses (Eg. Apache 2, MIT and BSD to name a few) that will give your the freedom to use these tools without compromising the legal ownership of the models you train with them. \n\nIn this example, we use Python, a programming language that has a very rich ecosystem for data science and machine learning. For the specific implementation, we need [scikit-learn](https://scikit-learn.org/stable/) and [pandas](https://pandas.pydata.org/). We can use [pip](https://pypi.org/project/pip/) Python package manager to install these two libraries. ", "_____no_output_____" ] ], [ [ "!pip install -U scikit-learn\n!pip install pandas", "_____no_output_____" ] ], [ [ "## Loading the Data\n\nWe use a popular publicly available labelled [sentiment analysis dataset](https://www.cs.cornell.edu/people/pabo/movie-review-data/) to demonstrate the different approaches. We use a star rating dataset from the famous movie review website, [IMDB](https://www.imdb.com/).\n\nFirst, we load the data from the local disc using the `load_data` function that has been implemented here. Then we convert that dataset into a `pandas.DataFrame` object that is highly compatible with `scikit-learn` machine learning library.", "_____no_output_____" ] ], [ [ "# import required functions\nfrom os.path import join\nfrom os import listdir\n\ndata_dir = \"data\"\npos_data_dir = join(data_dir, \"pos\")\nneg_data_dir = join(data_dir, \"neg\")", "_____no_output_____" ], [ "def load_data(filepath, label):\n files = [join(filepath, filename) for filename in listdir(filepath) if filename.endswith(\".txt\")]\n records = []\n \n for file in files:\n with open(file) as f:\n text = f.read()\n \n records.append({\"text\": text, \"label\": label})\n \n return records", "_____no_output_____" ], [ "import pandas as pd\nfrom sklearn.utils import shuffle\n\n\npos = load_data(pos_data_dir, 1)\nneg = load_data(neg_data_dir, 0)\n\nrecords_df = shuffle(pd.DataFrame(pos + neg)).reset_index(drop=True)", "_____no_output_____" ], [ "records_df", "_____no_output_____" ] ], [ [ "## Train-Test Split\n\nWhen training a machine learning model, we need to make sure that there is an ***unseen*** set of examples that we can use to evaluate the true performance of the trained machine learning model. A popular approach to pre-allocate a percentage of the full dataset for testing the trained model and avoid using that data during the model training process. \n\n`scikit-learn` already provides functions that can easily create this test-data allocation for us. In the following step, we create the train-test data split.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\n\nX = records_df[\"text\"]\ny = records_df[\"label\"]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)", "_____no_output_____" ] ], [ [ "### Data Vectorisation\n\nMachine Learning models dominantly work with ***numerical representations***. What that means is that the input we provide into the machine learning algorithm should contain numbers rather than letters and symbols. In this example, we are working with movie reviews that are text representations. The process of taking non-numerical data and transforming them into a numerical vectors in a sensible manner is called ***data vectorisation*** in data science. \n\nIn order to create numerical representations of the text we have, there are well tested methods such as extracting the [TFIDF representation](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) of the textual document. We use pre-built functions available in `scikit-learn` in order to vectorise text. `scikit-learn` library provides different vectorisation methods (a.k.a feature extraction) for different modalities such as [text](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.feature_extraction.text) and [images](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.feature_extraction.image).\n\n", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import TfidfVectorizer\n\nvectoriser = TfidfVectorizer(stop_words=\"english\")", "_____no_output_____" ], [ "x_train = vectoriser.fit_transform(X_train)", "_____no_output_____" ] ], [ [ "### Model Training\n\nAfter vectorising the data, we choose an appropriate machine learning model and train it by ***fitting the model*** to the training data.", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression()\n\nmodel.fit(x_train, y_train)", "_____no_output_____" ], [ "y_train_pred = model.predict(x_train)\nprint(list(y_train_pred))\nprint(list(y_train))", "_____no_output_____" ] ], [ [ "### Model Testing\n\nOnce the model is trained, we need to see how robust this model is in making predictions on data that it hasn't seen before. We can use the pre-allocated test data to serve this purpose.", "_____no_output_____" ] ], [ [ "x_test = vectoriser.transform(X_test)\ny_test_pred = model.predict(x_test)", "_____no_output_____" ] ], [ [ "## Example Prediction", "_____no_output_____" ] ], [ [ "example_text = list(X_test)[1]\nexample_label = list(y_test)[1]\n\nprint(\"Text: {}\\n Actual Label: {}\".format(example_text, example_label))", "_____no_output_____" ] ], [ [ "### Predicting on example with our proprietary model", "_____no_output_____" ] ], [ [ "x_vect = vectoriser.transform([example_text])\ny_pred = model.predict(x_vect)\nprint(\"Predicted Label: {}\".format(y_pred[0]))", "_____no_output_____" ] ], [ [ "# Part 2: Evaluation", "_____no_output_____" ], [ "## Evaluating Accuracy of the train and Test data\n\nEvaluating a trained machine learning model is critical to establishing the value it can bring to your business. In this section we look at how we can evaluate the performance of the trained sentiment classification model. \n\nThe [accuracy score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html) can be used here to evaluate classification accuracy. \n\n### Exercise\n\nUsing the `accuracy_score` function in `sklearn.metrics` module, calculate the accuracy classification accuracy of the trained model based on both training data and testing data (using actual and predicted labels)/", "_____no_output_____" ] ], [ [ "# insert code here", "_____no_output_____" ], [ "train_accuracy = # insert code here", "_____no_output_____" ], [ "test_accuracy = # insert code here", "_____no_output_____" ], [ "print(\"Accuracy of the model on training data: {}\".format(train_accuracy))\nprint(\"Accuracy of the model on test data: {}\".format(test_accuracy))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
4af3c4bf3bbf822f9c5324c7ef162a1bbf440ea2
717,676
ipynb
Jupyter Notebook
Notebooks/Python/Part05_cell_fate.ipynb
hds-sandbox/scRNASeq_course
21de29197979562e99ee2080ca41479b033384ee
[ "Apache-2.0" ]
null
null
null
Notebooks/Python/Part05_cell_fate.ipynb
hds-sandbox/scRNASeq_course
21de29197979562e99ee2080ca41479b033384ee
[ "Apache-2.0" ]
3
2022-03-24T14:50:49.000Z
2022-03-25T12:09:55.000Z
Notebooks/Python/Part05_cell_fate.ipynb
hds-sandbox/scRNASeq_course
21de29197979562e99ee2080ca41479b033384ee
[ "Apache-2.0" ]
1
2022-03-02T13:18:52.000Z
2022-03-02T13:18:52.000Z
494.948966
283,700
0.93846
[ [ [ "# **Pseudotimes and cell fates**\n\n---------------------------\n\n**Motivation:**\n\nWhile clustering is an useful type of analysis to try giving a structure to the development of cells towards their final stage (spermatozoa), it does not give an understanding of how the development \"stretches\" from start to end. For example, a cluster can have many cells and look \"big\" on UMAP, but actually its variability in terms of gene expressions could be low. Also, a developmental process can branches towards different ends (cell fates) or developmental checkpoints (e.g. stages where damaged cells express specific genes for apoptosis/cell death). Pseudotime and cell fates analysis can be used to hgihlight exactly those processes.\n- **Pseudotimes** assigns to each cell the value of a timeline, starting from 0 for the cells at the beginning of the development. This value is purely a reference for ordering the cells development, but pseudotimes at specific stages can be assigned to real times, using previous biological knowledge.\n- **Cell fates analysis** looks at the PCA projection of the data and the pseudotime of each data point on the PCA. From this, it tries to create a tree connecting the cells, so that the end branches of the tree are different end points or stages of the developmental process.\n\n\n![](https://raw.githubusercontent.com/hds-sandbox/scRNASeq_course/main/develop/python/img/differentiation.png)\n\n*Figure: cell fates tree on a 3D pca plot. Circles represent the middle point of each cluster. From Perredaeau et al. (2017)*\n\n---------------------------\n\n**Learning objectives:**\n- Understand and determine the pseudotimes on a single cell dataset\n- Infer cell fates and distinguish between differentiation stages or actual final developmental stages\n- Compare gene expressions along differentiation\n- Cluster genes with similar gene expression\n----------------\n**Execution time: 45 minutes**\n\n---------------", "_____no_output_____" ], [ "***Import packages***", "_____no_output_____" ] ], [ [ "import scanpy as sc\nimport pandas as pd\nimport scvelo as scv\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport sklearn\nimport anndata as ad", "_____no_output_____" ], [ "import rpy2.rinterface_lib.callbacks\nimport logging\n\nfrom rpy2.robjects import pandas2ri\nimport anndata2ri\n\n# Ignore R warning messages\n#Note: this can be commented out to get more verbose R output\nrpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR)\n\n# Automatically convert rpy2 outputs to pandas dataframes\npandas2ri.activate()\nanndata2ri.activate()\n\n#import os\n#os.environ['R_HOME'] = '../../../scrna-environment/lib/R/' #path to your R installation\n\n%load_ext rpy2.ipython", "_____no_output_____" ], [ "%%R\n.libPaths( c( \"../../../sandbox_scRNA_testAndFeedback/scrna-environment/lib/R/library/\" ) )", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "***Read data***", "_____no_output_____" ] ], [ [ "sample = sc.read('../../Data/notebooks_data/sample_123.filt.norm.red.clst.2.h5ad')", "WARNING: Your filename has more than two extensions: ['.filt', '.norm', '.red', '.clst', '.2', '.h5ad'].\nOnly considering the two last: ['.2', '.h5ad'].\nWARNING: Your filename has more than two extensions: ['.filt', '.norm', '.red', '.clst', '.2', '.h5ad'].\nOnly considering the two last: ['.2', '.h5ad'].\n" ] ], [ [ "## Calculate pseudotimes and cell fates", "_____no_output_____" ], [ "We want to calculate pseudotimes on the spermatogenic process. We exclude the somatic cells from.", "_____no_output_____" ] ], [ [ "cellsToKeep = [ i not in ['Somatic'] for i in sample.obs['clusters_spc'] ]\nsample = sample[ cellsToKeep, : ].copy()", "_____no_output_____" ] ], [ [ "we use the `python` package `palantir`. There will be some annoying warning messages sometimes in this notebook when using `palantir`, but they are just warnings related to font characters. Nothing to worry about.", "_____no_output_____" ] ], [ [ "%%capture --no-stdout\nimport palantir\npalantir.core.random.seed( a=12345 ) #define random_state (here called 'a')", "_____no_output_____" ] ], [ [ "we create a table (`pandas` dataframe) with the logarithm of the corrected UMI matrix, since `palantir` needs logarithmized raw counts in input", "_____no_output_____" ] ], [ [ "palantir_data = pd.DataFrame(np.log1p(sample.layers['umi_sct'].todense()),\n index=sample.obs_names,\n columns=sample.var_names)", "_____no_output_____" ] ], [ [ "Instead of letting the package calculate the PCA (without any form of datasets integration), we use our integrated PCA.", "_____no_output_____" ] ], [ [ "pca_projections = pd.DataFrame( sample.obsm['X_pca'][:,0:15].copy(),\n index=sample.obs_names ) ", "_____no_output_____" ] ], [ [ "Now we will infer the pseudotimes and related cell fates. We have to provide where the differentiation process starts from. In our case, we will choose one of the cells in the cluster `SpermatogoniaA`. Then `Palantir` will assign the pseudotimes=0 to the most appropriate cell in the cluster.\nNote the option `num_waypoints=100` in the last command. This option will use a certain number of cells to build the tree from which to calculate pseudotimes and cell fates. it is suggested to use only a portion of cells from the dataset, since using all cells will make you experience the inference of many cell fates that are mostly due to noise. In other words, you will build a tree with some tiny branches that will be detected as cellular fates. ", "_____no_output_____" ] ], [ [ "ORIGIN_STATE = 'SpermatogoniaA' #where to start\nsc.tl.diffmap(sample)\ndiffusionMap = pd.DataFrame(sample.obsm['X_diffmap'][:,1::], \n index=sample.obs_names,\n columns = [str(i) for i in range(sample.obsm['X_diffmap'].shape[1]-1)])\n#apply palantir\nstart_cell = str(sample[sample.obs['clusters_spc'] == ORIGIN_STATE].obs_names[0]) #assignment of diferentiation start\npr_res = palantir.core.run_palantir( diffusionMap, early_cell=start_cell, num_waypoints=1000) #fate detection", "Sampling and flocking waypoints...\nTime for determining waypoints: 0.009104061126708984 minutes\nDetermining pseudotime...\nShortest path distances using 30-nearest neighbor graph...\n" ] ], [ [ "We save pseudotimes in our dataset and plot them on UMAP", "_____no_output_____" ] ], [ [ "sample.obs['pseudotime'] = pr_res.pseudotime", "_____no_output_____" ], [ "sc.pl.umap( sample, color=['clusters_spc','pseudotime'], \n legend_loc='on data', \n legend_fontsize=16,\n ncols=2 )", "findfont: Font family ['Bitstream Vera Sans'] not found. Falling back to DejaVu Sans.\nfindfont: Font family ['Bitstream Vera Sans'] not found. Falling back to DejaVu Sans.\nfindfont: Font family ['Bitstream Vera Sans'] not found. Falling back to DejaVu Sans.\n" ] ], [ [ "We can look at how pseudotimes are distributed into each cluster. It seems the variability of pseudotimes increases along spermatogenesis with some oscillations. This can mean more variability in the expression of genes in the later clusters (but does not mean that there are more genes that are expressed). Note that there are considerable overlapping in pseudotimes. This is due to the fact that pseudotimes have a spike around Pachytene-Diplotene stages.", "_____no_output_____" ] ], [ [ "cluster_names = [i for i in ['SpermatogoniaA', 'SpermatogoniaB', 'Leptotene', 'Zygotene', \n 'Pachytene', 'SpermatocitesII', 'Diplotene', 'RoundSpermatids',\n 'ElongSpermatids'] if i in np.array(sample.obs['clusters_spc']) ]\nsc.pl.violin(sample, keys='pseudotime', groupby='clusters_spc', rotation=90,\n order=cluster_names)", "_____no_output_____" ] ], [ [ "## Analysis of cell fates", "_____no_output_____" ], [ "we can see how many fates we have. For each fate, there is the barcode of the cell best representing a differentiation stage. In some cases you can have more than two fates", "_____no_output_____" ] ], [ [ "fates = list(pr_res.branch_probs.columns)", "_____no_output_____" ], [ "fates", "_____no_output_____" ] ], [ [ "We can plot them on the UMAP plot. One fate is clearly the end of spermatogenesis, where cells become elongated spermatids and spermatozoa.There is another fate, probably due to something happening during meiosis. ", "_____no_output_____" ] ], [ [ "#necessary because palantir somewhat disables plotting on notebooks\n%matplotlib inline", "_____no_output_____" ], [ "f, ax = plt.subplots(1,1)\n\nsc.pl.umap( sample,\n legend_loc='on data', \n legend_fontsize=16, ax=ax, show=False)\n\ncoordinates = sample[fates].obsm['X_umap']\nax.plot(coordinates[:,0],coordinates[:,1],'o',markersize=12) \nfor i in range(coordinates.shape[0]):\n ax.text(coordinates[i,0]-1,coordinates[i,1]-2, f'Fate {i}')\n ax.set_title(\"Inferred cell fates\")\nplt.show()", "findfont: Font family ['Bitstream Vera Sans'] not found. Falling back to DejaVu Sans.\n" ] ], [ [ "We rename the fates instead of using cell barcodes as we plotted above", "_____no_output_____" ] ], [ [ "fates = np.array( pr_res.branch_probs.columns )\nfor i in range(coordinates.shape[0]):\n fates[i] = f'Fate {i}'\npr_res.branch_probs.columns = fates ", "_____no_output_____" ] ], [ [ "We save in our data the probability that each cell differentiate into one of the fates", "_____no_output_____" ] ], [ [ "for i in pr_res.branch_probs.columns:\n sample.obs[f'branch_prob_{i}'] = pr_res.branch_probs[i]", "_____no_output_____" ] ], [ [ "### Recognizing branchings or developmental stages", "_____no_output_____" ], [ "A good practice is to look at the probabilities of ending in a fate for each cluster. There are two possible scenarios:\n- only one fate: all cells have probability 1 of ending at a specific cell fate\n- more than one cell fate: some fates are actual branchings of the developmental process, and only some cells will have a probability of ending up in those branchings. Some other fates are just midpoints of the developmental process. Here, they will absorb with probability 1 entire sections of the dataset.\n\n\nWe plot below the probability of each cell (seen by cluster) to end up in a specific fate. Each violin plot corresponds to a single fate.", "_____no_output_____" ] ], [ [ "for i in range(coordinates.shape[0]):\n x = sc.pl.violin(sample, groupby='clusters_spc', keys=f'branch_prob_Fate {i}', rotation=90,\n order=cluster_names, ylabel=f'Probability of Fate {i}')\n", "_____no_output_____" ] ], [ [ "### Exploring gene expression and clusters", "_____no_output_____" ], [ "Here is a script that plots gene expressions of your choice along pseudotimes. This allows you to see how specific genes behave differently for different fates. Expressions are modeled using the fate probabilities we plotted above. ", "_____no_output_____" ] ], [ [ "import palantir", "_____no_output_____" ], [ "GENES = ['PIWIL1','PIWIL2','PIWIL3']\nGENES = np.intersect1d(GENES, sample.var_names)\nNGENES = len(GENES)\nCLUSTERS = sample.obs['clusters_spc']\nPSEUDOTIMES = sample.obs['pseudotime']\ngene_trends = palantir.presults.compute_gene_trends(pr_res, \n pd.DataFrame(sample.layers['norm_sct'], \n index=sample.obs_names,\n columns=sample.var_names).loc[:, GENES] \n )\n\nplt.rcParams['figure.figsize']=(12,4*int(NGENES))\nfig, ax = plt.subplots(NGENES,1)\n\nc = CLUSTERS\nx = PSEUDOTIMES\n\n\nif(NGENES==1):\n x2 = []\n t = []\n style = []\n for FATE in list(gene_trends.keys()):\n ARRAY = np.array( gene_trends[FATE]['trends'].loc[GENES[0],:].index )\n for i in ARRAY:\n idx = np.argmin(np.abs(x - i))\n x2.append(c[idx])\n t.append(i)\n if(len(style)==0):\n style = np.tile( FATE, 500 )\n y = np.array(gene_trends[FATE]['trends'].loc[GENES[0],:])\n else:\n style = np.append(arr=style, \n values=np.tile( FATE, 500 ))\n y = np.append(arr=y, \n values=np.array(gene_trends[FATE]['trends'].loc[GENES[0],:]))\n \n sns.lineplot(x=t,\n y=y, ci=False, \n hue=x2, ax=ax, style = style,\n linewidth = 5)\n ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n ax.set(xlabel = 'Pseudotime', ylabel=GENES[0]) \n \nif(NGENES>1): \n for GENE_NR in range(NGENES):\n style = []\n x2 = []\n t = []\n for FATE in list(gene_trends.keys()):\n ARRAY = np.array( gene_trends[FATE]['trends'].loc[GENES[GENE_NR],:].index )\n for i in ARRAY:\n idx = np.argmin(np.abs(x - i))\n x2.append(c[idx])\n t.append(i)\n if(len(style)==0):\n style = np.tile( FATE, 500 )\n y = np.array(gene_trends[FATE]['trends'].loc[GENES[GENE_NR],:])\n else:\n style = np.append(arr=style, \n values=np.tile( FATE, 500 ))\n y = np.append(arr=y, \n values=np.array(gene_trends[FATE]['trends'].loc[GENES[GENE_NR],:]))\n sns.lineplot(x=t,\n y=y, ci=False, \n hue=x2, ax=ax[GENE_NR],\n style = style, linewidth = 5, legend=GENE_NR==0)\n ax[GENE_NR].set(ylabel = GENES[GENE_NR])\n if(GENE_NR==0):\n ax[0].legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n ax[0].set_title(f'Gene expression along the fates:\\n{list(gene_trends.keys())}')\n ax[GENE_NR].set(xlabel = 'Pseudotime') \n\nplt.rcParams['figure.figsize']=(6,6)", "Fate 0\n" ] ], [ [ "**Gene clustering:**\nA last thing you can do is to cluster together genes that have the same expression patterns. We can try to do this for each different fate. Here you can only look at one fate at a time", "_____no_output_____" ], [ "For making the clustering faster, we cluster together only the differentially expressed genes we found in the previous analysis. However, below you can define the variable `genes` as any list of genes. You can for example read them from a text file, or you can use all possible genes by writing `genes=list(sample.var_names)`", "_____no_output_____" ] ], [ [ "genes = []\nfor names in sample.uns['DE_clusters_spc']['names']:\n genes.append( list( names ) )", "_____no_output_____" ], [ "genes = np.unique(np.ravel(genes))", "_____no_output_____" ] ], [ [ "model the gene expression along pseudotime", "_____no_output_____" ] ], [ [ "gene_trends = palantir.presults.compute_gene_trends( pr_res, \n pd.DataFrame(sample[ :, genes ].layers['norm_sct'], \n index=sample[ :, genes ].obs_names,\n columns=sample[ :, genes ].var_names) )", "Fate 0\n" ] ], [ [ "cluster the expressions together and plot clusters. If you see that there should be more clusters than the algorithm calculates, you can try to increase their number by changing the value of `k=20`. Usually, you should see a lot of genes expressed (in gray colour) differently from their averaged expression (in blue colour)", "_____no_output_____" ] ], [ [ "trends = gene_trends['Fate 0']['trends']\ngene_clusters = palantir.presults.cluster_gene_trends(trends, k=20)", "Finding 20 nearest neighbors using minkowski metric and 'auto' algorithm\nNeighbors computed in 0.16769909858703613 seconds\nJaccard graph constructed in 1.4810302257537842 seconds\nWrote graph to binary file in 0.008389949798583984 seconds\nRunning Louvain modularity optimization\nAfter 1 runs, maximum modularity is Q = 0.715314\nAfter 2 runs, maximum modularity is Q = 0.719889\nLouvain completed 22 runs in 2.799499988555908 seconds\nSorting communities by size, please wait ...\nPhenoGraph completed in 6.446572303771973 seconds\n" ], [ "palantir.plot.plot_gene_trend_clusters(trends, gene_clusters)", "findfont: Font family ['Bitstream Vera Sans'] not found. Falling back to DejaVu Sans.\nfindfont: Font family ['Bitstream Vera Sans'] not found. Falling back to DejaVu Sans.\n" ] ], [ [ "Here is a script to produce the plot as above, with averaged expression of each gene cluster coloured by cell types, together with confidence bands. It takes some time to do all the plots, so be patient.", "_____no_output_____" ] ], [ [ "GENE_CLST = np.array(gene_clusters)\nUNIQUE_CLST = np.sort(np.unique(GENE_CLST))\nCLST_NR = int(len(UNIQUE_CLST))\nCLUSTERS = sample.obs['clusters_spc']\nPSEUDOTIMES = sample.obs['pseudotime']\n\nplt.rcParams['figure.figsize']=(12,4*CLST_NR)\nfig, ax = plt.subplots(CLST_NR,1)\n\nc = CLUSTERS\nx = PSEUDOTIMES\n\nif(CLST_NR==1):\n t = []\n x2 = []\n ARRAY = np.array( trends.columns )\n for i in ARRAY:\n idx = np.argmin(np.abs(x - i))\n x2.append(c[idx])\n t.append(i)\n \n x=np.tile(ARRAY,trends.loc[GENE_CLST==0,:].shape[0])\n y=np.array(trends.loc[GENE_CLST==0,:]).ravel()\n hue=np.tile(x2,trends.loc[GENE_CLST==0,:].shape[0])\n ax = sns.lineplot(x=x, y=y, hue=hue)\n \n sns.lineplot(x=x, y=y, hue=hue, \n ax=ax, linewidth = 5)\n ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n \n \nif(CLST_NR>1):\n ARRAY = np.array( trends.columns )\n t = []\n x2 = []\n for i in ARRAY:\n idx = np.argmin(np.abs(x - i))\n x2.append(c[idx])\n t.append(i)\n for CLST_NR in UNIQUE_CLST:\n x=np.tile(ARRAY,trends.loc[GENE_CLST==CLST_NR,:].shape[0])\n y=np.array(trends.loc[GENE_CLST==CLST_NR,:]).ravel()\n hue=np.tile(x2,trends.loc[GENE_CLST==CLST_NR,:].shape[0])\n \n sns.lineplot(x=x, y=y, hue=hue,\n ax=ax[CLST_NR], linewidth = 5, legend=CLST_NR==0)\n ax[CLST_NR].set(ylabel = f'Cluster {CLST_NR}')\n if(CLST_NR==0):\n ax[CLST_NR].legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n ax[CLST_NR].set_title('Gene expression clustering for cell fate 0')\n ax[CLST_NR].set(xlabel = 'Pseudotime')\n \nplt.rcParams['figure.figsize']=(6,6)", "_____no_output_____" ] ], [ [ "you can always look at the genes in a specific cluster. In this case, each cluster should be quite matching the differentially expressed genes for a cell type, since we grouped together differentially expressed genes", "_____no_output_____" ] ], [ [ "gene_clusters[gene_clusters==5]", "_____no_output_____" ] ], [ [ "We also want to save the dataset (including somatic cells) with pseudotimes. To do this we reopen the whole dataset and assign pseudotimes equal to 0 to the somatic cell.", "_____no_output_____" ] ], [ [ "whole_sample = sc.read('../../Data/notebooks_data/sample_123.filt.norm.red.clst.2.h5ad')", "WARNING: Your filename has more than two extensions: ['.filt', '.norm', '.red', '.clst', '.2', '.h5ad'].\nOnly considering the two last: ['.2', '.h5ad'].\nWARNING: Your filename has more than two extensions: ['.filt', '.norm', '.red', '.clst', '.2', '.h5ad'].\nOnly considering the two last: ['.2', '.h5ad'].\n" ], [ "times = pd.Series(sample.obs['pseudotime'], index=sample.obs_names)\nwhole_times = pd.Series(index=whole_sample.obs_names)\nnames = sample.obs_names\nwhole_names = whole_sample.obs_names\nwhole_times = [ times[i] if i in names else 0 for i in whole_names ]", "_____no_output_____" ], [ "whole_sample.obs['pseudotimes'] = whole_times", "_____no_output_____" ], [ "whole_sample.write('../../Data/notebooks_data/sample_123.filt.norm.red.clst.2.times.h5ad')", "_____no_output_____" ] ], [ [ "## Wrapping up", "_____no_output_____" ], [ "This notebooks shows how to do pseudotimes analysis and exploring cell fates and gene expressions.\nWe have seen how to distinguish between an actual differentiation branch and a differentiation stage. Basically, all cells before (i.e. earlier in pseudotime) a differentiation stage will be associated to such stage with high probability, because they must go through that developmental stage. Finding a developmental stage around meiosis in spermatogenic samples is a common results across single cell datasets of many species (primates, humans, mice).\nUsing the `palantir` software, we can look at differences between gene expressions for different fates, and cluster together genes of interest for further analysis.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
4af3d0e0b0177774ce8715cf703ccf5f9e350a45
14,268
ipynb
Jupyter Notebook
2.dataProcessing/dataProcessing.ipynb
QiujieDong/ChineseFood
8bff579c2c1812798d17b1ce2861c7d962d3ef69
[ "MIT" ]
1
2021-03-18T07:30:05.000Z
2021-03-18T07:30:05.000Z
2.dataProcessing/dataProcessing.ipynb
QiujieDong/ChineseFood
8bff579c2c1812798d17b1ce2861c7d962d3ef69
[ "MIT" ]
null
null
null
2.dataProcessing/dataProcessing.ipynb
QiujieDong/ChineseFood
8bff579c2c1812798d17b1ce2861c7d962d3ef69
[ "MIT" ]
null
null
null
34.133971
125
0.526493
[ [ [ "# Data Processing\n\nThe project has five steps:\n- delet irregular (too large or small (no data)) and non-image data\n- remove duplicate image\n- remove irrelevant image\n- split dataset: create classes.txt, train.txt, test.txt\n- rename images", "_____no_output_____" ], [ "### Deleting irragular images", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport imghdr\n\nclass ImageDelet():\n def __init__(self):\n self.path = '/home/gpu/Project/dataProcess/bun/'\n self.imageTypes = ['.jpg', '.jpeg', '.png', '.gif']\n \n delet_count = 0\n \n def delet(self):\n filelist = os.listdir(self.path)\n total_num = len(filelist)\n\n delet_count = 0\n\n for item in filelist:\n src = os.path.join(os.path.abspath(self.path), item)\n image_type = os.path.splitext(src)[-1]\n\n if not imghdr.what(src): \n os.remove(src) # delet corrupted image\n delet_count += 1 \n elif image_type in self.imageTypes:\n imageSize = sys.getsizeof(src) # most abnormal image's getsizeof will exceed 150\n# print(imageSize)\n if imageSize > 150:\n os.remove(src)\n delet_count += 1 \n else:\n continue\n else:\n os.remove(src) # delet non-image data \n delet_count += 1 \n print ('Total: %d\\nDelet: %d' % (total_num, delet_count))", "_____no_output_____" ], [ "deletImage = ImageDelet()\ndeletImage.delet()", "Total: 19\nDelet: 0\n" ] ], [ [ "### Renaming the images downloaded by the web crawler.", "_____no_output_____" ], [ "### Renaming the images which have been processed.", "_____no_output_____" ] ], [ [ "class ImageRename():\n def __init__(self):\n self.path = '/home/gpu/Project/dataProcess/bun/'\n\n def rename(self):\n filelist = os.listdir(self.path)\n filelist.sort() # if the filelist is not sorted, some file will be replaced when repeating rename result in \n total_num = len(filelist)\n\n rename_count = 0\n\n for item in filelist:\n src = os.path.join(os.path.abspath(self.path), item)\n image_type = os.path.splitext(src)[-1]\n\n# if image_type in self.imageTypes:\n# dst = os.path.join(os.path.abspath(self.path), format(str(rename_count), '0>4s') + '.jpg')\n dst = os.path.join(os.path.abspath(self.path), str(rename_count).zfill(4) + image_type)\n os.rename(src, dst)\n print ('converting %s to %s ...' % (src, dst))\n rename_count += 1\n# elif os.path.isdir(src):\n# continue\n# else:\n# os.remove(src)\n# delet_count += 1\n \n print ('Total: %d\\nRename: %d' % (total_num, rename_count))", "_____no_output_____" ], [ "newName = ImageRename()\nnewName.rename()", "converting /home/gpu/Project/dataProcess/bun/0000.jpeg to /home/gpu/Project/dataProcess/bun/0000.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0001.jpeg to /home/gpu/Project/dataProcess/bun/0001.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0002.jpeg to /home/gpu/Project/dataProcess/bun/0002.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0003.jpeg to /home/gpu/Project/dataProcess/bun/0003.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0004.jpeg to /home/gpu/Project/dataProcess/bun/0004.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0005.jpeg to /home/gpu/Project/dataProcess/bun/0005.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0006.jpeg to /home/gpu/Project/dataProcess/bun/0006.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0007.jpeg to /home/gpu/Project/dataProcess/bun/0007.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0008.jpeg to /home/gpu/Project/dataProcess/bun/0008.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0009.jpeg to /home/gpu/Project/dataProcess/bun/0009.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0010.jpeg to /home/gpu/Project/dataProcess/bun/0010.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0011.jpeg to /home/gpu/Project/dataProcess/bun/0011.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0012.jpeg to /home/gpu/Project/dataProcess/bun/0012.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0013.jpeg to /home/gpu/Project/dataProcess/bun/0013.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0014.jpeg to /home/gpu/Project/dataProcess/bun/0014.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0015.jpeg to /home/gpu/Project/dataProcess/bun/0015.jpeg ...\nconverting /home/gpu/Project/dataProcess/bun/0016.jpg to /home/gpu/Project/dataProcess/bun/0016.jpg ...\nconverting /home/gpu/Project/dataProcess/bun/0017.jpg to /home/gpu/Project/dataProcess/bun/0017.jpg ...\nconverting /home/gpu/Project/dataProcess/bun/0018.jpeg to /home/gpu/Project/dataProcess/bun/0018.jpeg ...\nTotal: 19\nRename: 19\n" ] ], [ [ "### Removing the duplicate images ", "_____no_output_____" ] ], [ [ "# Perceptual Hash Algorithm - dHash\nimport cv2\n\ndef dhash(image):\n # convert image to 8*8\n image = cv2.resize(image, (9, 8), interpolation=cv2.INTER_CUBIC)\n # convert image to grayscale\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n dhash_str = ''\n for i in range(8):\n for j in range(8):\n if gray[i, j] > gray[i, j + 1]:\n dhash_str = dhash_str + '1'\n else:\n dhash_str = dhash_str + '0'\n result = ''\n for i in range(0, 64, 4):\n result += ''.join('%x' % int(dhash_str[i: i + 4], 2))\n return result\n\n# calculate the difference between hash1 and hash2\ndef campHash(hash1, hash2):\n n = 0\n # If the hash length is different, the comparison cannot be made, and -1 is returned.\n if len(hash1) != len(hash2):\n return -1\n # If the hash length is same, traversing hash1 ahd hash2 for comparison.\n for i in range(len(hash1)):\n if hash1[i] != hash2[i]:\n n = n + 1\n return n", "_____no_output_____" ], [ "image1 = cv2.imread('/home/gpu/Project/dataProcess/bun/0017.jpg')\nimage2 = cv2.imread('/home/gpu/Project/dataProcess/bun/0018.jpeg')\n\nhash1 = dhash(image1)\nhash2 = dhash(image2)\n\ndistance_hash = campHash(hash1, hash2)\n\n# if campHash == 0, it means that the two images are duplicate images.\nimage2_path = '/home/gpu/Project/dataProcess/bun/0012.jpeg'\nif distance_hash == 0:\n os.remove(image2_path)", "_____no_output_____" ] ], [ [ "### Removing the irrelevant images", "_____no_output_____" ] ], [ [ "# Perceptual Hash Algorithm - dHash\nimport cv2\n\ndef dhash(image):\n # convert image to 8*8\n image = cv2.resize(image, (9, 8), interpolation=cv2.INTER_CUBIC)\n # convert image to grayscale\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n dhash_str = ''\n for i in range(8):\n for j in range(8):\n if gray[i, j] > gray[i, j + 1]:\n dhash_str = dhash_str + '1'\n else:\n dhash_str = dhash_str + '0'\n result = ''\n for i in range(0, 64, 4):\n result += ''.join('%x' % int(dhash_str[i: i + 4], 2))\n return result\n\n# calculate the difference between hash1 and hash2\ndef campHash(hash1, hash2):\n n = 0\n # If the hash length is different, the comparison cannot be made, and -1 is returned.\n if len(hash1) != len(hash2):\n return -1\n # If the hash length is same, traversing hash1 ahd hash2 for comparison.\n for i in range(len(hash1)):\n if hash1[i] != hash2[i]:\n n = n + 1\n return n", "_____no_output_____" ], [ "image1 = cv2.imread('/home/gpu/Project/dataProcess/bun/0017.jpg')\nimage2 = cv2.imread('/home/gpu/Project/dataProcess/bun/0013.jpeg')\n\nhash1 = dhash(image1)\nhash2 = dhash(image2)\n\ndistance_hash = campHash(hash1, hash2)\n\n# if campHash > 10, it means that the two images are different classes.\nimage2_path = '/home/gpu/Project/dataProcess/bun/0012.jpeg'\nif distance_hash > 10:\n os.remove(image2_path)", "_____no_output_____" ] ], [ [ "### Spliting dataset", "_____no_output_____" ], [ "#### Generate the train.txt, test.txt, and classes.txt.", "_____no_output_____" ] ], [ [ "dataset_path = '/home/gpu/Project/dataProcess/'\n\ndef gengrateClass(dataset_path):\n filelist = os.listdir(dataset_path)\n \n for file_name in filelist:\n if file_name.startswith('.'):\n filelist.remove(file_name)\n \n filelist.sort()\n \n class_savePath = '/home/gpu/Project/dataProcess/meta/class.txt'\n \n # If filename does not exist, it will be created automatically. \n #'w' means to write data. The original data in the file will be cleared before writing!\n with open(class_savePath,'w') as f:\n for file_name in filelist:\n f.write(file_name)\n f.write('\\n')\n \n\ngengrateClass(dataset_path)", "_____no_output_____" ], [ "import math\ndef splitDataset(dataset_path):\n filelist = os.listdir(dataset_path)\n \n for file_name in filelist:\n if file_name.startswith('.'):\n filelist.remove(file_name)\n \n filelist.sort()\n \n train_savePath = '/home/gpu/Project/dataProcess/meta/train.txt'\n test_savePath = '/home/gpu/Project/dataProcess/meta/test.txt'\n \n for file_name in filelist:\n image_path = dataset_path + file_name\n image_list = os.listdir(image_path)\n \n for image_name in image_list:\n if image_name.startswith('.'):\n image_list.remove(image_name)\n\n image_size = len(image_list)\n train_size = math.ceil(image_size * 0.75)\n \n # If filename does not exist, it will be created automatically. \n #'w' means to append data. The original data in the file will not be cleared.\n with open(train_savePath,'a') as train:\n for file_name in image_list[:train_size]:\n train.write(file_name)\n train.write('\\n')\n with open(test_savePath,'a') as test:\n for file_name in image_list[train_size:]:\n test.write(file_name)\n test.write('\\n')\n\nsplitDataset(dataset_path)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
4af3d148d9cbfabcaa497828270fb15bfc3458fa
319,091
ipynb
Jupyter Notebook
notebooks/deep-regression.ipynb
MiloVentimiglia/bayesian-analysis-recipes
09097db96a0ade9b1ba3e304ab08334af734c384
[ "MIT" ]
1
2018-08-25T19:48:12.000Z
2018-08-25T19:48:12.000Z
notebooks/deep-regression.ipynb
MiloVentimiglia/bayesian-analysis-recipes
09097db96a0ade9b1ba3e304ab08334af734c384
[ "MIT" ]
null
null
null
notebooks/deep-regression.ipynb
MiloVentimiglia/bayesian-analysis-recipes
09097db96a0ade9b1ba3e304ab08334af734c384
[ "MIT" ]
null
null
null
436.512996
233,772
0.921486
[ [ [ "import pymc3 as pm\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport theano.tensor as tt\nimport theano\n\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'", "WARNING (theano.sandbox.cuda): The cuda backend is deprecated and will be removed in the next release (v0.10). Please switch to the gpuarray backend. You can get more information about how to switch at this URL:\n https://github.com/Theano/Theano/wiki/Converting-to-the-new-gpu-back-end%28gpuarray%29\n\nUsing gpu device 0: GeForce GTX 1080 (CNMeM is disabled, cuDNN Mixed dnn version. The header is from one version, but we link with a different version (5110, 6021))\n" ], [ "df = pd.read_csv('../datasets/bikes/hour.csv')\ndf\n\nfeature_cols = ['workingday', 'holiday', 'temp', 'atemp', 'hum', 'windspeed']\nout_col = ['cnt']\ndf[out_col]", "_____no_output_____" ], [ "X = pm.floatX(df[feature_cols])\nY = pm.floatX(df[out_col].apply(np.log10))\nn_hidden = X.shape[1]\n\nwith pm.Model() as nn_model:\n w1 = pm.Normal('w1', mu=0, sd=1, shape=(X.shape[1], n_hidden))\n w2 = pm.Normal('w2', mu=0, sd=1, shape=(n_hidden, 1))\n \n b1 = pm.Normal('b1', mu=0, sd=1, shape=(n_hidden,))\n b2 = pm.Normal('b2', mu=0, sd=1, shape=(1,))\n \n a1 = pm.Deterministic('a1', tt.nnet.relu(tt.dot(X, w1) + b1))\n a2 = pm.Deterministic('a2', tt.dot(a1, w2) + b2)\n \n output = pm.Normal('likelihood', mu=a2, observed=Y)", "_____no_output_____" ], [ "with pm.Model() as three_layer_model:\n w1 = pm.Normal('w1', mu=0, sd=1, shape=(X.shape[1], n_hidden))\n w2 = pm.Normal('w2', mu=0, sd=1, shape=(n_hidden, n_hidden))\n w3 = pm.Normal('w3', mu=0, sd=1, shape=(n_hidden, 1))\n \n b1 = pm.Normal('b1', mu=0, sd=1, shape=(n_hidden,))\n b2 = pm.Normal('b2', mu=0, sd=1, shape=(n_hidden,))\n b3 = pm.Normal('b3', mu=0, sd=1, shape=(1,))\n \n a1 = pm.Deterministic('a1', tt.nnet.relu(tt.dot(X, w1) + b1))\n a2 = pm.Deterministic('a2', tt.nnet.relu(tt.dot(a1, w2) + b2))\n a3 = pm.Deterministic('a3', tt.dot(a2, w3) + b3)\n \n sd = pm.HalfCauchy('sd', beta=1)\n \n output = pm.Normal('likelihood', mu=a3, sd=sd, observed=Y)", "_____no_output_____" ], [ "with pm.Model() as linreg_model:\n w1 = pm.Normal('w1', mu=0, sd=1, shape=(X.shape[1], 1))\n b1 = pm.Normal('b1', mu=0, sd=1, shape=(1,))\n a1 = pm.Deterministic('a1', tt.dot(X, w1) + b1)\n \n sd = pm.HalfCauchy('sd', beta=1)\n \n output = pm.Normal('likelihood', mu=a1, sd=sd, observed=Y)", "_____no_output_____" ], [ "with linreg_model:\n s = theano.shared(pm.floatX(1.1))\n inference = pm.ADVI(cost_part_grad_scale=s, learning_rate=.01)\n approx = pm.fit(200000, method=inference)", "Average Loss = 16,808: 9%|▉ | 17950/200000 [01:09<11:44, 258.57it/s] \nInterrupted at 17,974 [8%]: Average Loss = 28,541\n" ], [ "plt.plot(inference.hist)", "_____no_output_____" ], [ "with linreg_model:\n trace = approx.sample(2000)", "_____no_output_____" ], [ "pm.traceplot(trace, varnames=['w1', 'b1'])", "_____no_output_____" ], [ "with linreg_model:\n samps = pm.sample_ppc(trace)", "100%|██████████| 2000/2000 [00:02<00:00, 791.44it/s]\n" ], [ "samps['likelihood'].std(axis=0)", "_____no_output_____" ], [ "samps['likelihood'].mean(axis=0)", "_____no_output_____" ], [ "from sklearn.metrics import mean_squared_error as mse\n\nmse(Y, samps['likelihood'].mean(axis=0))", "_____no_output_____" ], [ "plt.scatter(samps['likelihood'].mean(axis=0).squeeze(), Y.values)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af3d68b04facf3d07934341dcbac5b0efaad762
41,001
ipynb
Jupyter Notebook
site/en-snapshot/federated/tutorials/federated_learning_for_text_generation.ipynb
yashk2810/tf-docs-l10n
922698ceb5de3c4ccd19123cc3c38da5dc0c4882
[ "Apache-2.0" ]
null
null
null
site/en-snapshot/federated/tutorials/federated_learning_for_text_generation.ipynb
yashk2810/tf-docs-l10n
922698ceb5de3c4ccd19123cc3c38da5dc0c4882
[ "Apache-2.0" ]
null
null
null
site/en-snapshot/federated/tutorials/federated_learning_for_text_generation.ipynb
yashk2810/tf-docs-l10n
922698ceb5de3c4ccd19123cc3c38da5dc0c4882
[ "Apache-2.0" ]
null
null
null
36.284071
764
0.532231
[ [ [ "##### Copyright 2019 The TensorFlow Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ] ], [ [ "# Federated Learning for Text Generation", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/federated/tutorials/federated_learning_for_text_generation\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/federated/blob/v0.15.0/docs/tutorials/federated_learning_for_text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/federated/blob/v0.15.0/docs/tutorials/federated_learning_for_text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>", "_____no_output_____" ], [ "**NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federated#compatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.\n\nThis tutorial builds on the concepts in the [Federated Learning for Image Classification](federated_learning_for_image_classification.ipynb) tutorial, and demonstrates several other useful approaches for federated learning.\n\nIn particular, we load a previously trained Keras model, and refine it using federated training on a (simulated) decentralized dataset. This is practically important for several reasons . The ability to use serialized models makes it easy to mix federated learning with other ML approaches. Further, this allows use of an increasing range of pre-trained models --- for example, training language models from scratch is rarely necessary, as numerous pre-trained models are now widely available (see, e.g., [TF Hub](https://www.tensorflow.org/hub)). Instead, it makes more sense to start from a pre-trained model, and refine it using Federated Learning, adapting to the particular characteristics of the decentralized data for a particular application.\n\nFor this tutorial, we start with a RNN that generates ASCII characters, and refine it via federated learning. We also show how the final weights can be fed back to the original Keras model, allowing easy evaluation and text generation using standard tools.", "_____no_output_____" ] ], [ [ "#@test {\"skip\": true}\n!pip install --quiet --upgrade tensorflow_federated", "_____no_output_____" ], [ "import collections\nimport functools\nimport os\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nnp.random.seed(0)\n\n# Test the TFF is working:\ntff.federated_computation(lambda: 'Hello, World!')()", "_____no_output_____" ] ], [ [ "## Load a pre-trained model\n\nWe load a model that was pre-trained following the TensorFlow tutorial\n[Text generation using a RNN with eager execution](https://www.tensorflow.org/tutorials/sequences/text_generation). However,\nrather than training on [The Complete Works of Shakespeare](http://www.gutenberg.org/files/100/100-0.txt), we pre-trained the model on the text from the Charles Dickens'\n [A Tale of Two Cities](http://www.ibiblio.org/pub/docs/books/gutenberg/9/98/98.txt)\n and\n [A Christmas Carol](http://www.ibiblio.org/pub/docs/books/gutenberg/4/46/46.txt).\n \nOther than expanding the vocabularly, we didn't modify the original tutorial, so this initial model isn't state-of-the-art, but it produces reasonable predictions and is sufficient for our tutorial purposes. The final model was saved with `tf.keras.models.save_model(include_optimizer=False)`.\n \n We will use federated learning to fine-tune this model for Shakespeare in this tutorial, using a federated version of the data provided by TFF.\n\n", "_____no_output_____" ], [ "### Generate the vocab lookup tables", "_____no_output_____" ] ], [ [ "# A fixed vocabularly of ASCII chars that occur in the works of Shakespeare and Dickens:\nvocab = list('dhlptx@DHLPTX $(,048cgkoswCGKOSW[_#\\'/37;?bfjnrvzBFJNRVZ\"&*.26:\\naeimquyAEIMQUY]!%)-159\\r')\n\n# Creating a mapping from unique characters to indices\nchar2idx = {u:i for i, u in enumerate(vocab)}\nidx2char = np.array(vocab)", "_____no_output_____" ] ], [ [ "### Load the pre-trained model and generate some text", "_____no_output_____" ] ], [ [ "def load_model(batch_size):\n urls = {\n 1: 'https://storage.googleapis.com/tff-models-public/dickens_rnn.batch1.kerasmodel',\n 8: 'https://storage.googleapis.com/tff-models-public/dickens_rnn.batch8.kerasmodel'}\n assert batch_size in urls, 'batch_size must be in ' + str(urls.keys())\n url = urls[batch_size]\n local_file = tf.keras.utils.get_file(os.path.basename(url), origin=url) \n return tf.keras.models.load_model(local_file, compile=False)", "_____no_output_____" ], [ "def generate_text(model, start_string):\n # From https://www.tensorflow.org/tutorials/sequences/text_generation\n num_generate = 200\n input_eval = [char2idx[s] for s in start_string]\n input_eval = tf.expand_dims(input_eval, 0)\n text_generated = []\n temperature = 1.0\n\n model.reset_states()\n for i in range(num_generate):\n predictions = model(input_eval)\n predictions = tf.squeeze(predictions, 0)\n predictions = predictions / temperature\n predicted_id = tf.random.categorical(\n predictions, num_samples=1)[-1, 0].numpy()\n input_eval = tf.expand_dims([predicted_id], 0)\n text_generated.append(idx2char[predicted_id])\n\n return (start_string + ''.join(text_generated))", "_____no_output_____" ], [ "# Text generation requires a batch_size=1 model.\nkeras_model_batch1 = load_model(batch_size=1)\nprint(generate_text(keras_model_batch1, 'What of TensorFlow Federated, you ask? '))", "Downloading data from https://storage.googleapis.com/tff-models-public/dickens_rnn.batch1.kerasmodel\n16195584/16193984 [==============================] - 0s 0us/step\n16203776/16193984 [==============================] - 0s 0us/step\nWhat of TensorFlow Federated, you ask? She\ncame his desk was the Crown, to refer to whom he was true. The two tasting up all the outward freedom should be produced before them. That, his protest, no even she had spoken with the year, tow!\n" ] ], [ [ "## Load and Preprocess the Federated Shakespeare Data\n\nThe `tff.simulation.datasets` package provides a variety of datasets that are split into \"clients\", where each client corresponds to a dataset on a particular device that might participate in federated learning.\n\nThese datasets provide realistic non-IID data distributions that replicate in simulation the challenges of training on real decentralized data. Some of the pre-processing of this data was done using tools from the [Leaf project](https://arxiv.org/abs/1812.01097) ([github](https://github.com/TalwalkarLab/leaf)).", "_____no_output_____" ] ], [ [ "train_data, test_data = tff.simulation.datasets.shakespeare.load_data()", "_____no_output_____" ] ], [ [ "The datasets provided by `shakespeare.load_data()` consist of a sequence of\nstring `Tensors`, one for each line spoken by a particular character in a\nShakespeare play. The client keys consist of the name of the play joined with\nthe name of the character, so for example `MUCH_ADO_ABOUT_NOTHING_OTHELLO` corresponds to the lines for the character Othello in the play *Much Ado About Nothing*. Note that in a real federated learning scenario\nclients are never identified or tracked by ids, but for simulation it is useful\nto work with keyed datasets.\n\nHere, for example, we can look at some data from King Lear:", "_____no_output_____" ] ], [ [ "# Here the play is \"The Tragedy of King Lear\" and the character is \"King\".\nraw_example_dataset = train_data.create_tf_dataset_for_client(\n 'THE_TRAGEDY_OF_KING_LEAR_KING')\n# To allow for future extensions, each entry x\n# is an OrderedDict with a single key 'snippets' which contains the text.\nfor x in raw_example_dataset.take(2):\n print(x['snippets'])", "tf.Tensor(b'', shape=(), dtype=string)\ntf.Tensor(b'What?', shape=(), dtype=string)\n" ] ], [ [ "We now use `tf.data.Dataset` transformations to prepare this data for training the char RNN loaded above. \n", "_____no_output_____" ] ], [ [ "# Input pre-processing parameters\nSEQ_LENGTH = 100\nBATCH_SIZE = 8\nBUFFER_SIZE = 10000 # For dataset shuffling", "_____no_output_____" ], [ "# Construct a lookup table to map string chars to indexes,\n# using the vocab loaded above:\ntable = tf.lookup.StaticHashTable(\n tf.lookup.KeyValueTensorInitializer(\n keys=vocab, values=tf.constant(list(range(len(vocab))),\n dtype=tf.int64)),\n default_value=0)\n\n\ndef to_ids(x):\n s = tf.reshape(x['snippets'], shape=[1])\n chars = tf.strings.bytes_split(s).values\n ids = table.lookup(chars)\n return ids\n\n\ndef split_input_target(chunk):\n input_text = tf.map_fn(lambda x: x[:-1], chunk)\n target_text = tf.map_fn(lambda x: x[1:], chunk)\n return (input_text, target_text)\n\n\ndef preprocess(dataset):\n return (\n # Map ASCII chars to int64 indexes using the vocab\n dataset.map(to_ids)\n # Split into individual chars\n .unbatch()\n # Form example sequences of SEQ_LENGTH +1\n .batch(SEQ_LENGTH + 1, drop_remainder=True)\n # Shuffle and form minibatches\n .shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)\n # And finally split into (input, target) tuples,\n # each of length SEQ_LENGTH.\n .map(split_input_target))", "_____no_output_____" ] ], [ [ "Note that in the formation of the original sequences and in the formation of\nbatches above, we use `drop_remainder=True` for simplicity. This means that any\ncharacters (clients) that don't have at least `(SEQ_LENGTH + 1) * BATCH_SIZE`\nchars of text will have empty datasets. A typical approach to address this would\nbe to pad the batches with a special token, and then mask the loss to not take\nthe padding tokens into account.\n\nThis would complicate the example somewhat, so for this tutorial we only use full batches, as in the\n[standard tutorial](https://www.tensorflow.org/tutorials/sequences/text_generation).\nHowever, in the federated setting this issue is more significant, because many\nusers might have small datasets.\n\nNow we can preprocess our `raw_example_dataset`, and check the types:", "_____no_output_____" ] ], [ [ "example_dataset = preprocess(raw_example_dataset)\nprint(example_dataset.element_spec)", "(TensorSpec(shape=(8, 100), dtype=tf.int64, name=None), TensorSpec(shape=(8, 100), dtype=tf.int64, name=None))\n" ] ], [ [ "## Compile the model and test on the preprocessed data", "_____no_output_____" ], [ "We loaded an uncompiled keras model, but in order to run `keras_model.evaluate`, we need to compile it with a loss and metrics. We will also compile in an optimizer, which will be used as the on-device optimizer in Federated Learning.", "_____no_output_____" ], [ "The original tutorial didn't have char-level accuracy (the fraction\nof predictions where the highest probability was put on the correct\nnext char). This is a useful metric, so we add it.\nHowever, we need to define a new metric class for this because \nour predictions have rank 3 (a vector of logits for each of the \n`BATCH_SIZE * SEQ_LENGTH` predictions), and `SparseCategoricalAccuracy`\nexpects only rank 2 predictions.", "_____no_output_____" ] ], [ [ "class FlattenedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):\n\n def __init__(self, name='accuracy', dtype=tf.float32):\n super().__init__(name, dtype=dtype)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n y_true = tf.reshape(y_true, [-1, 1])\n y_pred = tf.reshape(y_pred, [-1, len(vocab), 1])\n return super().update_state(y_true, y_pred, sample_weight)", "_____no_output_____" ] ], [ [ "Now we can compile a model, and evaluate it on our `example_dataset`.", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 8 # The training and eval batch size for the rest of this tutorial.\nkeras_model = load_model(batch_size=BATCH_SIZE)\nkeras_model.compile(\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[FlattenedCategoricalAccuracy()])\n\n# Confirm that loss is much lower on Shakespeare than on random data\nloss, accuracy = keras_model.evaluate(example_dataset.take(5), verbose=0)\nprint(\n 'Evaluating on an example Shakespeare character: {a:3f}'.format(a=accuracy))\n\n# As a sanity check, we can construct some completely random data, where we expect\n# the accuracy to be essentially random:\nrandom_guessed_accuracy = 1.0 / len(vocab)\nprint('Expected accuracy for random guessing: {a:.3f}'.format(\n a=random_guessed_accuracy))\nrandom_indexes = np.random.randint(\n low=0, high=len(vocab), size=1 * BATCH_SIZE * (SEQ_LENGTH + 1))\ndata = collections.OrderedDict(\n snippets=tf.constant(\n ''.join(np.array(vocab)[random_indexes]), shape=[1, 1]))\nrandom_dataset = preprocess(tf.data.Dataset.from_tensor_slices(data))\nloss, accuracy = keras_model.evaluate(random_dataset, steps=10, verbose=0)\nprint('Evaluating on completely random data: {a:.3f}'.format(a=accuracy))", "Downloading data from https://storage.googleapis.com/tff-models-public/dickens_rnn.batch8.kerasmodel\n16195584/16193984 [==============================] - 0s 0us/step\n16203776/16193984 [==============================] - 0s 0us/step\nEvaluating on an example Shakespeare character: 0.402750\nExpected accuracy for random guessing: 0.012\nEvaluating on completely random data: 0.013\n" ] ], [ [ "## Fine-tune the model with Federated Learning", "_____no_output_____" ], [ "TFF serializes all TensorFlow computations so they can potentially be run in a\nnon-Python environment (even though at the moment, only a simulation runtime implemented in Python is available). Even though we are running in eager mode, (TF 2.0), currently TFF serializes TensorFlow computations by constructing the\nnecessary ops inside the context of a \"`with tf.Graph.as_default()`\" statement.\nThus, we need to provide a function that TFF can use to introduce our model into\na graph it controls. We do this as follows:", "_____no_output_____" ] ], [ [ "# Clone the keras_model inside `create_tff_model()`, which TFF will\n# call to produce a new copy of the model inside the graph that it will \n# serialize. Note: we want to construct all the necessary objects we'll need \n# _inside_ this method.\ndef create_tff_model():\n # TFF uses an `input_spec` so it knows the types and shapes\n # that your model expects.\n input_spec = example_dataset.element_spec\n keras_model_clone = tf.keras.models.clone_model(keras_model)\n return tff.learning.from_keras_model(\n keras_model_clone,\n input_spec=input_spec,\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[FlattenedCategoricalAccuracy()])", "_____no_output_____" ] ], [ [ "Now we are ready to construct a Federated Averaging iterative process, which we will use to improve the model (for details on the Federated Averaging algorithm, see the paper [Communication-Efficient Learning of Deep Networks from Decentralized Data](https://arxiv.org/abs/1602.05629)).\n\nWe use a compiled Keras model to perform standard (non-federated) evaluation after each round of federated training. This is useful for research purposes when doing simulated federated learning and there is a standard test dataset. \n\nIn a realistic production setting this same technique might be used to take models trained with federated learning and evaluate them on a centralized benchmark dataset for testing or quality assurance purposes.", "_____no_output_____" ] ], [ [ "# This command builds all the TensorFlow graphs and serializes them: \nfed_avg = tff.learning.build_federated_averaging_process(\n model_fn=create_tff_model,\n client_optimizer_fn=lambda: tf.keras.optimizers.SGD(lr=0.5))", "_____no_output_____" ] ], [ [ "Here is the simplest possible loop, where we run federated averaging for one round on a single client on a single batch:", "_____no_output_____" ] ], [ [ "state = fed_avg.initialize()\nstate, metrics = fed_avg.next(state, [example_dataset.take(5)])\nprint('loss={l:.3f}, accuracy={a:.3f}'.format(\n l=metrics.train.loss, a=metrics.train.accuracy))", "loss=4.404, accuracy=0.129\n" ] ], [ [ "Now let's write a slightly more interesting training and evaluation loop.\n\nSo that this simulation still runs relatively quickly, we train on the same three clients each round, only considering two minibatches for each.\n\n", "_____no_output_____" ] ], [ [ "def data(client, source=train_data):\n return preprocess(\n source.create_tf_dataset_for_client(client)).take(5)\n\nclients = ['ALL_S_WELL_THAT_ENDS_WELL_CELIA',\n 'MUCH_ADO_ABOUT_NOTHING_OTHELLO',\n 'THE_TRAGEDY_OF_KING_LEAR_KING']\n\ntrain_datasets = [data(client) for client in clients]\n\n# We concatenate the test datasets for evaluation with Keras.\ntest_dataset = functools.reduce(\n lambda d1, d2: d1.concatenate(d2),\n [data(client, test_data) for client in clients])", "_____no_output_____" ] ], [ [ "The initial state of the model produced by `fed_avg.initialize()` is based\non the random initializers for the Keras model, not the weights that were loaded,\nsince `clone_model()` does not clone the weights. To start training\nfrom a pre-trained model, we set the model weights in the server state\ndirectly from the loaded model.", "_____no_output_____" ] ], [ [ "NUM_ROUNDS = 5\n\n# The state of the FL server, containing the model and optimization state.\nstate = fed_avg.initialize()\n\nstate = tff.learning.state_with_new_model_weights(\n state,\n trainable_weights=[v.numpy() for v in keras_model.trainable_weights],\n non_trainable_weights=[\n v.numpy() for v in keras_model.non_trainable_weights\n ])\n\n\ndef keras_evaluate(state, round_num):\n # Take our global model weights and push them back into a Keras model to\n # use its standard `.evaluate()` method.\n keras_model = load_model(batch_size=BATCH_SIZE)\n keras_model.compile(\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[FlattenedCategoricalAccuracy()])\n tff.learning.assign_weights_to_keras_model(keras_model, state.model)\n loss, accuracy = keras_model.evaluate(example_dataset, steps=2, verbose=0)\n print('\\tEval: loss={l:.3f}, accuracy={a:.3f}'.format(l=loss, a=accuracy))\n\nfor round_num in range(NUM_ROUNDS):\n print('Round {r}'.format(r=round_num))\n keras_evaluate(state, round_num)\n state, metrics = fed_avg.next(state, train_datasets)\n print('\\tTrain: loss={l:.3f}, accuracy={a:.3f}'.format(\n l=metrics.train.loss, a=metrics.train.accuracy))\n\nkeras_evaluate(state, NUM_ROUNDS + 1)", "Round 0\n\tEval: loss=3.372, accuracy=0.395\n\tTrain: loss=4.317, accuracy=0.083\nRound 1\n\tEval: loss=4.300, accuracy=0.129\n\tTrain: loss=4.172, accuracy=0.184\nRound 2\n\tEval: loss=4.152, accuracy=0.201\n\tTrain: loss=4.077, accuracy=0.191\nRound 3\n\tEval: loss=4.031, accuracy=0.189\n\tTrain: loss=3.965, accuracy=0.192\nRound 4\n\tEval: loss=3.946, accuracy=0.183\n\tTrain: loss=3.877, accuracy=0.196\n\tEval: loss=3.885, accuracy=0.168\n" ] ], [ [ "With the default changes, we haven't done enough training to make a big difference, but if you train longer on more Shakespeare data, you should see a difference in the style of the text generated with the updated model:", "_____no_output_____" ] ], [ [ "# Set our newly trained weights back in the originally created model.\nkeras_model_batch1.set_weights([v.numpy() for v in keras_model.weights])\n# Text generation requires batch_size=1\nprint(generate_text(keras_model_batch1, 'What of TensorFlow Federated, you ask? '))", "What of TensorFlow Federated, you ask? Says\r\na word. How can it ock.\r\n\r\nIV Contant the Spy travelled him up to small\r\nface, the time, all the village, like shoulder by his own.\r\n\r\nThe rain-d be; for the great reasons that were started tone\n" ] ], [ [ "## Suggested extensions\n\nThis tutorial is just the first step! Here are some ideas for how you might try extending this notebook:\n * Write a more realistic training loop where you sample clients to train on randomly.\n * Use \"`.repeat(NUM_EPOCHS)`\" on the client datasets to try multiple epochs of local training (e.g., as in [McMahan et. al.](https://arxiv.org/abs/1602.05629)). See also [Federated Learning for Image Classification](federated_learning_for_image_classification.ipynb) which does this.\n * Change the `compile()` command to experiment with using different optimization algorithms on the client.\n * Try the `server_optimizer` argument to `build_federated_averaging_process` to try different algorithms for applying the model updates on the server.\n * Try the `client_weight_fn` argument to to `build_federated_averaging_process` to try different weightings of the clients. The default weights client updates by the number of examples on the client, but you can do e.g. `client_weight_fn=lambda _: tf.constant(1.0)`.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4af3d94d00dcbe8a975b2010b112b8152f22825c
2,338
ipynb
Jupyter Notebook
Math/1226/1619. Mean of Array After Removing Some Elements.ipynb
YuHe0108/Leetcode
90d904dde125dd35ee256a7f383961786f1ada5d
[ "Apache-2.0" ]
1
2020-08-05T11:47:47.000Z
2020-08-05T11:47:47.000Z
Math/1226/1619. Mean of Array After Removing Some Elements.ipynb
YuHe0108/LeetCode
b9e5de69b4e4d794aff89497624f558343e362ad
[ "Apache-2.0" ]
null
null
null
Math/1226/1619. Mean of Array After Removing Some Elements.ipynb
YuHe0108/LeetCode
b9e5de69b4e4d794aff89497624f558343e362ad
[ "Apache-2.0" ]
null
null
null
21.850467
264
0.439692
[ [ [ "arr = [4,8,4,10,0,7,1,3,7,8,8,3,4,1,6,2,1,1,8,0,9,8,0,3,9,10,3,10,1,10,7,3,2,1,4,9,10,7,6,4,0,8,5,1,2,1,6,2,5,0,7,10,9,10,3,7,10,5,8,5,7,6,7,6,10,9,5,10,5,5,7,2,10,7,7,8,2,0,1,1]\narr.sort()\nprint(arr, len(arr))\nsum(arr[4:-4]) / (len(arr) - 8)", "[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] 80\n" ], [ "sum(arr) / len(arr)", "_____no_output_____" ], [ "class Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n n = len(arr)\n k = n * 0.05\n for i in range(int(k)):\n arr.pop(0)\n arr.pop()\n return sum(arr) / len(arr)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
4af3dee58b5c92275f39fbf0330decc3aea85a0d
128,891
ipynb
Jupyter Notebook
GPy/ParametricNonParametricInference.ipynb
freli005/notebook
ddb2a70491221ceb92d34cc3b7dc8b94f382192c
[ "BSD-3-Clause" ]
143
2015-01-24T10:22:21.000Z
2022-03-23T05:59:36.000Z
GPy/ParametricNonParametricInference.ipynb
lawrennd/notebook
de7d53f3e275a1882ec737bc16cf86bc02f64caa
[ "BSD-3-Clause" ]
16
2015-09-10T17:49:22.000Z
2022-03-24T16:27:12.000Z
GPy/ParametricNonParametricInference.ipynb
lawrennd/notebook
de7d53f3e275a1882ec737bc16cf86bc02f64caa
[ "BSD-3-Clause" ]
105
2015-01-20T14:10:39.000Z
2022-02-28T13:43:06.000Z
246.917625
26,326
0.904477
[ [ [ "Parametric non Parametric inference\n===================\n\nSuppose you have a physical model of an output variable, which takes the form of a parametric model. You now want to model the random effects of the data by a non-parametric (better: infinite parametric) model, such as a Gaussian Process as described in [BayesianLinearRegression](../background/BayesianLinearRegression.ipynb). We can do inference in both worlds, the parameteric and infinite parametric one, by extending the features to a mix between \n\n\\begin{align}\np(\\mathbf{y}|\\boldsymbol{\\Phi}, \\alpha, \\sigma) &= \\int p(\\mathbf{y}|\\boldsymbol{\\Phi}, \\mathbf{w}, \\sigma)p(\\mathbf{w}|\\alpha) \\,\\mathrm{d}\\mathbf{w}\\\\\n&= \\langle\\mathcal{N}(\\mathbf{y}|\\boldsymbol{\\Phi}\\mathbf{w}, \\sigma^2\\mathbf{I})\\rangle_{\\mathcal{N}(\\mathbf{0}, \\alpha\\mathbf{I})}\\\\\n&= \\mathcal{N}(\\mathbf{y}|\\mathbf{0}, \\alpha\\boldsymbol{\\Phi}\\boldsymbol{\\Phi}^\\top + \\sigma^2\\mathbf{I})\n\\end{align}\n\nThus, we can maximize this marginal likelihood w.r.t. the hyperparameters $\\alpha, \\sigma$ by log transforming and maximizing:\n\n\\begin{align}\n\\hat\\alpha, \\hat\\sigma = \\mathop{\\arg\\max}_{\\alpha, \\sigma}\\log p(\\mathbf{y}|\\boldsymbol{\\Phi}, \\alpha, \\sigma)\n\\end{align}\n\nSo we will define a mixed inference model mixing parametric and non-parametric models together. One part is described by a paramtric feature space mapping $\\boldsymbol{\\Phi}\\mathbf{w}$ and the other part is a non-parametric function $\\mathbf{f}_\\text{n}$. For this we define the underlying function $\\mathbf{f}$ as \n\n$$\n\\begin{align}\np(\\mathbf{f}) &= p\\left(\n \\underbrace{\n \\begin{bmatrix} \n \\delta(t-T)\\\\\n \\boldsymbol{\\Phi}\n \\end{bmatrix}\n }_{=:\\mathbf{A}}\n \\left.\n \\begin{bmatrix}\n \\mathbf{f}_{\\text{n}}\\\\\n \\mathbf{w}\n \\end{bmatrix}\n \\right|\n \\mathbf{0}, \n \\mathbf{A}\n \\underbrace{\n \\begin{bmatrix}\n \\mathbf{K}_{\\mathbf{f}} & \\\\\n & \\mathbf{K}_{\\mathbf{w}}\n \\end{bmatrix}\n }_{=:\\boldsymbol{\\Sigma}}\n \\mathbf{A}^\\top\n \\right)\\enspace,\n\\end{align}\n$$\n\nwhere $\\mathbf{K}_{\\mathbf{f}}$ is the covariance describing the non-parametric part $\\mathbf{f}_\\text{n}\\sim\\mathcal{N}(\\mathbf{0}, \\mathbf{K}_\\mathbf{f})$ and $\\mathbf{K}_{\\mathbf{w}}$ is the covariance of the prior over $\\mathbf{w}\\sim\\mathcal{N}(\\mathbf{w}|\\mathbf{0}, \\mathbf{K}_{\\mathbf{w}})$.\n\nThus we can now predict the different parts and even the paramters $\\mathbf{w}$ themselves using (Note: If someone is willing to write down the proper path to this, here a welcome and thank you very much. Thanks to Philipp Hennig for his ideas in this.)\n\n$$\n\\begin{align}\np(\\mathbf{f}|\\mathbf{y}) &= \n \\mathcal{N}(\\mathbf{f} | \n \\boldsymbol{\\Sigma}\\mathbf{A}^\\top \n \\underbrace{\n (\\mathbf{A}\\boldsymbol{\\Sigma}\\mathbf{A}^\\top + \\sigma^2\\mathbf{I})^{-1}}_{=:\\mathbf{K}^{-1}}\\mathbf{y}, \\boldsymbol{\\Sigma}-\\boldsymbol{\\Sigma}\\mathbf{A}^\\top\\mathbf{K}^{-1}\\mathbf{A}\\boldsymbol{\\Sigma})\n \\\\\np(\\mathbf{w}|\\mathbf{y}) &= \\mathcal{N}(\\mathbf{w} | \\mathbf{K}_\\mathbf{w}\\boldsymbol{\\Phi}^\\top\\mathbf{K}^{-1}\\mathbf{y},\n\\mathbf{K}_{\\mathbf{w}}-\\mathbf{K}_{\\mathbf{w}}\\boldsymbol{\\Phi}^\\top\\mathbf{K}^{-1}\\boldsymbol{\\Phi}\\mathbf{K}_{\\mathbf{w}}))\n \\\\\np(\\mathbf{f}_\\text{n}|\\mathbf{y}) &= \\mathcal{N}(\\mathbf{f}_\\text{n}| \\mathbf{K}_\\mathbf{f}\\mathbf{K}^{-1}\\mathbf{y},\n\\mathbf{K}_{\\mathbf{f}}-\\mathbf{K}_{\\mathbf{f}}\\mathbf{K}^{-1}\\mathbf{K}_{\\mathbf{f}}))\n\\end{align}\n$$", "_____no_output_____" ] ], [ [ "import GPy, numpy as np, pandas as pd\nfrom GPy.kern import LinearSlopeBasisFuncKernel, DomainKernel, ChangePointBasisFuncKernel\n%matplotlib inline\nfrom matplotlib import pyplot as plt", "_____no_output_____" ] ], [ [ "We will create some data with a non-linear function, strongly driven by piecewise linear trends:", "_____no_output_____" ] ], [ [ "np.random.seed(12345)", "_____no_output_____" ], [ "x = np.random.uniform(0, 10, 40)[:,None]\nx.sort(0)\nstarts, stops = np.arange(0, 10, 3), np.arange(1, 11, 3)\n\nk_lin = LinearSlopeBasisFuncKernel(1, starts, stops, variance=1., ARD=1)\nPhi = k_lin.phi(x)\n_ = plt.plot(x, Phi)", "_____no_output_____" ] ], [ [ "We will assume the prior over $w_i\\sim\\mathcal{N}(0, 3)$ and a Matern32 structure in the non-parametric part. Additionally, we add a half parametric part, which is a periodic effect only active between $x\\in[3,8]$:", "_____no_output_____" ] ], [ [ "k = GPy.kern.Matern32(1, .3)\nKf = k.K(x)\n\nk_per = GPy.kern.PeriodicMatern32(1, variance=100, period=1)\nk_per.period.fix()\nk_dom = DomainKernel(1, 1., 5.)\nk_perdom = k_per * k_dom\nKpd = k_perdom.K(x)", "_____no_output_____" ], [ "np.random.seed(1234)\nalpha = np.random.gamma(3, 1, Phi.shape[1])\nw = np.random.normal(0, alpha)[:,None]\n\nf_SE = np.random.multivariate_normal(np.zeros(x.shape[0]), Kf)[:, None]\nf_perdom = np.random.multivariate_normal(np.zeros(x.shape[0]), Kpd)[:, None]\nf_w = Phi.dot(w)\n\nf = f_SE + f_w + f_perdom\n\ny = f + np.random.normal(0, .1, f.shape)", "_____no_output_____" ], [ "plt.plot(x, f_w)\n_ = plt.plot(x, y)\n# Make sure the function is driven by the linear trend, as there can be a difficulty in identifiability.", "_____no_output_____" ] ], [ [ "With this data, we can fit a model using the basis functions as paramtric part. If you want to implement your own basis function kernel, see GPy.kern._src.basis_funcs.BasisFuncKernel and implement the necessary parts. Usually it is enough to implement the phi(X) method, returning the higher dimensional mapping of inputs X.", "_____no_output_____" ] ], [ [ "k = (GPy.kern.Bias(1) \n + GPy.kern.Matern52(1) \n + LinearSlopeBasisFuncKernel(1, ARD=1, start=starts, stop=stops, variance=.1, name='linear_slopes')\n + k_perdom.copy()\n )\n\nk.randomize()\nm = GPy.models.GPRegression(x, y, k)", "_____no_output_____" ], [ "m.checkgrad()", "_____no_output_____" ], [ "m.optimize()", "_____no_output_____" ], [ "m.plot()", "_____no_output_____" ], [ "x_pred = np.linspace(0, 10, 500)[:,None]\npred_SE, var_SE = m._raw_predict(x_pred, kern=m.kern.Mat52)\npred_per, var_per = m._raw_predict(x_pred, kern=m.kern.mul)\npred_bias, var_bias = m._raw_predict(x_pred, kern=m.kern.bias)\npred_lin, var_lin = m._raw_predict(x_pred, kern=m.kern.linear_slopes)", "_____no_output_____" ], [ "m.plot_f(resolution=500, predict_kw=dict(kern=m.kern.Mat52), plot_data=False)\nplt.plot(x, f_SE)", "_____no_output_____" ], [ "m.plot_f(resolution=500, predict_kw=dict(kern=m.kern.mul), plot_data=False)\nplt.plot(x, f_perdom)", "_____no_output_____" ], [ "m.plot_f(resolution=500, predict_kw=dict(kern=m.kern.linear_slopes), plot_data=False)\nplt.plot(x, f_w)", "_____no_output_____" ], [ "w_pred, w_var = m.kern.linear_slopes.posterior_inf()", "_____no_output_____" ], [ "df = pd.DataFrame(w, columns=['truth'], index=np.arange(Phi.shape[1]))\ndf['mean'] = w_pred\ndf['std'] = np.sqrt(w_var.diagonal())", "_____no_output_____" ], [ "np.round(df, 2)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af3e299767e786f362dca5960cc0c66c1c3abc1
157,297
ipynb
Jupyter Notebook
RNN_Extras.ipynb
gjvivar/deep_learning
94d45e54bcb8054b79e24aeb94cb2619049c0a5e
[ "MIT" ]
null
null
null
RNN_Extras.ipynb
gjvivar/deep_learning
94d45e54bcb8054b79e24aeb94cb2619049c0a5e
[ "MIT" ]
null
null
null
RNN_Extras.ipynb
gjvivar/deep_learning
94d45e54bcb8054b79e24aeb94cb2619049c0a5e
[ "MIT" ]
null
null
null
490.021807
93,930
0.929954
[ [ [ "import numpy as np\nimport pandas as pd\nimport pickle\nimport os\nimport time\n\nfrom sklearn.metrics import r2_score, accuracy_score, confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom IPython.display import Image\nimport tensorflow as tf\n\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten\nfrom keras.models import Sequential, load_model, Model\nfrom keras.layers import Dense, LSTM, SimpleRNN, GRU, Input, Embedding, concatenate\nfrom keras.utils import np_utils, to_categorical, plot_model\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, \\\n LearningRateScheduler\nfrom keras.layers.wrappers import TimeDistributed\nfrom keras.optimizers import Adam, RMSprop\nfrom keras.regularizers import l2\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.datasets import mnist\nfrom keras.layers.core import RepeatVector\n\n# import wrapper_data as wd\n# import lstm_wrapper as lw", "Using TensorFlow backend.\n" ] ], [ [ "## Stacking RNNs", "_____no_output_____" ] ], [ [ "# Only have to specify input_shape at the initial layer\n# Single scalar output\ntimesteps = 100\nfeatures = 3\nmodel = Sequential()\nmodel.add(LSTM(64, input_shape=(timesteps, features), return_sequences=True))\nmodel.add(LSTM(64))\nmodel.add(Dense(1))\n\n# Scalar output every timestep\nmodel2 = Sequential()\nmodel2.add(LSTM(64, input_shape=(timesteps, features), return_sequences=True))\nmodel2.add(LSTM(64, return_sequences=True),)\nmodel2.add(TimeDistributed(Dense(1)))", "_____no_output_____" ], [ "model.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlstm_9 (LSTM) (None, 100, 64) 17408 \n_________________________________________________________________\nlstm_10 (LSTM) (None, 64) 33024 \n_________________________________________________________________\ndense_4 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 50,497.0\nTrainable params: 50,497\nNon-trainable params: 0.0\n_________________________________________________________________\n" ], [ "model2.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlstm_11 (LSTM) (None, 100, 64) 17408 \n_________________________________________________________________\nlstm_12 (LSTM) (None, 100, 64) 33024 \n_________________________________________________________________\ntime_distributed_2 (TimeDist (None, 100, 1) 65 \n=================================================================\nTotal params: 50,497.0\nTrainable params: 50,497\nNon-trainable params: 0.0\n_________________________________________________________________\n" ] ], [ [ "## Unequal length sequences", "_____no_output_____" ] ], [ [ "# Pad sequences with zeros to have equal sizes\npadded_sequences = pad_sequences(list_of_sequences)\n\n# Add a masking layer\nmodel = Sequential()\nmodel.add(Masking(mask_value=0., input_shape=(timesteps, features)))\nmodel.add(LSTM(32))", "_____no_output_____" ] ], [ [ "## Keras in Tensorflow\n\n* tf.contrib.keras", "_____no_output_____" ], [ "# One-to-many", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename=\"/src/keras/Gerome/01_main/95_keras_practice/one_to_many.png\", height=200, width=200) ", "_____no_output_____" ], [ "# This model will encode an image into a vector.\nvision_model = Sequential()\nvision_model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(224, 224, 3)))\nvision_model.add(Conv2D(64, (3, 3), activation='relu'))\nvision_model.add(MaxPooling2D((2, 2)))\nvision_model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\nvision_model.add(Conv2D(128, (3, 3), activation='relu'))\nvision_model.add(MaxPooling2D((2, 2)))\nvision_model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))\nvision_model.add(Conv2D(256, (3, 3), activation='relu'))\nvision_model.add(Conv2D(256, (3, 3), activation='relu'))\nvision_model.add(MaxPooling2D((2, 2)))\nvision_model.add(Flatten())\nvision_model.add(Dense(4096, activation='relu'))\n\n# Now let's get a tensor with the output of our vision model:\nimage_input = Input(shape=(224, 224, 3))\nencoded_image = vision_model(image_input)\nrepeat_encoded_img = RepeatVector(100)(encoded_image)", "_____no_output_____" ], [ "# Sentence encoding model\nsentence_input = Input(shape=(100,), dtype='int32')\nembedded_question = Embedding(input_dim=10000, output_dim=256, input_length=100)(sentence_input)\nencoded_question = LSTM(256, return_sequences=True)(embedded_question)", "_____no_output_____" ], [ "# Merge both image features and sentences\nmerged = concatenate([encoded_question, repeat_encoded_img])\nlstm_layer = LSTM(256, return_sequences=True)(merged)\n\n# And let's train a logistic regression over 1000 words on top:\noutput = TimeDistributed(Dense(1000, activation='softmax'))(lstm_layer)\n\n# This is our final model:\nimage_captioning_model = Model(inputs=[image_input, sentence_input], outputs=output)", "_____no_output_____" ], [ "model_img_path = '/src/keras/Gerome/01_main/95_keras_practice/RNN_image_captioning_model.png'\nplot_model(image_captioning_model, to_file=model_img_path, show_shapes=True)\nImage(model_img_path)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4af3e5fa009fe3f62c9211abb10a0a14a696c1ab
682,581
ipynb
Jupyter Notebook
notebooks/CST_PTM_Data_Overview.ipynb
MaayanLab/CST_Lung_Cancer_Viz
bf840ffbc71d4ccd1b8dd063d9a7a1574fa02f27
[ "MIT" ]
2
2017-12-25T18:18:45.000Z
2019-01-10T18:20:43.000Z
notebooks/CST_PTM_Data_Overview.ipynb
MaayanLab/CST_Lung_Cancer_Viz
bf840ffbc71d4ccd1b8dd063d9a7a1574fa02f27
[ "MIT" ]
null
null
null
notebooks/CST_PTM_Data_Overview.ipynb
MaayanLab/CST_Lung_Cancer_Viz
bf840ffbc71d4ccd1b8dd063d9a7a1574fa02f27
[ "MIT" ]
5
2017-04-01T05:55:54.000Z
2022-01-31T17:59:59.000Z
812.596429
73,122
0.943986
[ [ [ "# CST PTM Data Overview\n\nThe PTM data from CST has a significant amount of missing data and requires special consideration when normalizing. The starting data is ratio-level-data - where log2 ratios have been calculated from the cancerous cell lines compared to the non-cancerous 'Normal Pool' data from within the 'plex'. This data is under the lung_cellline_3_1_16 directory and each PTM type has its own '_combined_ratios.tsv' file. \n\nThis notebook will overview the ratio-level datat from the PTM types: phosphorylation, methylation, and acetylation. The figures in this notebook demonstrate that there is a systematic difference in the distributions of PTM measurements in the lung cancer cell lines regardless of PTMs with missing data are considered. The normalization procedures used to correct for this systematic bias are discussed in the [CST_PTM_Normalization_Overview](https://github.com/MaayanLab/CST_Lung_Cancer_Viz/blob/master/CST_PTM_Normalization_Overview.ipynb) notebook.\n\nThe systematic difference in average PTM ratios in the cell lines could be due to a number of factors: \n* it could be biological in nature, e.g. some cell line have uniformly higher PTM levels than others\n* some cell lines might have higher/lower metabolism rates which will result in differences in incorporation of heavy isotopes\n* some cell lines might reproduce faster/slower during the time period where cells are exposed to heavy isotopes, which would result in differences in the population size of the different cell lines\n\nIn any case, it can be useful towards understanding the differences in cell line behavior to remove this systematic difference. \n\n# Phosphorylation Data\nI'll start by having a look at the phosphorylation data that can be found in \n\n`lung_cellline_3_1_16/lung_cellline_phospho/lung_cellline_TMT_phospho_combined_ratios.tsv`\n\nThis file was made using the `process_latest_cst_data.py` script. First I'll make the necessary imports. ", "_____no_output_____" ] ], [ [ "# imports and plotting defaults\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline \nimport matplotlib\nmatplotlib.style.use('ggplot')\nfrom copy import deepcopy\n\n# use clustergrammer module to load/process (source code in clustergrammer directory)\nfrom clustergrammer import Network", "_____no_output_____" ] ], [ [ "Next, I'll load the phosphorylation ratio data and simplify the column names (to improve readability)", "_____no_output_____" ] ], [ [ "# load data data and export as pandas dataframe: inst_df\ndef load_data(filename):\n ''' \n load data using clustergrammer and export as pandas dataframe\n '''\n net = deepcopy(Network())\n net.load_file(filename)\n tmp_df = net.dat_to_df()\n inst_df = tmp_df['mat']\n\n \n # simplify column names (remove categories)\n col_names = inst_df.columns.tolist()\n# simple_col_names = []\n# for inst_name in col_names:\n# simple_col_names.append(inst_name[0])\n\n inst_df.columns = col_names\n\n print(inst_df.shape)\n \n ini_rows = inst_df.index.tolist()\n unique_rows = list(set(ini_rows))\n \n if len(ini_rows) > len(unique_rows):\n print('found duplicate PTMs')\n else:\n print('did not find duplicate PTMs')\n \n return inst_df\n\nfilename = '../lung_cellline_3_1_16/lung_cellline_phospho/' + \\\n'lung_cellline_TMT_phospho_combined_ratios.tsv'\ninst_df = load_data(filename)", "(5798, 45)\ndid not find duplicate PTMs\n" ] ], [ [ "I loaded the phosphorylation tsv file using clustergrammer and exported it as a pandas dataframe. We can see that there are 5,798 unique phosphorylation sites measured in all 45 lung cancer cell lines. ", "_____no_output_____" ], [ "### Missing Phosphorylation Data\nHowever, there is also a large amount of missing data, e.g. no cell line has all 5798 phosphorylations mesaured. We can plot the number of measured phosphorylation sites (e.g. non-NaN values in the dataframe) below to get a sense of the amount of missing data", "_____no_output_____" ] ], [ [ "inst_df.count().sort_values().plot(kind='bar', figsize=(10,2))\nprint(type(inst_df))", "<class 'pandas.core.frame.DataFrame'>\n" ] ], [ [ "In the above visualization I have ranked the cell lines based in increasing number of measurements. We can see that there is a pattern in the missing data. The 45 cell lines appear to be aranged into nine groups of 5 cell lines each. These groups correpond to the 9 'plexes', or 'batches', in which the cell lines were measured. Each plex measured one control, Normal Pool, and five cancer cell lines (note that some cell lines have been measured in more than one plex and these have their plex number appended to their name). \n\n### Cell Line Phosphorylation Distributions\n\nSince each cell line has a large number of measured phosphorylations (at least 1,500) we can reasonably expect that the distributions of phosphorylation levels in the cell lines will be similar. This is based on the assumption that biological variation is not systematic and should not result in consistently higher or lower measurements in the cell lines. \n\nBelow we plot the mean values (ratios) of all measured phosphorylations in each cell line and order the cell lines by their average phosphorylation levels in ascending order. ", "_____no_output_____" ] ], [ [ "def plot_cl_boxplot_with_missing_data(inst_df):\n '''\n Make a box plot of the cell lines where the cell lines are ranked based \n on their average PTM levels\n '''\n \n # get the order of the cell lines based on their mean \n sorter = inst_df.mean().sort_values().index.tolist()\n # reorder based on ascending mean values\n sort_df = inst_df[sorter]\n # box plot of PTM values ordered based on increasing mean \n sort_df.plot(kind='box', figsize=(10,3), rot=90, ylim=(-8,8))\n\nplot_cl_boxplot_with_missing_data(inst_df)", "_____no_output_____" ] ], [ [ "We can see that there is a significant difference in the mean phosphorylation level across the cell lines. These large differenecs in the cell line distributions lead us to believe that there is a systematic error in the measurements that needs to be corrected. \n\nHowever, each cell line has a different subset of phosphorylations measured so to more fairly compare the cell lines we should only compare commonly measured phosphorylations. \n\nBelow we plot the mean values of phosphorylations that were measured in all cell lines. ", "_____no_output_____" ] ], [ [ "def plot_cl_boxplot_no_missing_data(inst_df):\n # get the order of the cell lines based on their mean \n sorter = inst_df.mean().sort_values().index.tolist()\n # reorder based on ascending mean values\n sort_df = inst_df[sorter]\n\n # transpose to get PTMs as columns \n tmp_df = sort_df.transpose()\n\n # keep only PTMs that are measured in all cell lines\n ptm_num_meas = tmp_df.count()\n ptm_all_meas = ptm_num_meas[ptm_num_meas == 45]\n ptm_all_meas = ptm_all_meas.index.tolist()\n\n print('There are ' + str(len(ptm_all_meas)) + ' PTMs measured in all cell lines')\n \n # only keep ptms that are measured in all cell lines \n # I will call this full_df as in no missing measurements\n full_df = tmp_df[ptm_all_meas]\n\n # transpose back to PTMs as rows\n full_df = full_df.transpose()\n\n full_df.plot(kind='box', figsize=(10,3), rot=90, ylim=(-8,8))\n num_ptm_all_meas = len(ptm_all_meas)\n\nplot_cl_boxplot_no_missing_data(inst_df)", "There are 513 PTMs measured in all cell lines\n" ] ], [ [ "From the above box plot we can see that there is a significant difference in the distributions of the cell lines even when we only consider phosphorylations that were measured in all cell lines (note that the cell lines are in the same order as the previous box plot). This indicates that this systematic differnce in average phosphorylation values is not caused by missing values. \n\nSince we do not expect biological variation to cause this type of systematic difference between cell lines we can conclude that the large differences between cell lines are likely the result of systematic experimental error that should be corrected. Normalizing the data will be discussed [here](https://github.com/MaayanLab/CST_Lung_Cancer_Viz)", "_____no_output_____" ], [ "# Acetylation Data\nI will perform the same overview on the acetylation data. There are 1,192 unique acetylations measured in the 45 cell lines. ", "_____no_output_____" ] ], [ [ "filename = '../lung_cellline_3_1_16/lung_cellline_Ack/' + \\\n 'lung_cellline_TMT_Ack_combined_ratios.tsv'\ninst_df = load_data(filename)", "(1192, 45)\ndid not find duplicate PTMs\n" ] ], [ [ "### Missing Acetylation Data", "_____no_output_____" ] ], [ [ "inst_df.count().sort_values().plot(kind='bar', figsize=(10,2))", "_____no_output_____" ] ], [ [ "### Cell Line Acetylation Distributions", "_____no_output_____" ] ], [ [ "plot_cl_boxplot_with_missing_data(inst_df)", "_____no_output_____" ] ], [ [ "Distribution of Acetylation data that was measured in all cell lines", "_____no_output_____" ] ], [ [ "plot_cl_boxplot_no_missing_data(inst_df)", "There are 125 PTMs measured in all cell lines\n" ] ], [ [ "# Methylation Data\nThe methylation data has been broken up into Arginine and Lysine methylation.\n\n## Arginine Methylation \nThere are 1,248 Arginine methylations measured in all 42 cell lines", "_____no_output_____" ] ], [ [ "filename = '../lung_cellline_3_1_16/lung_cellline_Rme1/' + \\\n'lung_cellline_TMT_Rme1_combined_ratios.tsv'\ninst_df = load_data(filename)", "(1248, 45)\ndid not find duplicate PTMs\n" ] ], [ [ "### Missing Arginine Methylation Data", "_____no_output_____" ] ], [ [ "inst_df.count().sort_values().plot(kind='bar', figsize=(10,2))", "_____no_output_____" ] ], [ [ "### Cell Line Arginine Methylation Distributions", "_____no_output_____" ] ], [ [ "plot_cl_boxplot_with_missing_data(inst_df)", "_____no_output_____" ] ], [ [ "Argining Methylation that was measured in all cell lines ", "_____no_output_____" ] ], [ [ "plot_cl_boxplot_no_missing_data(inst_df)", "There are 193 PTMs measured in all cell lines\n" ] ], [ [ "## Lysine Methylation Data\nThere are 230 lysine methylations measured in all cell line", "_____no_output_____" ] ], [ [ "filename = '../lung_cellline_3_1_16/lung_cellline_Kme1/' + \\\n'lung_cellline_TMT_Kme1_combined_ratios.tsv'\ninst_df = load_data(filename)", "(230, 45)\ndid not find duplicate PTMs\n" ] ], [ [ "### Missing Lysine Methylation Data\nSome cell lines have as few as 40 lysine methylations measured.", "_____no_output_____" ] ], [ [ "inst_df.count().sort_values().plot(kind='bar', figsize=(10,2))", "_____no_output_____" ] ], [ [ "### Cell Line Lysine Metylation Distributions", "_____no_output_____" ] ], [ [ "plot_cl_boxplot_with_missing_data(inst_df)", "_____no_output_____" ] ], [ [ "Lysine methylation that was measured in all cell lines ", "_____no_output_____" ] ], [ [ "plot_cl_boxplot_no_missing_data(inst_df)", "There are 26 PTMs measured in all cell lines\n" ] ], [ [ "There were only 26 lysine methylations that were measured in all cell lines. We still see the bias in the average values across the cell lines. ", "_____no_output_____" ], [ "# Conclusions\nWe see that the PTM measurements (phosphorylation, acetylation, and methylation) all show large differences in average behavior across the cell lines. Furthermore, the cell lines with the highest and lowest ratios are frequently the same: DMS153 is hte cell line with the lowest ratios and H661 is the cell line with the highest ratios in all cases. '\n\nIn other words, if we were to ask which cell line has the highest or lowest level of a particular PTM site we would almost always get the same cell line no matter which site we were interested in. Since this type of uniform and systematic difference between cell lines is not what we expect biologically we can conclude that the ratio data should be normalized in some way. The normalization procedure and its affects on cell line clustering are discussed in the notebook [CST_PTM_Normalization_Overview](https://github.com/MaayanLab/CST_Lung_Cancer_Viz/blob/master/CST_PTM_Normalization_Overview.ipynb) notebook.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4af3ecc20adcc726c3637782e0a6f9e0d1d95852
86,262
ipynb
Jupyter Notebook
notebooks/model_trainer_10_sigmoid_3_1000.ipynb
trentleslie/springboard_final_capstone
c61d7c105bade86847f313b2ef9ddebc06d801f3
[ "MIT" ]
null
null
null
notebooks/model_trainer_10_sigmoid_3_1000.ipynb
trentleslie/springboard_final_capstone
c61d7c105bade86847f313b2ef9ddebc06d801f3
[ "MIT" ]
null
null
null
notebooks/model_trainer_10_sigmoid_3_1000.ipynb
trentleslie/springboard_final_capstone
c61d7c105bade86847f313b2ef9ddebc06d801f3
[ "MIT" ]
null
null
null
83.587209
202
0.552086
[ [ [ "# Load the TensorBoard notebook extension\n%load_ext tensorboard", "The tensorboard extension is already loaded. To reload it, use:\n %reload_ext tensorboard\n" ], [ "import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional\nfrom tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom yahoo_fin import stock_info as si\nfrom collections import deque\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport random\n\nimport multiprocessing\n \ngpus = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(gpus[0], True)\n \nos.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1'\n\npolicy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')\ntf.keras.mixed_precision.experimental.set_policy(policy) ", "_____no_output_____" ], [ "def create_model(sequence_length, units=256, cell=LSTM, n_layers=2, dropout=0.3,\n loss=\"mean_absolute_error\", optimizer=\"rmsprop\", bidirectional=False,layer_activation=\"linear\"):\n model = Sequential()\n for i in range(n_layers):\n if i == 0:\n # first layer\n if bidirectional:\n model.add(Bidirectional(cell(units, return_sequences=True), input_shape=(None, sequence_length)))\n else:\n model.add(cell(units, return_sequences=True, input_shape=(None, sequence_length)))\n elif i == n_layers - 1:\n # last layer\n if bidirectional:\n model.add(Bidirectional(cell(units, return_sequences=False)))\n else:\n model.add(cell(units, return_sequences=False))\n else:\n # hidden layers\n if bidirectional:\n model.add(Bidirectional(cell(units, return_sequences=True)))\n else:\n model.add(cell(units, return_sequences=True))\n # add dropout after each layer\n model.add(Dropout(dropout))\n model.add(Dense(1, activation=layer_activation))\n model.compile(loss=loss, metrics=[\"mean_absolute_error\"], optimizer=optimizer)\n return model", "_____no_output_____" ], [ "#def run_tensorflow():\n\n# create these folders if they does not exist\n# Window size or the sequence length\nN_STEPS = 72\n# Lookup step, 1 is the next day\n#LOOKUP_STEP = int(run_dict[run][\"LOOKUP_STEP\"])\n\n# test ratio size, 0.2 is 20%\nTEST_SIZE = 0.3\n# features to use\nFEATURE_COLUMNS = [\"close_0\",\"ema_0\",\"high_0\",\"low_0\",\"open_0\",\"rsi_0\",\"sma_0\",\"volume_0\",\"close_1\",\"ema_1\",\"high_1\",\"low_1\",\"open_1\",\"rsi_1\",\"sma_1\",\"volume_1\",\n \"close_2\",\"ema_2\",\"high_2\",\"low_2\",\"open_2\",\"rsi_2\",\"sma_2\",\"volume_2\",\"close_3\",\"ema_3\",\"high_3\",\"low_3\",\"open_3\",\"rsi_3\",\"sma_3\",\"volume_3\",\n \"close_4\",\"ema_4\",\"high_4\",\"low_4\",\"open_4\",\"rsi_4\",\"sma_4\",\"volume_4\",\"close_5\",\"ema_5\",\"high_5\",\"low_5\",\"open_5\",\"rsi_5\",\"sma_5\",\"volume_5\",\n \"close_6\",\"ema_6\",\"high_6\",\"low_6\",\"open_6\",\"rsi_6\",\"sma_6\",\"volume_6\",\"close_7\",\"ema_7\",\"high_7\",\"low_7\",\"open_7\",\"rsi_7\",\"sma_7\",\"volume_7\",\n \"close_8\",\"ema_8\",\"high_8\",\"low_8\",\"open_8\",\"rsi_8\",\"sma_8\",\"volume_8\"]\nTARGET_COLUMNS = [\"close_9\",\"high_9\",\"low_9\",\"open_9\"]\n# date now\ndate_now = time.strftime(\"%Y-%m-%d\")\n\n### model parameters\n\nN_LAYERS = 3\n# LSTM cell\nCELL = LSTM\n# 256 LSTM neurons\nUNITS = 1000\n# 40% dropout\nDROPOUT = 0.25\n# whether to use bidirectional RNNs\nBIDIRECTIONAL = True\n\n### training parameters\n\n# mean absolute error loss\n# LOSS = \"mae\"\n# huber loss\nLOSS = \"huber_loss\"\nOPTIMIZER = \"adam\"\nBATCH_SIZE = 64\nEPOCHS = 50\n\nLAYER_ACTIVATION = \"sigmoid\"\n\n# Stock market\nticker = \"MIXED\"\nticker_data_filename = os.path.join(\"data\", f\"{ticker}_{date_now}.csv\")\n# model name to save, making it as unique as possible based on parameters\nmodel_name = f\"{date_now}_{ticker}-{LOSS}-{OPTIMIZER}-{CELL.__name__}-{LAYER_ACTIVATION}-layers-{N_LAYERS}-units-{UNITS}\"\nif BIDIRECTIONAL:\n model_name += \"-b\"\n\n#----------------------------------------------------------------------------------------------------------#\n#----------------------------------------------------------------------------------------------------------#\n#----------------------------------------------------------------------------------------------------------#\n\n#try:\nif not os.path.isdir(\"results\"):\n os.mkdir(\"results\")\n\nif not os.path.isdir(\"logs\"):\n os.mkdir(\"logs\")\n\nif not os.path.isdir(\"data\"):\n os.mkdir(\"data\")\n\n# load the data\ndata = pd.read_csv('../data/processed/all_processed_10.csv')\n\n# construct the model\nmodel = create_model(N_STEPS, loss=LOSS, units=UNITS, cell=CELL, n_layers=N_LAYERS,\n dropout=DROPOUT, optimizer=OPTIMIZER, bidirectional=BIDIRECTIONAL, layer_activation=LAYER_ACTIVATION)\n\n# some tensorflow callbacks\ncheckpointer = ModelCheckpoint(os.path.join(\"results\", model_name + \".h5\"), save_weights_only=True, save_best_only=True, verbose=1)\ntensorboard = TensorBoard(log_dir=os.path.join(\"logs\", model_name))\n\nX = data[FEATURE_COLUMNS]\ny = data[TARGET_COLUMNS]\n\n# convert to numpy arrays\nX = np.array(X)\ny = np.array(y)\n\n# reshape X to fit the neural network\nX = X.reshape((X.shape[0], 1, X.shape[1]))\n\n# split the dataset\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE, shuffle=True)\n\nhistory = model.fit(X_train, y_train,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n validation_data=(X_test, y_test),\n callbacks=[checkpointer, tensorboard],\n verbose=1)\n\nmodel.save(os.path.join(\"results\", model_name) + \".h5\")\n\n#except:\n# print(\"There was an attempt.\")\ntf.keras.backend.clear_session()", "Train on 67485 samples, validate on 28923 samples\nEpoch 1/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.5290 - mean_absolute_error: 0.9017\nEpoch 00001: val_loss improved from inf to 0.51433, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 43s 641us/sample - loss: 0.5290 - mean_absolute_error: 0.9017 - val_loss: 0.5143 - val_mean_absolute_error: 0.8855\nEpoch 2/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.5192 - mean_absolute_error: 0.8900\nEpoch 00002: val_loss improved from 0.51433 to 0.50869, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 35s 513us/sample - loss: 0.5192 - mean_absolute_error: 0.8900 - val_loss: 0.5087 - val_mean_absolute_error: 0.8789\nEpoch 3/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.5129 - mean_absolute_error: 0.8826\nEpoch 00003: val_loss improved from 0.50869 to 0.50849, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 35s 521us/sample - loss: 0.5127 - mean_absolute_error: 0.8825 - val_loss: 0.5085 - val_mean_absolute_error: 0.8791\nEpoch 4/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.5058 - mean_absolute_error: 0.8739\nEpoch 00004: val_loss improved from 0.50849 to 0.50397, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 36s 527us/sample - loss: 0.5057 - mean_absolute_error: 0.8737 - val_loss: 0.5040 - val_mean_absolute_error: 0.8727\nEpoch 5/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.4964 - mean_absolute_error: 0.8629\nEpoch 00005: val_loss improved from 0.50397 to 0.50087, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 34s 498us/sample - loss: 0.4964 - mean_absolute_error: 0.8628 - val_loss: 0.5009 - val_mean_absolute_error: 0.8692\nEpoch 6/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.4849 - mean_absolute_error: 0.8492\nEpoch 00006: val_loss improved from 0.50087 to 0.49192, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 480us/sample - loss: 0.4850 - mean_absolute_error: 0.8493 - val_loss: 0.4919 - val_mean_absolute_error: 0.8592\nEpoch 7/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.4686 - mean_absolute_error: 0.8300\nEpoch 00007: val_loss improved from 0.49192 to 0.48769, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 480us/sample - loss: 0.4685 - mean_absolute_error: 0.8299 - val_loss: 0.4877 - val_mean_absolute_error: 0.8544\nEpoch 8/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.4495 - mean_absolute_error: 0.8069\nEpoch 00008: val_loss improved from 0.48769 to 0.48280, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 480us/sample - loss: 0.4496 - mean_absolute_error: 0.8070 - val_loss: 0.4828 - val_mean_absolute_error: 0.8482\nEpoch 9/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.4283 - mean_absolute_error: 0.7816\nEpoch 00009: val_loss improved from 0.48280 to 0.47827, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 480us/sample - loss: 0.4282 - mean_absolute_error: 0.7815 - val_loss: 0.4783 - val_mean_absolute_error: 0.8426\nEpoch 10/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.4058 - mean_absolute_error: 0.7542\nEpoch 00010: val_loss did not improve from 0.47827\n67485/67485 [==============================] - 32s 476us/sample - loss: 0.4059 - mean_absolute_error: 0.7543 - val_loss: 0.4824 - val_mean_absolute_error: 0.8471\nEpoch 11/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.3853 - mean_absolute_error: 0.7296\nEpoch 00011: val_loss improved from 0.47827 to 0.47593, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 33s 490us/sample - loss: 0.3852 - mean_absolute_error: 0.7295 - val_loss: 0.4759 - val_mean_absolute_error: 0.8396\nEpoch 12/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.3654 - mean_absolute_error: 0.7061\nEpoch 00012: val_loss improved from 0.47593 to 0.47371, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 33s 483us/sample - loss: 0.3654 - mean_absolute_error: 0.7061 - val_loss: 0.4737 - val_mean_absolute_error: 0.8365\nEpoch 13/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.3479 - mean_absolute_error: 0.6844\nEpoch 00013: val_loss did not improve from 0.47371\n67485/67485 [==============================] - 33s 486us/sample - loss: 0.3479 - mean_absolute_error: 0.6844 - val_loss: 0.4798 - val_mean_absolute_error: 0.8441\nEpoch 14/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.3334 - mean_absolute_error: 0.6666\nEpoch 00014: val_loss improved from 0.47371 to 0.47267, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 33s 488us/sample - loss: 0.3334 - mean_absolute_error: 0.6666 - val_loss: 0.4727 - val_mean_absolute_error: 0.8360\nEpoch 15/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.3210 - mean_absolute_error: 0.6510\nEpoch 00015: val_loss improved from 0.47267 to 0.46970, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 33s 484us/sample - loss: 0.3210 - mean_absolute_error: 0.6511 - val_loss: 0.4697 - val_mean_absolute_error: 0.8321\nEpoch 16/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.3099 - mean_absolute_error: 0.6374\nEpoch 00016: val_loss improved from 0.46970 to 0.46634, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 479us/sample - loss: 0.3100 - mean_absolute_error: 0.6375 - val_loss: 0.4663 - val_mean_absolute_error: 0.8279\nEpoch 17/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.3008 - mean_absolute_error: 0.6257\nEpoch 00017: val_loss did not improve from 0.46634\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.3008 - mean_absolute_error: 0.6257 - val_loss: 0.4677 - val_mean_absolute_error: 0.8296\nEpoch 18/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2934 - mean_absolute_error: 0.6168\nEpoch 00018: val_loss did not improve from 0.46634\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2934 - mean_absolute_error: 0.6168 - val_loss: 0.4681 - val_mean_absolute_error: 0.8297\nEpoch 19/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2871 - mean_absolute_error: 0.6088\nEpoch 00019: val_loss did not improve from 0.46634\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2872 - mean_absolute_error: 0.6088 - val_loss: 0.4677 - val_mean_absolute_error: 0.8292\nEpoch 20/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2809 - mean_absolute_error: 0.6003\nEpoch 00020: val_loss improved from 0.46634 to 0.46502, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 478us/sample - loss: 0.2810 - mean_absolute_error: 0.6003 - val_loss: 0.4650 - val_mean_absolute_error: 0.8265\nEpoch 21/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2771 - mean_absolute_error: 0.5952\nEpoch 00021: val_loss improved from 0.46502 to 0.46425, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 478us/sample - loss: 0.2771 - mean_absolute_error: 0.5953 - val_loss: 0.4642 - val_mean_absolute_error: 0.8249\nEpoch 22/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2721 - mean_absolute_error: 0.5888\nEpoch 00022: val_loss improved from 0.46425 to 0.46007, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2721 - mean_absolute_error: 0.5889 - val_loss: 0.4601 - val_mean_absolute_error: 0.8200\nEpoch 23/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2684 - mean_absolute_error: 0.5840\nEpoch 00023: val_loss did not improve from 0.46007\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2684 - mean_absolute_error: 0.5840 - val_loss: 0.4615 - val_mean_absolute_error: 0.8216\nEpoch 24/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2655 - mean_absolute_error: 0.5802\nEpoch 00024: val_loss did not improve from 0.46007\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2655 - mean_absolute_error: 0.5802 - val_loss: 0.4619 - val_mean_absolute_error: 0.8219\nEpoch 25/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2626 - mean_absolute_error: 0.5765\nEpoch 00025: val_loss did not improve from 0.46007\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2626 - mean_absolute_error: 0.5765 - val_loss: 0.4645 - val_mean_absolute_error: 0.8254\nEpoch 26/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2595 - mean_absolute_error: 0.5723\nEpoch 00026: val_loss improved from 0.46007 to 0.45904, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 476us/sample - loss: 0.2595 - mean_absolute_error: 0.5722 - val_loss: 0.4590 - val_mean_absolute_error: 0.8181\nEpoch 27/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2551 - mean_absolute_error: 0.5667\nEpoch 00027: val_loss did not improve from 0.45904\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2551 - mean_absolute_error: 0.5667 - val_loss: 0.4595 - val_mean_absolute_error: 0.8184\nEpoch 28/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2542 - mean_absolute_error: 0.5657\nEpoch 00028: val_loss improved from 0.45904 to 0.45857, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2541 - mean_absolute_error: 0.5657 - val_loss: 0.4586 - val_mean_absolute_error: 0.8170\nEpoch 29/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2514 - mean_absolute_error: 0.5621\nEpoch 00029: val_loss improved from 0.45857 to 0.45786, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 476us/sample - loss: 0.2514 - mean_absolute_error: 0.5621 - val_loss: 0.4579 - val_mean_absolute_error: 0.8168\nEpoch 30/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2498 - mean_absolute_error: 0.5601\nEpoch 00030: val_loss improved from 0.45786 to 0.45564, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2498 - mean_absolute_error: 0.5601 - val_loss: 0.4556 - val_mean_absolute_error: 0.8140\nEpoch 31/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2485 - mean_absolute_error: 0.5577\nEpoch 00031: val_loss did not improve from 0.45564\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2485 - mean_absolute_error: 0.5576 - val_loss: 0.4572 - val_mean_absolute_error: 0.8155\nEpoch 32/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2470 - mean_absolute_error: 0.5561\nEpoch 00032: val_loss improved from 0.45564 to 0.45530, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2470 - mean_absolute_error: 0.5561 - val_loss: 0.4553 - val_mean_absolute_error: 0.8137\nEpoch 33/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2450 - mean_absolute_error: 0.5535\nEpoch 00033: val_loss did not improve from 0.45530\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2450 - mean_absolute_error: 0.5535 - val_loss: 0.4577 - val_mean_absolute_error: 0.8163\nEpoch 34/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2439 - mean_absolute_error: 0.5517\nEpoch 00034: val_loss did not improve from 0.45530\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2439 - mean_absolute_error: 0.5516 - val_loss: 0.4561 - val_mean_absolute_error: 0.8147\nEpoch 35/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2425 - mean_absolute_error: 0.5501\nEpoch 00035: val_loss improved from 0.45530 to 0.45456, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 476us/sample - loss: 0.2425 - mean_absolute_error: 0.5501 - val_loss: 0.4546 - val_mean_absolute_error: 0.8127\nEpoch 36/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2430 - mean_absolute_error: 0.5501\nEpoch 00036: val_loss did not improve from 0.45456\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2429 - mean_absolute_error: 0.5501 - val_loss: 0.4554 - val_mean_absolute_error: 0.8139\nEpoch 37/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2410 - mean_absolute_error: 0.5471\nEpoch 00037: val_loss did not improve from 0.45456\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2410 - mean_absolute_error: 0.5471 - val_loss: 0.4556 - val_mean_absolute_error: 0.8141\nEpoch 38/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2400 - mean_absolute_error: 0.5463\nEpoch 00038: val_loss improved from 0.45456 to 0.45247, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 33s 486us/sample - loss: 0.2400 - mean_absolute_error: 0.5462 - val_loss: 0.4525 - val_mean_absolute_error: 0.8100\nEpoch 39/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2388 - mean_absolute_error: 0.5444\nEpoch 00039: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2388 - mean_absolute_error: 0.5444 - val_loss: 0.4575 - val_mean_absolute_error: 0.8159\nEpoch 40/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2381 - mean_absolute_error: 0.5435\nEpoch 00040: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2382 - mean_absolute_error: 0.5435 - val_loss: 0.4554 - val_mean_absolute_error: 0.8136\nEpoch 41/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2369 - mean_absolute_error: 0.5420\nEpoch 00041: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2369 - mean_absolute_error: 0.5420 - val_loss: 0.4581 - val_mean_absolute_error: 0.8171\nEpoch 42/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2367 - mean_absolute_error: 0.5415\nEpoch 00042: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2367 - mean_absolute_error: 0.5415 - val_loss: 0.4552 - val_mean_absolute_error: 0.8134\nEpoch 43/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2360 - mean_absolute_error: 0.5406\nEpoch 00043: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2360 - mean_absolute_error: 0.5405 - val_loss: 0.4553 - val_mean_absolute_error: 0.8136\nEpoch 44/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2355 - mean_absolute_error: 0.5401\nEpoch 00044: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2355 - mean_absolute_error: 0.5401 - val_loss: 0.4536 - val_mean_absolute_error: 0.8112\nEpoch 45/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2348 - mean_absolute_error: 0.5388\nEpoch 00045: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2348 - mean_absolute_error: 0.5387 - val_loss: 0.4539 - val_mean_absolute_error: 0.8119\nEpoch 46/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2338 - mean_absolute_error: 0.5378\nEpoch 00046: val_loss did not improve from 0.45247\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2339 - mean_absolute_error: 0.5378 - val_loss: 0.4531 - val_mean_absolute_error: 0.8103\nEpoch 47/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2329 - mean_absolute_error: 0.5361\nEpoch 00047: val_loss improved from 0.45247 to 0.45096, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2329 - mean_absolute_error: 0.5360 - val_loss: 0.4510 - val_mean_absolute_error: 0.8081\nEpoch 48/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2324 - mean_absolute_error: 0.5355\nEpoch 00048: val_loss did not improve from 0.45096\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2324 - mean_absolute_error: 0.5354 - val_loss: 0.4540 - val_mean_absolute_error: 0.8114\nEpoch 49/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2322 - mean_absolute_error: 0.5351\nEpoch 00049: val_loss improved from 0.45096 to 0.45092, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 477us/sample - loss: 0.2322 - mean_absolute_error: 0.5351 - val_loss: 0.4509 - val_mean_absolute_error: 0.8080\nEpoch 50/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2320 - mean_absolute_error: 0.5346\nEpoch 00050: val_loss improved from 0.45092 to 0.45078, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 476us/sample - loss: 0.2320 - mean_absolute_error: 0.5346 - val_loss: 0.4508 - val_mean_absolute_error: 0.8082\nEpoch 51/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2307 - mean_absolute_error: 0.5331\nEpoch 00051: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2307 - mean_absolute_error: 0.5331 - val_loss: 0.4520 - val_mean_absolute_error: 0.8092\nEpoch 52/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2310 - mean_absolute_error: 0.5332\nEpoch 00052: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2310 - mean_absolute_error: 0.5332 - val_loss: 0.4528 - val_mean_absolute_error: 0.8100\nEpoch 53/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2303 - mean_absolute_error: 0.5324\nEpoch 00053: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2303 - mean_absolute_error: 0.5323 - val_loss: 0.4511 - val_mean_absolute_error: 0.8080\nEpoch 54/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2292 - mean_absolute_error: 0.5306\nEpoch 00054: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2292 - mean_absolute_error: 0.5306 - val_loss: 0.4523 - val_mean_absolute_error: 0.8093\nEpoch 55/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2294 - mean_absolute_error: 0.5313\nEpoch 00055: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2294 - mean_absolute_error: 0.5313 - val_loss: 0.4510 - val_mean_absolute_error: 0.8080\nEpoch 56/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2287 - mean_absolute_error: 0.5299\nEpoch 00056: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2287 - mean_absolute_error: 0.5299 - val_loss: 0.4512 - val_mean_absolute_error: 0.8080\nEpoch 57/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2293 - mean_absolute_error: 0.5307\nEpoch 00057: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2293 - mean_absolute_error: 0.5307 - val_loss: 0.4518 - val_mean_absolute_error: 0.8086\nEpoch 58/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2286 - mean_absolute_error: 0.5298\nEpoch 00058: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2286 - mean_absolute_error: 0.5299 - val_loss: 0.4512 - val_mean_absolute_error: 0.8083\nEpoch 59/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2278 - mean_absolute_error: 0.5290\nEpoch 00059: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2279 - mean_absolute_error: 0.5291 - val_loss: 0.4521 - val_mean_absolute_error: 0.8092\nEpoch 60/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2273 - mean_absolute_error: 0.5276\nEpoch 00060: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2273 - mean_absolute_error: 0.5276 - val_loss: 0.4521 - val_mean_absolute_error: 0.8090\nEpoch 61/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2275 - mean_absolute_error: 0.5281\nEpoch 00061: val_loss did not improve from 0.45078\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2276 - mean_absolute_error: 0.5281 - val_loss: 0.4511 - val_mean_absolute_error: 0.8078\nEpoch 62/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2273 - mean_absolute_error: 0.5280\nEpoch 00062: val_loss improved from 0.45078 to 0.45051, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 477us/sample - loss: 0.2273 - mean_absolute_error: 0.5280 - val_loss: 0.4505 - val_mean_absolute_error: 0.8077\nEpoch 63/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2271 - mean_absolute_error: 0.5275\nEpoch 00063: val_loss did not improve from 0.45051\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2271 - mean_absolute_error: 0.5275 - val_loss: 0.4506 - val_mean_absolute_error: 0.8070\nEpoch 64/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2264 - mean_absolute_error: 0.5269\nEpoch 00064: val_loss did not improve from 0.45051\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2264 - mean_absolute_error: 0.5269 - val_loss: 0.4528 - val_mean_absolute_error: 0.8102\nEpoch 65/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2262 - mean_absolute_error: 0.5262\nEpoch 00065: val_loss did not improve from 0.45051\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2262 - mean_absolute_error: 0.5262 - val_loss: 0.4543 - val_mean_absolute_error: 0.8115\nEpoch 66/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2260 - mean_absolute_error: 0.5259\nEpoch 00066: val_loss did not improve from 0.45051\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2260 - mean_absolute_error: 0.5259 - val_loss: 0.4513 - val_mean_absolute_error: 0.8075\nEpoch 67/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2260 - mean_absolute_error: 0.5259\nEpoch 00067: val_loss did not improve from 0.45051\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2259 - mean_absolute_error: 0.5259 - val_loss: 0.4527 - val_mean_absolute_error: 0.8092\nEpoch 68/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2253 - mean_absolute_error: 0.5250\nEpoch 00068: val_loss did not improve from 0.45051\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2253 - mean_absolute_error: 0.5249 - val_loss: 0.4520 - val_mean_absolute_error: 0.8087\nEpoch 69/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2253 - mean_absolute_error: 0.5251\nEpoch 00069: val_loss improved from 0.45051 to 0.45047, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2253 - mean_absolute_error: 0.5251 - val_loss: 0.4505 - val_mean_absolute_error: 0.8070\nEpoch 70/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2254 - mean_absolute_error: 0.5250\nEpoch 00070: val_loss improved from 0.45047 to 0.45025, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 478us/sample - loss: 0.2253 - mean_absolute_error: 0.5250 - val_loss: 0.4503 - val_mean_absolute_error: 0.8065\nEpoch 71/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2248 - mean_absolute_error: 0.5240\nEpoch 00071: val_loss did not improve from 0.45025\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2247 - mean_absolute_error: 0.5240 - val_loss: 0.4520 - val_mean_absolute_error: 0.8086\nEpoch 72/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2246 - mean_absolute_error: 0.5239\nEpoch 00072: val_loss did not improve from 0.45025\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2246 - mean_absolute_error: 0.5239 - val_loss: 0.4506 - val_mean_absolute_error: 0.8073\nEpoch 73/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2249 - mean_absolute_error: 0.5242\nEpoch 00073: val_loss did not improve from 0.45025\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2248 - mean_absolute_error: 0.5242 - val_loss: 0.4520 - val_mean_absolute_error: 0.8086\nEpoch 74/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2243 - mean_absolute_error: 0.5232\nEpoch 00074: val_loss did not improve from 0.45025\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2243 - mean_absolute_error: 0.5232 - val_loss: 0.4507 - val_mean_absolute_error: 0.8069\nEpoch 75/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2238 - mean_absolute_error: 0.5226\nEpoch 00075: val_loss did not improve from 0.45025\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2238 - mean_absolute_error: 0.5226 - val_loss: 0.4525 - val_mean_absolute_error: 0.8092\nEpoch 76/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2239 - mean_absolute_error: 0.5230\nEpoch 00076: val_loss did not improve from 0.45025\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2239 - mean_absolute_error: 0.5230 - val_loss: 0.4513 - val_mean_absolute_error: 0.8078\nEpoch 77/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2234 - mean_absolute_error: 0.5222\nEpoch 00077: val_loss improved from 0.45025 to 0.44999, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2234 - mean_absolute_error: 0.5221 - val_loss: 0.4500 - val_mean_absolute_error: 0.8061\nEpoch 78/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2233 - mean_absolute_error: 0.5218\nEpoch 00078: val_loss did not improve from 0.44999\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2233 - mean_absolute_error: 0.5218 - val_loss: 0.4510 - val_mean_absolute_error: 0.8069\nEpoch 79/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2232 - mean_absolute_error: 0.5218\nEpoch 00079: val_loss did not improve from 0.44999\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2232 - mean_absolute_error: 0.5218 - val_loss: 0.4506 - val_mean_absolute_error: 0.8070\nEpoch 80/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2227 - mean_absolute_error: 0.5210\nEpoch 00080: val_loss improved from 0.44999 to 0.44982, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2227 - mean_absolute_error: 0.5210 - val_loss: 0.4498 - val_mean_absolute_error: 0.8059\nEpoch 81/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2229 - mean_absolute_error: 0.5214\nEpoch 00081: val_loss improved from 0.44982 to 0.44977, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2229 - mean_absolute_error: 0.5214 - val_loss: 0.4498 - val_mean_absolute_error: 0.8055\nEpoch 82/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2228 - mean_absolute_error: 0.5211\nEpoch 00082: val_loss did not improve from 0.44977\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2229 - mean_absolute_error: 0.5212 - val_loss: 0.4524 - val_mean_absolute_error: 0.8090\nEpoch 83/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2222 - mean_absolute_error: 0.5206\nEpoch 00083: val_loss did not improve from 0.44977\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2222 - mean_absolute_error: 0.5206 - val_loss: 0.4500 - val_mean_absolute_error: 0.8062\nEpoch 84/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2222 - mean_absolute_error: 0.5203\nEpoch 00084: val_loss did not improve from 0.44977\n67485/67485 [==============================] - 32s 470us/sample - loss: 0.2222 - mean_absolute_error: 0.5203 - val_loss: 0.4502 - val_mean_absolute_error: 0.8065\nEpoch 85/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2225 - mean_absolute_error: 0.5204\nEpoch 00085: val_loss did not improve from 0.44977\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2225 - mean_absolute_error: 0.5204 - val_loss: 0.4515 - val_mean_absolute_error: 0.8077\nEpoch 86/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2224 - mean_absolute_error: 0.5205\nEpoch 00086: val_loss did not improve from 0.44977\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2224 - mean_absolute_error: 0.5205 - val_loss: 0.4498 - val_mean_absolute_error: 0.8056\nEpoch 87/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2218 - mean_absolute_error: 0.5197\nEpoch 00087: val_loss did not improve from 0.44977\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2218 - mean_absolute_error: 0.5197 - val_loss: 0.4500 - val_mean_absolute_error: 0.8060\nEpoch 88/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2219 - mean_absolute_error: 0.5198\nEpoch 00088: val_loss improved from 0.44977 to 0.44898, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2219 - mean_absolute_error: 0.5197 - val_loss: 0.4490 - val_mean_absolute_error: 0.8045\nEpoch 89/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2219 - mean_absolute_error: 0.5196\nEpoch 00089: val_loss did not improve from 0.44898\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2218 - mean_absolute_error: 0.5196 - val_loss: 0.4498 - val_mean_absolute_error: 0.8054\nEpoch 90/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2215 - mean_absolute_error: 0.5192\nEpoch 00090: val_loss did not improve from 0.44898\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2215 - mean_absolute_error: 0.5191 - val_loss: 0.4527 - val_mean_absolute_error: 0.8096\nEpoch 91/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2215 - mean_absolute_error: 0.5193\nEpoch 00091: val_loss did not improve from 0.44898\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2215 - mean_absolute_error: 0.5193 - val_loss: 0.4522 - val_mean_absolute_error: 0.8084\nEpoch 92/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2220 - mean_absolute_error: 0.5197\nEpoch 00092: val_loss improved from 0.44898 to 0.44858, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 476us/sample - loss: 0.2220 - mean_absolute_error: 0.5197 - val_loss: 0.4486 - val_mean_absolute_error: 0.8045\nEpoch 93/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2209 - mean_absolute_error: 0.5181\nEpoch 00093: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2209 - mean_absolute_error: 0.5181 - val_loss: 0.4494 - val_mean_absolute_error: 0.8054\nEpoch 94/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2215 - mean_absolute_error: 0.5191\nEpoch 00094: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2215 - mean_absolute_error: 0.5191 - val_loss: 0.4518 - val_mean_absolute_error: 0.8080\nEpoch 95/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2206 - mean_absolute_error: 0.5180\nEpoch 00095: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2207 - mean_absolute_error: 0.5181 - val_loss: 0.4510 - val_mean_absolute_error: 0.8073\nEpoch 96/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2207 - mean_absolute_error: 0.5179\nEpoch 00096: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2206 - mean_absolute_error: 0.5179 - val_loss: 0.4508 - val_mean_absolute_error: 0.8068\nEpoch 97/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2207 - mean_absolute_error: 0.5179\nEpoch 00097: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2206 - mean_absolute_error: 0.5179 - val_loss: 0.4490 - val_mean_absolute_error: 0.8049\nEpoch 98/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2209 - mean_absolute_error: 0.5182\nEpoch 00098: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2210 - mean_absolute_error: 0.5183 - val_loss: 0.4512 - val_mean_absolute_error: 0.8073\nEpoch 99/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2208 - mean_absolute_error: 0.5181\nEpoch 00099: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2208 - mean_absolute_error: 0.5181 - val_loss: 0.4508 - val_mean_absolute_error: 0.8071\nEpoch 100/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2206 - mean_absolute_error: 0.5176\nEpoch 00100: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2205 - mean_absolute_error: 0.5176 - val_loss: 0.4511 - val_mean_absolute_error: 0.8074\nEpoch 101/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2203 - mean_absolute_error: 0.5172\nEpoch 00101: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2204 - mean_absolute_error: 0.5174 - val_loss: 0.4511 - val_mean_absolute_error: 0.8070\nEpoch 102/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2202 - mean_absolute_error: 0.5168\nEpoch 00102: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2202 - mean_absolute_error: 0.5168 - val_loss: 0.4497 - val_mean_absolute_error: 0.8047\nEpoch 103/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2200 - mean_absolute_error: 0.5168\nEpoch 00103: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2200 - mean_absolute_error: 0.5167 - val_loss: 0.4509 - val_mean_absolute_error: 0.8062\nEpoch 104/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2201 - mean_absolute_error: 0.5170\nEpoch 00104: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2201 - mean_absolute_error: 0.5170 - val_loss: 0.4538 - val_mean_absolute_error: 0.8101\nEpoch 105/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2201 - mean_absolute_error: 0.5172\nEpoch 00105: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2200 - mean_absolute_error: 0.5172 - val_loss: 0.4488 - val_mean_absolute_error: 0.8044\nEpoch 106/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2199 - mean_absolute_error: 0.5168\nEpoch 00106: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2199 - mean_absolute_error: 0.5168 - val_loss: 0.4504 - val_mean_absolute_error: 0.8061\nEpoch 107/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2198 - mean_absolute_error: 0.5166\nEpoch 00107: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2198 - mean_absolute_error: 0.5166 - val_loss: 0.4515 - val_mean_absolute_error: 0.8078\nEpoch 108/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2198 - mean_absolute_error: 0.5163\nEpoch 00108: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2197 - mean_absolute_error: 0.5163 - val_loss: 0.4494 - val_mean_absolute_error: 0.8047\nEpoch 109/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2197 - mean_absolute_error: 0.5166\nEpoch 00109: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2197 - mean_absolute_error: 0.5166 - val_loss: 0.4509 - val_mean_absolute_error: 0.8069\nEpoch 110/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2195 - mean_absolute_error: 0.5164\nEpoch 00110: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2195 - mean_absolute_error: 0.5164 - val_loss: 0.4503 - val_mean_absolute_error: 0.8064\nEpoch 111/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2195 - mean_absolute_error: 0.5158\nEpoch 00111: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2195 - mean_absolute_error: 0.5158 - val_loss: 0.4533 - val_mean_absolute_error: 0.8099\nEpoch 112/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2199 - mean_absolute_error: 0.5164\nEpoch 00112: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2198 - mean_absolute_error: 0.5164 - val_loss: 0.4510 - val_mean_absolute_error: 0.8068\nEpoch 113/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2189 - mean_absolute_error: 0.5151\nEpoch 00113: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2189 - mean_absolute_error: 0.5152 - val_loss: 0.4512 - val_mean_absolute_error: 0.8075\nEpoch 114/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2187 - mean_absolute_error: 0.5151\nEpoch 00114: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2187 - mean_absolute_error: 0.5151 - val_loss: 0.4518 - val_mean_absolute_error: 0.8078\nEpoch 115/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2187 - mean_absolute_error: 0.5149\nEpoch 00115: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 470us/sample - loss: 0.2187 - mean_absolute_error: 0.5149 - val_loss: 0.4506 - val_mean_absolute_error: 0.8059\nEpoch 116/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2190 - mean_absolute_error: 0.5151\nEpoch 00116: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 468us/sample - loss: 0.2190 - mean_absolute_error: 0.5151 - val_loss: 0.4486 - val_mean_absolute_error: 0.8042\nEpoch 117/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2188 - mean_absolute_error: 0.5150\nEpoch 00117: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2188 - mean_absolute_error: 0.5150 - val_loss: 0.4514 - val_mean_absolute_error: 0.8078\nEpoch 118/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2188 - mean_absolute_error: 0.5150\nEpoch 00118: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2187 - mean_absolute_error: 0.5148 - val_loss: 0.4495 - val_mean_absolute_error: 0.8050\nEpoch 119/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2188 - mean_absolute_error: 0.5149\nEpoch 00119: val_loss did not improve from 0.44858\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2188 - mean_absolute_error: 0.5149 - val_loss: 0.4504 - val_mean_absolute_error: 0.8061\nEpoch 120/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2187 - mean_absolute_error: 0.5148\nEpoch 00120: val_loss improved from 0.44858 to 0.44845, saving model to results\\2021-11-30_MIXED-huber_loss-adam-LSTM-linear-layers-3-units-1000-b.h5\n67485/67485 [==============================] - 32s 477us/sample - loss: 0.2187 - mean_absolute_error: 0.5148 - val_loss: 0.4485 - val_mean_absolute_error: 0.8041\nEpoch 121/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2184 - mean_absolute_error: 0.5144\nEpoch 00121: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2184 - mean_absolute_error: 0.5144 - val_loss: 0.4519 - val_mean_absolute_error: 0.8078\nEpoch 122/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2188 - mean_absolute_error: 0.5147\nEpoch 00122: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2188 - mean_absolute_error: 0.5147 - val_loss: 0.4526 - val_mean_absolute_error: 0.8087\nEpoch 123/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2187 - mean_absolute_error: 0.5147\nEpoch 00123: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2188 - mean_absolute_error: 0.5148 - val_loss: 0.4505 - val_mean_absolute_error: 0.8064\nEpoch 124/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2185 - mean_absolute_error: 0.5144\nEpoch 00124: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2185 - mean_absolute_error: 0.5144 - val_loss: 0.4520 - val_mean_absolute_error: 0.8078\nEpoch 125/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2182 - mean_absolute_error: 0.5140\nEpoch 00125: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2182 - mean_absolute_error: 0.5140 - val_loss: 0.4509 - val_mean_absolute_error: 0.8070\nEpoch 126/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2186 - mean_absolute_error: 0.5142\nEpoch 00126: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2185 - mean_absolute_error: 0.5142 - val_loss: 0.4499 - val_mean_absolute_error: 0.8055\nEpoch 127/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2181 - mean_absolute_error: 0.5138\nEpoch 00127: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2181 - mean_absolute_error: 0.5138 - val_loss: 0.4531 - val_mean_absolute_error: 0.8094\nEpoch 128/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2180 - mean_absolute_error: 0.5139\nEpoch 00128: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2180 - mean_absolute_error: 0.5139 - val_loss: 0.4497 - val_mean_absolute_error: 0.8058\nEpoch 129/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2178 - mean_absolute_error: 0.5136\nEpoch 00129: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2179 - mean_absolute_error: 0.5137 - val_loss: 0.4497 - val_mean_absolute_error: 0.8052\nEpoch 130/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2182 - mean_absolute_error: 0.5138\nEpoch 00130: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2182 - mean_absolute_error: 0.5138 - val_loss: 0.4496 - val_mean_absolute_error: 0.8055\nEpoch 131/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2180 - mean_absolute_error: 0.5138\nEpoch 00131: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2180 - mean_absolute_error: 0.5138 - val_loss: 0.4525 - val_mean_absolute_error: 0.8090\nEpoch 132/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2182 - mean_absolute_error: 0.5139\nEpoch 00132: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2183 - mean_absolute_error: 0.5139 - val_loss: 0.4492 - val_mean_absolute_error: 0.8049\nEpoch 133/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2178 - mean_absolute_error: 0.5136\nEpoch 00133: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2177 - mean_absolute_error: 0.5136 - val_loss: 0.4511 - val_mean_absolute_error: 0.8071\nEpoch 134/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2176 - mean_absolute_error: 0.5130\nEpoch 00134: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2176 - mean_absolute_error: 0.5131 - val_loss: 0.4510 - val_mean_absolute_error: 0.8067\nEpoch 135/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2177 - mean_absolute_error: 0.5133\nEpoch 00135: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2176 - mean_absolute_error: 0.5133 - val_loss: 0.4496 - val_mean_absolute_error: 0.8051\nEpoch 136/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2179 - mean_absolute_error: 0.5136\nEpoch 00136: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2179 - mean_absolute_error: 0.5137 - val_loss: 0.4516 - val_mean_absolute_error: 0.8072\nEpoch 137/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2176 - mean_absolute_error: 0.5131\nEpoch 00137: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2177 - mean_absolute_error: 0.5131 - val_loss: 0.4497 - val_mean_absolute_error: 0.8052\nEpoch 138/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2178 - mean_absolute_error: 0.5135\nEpoch 00138: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2179 - mean_absolute_error: 0.5135 - val_loss: 0.4490 - val_mean_absolute_error: 0.8047\nEpoch 139/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2176 - mean_absolute_error: 0.5132\nEpoch 00139: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2176 - mean_absolute_error: 0.5132 - val_loss: 0.4532 - val_mean_absolute_error: 0.8093\nEpoch 140/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2174 - mean_absolute_error: 0.5127\nEpoch 00140: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2174 - mean_absolute_error: 0.5126 - val_loss: 0.4539 - val_mean_absolute_error: 0.8100\nEpoch 141/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2177 - mean_absolute_error: 0.5131\nEpoch 00141: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2177 - mean_absolute_error: 0.5131 - val_loss: 0.4513 - val_mean_absolute_error: 0.8068\nEpoch 142/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2175 - mean_absolute_error: 0.5129\nEpoch 00142: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2175 - mean_absolute_error: 0.5129 - val_loss: 0.4509 - val_mean_absolute_error: 0.8064\nEpoch 143/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2173 - mean_absolute_error: 0.5127\nEpoch 00143: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2173 - mean_absolute_error: 0.5127 - val_loss: 0.4519 - val_mean_absolute_error: 0.8075\nEpoch 144/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2176 - mean_absolute_error: 0.5129\nEpoch 00144: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2176 - mean_absolute_error: 0.5130 - val_loss: 0.4499 - val_mean_absolute_error: 0.8052\nEpoch 145/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2175 - mean_absolute_error: 0.5128\nEpoch 00145: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2175 - mean_absolute_error: 0.5128 - val_loss: 0.4532 - val_mean_absolute_error: 0.8092\nEpoch 146/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2171 - mean_absolute_error: 0.5122\nEpoch 00146: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2171 - mean_absolute_error: 0.5121 - val_loss: 0.4524 - val_mean_absolute_error: 0.8086\nEpoch 147/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2170 - mean_absolute_error: 0.5124\nEpoch 00147: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2170 - mean_absolute_error: 0.5124 - val_loss: 0.4523 - val_mean_absolute_error: 0.8079\nEpoch 148/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2172 - mean_absolute_error: 0.5124\nEpoch 00148: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2172 - mean_absolute_error: 0.5124 - val_loss: 0.4518 - val_mean_absolute_error: 0.8074\nEpoch 149/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2171 - mean_absolute_error: 0.5120\nEpoch 00149: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2170 - mean_absolute_error: 0.5120 - val_loss: 0.4524 - val_mean_absolute_error: 0.8082\nEpoch 150/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2172 - mean_absolute_error: 0.5127\nEpoch 00150: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2172 - mean_absolute_error: 0.5127 - val_loss: 0.4536 - val_mean_absolute_error: 0.8096\nEpoch 151/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2170 - mean_absolute_error: 0.5123\nEpoch 00151: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2170 - mean_absolute_error: 0.5122 - val_loss: 0.4486 - val_mean_absolute_error: 0.8037\nEpoch 152/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2172 - mean_absolute_error: 0.5121\nEpoch 00152: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 476us/sample - loss: 0.2172 - mean_absolute_error: 0.5120 - val_loss: 0.4518 - val_mean_absolute_error: 0.8075\nEpoch 153/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2169 - mean_absolute_error: 0.5120\nEpoch 00153: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2169 - mean_absolute_error: 0.5121 - val_loss: 0.4518 - val_mean_absolute_error: 0.8077\nEpoch 154/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2168 - mean_absolute_error: 0.5118\nEpoch 00154: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2168 - mean_absolute_error: 0.5118 - val_loss: 0.4510 - val_mean_absolute_error: 0.8065\nEpoch 155/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2167 - mean_absolute_error: 0.5120\nEpoch 00155: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2168 - mean_absolute_error: 0.5121 - val_loss: 0.4500 - val_mean_absolute_error: 0.8055\nEpoch 156/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2166 - mean_absolute_error: 0.5114\nEpoch 00156: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2166 - mean_absolute_error: 0.5114 - val_loss: 0.4509 - val_mean_absolute_error: 0.8067\nEpoch 157/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2167 - mean_absolute_error: 0.5116\nEpoch 00157: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2167 - mean_absolute_error: 0.5116 - val_loss: 0.4494 - val_mean_absolute_error: 0.8044\nEpoch 158/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2168 - mean_absolute_error: 0.5118\nEpoch 00158: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2168 - mean_absolute_error: 0.5117 - val_loss: 0.4547 - val_mean_absolute_error: 0.8106\nEpoch 159/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2170 - mean_absolute_error: 0.5119\nEpoch 00159: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2169 - mean_absolute_error: 0.5118 - val_loss: 0.4525 - val_mean_absolute_error: 0.8087\nEpoch 160/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2167 - mean_absolute_error: 0.5118\nEpoch 00160: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2167 - mean_absolute_error: 0.5118 - val_loss: 0.4509 - val_mean_absolute_error: 0.8063\nEpoch 161/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2166 - mean_absolute_error: 0.5118\nEpoch 00161: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2166 - mean_absolute_error: 0.5117 - val_loss: 0.4530 - val_mean_absolute_error: 0.8092\nEpoch 162/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2164 - mean_absolute_error: 0.5110\nEpoch 00162: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2163 - mean_absolute_error: 0.5110 - val_loss: 0.4525 - val_mean_absolute_error: 0.8082\nEpoch 163/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2168 - mean_absolute_error: 0.5121\nEpoch 00163: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2168 - mean_absolute_error: 0.5121 - val_loss: 0.4530 - val_mean_absolute_error: 0.8088\nEpoch 164/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2164 - mean_absolute_error: 0.5114\nEpoch 00164: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2164 - mean_absolute_error: 0.5114 - val_loss: 0.4529 - val_mean_absolute_error: 0.8086\nEpoch 165/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2167 - mean_absolute_error: 0.5113\nEpoch 00165: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2167 - mean_absolute_error: 0.5113 - val_loss: 0.4531 - val_mean_absolute_error: 0.8089\nEpoch 166/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2165 - mean_absolute_error: 0.5114\nEpoch 00166: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2165 - mean_absolute_error: 0.5114 - val_loss: 0.4532 - val_mean_absolute_error: 0.8090\nEpoch 167/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2165 - mean_absolute_error: 0.5112\nEpoch 00167: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2165 - mean_absolute_error: 0.5112 - val_loss: 0.4523 - val_mean_absolute_error: 0.8080\nEpoch 168/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2161 - mean_absolute_error: 0.5109\nEpoch 00168: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2161 - mean_absolute_error: 0.5109 - val_loss: 0.4523 - val_mean_absolute_error: 0.8080\nEpoch 169/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2162 - mean_absolute_error: 0.5109\nEpoch 00169: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2162 - mean_absolute_error: 0.5109 - val_loss: 0.4537 - val_mean_absolute_error: 0.8096\nEpoch 170/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2164 - mean_absolute_error: 0.5111\nEpoch 00170: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2164 - mean_absolute_error: 0.5110 - val_loss: 0.4521 - val_mean_absolute_error: 0.8075\nEpoch 171/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2165 - mean_absolute_error: 0.5111\nEpoch 00171: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 474us/sample - loss: 0.2164 - mean_absolute_error: 0.5110 - val_loss: 0.4515 - val_mean_absolute_error: 0.8070\nEpoch 172/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2160 - mean_absolute_error: 0.5105\nEpoch 00172: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2160 - mean_absolute_error: 0.5105 - val_loss: 0.4540 - val_mean_absolute_error: 0.8099\nEpoch 173/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2165 - mean_absolute_error: 0.5113\nEpoch 00173: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2164 - mean_absolute_error: 0.5112 - val_loss: 0.4558 - val_mean_absolute_error: 0.8119\nEpoch 174/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2161 - mean_absolute_error: 0.5109\nEpoch 00174: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2162 - mean_absolute_error: 0.5109 - val_loss: 0.4509 - val_mean_absolute_error: 0.8059\nEpoch 175/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2159 - mean_absolute_error: 0.5103\nEpoch 00175: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2159 - mean_absolute_error: 0.5103 - val_loss: 0.4507 - val_mean_absolute_error: 0.8057\nEpoch 176/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2160 - mean_absolute_error: 0.5105\nEpoch 00176: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2160 - mean_absolute_error: 0.5104 - val_loss: 0.4510 - val_mean_absolute_error: 0.8062\nEpoch 177/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2160 - mean_absolute_error: 0.5106\nEpoch 00177: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2160 - mean_absolute_error: 0.5107 - val_loss: 0.4520 - val_mean_absolute_error: 0.8073\nEpoch 178/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2157 - mean_absolute_error: 0.5101\nEpoch 00178: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2157 - mean_absolute_error: 0.5102 - val_loss: 0.4540 - val_mean_absolute_error: 0.8097\nEpoch 179/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2158 - mean_absolute_error: 0.5101\nEpoch 00179: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2159 - mean_absolute_error: 0.5101 - val_loss: 0.4528 - val_mean_absolute_error: 0.8084\nEpoch 180/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2161 - mean_absolute_error: 0.5105\nEpoch 00180: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2160 - mean_absolute_error: 0.5105 - val_loss: 0.4554 - val_mean_absolute_error: 0.8119\nEpoch 181/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2162 - mean_absolute_error: 0.5107\nEpoch 00181: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2161 - mean_absolute_error: 0.5106 - val_loss: 0.4529 - val_mean_absolute_error: 0.8088\nEpoch 182/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2159 - mean_absolute_error: 0.5106\nEpoch 00182: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2159 - mean_absolute_error: 0.5106 - val_loss: 0.4557 - val_mean_absolute_error: 0.8120\nEpoch 183/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2158 - mean_absolute_error: 0.5102\nEpoch 00183: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2158 - mean_absolute_error: 0.5101 - val_loss: 0.4522 - val_mean_absolute_error: 0.8078\nEpoch 184/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2159 - mean_absolute_error: 0.5105\nEpoch 00184: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2159 - mean_absolute_error: 0.5105 - val_loss: 0.4541 - val_mean_absolute_error: 0.8104\nEpoch 185/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2158 - mean_absolute_error: 0.5102\nEpoch 00185: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2159 - mean_absolute_error: 0.5104 - val_loss: 0.4535 - val_mean_absolute_error: 0.8098\nEpoch 186/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2160 - mean_absolute_error: 0.5105\nEpoch 00186: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2160 - mean_absolute_error: 0.5105 - val_loss: 0.4547 - val_mean_absolute_error: 0.8109\nEpoch 187/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2158 - mean_absolute_error: 0.5102\nEpoch 00187: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2158 - mean_absolute_error: 0.5102 - val_loss: 0.4518 - val_mean_absolute_error: 0.8074\nEpoch 188/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2160 - mean_absolute_error: 0.5103\nEpoch 00188: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2160 - mean_absolute_error: 0.5103 - val_loss: 0.4529 - val_mean_absolute_error: 0.8084\nEpoch 189/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2156 - mean_absolute_error: 0.5098\nEpoch 00189: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2156 - mean_absolute_error: 0.5098 - val_loss: 0.4517 - val_mean_absolute_error: 0.8075\nEpoch 190/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2155 - mean_absolute_error: 0.5099\nEpoch 00190: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2156 - mean_absolute_error: 0.5099 - val_loss: 0.4544 - val_mean_absolute_error: 0.8108\nEpoch 191/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2159 - mean_absolute_error: 0.5103\nEpoch 00191: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2159 - mean_absolute_error: 0.5102 - val_loss: 0.4558 - val_mean_absolute_error: 0.8125\nEpoch 192/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2158 - mean_absolute_error: 0.5104\nEpoch 00192: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 475us/sample - loss: 0.2158 - mean_absolute_error: 0.5104 - val_loss: 0.4532 - val_mean_absolute_error: 0.8095\nEpoch 193/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2157 - mean_absolute_error: 0.5099\nEpoch 00193: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2157 - mean_absolute_error: 0.5099 - val_loss: 0.4514 - val_mean_absolute_error: 0.8073\nEpoch 194/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2155 - mean_absolute_error: 0.5098\nEpoch 00194: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2156 - mean_absolute_error: 0.5099 - val_loss: 0.4528 - val_mean_absolute_error: 0.8089\nEpoch 195/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2156 - mean_absolute_error: 0.5101\nEpoch 00195: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2156 - mean_absolute_error: 0.5101 - val_loss: 0.4522 - val_mean_absolute_error: 0.8082\nEpoch 196/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2155 - mean_absolute_error: 0.5097\nEpoch 00196: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2154 - mean_absolute_error: 0.5097 - val_loss: 0.4544 - val_mean_absolute_error: 0.8106\nEpoch 197/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2154 - mean_absolute_error: 0.5099\nEpoch 00197: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2154 - mean_absolute_error: 0.5098 - val_loss: 0.4526 - val_mean_absolute_error: 0.8086\nEpoch 198/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2155 - mean_absolute_error: 0.5097\nEpoch 00198: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 471us/sample - loss: 0.2155 - mean_absolute_error: 0.5097 - val_loss: 0.4542 - val_mean_absolute_error: 0.8102\nEpoch 199/200\n67392/67485 [============================>.] - ETA: 0s - loss: 0.2152 - mean_absolute_error: 0.5093\nEpoch 00199: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 472us/sample - loss: 0.2152 - mean_absolute_error: 0.5093 - val_loss: 0.4519 - val_mean_absolute_error: 0.8075\nEpoch 200/200\n67456/67485 [============================>.] - ETA: 0s - loss: 0.2151 - mean_absolute_error: 0.5091\nEpoch 00200: val_loss did not improve from 0.44845\n67485/67485 [==============================] - 32s 473us/sample - loss: 0.2151 - mean_absolute_error: 0.5091 - val_loss: 0.4537 - val_mean_absolute_error: 0.8097\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4af3f42543d4b6660bd82e0a56335242d7162b12
11,710
ipynb
Jupyter Notebook
notebooks/08-Sublime-Text.ipynb
jbwhit/data-science-tips-and-tricks
cb65bb86c64eeb7591789bb0c5ff92cd743d664b
[ "MIT" ]
4
2017-06-26T19:12:02.000Z
2021-07-26T04:40:39.000Z
notebooks/08-Sublime-Text.ipynb
jbwhit/data-science-tips-and-tricks
cb65bb86c64eeb7591789bb0c5ff92cd743d664b
[ "MIT" ]
null
null
null
notebooks/08-Sublime-Text.ipynb
jbwhit/data-science-tips-and-tricks
cb65bb86c64eeb7591789bb0c5ff92cd743d664b
[ "MIT" ]
null
null
null
36.940063
367
0.60427
[ [ [ "# Sublime Text\n\n## Getting set up\n\n### Laptop install Sublime Text (Done once per laptop)\n\n1. Step one is to download and install [Sublime Text](https://www.sublimetext.com/3). Sidenote: You don't need to purchase a license, you can use it forever with all features in evaluate mode. If you purchase a license it follows you and you can install it on all your future laptops.\n\n2. **Install Package Manager**: open Sublime Text, then open command palette (we will use this several times)\n\n - CMD + SHIFT + P (Mac)\n - CTRL + SHIFT + P (Windows)\n\nstart typing \"install\" (Sidenote: as you type it will auto-filter, you can always select with your mouse the one that you want, or if the one you want is the top highlighted match, just hit enter.)\n\n", "_____no_output_____" ], [ "## SQLBeautifier\n\n```../examples/sqlbeautifier.sql```", "_____no_output_____" ], [ "## install sublimelinter\n\n### proselint (markdown)\n\n### shellcheck\n\nFrom: https://github.com/koalaman/shellcheck\n\n> The goals of ShellCheck are\n\n> - To point out and clarify typical beginner's syntax issues that cause a shell to give cryptic error messages.\n\n> - To point out and clarify typical intermediate level semantic problems that cause a shell to behave strangely and counter-intuitively.\n\n> - To point out subtle caveats, corner cases and pitfalls that may cause an advanced user's otherwise working script to fail under future circumstances.\n\n> See the [gallery of bad code](https://github.com/koalaman/shellcheck/blob/master/README.md#user-content-gallery-of-bad-code) for examples of what ShellCheck can help you identify!", "_____no_output_____" ], [ "## anaconda (not what you think!)\n\nAutomatically formats your code to be pep8 (or whatever variant you prefer). Should SVDS have an official style-guide for python?", "_____no_output_____" ], [ "## Others \n \n - install BracketHighlighter\n - install SidebarEnhancements\n - install text pastry\n - C-option N example\n - install wordcount\n - sublime-build \n - tools > build\n - install LaTeXTools (academic papers)", "_____no_output_____" ], [ "## rsub (subl)\n\nOnce you set up everything as below this is how you'll be able to edit files living on a server from the comfort of your laptop.\n\n1. `ssh` into the Mothership by setting up the port forwarding (keeping this open)\n2. Sublime Text open on your laptop\n3. `subl whatever.py` and enjoy editing your text file on your laptop's Sublime Text (remember to hit save frequently!)\n\n### Setting up remote Sublime Text editing\n\nThese instructions tell you how to set up your laptop and a server (mothership) so that you can edit files directly on the server by using Sublime Text on your laptop. You will have to make changes at different places and these instructions vary by what kind of laptop you have (windows/macOS).\n\nAlso, for complicated reasons, each laptop that connects to the mothership needs to have its own unique ports assigned to it. This applies to you if you have 2 laptops. So we'll start out assigning the following ports to people. For the rest of the instructions, you should replace {YOUR_PORT} with the following numbers (and choose the one assigned to you):\n\n 52687 # Free to assign\n 52688 # Free to assign\n 52689 # Free to assign\n 52690 # Free to assign\n 52691 # Free to assign\n 52692 # Free to assign\n 52693 # Free to assign\n 52694 # Free to assign\n 52695 # Free to assign\n 52696 # Free to assign\n 52698 # Default port\n\nAgain, we just arbitrarily assigned these (see the advanced notes section if you need to change this).\n\nAnd where you see {MOTHERSHIP_IP_ADDRESS} replace with the correct edgenode IP address: at the time of writing this, the SVDS Node's IP was: 10.178.134.62\n\nAnd where you see {USER} replace with your username `jbwhit` for example.\n\n\n### Installing `rsub`\n\n1. **Install `rsub`**: open command palette; type `install` (select option \"Package Control: Install Package\"); type `rsub` and select it. If you don't see it listed it's likely already installed. You can check by opening preferences and seeing if you have an rsub option.\n\n2. Create a file on your laptop called `rsub.sublime-settings` in folder (find by clicking in Sublime Text): `Preferences>Browse Packages>User>`\n\nThe contents of the file -- remember to replace {YOUR_PORT} with your port:\n\n```\n/*\n rsub default settings\n*/\n{\n /*\n rsub listen port\n IMPORTANT: Use a different port for each machine.\n */\n \"port\": {YOUR_PORT},\n\n /*\n rsub listen host\n\n WARNING: it's NOT recommended to change this option,\n use SSH tunneling instead.\n */\n \"host\": \"localhost\"\n}\n```", "_____no_output_____" ], [ "### Laptop ssh port forwarding [Windows]\n\nWe recommend installing [Git Bash](https://git-scm.com/download/win) -- install and accept the default options.\n\nCreate a shortcut script to connect to the edgenode with the Sublime connection.\n\n1. Start GitBash\n\n2. Create a file called `sublime_port_forward` (or whatever you want it to be)\n\n a. Navigate to your home directory on your Windows machine and create a new file (with Sublime Text if you want)!\n\n3. Paste the following one line as the entire content of that file (replacing as required):\n\n ssh -R {YOUR_PORT}:localhost:{YOUR_PORT} {USER}@{MOTHERSHIP_IP_ADDRESS}\n\nExample: `ssh -R 52697:localhost:52697 [email protected]`\n\n4. Save the file\n\n\n### Setting up ssh port forwarding [MacOS]\n\n1. Edit `~/.ssh/config` and update with relevant IP address {MOTHERSHIP_IP_ADDRESS} -- replace \"{MOTHERSHIP_IP_ADDRESS}\" with a number like {MOTHERSHIP_IP_ADDRESS}\n\n```bash\nHost rsub-svdsnode\n HostName {MOTHERSHIP_IP_ADDRESS}\n RemoteForward {YOUR_PORT} 127.0.0.1:{YOUR_PORT}\n```\n\nSetting up this config lets you type `ssh rsub-svdsnode` and you will SSH into the mothership. You can shorten this name to simply `rsub` or anything else in the Host section of the config. If you connect to multiple motherships (or edgenodes) simply create new rule by copy/pasting the three lines and filling in the relevant details.\n\n### Set up Mothership (Done once)\n\nThese steps set up your account on the mothership.\n\n1. Edit (or create) your `~/.bashrc`. Open with `vim ~/.bashrc` and add the following and **uncomment your port**:\n\n```bash\nexport RMATE_HOST=localhost\n# export RMATE_PORT=52694 #\n# export RMATE_PORT=52695 #\n# export RMATE_PORT=52696 #\n```\n\n### Running (what you do on a daily basis)\n\n#### Windows\n\nSince you've set up the script, you will be able to connect to the edgenode with the Sublime connection by simply running the following command after opening GitBash (remember the `.`):\n\n```bash\n. sublime_port_forward\n```\n\nAnd you (after entering your password) are logged into the Mothership. You will use prompt to open text files.\n\n#### MacOS\n\nSet up the port forwarding (you have to keep this open). You can do it the hard way:\n\n```bash\nssh -R {YOUR_PORT}:localhost:{YOUR_PORT} {USER}@{MOTHERSHIP_IP_ADDRESS}\n```\n\nor the easier way (if you set up your ssh config file as above):\n\n```bash\nssh rsub-svdsnode\n```\n\nHave Sublime Text running on your laptop -- this is where the file will appear when you run the `rsub` command on the Mothership.\n\n### On the Mothership\n\nOpen an existing file (for example framework.cfg) that you'd like to edit in Sublime Text (or create a new one by naming it):\n\n```bash\nsubl framework.cfg\n```\n\nAnd enjoy editing your text file on Sublime Text! It will sync the contents of the file when you save.", "_____no_output_____" ], [ "### FAQ and initial installation notes\n\nYou keep calling it `rsub` or `subl` but I keep seeing `rmate` everywhere -- what gives? The `rsub` command is using the utility originally created for TextMate, which was called using `rmate`. Since this is an update and uses Sublime Text, it's updated to `rsub`.\n\n#### Ports\n\nYou shouldn't have to worry about this unless you are an admin or something has gone wrong. If you need to choose different ports or assign them, check that nothing is using them on the mothership that you want to use by running something like:\n\n```bash\nsudo netstat -plant | grep {YOUR_PORT}\n```\n\nand verifying that nothing's returned.\n\n#### Installing rsub on mothership\n\nInstall rsub (this requires root -- can install locally if not on the edgenode)\n\n```\nsudo wget -O /usr/local/bin/subl https://raw.github.com/aurora/rmate/master/rmate\nsudo chmod +x /usr/local/bin/subl\n```", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af3f88bf7ae95a7870f7e40323bdc078ed824b1
344,974
ipynb
Jupyter Notebook
notebooks/XCS224W_Colab3.ipynb
leehanchung/cs224w
4e7bba7a2769c5ed016c53e165535a2bd34f7b22
[ "MIT" ]
10
2021-09-15T06:52:47.000Z
2022-03-10T16:11:30.000Z
notebooks/XCS224W_Colab3.ipynb
leehanchung/cs224w
4e7bba7a2769c5ed016c53e165535a2bd34f7b22
[ "MIT" ]
null
null
null
notebooks/XCS224W_Colab3.ipynb
leehanchung/cs224w
4e7bba7a2769c5ed016c53e165535a2bd34f7b22
[ "MIT" ]
null
null
null
123.161014
162,342
0.795538
[ [ [ "<a href=\"https://colab.research.google.com/github/leehanchung/cs224w/blob/main/notebooks/XCS224W_Colab3.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# **CS224W - Colab 3**", "_____no_output_____" ], [ "In Colab 2 we constructed GNN models by using PyTorch Geometric's built in GCN layer, `GCNConv`. In this Colab we will go a step deeper and implement the **GraphSAGE** ([Hamilton et al. (2017)](https://arxiv.org/abs/1706.02216)) and **GAT** ([Veličković et al. (2018)](https://arxiv.org/abs/1710.10903)) layers directly. Then we will run and test our models on the CORA dataset, a standard citation network benchmark dataset.\n\nNext, we will use [DeepSNAP](https://snap.stanford.edu/deepsnap/), a Python library assisting efficient deep learning on graphs, to split the graphs in different settings and apply dataset transformations.\n\nLastly, using DeepSNAP's transductive link prediction dataset spliting functionality, we will construct a simple GNN model for the task of edge property predition (link prediction).\n\n**Note**: Make sure to **sequentially run all the cells in each section** so that the intermediate variables / packages will carry over to the next cell\n\nHave fun and good luck on Colab 3 :)", "_____no_output_____" ], [ "# Device\nWe recommend using a GPU for this Colab.\n\nPlease click `Runtime` and then `Change runtime type`. Then set the `hardware accelerator` to **GPU**.", "_____no_output_____" ], [ "## Installation", "_____no_output_____" ] ], [ [ "# Install torch geometric\nimport os\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n !pip uninstall torch-scatter --y\n !pip uninstall torch-sparse --y\n !pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\n !pip install torch-sparse -f https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\n\n !pip install torch-geometric\n !pip install -q git+https://github.com/snap-stanford/deepsnap.git", "Found existing installation: torch-scatter 2.0.8\nUninstalling torch-scatter-2.0.8:\n Successfully uninstalled torch-scatter-2.0.8\nFound existing installation: torch-sparse 0.6.12\nUninstalling torch-sparse-0.6.12:\n Successfully uninstalled torch-sparse-0.6.12\nLooking in links: https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\nCollecting torch-scatter\n Using cached https://data.pyg.org/whl/torch-1.9.0%2Bcu111/torch_scatter-2.0.8-cp37-cp37m-linux_x86_64.whl (10.4 MB)\nInstalling collected packages: torch-scatter\nSuccessfully installed torch-scatter-2.0.8\nLooking in links: https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html\nCollecting torch-sparse\n Using cached https://data.pyg.org/whl/torch-1.9.0%2Bcu111/torch_sparse-0.6.12-cp37-cp37m-linux_x86_64.whl (3.7 MB)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-sparse) (1.4.1)\nRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from scipy->torch-sparse) (1.19.5)\nInstalling collected packages: torch-sparse\nSuccessfully installed torch-sparse-0.6.12\nRequirement already satisfied: torch-geometric in /usr/local/lib/python3.7/dist-packages (2.0.1)\nRequirement already satisfied: yacs in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (0.1.8)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.23.0)\nRequirement already satisfied: googledrivedownloader in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (0.4)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (4.62.3)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.1.5)\nRequirement already satisfied: pyparsing in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.4.7)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.19.5)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (0.22.2.post1)\nRequirement already satisfied: PyYAML in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (3.13)\nRequirement already satisfied: rdflib in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (6.0.2)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.4.1)\nRequirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.6.3)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.11.3)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->torch-geometric) (2.0.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2.8.2)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->torch-geometric) (1.15.0)\nRequirement already satisfied: isodate in /usr/local/lib/python3.7/dist-packages (from rdflib->torch-geometric) (0.6.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from rdflib->torch-geometric) (57.4.0)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2021.5.30)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (3.0.4)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->torch-geometric) (1.0.1)\n" ], [ "import torch_geometric\ntorch_geometric.__version__", "_____no_output_____" ] ], [ [ "# 1) GNN Layers", "_____no_output_____" ], [ "## Implementing Layer Modules\n\nIn Colab 2, we implemented a GCN model for node and graph classification tasks. However, for that notebook we took advantage of PyG's built in GCN module. For Colab 3, we provide a build upon a general Graph Neural Network Stack, into which we will be able to plugin our own module implementations: GraphSAGE and GAT.\n\nWe will then use our layer implemenations to complete node classification on the CORA dataset, a standard citation network benchmark. In this dataset, nodes correspond to documents and edges correspond to undirected citations. Each node or document in the graph is assigned a class label and features based on the documents binarized bag-of-words representation. Specifically, the Cora graph has 2708 nodes, 5429 edges, 7 prediction classes, and 1433 features per node. ", "_____no_output_____" ], [ "## GNN Stack Module\n\nBelow is the implementation of a general GNN stack, where we can plugin any GNN layer, such as **GraphSage**, **GAT**, etc. This module is provided for you. Your implementations of the **GraphSage** and **GAT** layers will function as components in the GNNStack Module.", "_____no_output_____" ] ], [ [ "import torch\nimport torch_scatter\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch_geometric.nn as pyg_nn\nimport torch_geometric.utils as pyg_utils\n\nfrom torch import Tensor\nfrom typing import Union, Tuple, Optional\nfrom torch_geometric.typing import (OptPairTensor, Adj, Size, NoneType,\n OptTensor)\n\nfrom torch.nn import Parameter, Linear\nfrom torch_sparse import SparseTensor, set_diag\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.utils import remove_self_loops, add_self_loops, softmax\n\nclass GNNStack(torch.nn.Module):\n def __init__(self, input_dim, hidden_dim, output_dim, args, emb=False):\n super(GNNStack, self).__init__()\n conv_model = self.build_conv_model(args.model_type)\n self.convs = nn.ModuleList()\n self.convs.append(conv_model(input_dim, hidden_dim))\n assert (args.num_layers >= 1), 'Number of layers is not >=1'\n for l in range(args.num_layers-1):\n self.convs.append(conv_model(args.heads * hidden_dim, hidden_dim))\n\n # post-message-passing\n self.post_mp = nn.Sequential(\n nn.Linear(args.heads * hidden_dim, hidden_dim), nn.Dropout(args.dropout), \n nn.Linear(hidden_dim, output_dim))\n\n self.dropout = args.dropout\n self.num_layers = args.num_layers\n\n self.emb = emb\n\n def build_conv_model(self, model_type):\n if model_type == 'GraphSage':\n return GraphSage\n elif model_type == 'GAT':\n # When applying GAT with num heads > 1, you need to modify the \n # input and output dimension of the conv layers (self.convs),\n # to ensure that the input dim of the next layer is num heads\n # multiplied by the output dim of the previous layer.\n # HINT: In case you want to play with multiheads, you need to change the for-loop that builds up self.convs to be\n # self.convs.append(conv_model(hidden_dim * num_heads, hidden_dim)), \n # and also the first nn.Linear(hidden_dim * num_heads, hidden_dim) in post-message-passing.\n return GAT\n\n def forward(self, data):\n x, edge_index, batch = data.x, data.edge_index, data.batch\n \n for i in range(self.num_layers):\n x = self.convs[i](x, edge_index)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout,training=self.training)\n\n x = self.post_mp(x)\n\n if self.emb == True:\n return x\n\n return F.log_softmax(x, dim=1)\n\n def loss(self, pred, label):\n return F.nll_loss(pred, label)", "_____no_output_____" ] ], [ [ "## Creating Our Own Message Passing Layer\n\nNow let's start implementing our own message passing layers! Working through this part will help us become acutely familiar with the behind the scenes work of implementing Pytorch Message Passing Layers, allowing us to build our own GNN models. To do so, we will work with and implement 3 critcal functions needed to define a PyG Message Passing Layer: `forward`, `message`, and `aggregate`.\n\nBefore diving head first into the coding details, let us quickly review the key components of the message passing process. To do so, we will focus on a single round of messsage passing with respect to a single central node $x$. Before message passing, $x$ is associated with a feature vector $x^{l-1}$, and the goal of message passing is to update this feature vector as $x^l$. To do so, we implement the following steps: 1) each neighboring node $v$ passes its current message $v^{l-1}$ across the edge $(x, v)$ - 2) for the node $x$, we aggregate all of the messages of the neighboring nodes (for example through a sum or mean) - and 3) we transform the aggregated information by for example applying linear and non-linear transformations. Altogether, the message passing process is applied such that every node $u$ in our graph updates its embedding by acting as the central node $x$ in step 1-3 described above. \n\nNow, we extending this process to that of a single message passing layer, the job of a message passing layer is to update the current feature representation or embedding of each node in a graph by propagating and transforming information within the graph. Overall, the general paradigm of a message passing layers is: 1) pre-processing -> 2) **message passing** / propagation -> 3) post-processing. \n\nThe `forward` fuction that we will implement for our message passing layer captures this execution logic. Namely, the `forward` function handles the pre and post-processing of node features / embeddings, as well as initiates message passing by calling the `propagate` function. \n\n\nThe `propagate` function encapsulates the message passing process! It does so by calling three important functions: 1) `message`, 2) `aggregate`, and 3) `update`. Our implementation will vary slightly from this, as we will not explicitly implement `update`, but instead place the logic for updating node embeddings after message passing and within the `forward` function. To be more specific, after information is propagated (message passing), we can further transform the node embeddings outputed by `propagate`. Therefore, the output of `forward` is exactly the node embeddings after one GNN layer.\n\nLastly, before starting to implement our own layer, let us dig a bit deeper into each of the functions described above:\n\n1. \n\n```\ndef propagate(edge_index, x=(x_i, x_j), extra=(extra_i, extra_j), size=size):\n```\nCalling `propagate` initiates the message passing process. Looking at the function parameters, we highlight a couple of key parameters. \n\n - `edge_index` is passed to the forward function and captures the edge structure of the graph.\n - `x=(x_i, x_j)` represents the node features that will be used in message passing. In order to explain why we pass the tuple `(x_i, x_j)`, we first look at how our edges are represented. For every edge $(i, j) \\in \\mathcal{E}$, we can differentiate $i$ as the source or central node ($x_{central}$) and j as the neighboring node ($x_{neighbor}$). \n \n Taking the example of message passing above, for a central node $u$ we will aggregate and transform all of the messages associated with the nodes $v$ s.t. $(u, v) \\in \\mathcal{E}$ (i.e. $v \\in \\mathcal{N}_{u}$). Thus we see, the subscripts `_i` and `_j` allow us to specifcally differenciate features associated with central nodes (i.e. nodes recieving message information) and neighboring nodes (i.e. nodes passing messages). \n\n This is definitely a somewhat confusing concept; however, one key thing to remember / wrap your head around is that depending on the perspective, a node $x$ acts as a central node or a neighboring node. In fact, in undirected graphs we store both edge directions (i.e. $(i, j)$ and $(j, i)$). From the central node perspective, `x_i`, x is collecting neighboring information to update its embedding. From a neighboring node perspective, `x_j`, x is passing its message information along the edge connecting it to a different central node.\n\n - `extra=(extra_i, extra_j)` represents additional information that we can associate with each node beyond its current feature embedding. In fact, we can include as many additional parameters of the form `param=(param_i, param_j)` as we would like. Again, we highlight that indexing with `_i` and `_j` allows us to differentiate central and neighboring nodes. \n\n The output of the `propagate` function is a matrix of node embeddings after the message passing process and has shape $[N, d]$.\n\n2. \n```\ndef message(x_j, ...):\n```\nThe `message` function is called by propagate and constructs the messages from\nneighboring nodes $j$ to central nodes $i$ for each edge $(i, j)$ in *edge_index*. This function can take any argument that was initially passed to `propagate`. Furthermore, we can again differentiate central nodes and neighboring nodes by appending `_i` or `_j` to the variable name, .e.g. `x_i` and `x_j`. Looking more specifically at the variables, we have:\n\n - `x_j` represents a matrix of feature embeddings for all neighboring nodes passing their messages along their respective edge (i.e. all nodes $j$ for edges $(i, j) \\in \\mathcal{E}$). Thus, its shape is $[|\\mathcal{E}|, d]$!\n - In implementing GAT we will see how to access additional variables passed to propagate\n\n Critically, we see that the output of the `message` function is a matrix of neighboring node embeddings ready to be aggregated, having shape $[|\\mathcal{E}|, d]$.\n\n3. \n```\ndef aggregate(self, inputs, index, dim_size = None):\n```\nLastly, the `aggregate` function is used to aggregate the messages from neighboring nodes. Looking at the parameters we highlight:\n\n - `inputs` represents a matrix of the messages passed from neighboring nodes (i.e. the output of the `message` function).\n - `index` has the same shape as `inputs` and tells us the central node that corresponding to each of the rows / messages $j$ in the `inputs` matrix. Thus, `index` tells us which rows / messages to aggregate for each central node.\n\n The output of `aggregate` is of shape $[N, d]$.\n\n\nFor additional resources refer to the PyG documentation for implementing custom message passing layers: https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html", "_____no_output_____" ], [ "## GraphSage Implementation\n\nFor our first GNN layer, we will implement the well known GraphSage ([Hamilton et al. (2017)](https://arxiv.org/abs/1706.02216)) layer! \n\nFor a given *central* node $v$ with current embedding $h_v^{l-1}$, the message passing update rule to tranform $h_v^{l-1} \\rightarrow h_v^l$ is as follows: \n\n\\begin{equation}\nh_v^{(l)} = W_l\\cdot h_v^{(l-1)} + W_r \\cdot AGG(\\{h_u^{(l-1)}, \\forall u \\in N(v) \\})\n\\end{equation}\n\nwhere $W_1$ and $W_2$ are learanble weight matrices and the nodes $u$ are *neighboring* nodes. Additionally, we use mean aggregation for simplicity:\n\n\\begin{equation}\nAGG(\\{h_u^{(l-1)}, \\forall u \\in N(v) \\}) = \\frac{1}{|N(v)|} \\sum_{u\\in N(v)} h_u^{(l-1)}\n\\end{equation}\n\nOne thing to note is that we're adding a **skip connection** to our GraphSage implementation through the term $W_l\\cdot h_v^{(l-1)}$. \n\nBefore implementing this update rule, we encourage you to think about how different parts of the formulas above correspond with the functions outlined earlier: 1) `forward`, 2) `message`, and 3) `aggregate`. As a hint, we are given what the aggregation function is (i.e. mean aggregation)! Now the question remains, what are the messages passed by each neighbor nodes and when do we call the `propagate` function? \n\nNote: in this case the message function or messages are actually quite simple. Additionally, remember that the `propagate` function encapsulates the operations of / the outputs of the combined `message` and `aggregate` functions.\n\n\nLastly, $\\ell$-2 normalization of the node embeddings is applied after each iteration.\n\n\n<font color='red'>For the following questions, DON'T refer to any existing implementations online.</font>", "_____no_output_____" ] ], [ [ "class GraphSage(MessagePassing):\n \n def __init__(self, in_channels, out_channels, normalize = True,\n bias = False, **kwargs): \n super(GraphSage, self).__init__(**kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.normalize = normalize\n\n self.lin_l = None\n self.lin_r = None\n\n ############################################################################\n # TODO: Your code here! \n # Define the layers needed for the message and update functions below.\n # self.lin_l is the linear transformation that you apply to embedding \n # for central node.\n # self.lin_r is the linear transformation that you apply to aggregated \n # message from neighbors.\n # Our implementation is ~2 lines, but don't worry if you deviate from this.\n self.lin_l = nn.Linear(self.in_channels, self.out_channels)\n self.lin_r = nn.Linear(self.in_channels, self.out_channels)\n\n\n ############################################################################\n\n self.reset_parameters()\n\n def reset_parameters(self):\n self.lin_l.reset_parameters()\n self.lin_r.reset_parameters()\n\n def forward(self, x, edge_index, size = None):\n \"\"\"\"\"\"\n\n out = None\n\n ############################################################################\n # TODO: Your code here! \n # Implement message passing, as well as any post-processing (our update rule).\n # 1. Call propagate function to conduct the message passing.\n # 1.1 See the description of propagate above or the following link for more information: \n # https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html\n # 1.2 We will only use the representation for neighbor nodes (x_j), so by default\n # we pass the same representation for central and neighbor nodes as x=(x, x). \n # 2. Update our node embedding with skip connection.\n # 3. If normalize is set, do L-2 normalization (defined in \n # torch.nn.functional)\n #\n # Our implementation is ~5 lines, but don't worry if you deviate from this.\n x_propagate = self.propagate(edge_index, x=(x, x), size=size)\n x = self.lin_l(x) + x_propagate\n\n if self.normalize:\n x = F.normalize(x)\n\n out = x\n ############################################################################\n\n return out\n\n def message(self, x_j):\n\n out = None\n\n ############################################################################\n # TODO: Your code here! \n # Implement your message function here.\n # Hint: Look at the formulation of the mean aggregation function, focusing on \n # what message each neighboring node passes.\n #\n # Our implementation is ~1 lines, but don't worry if you deviate from this.\n out = self.lin_r(x_j)\n\n ############################################################################\n\n return out\n\n def aggregate(self, inputs, index, dim_size = None):\n\n out = None\n\n # The axis along which to index number of nodes.\n node_dim = self.node_dim\n\n ############################################################################\n # TODO: Your code here! \n # Implement your aggregate function here.\n # See here as how to use torch_scatter.scatter: \n # https://pytorch-scatter.readthedocs.io/en/latest/functions/scatter.html#torch_scatter.scatter\n #\n # Our implementation is ~1 lines, but don't worry if you deviate from this.\n out = torch_scatter.scatter(inputs, index, dim=node_dim, reduce='mean')\n\n ############################################################################\n\n return out\n", "_____no_output_____" ] ], [ [ "## GAT Implementation\n\nAttention mechanisms have become the state-of-the-art in many sequence-based tasks such as machine translation and learning sentence representations. One of the major benefits of attention-based mechanisms is their ability to focus on the most relevant parts of the input to make decisions. In this problem, we will see how attention mechanisms can be used to perform node classification over graph-structured data through the usage of Graph Attention Networks (GATs) ([Veličković et al. (2018)](https://arxiv.org/abs/1710.10903)).\n\nThe building block of the Graph Attention Network is the graph attention layer, which is a variant of the aggregation function. Let $N$ be the number of nodes and $F$ be the dimension of the feature vector for each node. The input to each graph attentional layer is a set of node features: $\\mathbf{h} = \\{\\overrightarrow{h_1}, \\overrightarrow{h_2}, \\dots, \\overrightarrow{h_N}$\\}, $\\overrightarrow{h_i} \\in R^F$. The output of each graph attentional layer is a new set of node features, which may have a new dimension $F'$: $\\mathbf{h'} = \\{\\overrightarrow{h_1'}, \\overrightarrow{h_2'}, \\dots, \\overrightarrow{h_N'}\\}$, with $\\overrightarrow{h_i'} \\in \\mathbb{R}^{F'}$.\n\nWe will now describe how this transformation is performed for each graph attention layer. First, a shared linear transformation parametrized by the weight matrix $\\mathbf{W} \\in \\mathbb{R}^{F' \\times F}$ is applied to every node. \n\nNext, we perform self-attention on the nodes. We use a shared attention function $a$:\n\\begin{equation} \na : \\mathbb{R}^{F'} \\times \\mathbb{R}^{F'} \\rightarrow \\mathbb{R}.\n\\end{equation}\n\nthat computes the attention coefficients capturing the importance of node $j$'s features to node $i$:\n\\begin{equation}\ne_{ij} = a(\\mathbf{W_l}\\overrightarrow{h_i}, \\mathbf{W_r} \\overrightarrow{h_j})\n\\end{equation}\n\nThe most general formulation of self-attention allows every node to attend to all other nodes which drops all structural information. However, to utilize graph structure in the attention mechanisms, we use **masked attention**. In masked attention, we only compute attention coefficients $e_{ij}$ for nodes $j \\in \\mathcal{N}_i$ where $\\mathcal{N}_i$ is some neighborhood of node $i$ in the graph.\n\nTo easily compare coefficients across different nodes, we normalize the coefficients across $j$ using a softmax function:\n\\begin{equation}\n\\alpha_{ij} = \\text{softmax}_j(e_{ij}) = \\frac{\\exp(e_{ij})}{\\sum_{k \\in \\mathcal{N}_i} \\exp(e_{ik})}\n\\end{equation}\n\nFor this problem, our attention mechanism $a$ will be a single-layer feedforward neural network parametrized by a weight vectors $\\overrightarrow{a} \\in \\mathbb{R}^{F'}$ and $\\overrightarrow{a} \\in \\mathbb{R}^{F'}$, followed by a LeakyReLU nonlinearity (with negative input slope 0.2). Let $\\cdot^T$ represent transposition and $||$ represent concatenation. The coefficients computed by our attention mechanism may be expressed as:\n\n\\begin{equation}\n\\alpha_{ij} = \\frac{\\exp\\Big(\\text{LeakyReLU}\\Big(\\overrightarrow{a_l}^T \\mathbf{W_l} \\overrightarrow{h_i} + \\overrightarrow{a_r}^T\\mathbf{W_r}\\overrightarrow{h_j}\\Big)\\Big)}{\\sum_{k\\in \\mathcal{N}_i} \\exp\\Big(\\text{LeakyReLU}\\Big(\\overrightarrow{a_l}^T \\mathbf{W_l} \\overrightarrow{h_i} + \\overrightarrow{a_r}^T\\mathbf{W_r}\\overrightarrow{h_k}\\Big)\\Big)}\n\\end{equation}\n\nFor the following questions, we denote `alpha_l` = $\\alpha_l = [...,\\overrightarrow{a_l}^T \\mathbf{W_l} \\overrightarrow{h_i},...] \\in \\mathcal{R}^n$ and `alpha_r` = $\\alpha_r = [..., \\overrightarrow{a_r}^T \\mathbf{W_r} \\overrightarrow{h_j}, ...] \\in \\mathcal{R}^n$.\n\n\nAt every layer of GAT, after the attention coefficients are computed for that layer, the aggregation function can be computed by a weighted sum of neighborhood messages, where weights are specified by $\\alpha_{ij}$.\n\nNow, we use the normalized attention coefficients to compute a linear combination of the features corresponding to them. These aggregated features will serve as the final output features for every node.\n\n\\begin{equation}\nh_i' = \\sum_{j \\in \\mathcal{N}_i} \\alpha_{ij} \\mathbf{W_r} \\overrightarrow{h_j}.\n\\end{equation}\n\nAt this point, we have covered a lot of information! Before reading further about multi-head attention, we encourage you to go again through the excersize of thinking about what components of the attention mechanism correspond with the different funcitons: 1) `forward`, 2) `message`, and 3 `aggregate`. \n\n- Hint 1: Our aggregation is very similar to that of GraphSage except now we are using sum aggregation\n- Hint 2: The terms we aggregate over again represent the individual message that each neighbor node j sends. Thus, we see that $\\alpha_{ij}$ is part of the message each node sends and is thus computed during the message step. This makes sense since an attention weight is associated with each edge in the graph.\n- Hint 3: Look at the terms in the definition of $\\alpha_{ij}$. What values do we want to pre-process and pass as parameters to the `propagate` function. The parameters of `message(..., x_j, alpha_j, alpha_i, ...)` should give a good hint. \n\n### Multi-Head Attention\nTo stabilize the learning process of self-attention, we use multi-head attention. To do this we use $K$ independent attention mechanisms, or ``heads'' compute output features as in the above equations. Then, we concatenate these output feature representations:\n\n\\begin{equation}\n \\overrightarrow{h_i}' = ||_{k=1}^K \\Big(\\sum_{j \\in \\mathcal{N}_i} \\alpha_{ij}^{(k)} \\mathbf{W_r}^{(k)} \\overrightarrow{h_j}\\Big)\n\\end{equation}\n\nwhere $||$ is concentation, $\\alpha_{ij}^{(k)}$ are the normalized attention coefficients computed by the $k$-th attention mechanism $(a^k)$, and $\\mathbf{W}^{(k)}$ is the corresponding input linear transformation's weight matrix. Note that for this setting, $\\mathbf{h'} \\in \\mathbb{R}^{KF'}$.", "_____no_output_____" ] ], [ [ "class GAT(MessagePassing):\n\n def __init__(self, in_channels, out_channels, heads = 2,\n negative_slope = 0.2, dropout = 0., **kwargs):\n super(GAT, self).__init__(node_dim=0, **kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.heads = heads\n self.negative_slope = negative_slope\n self.dropout = dropout\n\n self.lin_l = None\n self.lin_r = None\n self.att_l = None\n self.att_r = None\n\n ############################################################################\n # TODO: Your code here! \n # Define the layers needed for the message functions below.\n # self.lin_l is the linear transformation that you apply to embeddings \n # BEFORE message passing.\n # \n # Pay attention to dimensions of the linear layers, since we're using \n # multi-head attention.\n # Our implementation is ~1 lines, but don't worry if you deviate from this.\n self.lin_l = nn.Linear(self.in_channels, self.heads * self.out_channels)\n\n ############################################################################\n\n self.lin_r = self.lin_l\n\n ############################################################################\n # TODO: Your code here! \n # Define the attention parameters \\overrightarrow{a_l/r}^T in the above intro.\n # You have to deal with multi-head scenarios.\n # Use nn.Parameter instead of nn.Linear\n # Our implementation is ~2 lines, but don't worry if you deviate from this.\n self.att_l = nn.Parameter(torch.randn(heads, self.out_channels))\n self.att_r = nn.Parameter(torch.randn(heads, self.out_channels))\n\n ############################################################################\n\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.xavier_uniform_(self.lin_l.weight)\n nn.init.xavier_uniform_(self.lin_r.weight)\n nn.init.xavier_uniform_(self.att_l)\n nn.init.xavier_uniform_(self.att_r)\n\n def forward(self, x, edge_index, size = None):\n \n H, C = self.heads, self.out_channels\n\n ############################################################################\n # TODO: Your code here! \n # Implement message passing, as well as any pre- and post-processing (our update rule).\n # 1. First apply linear transformation to node embeddings, and split that \n # into multiple heads. We use the same representations for source and\n # target nodes, but apply different linear weights (W_l and W_r)\n # 2. Calculate alpha vectors for central nodes (alpha_l) and neighbor nodes (alpha_r).\n # 3. Call propagate function to conduct the message passing. \n # 3.1 Remember to pass alpha = (alpha_l, alpha_r) as a parameter.\n # 3.2 See there for more information: https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html\n # 4. Transform the output back to the shape of N * d.\n # Our implementation is ~5 lines, but don't worry if you deviate from this.\n \n # x_l dims: N x H x C\n x_l = self.lin_l(x).view(-1, H, C) \n # x_r dims: N x H x C\n x_r = self.lin_r(x).view(-1, H, C)\n\n # alpha_l dims: # 1 x H x C * N x H x C\n alpha_l = self.att_l.unsqueeze(0) * x_l\n # alpha_r dims: # 1 x H x C * N x H x C\n alpha_r = self.att_r.unsqueeze(0) * x_r\n\n out = self.propagate(edge_index, x = (x_l, x_r), alpha=(alpha_l, alpha_r))\n out = out.view(-1, H*C)\n ############################################################################\n\n return out\n\n\n def message(self, x_j, alpha_j, alpha_i, index, ptr, size_i):\n\n ############################################################################\n # TODO: Your code here! \n # Implement your message function. Putting the attention in message \n # instead of in update is a little tricky.\n # 1. Calculate the final attention weights using alpha_i and alpha_j,\n # and apply leaky Relu.\n # 2. Calculate softmax over the neighbor nodes for all the nodes. Use \n # torch_geometric.utils.softmax instead of the one in Pytorch.\n # 3. Apply dropout to attention weights (alpha).\n # 4. Multiply embeddings and attention weights. As a sanity check, the output\n # should be of shape E * H * d.\n # 5. ptr (LongTensor, optional): If given, computes the softmax based on\n # sorted inputs in CSR representation. You can simply pass it to softmax.\n # Our implementation is ~5 lines, but don't worry if you deviate from this.\n alpha_ij = F.leaky_relu(alpha_i + alpha_j, negative_slope=self.negative_slope)\n\n if ptr is None:\n alpha_ij = softmax(alpha_ij, index)\n else:\n alpha_ij = softmax(alphaij, ptr)\n \n alpha_ij = F.dropout(alpha_ij, p=self.dropout)\n out = x_j * alpha_ij\n ############################################################################\n\n return out\n\n\n def aggregate(self, inputs, index, dim_size = None):\n\n ############################################################################\n # TODO: Your code here! \n # Implement your aggregate function here.\n # See here as how to use torch_scatter.scatter: https://pytorch-scatter.readthedocs.io/en/latest/_modules/torch_scatter/scatter.html\n # Pay attention to \"reduce\" parameter is different from that in GraphSage.\n # Our implementation is ~1 lines, but don't worry if you deviate from this.\n out = torch_scatter.scatter(inputs, index, dim=self.node_dim, reduce='sum')\n\n ############################################################################\n \n return out", "_____no_output_____" ] ], [ [ "## Building Optimizers\n\nThis function has been implemented for you. **For grading purposes please use the default Adam optimizer**, but feel free to play with other types of optimizers on your own.", "_____no_output_____" ] ], [ [ "import torch.optim as optim\n\ndef build_optimizer(args, params):\n weight_decay = args.weight_decay\n filter_fn = filter(lambda p : p.requires_grad, params)\n if args.opt == 'adam':\n optimizer = optim.Adam(filter_fn, lr=args.lr, weight_decay=weight_decay)\n elif args.opt == 'sgd':\n optimizer = optim.SGD(filter_fn, lr=args.lr, momentum=0.95, weight_decay=weight_decay)\n elif args.opt == 'rmsprop':\n optimizer = optim.RMSprop(filter_fn, lr=args.lr, weight_decay=weight_decay)\n elif args.opt == 'adagrad':\n optimizer = optim.Adagrad(filter_fn, lr=args.lr, weight_decay=weight_decay)\n if args.opt_scheduler == 'none':\n return None, optimizer\n elif args.opt_scheduler == 'step':\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.opt_decay_step, gamma=args.opt_decay_rate)\n elif args.opt_scheduler == 'cos':\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.opt_restart)\n return scheduler, optimizer", "_____no_output_____" ] ], [ [ "## Training and Testing\n\nHere we provide you with the functions to train and test. **Please do not modify this part for grading purposes.**", "_____no_output_____" ] ], [ [ "import time\n\nimport networkx as nx\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom tqdm import trange\nimport pandas as pd\nimport copy\n\nfrom torch_geometric.datasets import TUDataset\nfrom torch_geometric.datasets import Planetoid\nfrom torch_geometric.data import DataLoader\n\nimport torch_geometric.nn as pyg_nn\n\nimport matplotlib.pyplot as plt\n\n\ndef train(dataset, args):\n \n print(\"Node task. test set size:\", np.sum(dataset[0]['test_mask'].numpy()))\n print()\n test_loader = loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False)\n\n # build model\n model = GNNStack(dataset.num_node_features, args.hidden_dim, dataset.num_classes, \n args)\n scheduler, opt = build_optimizer(args, model.parameters())\n\n # train\n losses = []\n test_accs = []\n best_acc = 0\n best_model = None\n for epoch in trange(args.epochs, desc=\"Training\", unit=\"Epochs\"):\n total_loss = 0\n model.train()\n for batch in loader:\n opt.zero_grad()\n pred = model(batch)\n label = batch.y\n pred = pred[batch.train_mask]\n label = label[batch.train_mask]\n loss = model.loss(pred, label)\n loss.backward()\n opt.step()\n total_loss += loss.item() * batch.num_graphs\n total_loss /= len(loader.dataset)\n losses.append(total_loss)\n\n if epoch % 10 == 0:\n test_acc = test(test_loader, model)\n test_accs.append(test_acc)\n if test_acc > best_acc:\n best_acc = test_acc\n best_model = copy.deepcopy(model)\n else:\n test_accs.append(test_accs[-1])\n \n return test_accs, losses, best_model, best_acc, test_loader\n\ndef test(loader, test_model, is_validation=False, save_model_preds=False, model_type=None):\n test_model.eval()\n\n correct = 0\n # Note that Cora is only one graph!\n for data in loader:\n with torch.no_grad():\n # max(dim=1) returns values, indices tuple; only need indices\n pred = test_model(data).max(dim=1)[1]\n label = data.y\n\n mask = data.val_mask if is_validation else data.test_mask\n # node classification: only evaluate on nodes in test set\n pred = pred[mask]\n label = label[mask]\n\n if save_model_preds:\n print (\"Saving Model Predictions for Model Type\", model_type)\n\n data = {}\n data['pred'] = pred.view(-1).cpu().detach().numpy()\n data['label'] = label.view(-1).cpu().detach().numpy()\n\n df = pd.DataFrame(data=data)\n # Save locally as csv\n df.to_csv('CORA-Node-' + model_type + '.csv', sep=',', index=False)\n \n correct += pred.eq(label).sum().item()\n\n total = 0\n for data in loader.dataset:\n total += torch.sum(data.val_mask if is_validation else data.test_mask).item()\n\n return correct / total\n \nclass objectview(object):\n def __init__(self, d):\n self.__dict__ = d\n", "_____no_output_____" ] ], [ [ "## Let's Start the Training!\n\nWe will be working on the CORA dataset on node-level classification.\n\nThis part is implemented for you. **For grading purposes, please do not modify the default parameters.** However, feel free to play with different configurations just for fun!\n\n**Submit your best accuracy and loss on Gradescope.**", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n for args in [\n {'model_type': 'GraphSage', 'dataset': 'cora', 'num_layers': 2, 'heads': 1, 'batch_size': 32, 'hidden_dim': 32, 'dropout': 0.5, 'epochs': 500, 'opt': 'adam', 'opt_scheduler': 'none', 'opt_restart': 0, 'weight_decay': 5e-3, 'lr': 0.01},\n ]:\n args = objectview(args)\n for model in ['GraphSage', 'GAT']:\n args.model_type = model\n\n # Match the dimension.\n if model == 'GAT':\n args.heads = 2\n else:\n args.heads = 1\n\n if args.dataset == 'cora':\n dataset = Planetoid(root='/tmp/cora', name='Cora')\n else:\n raise NotImplementedError(\"Unknown dataset\") \n test_accs, losses, best_model, best_acc, test_loader = train(dataset, args) \n\n print(\"Maximum test set accuracy: {0}\".format(max(test_accs)))\n print(\"Minimum loss: {0}\".format(min(losses)))\n\n # Run test for our best model to save the predictions!\n test(test_loader, best_model, is_validation=False, save_model_preds=True, model_type=model)\n print()\n\n plt.title(dataset.name)\n plt.plot(losses, label=\"training loss\" + \" - \" + args.model_type)\n plt.plot(test_accs, label=\"test accuracy\" + \" - \" + args.model_type)\n plt.legend()\n plt.show()\n", "/usr/local/lib/python3.7/dist-packages/torch_geometric/deprecation.py:13: UserWarning: 'data.DataLoader' is deprecated, use 'loader.DataLoader' instead\n warnings.warn(out)\n" ] ], [ [ "## Question 1.1: What is the maximum accuracy obtained on the test set for GraphSage? (10 points)\n\nRunning the cell above will show the results of your best model and save your best model's predictions to a file named *CORA-Node-GraphSage.csv*. \n\nAs we have seen before you can view this file by clicking on the *Folder* icon on the left side pannel. When you sumbit your assignment, you will have to download this file and attatch it to your submission.", "_____no_output_____" ], [ "## Question 1.2: What is the maximum accuracy obtained on test set for GAT? (10 points)\n\n\nRunning the training cell above will also save your best GAT model predictions as *CORA-Node-GAT.csv*. \n\nWhen you sumbit your assignment, you will have to download this file and attatch it to your submission.\n", "_____no_output_____" ], [ "# 2) DeepSNAP Basics\n\nIn previous Colabs, we have seen graph class (NetworkX) and tensor (PyG) representations of graphs. The graph class `nx.Graph` provides rich analysis and manipulation functionalities, such as computing the clustering coefficient and PageRank vector for a graph. When working with PyG we were then introduced to tensor based representation of graphs (i.e. edge tensor `edge_index` and node attributes tensors `x` and `y`). \n\nIn this section, we present DeepSNAP, a package that combines the benifits of both graph representations and offers a full pipeline for GNN training / validation / and testing. Namely, DeepSNAP includes a graph class representation to allow for more efficient graph manipulation and analysis in addition to a tensor based representation for efficient message passing computation.\n\n", "_____no_output_____" ], [ "In general, [DeepSNAP](https://github.com/snap-stanford/deepsnap) is a Python library to assist efficient deep learning on graphs. DeepSNAP enables flexible graph manipulation, standard graph learning pipelines, heterogeneous graphs, and ovearll represents a simple graph learning API. In more detail:\n\n1. DeepSNAP allows for sophisticated graph manipulations, such as feature computation, pretraining, subgraph extraction etc. during/before training.\n2. DeepSNAP standardizes the pipelines for node, edge, and graph-level prediction tasks under inductive or transductive settings. Specifically, DeepSNAP removes previous non-trivial / repetative design choices left to the user, such as how to split datasets. DeepSNAP thus greatly saves repetitive often non-trivial coding efforts and enables fair model comparison.\n3. Many real-world graphs are heterogeneous in nature (i.e. include different node types or edge types). However, most packages lack complete support for heterogeneous graphs, including data storage and flexible message passing. DeepSNAP provides an efficient and flexible heterogeneous graph that supports both node and edge heterogeneity.\n\n\nIn this next section, we will focus on working with DeepSNAP for graph manipulation and dataset splitting.\n\n[DeepSNAP](https://github.com/snap-stanford/deepsnap) is a newly released project and it is still under development. If you find any bugs or have any improvement ideas, feel free to raise issues or create pull requests on the GitHub directly :)", "_____no_output_____" ], [ "## Setup", "_____no_output_____" ] ], [ [ "import torch\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nfrom deepsnap.graph import Graph\nfrom deepsnap.batch import Batch\nfrom deepsnap.dataset import GraphDataset\nfrom torch_geometric.datasets import Planetoid, TUDataset\n\nfrom torch.utils.data import DataLoader\n\ndef visualize(G, color_map=None, seed=123):\n if color_map is None:\n color_map = '#c92506'\n plt.figure(figsize=(8, 8))\n nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G, seed=seed), \\\n label=None, node_color=color_map, node_shape='o', node_size=150)\n edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G, seed=seed), alpha=0.5)\n if color_map is not None:\n plt.scatter([],[], c='#c92506', label='Nodes with label 0', edgecolors=\"black\", s=140)\n plt.scatter([],[], c='#fcec00', label='Nodes with label 1', edgecolors=\"black\", s=140)\n plt.legend(prop={'size': 13}, handletextpad=0)\n nodes.set_edgecolor('black')\n plt.show()", "_____no_output_____" ] ], [ [ "## DeepSNAP Graph\n\nThe `deepsnap.graph.Graph` class is the core class of DeepSNAP. It not only represents a graph in tensor format but also includes a graph object from a graph manipulation package.\n\nCurrently DeepSNAP supports [NetworkX](https://networkx.org/) and [Snap.py](https://snap.stanford.edu/snappy/doc/index.html) as back end graph manipulation packages.\n\nIn this Colab, we will focus on using NetworkX as the back end graph manipulation package.", "_____no_output_____" ], [ "### NetworkX to DeepSNAP\nTo begin, let us first work through converting a simple random NetworkX graph to a DeepSNAP graph.", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n num_nodes = 100\n p = 0.05\n seed = 100\n\n # Generate a networkx random graph\n G = nx.gnp_random_graph(num_nodes, p, seed=seed)\n\n # Generate some random node features and labels\n node_feature = {node : torch.rand([5, ]) for node in G.nodes()}\n node_label = {node : torch.randint(0, 2, ()) for node in G.nodes()}\n\n # Set the random features and labels to G\n nx.set_node_attributes(G, node_feature, name='node_feature')\n nx.set_node_attributes(G, node_label, name='node_label')\n\n # Print one node example\n for node in G.nodes(data=True):\n print(node)\n break\n\n color_map = ['#c92506' if node[1]['node_label'].item() == 0 else '#fcec00' for node in G.nodes(data=True)]\n\n # Visualize the graph\n visualize(G, color_map=color_map)\n\n # Transform the networkx graph into the deepsnap graph\n graph = Graph(G)\n\n # Print out the general deepsnap graph information\n print(graph)\n\n # DeepSNAP will convert node attributes to tensors\n # Notice the type of tensors\n print(\"Node feature (node_feature) has shape {} and type {}\".format(graph.node_feature.shape, graph.node_feature.dtype))\n print(\"Node label (node_label) has shape {} and type {}\".format(graph.node_label.shape, graph.node_label.dtype))\n\n # DeepSNAP will also generate the edge_index tensor\n print(\"Edge index (edge_index) has shape {} and type {}\".format(graph.edge_index.shape, graph.edge_index.dtype))\n\n # Different from only storing tensors, deepsnap graph also references to the networkx graph\n # We will discuss why the reference will be helpful later\n print(\"The DeepSNAP graph has {} as the internal manupulation graph\".format(type(graph.G)))", "(0, {'node_feature': tensor([0.6352, 0.5361, 0.8233, 0.5733, 0.4873]), 'node_label': tensor(1)})\n" ] ], [ [ "### Tensor graph attributes\n\nSimilar to the native PyG tensor based representation, DeepSNAP includes a graph tensor based representation with three levels of graph attributes. In this example, we primarily have **node level** attributes including `node_feature` and `node_label`. The other two levels of attributes are **edge** and **graph** attributes. Similar to node level attributes, these attributes are prefixed by their respective type. For example, the features become `edge_feature` or `graph_feature` and labels becomes `edge_label` or `graph_label` etc.", "_____no_output_____" ], [ "### Graph Object\nDeepSNAP additionally allows us to easily access graph information through the backend graph object and graph manipulation package.", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n # Number of nodes\n print(\"The random graph has {} nodes\".format(graph.num_nodes))\n\n # Number of edges\n print(\"The random graph has {} edges\".format(graph.num_edges))", "The random graph has 100 nodes\nThe random graph has 262 edges\n" ] ], [ [ "### PyG to DeepSNAP\n\nLastly, DeepSNAP provides functionality to automatically transform a PyG dataset into a list of DeepSNAP graphs.\n\nHere we transform the CORA dataset into a list with one DeepSNAP graph (i.e. the singular CORA graph).", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n root = './tmp/cora'\n name = 'Cora'\n\n # The Cora dataset\n pyg_dataset= Planetoid(root, name)\n\n # PyG dataset to a list of deepsnap graphs\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n\n # Get the first deepsnap graph (CORA only has one graph)\n graph = graphs[0]\n print(graph)", "Graph(G=[], edge_index=[2, 10556], edge_label_index=[2, 10556], node_feature=[2708, 1433], node_label=[2708], node_label_index=[2708])\n" ] ], [ [ "## Question 2.1: How many classes are in the CORA graph? How many features does each node have? (5 points)\n", "_____no_output_____" ] ], [ [ "def get_num_node_classes(graph):\n # TODO: Implement a function that takes a deepsnap graph object\n # and return the number of node classes of that graph.\n\n num_node_classes = 0\n\n ############# Your code here #############\n ## (~1 line of code)\n ## Note\n ## 1. Colab autocomplete functionality might be useful\n ## 2. DeepSNAP documentation might be useful https://snap.stanford.edu/deepsnap/modules/graph.html\n num_node_classes = graph.num_node_labels\n\n ##########################################\n\n return num_node_classes\n\ndef get_num_node_features(graph):\n # TODO: Implement a function that takes a deepsnap graph object\n # and return the number of node features of that graph.\n\n num_node_features = 0\n\n ############# Your code here #############\n ## (~1 line of code)\n ## Note\n ## 1. Colab autocomplete functionality might be useful\n ## 2. DeepSNAP documentation might be useful https://snap.stanford.edu/deepsnap/modules/graph.html\n num_node_features = graph.num_node_features\n\n ##########################################\n\n return num_node_features\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n num_node_classes = get_num_node_classes(graph)\n num_node_features = get_num_node_features(graph)\n print(\"{} has {} classes\".format(name, num_node_classes))\n print(\"{} has {} features\".format(name, num_node_features))", "Cora has 7 classes\nCora has 1433 features\n" ] ], [ [ "## DeepSNAP Dataset\n\nNow, we will learn how to create DeepSNAP datasets. A `deepsnap.dataset.GraphDataset` contains a list of `deepsnap.graph.Graph` objects. In addition to the list of graphs, we specify what task the dataset will be used on, such as node level task (`task=node`), edge level task (`task=link_pred`) and graph level task (`task=graph`).\n\nThe GraphDataset class contains many other useful parameters that can be specified during initialization. If you are interested, you can take a look at the [documentation](https://snap.stanford.edu/deepsnap/modules/dataset.html#deepsnap-graphdataset).", "_____no_output_____" ], [ "As an example, we will first look at the COX2 dataset, which contains 467 graphs. In initializng our dataset, we convert the PyG dataset into its corresponding DeepSNAP dataset and specify the task to `graph`.", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ: \n root = './tmp/cox2'\n name = 'COX2'\n\n # Load the dataset through PyG\n pyg_dataset = TUDataset(root, name)\n\n # Convert to a list of deepsnap graphs\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n\n # Convert list of deepsnap graphs to deepsnap dataset with specified task=graph\n dataset = GraphDataset(graphs, task='graph')\n print(dataset)", "GraphDataset(467)\n" ] ], [ [ "## Question 2.2: What is the label of the graph with index 100? (5 points)", "_____no_output_____" ] ], [ [ "def get_graph_class(dataset, idx):\n # TODO: Implement a function that takes a deepsnap dataset object,\n # the index of a graph in the dataset, and returns the class/label \n # of the graph (in integer).\n\n label = -1\n\n ############# Your code here ############\n ## (~1 line of code)\n ## Notice\n ## 1. The graph label refers to a graph-level attribute\n label = dataset[idx].graph_label\n\n #########################################\n\n return label\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n graph_0 = dataset[0]\n print(graph_0)\n idx = 100\n label = get_graph_class(dataset, idx)\n print('Graph with index {} has label {}'.format(idx, label))", "Graph(G=[], edge_index=[2, 82], edge_label_index=[2, 82], graph_label=[1], node_feature=[39, 35], node_label_index=[39], task=[])\nGraph with index 100 has label tensor([0])\n" ] ], [ [ "## Question 2.3: How many edges are in the graph with index 200? (5 points)\n", "_____no_output_____" ] ], [ [ "def get_graph_num_edges(dataset, idx):\n # TODO: Implement a function that takes a deepsnap dataset object,\n # the index of a graph in dataset, and returns the number of \n # edges in the graph (in integer).\n\n num_edges = 0\n\n ############# Your code here ############\n ## (~1 lines of code)\n ## Note\n ## 1. You can use the class property directly\n num_edges = dataset[idx].num_edges\n\n #########################################\n\n return num_edges\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n idx = 200\n num_edges = get_graph_num_edges(dataset, idx)\n print('Graph with index {} has {} edges'.format(idx, num_edges))", "Graph with index 200 has 49 edges\n" ] ], [ [ "# 3) DeepSNAP Advanced\n\nNow that we have learned the basics of DeepSNAP lets move on to some more advanced functionalities.\n\nIn this section we will use DeepSNAP for graph feature computation and transductive/inductive dataset splitting.", "_____no_output_____" ], [ "## Setup", "_____no_output_____" ] ], [ [ "import torch\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nfrom deepsnap.graph import Graph\nfrom deepsnap.batch import Batch\nfrom deepsnap.dataset import GraphDataset\nfrom torch_geometric.datasets import Planetoid, TUDataset\n\nfrom torch.utils.data import DataLoader", "_____no_output_____" ] ], [ [ "## Data Split in Graphs\n\nAs discussed in (LECTURE REFERENCE), data splitting for graphs can be much harder than for CV or NLP.\n\nIn general, data splitting is divided into two settings, **inductive** and **transductive**.", "_____no_output_____" ], [ "## Inductive Split\n\nIn an inductive setting, we split a list of multiple graphs into disjoint training/valiation and test sets.\n\nHere is an example of using DeepSNAP to inductively split a list of graphs for a graph level task (graph classification etc.):", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n root = './tmp/cox2'\n name = 'COX2'\n\n pyg_dataset = TUDataset(root, name)\n\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n\n # Here we specify the task as graph-level task such as graph classification\n task = 'graph'\n dataset = GraphDataset(graphs, task=task)\n\n # Specify transductive=False (inductive)\n dataset_train, dataset_val, dataset_test = dataset.split(transductive=False, split_ratio=[0.8, 0.1, 0.1])\n\n print(\"COX2 train dataset: {}\".format(dataset_train))\n print(\"COX2 validation dataset: {}\".format(dataset_val))\n print(\"COX2 test dataset: {}\".format(dataset_test))", "COX2 train dataset: GraphDataset(373)\nCOX2 validation dataset: GraphDataset(46)\nCOX2 test dataset: GraphDataset(48)\n" ] ], [ [ "## Transductive Split\n\nIn the transductive setting, the training /validation / test sets are all over the same graph. As discussed in (LECTURE REF), we consider a transductive setting when we do not need to generalize to new unseen graphs. \n\nAs an example, here we transductively split the CORA graph for a node level task, such as node classification. \n\n(Notice that in DeepSNAP the default split setting is random (i.e. DeepSNAP randomly splits the e.g. nodes into train / val / test); however, you can also use a fixed split by specifying `fixed_split=True` when loading the dataset from PyG or changing the `node_label_index` directly).", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n root = './tmp/cora'\n name = 'Cora'\n\n pyg_dataset = Planetoid(root, name)\n\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n\n # Here we specify the task as node-level task such as node classification\n task = 'node'\n\n dataset = GraphDataset(graphs, task=task)\n\n # Specify we want the transductive splitting\n dataset_train, dataset_val, dataset_test = dataset.split(transductive=True, split_ratio=[0.8, 0.1, 0.1])\n\n print(\"Cora train dataset: {}\".format(dataset_train))\n print(\"Cora validation dataset: {}\".format(dataset_val))\n print(\"Cora test dataset: {}\".format(dataset_test))\n\n print(\"Original Cora has {} nodes\".format(dataset.num_nodes[0]))\n\n # The nodes in each set can be find in node_label_index\n print(\"After the split, Cora has {} training nodes\".format(dataset_train[0].node_label_index.shape[0]))\n print(\"After the split, Cora has {} validation nodes\".format(dataset_val[0].node_label_index.shape[0]))\n print(\"After the split, Cora has {} test nodes\".format(dataset_test[0].node_label_index.shape[0]))", "Cora train dataset: GraphDataset(1)\nCora validation dataset: GraphDataset(1)\nCora test dataset: GraphDataset(1)\nOriginal Cora has 2708 nodes\nAfter the split, Cora has 2166 training nodes\nAfter the split, Cora has 270 validation nodes\nAfter the split, Cora has 272 test nodes\n" ] ], [ [ "## Edge Level Split\n\nCompared to node and graph level splitting, edge level splitting is a little bit tricky ;)\n\nFor edge level splitting we need to consider several different tasks:\n\n1. Splitting positive edges into train / val / test datasets.\n2. Sampling / re-sampling negative edges (i.e. edges not present in the graph).\n3. Splitting edges into message passing and supervision edges.\n\nWith regard to point 3, for edge level data splitting we classify edges into two types. The first is `message passing` edges, edges that are used for message passing by our GNN. The second is `supervision`, edges that are used in the loss function for backpropagation. DeepSNAP allows for two different modes, where the `message passing` and `supervision` edges are either the same or disjoint.", "_____no_output_____" ], [ "### All Edge Splitting Mode\n\nFirst, we explore the `edge_train_mode=\"all\"` mode for edge level splitting, where the `message passing` and `supervision` edges are shared during training.", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n root = './tmp/cora'\n name = 'Cora'\n\n pyg_dataset = Planetoid(root, name)\n\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n\n # Specify task as link_pred for edge-level task\n task = 'link_pred'\n\n # Specify the train mode, \"all\" mode is default for deepsnap dataset\n edge_train_mode = \"all\"\n\n dataset = GraphDataset(graphs, task=task, edge_train_mode=edge_train_mode)\n\n # Transductive link prediction split\n dataset_train, dataset_val, dataset_test = dataset.split(transductive=True, split_ratio=[0.8, 0.1, 0.1])\n\n print(\"Cora train dataset: {}\".format(dataset_train))\n print(\"Cora validation dataset: {}\".format(dataset_val))\n print(\"Cora test dataset: {}\".format(dataset_test))", "Cora train dataset: GraphDataset(1)\nCora validation dataset: GraphDataset(1)\nCora test dataset: GraphDataset(1)\n" ] ], [ [ "In DeepSNAP, the indices of supervision edges are stored in the `edge_label_index` tensor and the corresponding edge labels are stored in `edge_label` tensor.", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n print(\"Original Cora graph has {} edges\".format(dataset[0].num_edges))\n print()\n\n print(\"Train set has {} message passing edge\".format(dataset_train[0].edge_index.shape[1] // 2))\n print(\"Train set has {} supervision (positive) edges\".format(dataset_train[0].edge_label_index.shape[1] // 4))\n\n print()\n print(\"Validation set has {} message passing edge\".format(dataset_val[0].edge_index.shape[1] // 2))\n print(\"Validation set has {} supervision (positive) edges\".format(dataset_val[0].edge_label_index.shape[1] // 4))\n\n print()\n print(\"Test set has {} message passing edge\".format(dataset_test[0].edge_index.shape[1] // 2))\n print(\"Test set has {} supervision (positive) edges\".format(dataset_test[0].edge_label_index.shape[1] // 4))", "Original Cora graph has 5278 edges\n\nTrain set has 4222 message passing edge\nTrain set has 4222 supervision (positive) edges\n\nValidation set has 4222 message passing edge\nValidation set has 527 supervision (positive) edges\n\nTest set has 4749 message passing edge\nTest set has 529 supervision (positive) edges\n" ] ], [ [ "**Specific things to note in `all` mode**:\n\n* At training time: the supervision edges are the same as the training message passing edges. \n* At validation time: the message passing edges are the training message passing edges and training supervision edges (still the training message passing edges in this case). However, we now include a set of unseen validation supervision edges that are disjoint from the training supervision edges.\n* At test time: the message passing edges are the union of training message passing edges, training supervision edges, and validation supervision edges. The test supervision edges then disjoint from the training supervision edges and validation supervision edges.\n* We exclude negative edges in this illustration. However, the attributes `edge_label` and `edge_label_index` naturally also include the negative supervision edges (by default the number of negative edges is the same as the number of positive edges, hence the divide by 4 above).\n\n\nNow, that we have seen the basics of the `all` method for edge splitting, we will implement a function that checks whether two edge index tensors are disjoint and explore more edge splitting properties by using that function.", "_____no_output_____" ], [ "## Question 3: Implement a function that checks whether two edge_index tensors are disjoint (i.e. do not share any common edges). Then answer the True/False questions below. (5 points)\n\n", "_____no_output_____" ] ], [ [ "def edge_indices_disjoint(edge_index_1, edge_index_2):\n # TODO: Implement this function that takes two edge index tensors,\n # and returns whether these two edge index tensors are disjoint.\n disjoint = None\n\n ############# Your code here ############\n ## (~5 lines of code)\n ## Note\n ## 1. Here disjoint means that there is no single edge belongs to both edge index tensors\n ## 2. You do not need to consider the undirected case. For example, if edge_index_1 contains\n ## edge (a, b) and edge_index_2 contains edge (b, a). We will treat them as disjoint in this\n ## function.\n edge_index_1_np = edge_index_1.T.detach().cpu().numpy()\n edge_index_2_np = edge_index_2.T.detach().cpu().numpy()\n\n intercept = [x for x in set(tuple(x) for x in edge_index_1_np) & set(tuple(x) for x in edge_index_2_np)]\n\n disjoint = len(intercept) == 0\n #########################################\n\n return disjoint", "_____no_output_____" ], [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n num_train_edges = dataset_train[0].edge_label_index.shape[1] // 2\n train_pos_edge_index = dataset_train[0].edge_label_index[:, :num_train_edges]\n train_neg_edge_index = dataset_train[0].edge_label_index[:, num_train_edges:]\n print(\"3.1 Training (supervision) positve and negative edges are disjoint = {}\"\\\n .format(edge_indices_disjoint(train_pos_edge_index, train_neg_edge_index)))\n\n num_val_edges = dataset_val[0].edge_label_index.shape[1] // 2\n val_pos_edge_index = dataset_val[0].edge_label_index[:, :num_val_edges]\n val_neg_edge_index = dataset_val[0].edge_label_index[:, num_val_edges:]\n print(\"3.2 Validation (supervision) positve and negative edges are disjoint = {}\"\\\n .format(edge_indices_disjoint(val_pos_edge_index, val_neg_edge_index)))\n\n num_test_edges = dataset_test[0].edge_label_index.shape[1] // 2\n test_pos_edge_index = dataset_test[0].edge_label_index[:, :num_test_edges]\n test_neg_edge_index = dataset_test[0].edge_label_index[:, num_test_edges:]\n print(\"3.3 Test (supervision) positve and negative edges are disjoint = {}\"\\\n .format(edge_indices_disjoint(test_pos_edge_index, test_neg_edge_index)))\n\n print(\"3.4 Test (supervision) positve and validation (supervision) positve edges are disjoint = {}\"\\\n .format(edge_indices_disjoint(test_pos_edge_index, val_pos_edge_index)))\n print(\"3.5 Validation (supervision) positve and training (supervision) positve edges are disjoint = {}\"\\\n .format(edge_indices_disjoint(val_pos_edge_index, train_pos_edge_index)))", "3.1 Training (supervision) positve and negative edges are disjoint = True\n3.2 Validation (supervision) positve and negative edges are disjoint = True\n3.3 Test (supervision) positve and negative edges are disjoint = True\n3.4 Test (supervision) positve and validation (supervision) positve edges are disjoint = True\n3.5 Validation (supervision) positve and training (supervision) positve edges are disjoint = True\n" ] ], [ [ "### Disjoint Edge Splitting Mode\n\nNow we will look at a relatively more complex transductive edge split setting, the `edge_train_mode=\"disjoint\"` mode in DeepSNAP. In this setting, the `message passing` and `supervision` edges are completely disjoint", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ: \n edge_train_mode = \"disjoint\"\n\n dataset = GraphDataset(graphs, task='link_pred', edge_train_mode=edge_train_mode)\n orig_edge_index = dataset[0].edge_index\n dataset_train, dataset_val, dataset_test = dataset.split(\n transductive=True, split_ratio=[0.8, 0.1, 0.1])\n\n train_message_edge_index = dataset_train[0].edge_index\n train_sup_edge_index = dataset_train[0].edge_label_index\n val_message_edge_index = dataset_val[0].edge_index\n val_sup_edge_index = dataset_val[0].edge_label_index\n test_message_edge_index = dataset_test[0].edge_index\n test_sup_edge_index = dataset_test[0].edge_label_index\n\n print(\"Original Cora graph has {} edges\".format(dataset[0].num_edges))\n print()\n print(\"Train set has {} message passing edge\".format(train_message_edge_index.shape[1] // 2))\n print(\"Train set has {} supervision (positive) edges\".format(train_sup_edge_index.shape[1] // 4))\n\n print()\n print(\"Validation set has {} message passing edge\".format(val_message_edge_index.shape[1] // 2))\n print(\"Validation set has {} supervision (positive) edges\".format(val_sup_edge_index.shape[1] // 4))\n\n print()\n print(\"Test set has {} message passing edge\".format(test_message_edge_index.shape[1] // 2))\n print(\"Test set has {} supervision (positive) edges\".format(test_sup_edge_index.shape[1] // 4))", "Original Cora graph has 5278 edges\n\nTrain set has 3377 message passing edge\nTrain set has 845 supervision (positive) edges\n\nValidation set has 4222 message passing edge\nValidation set has 527 supervision (positive) edges\n\nTest set has 4749 message passing edge\nTest set has 529 supervision (positive) edges\n" ] ], [ [ "\n**Specific things to note in `disjoint` mode**:\n\n* At training time: the training supervision edges are disjoint from the training message passing edges.\n* At validation time: the message passing edges are the union of training message passing edges and training supervision edges. The validation supervision edges are disjoint from both the training message passing and supervision edges.\n* At test time: the message passing edges are the training message passing edges, training supervision edges, and validation supervision edges. The test supervision edges are disjoint from all the training and validation edges.", "_____no_output_____" ], [ "## Negative Edges\n\nFor edge level tasks, sampling negative edges is critical. Moreover, during each training iteration, we want to resample the negative edges.\n\nBelow we print the training and validation sets negative edges in two training iterations.\n\nWhat we demonstrate is that the negative edges are only resampled during training.", "_____no_output_____" ] ], [ [ "if 'IS_GRADESCOPE_ENV' not in os.environ: \n dataset = GraphDataset(graphs, task='link_pred', edge_train_mode=\"disjoint\")\n datasets = {}\n follow_batch = []\n datasets['train'], datasets['val'], datasets['test'] = dataset.split(\n transductive=True, split_ratio=[0.8, 0.1, 0.1])\n dataloaders = {\n split: DataLoader(\n ds, collate_fn=Batch.collate(follow_batch),\n batch_size=1, shuffle=(split=='train')\n )\n for split, ds in datasets.items()\n }\n neg_edges_1 = None\n for batch in dataloaders['train']:\n num_edges = batch.edge_label_index.shape[1] // 2\n neg_edges_1 = batch.edge_label_index[:, num_edges:]\n print(\"First iteration training negative edges:\")\n print(neg_edges_1)\n break\n neg_edges_2 = None\n for batch in dataloaders['train']:\n num_edges = batch.edge_label_index.shape[1] // 2\n neg_edges_2 = batch.edge_label_index[:, num_edges:]\n print(\"Second iteration training negative edges:\")\n print(neg_edges_2)\n break\n\n neg_edges_1 = None\n for batch in dataloaders['val']:\n num_edges = batch.edge_label_index.shape[1] // 2\n neg_edges_1 = batch.edge_label_index[:, num_edges:]\n print(\"First iteration validation negative edges:\")\n print(neg_edges_1)\n break\n neg_edges_2 = None\n for batch in dataloaders['val']:\n num_edges = batch.edge_label_index.shape[1] // 2\n neg_edges_2 = batch.edge_label_index[:, num_edges:]\n print(\"Second iteration validation negative edges:\")\n print(neg_edges_2)\n break", "First iteration training negative edges:\ntensor([[ 929, 69, 1042, ..., 572, 1133, 358],\n [1410, 2548, 2525, ..., 645, 2494, 2686]])\nSecond iteration training negative edges:\ntensor([[1825, 2407, 2433, ..., 599, 940, 868],\n [ 250, 1064, 514, ..., 1799, 2427, 52]])\nFirst iteration validation negative edges:\ntensor([[ 2, 1232, 972, ..., 1000, 2505, 1749],\n [1156, 2353, 645, ..., 2365, 1618, 409]])\nSecond iteration validation negative edges:\ntensor([[ 2, 1232, 972, ..., 1000, 2505, 1749],\n [1156, 2353, 645, ..., 2365, 1618, 409]])\n" ] ], [ [ "If you are interested in more graph splitting settings, please refer to the DeepSNAP dataset [documentation](https://snap.stanford.edu/deepsnap/modules/dataset.html).", "_____no_output_____" ], [ "## Graph Transformation and Feature Computation\n\nThe other core functionality of DeepSNAP is graph transformation / feature computation.\n\nIn DeepSNAP, we divide graph transformation / feature computation into two different types. The first includes transformations before training (e.g. transform the whole dataset before training directly), and the second includes transformations during training (transform batches of graphs).\n\nBelow is an example that uses the NetworkX back end to calculate the PageRank value for each node and subsequently transforms the node features by concatenating each nodes PageRank score (transform the dataset before training).", "_____no_output_____" ] ], [ [ "def pagerank_transform_fn(graph):\n\n # Get the referenced networkx graph\n G = graph.G\n\n # Calculate the pagerank by using networkx\n pr = nx.pagerank(G)\n\n # Transform the pagerank values to tensor\n pr_feature = torch.tensor([pr[node] for node in range(graph.num_nodes)], dtype=torch.float32)\n pr_feature = pr_feature.view(graph.num_nodes, 1)\n\n # Concat the pagerank values to the node feature\n graph.node_feature = torch.cat([graph.node_feature, pr_feature], dim=-1)\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n root = './tmp/cox2'\n name = 'COX2'\n pyg_dataset = TUDataset(root, name)\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n dataset = GraphDataset(graphs, task='graph')\n print(\"Number of features before transformation: {}\".format(dataset.num_node_features))\n dataset.apply_transform(pagerank_transform_fn, update_tensor=False)\n print(\"Number of features after transformation: {}\".format(dataset.num_node_features))", "Number of features before transformation: 35\nNumber of features after transformation: 36\n" ] ], [ [ "## Question 4: Implement a transformation that adds the clustering coefficient of each node to its feature vector and then report the clustering coefficient of the node with index 3 in the graph with index 406 (5 points).", "_____no_output_____" ] ], [ [ "def cluster_transform_fn(graph):\n # TODO: Implement a function that takes an deepsnap graph object and \n # transform the graph by adding each node's clustering coefficient to its \n # graph.node_feature representation\n\n ############# Your code here ############\n ## (~5 lines of code)\n ## Note\n ## 1. Compute the clustering coefficient value for each node and\n ## concat this value to the last dimension of graph.node_feature\n \n # Get networkx graph\n G = graph.G\n\n # Calculate clustering coefficient/pagerank using networkx\n pr = nx.algorithms.cluster.clustering(G)\n\n # Transform pagerank value to tensor\n pr_feature = torch.tensor([pr[node] for node in range(graph.num_nodes)], dtype=torch.float16)\n pr_feature = pr_feature.view(graph.num_nodes, 1)\n\n # concat pagerank values to the node features\n graph.node_feature = torch.cat([graph.node_feature, pr_feature], dim=-1)\n\n #########################################\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n root = './cox2'\n name = 'COX2'\n pyg_dataset = TUDataset(root, name)\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n dataset = GraphDataset(graphs, task='graph')\n\n # Transform the dataset\n dataset.apply_transform(cluster_transform_fn, update_tensor=False)\n\n node_idx = 3\n graph_idx = 406\n node_feature = dataset[graph_idx].node_feature\n\n print(\"The node has clustering coefficient: {}\".format(round(node_feature[node_idx][-1].item(), 2)))", "The node has clustering coefficient: 0.17\n" ] ], [ [ "### Final Thoughts\nApart from transforming the whole dataset before training, DeepSNAP can also transform the graph (usually sampled batches of graphs, `deepsnap.batch.Batch`) during each training iteration.\n\nAlso, DeepSNAP supports the synchronization of the transformation between the referenced graph objects and tensor representations. For example, you can just update the NetworkX graph object in the transform function and by specifying `update_tensor=True` the internal tensor representations will be automatically updated!\n\nFor more information, please refer to the DeepSNAP [documentation](https://snap.stanford.edu/deepsnap/).", "_____no_output_____" ], [ "# 4) Edge Level Prediction\n\nFrom the last section, we learned how DeepSNAP trandsuctively splits edges for edge level tasks. For the last part of the notebook, we will use DeepSNAP and PyG together to implement a simple edge level prediction (link prediction) model!\n\nSpecifically, we will use a 2 layer GraphSAGE embedding model to generate node embeddings, and then compute link predictions through a dot product link prediction head. Namely, given an edge (u, v) with GNN feature embeddings $f_u$ and $f_v$, our link prediction head generates its link prediction as $f_u \\cdot f_v$. \n\nTo give a brief intuition for this dot product link prediction model, we are learning a GNN that embedds nodes such that nodes that have an edge in the graph are closer within the embedding space than nodes that do not have an edge. The dot product provides a proxy for closeness in our embedding space where a high positive dot product indicates that two vectors are more closely aligned (the angle between the vectors is small), whereas a negative dot-product indicates that vectors are unaligned (the angle between the vectors is greater than 90). ", "_____no_output_____" ] ], [ [ "import copy\nimport torch\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nfrom deepsnap.graph import Graph\nfrom deepsnap.batch import Batch\nfrom deepsnap.dataset import GraphDataset\nfrom torch_geometric.datasets import Planetoid, TUDataset\n\nfrom torch.utils.data import DataLoader\n\nimport torch.nn.functional as F\nfrom torch_geometric.nn import SAGEConv\n\nclass LinkPredModel(torch.nn.Module):\n def __init__(self, input_dim, hidden_dim, num_classes, dropout=0.2):\n super(LinkPredModel, self).__init__()\n\n self.conv1 = SAGEConv(input_dim, hidden_dim)\n self.conv2 = SAGEConv(hidden_dim, num_classes)\n\n self.loss_fn = None\n\n ############# Your code here #############\n ## (~1 line of code)\n ## Note\n ## 1. Initialize the loss function to BCEWithLogitsLoss\n self.loss_fn = nn.BCEWithLogitsLoss()\n\n ##########################################\n\n self.dropout = dropout\n\n def reset_parameters(self):\n self.conv1.reset_parameters()\n self.conv2.reset_parameters()\n\n def forward(self, batch):\n node_feature, edge_index, edge_label_index = batch.node_feature, batch.edge_index, batch.edge_label_index\n \n ############# Your code here #############\n ## (~6 line of code)\n ## Note\n ## 1. Feed the node feature into the first conv layer\n ## 2. Add a ReLU after the first conv layer\n ## 3. Add dropout after the ReLU (with probability self.dropout)\n ## 4. Feed the output to the second conv layer\n ## 5. Select the embeddings of the source nodes and destination nodes\n ## by using the edge_label_index and compute the similarity of each pair\n ## by dot product\n x = self.conv1(node_feature, edge_index)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout)\n x = self.conv2(x, edge_index)\n\n x_src = x[edge_label_index[0]]\n x_dst = x[edge_label_index[1]]\n x_similarity = x_src * x_dst\n\n pred = torch.sum(x_similarity, dim=-1)\n \n ##########################################\n\n return pred\n \n def loss(self, pred, link_label):\n return self.loss_fn(pred, link_label)", "_____no_output_____" ], [ "from sklearn.metrics import *\n\ndef train(model, dataloaders, optimizer, args):\n val_max = 0\n best_model = model\n\n for epoch in range(1, args[\"epochs\"]):\n for i, batch in enumerate(dataloaders['train']):\n \n batch.to(args[\"device\"])\n\n ############# Your code here #############\n ## (~6 lines of code)\n ## Note\n ## 1. Zero grad the optimizer\n ## 2. Compute loss and backpropagate\n ## 3. Update the model parameters\n optimizer.zero_grad()\n pred = model(batch)\n loss = model.loss(pred, batch.edge_label.type_as(pred))\n loss.backward()\n optimizer.step()\n ##########################################\n\n log = 'Epoch: {:03d}, Train: {:.4f}, Val: {:.4f}, Test: {:.4f}, Loss: {}'\n score_train = test(model, dataloaders['train'], args)\n score_val = test(model, dataloaders['val'], args)\n score_test = test(model, dataloaders['test'], args)\n\n print(log.format(epoch, score_train, score_val, score_test, loss.item()))\n if val_max < score_val:\n val_max = score_val\n best_model = copy.deepcopy(model)\n return best_model\n\ndef test(model, dataloader, args, save_model_preds=False):\n model.eval()\n\n score = 0\n preds = None\n labels = None\n\n ############# Your code here #############\n ## (~7 lines of code)\n ## Note\n ## 1. Loop through batches in the dataloader (Note for us there is only one batch!)\n ## 2. Feed the batch to the model\n ## 3. Feed the model output to sigmoid\n ## 4. Compute the ROC-AUC score by using sklearn roc_auc_score function \n ## Note: Look into flattening and converting torch tensors into numpy arrays\n ## 5. Edge labels are stored in batch.edge_label\n ## 6. Make sure to save your **numpy** model predictions as 'preds' \n ## and the **numpy** edge labels as 'labels'\n # for batch in dataloader:\n for batch in dataloaders['test']:\n batch.to(args['device'])\n preds = model(batch)\n preds = torch.sigmoid(preds).cpu().detach().numpy()\n labels = batch.edge_label.cpu().detach().numpy()\n score += roc_auc_score(labels, preds)\n score /= len(dataloaders['test'])\n ##########################################\n\n if save_model_preds:\n print (\"Saving Link Classification Model Predictions\")\n print()\n\n data = {}\n data['pred'] = preds\n data['label'] = labels\n\n df = pd.DataFrame(data=data)\n # Save locally as csv\n df.to_csv('CORA-Link-Prediction.csv', sep=',', index=False)\n \n return score", "_____no_output_____" ], [ "# Please don't change any parameters\nargs = {\n \"device\" : 'cuda' if torch.cuda.is_available() else 'cpu',\n \"hidden_dim\" : 128,\n \"epochs\" : 200,\n}", "_____no_output_____" ], [ "if 'IS_GRADESCOPE_ENV' not in os.environ:\n pyg_dataset = Planetoid('./tmp/cora', 'Cora')\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset)\n\n dataset = GraphDataset(\n graphs,\n task='link_pred',\n edge_train_mode=\"disjoint\"\n )\n datasets = {}\n datasets['train'], datasets['val'], datasets['test']= dataset.split(\n transductive=True, split_ratio=[0.85, 0.05, 0.1])\n input_dim = datasets['train'].num_node_features\n num_classes = datasets['train'].num_edge_labels\n\n model = LinkPredModel(input_dim, args[\"hidden_dim\"], num_classes).to(args[\"device\"])\n model.reset_parameters()\n\n optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)\n\n dataloaders = {split: DataLoader(\n ds, collate_fn=Batch.collate([]),\n batch_size=1, shuffle=(split=='train'))\n for split, ds in datasets.items()}\n best_model = train(model, dataloaders, optimizer, args)\n log = \"Best Model Accuraies Train: {:.4f}, Val: {:.4f}, Test: {:.4f}\"\n best_train_roc = test(best_model, dataloaders['train'], args)\n best_val_roc = test(best_model, dataloaders['val'], args)\n best_test_roc = test(best_model, dataloaders['test'], args, save_model_preds=True)\n print(log.format(best_train_roc, best_val_roc, best_test_roc))", "Epoch: 001, Train: 0.5019, Val: 0.4953, Test: 0.5062, Loss: 0.6932055354118347\nEpoch: 002, Train: 0.5089, Val: 0.4964, Test: 0.4886, Loss: 0.6931920647621155\nEpoch: 003, Train: 0.5206, Val: 0.4928, Test: 0.5118, Loss: 0.6932067275047302\nEpoch: 004, Train: 0.5019, Val: 0.4990, Test: 0.5043, Loss: 0.6931806802749634\nEpoch: 005, Train: 0.5082, Val: 0.5174, Test: 0.4950, Loss: 0.6932178139686584\nEpoch: 006, Train: 0.5022, Val: 0.5271, Test: 0.5069, Loss: 0.6932305097579956\nEpoch: 007, Train: 0.5222, Val: 0.4992, Test: 0.5077, Loss: 0.6932173371315002\nEpoch: 008, Train: 0.4989, Val: 0.5117, Test: 0.5131, Loss: 0.6931739449501038\nEpoch: 009, Train: 0.5138, Val: 0.5229, Test: 0.5192, Loss: 0.693060040473938\nEpoch: 010, Train: 0.5168, Val: 0.5268, Test: 0.5048, Loss: 0.6931229829788208\nEpoch: 011, Train: 0.5327, Val: 0.5091, Test: 0.5290, Loss: 0.6930479407310486\nEpoch: 012, Train: 0.5337, Val: 0.5132, Test: 0.5371, Loss: 0.6930755972862244\nEpoch: 013, Train: 0.5220, Val: 0.5220, Test: 0.5197, Loss: 0.693119466304779\nEpoch: 014, Train: 0.5292, Val: 0.5178, Test: 0.5210, Loss: 0.6930415630340576\nEpoch: 015, Train: 0.5166, Val: 0.5225, Test: 0.5263, Loss: 0.6930370330810547\nEpoch: 016, Train: 0.5366, Val: 0.5217, Test: 0.5326, Loss: 0.693081796169281\nEpoch: 017, Train: 0.5396, Val: 0.5155, Test: 0.5344, Loss: 0.6929906010627747\nEpoch: 018, Train: 0.5304, Val: 0.5175, Test: 0.5372, Loss: 0.6929558515548706\nEpoch: 019, Train: 0.5353, Val: 0.5420, Test: 0.5374, Loss: 0.6928719282150269\nEpoch: 020, Train: 0.5443, Val: 0.5569, Test: 0.5219, Loss: 0.6928818225860596\nEpoch: 021, Train: 0.5439, Val: 0.5291, Test: 0.5486, Loss: 0.6928641200065613\nEpoch: 022, Train: 0.5366, Val: 0.5287, Test: 0.5459, Loss: 0.6927971243858337\nEpoch: 023, Train: 0.5313, Val: 0.5400, Test: 0.5477, Loss: 0.6928063035011292\nEpoch: 024, Train: 0.5432, Val: 0.5306, Test: 0.5574, Loss: 0.6927868127822876\nEpoch: 025, Train: 0.5360, Val: 0.5359, Test: 0.5440, Loss: 0.6928010582923889\nEpoch: 026, Train: 0.5425, Val: 0.5373, Test: 0.5201, Loss: 0.692813515663147\nEpoch: 027, Train: 0.5476, Val: 0.5447, Test: 0.5412, Loss: 0.6927600502967834\nEpoch: 028, Train: 0.5377, Val: 0.5493, Test: 0.5632, Loss: 0.6926769614219666\nEpoch: 029, Train: 0.5447, Val: 0.5579, Test: 0.5498, Loss: 0.6925768852233887\nEpoch: 030, Train: 0.5531, Val: 0.5458, Test: 0.5538, Loss: 0.6925328969955444\nEpoch: 031, Train: 0.5502, Val: 0.5608, Test: 0.5495, Loss: 0.6924236416816711\nEpoch: 032, Train: 0.5685, Val: 0.5580, Test: 0.5468, Loss: 0.6924571990966797\nEpoch: 033, Train: 0.5701, Val: 0.5536, Test: 0.5451, Loss: 0.6924594640731812\nEpoch: 034, Train: 0.5480, Val: 0.5416, Test: 0.5586, Loss: 0.6924310922622681\nEpoch: 035, Train: 0.5610, Val: 0.5585, Test: 0.5397, Loss: 0.6923143267631531\nEpoch: 036, Train: 0.5472, Val: 0.5463, Test: 0.5490, Loss: 0.6921097040176392\nEpoch: 037, Train: 0.5622, Val: 0.5556, Test: 0.5273, Loss: 0.6921440958976746\nEpoch: 038, Train: 0.5449, Val: 0.5430, Test: 0.5551, Loss: 0.6920964121818542\nEpoch: 039, Train: 0.5575, Val: 0.5524, Test: 0.5576, Loss: 0.6919888257980347\nEpoch: 040, Train: 0.5427, Val: 0.5541, Test: 0.5403, Loss: 0.6920359134674072\nEpoch: 041, Train: 0.5478, Val: 0.5588, Test: 0.5605, Loss: 0.691764235496521\nEpoch: 042, Train: 0.5579, Val: 0.5612, Test: 0.5501, Loss: 0.6918411254882812\nEpoch: 043, Train: 0.5679, Val: 0.5459, Test: 0.5517, Loss: 0.6918407082557678\nEpoch: 044, Train: 0.5434, Val: 0.5483, Test: 0.5473, Loss: 0.6916317939758301\nEpoch: 045, Train: 0.5485, Val: 0.5527, Test: 0.5550, Loss: 0.6913734674453735\nEpoch: 046, Train: 0.5520, Val: 0.5572, Test: 0.5527, Loss: 0.691251814365387\nEpoch: 047, Train: 0.5697, Val: 0.5536, Test: 0.5556, Loss: 0.6910400390625\nEpoch: 048, Train: 0.5674, Val: 0.5626, Test: 0.5664, Loss: 0.691244900226593\nEpoch: 049, Train: 0.5519, Val: 0.5604, Test: 0.5554, Loss: 0.6907708644866943\nEpoch: 050, Train: 0.5556, Val: 0.5720, Test: 0.5574, Loss: 0.6903576850891113\nEpoch: 051, Train: 0.5573, Val: 0.5688, Test: 0.5653, Loss: 0.6909399628639221\nEpoch: 052, Train: 0.5678, Val: 0.5613, Test: 0.5536, Loss: 0.6901348233222961\nEpoch: 053, Train: 0.5552, Val: 0.5795, Test: 0.5688, Loss: 0.6899186372756958\nEpoch: 054, Train: 0.5662, Val: 0.5630, Test: 0.5643, Loss: 0.6895727515220642\nEpoch: 055, Train: 0.5702, Val: 0.5625, Test: 0.5529, Loss: 0.6899831295013428\nEpoch: 056, Train: 0.5701, Val: 0.5714, Test: 0.5617, Loss: 0.688920259475708\nEpoch: 057, Train: 0.5670, Val: 0.5650, Test: 0.5717, Loss: 0.688893735408783\nEpoch: 058, Train: 0.5651, Val: 0.5668, Test: 0.5672, Loss: 0.6887857913970947\nEpoch: 059, Train: 0.5730, Val: 0.5687, Test: 0.5598, Loss: 0.6882851719856262\nEpoch: 060, Train: 0.5730, Val: 0.5745, Test: 0.5768, Loss: 0.688106119632721\nEpoch: 061, Train: 0.5701, Val: 0.5684, Test: 0.5683, Loss: 0.6876559853553772\nEpoch: 062, Train: 0.5765, Val: 0.5755, Test: 0.5710, Loss: 0.6875297427177429\nEpoch: 063, Train: 0.5779, Val: 0.5758, Test: 0.5827, Loss: 0.6867380738258362\nEpoch: 064, Train: 0.5782, Val: 0.5670, Test: 0.5797, Loss: 0.68626868724823\nEpoch: 065, Train: 0.5750, Val: 0.5858, Test: 0.5769, Loss: 0.6862733364105225\nEpoch: 066, Train: 0.5778, Val: 0.5756, Test: 0.5804, Loss: 0.6857287287712097\nEpoch: 067, Train: 0.5749, Val: 0.5798, Test: 0.5715, Loss: 0.685171365737915\nEpoch: 068, Train: 0.5849, Val: 0.5790, Test: 0.5741, Loss: 0.6841467618942261\nEpoch: 069, Train: 0.5831, Val: 0.5791, Test: 0.5880, Loss: 0.6842892169952393\nEpoch: 070, Train: 0.5765, Val: 0.5782, Test: 0.5797, Loss: 0.6838349103927612\nEpoch: 071, Train: 0.5860, Val: 0.5885, Test: 0.5847, Loss: 0.6830412149429321\nEpoch: 072, Train: 0.5827, Val: 0.5856, Test: 0.5859, Loss: 0.6808038949966431\nEpoch: 073, Train: 0.5878, Val: 0.5872, Test: 0.5836, Loss: 0.6804813146591187\nEpoch: 074, Train: 0.5849, Val: 0.5877, Test: 0.5882, Loss: 0.6788002252578735\nEpoch: 075, Train: 0.5950, Val: 0.5847, Test: 0.5861, Loss: 0.6783311367034912\nEpoch: 076, Train: 0.5907, Val: 0.5925, Test: 0.5909, Loss: 0.6774953603744507\nEpoch: 077, Train: 0.5903, Val: 0.5897, Test: 0.5954, Loss: 0.6758286356925964\nEpoch: 078, Train: 0.5999, Val: 0.5948, Test: 0.5963, Loss: 0.675263524055481\nEpoch: 079, Train: 0.6012, Val: 0.6020, Test: 0.5992, Loss: 0.6710941195487976\nEpoch: 080, Train: 0.6011, Val: 0.5963, Test: 0.6017, Loss: 0.6713895201683044\nEpoch: 081, Train: 0.6026, Val: 0.5997, Test: 0.6035, Loss: 0.6704581379890442\nEpoch: 082, Train: 0.6122, Val: 0.6075, Test: 0.6132, Loss: 0.6695705056190491\nEpoch: 083, Train: 0.6164, Val: 0.6143, Test: 0.6156, Loss: 0.6671017408370972\nEpoch: 084, Train: 0.6198, Val: 0.6248, Test: 0.6218, Loss: 0.6689134836196899\nEpoch: 085, Train: 0.6330, Val: 0.6274, Test: 0.6404, Loss: 0.6630488038063049\nEpoch: 086, Train: 0.6432, Val: 0.6436, Test: 0.6440, Loss: 0.6611646413803101\nEpoch: 087, Train: 0.6535, Val: 0.6534, Test: 0.6497, Loss: 0.6594260931015015\nEpoch: 088, Train: 0.6574, Val: 0.6575, Test: 0.6556, Loss: 0.6585035920143127\nEpoch: 089, Train: 0.6550, Val: 0.6719, Test: 0.6709, Loss: 0.6572673916816711\nEpoch: 090, Train: 0.6725, Val: 0.6675, Test: 0.6728, Loss: 0.651466429233551\nEpoch: 091, Train: 0.6772, Val: 0.6765, Test: 0.6786, Loss: 0.6508798599243164\nEpoch: 092, Train: 0.6733, Val: 0.6770, Test: 0.6773, Loss: 0.6480381488800049\nEpoch: 093, Train: 0.6733, Val: 0.6829, Test: 0.6780, Loss: 0.6487643718719482\nEpoch: 094, Train: 0.6846, Val: 0.6789, Test: 0.6798, Loss: 0.6418784856796265\nEpoch: 095, Train: 0.6845, Val: 0.6838, Test: 0.6803, Loss: 0.6384830474853516\nEpoch: 096, Train: 0.6805, Val: 0.6882, Test: 0.6869, Loss: 0.6390049457550049\nEpoch: 097, Train: 0.6846, Val: 0.6803, Test: 0.6791, Loss: 0.641418993473053\nEpoch: 098, Train: 0.6776, Val: 0.6836, Test: 0.6817, Loss: 0.6370711922645569\nEpoch: 099, Train: 0.6855, Val: 0.6783, Test: 0.6785, Loss: 0.6326021552085876\nEpoch: 100, Train: 0.6744, Val: 0.6765, Test: 0.6750, Loss: 0.6325771808624268\nEpoch: 101, Train: 0.6755, Val: 0.6802, Test: 0.6804, Loss: 0.6332057118415833\nEpoch: 102, Train: 0.6774, Val: 0.6818, Test: 0.6858, Loss: 0.6326180696487427\nEpoch: 103, Train: 0.6832, Val: 0.6878, Test: 0.6849, Loss: 0.6269603371620178\nEpoch: 104, Train: 0.6846, Val: 0.6784, Test: 0.6855, Loss: 0.6200358867645264\nEpoch: 105, Train: 0.6769, Val: 0.6822, Test: 0.6828, Loss: 0.6257349252700806\nEpoch: 106, Train: 0.6778, Val: 0.6847, Test: 0.6811, Loss: 0.6317898631095886\nEpoch: 107, Train: 0.6798, Val: 0.6795, Test: 0.6824, Loss: 0.6347403526306152\nEpoch: 108, Train: 0.6757, Val: 0.6804, Test: 0.6797, Loss: 0.6143648028373718\nEpoch: 109, Train: 0.6861, Val: 0.6798, Test: 0.6769, Loss: 0.6243528127670288\nEpoch: 110, Train: 0.6838, Val: 0.6796, Test: 0.6907, Loss: 0.622592031955719\nEpoch: 111, Train: 0.6899, Val: 0.6895, Test: 0.6906, Loss: 0.6148200631141663\nEpoch: 112, Train: 0.6933, Val: 0.6927, Test: 0.6928, Loss: 0.6142141222953796\nEpoch: 113, Train: 0.6904, Val: 0.6858, Test: 0.6943, Loss: 0.61095130443573\nEpoch: 114, Train: 0.6854, Val: 0.6899, Test: 0.6904, Loss: 0.6084436774253845\nEpoch: 115, Train: 0.6851, Val: 0.6866, Test: 0.6905, Loss: 0.6014653444290161\nEpoch: 116, Train: 0.6855, Val: 0.6905, Test: 0.6917, Loss: 0.6062939763069153\nEpoch: 117, Train: 0.6884, Val: 0.6863, Test: 0.6922, Loss: 0.6057735085487366\nEpoch: 118, Train: 0.6912, Val: 0.6885, Test: 0.6918, Loss: 0.6048821210861206\nEpoch: 119, Train: 0.6924, Val: 0.6887, Test: 0.6927, Loss: 0.5992241501808167\nEpoch: 120, Train: 0.6963, Val: 0.6995, Test: 0.6926, Loss: 0.6004308462142944\nEpoch: 121, Train: 0.6916, Val: 0.6929, Test: 0.6951, Loss: 0.6008142828941345\nEpoch: 122, Train: 0.6885, Val: 0.6908, Test: 0.6898, Loss: 0.597372829914093\nEpoch: 123, Train: 0.6924, Val: 0.6954, Test: 0.6960, Loss: 0.6026260852813721\nEpoch: 124, Train: 0.6953, Val: 0.6937, Test: 0.6927, Loss: 0.5994287133216858\nEpoch: 125, Train: 0.6991, Val: 0.6923, Test: 0.6964, Loss: 0.5926941633224487\nEpoch: 126, Train: 0.6901, Val: 0.6915, Test: 0.6953, Loss: 0.5947172045707703\nEpoch: 127, Train: 0.6929, Val: 0.6982, Test: 0.6940, Loss: 0.5826076865196228\nEpoch: 128, Train: 0.6934, Val: 0.7004, Test: 0.6951, Loss: 0.5893241763114929\nEpoch: 129, Train: 0.6926, Val: 0.6915, Test: 0.6912, Loss: 0.5897101163864136\nEpoch: 130, Train: 0.6890, Val: 0.6911, Test: 0.6837, Loss: 0.5968517661094666\nEpoch: 131, Train: 0.6877, Val: 0.6908, Test: 0.6850, Loss: 0.589328408241272\nEpoch: 132, Train: 0.6943, Val: 0.6917, Test: 0.6922, Loss: 0.5831955671310425\nEpoch: 133, Train: 0.6971, Val: 0.6953, Test: 0.7014, Loss: 0.5696879625320435\nEpoch: 134, Train: 0.6930, Val: 0.6998, Test: 0.6988, Loss: 0.5866789817810059\nEpoch: 135, Train: 0.6912, Val: 0.6847, Test: 0.6834, Loss: 0.5844400525093079\nEpoch: 136, Train: 0.6843, Val: 0.6922, Test: 0.6905, Loss: 0.5795565843582153\nEpoch: 137, Train: 0.6946, Val: 0.6935, Test: 0.6870, Loss: 0.5705973505973816\nEpoch: 138, Train: 0.6994, Val: 0.6960, Test: 0.6919, Loss: 0.573519229888916\nEpoch: 139, Train: 0.6969, Val: 0.6982, Test: 0.6976, Loss: 0.5754662156105042\nEpoch: 140, Train: 0.7000, Val: 0.6936, Test: 0.6962, Loss: 0.5710124373435974\nEpoch: 141, Train: 0.6977, Val: 0.6974, Test: 0.6912, Loss: 0.5696238279342651\nEpoch: 142, Train: 0.6941, Val: 0.6926, Test: 0.6963, Loss: 0.5677017569541931\nEpoch: 143, Train: 0.6944, Val: 0.6818, Test: 0.6934, Loss: 0.5729352235794067\nEpoch: 144, Train: 0.6935, Val: 0.6907, Test: 0.6890, Loss: 0.5693244338035583\nEpoch: 145, Train: 0.6975, Val: 0.6938, Test: 0.7049, Loss: 0.5650897026062012\nEpoch: 146, Train: 0.6992, Val: 0.7005, Test: 0.6973, Loss: 0.5605905652046204\nEpoch: 147, Train: 0.6993, Val: 0.7074, Test: 0.6988, Loss: 0.5520856380462646\nEpoch: 148, Train: 0.7046, Val: 0.6977, Test: 0.6991, Loss: 0.5596573948860168\nEpoch: 149, Train: 0.7030, Val: 0.6995, Test: 0.7039, Loss: 0.5518948435783386\nEpoch: 150, Train: 0.7009, Val: 0.7009, Test: 0.7007, Loss: 0.5539484620094299\nEpoch: 151, Train: 0.7032, Val: 0.7044, Test: 0.7017, Loss: 0.5543316006660461\nEpoch: 152, Train: 0.7123, Val: 0.7061, Test: 0.7035, Loss: 0.554809033870697\nEpoch: 153, Train: 0.7123, Val: 0.7023, Test: 0.7083, Loss: 0.5473509430885315\nEpoch: 154, Train: 0.7083, Val: 0.7049, Test: 0.7143, Loss: 0.5487227439880371\nEpoch: 155, Train: 0.7078, Val: 0.7112, Test: 0.7117, Loss: 0.5427062511444092\nEpoch: 156, Train: 0.7134, Val: 0.7131, Test: 0.7106, Loss: 0.5389374494552612\nEpoch: 157, Train: 0.7166, Val: 0.7156, Test: 0.7157, Loss: 0.5452955365180969\nEpoch: 158, Train: 0.7201, Val: 0.7202, Test: 0.7172, Loss: 0.5453580021858215\nEpoch: 159, Train: 0.7228, Val: 0.7193, Test: 0.7295, Loss: 0.5366584658622742\nEpoch: 160, Train: 0.7202, Val: 0.7210, Test: 0.7190, Loss: 0.5381338596343994\nEpoch: 161, Train: 0.7270, Val: 0.7233, Test: 0.7250, Loss: 0.5340146422386169\nEpoch: 162, Train: 0.7286, Val: 0.7189, Test: 0.7235, Loss: 0.5423163771629333\nEpoch: 163, Train: 0.7274, Val: 0.7305, Test: 0.7249, Loss: 0.5440378785133362\nEpoch: 164, Train: 0.7344, Val: 0.7310, Test: 0.7325, Loss: 0.5293395519256592\nEpoch: 165, Train: 0.7375, Val: 0.7351, Test: 0.7351, Loss: 0.5210434198379517\nEpoch: 166, Train: 0.7452, Val: 0.7383, Test: 0.7383, Loss: 0.533065140247345\nEpoch: 167, Train: 0.7420, Val: 0.7399, Test: 0.7403, Loss: 0.5240846276283264\nEpoch: 168, Train: 0.7326, Val: 0.7400, Test: 0.7425, Loss: 0.5234970450401306\nEpoch: 169, Train: 0.7409, Val: 0.7451, Test: 0.7399, Loss: 0.5360404253005981\nEpoch: 170, Train: 0.7472, Val: 0.7486, Test: 0.7388, Loss: 0.5209401845932007\nEpoch: 171, Train: 0.7507, Val: 0.7517, Test: 0.7532, Loss: 0.5266425013542175\nEpoch: 172, Train: 0.7503, Val: 0.7514, Test: 0.7527, Loss: 0.5186090469360352\nEpoch: 173, Train: 0.7505, Val: 0.7531, Test: 0.7534, Loss: 0.5280333757400513\nEpoch: 174, Train: 0.7552, Val: 0.7526, Test: 0.7503, Loss: 0.5169417262077332\nEpoch: 175, Train: 0.7522, Val: 0.7548, Test: 0.7490, Loss: 0.5271726250648499\nEpoch: 176, Train: 0.7538, Val: 0.7506, Test: 0.7491, Loss: 0.525481104850769\nEpoch: 177, Train: 0.7562, Val: 0.7601, Test: 0.7537, Loss: 0.5083685517311096\nEpoch: 178, Train: 0.7586, Val: 0.7582, Test: 0.7592, Loss: 0.5087206363677979\nEpoch: 179, Train: 0.7539, Val: 0.7575, Test: 0.7601, Loss: 0.524002194404602\nEpoch: 180, Train: 0.7592, Val: 0.7525, Test: 0.7563, Loss: 0.5085655450820923\nEpoch: 181, Train: 0.7619, Val: 0.7643, Test: 0.7559, Loss: 0.5135030746459961\nEpoch: 182, Train: 0.7499, Val: 0.7533, Test: 0.7544, Loss: 0.5254723429679871\nEpoch: 183, Train: 0.7564, Val: 0.7625, Test: 0.7638, Loss: 0.5017015337944031\nEpoch: 184, Train: 0.7559, Val: 0.7550, Test: 0.7587, Loss: 0.5086198449134827\nEpoch: 185, Train: 0.7640, Val: 0.7551, Test: 0.7635, Loss: 0.5079658627510071\nEpoch: 186, Train: 0.7547, Val: 0.7546, Test: 0.7589, Loss: 0.5196709632873535\nEpoch: 187, Train: 0.7573, Val: 0.7547, Test: 0.7511, Loss: 0.5095032453536987\nEpoch: 188, Train: 0.7583, Val: 0.7568, Test: 0.7608, Loss: 0.5064508318901062\nEpoch: 189, Train: 0.7639, Val: 0.7599, Test: 0.7582, Loss: 0.506013810634613\nEpoch: 190, Train: 0.7581, Val: 0.7564, Test: 0.7571, Loss: 0.5119727849960327\nEpoch: 191, Train: 0.7545, Val: 0.7540, Test: 0.7552, Loss: 0.4914553463459015\nEpoch: 192, Train: 0.7569, Val: 0.7505, Test: 0.7552, Loss: 0.5008942484855652\nEpoch: 193, Train: 0.7584, Val: 0.7565, Test: 0.7597, Loss: 0.4939987063407898\nEpoch: 194, Train: 0.7549, Val: 0.7504, Test: 0.7539, Loss: 0.49491646885871887\nEpoch: 195, Train: 0.7568, Val: 0.7509, Test: 0.7587, Loss: 0.4982417821884155\nEpoch: 196, Train: 0.7530, Val: 0.7523, Test: 0.7503, Loss: 0.506991446018219\nEpoch: 197, Train: 0.7558, Val: 0.7564, Test: 0.7518, Loss: 0.5017726421356201\nEpoch: 198, Train: 0.7604, Val: 0.7544, Test: 0.7535, Loss: 0.498566210269928\nEpoch: 199, Train: 0.7577, Val: 0.7596, Test: 0.7664, Loss: 0.4957054555416107\nSaving Link Classification Model Predictions\n\nBest Model Accuraies Train: 0.7554, Val: 0.7567, Test: 0.7609\n" ] ], [ [ "## Question 4: What is the maximum ROC-AUC score you get for your best_model on test set? (13 points)\n\n\nAfter training your model, download and submit your best model prediction file: *CORA-Link-Prediction.csv*. \n\nAs we have seen before you can view this file by clicking on the *Folder* icon on the left side pannel. ", "_____no_output_____" ], [ "# Submission\n\nYou will need to submit four files on Gradescope to complete this notebook. \n\n1. Your completed *XCS224W_Colab3.ipynb*. From the \"File\" menu select \"Download .ipynb\" to save a local copy of your completed Colab. \n2. *CORA-Node-GraphSage.csv* \n3. *CORA-Node-GAT.csv*\n4. *CORA-Link-Prediction.csv*\n\nDownload the csv files by selecting the *Folder* icon on the left panel. \n\nTo submit your work, zip the files downloaded in steps 1-4 above and submit to gradescope. **NOTE:** DO NOT rename any of the downloaded files. ", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4af3f8eff7f0a673724c421ddeaba62c549fec9d
165,493
ipynb
Jupyter Notebook
Threat_Model_with_Pandas.ipynb
yurichernyshov/Examples
c5accf6bcf0be370ecfa361ec4b7f70e03650009
[ "MIT" ]
1
2021-07-15T11:35:15.000Z
2021-07-15T11:35:15.000Z
Threat_Model_with_Pandas.ipynb
yurichernyshov/Examples
c5accf6bcf0be370ecfa361ec4b7f70e03650009
[ "MIT" ]
null
null
null
Threat_Model_with_Pandas.ipynb
yurichernyshov/Examples
c5accf6bcf0be370ecfa361ec4b7f70e03650009
[ "MIT" ]
1
2021-08-24T07:49:57.000Z
2021-08-24T07:49:57.000Z
48.122419
20,400
0.5294
[ [ [ "!python3 -m pip freeze | grep xlrd", "xlrd==1.2.0\r\n" ], [ "!python3 -m pip freeze | grep openpy", "openpyxl==3.0.5\r\n" ] ], [ [ "# Использование библиотеки pandas для анализа описаний уязвимостей из банка данных ФСТЭК", "_____no_output_____" ], [ "В статье демонстрируются возможности использования библиотеки pandas для работы с информацией из банка данных ФСТЭК (bdu.fstec.ru) об угрозах (thrlist.xlsx) и уязвимостях (vullist.xlsx)\n\nДля работы можно использовать открытый ресурс google colab с уже предустановленным программным обеспечением.", "_____no_output_____" ], [ "pandas\nxlrd\nopenpyxls", "_____no_output_____" ], [ "## Загрузка файлов с сайта <a name='load'></a>", "_____no_output_____" ], [ "## Содержание <a name='toc'></a>\n<ul>\n <a href='#load'>Загрузка данных с сайта</a>\n</ul>\n<ul>\n <a href='#thrlist'>Анализ файла угроз thrlist.xlsx</a>\n</ul>\n<ul>\n <a href='#vullist'>Анализ файла уязвимостей vullist.xlsx</a>\n</ul>\n<ul>\n <a href='#refs'>Ссылки</a>\n</ul>", "_____no_output_____" ], [ "## Загрузка файлов с сайта <a name='load'></a>", "_____no_output_____" ], [ "На официальном сайте ФСТЭК опубликованы списки угроз (thrlist.xlsx) и уязвимостей (vullist.xlsx) в эксель файлах.\nЗагрузим их.", "_____no_output_____" ] ], [ [ "!wget https://bdu.fstec.ru/files/documents/thrlist.xlsx\n!wget https://bdu.fstec.ru/files/documents/vullist.xlsx", "--2021-02-22 09:53:29-- https://bdu.fstec.ru/files/documents/thrlist.xlsx\nResolving bdu.fstec.ru (bdu.fstec.ru)... 95.173.157.16\nConnecting to bdu.fstec.ru (bdu.fstec.ru)|95.173.157.16|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 94259 (92K) [application/vnd.openxmlformats-officedocument.spreadsheetml.sheet]\nSaving to: ‘thrlist.xlsx’\n\nthrlist.xlsx 100%[===================>] 92.05K --.-KB/s in 0.08s \n\n2021-02-22 09:53:29 (1.18 MB/s) - ‘thrlist.xlsx’ saved [94259/94259]\n\n--2021-02-22 09:53:29-- https://bdu.fstec.ru/files/documents/vullist.xlsx\nResolving bdu.fstec.ru (bdu.fstec.ru)... 95.173.157.16\nConnecting to bdu.fstec.ru (bdu.fstec.ru)|95.173.157.16|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 5806439 (5.5M) [application/vnd.openxmlformats-officedocument.spreadsheetml.sheet]\nSaving to: ‘vullist.xlsx’\n\nvullist.xlsx 100%[===================>] 5.54M 218KB/s in 48s \n\n2021-02-22 09:54:18 (118 KB/s) - ‘vullist.xlsx’ saved [5806439/5806439]\n\n" ] ], [ [ "Убедимся, что файлы появились в локальной директории. Для этого можно вызвать стаднатрную команду linux для просмотра содержимого директория ls, для этого перед командой в ячейке надо поставить \"!\".", "_____no_output_____" ] ], [ [ "!ls", " ARIMA.ipynb\t\t RNN.ipynb\r\n EDA.ipynb\t\t SQL_DB.ipynb\r\n'GridSearchCV example.ipynb' TensorFlow_basics.ipynb\r\n LICENSE\t\t Threat_Model_with_Pandas.ipynb\r\n NQueensTask.ipynb\t flask\r\n NetworkX.ipynb\t\t thrlist.xlsx\r\n README.md\t\t vullist.xlsx\r\n" ] ], [ [ "Загружаем библиотеку pandas для работы с таблицами.", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ] ], [ [ "Создаем DataFrame из xlsx файла (пропускаем одну строчку, чтобы корректно отображались заголовки)", "_____no_output_____" ] ], [ [ "df = pd.read_excel(\"./thrlist.xlsx\", skiprows=1, engine=\"openpyxl\")", "_____no_output_____" ] ], [ [ "Отобразим первые три строки датафрейма.", "_____no_output_____" ] ], [ [ "df.head(3)", "_____no_output_____" ] ], [ [ "Посмотрим размеры", "_____no_output_____" ] ], [ [ "df.shape", "_____no_output_____" ] ], [ [ "Посмотрим перечень названий столбцов", "_____no_output_____" ] ], [ [ "for i,col in enumerate(df.columns):\n print(i+1,\":\",col)", "1 : Идентификатор УБИ\n2 : Наименование УБИ\n3 : Описание\n4 : Источник угрозы (характеристика и потенциал нарушителя)\n5 : Объект воздействия\n6 : Нарушение конфиденциальности\n7 : Нарушение целостности\n8 : Нарушение доступности\n9 : Дата включения угрозы в БнД УБИ\n10 : Дата последнего изменения данных\n" ] ], [ [ "Итак, мы загрузили описания угроз и уязвимостей с официального сайта ФСТЭК в виде xlsx файлов и на основе их данных создали табличные структуры pandas.DataFrame. Далее будем анализировать содержимое этих таблиц методами библиотеки pandas.", "_____no_output_____" ], [ "<a href='#toc'>Назад к оглавлению</a>", "_____no_output_____" ], [ "## Анализ файла угроз thrlist.xlsx <a name='thrlist'></a>", "_____no_output_____" ], [ "Посмотрим информацию о столбцах таблицы", "_____no_output_____" ] ], [ [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 222 entries, 0 to 221\nData columns (total 10 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Идентификатор УБИ 222 non-null int64 \n 1 Наименование УБИ 222 non-null object \n 2 Описание 222 non-null object \n 3 Источник угрозы (характеристика и потенциал нарушителя) 220 non-null object \n 4 Объект воздействия 222 non-null object \n 5 Нарушение конфиденциальности 222 non-null int64 \n 6 Нарушение целостности 222 non-null int64 \n 7 Нарушение доступности 222 non-null int64 \n 8 Дата включения угрозы в БнД УБИ 222 non-null datetime64[ns]\n 9 Дата последнего изменения данных 222 non-null datetime64[ns]\ndtypes: datetime64[ns](2), int64(4), object(4)\nmemory usage: 17.5+ KB\n" ] ], [ [ "Из полученного описания видим, что в таблице 10 столбцов, четыре из них целочисленные, два имеют тип \"datetime\", остальные являются строками.\n\nТакже видим, что в столбце \"Источник угрозы\" есть два пустых значения (NaN).", "_____no_output_____" ], [ "Выведем только те строки, для который угроза связана с нарушением целостности", "_____no_output_____" ] ], [ [ "df[df['Нарушение целостности']==1]", "_____no_output_____" ] ], [ [ "Выведем только те строки, которые относятся к BIOS", "_____no_output_____" ] ], [ [ "df[df['Наименование УБИ'].apply(lambda x: x.find(\"BIOS\"))!=-1]", "_____no_output_____" ] ], [ [ "Выведем угрозы за 2019 год", "_____no_output_____" ] ], [ [ "df[(df['Дата включения угрозы в БнД УБИ']>'2019-01-01')&(df['Дата включения угрозы в БнД УБИ']<'2020-01-01')]", "_____no_output_____" ] ], [ [ "При попытке отфильтровать содержимое таблицы, оставив только те строки, которые содержать слово \"высоким\" в столбце \"Источник угрозы (характеристика и потенциал нарушителя)\", возникает ошибка.\n\nПричина в том, что в двух ячейках столбца \"Источник угрозы (характеристика и потенциал нарушителя)\" были два пустых значения (NaN - \"Not a number\", специальное обозначение для пустого значения).\n\nДалее по тексту мы это обнаружили и заменили пустые значения строкой \"не задано\".", "_____no_output_____" ] ], [ [ "df['Источник угрозы (характеристика и потенциал нарушителя)'].isna().sum()", "_____no_output_____" ], [ "df['Источник угрозы (характеристика и потенциал нарушителя)'].fillna(\"не задано\", inplace=True)", "_____no_output_____" ], [ "df['Источник угрозы (характеристика и потенциал нарушителя)'].isna().sum()", "_____no_output_____" ] ], [ [ "Теперь все работает, оставим только строчки с высоким потенциалом нарушителя.", "_____no_output_____" ] ], [ [ "df[df['Источник угрозы (характеристика и потенциал нарушителя)'].str.contains(\"высоким\")]", "_____no_output_____" ] ], [ [ "Двойное условие: 1) BIOS в \"Наименовании УБИ\" и 2) Нарушение конфиденциальности", "_____no_output_____" ] ], [ [ "df_result = df[(df['Наименование УБИ'].apply(lambda x: x.find(\"BIOS\"))!=-1)&(df['Нарушение конфиденциальности']==1)]", "_____no_output_____" ], [ "df_result", "_____no_output_____" ] ], [ [ "Запись результата в файл xls.", "_____no_output_____" ] ], [ [ "df_result.to_excel(\"name.xls\")", "_____no_output_____" ], [ "!ls", " ARIMA.ipynb\t\t SQL_DB.ipynb\r\n EDA.ipynb\t\t TensorFlow_basics.ipynb\r\n'GridSearchCV example.ipynb' Threat_Model_with_Pandas.ipynb\r\n LICENSE\t\t flask\r\n NQueensTask.ipynb\t name.xls\r\n NetworkX.ipynb\t\t thrlist.xlsx\r\n README.md\t\t vullist.xlsx\r\n RNN.ipynb\r\n" ] ], [ [ "Сохранить файл из виртуального диска Google Colab на локальный диск.", "_____no_output_____" ] ], [ [ "from google.colab import files", "_____no_output_____" ], [ "files.download(\"name.xls\")", "_____no_output_____" ], [ "!ls", "name.xls sample_data thrlist.xlsx vullist.xlsx\n" ] ], [ [ "<a href=\"#toc\">Назад к оглавлению</a>", "_____no_output_____" ], [ "## Анализ файла с описанием уязвимостей vullist.xlsx <a name><>", "_____no_output_____" ] ], [ [ "df2 = pd.read_excel(\"vullist.xlsx\", skiprows=2)", "_____no_output_____" ], [ "df2", "_____no_output_____" ], [ "df2.shape", "_____no_output_____" ], [ "df2.columns", "_____no_output_____" ], [ "df2[df2['Вендор ПО'].apply(lambda x:x.find(\"D-Link\"))!=-1]", "_____no_output_____" ], [ "df2['Вендор ПО'].unique().shape", "_____no_output_____" ], [ "df2['Вендор ПО'].value_counts()[:10].plot(kind='bar')", "_____no_output_____" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "plt.bar(x=range(10),height=df2['Вендор ПО'].value_counts()[:10])\nplt.show()", "_____no_output_____" ], [ "df2[df2['Наименование уязвимости'].apply(lambda x:x.find(\"облач\"))!=-1].shape", "_____no_output_____" ] ], [ [ "## Ссылки <a name='refs'></a>", "_____no_output_____" ], [ "- https://bdu.fstec.ru\n- https://pandas.pydata.org\n- https://github.com/yurichernyshov/Data-Science-Course-USURT/blob/master/lessons/100%20questions%20Pandas.ipynb", "_____no_output_____" ], [ "<a href='#toc'>Назад к оглавлению</a>", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "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", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
4af3fdaacfc002f1aa25c252ebdc5e122a2d22c9
36,824
ipynb
Jupyter Notebook
notebooks/00_quick_start/lightgbm_tinycriteo.ipynb
wutaomsft/recommenders
89e922b2c8c90d25cc247bbc70ae44a7119b9afe
[ "MIT" ]
2
2019-12-05T01:39:15.000Z
2020-04-03T03:25:57.000Z
notebooks/00_quick_start/lightgbm_tinycriteo.ipynb
moradbeikie/recommenders
89e922b2c8c90d25cc247bbc70ae44a7119b9afe
[ "MIT" ]
null
null
null
notebooks/00_quick_start/lightgbm_tinycriteo.ipynb
moradbeikie/recommenders
89e922b2c8c90d25cc247bbc70ae44a7119b9afe
[ "MIT" ]
1
2019-11-21T07:57:45.000Z
2019-11-21T07:57:45.000Z
36.031311
743
0.478682
[ [ [ "<i>Copyright (c) Microsoft Corporation. All rights reserved.</i>\n\n<i>Licensed under the MIT License.</i>", "_____no_output_____" ], [ "# LightGBM: A Highly Efficient Gradient Boosting Decision Tree\nThis notebook will give you an example of how to train a LightGBM model to estimate click-through rates on an e-commerce advertisement. We will train a LightGBM based model on the Criteo dataset.\n\n[LightGBM](https://github.com/Microsoft/LightGBM) is a gradient boosting framework that uses tree-based learning algorithms. It is designed to be distributed and efficient with the following advantages:\n* Fast training speed and high efficiency.\n* Low memory usage.\n* Great accuracy.\n* Support of parallel and GPU learning.\n* Capable of handling large-scale data.", "_____no_output_____" ], [ "## Global Settings and Imports", "_____no_output_____" ] ], [ [ "import sys, os\nsys.path.append(\"../../\")\nimport numpy as np\nimport lightgbm as lgb\nimport papermill as pm\nimport pandas as pd\nimport category_encoders as ce\nfrom tempfile import TemporaryDirectory\nfrom sklearn.metrics import roc_auc_score, log_loss\n\nimport reco_utils.recommender.lightgbm.lightgbm_utils as lgb_utils\nimport reco_utils.dataset.criteo as criteo\n\nprint(\"System version: {}\".format(sys.version))\nprint(\"LightGBM version: {}\".format(lgb.__version__))", "System version: 3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 19:16:44) \n[GCC 7.3.0]\nLightGBM version: 2.2.1\n" ] ], [ [ "### Parameter Setting\nLet's set the main related parameters for LightGBM now. Basically, the task is a binary classification (predicting click or no click), so the objective function is set to binary logloss, and 'AUC' metric, is used as a metric which is less effected by imbalance in the classes of the dataset.\n\nGenerally, we can adjust the number of leaves (MAX_LEAF), the minimum number of data in each leaf (MIN_DATA), maximum number of trees (NUM_OF_TREES), the learning rate of trees (TREE_LEARNING_RATE) and EARLY_STOPPING_ROUNDS (to avoid overfitting) in the model to get better performance.\n\nBesides, we can also adjust some other listed parameters to optimize the results. [In this link](https://github.com/Microsoft/LightGBM/blob/master/docs/Parameters.rst), a list of all the parameters is shown. Also, some advice on how to tune these parameters can be found [in this url](https://github.com/Microsoft/LightGBM/blob/master/docs/Parameters-Tuning.rst). ", "_____no_output_____" ] ], [ [ "MAX_LEAF = 64\nMIN_DATA = 20\nNUM_OF_TREES = 100\nTREE_LEARNING_RATE = 0.15\nEARLY_STOPPING_ROUNDS = 20\nMETRIC = \"auc\"\nSIZE = \"sample\"", "_____no_output_____" ], [ "params = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'num_class': 1,\n 'objective': \"binary\",\n 'metric': METRIC,\n 'num_leaves': MAX_LEAF,\n 'min_data': MIN_DATA,\n 'boost_from_average': True,\n #set it according to your cpu cores.\n 'num_threads': 20,\n 'feature_fraction': 0.8,\n 'learning_rate': TREE_LEARNING_RATE,\n}", "_____no_output_____" ] ], [ [ "## Data Preparation\nHere we use CSV format as the example data input. Our example data is a sample (about 100 thousand samples) from [Criteo dataset](https://www.kaggle.com/c/criteo-display-ad-challenge). The Criteo dataset is a well-known industry benchmarking dataset for developing CTR prediction models, and it's frequently adopted as evaluation dataset by research papers. The original dataset is too large for a lightweight demo, so we sample a small portion from it as a demo dataset.\n\nSpecifically, there are 39 columns of features in Criteo, where 13 columns are numerical features (I1-I13) and the other 26 columns are categorical features (C1-C26).", "_____no_output_____" ] ], [ [ "nume_cols = [\"I\" + str(i) for i in range(1, 14)]\ncate_cols = [\"C\" + str(i) for i in range(1, 27)]\nlabel_col = \"Label\"\n\nheader = [label_col] + nume_cols + cate_cols\nwith TemporaryDirectory() as tmp:\n all_data = criteo.load_pandas_df(size=SIZE, local_cache_path=tmp, header=header)\ndisplay(all_data.head())", "8.79MB [00:00, 12.1MB/s] \n" ] ], [ [ "First, we cut three sets (train_data (first 80%), valid_data (middle 10%) and test_data (last 10%)), cut from the original all data. <br>\nNotably, considering the Criteo is a kind of time-series streaming data, which is also very common in recommendation scenario, we split the data by its order.", "_____no_output_____" ] ], [ [ "# split data to 3 sets \nlength = len(all_data)\ntrain_data = all_data.loc[:0.8*length-1]\nvalid_data = all_data.loc[0.8*length:0.9*length-1]\ntest_data = all_data.loc[0.9*length:]", "_____no_output_____" ] ], [ [ "## Basic Usage\n### Ordinal Encoding\nConsidering LightGBM could handle the low-frequency features and missing value by itself, for basic usage, we only encode the string-like categorical features by an ordinal encoder.", "_____no_output_____" ] ], [ [ "ord_encoder = ce.ordinal.OrdinalEncoder(cols=cate_cols)\n\ndef encode_csv(df, encoder, label_col, typ='fit'):\n if typ == 'fit':\n df = encoder.fit_transform(df)\n else:\n df = encoder.transform(df)\n y = df[label_col].values\n del df[label_col]\n return df, y\n\ntrain_x, train_y = encode_csv(train_data, ord_encoder, label_col)\nvalid_x, valid_y = encode_csv(valid_data, ord_encoder, label_col, 'transform')\ntest_x, test_y = encode_csv(test_data, ord_encoder, label_col, 'transform')\n\nprint('Train Data Shape: X: {trn_x_shape}; Y: {trn_y_shape}.\\nValid Data Shape: X: {vld_x_shape}; Y: {vld_y_shape}.\\nTest Data Shape: X: {tst_x_shape}; Y: {tst_y_shape}.\\n'\n .format(trn_x_shape=train_x.shape,\n trn_y_shape=train_y.shape,\n vld_x_shape=valid_x.shape,\n vld_y_shape=valid_y.shape,\n tst_x_shape=test_x.shape,\n tst_y_shape=test_y.shape,))\ntrain_x.head()", "Train Data Shape: X: (80000, 39); Y: (80000,).\nValid Data Shape: X: (10000, 39); Y: (10000,).\nTest Data Shape: X: (10000, 39); Y: (10000,).\n\n" ] ], [ [ "### Create model\nWhen both hyper-parameters and data are ready, we can create a model:", "_____no_output_____" ] ], [ [ "lgb_train = lgb.Dataset(train_x, train_y.reshape(-1), params=params, categorical_feature=cate_cols)\nlgb_valid = lgb.Dataset(valid_x, valid_y.reshape(-1), reference=lgb_train, categorical_feature=cate_cols)\nlgb_test = lgb.Dataset(test_x, test_y.reshape(-1), reference=lgb_train, categorical_feature=cate_cols)\nlgb_model = lgb.train(params,\n lgb_train,\n num_boost_round=NUM_OF_TREES,\n early_stopping_rounds=EARLY_STOPPING_ROUNDS,\n valid_sets=lgb_valid,\n categorical_feature=cate_cols)", "[1]\tvalid_0's auc: 0.728695\nTraining until validation scores don't improve for 20 rounds.\n[2]\tvalid_0's auc: 0.742373\n[3]\tvalid_0's auc: 0.747298\n[4]\tvalid_0's auc: 0.747969\n[5]\tvalid_0's auc: 0.751102\n[6]\tvalid_0's auc: 0.753734\n[7]\tvalid_0's auc: 0.755335\n[8]\tvalid_0's auc: 0.75658\n[9]\tvalid_0's auc: 0.757071\n[10]\tvalid_0's auc: 0.758572\n[11]\tvalid_0's auc: 0.759742\n[12]\tvalid_0's auc: 0.760415\n[13]\tvalid_0's auc: 0.760602\n[14]\tvalid_0's auc: 0.761192\n[15]\tvalid_0's auc: 0.7616\n[16]\tvalid_0's auc: 0.761697\n[17]\tvalid_0's auc: 0.762255\n[18]\tvalid_0's auc: 0.76253\n[19]\tvalid_0's auc: 0.763092\n[20]\tvalid_0's auc: 0.762172\n[21]\tvalid_0's auc: 0.762066\n[22]\tvalid_0's auc: 0.761866\n[23]\tvalid_0's auc: 0.761433\n[24]\tvalid_0's auc: 0.761588\n[25]\tvalid_0's auc: 0.761017\n[26]\tvalid_0's auc: 0.761086\n[27]\tvalid_0's auc: 0.761177\n[28]\tvalid_0's auc: 0.760893\n[29]\tvalid_0's auc: 0.760635\n[30]\tvalid_0's auc: 0.760104\n[31]\tvalid_0's auc: 0.759298\n[32]\tvalid_0's auc: 0.759176\n[33]\tvalid_0's auc: 0.758384\n[34]\tvalid_0's auc: 0.758168\n[35]\tvalid_0's auc: 0.757902\n[36]\tvalid_0's auc: 0.758005\n[37]\tvalid_0's auc: 0.757782\n[38]\tvalid_0's auc: 0.757542\n[39]\tvalid_0's auc: 0.756966\nEarly stopping, best iteration is:\n[19]\tvalid_0's auc: 0.763092\n" ] ], [ [ "Now let's see what is the model's performance:", "_____no_output_____" ] ], [ [ "test_preds = lgb_model.predict(test_x)\nauc = roc_auc_score(np.asarray(test_y.reshape(-1)), np.asarray(test_preds))\nlogloss = log_loss(np.asarray(test_y.reshape(-1)), np.asarray(test_preds), eps=1e-12)\nres_basic = {\"auc\": auc, \"logloss\": logloss}\nprint(res_basic)\npm.record(\"res_basic\", res_basic)", "{'auc': 0.7674356153037237, 'logloss': 0.466876775528735}\n" ] ], [ [ "<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=default\"></script>\n## Optimized Usage\n### Label-encoding and Binary-encoding\nNext, since LightGBM has a better capability in handling dense numerical features effectively, we try to convert all the categorical features in original data into numerical ones, by label-encoding [3] and binary-encoding [4]. Also due to the sequence property of Criteo, the label-encoding we adopted is executed one-by-one, which means we encode the samples in order, by the information of the previous samples before each sample (sequential label-encoding and sequential count-encoding). Besides, we also filter the low-frequency categorical features and fill the missing values by the mean of corresponding columns for the numerical features. (consulting `lgb_utils.NumEncoder`)\n\nSpecifically, in `lgb_utils.NumEncoder`, the main steps are as follows.\n* Firstly, we convert the low-frequency categorical features to `\"LESS\"` and the missing categorical features to `\"UNK\"`. \n* Secondly, we convert the missing numerical features into the mean of corresponding columns. \n* Thirdly, the string-like categorical features are ordinal encoded like the example shown in basic usage. \n* And then, we target encode the categorical features in the samples order one-by-one. For each sample, we add the label and count information of its former samples into the data and produce new features. Formally, for $i=1,2,...,n$, we add $\\frac{\\sum\\nolimits_{j=1}^{i-1} I(x_j=c) \\cdot y}{\\sum\\nolimits_{j=1}^{i-1} I(x_j=c)}$ as a new label feature for current sample $x_i$, where $c$ is a category to encode in current sample, so $(i-1)$ is the number of former samples, and $I(\\cdot)$ is the indicator function that check the former samples contain $c$ (whether $x_j=c$) or not. At the meantime, we also add the count frequency of $c$, which is $\\frac{\\sum\\nolimits_{j=1}^{i-1} I(x_j=c)}{i-1}$, as a new count feature. \n* Finally, based on the results of ordinal encoding, we add the binary encoding results as new columns into the data.\n\nNote that the statistics used in the above process only updates when fitting the training set, while maintaining static when transforming the testing set because the label of test data should be considered as unknown.", "_____no_output_____" ] ], [ [ "label_col = 'Label'\nnum_encoder = lgb_utils.NumEncoder(cate_cols, nume_cols, label_col)\ntrain_x, train_y = num_encoder.fit_transform(train_data)\nvalid_x, valid_y = num_encoder.transform(valid_data)\ntest_x, test_y = num_encoder.transform(test_data)\ndel num_encoder\nprint('Train Data Shape: X: {trn_x_shape}; Y: {trn_y_shape}.\\nValid Data Shape: X: {vld_x_shape}; Y: {vld_y_shape}.\\nTest Data Shape: X: {tst_x_shape}; Y: {tst_y_shape}.\\n'\n .format(trn_x_shape=train_x.shape,\n trn_y_shape=train_y.shape,\n vld_x_shape=valid_x.shape,\n vld_y_shape=valid_y.shape,\n tst_x_shape=test_x.shape,\n tst_y_shape=test_y.shape,))\n", "2019-04-29 11:26:21,158 [INFO] Filtering and fillna features\n100%|██████████| 26/26 [00:02<00:00, 12.36it/s]\n100%|██████████| 13/13 [00:00<00:00, 711.59it/s]\n2019-04-29 11:26:23,286 [INFO] Ordinal encoding cate features\n2019-04-29 11:26:24,680 [INFO] Target encoding cate features\n100%|██████████| 26/26 [00:03<00:00, 6.72it/s]\n2019-04-29 11:26:28,554 [INFO] Start manual binary encoding\n100%|██████████| 65/65 [00:04<00:00, 15.87it/s]\n100%|██████████| 26/26 [00:02<00:00, 8.17it/s]\n2019-04-29 11:26:35,518 [INFO] Filtering and fillna features\n100%|██████████| 26/26 [00:00<00:00, 171.81it/s]\n100%|██████████| 13/13 [00:00<00:00, 2174.25it/s]\n2019-04-29 11:26:35,690 [INFO] Ordinal encoding cate features\n2019-04-29 11:26:35,854 [INFO] Target encoding cate features\n100%|██████████| 26/26 [00:00<00:00, 53.42it/s]\n2019-04-29 11:26:36,344 [INFO] Start manual binary encoding\n100%|██████████| 65/65 [00:03<00:00, 20.02it/s]\n100%|██████████| 26/26 [00:01<00:00, 17.67it/s]\n2019-04-29 11:26:41,081 [INFO] Filtering and fillna features\n100%|██████████| 26/26 [00:00<00:00, 158.08it/s]\n100%|██████████| 13/13 [00:00<00:00, 2203.78it/s]\n2019-04-29 11:26:41,267 [INFO] Ordinal encoding cate features\n2019-04-29 11:26:41,429 [INFO] Target encoding cate features\n100%|██████████| 26/26 [00:00<00:00, 53.08it/s]\n2019-04-29 11:26:41,922 [INFO] Start manual binary encoding\n100%|██████████| 65/65 [00:03<00:00, 20.10it/s]\n100%|██████████| 26/26 [00:01<00:00, 18.37it/s]" ] ], [ [ "### Training and Evaluation", "_____no_output_____" ] ], [ [ "lgb_train = lgb.Dataset(train_x, train_y.reshape(-1), params=params)\nlgb_valid = lgb.Dataset(valid_x, valid_y.reshape(-1), reference=lgb_train)\nlgb_model = lgb.train(params,\n lgb_train,\n num_boost_round=NUM_OF_TREES,\n early_stopping_rounds=EARLY_STOPPING_ROUNDS,\n valid_sets=lgb_valid)", "[1]\tvalid_0's auc: 0.731759\nTraining until validation scores don't improve for 20 rounds.\n[2]\tvalid_0's auc: 0.747705\n[3]\tvalid_0's auc: 0.751667\n[4]\tvalid_0's auc: 0.75589\n[5]\tvalid_0's auc: 0.758054\n[6]\tvalid_0's auc: 0.758094\n[7]\tvalid_0's auc: 0.759904\n[8]\tvalid_0's auc: 0.761098\n[9]\tvalid_0's auc: 0.761744\n[10]\tvalid_0's auc: 0.762308\n[11]\tvalid_0's auc: 0.762473\n[12]\tvalid_0's auc: 0.763606\n[13]\tvalid_0's auc: 0.764222\n[14]\tvalid_0's auc: 0.765004\n[15]\tvalid_0's auc: 0.765933\n[16]\tvalid_0's auc: 0.766507\n[17]\tvalid_0's auc: 0.767192\n[18]\tvalid_0's auc: 0.767284\n[19]\tvalid_0's auc: 0.767859\n[20]\tvalid_0's auc: 0.768619\n[21]\tvalid_0's auc: 0.769045\n[22]\tvalid_0's auc: 0.768987\n[23]\tvalid_0's auc: 0.769601\n[24]\tvalid_0's auc: 0.77011\n[25]\tvalid_0's auc: 0.770183\n[26]\tvalid_0's auc: 0.770539\n[27]\tvalid_0's auc: 0.77096\n[28]\tvalid_0's auc: 0.771164\n[29]\tvalid_0's auc: 0.771296\n[30]\tvalid_0's auc: 0.771402\n[31]\tvalid_0's auc: 0.771596\n[32]\tvalid_0's auc: 0.771476\n[33]\tvalid_0's auc: 0.771697\n[34]\tvalid_0's auc: 0.77169\n[35]\tvalid_0's auc: 0.771836\n[36]\tvalid_0's auc: 0.771832\n[37]\tvalid_0's auc: 0.771948\n[38]\tvalid_0's auc: 0.772098\n[39]\tvalid_0's auc: 0.772136\n[40]\tvalid_0's auc: 0.771748\n[41]\tvalid_0's auc: 0.771748\n[42]\tvalid_0's auc: 0.771724\n[43]\tvalid_0's auc: 0.771676\n[44]\tvalid_0's auc: 0.77169\n[45]\tvalid_0's auc: 0.771916\n[46]\tvalid_0's auc: 0.771864\n[47]\tvalid_0's auc: 0.771851\n[48]\tvalid_0's auc: 0.771891\n[49]\tvalid_0's auc: 0.771629\n[50]\tvalid_0's auc: 0.771984\n[51]\tvalid_0's auc: 0.772085\n[52]\tvalid_0's auc: 0.771988\n[53]\tvalid_0's auc: 0.771778\n[54]\tvalid_0's auc: 0.771485\n[55]\tvalid_0's auc: 0.7715\n[56]\tvalid_0's auc: 0.770778\n[57]\tvalid_0's auc: 0.770816\n[58]\tvalid_0's auc: 0.770408\n[59]\tvalid_0's auc: 0.770489\nEarly stopping, best iteration is:\n[39]\tvalid_0's auc: 0.772136\n" ], [ "test_preds = lgb_model.predict(test_x)\nauc = roc_auc_score(np.asarray(test_y.reshape(-1)), np.asarray(test_preds))\nlogloss = log_loss(np.asarray(test_y.reshape(-1)), np.asarray(test_preds), eps=1e-12)\nres_optim = {\"auc\": auc, \"logloss\": logloss}\nprint(res_optim)\npm.record(\"res_optim\", res_optim)", "{'auc': 0.7757371640011422, 'logloss': 0.4606505068849181}\n" ] ], [ [ "## Model saving and loading\nNow we finish the basic training and testing for LightGBM, next let's try to save and reload the model, and then evaluate it again.", "_____no_output_____" ] ], [ [ "with TemporaryDirectory() as tmp:\n save_file = os.path.join(tmp, r'finished.model')\n lgb_model.save_model(save_file)\n loaded_model = lgb.Booster(model_file=save_file)\n\n# eval the performance again\ntest_preds = loaded_model.predict(test_x)\n\nauc = roc_auc_score(np.asarray(test_y.reshape(-1)), np.asarray(test_preds))\nlogloss = log_loss(np.asarray(test_y.reshape(-1)), np.asarray(test_preds), eps=1e-12)\nprint({\"auc\": auc, \"logloss\": logloss})", "{'auc': 0.7757371640011422, 'logloss': 0.4606505068849181}\n" ] ], [ [ "## Additional Reading\n\n\\[1\\] Guolin Ke, Qi Meng, Thomas Finley, Taifeng Wang, Wei Chen, Weidong Ma, Qiwei Ye, and Tie-Yan Liu. 2017. LightGBM: A highly efficient gradient boosting decision tree. In Advances in Neural Information Processing Systems. 3146–3154.<br>\n\\[2\\] The parameters of LightGBM: https://github.com/Microsoft/LightGBM/blob/master/docs/Parameters.rst <br>\n\\[3\\] Anna Veronika Dorogush, Vasily Ershov, and Andrey Gulin. 2018. CatBoost: gradient boosting with categorical features support. arXiv preprint arXiv:1810.11363 (2018).<br>\n\\[4\\] Scikit-learn. 2018. categorical_encoding. https://github.com/scikit-learn-contrib/categorical-encoding<br>\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4af40f6d1c42e5ec990f3d8a47792886bcd89de2
7,434
ipynb
Jupyter Notebook
snippets/EM/zwatershed/zwatershed.ipynb
michielkleinnijenhuis/EM
f46a9b11298919b359e80d9f23a7e824df1356cb
[ "Apache-2.0" ]
null
null
null
snippets/EM/zwatershed/zwatershed.ipynb
michielkleinnijenhuis/EM
f46a9b11298919b359e80d9f23a7e824df1356cb
[ "Apache-2.0" ]
null
null
null
snippets/EM/zwatershed/zwatershed.ipynb
michielkleinnijenhuis/EM
f46a9b11298919b359e80d9f23a7e824df1356cb
[ "Apache-2.0" ]
null
null
null
27.533333
110
0.531612
[ [ [ "import os\n\ndatadir = \"/Users/michielk/oxdata/P01/EM/Myrf_01/SET-B/B-NT-S10-2f_ROI_00/zws\"\n# pred_file = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs1_eed2_main.h5') # dataset: 'main'\npred_file = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs_main_vol00.h5') # dataset: 'main'\naff_file = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs_main_vol00_grad.h5') # dataset: 'main'\nout_folder = os.path.join(datadir, 'zws_vol00_')\noutname = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs_zws.h5') # dataset: 'main'\nmax_len = 300\n", "_____no_output_____" ], [ "# in conda root env\nimport h5py\nimport numpy as np\nfrom wmem import utils\n\nh5path_in = os.path.join(pred_file, 'main')\nh5file_in, ds_in, elsize, axlab = utils.h5_load(h5path_in)\ngrad = np.array(np.absolute(np.gradient(ds_in[0,:,:,:], 1)))\n\nh5file_in.close()\n\nh5path_out = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs_main_vol00_absgrad.h5', 'main')\nh5file_out, ds_out = utils.h5_write(None, grad.shape, grad.dtype,\n h5path_out,\n element_size_um=elsize,\n axislabels=axlab)\nds_out[:] = grad\nh5file_out.close()\n", "_____no_output_____" ], [ "from zwatershed import (partition_subvols,\n eval_with_par_map,\n eval_with_spark,\n stitch_and_save,\n merge_by_thresh)\n", "_____no_output_____" ], [ "partition_data = partition_subvols(aff_file, out_folder, max_len)\n", "_____no_output_____" ], [ "eval_with_spark(partition_data[0])\n# NUM_WORKERS=4\n# eval_with_par_map(partition_data[0], NUM_WORKERS)\n", "_____no_output_____" ], [ "stitch_and_save(partition_data, outname)\n", "_____no_output_____" ], [ "%matplotlib nbagg\n\nimport numpy as np\nimport sys\nimport time\nimport os\nimport h5py\nimport os.path as op\nimport matplotlib\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Pool\nfrom itertools import product\nfrom zwatershed import (partition_subvols,\n eval_with_par_map,\n stitch_and_save,\n merge_by_thresh)\n# from par_funcs import *\n# sys.path.append('..')\ncmap = matplotlib.colors.ListedColormap(np.vstack( ((0, 0, 0), np.random.rand(1e6, 3))) )\nV = 20\n\ndatadir = \"/Users/michielk/oxdata/P01/EM/Myrf_01/SET-B/B-NT-S10-2f_ROI_00/zws\"\n# zwsbase = os.path.join(datadir, \"zws\")\noutname = os.path.join(datadir, 'B-NT-S10-2f_ROI_00ds7_probs_zws.h5') # dataset: 'main'\n", "_____no_output_____" ], [ "orig_file = h5py.File(aff_file,'r')\nstart = np.array([0, 0, 0])\nstop = np.array([191, 301, 244])\nfig, axs = plt.subplots(1, 3)\nfor i in range(0, 3):\n orig = orig_file['main'][i, start[0]:stop[0], start[1]:stop[1], start[2]:stop[2]]\n ax = axs[i]\n cax = ax.imshow(orig[V,:,:], cmap=plt.get_cmap('Greys'))\n cbar = fig.colorbar(cax, ax=ax, orientation='horizontal')\n ax.set_title('orig{}'.format(i))\norig_file.close()\nplt.show()\n", "_____no_output_____" ], [ "num, thresh = 0, 1000.0\nfig, axs = plt.subplots(1, 2)\n\nbasic_file = h5py.File(os.path.join(datadir, 'zws_vol01_0_0_0_vol', 'basic.h5'),'r')\nseg_init = np.array(basic_file['seg'])\nrg_init = np.array(basic_file['rg'])\nkeeps = rg_init[:,0]<rg_init[:,1]\nrg_init = rg_init[keeps,:]\nseg_sizes_init = np.array(basic_file['counts'])\nbasic_file.close()\nax = axs[0]\nax.imshow(seg_init[V,:,:], cmap=cmap)\nax.set_title('seg_init')\n\nf = h5py.File(outname, 'a')\ns,e = f['starts'][num],f['ends'][num]\nseg = f['seg'][s[0]:e[0]-3,s[1]:e[1]-3,s[2]:e[2]-3]\nseg_sizes = np.array(f['seg_sizes'])\nrg = np.array(f['rg_'+str(num)])\nf.close()\nax = axs[1]\nax.imshow(seg[V,:,:], cmap=cmap)\nax.set_title('seg_after_stitching')\n\nplt.show()\n\nprint \"num_segs\",len(np.unique(seg_init)),len(np.unique(seg))\nprint \"rg lens\",len(rg_init),len(rg)\n", "_____no_output_____" ], [ "num, thresh = 0, 0.5\nseg_init_merged = merge_by_thresh(seg_init, seg_sizes_init, rg_init, thresh)\nseg_merged = merge_by_thresh(seg, seg_sizes, rg, thresh)\n", "_____no_output_____" ], [ "fig, axs = plt.subplots(1, 2)\n\nax = axs[0]\nax.imshow(seg_init_merged[V,:,:], cmap=cmap)\nax.set_title('merged init')\n\nax = axs[1]\nax.imshow(seg_merged[V,:,:], cmap=cmap)\nax.set_title('merged')\n\nplt.show()\n\nprint \"num_segs\",len(np.unique(seg_init)),len(np.unique(seg))\nprint \"rg lens\",len(rg_init),len(rg)\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af41a351fa1fdd0e0ec723a787d8bfbe18961de
220,680
ipynb
Jupyter Notebook
sigMF GPU STFT SVD voice reconstruction ACE Xeon 1MSPS-save_array vodeson old.ipynb
rdbadger/RF_SVD
d9d2da1c6f6b08df8968944ff463d738420984d7
[ "MIT" ]
null
null
null
sigMF GPU STFT SVD voice reconstruction ACE Xeon 1MSPS-save_array vodeson old.ipynb
rdbadger/RF_SVD
d9d2da1c6f6b08df8968944ff463d738420984d7
[ "MIT" ]
null
null
null
sigMF GPU STFT SVD voice reconstruction ACE Xeon 1MSPS-save_array vodeson old.ipynb
rdbadger/RF_SVD
d9d2da1c6f6b08df8968944ff463d738420984d7
[ "MIT" ]
null
null
null
263.341289
197,628
0.92215
[ [ [ "## sigMF STFT on GPU and CPU", "_____no_output_____" ] ], [ [ "import os\nimport itertools\nfrom sklearn.utils import shuffle\nimport torch, torchvision\nimport torch.nn as nn\nimport torch.nn.functional as d\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.nn.modules as mod\nimport torch.utils.data\nimport torch.utils.data as data\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom torch.nn.utils.rnn import pad_packed_sequence\nfrom torch.autograd import Variable\nimport numpy as np\nimport sys\nimport importlib\nimport time\nimport matplotlib.pyplot as plt\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torchvision.utils import save_image\nimport librosa\nfrom scipy import signal\nfrom scipy import stats\nfrom scipy.special import comb\nimport matplotlib.pyplot as plt\nimport glob\nimport json\nimport pickle\nfrom random import randint, choice\nimport random\nfrom timeit import default_timer as timer\nfrom torchaudio.functional import istft\nfrom sklearn.decomposition import NMF\nplt.style.use('default')\ndevice = torch.device('cuda:0')\nprint('Torch version =', torch.__version__, 'CUDA version =', torch.version.cuda)\nprint('CUDA Device:', device)\nprint('Is cuda available? =',torch.cuda.is_available())", "Torch version = 1.6.0 CUDA version = 10.2\nCUDA Device: cuda:0\nIs cuda available? = True\n" ], [ "# %matplotlib notebook\n# %matplotlib inline", "_____no_output_____" ] ], [ [ "#### Machine paths", "_____no_output_____" ] ], [ [ "# path = \"/home/db/sigMF_ML/class3/data_voice/\" # G7\n# path_val = \"/home/db/sigMF_ML/class3/val_data2/\" # G7\n# path_save = \"/home/db/sigMF_ML/class3/\" # G7\n# path_doc = \"/home/db/sigMF_ML/class3/data_dump2/\" # G7\n# path_temp = \"/home/db/sigMF_ML/class3/temp2/\" # G7\n\n# path = \"/home/david/sigMF_ML/class2/data2/\" # GTX1080Ti\n\n# path_save = \"/home/david/sigMF_ML/class2/\" # GTX1080Ti\n# path_temp = \"/home/david/sigMF_ML/class2/temp2/\" # GTX1080Ti\n# path_val = \"/home/david/sigMF_ML/class2/val_data2/\" # GTX1080Ti\n# path_doc = \"/home/david/sigMF_ML/class2/data_dump2/\" # GTX1080Ti\n# path = \"/home/david/sigMF_ML/class2/data_voice/\" # GTX1080Ti\n\n# path = \"/home/david/sigMF_ML/class2/E503 project/\" # ace\n# path_val = \"/home/david/sigMF_ML/class2/val_data2/\" # ace\npath_save = \"/home/david/sigMF_ML/class2/UDV_matrix/\" # ace\n# path_doc = \"/home/david/sigMF_ML/class2/data_dump2/\" # ace\n# path_temp = \"/home/david/sigMF_ML/class2/temp2/\" # ace\npath = \"/home/david/sigMF_ML/class2/clean_speech/IQ_files/\" # ace\n\n# path = \"/home/david/sigMF_ML2/class3/data/\" # tensorbook\n# path_val = \"/home/david/sigMF_ML2/class3/val_data/\" # tensorbook\n# path_save = \"/home/david/sigMF_ML2/class3/\" # tensorbook\n# path_doc = \"/home/david/sigMF_ML2/class3/data_dump/\" # tensorbook\n# path_temp = \"/home/david/sigMF_ML2/class3/temp/\" # tensorbook\n# path = \"/home/david/sigMF_ML2/class3/data2/\" # tensorbook\n# path_val = \"/home/david/sigMF_ML2/class3/val_data/\" # tensorbook\n# path_save = \"/home/david/sigMF_ML2/class3/\" # tensorbook\n# path_doc = \"/home/david/sigMF_ML2/class3/data_dump/\" # tensorbook\n# path_temp = \"/home/david/sigMF_ML2/class3/temp/\" # tensorbook\n# path = \"/home/david/sigMF_ML2/class3/data_voice/\" # tensorbook\n\n#path = \"/content/\" # colab\nprint(path)", "/home/david/sigMF_ML/class2/clean_speech/IQ_files/\n" ] ], [ [ "#### reading sigmf meta data and encoder function", "_____no_output_____" ] ], [ [ "# START OF FUNCTIONS ****************************************************\ndef meta_encoder(meta_list, num_classes): \n a = np.asarray(meta_list, dtype=int)\n# print('a = ', a)\n return a \n\ndef read_meta(meta_files):\n meta_list = []\n for meta in meta_files:\n all_meta_data = json.load(open(meta))\n meta_list.append(all_meta_data['global'][\"core:class\"])\n meta_list = list(map(int, meta_list))\n return meta_list\n\ndef read_num_val(x):\n x = len(meta_list_val)\n return x", "_____no_output_____" ], [ "print(path)\nos.chdir(path)\ndata_files = sorted(glob.glob('*.sigmf-data'))\nmeta_files = sorted(glob.glob('*.sigmf-meta'))", "/home/david/sigMF_ML/class2/clean_speech/IQ_files/\n" ], [ "for meta in meta_files:\n all_meta_data = json.load(open(meta))\n print(\"file name = \", meta)", "file name = UHF_vodeson_snr_hi.sigmf-meta\n" ] ], [ [ "#### torch GPU Cuda stft", "_____no_output_____" ] ], [ [ "def gpu(db, n_fft):\n I = db[0::2]\n Q = db[1::2]\n start = timer()\n w = 512\n win = torch.hann_window(w, periodic=True, dtype=None, layout=torch.strided, requires_grad=False)\n I_stft = torch.stft(torch.tensor(I).cuda(), n_fft=n_fft, hop_length=n_fft//2, win_length=w, window=win, center=True, normalized=True, onesided=False)\n Q_stft = torch.stft(torch.tensor(Q).cuda(), n_fft=n_fft, hop_length=n_fft//2, win_length=w, window=win, center=True, normalized=True, onesided=False)\n X_stft = I_stft[...,0] + Q_stft[...,0] + I_stft[...,1] + -1*Q_stft[...,1]\n X_stft = torch.cat((X_stft[n_fft//2:],X_stft[:n_fft//2]))\n end = timer()\n print(end - start)\n torch.cuda.empty_cache()\n return X_stft, I_stft, Q_stft", "_____no_output_____" ] ], [ [ "#### scipy CPU stft function", "_____no_output_____" ] ], [ [ "# def cpu(db, n_fft):\n# t = len(db)\n# db2 = db[0::]\n# start = timer()\n# db = db.astype(np.float32).view(np.complex64)\n# Fs = 1e6\n# I_t, I_f, Z = signal.stft(db, fs=Fs, nperseg=n_fft, return_onesided=False)\n# Z = np.vstack([Z[n_fft//2:], Z[:n_fft//2]])\n# end = timer()\n# print(end - start)\n# return Z", "_____no_output_____" ] ], [ [ "### GPU Timing", "_____no_output_____" ] ], [ [ "n_fft = 1000\nfor file in data_files:\n db = np.fromfile(file, dtype=\"float32\")\n stft_gpu, I_stft, Q_stft = gpu(db, n_fft)", "0.03586900804657489\n" ], [ "I_stft.shape, Q_stft.shape, stft_gpu.shape", "_____no_output_____" ], [ "Q_stft[497:504, 1, 0],Q_stft[497:504, 1, 1]", "_____no_output_____" ], [ "I_stft[497:504, 1, 0],I_stft[497:504, 1, 1]", "_____no_output_____" ], [ "stft_gpu[497:504, 1]", "_____no_output_____" ], [ "stft_gpu.shape", "_____no_output_____" ], [ "plt.figure(figsize=(9, 6))\nfig3 = plt.figure()\nplt.imshow(20*np.log10(np.abs(stft_gpu.cpu()+1e-8)), aspect='auto', origin='lower')\ntitle = \"Vodeson Original spectrum\"\nplt.title(title)\nplt.xlabel('Time in bins')\nplt.ylabel('Frequency bins(1Khz resolution)')\nplt.minorticks_on()\n# plt.yticks(np.arange(0,60, 6))\nfig3.savefig('vod_full_spectrum.pdf', format=\"pdf\")\nplt.show()", "_____no_output_____" ] ], [ [ "### CPU Timing", "_____no_output_____" ] ], [ [ "# for file in data_files:\n# db = np.fromfile(file, dtype=\"float32\")\n# stft_cpu = cpu(db, 1000)", "_____no_output_____" ], [ "# stft_cpu.shape", "_____no_output_____" ], [ "np.abs(stft_gpu.detach().cpu().numpy()[497:504, 1])", "_____no_output_____" ], [ "# np.abs(stft_cpu[497:504, 1])", "_____no_output_____" ] ], [ [ "### CPU load stft to Cuda Time", "_____no_output_____" ] ], [ [ "# start = timer()\n# IQ_tensor = torch.tensor(np.abs(stft_cpu)).cuda()\n# end = timer()\n# print(end - start)\n# torch.cuda.empty_cache()", "_____no_output_____" ], [ "# plt.imshow(20*np.log10(np.abs(stft_cpu)+1e-8), aspect='auto', origin='lower')\n# plt.show()", "_____no_output_____" ] ], [ [ "#### GPU SVD", "_____no_output_____" ] ], [ [ "def udv_stft(I_stft,Q_stft):\n start = timer()\n U_I0, D_I0, V_I0 = torch.svd(I_stft[...,0]) \n U_I1, D_I1, V_I1 = torch.svd(I_stft[...,1]) \n U_Q0, D_Q0, V_Q0 = torch.svd(Q_stft[...,0]) \n U_Q1, D_Q1, V_Q1 = torch.svd(Q_stft[...,1]) \n end = timer()\n print('SVD time: ',end - start)\n return U_I0, D_I0, V_I0, U_I1, D_I1, V_I1, U_Q0, D_Q0, V_Q0, U_Q1, D_Q1, V_Q1", "_____no_output_____" ] ], [ [ "#### Inverse stft ", "_____no_output_____" ] ], [ [ "def ISTFT(db, n_fft):# We are matching scipy.signal behavior (setting noverlap=frame_length - hop) \n w = 512\n win = torch.hann_window(w, periodic=True, dtype=None, layout=torch.strided, requires_grad=False).cuda()\n start = timer()\n Z = istft(db, n_fft=n_fft, hop_length=n_fft//2, win_length=w, window=win, center=True, normalized=True, onesided=False)\n end = timer()\n print('ISTFT time = ',end - start)\n torch.cuda.empty_cache()\n return Z", "_____no_output_____" ] ], [ [ "#### Re-combine UDV to approximate original signal", "_____no_output_____" ] ], [ [ "def udv(u, d, v, k): # like ----> np.matrix(U[:, :k]) * np.diag(D[:k]) * V[:k, :]\n start = timer()\n UD = torch.mul(u[:, :k], d[:k])\n v = torch.transpose(v,1,0)\n UDV = torch.mm(UD, v[:k, :])\n end = timer()\n print('UDV time: ',end - start)\n return UDV", "_____no_output_____" ], [ "print(path_save)\nos.chdir(path_save)", "/home/david/sigMF_ML/class2/UDV_matrix/\n" ], [ "np.save('I_stft', I_stft.detach().cpu().numpy())\nnp.save('Q_stft', Q_stft.detach().cpu().numpy())", "_____no_output_____" ] ], [ [ "### Main function to run all sub function calls", "_____no_output_____" ] ], [ [ "def complete(I_stft,Q_stft, num, n_fft):\n U_I0, D_I0, V_I0, U_I1, D_I1, V_I1, U_Q0, D_Q0, V_Q0, U_Q1, D_Q1, V_Q1 = udv_stft(I_stft,Q_stft)\n torch.cuda.empty_cache()\n print('UDV I0 shapes = ',U_I0.shape, D_I0.shape, V_I0.shape)\n print('UDV I1 shapes = ',U_I1.shape, D_I1.shape, V_I1.shape)\n print('UDV Q0 shapes = ', U_Q0.shape, D_Q0.shape, V_Q0.shape)\n print('UDV Q1 shapes = ', U_Q1.shape, D_Q1.shape, V_Q1.shape)\n # ------------ I0 ------------------------------------------------------\n np.save('U_I0', U_I0[:, :num].detach().cpu().numpy())\n np.save('D_I0', D_I0[:num].detach().cpu().numpy())\n np.save('V_I0', V_I0[:num, :].detach().cpu().numpy())\n # ------------ I1 ------------------------------------------------------\n np.save('U_I1', U_I1[:, :num].detach().cpu().numpy())\n np.save('D_I1', D_I1[:num].detach().cpu().numpy())\n np.save('V_I1', V_I1[:num, :].detach().cpu().numpy())\n # ------------ Q0 ------------------------------------------------------\n np.save('U_Q0', U_Q0[:, :num].detach().cpu().numpy())\n np.save('D_Q0', D_Q0[:num].detach().cpu().numpy())\n np.save('V_Q0', V_Q0[:num, :].detach().cpu().numpy()) \n # ------------ Q1 ------------------------------------------------------\n np.save('U_Q1', U_Q1[:, :num].detach().cpu().numpy())\n np.save('D_Q1', D_Q1[:num].detach().cpu().numpy())\n np.save('V_Q1', V_Q1[:num, :].detach().cpu().numpy()) \n # -----------------------------------------------------------------------\n udv_I0 = udv(U_I0, D_I0, V_I0,num)\n udv_I1 = udv(U_I1, D_I1, V_I1,num)\n udv_Q0 = udv(U_Q0, D_Q0, V_Q0,num)\n udv_Q1 = udv(U_Q1, D_Q1, V_Q1,num)\n torch.cuda.empty_cache()\n print('udv I shapes = ',udv_I0.shape,udv_I1.shape)\n print('udv Q shapes = ',udv_Q0.shape,udv_Q1.shape)\n # -------------stack and transpose----------------------------------------\n UDV_I = torch.stack([udv_I0,udv_I1])\n UDV_I = torch.transpose(UDV_I,2,0)\n UDV_I = torch.transpose(UDV_I,1,0)\n UDV_Q = torch.stack([udv_Q0,udv_Q1])\n UDV_Q = torch.transpose(UDV_Q,2,0)\n UDV_Q = torch.transpose(UDV_Q,1,0)\n torch.cuda.empty_cache()\n #--------------------------------------------------------------------------\n I = ISTFT(UDV_I, n_fft)\n Q = ISTFT(UDV_Q, n_fft)\n torch.cuda.empty_cache()\n I = I.detach().cpu().numpy()\n Q = Q.detach().cpu().numpy()\n end = len(I)*2\n IQ_SVD = np.zeros(len(I)*2)\n IQ_SVD[0:end:2] = I\n IQ_SVD[1:end:2] = Q \n IQ_SVD = IQ_SVD.astype(np.float32).view(np.complex64)\n return IQ_SVD", "_____no_output_____" ] ], [ [ "### Perform SVD on IQ stft data", "_____no_output_____" ] ], [ [ "num = 2 # number to reconstruct SVD matrix from\nIQ_SVD = complete(I_stft,Q_stft, num, n_fft)", "SVD time: 2.4772577389958315\nUDV I0 shapes = torch.Size([1000, 1000]) torch.Size([1000]) torch.Size([10000, 1000])\nUDV I1 shapes = torch.Size([1000, 1000]) torch.Size([1000]) torch.Size([10000, 1000])\nUDV Q0 shapes = torch.Size([1000, 1000]) torch.Size([1000]) torch.Size([10000, 1000])\nUDV Q1 shapes = torch.Size([1000, 1000]) torch.Size([1000]) torch.Size([10000, 1000])\nUDV time: 0.001360287016723305\nUDV time: 0.0003790960181504488\nUDV time: 0.00034324597800150514\nUDV time: 0.0002986839972436428\nudv I shapes = torch.Size([1000, 10000]) torch.Size([1000, 10000])\nudv Q shapes = torch.Size([1000, 10000]) torch.Size([1000, 10000])\nISTFT time = 0.0032885090331546962\nISTFT time = 0.005317253991961479\n" ] ], [ [ "### Write reconstructed IQ file to file", "_____no_output_____" ] ], [ [ "from array import array\nIQ_file = open(\"vod_clean_svd2\", 'wb')\nIQ_SVD.tofile(IQ_file)\nIQ_file.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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]