hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
sequence
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
sequence
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
sequence
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
sequence
cell_types
sequence
cell_type_groups
sequence
d037451016933493d2634e0e1dd4724fa8c0652e
5,848
ipynb
Jupyter Notebook
Practical-06-2. Exploration.ipynb
kingsgeocomp/applied_gsa
936c87392792452ffa6465e7e07f2f7b59299314
[ "MIT" ]
1
2022-03-31T16:13:57.000Z
2022-03-31T16:13:57.000Z
Practical-06-2. Exploration.ipynb
kingsgeocomp/applied_gsa
936c87392792452ffa6465e7e07f2f7b59299314
[ "MIT" ]
null
null
null
Practical-06-2. Exploration.ipynb
kingsgeocomp/applied_gsa
936c87392792452ffa6465e7e07f2f7b59299314
[ "MIT" ]
4
2018-10-12T21:09:07.000Z
2022-02-10T00:46:27.000Z
25.426087
142
0.55301
[ [ [ "## Dimensionality Reduction", "_____no_output_____" ] ], [ [ "from sklearn.decomposition import PCA", "_____no_output_____" ] ], [ [ "### Principal Components Analysis", "_____no_output_____" ] ], [ [ "o_dir = os.path.join('outputs','pca')\nif os.path.isdir(o_dir) is not True:\n print(\"Creating '{0}' directory.\".format(o_dir))\n os.mkdir(o_dir)", "_____no_output_____" ], [ "pca = PCA() # Use all Principal Components\npca.fit(scdf) # Train model on all data\npcdf = pd.DataFrame(pca.transform(scdf)) # Transform data using model\n\nfor i in range(0,21):\n print(\"Amount of explained variance for component {0} is: {1:6.2f}%\".format(i, pca.explained_variance_ratio_[i]*100))\n\nprint(\"The amount of explained variance of the SES score using each component is...\")\nsns.lineplot(x=list(range(1,len(pca.explained_variance_ratio_)+1)), y=pca.explained_variance_ratio_)", "_____no_output_____" ], [ "pca = PCA(n_components=11)\npca.fit(scdf)\nscores = pd.DataFrame(pca.transform(scdf), index=scdf.index)\nscores.to_csv(os.path.join(o_dir,'Scores.csv.gz'), compression='gzip', index=True)\n\n# Adapted from https://stackoverflow.com/questions/22984335/recovering-features-names-of-explained-variance-ratio-in-pca-with-sklearn\ni = np.identity(scdf.shape[1]) # identity matrix\n\ncoef = pca.transform(i)\n\nloadings = pd.DataFrame(coef, index=scdf.columns)\nloadings.to_csv(os.path.join(o_dir,'Loadings.csv.gz'), compression='gzip', index=True)", "_____no_output_____" ], [ "print(scores.shape)\nscores.sample(5, random_state=42)", "_____no_output_____" ], [ "print(loadings.shape)\nloadings.sample(5, random_state=42)", "_____no_output_____" ], [ "odf = pd.DataFrame(columns=['Variable','Component Loading','Score'])\nfor i in range(0,len(loadings.index)):\n row = loadings.iloc[i,:]\n for c in list(loadings.columns.values):\n d = {'Variable':loadings.index[i], 'Component Loading':c, 'Score':row[c]}\n odf = odf.append(d, ignore_index=True)\n\ng = sns.FacetGrid(odf, col=\"Variable\", col_wrap=4, height=3, aspect=2.0, margin_titles=True, sharey=True)\ng = g.map(plt.plot, \"Component Loading\", \"Score\", marker=\".\")", "_____no_output_____" ] ], [ [ "### What Have We Done?", "_____no_output_____" ] ], [ [ "sns.set_style('white')\nsns.jointplot(data=scores, x=0, y=1, kind='hex', height=8, ratio=8)", "_____no_output_____" ] ], [ [ "#### Create an Output Directory and Load the Data", "_____no_output_____" ] ], [ [ "o_dir = os.path.join('outputs','clusters-pca')\nif os.path.isdir(o_dir) is not True:\n print(\"Creating '{0}' directory.\".format(o_dir))\n os.mkdir(o_dir)", "_____no_output_____" ], [ "score_df = pd.read_csv(os.path.join('outputs','pca','Scores.csv.gz'))\nscore_df.rename(columns={'Unnamed: 0':'lsoacd'}, inplace=True)\nscore_df.set_index('lsoacd', inplace=True)\n\n# Ensures that df is initialised but original scores remain accessible\ndf = score_df.copy(deep=True)\n\nscore_df.describe()", "_____no_output_____" ], [ "score_df.sample(3, random_state=42)", "_____no_output_____" ] ], [ [ "#### Rescale the Loaded Data\n\nWe need this so that differences in the component scores don't cause the clustering algorithms to focus only on the 1st component.", "_____no_output_____" ] ], [ [ "scaler = preprocessing.MinMaxScaler()\n\ndf[df.columns] = scaler.fit_transform(df[df.columns])\n\ndf.describe()", "_____no_output_____" ], [ "df.sample(3, random_state=42)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d037571ff55a7aa75fa192b088e5784e887496ba
22,739
ipynb
Jupyter Notebook
demo/Detection_check.ipynb
chauhan-utk/ssd.DomainAdaptation
de70b27bf2b90ca182095173f34a55ac6ca5224a
[ "MIT" ]
3
2018-04-07T01:47:28.000Z
2020-12-03T03:40:19.000Z
demo/Detection_check.ipynb
chauhan-utk/ssd.DomainAdaptation
de70b27bf2b90ca182095173f34a55ac6ca5224a
[ "MIT" ]
null
null
null
demo/Detection_check.ipynb
chauhan-utk/ssd.DomainAdaptation
de70b27bf2b90ca182095173f34a55ac6ca5224a
[ "MIT" ]
null
null
null
20.72835
63
0.25586
[ [ [ "import os\nimport numpy as np", "_____no_output_____" ], [ "path = \"/users/gpu/utkrsh/data/PennDataset_detections/\"", "_____no_output_____" ], [ "directories = os.listdir(path)", "_____no_output_____" ], [ "d = []\nfor directory in directories:\n files = os.listdir(path+directory+\"/\")\n for file in files:\n try:\n var = np.load(file)\n except OSError:\n if directory not in d:\n d+= [directory]", "_____no_output_____" ], [ "d", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
d03761e99f94afa4b869578c8b083a812abf9cf7
120,911
ipynb
Jupyter Notebook
20210115/.ipynb_checkpoints/policyGradient -checkpoint.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
20210115/.ipynb_checkpoints/policyGradient -checkpoint.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
20210115/.ipynb_checkpoints/policyGradient -checkpoint.ipynb
dongxulee/lifeCycle
2b4a74dbd64357d00b29f7d946a66afcba747cc6
[ "MIT" ]
null
null
null
284.496471
26,996
0.924937
[ [ [ "### The model\n\n$u(c) = log(c)$ utility function \n$y = 1$ Deterministic income \n$p(r = 0.02) = 0.5$ \n$p(r = -0.02) = 0.5$ ", "_____no_output_____" ], [ "### value iteration ", "_____no_output_____" ] ], [ [ "# infinite horizon MDP problem\n%pylab inline\nimport numpy as np\nfrom scipy.optimize import minimize\ndef u(c):\n return np.log(c)", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "# discounting factor \nbeta = 0.95\n# wealth level\nw_low = 0 \nw_high = 10\n# interest rate\nr = 0.02\n# deterministic income\ny = 1\n# good state and bad state economy with equal probability 0.5\n# with good investment return 0.05 or bad investment return -0.05\nws = np.linspace(0.001,10**(1/2),100)**2\nVs = np.zeros(100)\nCs = np.zeros(100)", "_____no_output_____" ], [ "# Value iteration\nfor j in range(50):\n if j % 10 == 0:\n print(j)\n for i in range(len(ws)):\n w = ws[i]\n def obj(c):\n return -(u(c) + beta*(np.interp((y+w-c)*(1+r), ws, Vs) + np.interp((y+w-c)*(1-r), ws, Vs))/2)\n bounds = [(0.0001, y+w-0.0001)]\n res = minimize(obj, 0.0001, method='SLSQP', bounds=bounds)\n Cs[i] = res.x[0]\n Vs[i] = -res.fun", "0\n10\n20\n30\n40\n" ], [ "plt.plot(ws,Vs)", "_____no_output_____" ], [ "plt.plot(ws,Cs)", "_____no_output_____" ] ], [ [ "### policy gradient\nAssume the policy form $\\theta = (a,b,c, \\sigma)$, then $\\pi_\\theta$ ~ $N(log(ax+b)+c, \\sigma)$\n\nAssume the initial value $a = 1$, $b = 1$, $c = 1$, $\\sigma = 1$ \n\n\n$$\\theta_{k+1} = \\theta_{k} + \\alpha \\nabla_\\theta V(\\pi_\\theta)|\\theta_k$$", "_____no_output_____" ] ], [ [ "# simulation step T = 100\nT = 10\ndef mu(theta, w):\n return np.log(theta[0] * w + theta[1]) + theta[2] \n\ndef simSinglePath(theta):\n wPath = np.zeros(T)\n aPath = np.zeros(T)\n rPath = np.zeros(T)\n w = np.random.choice(ws)\n for t in range(T):\n c = np.random.normal(mu(theta, w), theta[3])\n while c < 0.0001 or c > w+y-0.0001:\n c = np.random.normal(mu(theta, w), theta[3])\n wPath[t] = w\n aPath[t] = c\n rPath[t] = np.log(c)*(beta**t)\n if np.random.uniform(0,1) > 0.5:\n w = (w+y-c) * (1+r)\n else:\n w = (w+y-c) * (1-r)\n return wPath, aPath, rPath\n\n\ndef gradientV(theta, D = 100):\n '''\n D is the sample size\n '''\n grad = np.zeros(len(theta))\n newGrad = np.zeros(len(theta))\n for d in range(D):\n wp, ap, rp = simSinglePath(theta) \n newGrad[0] = np.sum((ap - mu(theta, wp))/(theta[3]**2)*(w/(theta[0]*w + theta[1])))\n newGrad[1] = np.sum((ap - mu(theta, wp))/(theta[3]**2)*(1/(theta[0]*w + theta[1])))\n newGrad[2] = np.sum((ap - mu(theta, wp))/(theta[3]**2))\n #newGrad[3] = np.sum((((ap - mu(theta, wp))**2 - theta[3]**2)/(theta[3]**3)))\n grad += newGrad * np.sum(rp)\n grad /= D\n grad[-1] = 0\n return grad\n\ndef updateTheta(theta):\n theta = theta + alpha * gradientV(theta)\n return theta \n\n\nimport time\ndef plot(theta):\n def f(x):\n return np.log(theta[0]*x + theta[1]) + theta[2]\n plt.plot(ws, Cs, 'b')\n plt.plot(ws, f(ws), 'r')", "_____no_output_____" ], [ "# c < 0 or c > w + 5, then reward -100\n# initial theta \ntheta = [1,1,1,0.1]\n# gradient ascend step size \nalpha = 0.001\n# store theta \nTHETA = np.zeros((3,10000))\nfor i in range(10000):\n theta = updateTheta(theta)\n THETA[:,i] = theta[:3]\n plot(theta)", "_____no_output_____" ], [ "theta = [0.4, 1.00560229, 0.74852663, 0.1 ]", "_____no_output_____" ], [ "plt.plot(THETA[0,:])", "_____no_output_____" ], [ "plt.plot(THETA[1,:])", "_____no_output_____" ], [ "plt.plot(THETA[2,:])", "_____no_output_____" ], [ "def V(theta, w, D = 100):\n def sPath(theta, w):\n wPath = np.zeros(T)\n aPath = np.zeros(T)\n rPath = np.zeros(T)\n for t in range(T):\n c = np.random.normal(mu(theta, w), theta[3])\n while c < 0.0001 or c > w+y-0.0001:\n c = np.random.normal(mu(theta, w), theta[3])\n wPath[t] = w\n aPath[t] = c\n rPath[t] = np.log(c)*(beta**t)\n if np.random.uniform(0,1) > 0.5:\n w = (w+y-c) * (1+r)\n else:\n w = (w+y-c) * (1-r)\n return wPath, aPath, rPath\n value = 0\n for d in range(D):\n _,_,rp = sPath(theta,w)\n value += np.sum(rp)\n return value/D", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d03778fbaf8018555bc8622cec5e6abc7d49f4e2
40,577
ipynb
Jupyter Notebook
site/en/tutorials/load_data/tfrecord.ipynb
blueyi/docs
dabcd8664c95e21b8c7f5b190d1ea9de87fcc369
[ "Apache-2.0" ]
null
null
null
site/en/tutorials/load_data/tfrecord.ipynb
blueyi/docs
dabcd8664c95e21b8c7f5b190d1ea9de87fcc369
[ "Apache-2.0" ]
null
null
null
site/en/tutorials/load_data/tfrecord.ipynb
blueyi/docs
dabcd8664c95e21b8c7f5b190d1ea9de87fcc369
[ "Apache-2.0" ]
null
null
null
32.48759
476
0.534096
[ [ [ "##### 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_____" ] ], [ [ "# TFRecord and tf.Example\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/load_data/tfrecord\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/load_data/tfrecord.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/tutorials/load_data/tfrecord.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/load_data/tfrecord.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>", "_____no_output_____" ], [ "To read data efficiently it can be helpful to serialize your data and store it in a set of files (100-200MB each) that can each be read linearly. This is especially true if the data is being streamed over a network. This can also be useful for caching any data-preprocessing.\n\nThe TFRecord format is a simple format for storing a sequence of binary records.\n\n[Protocol buffers](https://developers.google.com/protocol-buffers/) are a cross-platform, cross-language library for efficient serialization of structured data.\n\nProtocol messages are defined by `.proto` files, these are often the easiest way to understand a message type.\n\nThe `tf.Example` message (or protobuf) is a flexible message type that represents a `{\"string\": value}` mapping. It is designed for use with TensorFlow and is used throughout the higher-level APIs such as [TFX](https://www.tensorflow.org/tfx/).", "_____no_output_____" ], [ "This notebook will demonstrate how to create, parse, and use the `tf.Example` message, and then serialize, write, and read `tf.Example` messages to and from `.tfrecord` files.\n\nNote: While useful, these structures are optional. There is no need to convert existing code to use TFRecords, unless you are using [`tf.data`](https://www.tensorflow.org/guide/datasets) and reading data is still the bottleneck to training. See [Data Input Pipeline Performance](https://www.tensorflow.org/guide/performance/datasets) for dataset performance tips.", "_____no_output_____" ], [ "## Setup", "_____no_output_____" ] ], [ [ "!pip install tf-nightly\nimport tensorflow as tf\n\nimport numpy as np\nimport IPython.display as display", "_____no_output_____" ] ], [ [ "## `tf.Example`", "_____no_output_____" ], [ "### Data types for `tf.Example`", "_____no_output_____" ], [ "Fundamentally, a `tf.Example` is a `{\"string\": tf.train.Feature}` mapping.\n\nThe `tf.train.Feature` message type can accept one of the following three types (See the [`.proto` file](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto) for reference). Most other generic types can be coerced into one of these:\n\n1. `tf.train.BytesList` (the following types can be coerced)\n\n - `string`\n - `byte`\n\n1. `tf.train.FloatList` (the following types can be coerced)\n\n - `float` (`float32`)\n - `double` (`float64`)\n\n1. `tf.train.Int64List` (the following types can be coerced)\n\n - `bool`\n - `enum`\n - `int32`\n - `uint32`\n - `int64`\n - `uint64`", "_____no_output_____" ], [ "In order to convert a standard TensorFlow type to a `tf.Example`-compatible `tf.train.Feature`, you can use the shortcut functions below. Note that each function takes a scalar input value and returns a `tf.train.Feature` containing one of the three `list` types above:", "_____no_output_____" ] ], [ [ "# The following functions can be used to convert a value to a type compatible\n# with tf.Example.\n\ndef _bytes_feature(value):\n \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n if isinstance(value, type(tf.constant(0))):\n value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _float_feature(value):\n \"\"\"Returns a float_list from a float / double.\"\"\"\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\ndef _int64_feature(value):\n \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))", "_____no_output_____" ] ], [ [ "Note: To stay simple, this example only uses scalar inputs. The simplest way to handle non-scalar features is to use `tf.serialize_tensor` to convert tensors to binary-strings. Strings are scalars in tensorflow. Use `tf.parse_tensor` to convert the binary-string back to a tensor.", "_____no_output_____" ], [ "Below are some examples of how these functions work. Note the varying input types and the standardized output types. If the input type for a function does not match one of the coercible types stated above, the function will raise an exception (e.g. `_int64_feature(1.0)` will error out, since `1.0` is a float, so should be used with the `_float_feature` function instead):", "_____no_output_____" ] ], [ [ "print(_bytes_feature(b'test_string'))\nprint(_bytes_feature(u'test_bytes'.encode('utf-8')))\n\nprint(_float_feature(np.exp(1)))\n\nprint(_int64_feature(True))\nprint(_int64_feature(1))", "_____no_output_____" ] ], [ [ "All proto messages can be serialized to a binary-string using the `.SerializeToString` method:", "_____no_output_____" ] ], [ [ "feature = _float_feature(np.exp(1))\n\nfeature.SerializeToString()", "_____no_output_____" ] ], [ [ "### Creating a `tf.Example` message", "_____no_output_____" ], [ "Suppose you want to create a `tf.Example` message from existing data. In practice, the dataset may come from anywhere, but the procedure of creating the `tf.Example` message from a single observation will be the same:\n\n1. Within each observation, each value needs to be converted to a `tf.train.Feature` containing one of the 3 compatible types, using one of the functions above.\n\n1. You create a map (dictionary) from the feature name string to the encoded feature value produced in #1.\n\n1. The map produced in step 2 is converted to a [`Features` message](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto#L85).", "_____no_output_____" ], [ "In this notebook, you will create a dataset using NumPy.\n\nThis dataset will have 4 features:\n\n* a boolean feature, `False` or `True` with equal probability\n* an integer feature uniformly randomly chosen from `[0, 5]`\n* a string feature generated from a string table by using the integer feature as an index\n* a float feature from a standard normal distribution\n\nConsider a sample consisting of 10,000 independently and identically distributed observations from each of the above distributions:", "_____no_output_____" ] ], [ [ "# The number of observations in the dataset.\nn_observations = int(1e4)\n\n# Boolean feature, encoded as False or True.\nfeature0 = np.random.choice([False, True], n_observations)\n\n# Integer feature, random from 0 to 4.\nfeature1 = np.random.randint(0, 5, n_observations)\n\n# String feature\nstrings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat'])\nfeature2 = strings[feature1]\n\n# Float feature, from a standard normal distribution\nfeature3 = np.random.randn(n_observations)", "_____no_output_____" ] ], [ [ "Each of these features can be coerced into a `tf.Example`-compatible type using one of `_bytes_feature`, `_float_feature`, `_int64_feature`. You can then create a `tf.Example` message from these encoded features:", "_____no_output_____" ] ], [ [ "def serialize_example(feature0, feature1, feature2, feature3):\n \"\"\"\n Creates a tf.Example message ready to be written to a file.\n \"\"\"\n # Create a dictionary mapping the feature name to the tf.Example-compatible\n # data type.\n feature = {\n 'feature0': _int64_feature(feature0),\n 'feature1': _int64_feature(feature1),\n 'feature2': _bytes_feature(feature2),\n 'feature3': _float_feature(feature3),\n }\n\n # Create a Features message using tf.train.Example.\n\n example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n return example_proto.SerializeToString()", "_____no_output_____" ] ], [ [ "For example, suppose you have a single observation from the dataset, `[False, 4, bytes('goat'), 0.9876]`. You can create and print the `tf.Example` message for this observation using `create_message()`. Each single observation will be written as a `Features` message as per the above. Note that the `tf.Example` [message](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/example.proto#L88) is just a wrapper around the `Features` message:", "_____no_output_____" ] ], [ [ "# This is an example observation from the dataset.\n\nexample_observation = []\n\nserialized_example = serialize_example(False, 4, b'goat', 0.9876)\nserialized_example", "_____no_output_____" ] ], [ [ "To decode the message use the `tf.train.Example.FromString` method.", "_____no_output_____" ] ], [ [ "example_proto = tf.train.Example.FromString(serialized_example)\nexample_proto", "_____no_output_____" ] ], [ [ "## TFRecords format details\n\nA TFRecord file contains a sequence of records. The file can only be read sequentially.\n\nEach record contains a byte-string, for the data-payload, plus the data-length, and CRC32C (32-bit CRC using the Castagnoli polynomial) hashes for integrity checking.\n\nEach record is stored in the following formats:\n\n uint64 length\n uint32 masked_crc32_of_length\n byte data[length]\n uint32 masked_crc32_of_data\n\nThe records are concatenated together to produce the file. CRCs are\n[described here](https://en.wikipedia.org/wiki/Cyclic_redundancy_check), and\nthe mask of a CRC is:\n\n masked_crc = ((crc >> 15) | (crc << 17)) + 0xa282ead8ul\n\nNote: There is no requirement to use `tf.Example` in TFRecord files. `tf.Example` is just a method of serializing dictionaries to byte-strings. Lines of text, encoded image data, or serialized tensors (using `tf.io.serialize_tensor`, and\n`tf.io.parse_tensor` when loading). See the `tf.io` module for more options.", "_____no_output_____" ], [ "## TFRecord files using `tf.data`", "_____no_output_____" ], [ "The `tf.data` module also provides tools for reading and writing data in TensorFlow.", "_____no_output_____" ], [ "### Writing a TFRecord file\n\nThe easiest way to get the data into a dataset is to use the `from_tensor_slices` method.\n\nApplied to an array, it returns a dataset of scalars:", "_____no_output_____" ] ], [ [ "tf.data.Dataset.from_tensor_slices(feature1)", "_____no_output_____" ] ], [ [ "Applied to a tuple of arrays, it returns a dataset of tuples:", "_____no_output_____" ] ], [ [ "features_dataset = tf.data.Dataset.from_tensor_slices((feature0, feature1, feature2, feature3))\nfeatures_dataset", "_____no_output_____" ], [ "# Use `take(1)` to only pull one example from the dataset.\nfor f0,f1,f2,f3 in features_dataset.take(1):\n print(f0)\n print(f1)\n print(f2)\n print(f3)", "_____no_output_____" ] ], [ [ "Use the `tf.data.Dataset.map` method to apply a function to each element of a `Dataset`.\n\nThe mapped function must operate in TensorFlow graph mode—it must operate on and return `tf.Tensors`. A non-tensor function, like `serialize_example`, can be wrapped with `tf.py_function` to make it compatible.\n\nUsing `tf.py_function` requires to specify the shape and type information that is otherwise unavailable:", "_____no_output_____" ] ], [ [ "def tf_serialize_example(f0,f1,f2,f3):\n tf_string = tf.py_function(\n serialize_example,\n (f0,f1,f2,f3), # pass these args to the above function.\n tf.string) # the return type is `tf.string`.\n return tf.reshape(tf_string, ()) # The result is a scalar", "_____no_output_____" ], [ "tf_serialize_example(f0,f1,f2,f3)", "_____no_output_____" ] ], [ [ "Apply this function to each element in the dataset:", "_____no_output_____" ] ], [ [ "serialized_features_dataset = features_dataset.map(tf_serialize_example)\nserialized_features_dataset", "_____no_output_____" ], [ "def generator():\n for features in features_dataset:\n yield serialize_example(*features)", "_____no_output_____" ], [ "serialized_features_dataset = tf.data.Dataset.from_generator(\n generator, output_types=tf.string, output_shapes=())", "_____no_output_____" ], [ "serialized_features_dataset", "_____no_output_____" ] ], [ [ "And write them to a TFRecord file:", "_____no_output_____" ] ], [ [ "filename = 'test.tfrecord'\nwriter = tf.data.experimental.TFRecordWriter(filename)\nwriter.write(serialized_features_dataset)", "_____no_output_____" ] ], [ [ "### Reading a TFRecord file", "_____no_output_____" ], [ "You can also read the TFRecord file using the `tf.data.TFRecordDataset` class.\n\nMore information on consuming TFRecord files using `tf.data` can be found [here](https://www.tensorflow.org/guide/datasets#consuming_tfrecord_data).\n\nUsing `TFRecordDataset`s can be useful for standardizing input data and optimizing performance.", "_____no_output_____" ] ], [ [ "filenames = [filename]\nraw_dataset = tf.data.TFRecordDataset(filenames)\nraw_dataset", "_____no_output_____" ] ], [ [ "At this point the dataset contains serialized `tf.train.Example` messages. When iterated over it returns these as scalar string tensors.\n\nUse the `.take` method to only show the first 10 records.\n\nNote: iterating over a `tf.data.Dataset` only works with eager execution enabled.", "_____no_output_____" ] ], [ [ "for raw_record in raw_dataset.take(10):\n print(repr(raw_record))", "_____no_output_____" ] ], [ [ "These tensors can be parsed using the function below. Note that the `feature_description` is necessary here because datasets use graph-execution, and need this description to build their shape and type signature:", "_____no_output_____" ] ], [ [ "# Create a description of the features.\nfeature_description = {\n 'feature0': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n 'feature1': tf.io.FixedLenFeature([], tf.int64, default_value=0),\n 'feature2': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'feature3': tf.io.FixedLenFeature([], tf.float32, default_value=0.0),\n}\n\ndef _parse_function(example_proto):\n # Parse the input `tf.Example` proto using the dictionary above.\n return tf.io.parse_single_example(example_proto, feature_description)", "_____no_output_____" ] ], [ [ "Alternatively, use `tf.parse example` to parse the whole batch at once. Apply this function to each item in the dataset using the `tf.data.Dataset.map` method:", "_____no_output_____" ] ], [ [ "parsed_dataset = raw_dataset.map(_parse_function)\nparsed_dataset", "_____no_output_____" ] ], [ [ "Use eager execution to display the observations in the dataset. There are 10,000 observations in this dataset, but you will only display the first 10. The data is displayed as a dictionary of features. Each item is a `tf.Tensor`, and the `numpy` element of this tensor displays the value of the feature:", "_____no_output_____" ] ], [ [ "for parsed_record in parsed_dataset.take(10):\n print(repr(parsed_record))", "_____no_output_____" ] ], [ [ "Here, the `tf.parse_example` function unpacks the `tf.Example` fields into standard tensors.", "_____no_output_____" ], [ "## TFRecord files in Python", "_____no_output_____" ], [ "The `tf.io` module also contains pure-Python functions for reading and writing TFRecord files.", "_____no_output_____" ], [ "### Writing a TFRecord file", "_____no_output_____" ], [ "Next, write the 10,000 observations to the file `test.tfrecord`. Each observation is converted to a `tf.Example` message, then written to file. You can then verify that the file `test.tfrecord` has been created:", "_____no_output_____" ] ], [ [ "# Write the `tf.Example` observations to the file.\nwith tf.io.TFRecordWriter(filename) as writer:\n for i in range(n_observations):\n example = serialize_example(feature0[i], feature1[i], feature2[i], feature3[i])\n writer.write(example)", "_____no_output_____" ], [ "!du -sh {filename}", "_____no_output_____" ] ], [ [ "### Reading a TFRecord file\n\nThese serialized tensors can be easily parsed using `tf.train.Example.ParseFromString`:", "_____no_output_____" ] ], [ [ "filenames = [filename]\nraw_dataset = tf.data.TFRecordDataset(filenames)\nraw_dataset", "_____no_output_____" ], [ "for raw_record in raw_dataset.take(1):\n example = tf.train.Example()\n example.ParseFromString(raw_record.numpy())\n print(example)", "_____no_output_____" ] ], [ [ "## Walkthrough: Reading and writing image data", "_____no_output_____" ], [ "This is an end-to-end example of how to read and write image data using TFRecords. Using an image as input data, you will write the data as a TFRecord file, then read the file back and display the image.\n\nThis can be useful if, for example, you want to use several models on the same input dataset. Instead of storing the image data raw, it can be preprocessed into the TFRecords format, and that can be used in all further processing and modelling.\n\nFirst, let's download [this image](https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg) of a cat in the snow and [this photo](https://upload.wikimedia.org/wikipedia/commons/f/fe/New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg) of the Williamsburg Bridge, NYC under construction.", "_____no_output_____" ], [ "### Fetch the images", "_____no_output_____" ] ], [ [ "cat_in_snow = tf.keras.utils.get_file('320px-Felis_catus-cat_on_snow.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/320px-Felis_catus-cat_on_snow.jpg')\nwilliamsburg_bridge = tf.keras.utils.get_file('194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg')", "_____no_output_____" ], [ "display.display(display.Image(filename=cat_in_snow))\ndisplay.display(display.HTML('Image cc-by: <a \"href=https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg\">Von.grzanka</a>'))", "_____no_output_____" ], [ "display.display(display.Image(filename=williamsburg_bridge))\ndisplay.display(display.HTML('<a \"href=https://commons.wikimedia.org/wiki/File:New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg\">From Wikimedia</a>'))", "_____no_output_____" ] ], [ [ "### Write the TFRecord file", "_____no_output_____" ], [ "As before, encode the features as types compatible with `tf.Example`. This stores the raw image string feature, as well as the height, width, depth, and arbitrary `label` feature. The latter is used when you write the file to distinguish between the cat image and the bridge image. Use `0` for the cat image, and `1` for the bridge image:", "_____no_output_____" ] ], [ [ "image_labels = {\n cat_in_snow : 0,\n williamsburg_bridge : 1,\n}", "_____no_output_____" ], [ "# This is an example, just using the cat image.\nimage_string = open(cat_in_snow, 'rb').read()\n\nlabel = image_labels[cat_in_snow]\n\n# Create a dictionary with features that may be relevant.\ndef image_example(image_string, label):\n image_shape = tf.image.decode_jpeg(image_string).shape\n\n feature = {\n 'height': _int64_feature(image_shape[0]),\n 'width': _int64_feature(image_shape[1]),\n 'depth': _int64_feature(image_shape[2]),\n 'label': _int64_feature(label),\n 'image_raw': _bytes_feature(image_string),\n }\n\n return tf.train.Example(features=tf.train.Features(feature=feature))\n\nfor line in str(image_example(image_string, label)).split('\\n')[:15]:\n print(line)\nprint('...')", "_____no_output_____" ] ], [ [ "Notice that all of the features are now stored in the `tf.Example` message. Next, functionalize the code above and write the example messages to a file named `images.tfrecords`:", "_____no_output_____" ] ], [ [ "# Write the raw image files to `images.tfrecords`.\n# First, process the two images into `tf.Example` messages.\n# Then, write to a `.tfrecords` file.\nrecord_file = 'images.tfrecords'\nwith tf.io.TFRecordWriter(record_file) as writer:\n for filename, label in image_labels.items():\n image_string = open(filename, 'rb').read()\n tf_example = image_example(image_string, label)\n writer.write(tf_example.SerializeToString())", "_____no_output_____" ], [ "!du -sh {record_file}", "_____no_output_____" ] ], [ [ "### Read the TFRecord file\n\nYou now have the file—`images.tfrecords`—and can now iterate over the records in it to read back what you wrote. Given that in this example you will only reproduce the image, the only feature you will need is the raw image string. Extract it using the getters described above, namely `example.features.feature['image_raw'].bytes_list.value[0]`. You can also use the labels to determine which record is the cat and which one is the bridge:", "_____no_output_____" ] ], [ [ "raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')\n\n# Create a dictionary describing the features.\nimage_feature_description = {\n 'height': tf.io.FixedLenFeature([], tf.int64),\n 'width': tf.io.FixedLenFeature([], tf.int64),\n 'depth': tf.io.FixedLenFeature([], tf.int64),\n 'label': tf.io.FixedLenFeature([], tf.int64),\n 'image_raw': tf.io.FixedLenFeature([], tf.string),\n}\n\ndef _parse_image_function(example_proto):\n # Parse the input tf.Example proto using the dictionary above.\n return tf.io.parse_single_example(example_proto, image_feature_description)\n\nparsed_image_dataset = raw_image_dataset.map(_parse_image_function)\nparsed_image_dataset", "_____no_output_____" ] ], [ [ "Recover the images from the TFRecord file:", "_____no_output_____" ] ], [ [ "for image_features in parsed_image_dataset:\n image_raw = image_features['image_raw'].numpy()\n display.display(display.Image(data=image_raw))", "_____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" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0377acbce1b1ad2a2486bf3e67970afb775bbca
13,792
ipynb
Jupyter Notebook
.ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb
Ruila/PythonCrwalerMarathon_Day14
27f7204f5eeb3e2a97a91413dbde1ed224edf0fb
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb
Ruila/PythonCrwalerMarathon_Day14
27f7204f5eeb3e2a97a91413dbde1ed224edf0fb
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Day_014_Yahoo_Movie_HW-checkpoint.ipynb
Ruila/PythonCrwalerMarathon_Day14
27f7204f5eeb3e2a97a91413dbde1ed224edf0fb
[ "MIT" ]
null
null
null
31.560641
1,428
0.518199
[ [ [ "# YAHOO電影爬蟲練習\n## 練習爬取電影放映資訊。必須逐步獲取電影的代號、放映地區、放映日期後,再送出查詢給伺服器。", "_____no_output_____" ] ], [ [ "import requests\nimport re\nfrom bs4 import BeautifulSoup", "_____no_output_____" ] ], [ [ "### 先搜尋全部的電影代號(ID)資訊", "_____no_output_____" ] ], [ [ "# 查看目前上映那些電影,並擷取出其ID資訊\nurl = 'https://movies.yahoo.com.tw/'\nresp = requests.get(url)\nresp.encoding = 'utf-8'\n# gggggg\nsoup = BeautifulSoup(resp.text, 'lxml')\nhtml = soup.find(\"select\", attrs={'name':'movie_id'})\nmovie_item = html.find_all(\"option\", attrs={'data-name':re.compile('.*')})\n\nfor p in movie_item:\n print(\"Movie: %s, ID: %s\" % (p[\"data-name\"], p[\"value\"]))", "Movie: 空中謎航, ID: 11152\nMovie: 致命天際線, ID: 11147\nMovie: 廢青四重奏, ID: 11130\nMovie: 妄想代理人:前篇, ID: 11102\nMovie: 水漾的女人, ID: 11065\nMovie: 午夜天鵝, ID: 11045\nMovie: 拆彈專家2, ID: 10986\nMovie: 杏林醫院, ID: 10781\nMovie: 靈魂急轉彎, ID: 11089\nMovie: 瑰麗卡萊爾:浮華紐約, ID: 11129\nMovie: 愛是您・愛是我, ID: 11123\nMovie: 來者弒客, ID: 11107\nMovie: 真愛鄰距離, ID: 11101\nMovie: 坑爹大作戰, ID: 11082\nMovie: 生為女人, ID: 10977\nMovie: 一家之煮, ID: 10955\nMovie: 腿, ID: 10934\nMovie: 鬼巢, ID: 11105\nMovie: 高校棋蹟, ID: 11099\nMovie: 戀愛進行弒, ID: 11080\nMovie: 85年的夏天, ID: 11076\nMovie: 順其自然的日子, ID: 11066\nMovie: 總是有個人在愛你, ID: 11063\nMovie: 神力女超人1984, ID: 10413\nMovie: 新解釋・三國志, ID: 11050\nMovie: 信用詐欺師JP:公主篇, ID: 11021\nMovie: 求婚好意外, ID: 10796\nMovie: 再見街貓BOB, ID: 11016\nMovie: 愛在午夜希臘時, ID: 11054\nMovie: 愛在黎明破曉時, ID: 11053\nMovie: 愛在日落巴黎時, ID: 11052\nMovie: 魔物獵人, ID: 10983\nMovie: 親愛的殺手, ID: 10861\nMovie: 未來的我們, ID: 11046\nMovie: 十二夜2:回到第零天, ID: 11035\nMovie: 尋找小魔女Doremi, ID: 11027\nMovie: 緝毒風暴, ID: 11023\nMovie: 古魯家族:新石代, ID: 10958\nMovie: 同學麥娜絲, ID: 10935\nMovie: 名偵探柯南:紅之校外旅行 鮮紅篇&戀紅篇, ID: 10887\nMovie: 我的媽媽開GAYBAR, ID: 10973\nMovie: 愛麗絲與夢幻島, ID: 11018\nMovie: 孤味, ID: 10477\nMovie: 聖荷西謀殺案, ID: 10990\nMovie: 入魔, ID: 10989\nMovie: 悄悄告訴她 經典數位修復, ID: 10911\nMovie: 鬼滅之刃劇場版 無限列車篇, ID: 10816\nMovie: 親愛的房客, ID: 10707\nMovie: 地下弒的秘密, ID: 10984\nMovie: 藥頭大媽, ID: 10951\nMovie: 看不見的目擊者, ID: 10946\nMovie: 無價之保, ID: 10959\nMovie: 倒數反擊, ID: 10906\nMovie: 阿公當家, ID: 10914\nMovie: 刻在你心底的名字, ID: 10902\nMovie: 急先鋒, ID: 10443\nMovie: 殺戮荒村, ID: 10903\nMovie: 消失的情人節, ID: 10870\nMovie: 中央車站:數位修復版, ID: 10907\nMovie: 海霧, ID: 10872\nMovie: 花木蘭, ID: 8632\nMovie: TENET天能, ID: 10433\nMovie: 聖雅各的天空, ID: 10877\nMovie: 看不見的證人, ID: 10873\nMovie: 可不可以,你也剛好喜歡我, ID: 10473\nMovie: 東京教父:4K數位修復版, ID: 10860\nMovie: 劇場版 新幹線變形機器人—來自未來的神速ALFA-X, ID: 10823\nMovie: 巴亞拉魔幻冒險, ID: 10851\nMovie: 怪胎, ID: 10733\nMovie: 魔王的女兒, ID: 10730\nMovie: 藍色恐懼:數位修復版, ID: 10775\nMovie: 角落小夥伴電影版:魔法繪本裡的新朋友, ID: 10647\nMovie: 一首搖滾上月球, ID: 4887\nMovie: 錢不夠用2, ID: 3026\n" ] ], [ [ "### 指定你有興趣的電影其ID,然後查詢其放映地區資訊。", "_____no_output_____" ] ], [ [ "# 參考前一個步驟中擷取到的ID資訊,並指定ID\nmovie_id = 10477", "_____no_output_____" ], [ "url = 'https://movies.yahoo.com.tw/api/v1/areas_by_movie_theater'\npayload = {'movie_id':str(movie_id)}\n\n# 模擬一個header\nheaders = {\n 'authority': 'movies.yahoo.com.tw',\n 'method': 'GET',\n 'path': '/api/v1/areas_by_movie_theater?movie_id=' + str(movie_id),\n 'scheme': 'https',\n 'accept': 'application/json, text/javascript, */*; q=0.01',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6',\n 'cookie': 'rxx=9s3x2fws06.1g16irnc&v=1; _ga=GA1.3.2056742944.1551651301; GUC=AQEBAQFczFpdm0IfmwSB&s=AQAAACoo4N5D&g=XMsVBw; BX=4hkdk1decm57t&b=3&s=mr; _ga=GA1.4.2056742944.1551651301; nexagesuid=82843256dd234e8e91aa73f2062f8218; browsed_movie=eyJpdiI6IlJXWWtiSWJaZlNGK2MxQnhscnVUYWc9PSIsInZhbHVlIjoiMXRhMmVHRXRIeUNjc1RBWDJzdGYwbnlIQURmWGsrcjJSMzhkbkcraDNJVUNIZEZsbzU3amlFcVZ1NzlmazJrTGpoMjVrbHk1YmpoRENXaHZTOUw1TmI2ZTZVWHdOejZQZm16RmVuMWlHTTJLaTZLVFZZVkFOMDlTd1wvSGltcytJIiwibWFjIjoiZWQ2ZjA4MmVjZmZlYjlmNjJmYmY2NGMyMDI0Njc0NWViYjVkOWE2NDg0N2RhODMxZjBjZDhiMmJhZTc2MDZhYiJ9; avi=eyJpdiI6Im1NeWFJRlVRWDR1endEcGRGUGJUbVE9PSIsInZhbHVlIjoickRpU3JuUytmcGl6cjF5OW0rNU9iZz09IiwibWFjIjoiY2VmY2NkNzZmM2NhNjY5YzlkOTcyNjE5OGEyMzU0NWYxOTdmMDRkMDY3OWNmMmZjOTMxYjc5MjI5N2Q5NGE5MiJ9; cmp=t=1559391030&j=0; _gid=GA1.4.779543841.1559391031; XSRF-TOKEN=eyJpdiI6IkhpS2hGcDRQaHlmWUJmaHdSS2Q2bHc9PSIsInZhbHVlIjoiOUVoNFk4OHI1UUZmUWRtYXhza0MyWjJSTlhlZ3RnT0VGeVJPN2JuczVRMGRFdWt2OUlsamVKeHRobFwvcHBGM0dhU3VyMXNGTHlsb2dVM2l0U1hpUGxBPT0iLCJtYWMiOiJkZWU4YzJhNjAxMTY3MzE4Y2ExNWIxYmE1ZjE1YWZlZTlhOTcyYjc4M2RlZGY4ZWNjZDYyMTA2NGYwZGViMzc2In0%3D; m_s=eyJpdiI6InpsZHZ2Tk1BZ0dxaHhETml1RjBnUXc9PSIsInZhbHVlIjoiSkNGeHUranRoXC85bDFiaDhySTJqNkJRcWdjWUxjeVRJSHVYZ1wvd2d4bWJZUTUrSHVDM0lUcW5KNHdETFZ4T1lieU81OUhzc1VoUXhZcWk0UDZSQXVFdz09IiwibWFjIjoiYmJkMDJkMDhlODIzMzcyMWY4M2NmYWNjNGVlOWRjMDIwZmVmNzAyMjE3Yzg3ZGY3ODBkZWEzZTI4MTI5ZWNmOSJ9; _gat=1; nexagesd=10',\n 'dnt': '1',\n 'mv-authorization': '21835b082e15b91a69b3851eec7b31b82ce82afb',\n 'referer': 'https://movies.yahoo.com.tw/',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',\n 'x-requested-with': 'XMLHttpRequest',\n}\n \nresp = requests.get(url, params=payload, headers=headers)\n#print(resp.json()) # 若有需要,列印出json原始碼\n\n# 這裡回傳的格式是JSON格式的資料,要解析JSON擷取資料\nfor p in resp.json():\n print('放映地區: {0}, 代號(area_id): {1}'.format(p['title'], p['area_id']))", "放映地區: 台北市, 代號(area_id): 28\n放映地區: 新北市, 代號(area_id): 8\n放映地區: 桃園, 代號(area_id): 16\n放映地區: 新竹, 代號(area_id): 20\n放映地區: 苗栗, 代號(area_id): 15\n放映地區: 台中, 代號(area_id): 2\n放映地區: 南投, 代號(area_id): 13\n放映地區: 嘉義, 代號(area_id): 21\n放映地區: 台南, 代號(area_id): 10\n放映地區: 高雄, 代號(area_id): 17\n放映地區: 宜蘭, 代號(area_id): 11\n放映地區: 花蓮, 代號(area_id): 12\n放映地區: 澎湖, 代號(area_id): 23\n" ] ], [ [ "### 指定你想要觀看的放映地區,查詢有上映電影的場次日期", "_____no_output_____" ] ], [ [ "# 指定放映地區\narea_id = 28", "_____no_output_____" ], [ "# 向網站發送請求\nurl = 'https://movies.yahoo.com.tw/movietime_result.html'\npayload = {'movie_id':str(movie_id), 'area_id':str(area_id)}\nresp = requests.get(url, params=payload)\nresp.encoding = 'utf-8'\n\nsoup = BeautifulSoup(resp.text, 'lxml')\nmovie_date = soup.find_all(\"label\", attrs={'for':re.compile(\"date_[\\d]\")})\n\n# 列印播放日期\nfor date in movie_date:\n print(\"%s %s\" % (date.p.string, date.h3.string))", "一月 1\n一月 2\n一月 3\n一月 4\n一月 5\n" ] ], [ [ "### 最後指定觀看的日期,查詢並列印出放映的電影院、放映類型(數位、3D、IMAX 3D...)、放映時間等資訊。", "_____no_output_____" ] ], [ [ "# 選定要觀看的日期\ndate = \"2019-08-21\"", "_____no_output_____" ], [ "# 向網站發送請求,獲取上映的電影院及時間資訊\nurl = \"https://movies.yahoo.com.tw/ajax/pc/get_schedule_by_movie\"\npayload = {'movie_id':str(movie_id),\n 'date':date,\n 'area_id':str(area_id),\n 'theater_id':'',\n 'datetime':'',\n 'movie_type_id':''}\n\nresp = requests.get(url, params=payload)\n#print(resp.json()['view']) # 若有需要,列印出json原始碼\n\nsoup = BeautifulSoup(resp.json()['view'], 'lxml')\nhtml = soup.find_all(\"ul\", attrs={'data-theater_name':re.compile(\".*\")})", "_____no_output_____" ], [ "'''\n\n 試著從上一步驟回傳的電影院資料中,擷取電影院名稱、影片放映類型以及時間表\n \n Your code here.\n\n'''\n", "----------------------------------------------------------------------\n電影院: 台北美麗華大直影城\n放映類型: 數位\n2019-08-21 09:00:00\n2019-08-21 11:10:00\n2019-08-21 13:15:00\n2019-08-21 15:20:00\n2019-08-21 19:30:00\n2019-08-21 21:40:00\n2019-08-21 22:30:00\n----------------------------------------------------------------------\n電影院: 台北新光影城\n放映類型: 數位\n2019-08-21 10:00:00\n2019-08-21 14:50:00\n2019-08-21 19:30:00\n----------------------------------------------------------------------\n電影院: 台北in89豪華數位影城\n放映類型: 數位\n2019-08-21 09:30:00\n2019-08-21 11:20:00\n2019-08-21 13:15:00\n2019-08-21 15:10:00\n2019-08-21 16:10:00\n2019-08-21 17:10:00\n2019-08-21 18:05:00\n2019-08-21 19:10:00\n2019-08-21 21:10:00\n2019-08-21 23:10:00\n2019-08-22 01:10:00\n----------------------------------------------------------------------\n電影院: 台北日新威秀影城\n放映類型: 數位\n2019-08-21 09:00:00\n2019-08-21 10:55:00\n2019-08-21 12:50:00\n2019-08-21 14:45:00\n2019-08-21 16:40:00\n2019-08-21 18:35:00\n2019-08-21 20:35:00\n----------------------------------------------------------------------\n電影院: 喜滿客絕色影城\n放映類型: 數位\n2019-08-21 10:00:00\n2019-08-21 11:55:00\n2019-08-21 13:50:00\n2019-08-21 15:45:00\n2019-08-21 17:40:00\n2019-08-21 19:35:00\n2019-08-21 21:30:00\n----------------------------------------------------------------------\n電影院: 台北信義威秀影城\n放映類型: 數位\n2019-08-21 09:00:00\n2019-08-21 11:00:00\n2019-08-21 13:00:00\n2019-08-21 15:00:00\n2019-08-21 17:00:00\n2019-08-21 19:00:00\n2019-08-21 21:00:00\n2019-08-21 23:00:00\n----------------------------------------------------------------------\n電影院: 喜滿客京華影城\n放映類型: 數位\n2019-08-21 10:30:00\n2019-08-21 12:30:00\n2019-08-21 14:30:00\n2019-08-21 16:30:00\n2019-08-21 18:30:00\n2019-08-21 20:30:00\n2019-08-21 22:30:00\n----------------------------------------------------------------------\n電影院: 京站威秀影城\n放映類型: 數位\n2019-08-21 09:00:00\n2019-08-21 11:00:00\n2019-08-21 13:00:00\n2019-08-21 15:00:00\n2019-08-21 17:00:00\n2019-08-21 19:00:00\n2019-08-21 21:00:00\n----------------------------------------------------------------------\n電影院: 喜樂時代影城南港店\n放映類型: 數位\n2019-08-21 10:20:00\n2019-08-21 11:10:00\n2019-08-21 12:20:00\n2019-08-21 13:10:00\n2019-08-21 14:20:00\n2019-08-21 15:10:00\n2019-08-21 16:20:00\n2019-08-21 17:10:00\n2019-08-21 18:20:00\n2019-08-21 19:15:00\n2019-08-21 20:20:00\n2019-08-21 21:15:00\n2019-08-21 22:20:00\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d0377f3497b4a697f14162918977607a611300c6
209,548
ipynb
Jupyter Notebook
sandbox/Chapter10_/More hacking with PyMC.ipynb
jeongho/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
f33d59f909acc3ca6713fa6cb4a1ff86a02c92ef
[ "MIT" ]
19,259
2015-01-01T10:31:47.000Z
2022-03-31T20:15:16.000Z
sandbox/Chapter10_/More hacking with PyMC.ipynb
ronnywilhelmsen/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
aa54c8ee5a52ff2a8ba77dd2d8959b75bb63d292
[ "MIT" ]
255
2015-01-07T17:12:59.000Z
2022-03-02T14:13:03.000Z
sandbox/Chapter10_/More hacking with PyMC.ipynb
ronnywilhelmsen/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
aa54c8ee5a52ff2a8ba77dd2d8959b75bb63d292
[ "MIT" ]
7,037
2015-01-01T12:58:13.000Z
2022-03-31T23:01:12.000Z
230.779736
51,694
0.883535
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d03783c3b489b14cf25f9fb4cb5d709c7f2ffb2b
87,814
ipynb
Jupyter Notebook
examples/Notebooks/flopy3_mf6_tutorial.ipynb
jdlarsen-UA/flopy
bf2c59aaa689de186bd4c80685532802ac7149cd
[ "CC0-1.0", "BSD-3-Clause" ]
351
2015-01-03T15:18:48.000Z
2022-03-31T09:46:43.000Z
examples/Notebooks/flopy3_mf6_tutorial.ipynb
smasky/flopy
81b17fa93df67f938c2d1b1bea34e8292359208d
[ "CC0-1.0", "BSD-3-Clause" ]
1,256
2015-01-15T21:10:42.000Z
2022-03-31T22:43:06.000Z
examples/Notebooks/flopy3_mf6_tutorial.ipynb
smasky/flopy
81b17fa93df67f938c2d1b1bea34e8292359208d
[ "CC0-1.0", "BSD-3-Clause" ]
553
2015-01-31T22:46:48.000Z
2022-03-31T17:43:35.000Z
68.284603
21,080
0.755107
[ [ [ "# Flopy MODFLOW 6 (MF6) Support", "_____no_output_____" ], [ "The Flopy library contains classes for creating, saving, running, loading, and modifying MF6 simulations. The MF6 portion of the flopy library is located in:\n\n*flopy.mf6*\n\nWhile there are a number of classes in flopy.mf6, to get started you only need to use the main classes summarized below:\n\nflopy.mf6.MFSimulation \n* MODFLOW Simulation Class. Entry point into any MODFLOW simulation.\n\nflopy.mf6.ModflowGwf\n* MODFLOW Groundwater Flow Model Class. Represents a single model in a simulation.\n\nflopy.mf6.Modflow[pc]\n * MODFLOW package classes where [pc] is the abbreviation of the package name. Each package is a separate class. \n\nFor packages that are part of a groundwater flow model, the abbreviation begins with \"Gwf\". For example, \"flopy.mf6.ModflowGwfdis\" is the Discretization package.\n ", "_____no_output_____" ] ], [ [ "import os\nimport sys\nfrom shutil import copyfile\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ntry:\n import flopy\nexcept:\n fpth = os.path.abspath(os.path.join('..', '..'))\n sys.path.append(fpth)\n import flopy\n \nprint(sys.version)\nprint('numpy version: {}'.format(np.__version__))\nprint('matplotlib version: {}'.format(mpl.__version__))\nprint('flopy version: {}'.format(flopy.__version__))", "3.8.10 (default, May 19 2021, 11:01:55) \n[Clang 10.0.0 ]\nnumpy version: 1.19.2\nmatplotlib version: 3.4.2\nflopy version: 3.3.4\n" ] ], [ [ "# Creating a MF6 Simulation", "_____no_output_____" ], [ "A MF6 simulation is created by first creating a simulation object \"MFSimulation\". When you create the simulation object you can define the simulation's name, version, executable name, workspace path, and the name of the tdis file. All of these are optional parameters, and if not defined each one will default to the following:\n\nsim_name='modflowtest'\n\nversion='mf6'\n\nexe_name='mf6.exe'\n\nsim_ws='.'\n\nsim_tdis_file='modflow6.tdis'", "_____no_output_____" ] ], [ [ "import os\nimport sys\nfrom shutil import copyfile\ntry:\n import flopy\nexcept:\n fpth = os.path.abspath(os.path.join('..', '..'))\n sys.path.append(fpth)\n import flopy\n\nsim_name = 'example_sim'\nsim_path = os.path.join('data', 'example_project')\nsim = flopy.mf6.MFSimulation(sim_name=sim_name, version='mf6', exe_name='mf6', \n sim_ws=sim_path)", "_____no_output_____" ] ], [ [ "The next step is to create a tdis package object \"ModflowTdis\". The first parameter of the ModflowTdis class is a simulation object, which ties a ModflowTdis object to a specific simulation. The other parameters and their definitions can be found in the docstrings.", "_____no_output_____" ] ], [ [ "tdis = flopy.mf6.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=2, \n perioddata=[(1.0, 1, 1.0), (10.0, 5, 1.0)])", "_____no_output_____" ] ], [ [ "Next one or more models are created using the ModflowGwf class. The first parameter of the ModflowGwf class is the simulation object that the model will be a part of.", "_____no_output_____" ] ], [ [ "model_name = 'example_model'\nmodel = flopy.mf6.ModflowGwf(sim, modelname=model_name,\n model_nam_file='{}.nam'.format(model_name))", "_____no_output_____" ] ], [ [ "Next create one or more Iterative Model Solution (IMS) files.", "_____no_output_____" ] ], [ [ "ims_package = flopy.mf6.ModflowIms(sim, pname='ims', print_option='ALL',\n complexity='SIMPLE', outer_hclose=0.00001,\n outer_maximum=50, under_relaxation='NONE',\n inner_maximum=30, inner_hclose=0.00001,\n linear_acceleration='CG',\n preconditioner_levels=7,\n preconditioner_drop_tolerance=0.01,\n number_orthogonalizations=2)", "_____no_output_____" ] ], [ [ "Each ModflowGwf object needs to be associated with an ModflowIms object. This is done by calling the MFSimulation object's \"register_ims_package\" method. The first parameter in this method is the ModflowIms object and the second parameter is a list of model names (strings) for the models to be associated with the ModflowIms object.", "_____no_output_____" ] ], [ [ "sim.register_ims_package(ims_package, [model_name])", "_____no_output_____" ] ], [ [ "Next add packages to each model. The first package added needs to be a spatial discretization package since flopy uses information from the spatial discretization package to help you build other packages. There are three spatial discretization packages to choose from:\n\nDIS (ModflowGwfDis) - Structured discretization\nDISV (ModflowGwfdisv) - Discretization with vertices\nDISU (ModflowGwfdisu) - Unstructured discretization", "_____no_output_____" ] ], [ [ "dis_package = flopy.mf6.ModflowGwfdis(model, pname='dis', length_units='FEET', nlay=2,\n nrow=2, ncol=5, delr=500.0,\n delc=500.0,\n top=100.0, botm=[50.0, 20.0],\n filename='{}.dis'.format(model_name))", "_____no_output_____" ] ], [ [ "## Accessing Namefiles\n\nNamefiles are automatically built for you by flopy. However, there are some options contained in the namefiles that you may want to set. To get the namefile object access the name_file attribute in either a simulation or model object to get the simulation or model namefile.", "_____no_output_____" ] ], [ [ "# set the nocheck property in the simulation namefile\nsim.name_file.nocheck = True\n# set the print_input option in the model namefile\nmodel.name_file.print_input = True", "_____no_output_____" ] ], [ [ "## Specifying Options\n\nOption that appear alone are assigned a boolean value, like the print_input option above. Options that have additional optional parameters are assigned using a tuple, with the entries containing the names of the optional parameters to turn on. Use a tuple with an empty string to indicate no optional parameters and use a tuple with None to turn the option off. ", "_____no_output_____" ] ], [ [ "# Turn Newton option on with under relaxation \nmodel.name_file.newtonoptions = ('UNDER_RELAXATION')\n# Turn Newton option on without under relaxation\nmodel.name_file.newtonoptions = ('')\n# Turn off Newton option \nmodel.name_file.newtonoptions = (None)", "_____no_output_____" ] ], [ [ "## MFArray Templates\n\nLastly define all other packages needed. \n\nNote that flopy supports a number of ways to specify data for a package. A template, which defines the data array shape for you, can be used to specify the data. Templates are built by calling the empty of the data type you are building. For example, to build a template for k in the npf package you would call:\n\nModflowGwfnpf.k.empty()\n\nThe empty method for \"MFArray\" data templates (data templates whose size is based on the structure of the model grid) take up to four parameters:\n\n* model - The model object that the data is a part of. A valid model object with a discretization package is required in order to build the proper array dimensions. This parameter is required.\n\n* layered - True or false whether the data is layered or not.\n\n* data_storage_type_list - List of data storage types, one for each model layer. If the template is not layered, only one data storage type needs to be specified. There are three data storage types supported, internal_array, internal_constant, and external_file. \n\n* default_value - The initial value for the array.", "_____no_output_____" ] ], [ [ "# build a data template for k that stores the first layer as an internal array and the second\n# layer as a constant with the default value of k for all layers set to 100.0 \nlayer_storage_types = [flopy.mf6.data.mfdatastorage.DataStorageType.internal_array, \n flopy.mf6.data.mfdatastorage.DataStorageType.internal_constant]\nk_template = flopy.mf6.ModflowGwfnpf.k.empty(model, True, layer_storage_types, 100.0)\n# change the value of the second layer to 50.0\nk_template[0]['data'] = [65.0, 60.0, 55.0, 50.0, 45.0, 40.0, 35.0, 30.0, 25.0, 20.0]\nk_template[0]['factor'] = 1.5\nprint(k_template)\n# create npf package using the k template to define k\nnpf_package = flopy.mf6.ModflowGwfnpf(model, pname='npf', save_flows=True, icelltype=1, k=k_template)", "[{'factor': 1.5, 'iprn': 1, 'data': [65.0, 60.0, 55.0, 50.0, 45.0, 40.0, 35.0, 30.0, 25.0, 20.0]}, 100.0]\n" ] ], [ [ "## Specifying MFArray Data\n\nMFArray data can also be specified as a numpy array, a list of values, or a single value. Below strt (starting heads) are defined as a single value, 100.0, which is interpreted as an internal constant storage type of value 100.0. Strt could also be defined as a list defining a value for every model cell:\n\nstrt=[100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, \n 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0]\n \nOr as a list defining a value or values for each model layer:\n\nstrt=[100.0, 90.0]\n\nor:\n\nstrt=[[100.0], [90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0]]\n\nMFArray data can also be stored in an external file by using a dictionary using the keys 'filename' to specify the file name relative to the model folder and 'data' to specific the data. The optional 'factor', 'iprn', and 'binary' keys may also be used.\n\nstrt={'filename': 'strt.txt', 'factor':1.0, 'data':[100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, \n 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0], 'binary': 'True'}\n \nIf the 'data' key is omitted from the dictionary flopy will try to read the data from an existing file 'filename'. Any relative paths for loading data from a file should specified relative to the MF6 simulation folder.", "_____no_output_____" ] ], [ [ "strt={'filename': 'strt.txt', 'factor':1.0, 'data':[100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, \n 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0], 'binary': 'True'}\nic_package = flopy.mf6.ModflowGwfic(model, pname='ic', strt=strt,\n filename='{}.ic'.format(model_name))\n# move external file data into model folder\nicv_data_path = os.path.join('..', 'data', 'mf6', 'notebooks', 'iconvert.txt')\ncopyfile(icv_data_path, os.path.join(sim_path, 'iconvert.txt'))\n# create storage package\nsto_package = flopy.mf6.ModflowGwfsto(model, pname='sto', save_flows=True, iconvert={'filename':'iconvert.txt'},\n ss=[0.000001, 0.000002], \n sy=[0.15, 0.14, 0.13, 0.12, 0.11, 0.11, 0.12, 0.13, 0.14, 0.15,\n 0.15, 0.14, 0.13, 0.12, 0.11, 0.11, 0.12, 0.13, 0.14, 0.15])", "_____no_output_____" ] ], [ [ "## MFList Templates\n\nFlopy supports specifying record and recarray \"MFList\" data in a number of ways. Templates can be created that define the shape of the data. The empty method for \"MFList\" data templates take up to 7 parameters.\n\n* model - The model object that the data is a part of. A valid model object with a discretization package is required in order to build the proper array dimensions. This parameter is required.\n\n* maxbound - The number of rows in the recarray. If not specified one row is returned.\n\n* aux_vars - List of auxiliary variable names. If not specified auxiliary variables are not used.\n\n* boundnames - True/False if boundnames is to be used.\n\n* nseg - Number of segments (only relevant for a few data types)\n\n* timeseries - True/False indicates that time series data will be used.\n\n* stress_periods - List of integer stress periods to be used (transient MFList data only). If not specified for transient data, template will only be defined for stress period 1. \n\nMFList transient data templates are numpy recarrays stored in a dictionary with the dictionary key an integer zero based stress period value (stress period - 1).\n\nIn the code below the well package is set up using a transient MFList template to help build the well's stress_periods. ", "_____no_output_____" ] ], [ [ "maxbound = 2\n# build a stress_period_data template with 2 wells over stress periods 1 and 2 with boundnames \n# and three aux variables\nwel_periodrec = flopy.mf6.ModflowGwfwel.stress_period_data.empty(model, maxbound=maxbound, boundnames=True, \n aux_vars=['var1', 'var2', 'var3'],\n stress_periods=[0,1])\n# define the two wells for stress period one\nwel_periodrec[0][0] = ((0,1,2), -50.0, -1, -2, -3, 'First Well')\nwel_periodrec[0][1] = ((1,1,4), -25.0, 2, 3, 4, 'Second Well')\n# define the two wells for stress period two\nwel_periodrec[1][0] = ((0,1,2), -200.0, -1, -2, -3, 'First Well')\nwel_periodrec[1][1] = ((1,1,4), -4000.0, 2, 3, 4, 'Second Well')\n# build the well package\nwel_package = flopy.mf6.ModflowGwfwel(model, pname='wel', print_input=True, print_flows=True,\n auxiliary=['var1', 'var2', 'var3'], maxbound=maxbound,\n stress_period_data=wel_periodrec, boundnames=True, save_flows=True)", "/Users/jdhughes/Documents/Development/flopy_git/flopy_fork/flopy/mf6/data/mfdatalist.py:1688: FutureWarning: elementwise == comparison failed and returning scalar instead; this will raise an error or perform elementwise comparison in the future.\n if \"check\" in list_item:\n" ] ], [ [ "## Cell IDs\n\nCell IDs always appear as tuples in an MFList. For a structured grid cell IDs appear as:\n\n(&lt;layer&gt;, &lt;row&gt;, &lt;column&gt;)\n\nFor vertice based grid cells IDs appear as:\n\n(&lt;layer&gt;, &lt;intralayer_cell_id&gt;)\n\nUnstructured grid cell IDs appear as:\n\n(&lt;cell_id&gt;)", "_____no_output_____" ], [ "## Specifying MFList Data\n\nMFList data can also be defined as a list of tuples, with each tuple being a row of the recarray. For transient data the list of tuples can be stored in a dictionary with the dictionary key an integer zero based stress period value. If only a list of tuples is specified for transient data, the data is assumed to apply to stress period 1. Additional stress periods can be added with the add_transient_key method. The code below defines saverecord and printrecord as a list of tuples.", "_____no_output_____" ] ], [ [ "# printrecord data as a list of tuples. since no stress\n# period is specified it will default to stress period 1\nprintrec_tuple_list = [('HEAD', 'ALL'), ('BUDGET', 'ALL')]\n# saverecord data as a dictionary of lists of tuples for \n# stress periods 1 and 2. \nsaverec_dict = {0:[('HEAD', 'ALL'), ('BUDGET', 'ALL')],1:[('HEAD', 'ALL'), ('BUDGET', 'ALL')]}\n# create oc package\noc_package = flopy.mf6.ModflowGwfoc(model, pname='oc', \n budget_filerecord=[('{}.cbc'.format(model_name),)],\n head_filerecord=[('{}.hds'.format(model_name),)],\n saverecord=saverec_dict,\n printrecord=printrec_tuple_list)\n# add stress period two to the print record\noc_package.printrecord.add_transient_key(1)\n# set the data for stress period two in the print record\noc_package.printrecord.set_data([('HEAD', 'ALL'), ('BUDGET', 'ALL')], 1)", "_____no_output_____" ] ], [ [ "### Specifying MFList Data in an External File \n\nMFList data can be specified in an external file using a dictionary with the 'filename' key. If the 'data' key is also included in the dictionary and is not None, flopy will create the file with the data contained in the 'data' key. The 'binary' key can be used to save data to a binary file ('binary': True). The code below creates a chd package which creates and references an external file containing data for stress period 1 and stores the data internally in the chd package file for stress period 2. ", "_____no_output_____" ] ], [ [ "stress_period_data = {0: {'filename': 'chd_sp1.dat', 'data': [[(0, 0, 0), 70.]]},\n 1: [[(0, 0, 0), 60.]]}\nchd = flopy.mf6.ModflowGwfchd(model, maxbound=1, stress_period_data=stress_period_data)", "_____no_output_____" ] ], [ [ "## Packages that Support both List-based and Array-based Data\n\nThe recharge and evapotranspiration packages can be specified using list-based or array-based input. The array packages have an \"a\" on the end of their name:\n\nModflowGwfrch - list based recharge package\nModflowGwfrcha - array based recharge package\nModflowGwfevt - list based evapotranspiration package\nModflowGwfevta - array based evapotranspiration package", "_____no_output_____" ] ], [ [ "rch_recarray = {0:[((0,0,0), 'rch_1'), ((1,1,1), 'rch_2')],\n 1:[((0,0,0), 'rch_1'), ((1,1,1), 'rch_2')]}\nrch_package = flopy.mf6.ModflowGwfrch(model, pname='rch', fixed_cell=True, print_input=True, \n maxbound=2, stress_period_data=rch_recarray)", "_____no_output_____" ] ], [ [ "## Utility Files (TS, TAS, OBS, TAB)\n\nUtility files, MF6 formatted files that reference by packages, include time series, time array series, observation, and tab files. The file names for utility files are specified using the package that references them. The utility files can be created in several ways. A simple case is demonstrated below. More detail is given in the flopy3_mf6_obs_ts_tas notebook. ", "_____no_output_____" ] ], [ [ "# build a time series array for the recharge package\nts_data = [(0.0, 0.015, 0.0017), (1.0, 0.016, 0.0019), (2.0, 0.012, 0.0015),\n (3.0, 0.020, 0.0014), (4.0, 0.015, 0.0021), (5.0, 0.013, 0.0012),\n (6.0, 0.022, 0.0012), (7.0, 0.016, 0.0014), (8.0, 0.013, 0.0011),\n (9.0, 0.021, 0.0011), (10.0, 0.017, 0.0016), (11.0, 0.012, 0.0015)]\nrch_package.ts.initialize(time_series_namerecord=['rch_1', 'rch_2'], \n timeseries=ts_data, filename='recharge_rates.ts',\n interpolation_methodrecord=['stepwise', 'stepwise'])\n\n# build an recharge observation package that outputs the western recharge to a binary file and the eastern\n# recharge to a text file\nobs_data = {('rch_west.csv', 'binary'): [('rch_1_1_1', 'RCH', (0, 0, 0)),\n ('rch_1_2_1', 'RCH', (0, 1, 0))],\n 'rch_east.csv': [('rch_1_1_5', 'RCH', (0, 0, 4)),\n ('rch_1_2_5', 'RCH', (0, 1, 4))]}\nrch_package.obs.initialize(filename='example_model.rch.obs', digits=10, \n print_input=True, continuous=obs_data)", "_____no_output_____" ] ], [ [ "# Saving and Running a MF6 Simulation", "_____no_output_____" ], [ "Saving and running a simulation are done with the MFSimulation class's write_simulation and run_simulation methods.", "_____no_output_____" ] ], [ [ "# write simulation to new location\nsim.write_simulation()\n\n# run simulation\nsim.run_simulation()", "writing simulation...\n writing simulation name file...\n writing simulation tdis package...\n writing ims package ims...\n writing model example_model...\n writing model name file...\n writing package dis...\n writing package npf...\n writing package ic...\n writing package sto...\n writing package wel...\n writing package oc...\n writing package chd_0...\n writing package rch...\n writing package ts_0...\n writing package obs_0...\nFloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6\n MODFLOW 6\n U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL\n VERSION 6.2.2 07/30/2021\n\n MODFLOW 6 compiled Aug 01 2021 12:51:08 with IFORT compiler (ver. 19.10.3)\n\nThis software has been approved for release by the U.S. Geological \nSurvey (USGS). Although the software has been subjected to rigorous \nreview, the USGS reserves the right to update the software as needed \npursuant to further analysis and review. No warranty, expressed or \nimplied, is made by the USGS or the U.S. Government as to the \nfunctionality of the software and related material nor shall the \nfact of release constitute any such warranty. Furthermore, the \nsoftware is released on condition that neither the USGS nor the U.S. \nGovernment shall be held liable for any damages resulting from its \nauthorized or unauthorized use. Also refer to the USGS Water \nResources Software User Rights Notice for complete use, copyright, \nand distribution information.\n\n \n Run start date and time (yyyy/mm/dd hh:mm:ss): 2021/08/06 16:21:19\n \n Writing simulation list file: mfsim.lst\n Using Simulation name file: mfsim.nam\n \n" ] ], [ [ "# Exporting a MF6 Model", "_____no_output_____" ], [ "Exporting a MF6 model to a shapefile or netcdf is the same as exporting a MF2005 model.", "_____no_output_____" ] ], [ [ "# make directory\npth = os.path.join('data', 'netCDF_export')\nif not os.path.exists(pth):\n os.makedirs(pth)\n \n# export the dis package to a netcdf file\nmodel.dis.export(os.path.join(pth, 'dis.nc'))\n\n# export the botm array to a shapefile\nmodel.dis.botm.export(os.path.join(pth, 'botm.shp'))", "initialize_geometry::proj4_str = epsg:4326\n" ] ], [ [ "# Loading an Existing MF6 Simulation", "_____no_output_____" ], [ "Loading a simulation can be done with the flopy.mf6.MFSimulation.load static method.", "_____no_output_____" ] ], [ [ "# load the simulation\nloaded_sim = flopy.mf6.MFSimulation.load(sim_name, 'mf6', 'mf6', sim_path)", "loading simulation...\n loading simulation name file...\n loading tdis package...\n loading model gwf6...\n loading package dis...\n loading package npf...\n loading package ic...\n loading package sto...\n loading package wel...\n loading package oc...\n loading package chd...\n" ] ], [ [ "# Retrieving Data and Modifying an Existing MF6 Simulation", "_____no_output_____" ], [ "Data can be easily retrieved from a simulation. Data can be retrieved using two methods. One method is to retrieve the data object from a master simulation dictionary that keeps track of all the data. The master simulation dictionary is accessed by accessing a simulation's \"simulation_data\" property and then the \"mfdata\" property:\n\nsim.simulation_data.mfdata[<data path>]\n\nThe data path is the path to the data stored as a tuple containing the model name, package name, block name, and data name.\n\nThe second method is to get the data from the package object. If you do not already have the package object, you can work your way down the simulation structure, from the simulation to the correct model, to the correct package, and finally to the data object.\n\nThese methods are demonstrated in the code below. ", "_____no_output_____" ] ], [ [ "# get hydraulic conductivity data object from the data dictionary\nhk = sim.simulation_data.mfdata[(model_name, 'npf', 'griddata', 'k')]\n\n# get specific yield data object from the storage package\nsy = sto_package.sy\n\n# get the model object from the simulation object using the get_model method, \n# which takes a string with the model's name and returns the model object\nmdl = sim.get_model(model_name)\n# get the package object from the model mobject using the get_package method,\n# which takes a string with the package's name or type\nic = mdl.get_package('ic')\n# get the data object from the initial condition package object\nstrt = ic.strt", "_____no_output_____" ] ], [ [ "Once you have the appropriate data object there are a number methods to retrieve data from that object. Data retrieved can either be the data as it appears in the model file or the data with any factor specified in the model file applied to it. To get the raw data without applying a factor use the get_data method. To get the data with the factor already applied use .array.\n\nNote that MFArray data is always a copy of the data stored by flopy. Modifying the copy of the flopy data will have no affect on the data stored in flopy. Non-constant internal MFList data is returned as a reference to a numpy recarray. Modifying this recarray will modify the data stored in flopy. ", "_____no_output_____" ] ], [ [ "# get the data without applying any factor\nhk_data_no_factor = hk.get_data()\nprint('Data without factor:\\n{}\\n'.format(hk_data_no_factor))\n\n# get data with factor applied\nhk_data_factor = hk.array\nprint('Data with factor:\\n{}\\n'.format(hk_data_factor))", "Data without factor:\n[[[ 65. 60. 55. 50. 45.]\n [ 40. 35. 30. 25. 20.]]\n\n [[100. 100. 100. 100. 100.]\n [100. 100. 100. 100. 100.]]]\n\nData with factor:\n[[[ 97.5 90. 82.5 75. 67.5]\n [ 60. 52.5 45. 37.5 30. ]]\n\n [[100. 100. 100. 100. 100. ]\n [100. 100. 100. 100. 100. ]]]\n\n" ] ], [ [ "Data can also be retrieved from the data object using []. For unlayered data the [] can be used to slice the data.", "_____no_output_____" ] ], [ [ "# slice layer one row two\nprint('SY slice of layer on row two\\n{}\\n'.format(sy[0,:,2]))", "SY slice of layer on row two\n[0.13 0.13]\n\n" ] ], [ [ "For layered data specify the layer number within the brackets. This will return a \"LayerStorage\" object which let's you change attributes of an individual layer.", "_____no_output_____" ] ], [ [ "# get layer one LayerStorage object\nhk_layer_one = hk[0]\n# change the print code and factor for layer one\nhk_layer_one.iprn = '2'\nhk_layer_one.factor = 1.1\nprint('Layer one data without factor:\\n{}\\n'.format(hk_layer_one.get_data()))\nprint('Data with new factor:\\n{}\\n'.format(hk.array))", "Layer one data without factor:\n[[65. 60. 55. 50. 45.]\n [40. 35. 30. 25. 20.]]\n\nData with new factor:\n[[[ 71.5 66. 60.5 55. 49.5]\n [ 44. 38.5 33. 27.5 22. ]]\n\n [[100. 100. 100. 100. 100. ]\n [100. 100. 100. 100. 100. ]]]\n\n" ] ], [ [ "## Modifying Data\n\nData can be modified in several ways. One way is to set data for a given layer within a LayerStorage object, like the one accessed in the code above. Another way is to set the data attribute to the new data. Yet another way is to call the data object's set_data method.", "_____no_output_____" ] ], [ [ "# set data within a LayerStorage object\nhk_layer_one.set_data([120.0, 100.0, 80.0, 70.0, 60.0, 50.0, 40.0, 30.0, 25.0, 20.0])\nprint('New HK data no factor:\\n{}\\n'.format(hk.get_data()))\n# set data attribute to new data\nic_package.strt = 150.0\nprint('New strt values:\\n{}\\n'.format(ic_package.strt.array))\n# call set_data\nsto_package.ss.set_data([0.000003, 0.000004])\nprint('New ss values:\\n{}\\n'.format(sto_package.ss.array))", "New HK data no factor:\n[[[120. 100. 80. 70. 60.]\n [ 50. 40. 30. 25. 20.]]\n\n [[100. 100. 100. 100. 100.]\n [100. 100. 100. 100. 100.]]]\n\nNew strt values:\n[[[150. 150. 150. 150. 150.]\n [150. 150. 150. 150. 150.]]\n\n [[150. 150. 150. 150. 150.]\n [150. 150. 150. 150. 150.]]]\n\nNew ss values:\n[[[3.e-06 3.e-06 3.e-06 3.e-06 3.e-06]\n [3.e-06 3.e-06 3.e-06 3.e-06 3.e-06]]\n\n [[4.e-06 4.e-06 4.e-06 4.e-06 4.e-06]\n [4.e-06 4.e-06 4.e-06 4.e-06 4.e-06]]]\n\n" ] ], [ [ "## Modifying the Simulation Path\n\nThe simulation path folder can be changed by using the set_sim_path method in the MFFileMgmt object. The MFFileMgmt object can be obtained from the simulation object through properties:\n\nsim.simulation_data.mfpath", "_____no_output_____" ] ], [ [ "# create new path\nsave_folder = os.path.join(sim_path, 'sim_modified')\n# change simulation path\nsim.simulation_data.mfpath.set_sim_path(save_folder)\n# create folder\nif not os.path.isdir(save_folder):\n os.makedirs(save_folder)", "WARNING: MFFileMgt's set_sim_path has been deprecated. Please use MFSimulation's set_sim_path in the future.\n" ] ], [ [ "## Adding a Model Relative Path\n\nA model relative path lets you put all of the files associated with a model in a folder relative to the simulation folder. Warning, this will override all of your file paths to model package files and will also override any relative file paths to external model data files. ", "_____no_output_____" ] ], [ [ "# Change path of model files relative to the simulation folder\nmodel.set_model_relative_path('model_folder')\n\n# create folder\nif not os.path.isdir(save_folder):\n os.makedirs(os.path.join(save_folder,'model_folder'))\n\n# write simulation to new folder\nsim.write_simulation()\n\n# run simulation from new folder\nsim.run_simulation() ", "writing simulation...\n writing simulation name file...\n writing simulation tdis package...\n writing ims package ims...\n writing model example_model...\n writing model name file...\n writing package dis...\n writing package npf...\n writing package ic...\n writing package sto...\n writing package wel...\n writing package oc...\n writing package chd_0...\n writing package rch...\n writing package ts_0...\n writing package obs_0...\nFloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6\n" ] ], [ [ "## Post-Processing the Results\n\nResults can be retrieved from the master simulation dictionary. Results are retrieved from the master simulation dictionary with using a tuple key that identifies the data to be retrieved. For head data use the key\n\n('&lt;model name&gt;', 'HDS', 'HEAD')\n\nwhere &lt;model name&gt; is the name of your model. For cell by cell budget data use the key\n\n('&lt;model name&gt;', 'CBC', '&lt;flow data name&gt;')\n\nwhere &lt;flow data name&gt; is the name of the flow data to be retrieved (ex. 'FLOW-JA-FACE'). All available output keys can be retrieved using the output_keys method.", "_____no_output_____" ] ], [ [ "keys = sim.simulation_data.mfdata.output_keys()", "('example_model', 'CBC', 'STO-SS')\n('example_model', 'CBC', 'STO-SY')\n('example_model', 'CBC', 'FLOW-JA-FACE')\n('example_model', 'CBC', 'WEL')\n('example_model', 'HDS', 'HEAD')\n" ] ], [ [ "The entries in the list above are keys for data in the head file \"HDS\" and data in cell by cell flow file \"CBC\". Keys in this list are not guaranteed to be in any particular order. The code below uses the head file key to retrieve head data and then plots head data using matplotlib.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n# get all head data\nhead = sim.simulation_data.mfdata['example_model', 'HDS', 'HEAD']\n# get the head data from the end of the model run\nhead_end = head[-1]\n# plot the head data from the end of the model run\nlevels = np.arange(160,162,1)\nextent = (0.0, 1000.0, 2500.0, 0.0)\nplt.contour(head_end[0, :, :],extent=extent)\nplt.show()", "_____no_output_____" ] ], [ [ "Results can also be retrieved using the existing binaryfile method.", "_____no_output_____" ] ], [ [ "# get head data using old flopy method\nhds_path = os.path.join(sim_path, model_name + '.hds')\nhds = flopy.utils.HeadFile(hds_path)\n# get heads after 1.0 days\nhead = hds.get_data(totim=1.0)\n# plot head data\nplt.contour(head[0, :, :],extent=extent)\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", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0378a66068f8659150456e64f077734bdeaa74d
717,545
ipynb
Jupyter Notebook
Lectures/4Regression_Analysis_Student.ipynb
jacobswe/data-science-lectures
3003f1fbad3c88140b92a5466d5b016aa459aa4a
[ "MIT" ]
null
null
null
Lectures/4Regression_Analysis_Student.ipynb
jacobswe/data-science-lectures
3003f1fbad3c88140b92a5466d5b016aa459aa4a
[ "MIT" ]
null
null
null
Lectures/4Regression_Analysis_Student.ipynb
jacobswe/data-science-lectures
3003f1fbad3c88140b92a5466d5b016aa459aa4a
[ "MIT" ]
null
null
null
609.121392
186,676
0.945638
[ [ [ "# Regression\nRegression is fundamentally a way to estimate an independent variable based on its relationships to predictor variables. This can be done both linearly and non-linearly with a single to many predictor variables. However, there are certain assumptions that must be satisfied in order for these results to be trustworthy.", "_____no_output_____" ] ], [ [ "#Import Packages\nimport numpy as np\nimport pandas as pd\n\n#Plotting\nimport seaborn as sns\nsns.set(rc={'figure.figsize':(11,8)})\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.ticker as ticker\n\n#Stats\nfrom scipy import stats\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom statsmodels.tools.tools import add_constant\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.datasets import make_regression\nimport statistics", "_____no_output_____" ] ], [ [ "## Linear Regression\n\nRecall $y=mx+b$, in this case we can see that $y$ is defined by a pair of constants and $x$. Similarly in regression, we have our independent target variable being estimated by a set of derived constants and the input variable(s). Since what comes out of the model is not necessarily what was observed, we call the prediction of the model $\\hat{y}$. The equation is then: $\\hat{y}=\\hat{\\beta_0} + \\hat{\\beta_1}x_1 + ... + \\hat{\\beta_n}x_n + \\epsilon$ for n predictors, where the $\\hat{\\beta_i}$ are the estimated coefficients and constant.\n\nIn the case of linear regression, the line will have the equation:$\\hat{y}=\\hat{\\beta_0}+\\hat{\\beta_1}x_1+\\epsilon$, with $\\epsilon$ being the distance between the observation and the prediction, i.e. $y-\\hat{y}$.\n\nNow the question is \"how do we determine what the $\\hat{\\beta_0}\\ ...\\ \\hat{\\beta_n}$ should be?\" or rather \"how can we manipulate the $\\hat{\\beta_0}\\ ...\\ \\hat{\\beta_n}$ to minimize error?\"\n\n$\\epsilon$ is defined as the difference between reality and prediction, so minimizing this distance by itself would be a good starting place. However, since we generally want to increase punishment to the algorithm for missing points by a large margin, $punishment = (y-\\hat{y})^2 = \\epsilon^2$ is used. More formally, for a series of $m$ data points, the Sum of Squared Errors is defined as follows: $SSE=\\sum_{i=1}^{m}(y_i-\\hat{y_i})^2$ for $m$ predictions. This makes the Mean Squared Error $\\frac{SSE}{m}=MSE$. So, if we minimize mean squared error ($MSE$) we find the optimal line.", "_____no_output_____" ] ], [ [ "#Create a function to predict our line\ndef predict(x,slope,intercept):\n return (slope*x+intercept)", "_____no_output_____" ], [ "#Generate Data\nX = np.random.uniform(10,size=10)\nY = list(map(lambda x: x+ 2*np.random.randn(1)[0], X)) #f(x) = x + 2N\n\n#Graph Cloud\nsns.relplot(x='X', y='Y', data=pd.DataFrame({'X':X,'Y':Y}),color='darkblue', zorder=10)", "_____no_output_____" ] ], [ [ "Now, with a regression line", "_____no_output_____" ] ], [ [ "#Get Regression Results\nslope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)\n\n#Create Regression Line\nlx = [min(X)-1,max(X)+1] #X-Bounds\nly = [predict(lx[0],slope,intercept),predict(lx[1],slope,intercept)] #Predictions at Bounds\n\n#Graph\nsns.relplot(x='X', y='Y', data=pd.DataFrame({'X':X,'Y':Y}),color='darkblue', zorder=10)\nsns.lineplot(lx, ly, color='r', zorder=5)", "_____no_output_____" ] ], [ [ "Then, find the $y_i-\\hat{y_i}$", "_____no_output_____" ] ], [ [ "#Plot Background\nsns.relplot(x='X', y='Y', data=pd.DataFrame({'X':X,'Y':Y}),color='darkblue', zorder=10)\nsns.lineplot(lx, ly, color='r', zorder=5)\n\n#Plot Distances\nfor i in range(len(X)):\n plt.plot([X[i],X[i]],[Y[i],predict(X[i],slope,intercept)],color = 'royalblue',linestyle=':',zorder=0)", "_____no_output_____" ] ], [ [ "Finally, calculate the MSE", "_____no_output_____" ] ], [ [ "#Setup\nfig, axs = plt.subplots(ncols=3, figsize=(15,5))\n\n#Calculations\nxy = pd.DataFrame({'X':X,'Y':Y}).sort_values('Y')\nxy['Y`'] = list(map(lambda x,y: ((predict(x,slope,intercept))), xy['X'], xy['Y']))\nxy['E'] = abs(xy['Y'] - xy['Y`'])\nxy = xy.sort_values(by=['E'])\n\n#Plot First Graph\nfor i in range(len(xy)):\n axs[0].plot([i,i],[0,xy.iloc[i,3]], color='royalblue',linestyle='-')\naxs[0].set_title('Sorted Errors')\n\n#Plot Second Graph\nfor i in range(len(xy)):\n axs[1].plot([i,i],[0,xy.iloc[i,3]**2], color='royalblue',linestyle='-')\naxs[1].set_title('Sorted Squared Errors')\n\n#Plot Third Graph\ntotal = min(xy['E'])\nfor i in range(len(xy)):\n deltah = xy.iloc[i,3]**2\n axs[2].plot([i,i],[0,xy.iloc[i,3]**2], color='royalblue',linestyle='-')\n axs[2].plot([max(0,i-1),i],[total,total + deltah], color='red',linestyle='-',marker='o')\n total+=deltah\naxs[2].set_title('Running Sum of Squared Erros')\nplt.show()\n\n#Calculate MSE\nMSE = statistics.mean(list(map(lambda e: e**2, xy['E'])))\nprint('Sum of Squared Errors:',round(total-min(xy['E']),3))\nprint('Total Observations:',len(xy))\nprint('Mean Squared Error:',round(MSE,4))", "_____no_output_____" ] ], [ [ "Now that we have a measure of success, we would like to develop some intuition and a function for how good we are predicting relative to perfect. If we were to imagine a straight line exactly through the mean of the Y-value (target value) of the cloud, we can imagine that half the points are above and half below. This calculation would give an $SSE$ of $\\sum_{i=1}^{n}(y_i-\\bar{y_i})^2$, or how this will be defined hereon the $SST$ or Sum of Squared Total Error. This guess is assumed to be the baseline guess you can make, and anything better is considered to be an improvement. As such, the ratio of $\\frac{SSE}{SST}$ models success relative to a benchmark. Functioning under the assumption that $0\\leq SSE\\leq SST$, $1-\\frac{SSE}{SST}$ gives a [0,1] interval of success generally known as $R^2$.\n\nLet's calculate.", "_____no_output_____" ] ], [ [ "#Create Data, Figures\nX = np.random.uniform(10,size=10)\nY = list(map(lambda x: x+ len(X)/10*np.random.randn(1)[0], X))\navgy = statistics.mean(Y)\nfig, axs = plt.subplots(ncols=2,figsize=(10,5))\n\n#Calculate Regressions\nslope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)\nlx = [min(X)-1,max(X)+1]\nly = [predict(lx[0],slope,intercept),predict(lx[1],slope,intercept)]\navgy = statistics.mean(Y)\n\n#Calculate and Format MSE\nMSEr = 'MSE: '+str(round(statistics.mean(list(map(lambda x, y: (y-(predict(x,slope,intercept)))**2, X, Y))),3))\nMSEa = 'MSE: '+str(round(statistics.mean(list(map(lambda y: (y-avgy)**2, Y))),3))\n\n#Create Scatter And Lines\naxs[0].scatter(X,Y, color='darkblue', zorder=10)\naxs[1].scatter(X,Y, color='darkblue', zorder=10)\naxs[0].plot(lx, ly, color='r', zorder=5, label=MSEr)\naxs[1].plot(lx, [avgy,avgy], color='lightslategray', label=MSEa)\n\n#Create Dotted Lines\nfor i in range(len(X)):\n axs[0].plot([X[i],X[i]],[Y[i],predict(X[i],slope,intercept)],color = 'red',linestyle=':',zorder=0)\n axs[1].plot([X[i],X[i]],[Y[i],avgy],color = 'dimgray',linestyle=':',zorder=0) \n\n#Calculate R2\nR2r = 'Linear Regression: R-squared = '+str(round(r_value,3))\nSSTa = sum(list(map(lambda y: (y-statistics.mean(Y))**2, Y)))\nSSEa = sum(list(map(lambda y: (y-statistics.mean(Y))**2, Y)))\nR2a = 'Linear Regression: R-squared = '+str(round(1 - SSEa/SSTa,3))\n\n#Format\naxs[0].set(xlabel='X',ylabel='Y',title=R2r)\naxs[1].set(xlabel='X',ylabel='Y',title=R2a)\naxs[0].legend()\naxs[1].legend()\n\n#Paint Graphs\nplt.show()", "_____no_output_____" ] ], [ [ "Thankfully, we don't have to do this manually. To repeat this process and get out all the same information automatically, we can use SciPy, a scientific modeling library for python. In this case, as you saw above, we are using the linregress function to solve the linear system of equations that gives us the minimal MSE. Let's see how this would be implemented in practice.", "_____no_output_____" ] ], [ [ "X = np.random.randn(150).tolist()\nY = list(map(lambda x: x + np.random.randn(1)[0]/1.5, X)) #f(x) = x + N(0,2/3)\n\nreg = stats.linregress(X,Y)\ntitle = 'Linear Regression R-Squared: '+str(round(reg.rvalue,3))\n\nfig = sns.lmplot(x='X',y='Y',data=pd.DataFrame({'X':X,'Y':Y}),ci=False).set(title=title)\nfig.ax.get_lines()[0].set_color('red')", "_____no_output_____" ] ], [ [ "However, not all data can be regressed. There are four criterian that must be met in order for the assumptions necessary for regression to be satisfied. These can be generally analyzed through residuals, or $y-\\hat{y}$.\n\n1) Linearity\n\n2) Independence\n\n3) Homoscedasticity\n\n4) Normality\n\nWe will go through each one a describe how to ensure your data is acceptable.", "_____no_output_____" ], [ "### Linearity\nThis is essentially that the relationship between the variables in linear in nature\n\n#### Method 1: Residuals vs. Observed, what you are looking for is any pattern to the data.", "_____no_output_____" ] ], [ [ "#Data\nX = np.random.randn(300).tolist()", "_____no_output_____" ], [ "#Setup\nfig, axs = plt.subplots(ncols=2,figsize=(10,5))\n\n#Accepted\nY = list(map(lambda x: x + np.random.randn(1)[0]/1.5, X))\nsns.residplot(x='X',y='Y',data=pd.DataFrame({'X':X,'Y':Y})\n ,ax=axs[0]).set_title('Residuals of Linear Regression: Accepted')\n\n#Rejected\nY = list(map(lambda x: x**2 + np.random.randn(1)[0]/8, X))\nsns.residplot(x='X',y='Y',data=pd.DataFrame({'X':X,'Y':Y})\n ,ax=axs[1], color='b').set_title('Residuals of Linear Regression: Rejected')", "_____no_output_____" ] ], [ [ "#### Method 2: Observed vs. Predicted, looking for patterns", "_____no_output_____" ] ], [ [ "#Setup\nfig, axs = plt.subplots(ncols=2,figsize=(10,5))\n\n#Accept\nY = list(map(lambda x: x + np.random.randn(1)[0]/1.5, X))\nslope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)\nYp = list(map(lambda x: predict(x,slope,intercept), X))\n\nsns.scatterplot(x='Y',y='Yp',data=pd.DataFrame({'Y':Y,'Yp':Yp}), ax=axs[0])\naxs[0].set(title='Predictions versus Observations: Accepted')\n\n#Reject\nY = list(map(lambda x: x**2 + np.random.randn(1)[0]/1.5, X))\nslope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)\nYp = list(map(lambda x: predict(x,slope,intercept), X))\n\nsns.scatterplot(x='Y',y='Yp',data=pd.DataFrame({'Y':Y,'Yp':Yp}), ax=axs[1])\naxs[1].set(title='Predictions versus Observations: Rejected')", "_____no_output_____" ] ], [ [ "### Independence\nThis looks at whether the $\\epsilon$ is correlated to the predictors either through sorting or other methods. This is a serious consideration for time series data, but we will focus on non-time series for now. \n\n#### Method 1) Same as above. Compare the order of observations agains the residuals, there should be no pattern\n\n#### Method 2) For more than 1 predictor, use VIF scores to check for multicolinearity amongst the variables\nThere is no hard and fast rule for kicking variables out due to VIF scores, but a good rule of thumb is anything more than 10 needs should likely need to be dealt with and anything greater than 5 should at least be looked at.", "_____no_output_____" ] ], [ [ "#Calculate Scores\nA = np.random.randn(150).tolist()\nB = list(map(lambda a: a + np.random.randn(1)[0]/20, A))\nC = np.random.uniform(1,10,size=150).tolist()\n\ndata = pd.DataFrame({'A':A,'B':B,'C':C})\ndata = add_constant(data)\n\nVIFs = pd.DataFrame([variance_inflation_factor(data.values, i) for i in range(data.shape[1])], index=data.columns,\n columns=['VIF Score'])\nprint('Accept if less than 5, Reject if more than 10\\n')\nprint(VIFs)", "Accept if less than 5, Reject if more than 10\n\n VIF Score\nconst 5.102457\nA 431.508540\nB 431.471557\nC 1.005629\n" ] ], [ [ "### Homoscedasticity\nCheck for if the magnitude of the residuals is the same over time or observations\n\n#### Method 1) Ordered Plot", "_____no_output_____" ] ], [ [ "#Setup\nfig, axs = plt.subplots(ncols=2,figsize=(10,5))\n\n#Accept\nX = np.random.randn(150)\nY = np.random.randn(150)\n\nslope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)\npredicted = X*slope+intercept\nresiduals = np.subtract(Y,predicted)\n\nsns.scatterplot(x='Predicted',y='Residuals', ax = axs[0],\n data=pd.DataFrame({'Predicted':predicted,'Residuals':residuals})).set_title('Accept')\n\n#Reject\nX = np.random.randn(150)\nY = list(map(lambda x: x**2 + np.random.randn(1)[0], X))\n\nslope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)\npredicted = X*slope+intercept\nresiduals = np.subtract(Y,predicted)\n\nsns.scatterplot(x='Predicted',y='Residuals', ax = axs[1],\n data=pd.DataFrame({'Predicted':predicted,'Residuals':residuals})).set_title(\"Reject\")", "_____no_output_____" ] ], [ [ "### Normality\n\n#### Method 1) Q-Q Plot", "_____no_output_____" ] ], [ [ "fig, axs = plt.subplots(ncols=2,figsize=(10,5))\n\n#Accept\nX = np.random.randn(150)\nY = np.random.randn(150)\n\nslope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)\npredicted = X*slope+intercept\nresiduals = np.subtract(Y,predicted)\n\nsm.qqplot(residuals, line='45',ax=axs[0])\n\n#Reject\nX = np.random.randn(150)\nY = list(map(lambda x: x**2 + np.random.randn(1)[0], X))\n\nslope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)\npredicted = X*slope+intercept\nresiduals = np.subtract(Y,predicted)\n\nsm.qqplot(residuals, line='45',ax=axs[1])\n\nplt.show()", "_____no_output_____" ] ], [ [ "## Multiple Regression\n\nThis is exactly the same as before, but we can increase the number of predictors. For example, this is what it looks like to perform linear regression in free space, fitting a plane to a cloud of points.", "_____no_output_____" ] ], [ [ "#Generate Data\nX = np.random.randn(150)\nY = np.random.randn(150)\nZ = list(map(lambda y, x: 4*(y + x) + np.random.randn(1)[0], Y, X))\n\n#Regress\nreg = smf.ols(formula='Z ~ X+Y', data=pd.DataFrame({'X':X,'Y':Y,'Z':Z})).fit()\n\n#Calculate Plane\nxx = np.linspace(min(X), max(X), 8)\nyy = np.linspace(min(Y), max(Y), 8)\nXX, YY = np.meshgrid(xx, yy)\nZZ = XX*reg.params[1]+YY*reg.params[2]+reg.params[0]\n\n#Create the figure\nfig = plt.figure(figsize=(15,15))\nax = fig.add_subplot(111,projection='3d')\nax.set(xlabel='X',ylabel='Y',zlabel='Z')\nax.view_init(30, 315)\nax.set(title='Three Dimensional Visualization')\n\n#Plot Plane and Points\nax.scatter(X, Y, Z, color='blue')\nax.plot_wireframe(X=XX,Y=YY,Z=ZZ)", "_____no_output_____" ] ], [ [ "We are also still able to run all of the same tests as before, looking at the diagnostic plots.", "_____no_output_____" ] ], [ [ "#1) Linearity: Residuals vs. Observed\nresiduals = list(map(lambda x, y, z: z-(x*reg.params[1]+y*reg.params[2]+reg.params[0]), X,Y,Z))\nsns.relplot(x='Observed',y='Residuals',\n data=pd.DataFrame({'Observed':Z,'Residuals':residuals}))", "_____no_output_____" ], [ "#2) Independence: VIF Scores\ndata = pd.DataFrame({'X':X,'Y':Y})\ndata = add_constant(data)\nVIFs = pd.DataFrame([variance_inflation_factor(data.values, i) for i in range(data.shape[1])], index=data.columns,\n columns=['VIF Score'])\nprint('Accept if less than 5, Reject if more than 10\\n')\nprint(VIFs)", "Accept if less than 5, Reject if more than 10\n\n VIF Score\nconst 1.021775\nX 1.012041\nY 1.012041\n" ], [ "#3) Predicted vs. Residuals\npredicted = X*reg.params[1]+Y*reg.params[2]+reg.params[0]\nresiduals = list(map(lambda x, y, z: z-(x*reg.params[1]+y*reg.params[2]+reg.params[0]), X,Y,Z))\n\nsns.relplot(x='Predicted',y='Residuals',\n data=pd.DataFrame({'Predicted':predicted,'Residuals':residuals}))", "_____no_output_____" ], [ "#4) Normality: QQ Plot\nresiduals = np.array(list(map(lambda x, y, z: z-(x*reg.params[1]+y*reg.params[2]+reg.params[0]), X,Y,Z)))\nsm.qqplot(residuals, line='45')\nplt.show()", "_____no_output_____" ] ], [ [ "This can be done in infinitely many dimensions, but because we cannot visualize above three dimensions (at least statically), you can only investigate this with the diagnostic plots.", "_____no_output_____" ], [ "## Predictor Significance Analysis\nRemembering back to how you can statistically say whether two random variables are equivalent with a T test, we would like to know if the $\\hat{\\beta_i}$ is statistically different from zero. If it is, at whatever confidence level we choose, we can say that it is useful in predicting the target variable. This is generally done automatically by any regression engine and is stored in the form of a p-value. What the p-value says is the 1 - the probability that what was observed is different than what it is being tested against, in this case zero. In other words, the lower your p-value the higher the probability that the two values are different. When you hear the term statistical significance, what you are hearing is \"does the p-value cross our confidence boundary?\" This is often thought of as 0.1, 0.05, or 0.01 depending on the application. Each predictor will have it's own p-value, which can say whether or not it is useful in predicting the target variable. Let's see.", "_____no_output_____" ] ], [ [ "#Generate Data\nX = np.random.randn(150)\nY = np.random.randn(150)\nZ = list(map(lambda y, x: 4*(y + x) + np.random.randn(1)[0], Y, X))\n\n#Regress\nreg = smf.ols(formula='Z ~ X+Y', data=pd.DataFrame({'X':X,'Y':Y,'Z':Z})).fit()\n\n#Grab P-values and Coefficients\nconfint = pd.DataFrame(reg.conf_int())\npvalues = pd.DataFrame({'P-Value':reg.pvalues.round(7)})\nprint(pvalues)\nprint(confint)", " P-Value\nIntercept 0.240027\nX 0.000000\nY 0.000000\n 0 1\nIntercept -0.064758 0.256575\nX 3.851395 4.147178\nY 3.821662 4.162070\n" ] ], [ [ "This is generally much easier to do in purely statistical engines like R. We will cover that soon.", "_____no_output_____" ], [ "## Solving Regression\nThere are many ways that regression equations can be solved, one of these ways is through gradient descent, essentially adjusting a combination of variables until you find the minimum MSE. Let's visualize this. Note, this will take a minute or so to run as it calculating the MSE of a regression line for all the possibilities. What will develop is a smooth visualization of the MSEs. If you imagine placing a marble on the graph, where it roles is the direction to the best fit line. It will roll, and reverse, and roll, and reverse until it finally settles at the lowest point. This is gradient descent.", "_____no_output_____" ] ], [ [ "def getMSE(slope, intercept, X, Y):\n return statistics.mean(list(map(lambda x, y: (y-(predict(x,slope,intercept)))**2, X, Y)))\n\ndef getHMData(slope,intercept,X,Y,step=0.1,):\n slopeDist = slope[1]-slope[0]\n slopeSteps = int(slopeDist/step)\n \n interceptDist = intercept[1]-intercept[0]\n interceptSteps = int(interceptDist/step)\n \n data = []\n \n for i in range(slopeSteps):\n row = []\n for j in range(interceptSteps):\n row.append(getMSE(slope=slope[0]+step*i,intercept=intercept[0]+step*j,X=X,Y=Y))\n data.append(row)\n \n return pd.DataFrame(data)", "_____no_output_____" ], [ "#Set Limits\nincrement = 0.1\nslopes = [-10,10]\nnumslopes = (slopes[1]-slopes[0])/increment\nintercepts = [-10,10]\nnuminter = (intercepts[1]-intercepts[0])/increment\n\n#Get Data\nX = np.random.randn(500)-2*np.random.randn(1)[0]\nY = list(map(lambda x: np.random.uniform(1,4)*x + np.random.randn(1)[0], X))\ndata = getHMData(slope=slopes,intercept=intercepts,X=X,Y=Y,step=increment)\n\n#Format Labels\ndata = data.set_index(np.linspace(slopes[0],slopes[1],int(numslopes)).round(1))\ndata.columns = np.linspace(intercepts[0],intercepts[1],int(numinter)).round(1)\n\n#Heat Map of MSE\nfig, axs = plt.subplots(ncols=2,figsize=(20,10))\nsns.heatmap(data.iloc[::-1,:],cmap=\"RdYlGn_r\",ax = axs[1]).set(title='MSE over Slopes and Intercepts')\naxs[1].set(xlabel='Intercept',ylabel='Slope')\n\n#Regression Plot\nsns.regplot(x='X',y='Y',data=pd.DataFrame({'X':X,'Y':Y}), ax = axs[0])\nslope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)\ntitle = ('Regression\\nSlope: '+str(slope.round(3))+', Intercept: '+\n str(intercept.round(3))+', R-Squared: '+str(r_value.round(3)))\naxs[0].set_title(title)\n\n#Plot Over Heatmap\naxs[1].hlines([slope*-10+100], *axs[1].get_xlim(),linestyles='dashed',colors='indigo')\naxs[1].vlines([intercept*10+100], *axs[1].get_ylim(),linestyles='dashed',colors='indigo')\naxs[1].scatter(intercept*10+100,slope*-10+100,zorder=10,c='indigo',s=50)", "_____no_output_____" ] ], [ [ "## Your turn to solve a problem.\n\nThe below code will generate for you 3 sets of values: 'X1','X2' - Predictors, 'Y' - Target\nYou will need to generate a regression. Then, you should check the predictors to see which one is significant. After this, you will need to re-run the regression and confirm if the data satisfies our regression assumption. Finally, you should create a seaborn plot of your regression.", "_____no_output_____" ] ], [ [ "Xs, Y = make_regression(n_samples=300, n_features=2, n_informative=1, noise=1)\ndata = pd.DataFrame(np.column_stack([Xs,Y]), columns=['X1','X2','Y'])", "_____no_output_____" ], [ "reg = smf.ols(formula='Y~X1+X2', data=pd.DataFrame({'X1':data['X1'],'X2':data['X2'],'Y':data['Y']})).fit()", "_____no_output_____" ], [ "confint = pd.DataFrame(reg.conf_int())\npvalues = pd.DataFrame({'P-Value':reg.pvalues.round(7)})\nprint(confint)\nprint(pvalues)", " 0 1\nIntercept -0.215802 0.026132\nX1 -0.151988 0.093336\nX2 0.626301 0.877282\n P-Value\nIntercept 0.123932\nX1 0.638339\nX2 0.000000\n" ], [ "reg = smf.ols(formula='Y ~ X2', data=pd.DataFrame({'X2':data['X2'],'Y':data['Y']})).fit()", "_____no_output_____" ], [ "sm.qqplot(reg.resid, line='45')\nplt.show()", "_____no_output_____" ], [ "sns.relplot(x='Residuals',y='Predicted',data=pd.DataFrame({'Residuals':reg.resid,'Predicted':reg.fittedvalues}))", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d0378ff52b3abcb816e68d656de909df925558ab
132,105
ipynb
Jupyter Notebook
SVM_sklearn.ipynb
CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster
951751211e218c98bfff0035a3dbccdc10690214
[ "MIT" ]
null
null
null
SVM_sklearn.ipynb
CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster
951751211e218c98bfff0035a3dbccdc10690214
[ "MIT" ]
null
null
null
SVM_sklearn.ipynb
CoderSLZhang/Kaggle-Titanic-Machine-Learning-from-Disaster
951751211e218c98bfff0035a3dbccdc10690214
[ "MIT" ]
null
null
null
49.366592
13,908
0.606904
[ [ [ "from sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn import metrics\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pylab as plt\nimport re\n\n%matplotlib inline", "/Users/zytec/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n \"This module will be removed in 0.20.\", DeprecationWarning)\n/Users/zytec/anaconda3/lib/python3.6/site-packages/sklearn/grid_search.py:42: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.\n DeprecationWarning)\n" ] ], [ [ "## 数据读取", "_____no_output_____" ] ], [ [ "df = pd.read_csv('data/train.csv')", "_____no_output_____" ], [ "df.head(10)", "_____no_output_____" ], [ "print('共有{}条数据.'.format(len(df)))\nprint('幸存者{}人.'.format(df.Survived.sum()))", "共有891条数据.\n幸存者342人.\n" ] ], [ [ "## 数据分析", "_____no_output_____" ], [ "#### Pclass 代表社会经济状况,数字越小状况越好 1 = upper, 2 = mid, 3 = lower", "_____no_output_____" ] ], [ [ "df.Pclass.value_counts(dropna=False)", "_____no_output_____" ], [ "df[['Pclass', 'Survived']].groupby(['Pclass']).mean().plot(kind='bar')", "_____no_output_____" ] ], [ [ "*社会等级越高,幸存率越高*", "_____no_output_____" ] ], [ [ "df['P1'] = (df.Pclass == 1).astype('int')\ndf['P2'] = (df.Pclass == 2).astype('int')\ndf['P3'] = (df.Pclass == 3).astype('int')\ndf.head()", "_____no_output_____" ] ], [ [ "#### Sex male时为1, female时为0", "_____no_output_____" ] ], [ [ "df.Sex.value_counts(dropna=False)", "_____no_output_____" ], [ "df[['Sex', 'Survived']].groupby(['Sex']).mean().plot(kind='bar')", "_____no_output_____" ] ], [ [ "*女性的幸存率比较高*", "_____no_output_____" ] ], [ [ "df.Sex.replace(['male', 'female'], [1, 0], inplace=True)\ndf.head()", "_____no_output_____" ] ], [ [ "#### Age 有缺失值,简单用平均值填充", "_____no_output_____" ] ], [ [ "df.Age.isnull().sum()", "_____no_output_____" ], [ "df.Age.fillna(df.Age.median(), inplace=True)", "_____no_output_____" ], [ "df['Age_categories'] = pd.cut(df['Age'], 5)", "_____no_output_____" ], [ "df[['Age_categories', 'Survived']].groupby(['Age_categories']).mean().plot(kind='bar')", "_____no_output_____" ] ], [ [ "*可见小孩的幸存率比较高*", "_____no_output_____" ], [ "#### Sibsp\t在船上的旁系亲属和配偶的数量", "_____no_output_____" ] ], [ [ "df.SibSp.isnull().sum()", "_____no_output_____" ] ], [ [ "#### Parch\t在船上的父母子女的数量", "_____no_output_____" ] ], [ [ "df.Parch.isnull().sum()", "_____no_output_____" ], [ "df['Family_size'] = df['SibSp'] + df['Parch']\ndf[['Family_size', 'Survived']].groupby(['Family_size']).mean().plot(kind='bar')", "_____no_output_____" ] ], [ [ "*亲属和配偶的数量和父母子女的数量合并为一个特征*", "_____no_output_____" ], [ "#### Fare\t船费", "_____no_output_____" ] ], [ [ "df.Fare.isnull().sum()", "_____no_output_____" ], [ "df['Fare_categories'] = pd.qcut(df['Fare'], 5)\ndf[['Fare_categories', 'Survived']].groupby(['Fare_categories']).mean().plot(kind='bar')", "_____no_output_____" ] ], [ [ "*票价越贵,乘客越有钱,幸存几率越大*", "_____no_output_____" ], [ "#### Embarked\t登船港口 C = Cherbourg, Q = Queenstown, S = Southampton", "_____no_output_____" ] ], [ [ "df.Embarked.value_counts(dropna=False)", "_____no_output_____" ], [ "df[['Embarked', 'Survived']].groupby(['Embarked']).mean().plot(kind='bar')", "_____no_output_____" ] ], [ [ "*可以看到在Cherbourg登陆的乘客幸存几率大*", "_____no_output_____" ] ], [ [ "df['E1'] = (df['Embarked'] == 'S').astype('int')\ndf['E2'] = (df['Embarked'] == 'C').astype('int')\ndf['E3'] = (df['Embarked'] == 'Q').astype('int')\ndf['E4'] = (df['Embarked'].isnull()).astype('int')\ndf.head()", "_____no_output_____" ] ], [ [ "#### 称谓,Mr、Miss、Master ...", "_____no_output_____" ] ], [ [ "def parse_title(name):\n match = re.match(r'\\w+\\,\\s(\\w+)\\.\\s', name)\n if match:\n return match.group(1)\n else:\n return np.nan", "_____no_output_____" ], [ "df['Title'] = df.Name.apply(parse_title)\ndf.Title.fillna('NoTitle', inplace=True)\ndf.Title.value_counts(dropna=False)", "_____no_output_____" ], [ "title_set = set(df.Title)\nfor i, title in enumerate(title_set):\n df['T'+str(i)] = (df.Title == title).astype('int')", "_____no_output_____" ], [ "df.head(3)", "_____no_output_____" ] ], [ [ "### 预处理后的数据", "_____no_output_____" ] ], [ [ "df_processed = df[['Survived', 'Sex', 'Age', 'Family_size', 'Fare', 'Pclass',\n 'E1', 'E2', 'E3', 'E4', 'T0', 'T1', 'T2', 'T3', 'T4', 'T5',\n 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'T13', 'T14']]\ndf_processed.head(3)", "_____no_output_____" ] ], [ [ "## 划分训练集和测试集", "_____no_output_____" ] ], [ [ "total_X = df_processed.iloc[:, 1:].values\ntotal_Y = df_processed.iloc[:, 0].values", "_____no_output_____" ], [ "train_X, test_X, train_Y, test_Y = train_test_split(total_X, total_Y, test_size=0.25)", "_____no_output_____" ] ], [ [ "## 数据标准化", "_____no_output_____" ] ], [ [ "X_scaler = StandardScaler()\ntrain_X_std = X_scaler.fit_transform(train_X)\ntest_X_std = X_scaler.transform(test_X)", "_____no_output_____" ] ], [ [ "### SVM超参数网格搜索", "_____no_output_____" ] ], [ [ "svm = SVC()\n\nparams = {\n 'C': np.logspace(1, (2 * np.random.rand()), 10),\n 'gamma':np.logspace(-4, (2 * np.random.rand()), 10)\n}\n\ngrid_search = GridSearchCV(svm, params, cv=3)\ngrid_search.fit(train_X_std, train_Y)", "_____no_output_____" ], [ "best_score = grid_search.best_score_", "_____no_output_____" ], [ "best_params = grid_search.best_params_\nC = best_params['C']\ngamma = best_params['gamma']\nC, gamma", "_____no_output_____" ], [ "grid_search.score(test_X_std, test_Y)", "_____no_output_____" ], [ "predicts = grid_search.predict(test_X_std)\nprint(metrics.classification_report(test_Y, predicts))", " precision recall f1-score support\n\n 0 0.78 0.95 0.85 129\n 1 0.89 0.63 0.74 94\n\navg / total 0.83 0.81 0.80 223\n\n" ] ], [ [ "## 最终预测", "_____no_output_____" ] ], [ [ "total_X_std = X_scaler.transform(df_processed.iloc[:, 1:].values)\ntotal_Y = df_processed.iloc[:, 0]", "_____no_output_____" ], [ "svm = SVC(C=C, gamma=gamma)\nsvm.fit(total_X_std, total_Y)", "_____no_output_____" ], [ "svm.score(total_X_std, total_Y)", "_____no_output_____" ], [ "test_df = pd.read_csv('data/test.csv')\ntest_df.head()", "_____no_output_____" ], [ "test_df.Sex.replace(['male', 'female'], [1, 0], inplace=True)\ntest_df.Age.fillna(df.Age.median(), inplace=True)\ntest_df['Family_size'] = test_df['SibSp'] + test_df['Parch']\ntest_df['P1'] = (df.Pclass == 1).astype('int')\ntest_df['P2'] = (df.Pclass == 2).astype('int')\ntest_df['P3'] = (df.Pclass == 3).astype('int')\ntest_df['E1'] = (df['Embarked'] == 'S').astype('int')\ntest_df['E2'] = (df['Embarked'] == 'C').astype('int')\ntest_df['E3'] = (df['Embarked'] == 'Q').astype('int')\ntest_df['E4'] = (df['Embarked'].isnull()).astype('int')\ntest_df['Title'] = df.Name.apply(parse_title)\ntest_df.Title.fillna('NoTitle', inplace=True)\ntitle_set = set(df.Title)\nfor i, title in enumerate(title_set):\n test_df['T'+str(i)] = (test_df.Title == title).astype('int')\n\ntest_df.head()", "_____no_output_____" ], [ "test_df.isnull().sum()", "_____no_output_____" ], [ "test_df.Fare.fillna(df.Fare.median(), inplace=True)", "_____no_output_____" ], [ "test_df_processed = test_df[['Sex', 'Age', 'Family_size', 'Fare', 'Pclass',\n 'E1', 'E2', 'E3', 'E4', 'T0', 'T1', 'T2', 'T3', 'T4', 'T5',\n 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'T13', 'T14']]\ntest_df_processed.head(3)", "_____no_output_____" ], [ "final_X = test_df_processed.values\nfinal_X_std = X_scaler.transform(final_X)", "_____no_output_____" ] ], [ [ "### 预测", "_____no_output_____" ] ], [ [ "predicts = svm.predict(final_X_std)", "_____no_output_____" ], [ "ids = test_df['PassengerId'].values", "_____no_output_____" ], [ "result = pd.DataFrame({\n 'PassengerId': ids,\n 'Survived': predicts\n})", "_____no_output_____" ], [ "result.head()", "_____no_output_____" ], [ "result.to_csv('./2018-8-23_6.csv', index=False)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d037925670701401b3ac15c4d1e6ce0a494adf16
3,197
ipynb
Jupyter Notebook
enumeration/enumeration.ipynb
MaiaNgo/python-advanced
372d741b061548654ca77cb513085d2aeb3d767b
[ "Apache-2.0" ]
1
2022-02-16T03:14:27.000Z
2022-02-16T03:14:27.000Z
enumeration/enumeration.ipynb
MaiaNgo/python-advanced
372d741b061548654ca77cb513085d2aeb3d767b
[ "Apache-2.0" ]
null
null
null
enumeration/enumeration.ipynb
MaiaNgo/python-advanced
372d741b061548654ca77cb513085d2aeb3d767b
[ "Apache-2.0" ]
null
null
null
18.062147
81
0.476071
[ [ [ "# Sometimes we need an immutable collection of related constant elements\nimport enum\n\nclass Color(enum.Enum):\n red = 1\n green = 2\n blue = 3\n\nclass Status(enum.Enum):\n PENDING = 'PENDING'\n RUNNING = 'RUNNING'\n COMPLETE = 'COMPLETE'", "_____no_output_____" ], [ "type(Color.red)", "_____no_output_____" ], [ "isinstance(Color.red, Color)", "_____no_output_____" ], [ "Color.red.name, Color.red.value", "_____no_output_____" ], [ "list(Status)", "_____no_output_____" ], [ "for status in list(Status):\n print(status)", "Status.PENDING\nStatus.RUNNING\nStatus.COMPLETE\n" ], [ "type(Status)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d037977dc3146b8a0a9aecdb3484201e87c1d046
4,543
ipynb
Jupyter Notebook
HW2/Q1.ipynb
SiqiT/Assigmnment
b5a890045041e6d58551ca4e2497cf1f9655080d
[ "Xnet", "X11" ]
null
null
null
HW2/Q1.ipynb
SiqiT/Assigmnment
b5a890045041e6d58551ca4e2497cf1f9655080d
[ "Xnet", "X11" ]
null
null
null
HW2/Q1.ipynb
SiqiT/Assigmnment
b5a890045041e6d58551ca4e2497cf1f9655080d
[ "Xnet", "X11" ]
null
null
null
42.457944
2,024
0.578472
[ [ [ "def grad(x):\n h=0.41\n while x <=1:\n return -1\n while x>1 and x<(1+h):\n return 1\n while x>(1+h) and x<(1+2*h):\n return -1", "_____no_output_____" ], [ "h=0.41\nlr=0.3\nbeta1=0.9\nbeta2=0.999\nepislon=0\nm=[0]\nv = [0]\nt = 0\nxt=0", "_____no_output_____" ], [ "while 1:\n t+=1\n gx=grad(xt)\n m.append(beta1*m[t-1]+(1-beta1)*gx)\n v.append(beta2*v[t-1]+(1-beta2)*gx*gx)\n m_hat=m[t] / (1 - beta1 ** t)\n v_hat=v[t] / (1 - beta2 ** t)\n xt -= lr *m_hat / (v_hat ** 0.5 + epislon)\n print('t=',t,'xt=',xt)", "t= 1 xt= 0.3\nt= 2 xt= 0.5999999999999979\nt= 3 xt= 0.8999999999999977\nt= 4 xt= 1.199999999999996\nt= 5 xt= 1.353483431418032\nt= 6 xt= 1.4101842951299657\nt= 7 xt= 1.5135207138708162\nt= 8 xt= 1.6513878189412725\nt= 9 xt= 1.8157221649197492\nt= 10 xt= 2.000885800510925\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
d037a371c13ff24eb778b2998091d56b7a72044d
445,057
ipynb
Jupyter Notebook
study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb
take2rohit/monk_v1
9c567bf2c8b571021b120d879ba9edf7751b9f92
[ "Apache-2.0" ]
542
2019-11-10T12:09:31.000Z
2022-03-28T11:39:07.000Z
study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb
take2rohit/monk_v1
9c567bf2c8b571021b120d879ba9edf7751b9f92
[ "Apache-2.0" ]
117
2019-11-12T09:39:24.000Z
2022-03-12T00:20:41.000Z
study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks in Deep Learning Networks/8) Resnet V2 Bottleneck Block (Type - 2).ipynb
take2rohit/monk_v1
9c567bf2c8b571021b120d879ba9edf7751b9f92
[ "Apache-2.0" ]
246
2019-11-09T21:53:24.000Z
2022-03-29T00:57:07.000Z
328.213127
104,108
0.928793
[ [ [ "<a href=\"https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/3_image_processing_deep_learning_roadmap/3_deep_learning_advanced/1_Blocks%20in%20Deep%20Learning%20Networks/8)%20Resnet%20V2%20Bottleneck%20Block%20(Type%20-%202).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Goals\n\n### 1. Learn to implement Resnet V2 Bottleneck Block (Type - 1) using monk\n - Monk's Keras\n - Monk's Pytorch\n - Monk's Mxnet\n \n### 2. Use network Monk's debugger to create complex blocks \n\n\n### 3. Understand how syntactically different it is to implement the same using\n - Traditional Keras\n - Traditional Pytorch\n - Traditional Mxnet", "_____no_output_____" ], [ "# Resnet V2 Bottleneck Block - Type 1\n \n - Note: The block structure can have variations too, this is just an example", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/resnet_v2_bottleneck_without_downsample.png')", "_____no_output_____" ] ], [ [ "# Table of contents\n\n[1. Install Monk](#1)\n\n\n[2. Block basic Information](#2)\n\n - [2.1) Visual structure](#2-1)\n \n - [2.2) Layers in Branches](#2-2)\n\n\n[3) Creating Block using monk visual debugger](#3)\n\n - [3.1) Create the first branch](#3-1)\n\n - [3.2) Create the second branch](#3-2)\n \n - [3.3) Merge the branches](#3-3)\n \n - [3.4) Debug the merged network](#3-4)\n \n - [3.5) Compile the network](#3-5)\n \n - [3.6) Visualize the network](#3-6)\n \n - [3.7) Run data through the network](#3-7)\n \n \n[4) Creating Block Using MONK one line API call](#4)\n\n - [Mxnet Backend](#4-1)\n \n - [Pytorch Backend](#4-2)\n \n - [Keras Backend](#4-3)\n \n \n \n[5) Appendix](#5)\n\n - [Study Material](#5-1)\n \n - [Creating block using traditional Mxnet](#5-2)\n \n - [Creating block using traditional Pytorch](#5-3)\n \n - [Creating block using traditional Keras](#5-4)\n ", "_____no_output_____" ], [ "<a id='0'></a>\n# Install Monk", "_____no_output_____" ], [ "## Using pip (Recommended)\n\n - colab (gpu) \n - All bakcends: `pip install -U monk-colab`\n \n\n - kaggle (gpu) \n - All backends: `pip install -U monk-kaggle`\n \n\n - cuda 10.2\t\n - All backends: `pip install -U monk-cuda102`\n - Gluon bakcned: `pip install -U monk-gluon-cuda102`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda102`\n - Keras backend: `pip install -U monk-keras-cuda102`\n \n\n - cuda 10.1\t\n - All backend: `pip install -U monk-cuda101`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda101`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda101`\n\t - Keras backend: `pip install -U monk-keras-cuda101`\n \n\n - cuda 10.0\t\n - All backend: `pip install -U monk-cuda100`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda100`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda100`\n\t - Keras backend: `pip install -U monk-keras-cuda100`\n \n\n - cuda 9.2\t\n - All backend: `pip install -U monk-cuda92`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda92`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda92`\n\t - Keras backend: `pip install -U monk-keras-cuda92`\n \n\n - cuda 9.0\t\n - All backend: `pip install -U monk-cuda90`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda90`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda90`\n\t - Keras backend: `pip install -U monk-keras-cuda90`\n \n\n - cpu \t\t\n - All backend: `pip install -U monk-cpu`\n\t - Gluon bakcned: `pip install -U monk-gluon-cpu`\n\t - Pytorch backend: `pip install -U monk-pytorch-cpu`\n\t - Keras backend: `pip install -U monk-keras-cpu`", "_____no_output_____" ], [ "## Install Monk Manually (Not recommended)\n \n### Step 1: Clone the library\n - git clone https://github.com/Tessellate-Imaging/monk_v1.git\n \n \n \n \n### Step 2: Install requirements \n - Linux\n - Cuda 9.0\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu90.txt`\n - Cuda 9.2\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu92.txt`\n - Cuda 10.0\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu100.txt`\n - Cuda 10.1\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu101.txt`\n - Cuda 10.2\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu102.txt`\n - CPU (Non gpu system)\n - `cd monk_v1/installation/Linux && pip install -r requirements_cpu.txt`\n \n \n - Windows\n - Cuda 9.0 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu90.txt`\n - Cuda 9.2 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu92.txt`\n - Cuda 10.0 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu100.txt`\n - Cuda 10.1 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu101.txt`\n - Cuda 10.2 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu102.txt`\n - CPU (Non gpu system)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cpu.txt`\n \n \n - Mac\n - CPU (Non gpu system)\n - `cd monk_v1/installation/Mac && pip install -r requirements_cpu.txt`\n \n \n - Misc\n - Colab (GPU)\n - `cd monk_v1/installation/Misc && pip install -r requirements_colab.txt`\n - Kaggle (GPU)\n - `cd monk_v1/installation/Misc && pip install -r requirements_kaggle.txt`\n \n \n \n### Step 3: Add to system path (Required for every terminal or kernel run)\n - `import sys`\n - `sys.path.append(\"monk_v1/\");`", "_____no_output_____" ], [ "# Imports", "_____no_output_____" ] ], [ [ "# Common\nimport numpy as np\nimport math\nimport netron\nfrom collections import OrderedDict\nfrom functools import partial", "_____no_output_____" ], [ "#Using mxnet-gluon backend \n\n# When installed using pip\nfrom monk.gluon_prototype import prototype\n\n\n# When installed manually (Uncomment the following)\n#import os\n#import sys\n#sys.path.append(\"monk_v1/\");\n#sys.path.append(\"monk_v1/monk/\");\n#from monk.gluon_prototype import prototype", "_____no_output_____" ] ], [ [ "<a id='2'></a>\n# Block Information", "_____no_output_____" ], [ "<a id='2_1'></a>\n## Visual structure", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='imgs/resnet_v2_bottleneck_without_downsample.png')", "_____no_output_____" ] ], [ [ "<a id='2_2'></a>\n## Layers in Branches\n\n - Number of branches: 2\n \n \n - Common Elements\n - batchnorm -> relu\n \n \n - Branch 1\n - identity\n \n \n - Branch 2\n - conv_1x1 -> batchnorm -> relu -> conv_3x3 -> batchnorm -> relu -> conv1x1\n \n \n - Branches merged using\n - Elementwise addition\n \n \n(See Appendix to read blogs on resnets)", "_____no_output_____" ], [ "<a id='3'></a>\n# Creating Block using monk debugger", "_____no_output_____" ] ], [ [ "# Imports and setup a project\n# To use pytorch backend - replace gluon_prototype with pytorch_prototype\n# To use keras backend - replace gluon_prototype with keras_prototype\n\nfrom monk.gluon_prototype import prototype\n\n# Create a sample project\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");", "Mxnet Version: 1.5.1\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\n" ] ], [ [ "<a id='3-1'></a>\n## Create the first branch", "_____no_output_____" ] ], [ [ "def first_branch():\n network = [];\n network.append(gtf.identity());\n return network;", "_____no_output_____" ], [ "# Debug the branch\nbranch_1 = first_branch()\nnetwork = [];\nnetwork.append(branch_1);\ngtf.debug_custom_model_design(network);", "_____no_output_____" ] ], [ [ "<a id='3-2'></a>\n## Create the second branch", "_____no_output_____" ] ], [ [ "def second_branch(output_channels=128, stride=1):\n network = [];\n \n # Bottleneck convolution \n network.append(gtf.convolution(output_channels=output_channels//4, kernel_size=1, stride=stride));\n network.append(gtf.batch_normalization());\n network.append(gtf.relu());\n \n #Bottleneck convolution\n network.append(gtf.convolution(output_channels=output_channels//4, kernel_size=1, stride=stride));\n network.append(gtf.batch_normalization());\n network.append(gtf.relu());\n \n #Normal convolution\n network.append(gtf.convolution(output_channels=output_channels, kernel_size=1, stride=1));\n return network;", "_____no_output_____" ], [ "# Debug the branch\nbranch_2 = second_branch(output_channels=128, stride=1)\nnetwork = [];\nnetwork.append(branch_2);\ngtf.debug_custom_model_design(network);", "_____no_output_____" ] ], [ [ "<a id='3-3'></a>\n## Merge the branches", "_____no_output_____" ] ], [ [ "\ndef final_block(output_channels=128, stride=1):\n network = [];\n \n #Common Elements\n network.append(gtf.batch_normalization());\n network.append(gtf.relu());\n \n #Create subnetwork and add branches\n subnetwork = [];\n branch_1 = first_branch()\n branch_2 = second_branch(output_channels=output_channels, stride=stride)\n subnetwork.append(branch_1);\n subnetwork.append(branch_2);\n \n # Add merging element\n subnetwork.append(gtf.add());\n \n # Add the subnetwork\n network.append(subnetwork)\n return network;", "_____no_output_____" ] ], [ [ "<a id='3-4'></a>\n## Debug the merged network", "_____no_output_____" ] ], [ [ "final = final_block(output_channels=64, stride=1)\nnetwork = [];\nnetwork.append(final);\ngtf.debug_custom_model_design(network);", "_____no_output_____" ] ], [ [ "<a id='3-5'></a>\n## Compile the network", "_____no_output_____" ] ], [ [ "gtf.Compile_Network(network, data_shape=(64, 224, 224), use_gpu=False);", "Model Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num of potentially trainable layers: 6\n Num of actual trainable layers: 6\n\n" ] ], [ [ "<a id='3-6'></a>\n## Run data through the network", "_____no_output_____" ] ], [ [ "import mxnet as mx\nx = np.zeros((1, 64, 224, 224));\nx = mx.nd.array(x);\ny = gtf.system_dict[\"local\"][\"model\"].forward(x);\nprint(x.shape, y.shape)", "(1, 64, 224, 224) (1, 64, 224, 224)\n" ] ], [ [ "<a id='3-7'></a>\n## Visualize network using netron", "_____no_output_____" ] ], [ [ "gtf.Visualize_With_Netron(data_shape=(64, 224, 224))", "Using Netron To Visualize\nNot compatible on kaggle\nCompatible only for Jupyter Notebooks\n\nStopping http://localhost:8080\nServing 'model-symbol.json' at http://localhost:8080\n" ] ], [ [ "<a id='4'></a>\n# Creating Using MONK LOW code API", "_____no_output_____" ], [ "<a id='4-1'></a>\n## Mxnet backend", "_____no_output_____" ] ], [ [ "from monk.gluon_prototype import prototype\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");\n\n\nnetwork = [];\n\n# Single line addition of blocks\nnetwork.append(gtf.resnet_v2_bottleneck_block(output_channels=64, downsample=False));\n\n\ngtf.Compile_Network(network, data_shape=(64, 224, 224), use_gpu=False);\n", "Mxnet Version: 1.5.1\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num of potentially trainable layers: 6\n Num of actual trainable layers: 6\n\n" ] ], [ [ "<a id='4-2'></a>\n## Pytorch backend\n\n - Only the import changes", "_____no_output_____" ] ], [ [ "#Change gluon_prototype to pytorch_prototype\nfrom monk.pytorch_prototype import prototype\n\n\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");\n\n\nnetwork = [];\n\n# Single line addition of blocks\nnetwork.append(gtf.resnet_v2_bottleneck_block(output_channels=64, downsample=False));\n\n\ngtf.Compile_Network(network, data_shape=(64, 224, 224), use_gpu=False);", "Pytorch Version: 1.2.0\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num layers in model: 6\n Num trainable layers: 6\n\n" ] ], [ [ "<a id='4-3'></a>\n## Keras backend\n\n - Only the import changes", "_____no_output_____" ] ], [ [ "#Change gluon_prototype to keras_prototype\nfrom monk.keras_prototype import prototype\n\n\ngtf = prototype(verbose=1);\ngtf.Prototype(\"sample-project-1\", \"sample-experiment-1\");\n\n\nnetwork = [];\n\n# Single line addition of blocks\nnetwork.append(gtf.resnet_v2_bottleneck_block(output_channels=64, downsample=False));\n\n\ngtf.Compile_Network(network, data_shape=(64, 224, 224), use_gpu=False);", "Keras Version: 2.2.5\nTensorflow Version: 1.12.0\n\nExperiment Details\n Project: sample-project-1\n Experiment: sample-experiment-1\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/blocks/workspace/sample-project-1/sample-experiment-1/\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: Custom Model\n Num layers in model: 11\n Num trainable layers: 10\n\n" ] ], [ [ "<a id='5'></a>\n# Appendix", "_____no_output_____" ], [ "<a id='5-1'></a>\n## Study links\n - https://towardsdatascience.com/residual-blocks-building-blocks-of-resnet-fd90ca15d6ec\n - https://medium.com/@MaheshNKhatri/resnet-block-explanation-with-a-terminology-deep-dive-989e15e3d691\n - https://medium.com/analytics-vidhya/understanding-and-implementation-of-residual-networks-resnets-b80f9a507b9c\n - https://hackernoon.com/resnet-block-level-design-with-deep-learning-studio-part-1-727c6f4927ac", "_____no_output_____" ], [ "<a id='5-2'></a>\n## Creating block using traditional Mxnet\n\n - Code credits - https://mxnet.incubator.apache.org/", "_____no_output_____" ] ], [ [ "# Traditional-Mxnet-gluon\nimport mxnet as mx\nfrom mxnet.gluon import nn\nfrom mxnet.gluon.nn import HybridBlock, BatchNorm\nfrom mxnet.gluon.contrib.nn import HybridConcurrent, Identity\nfrom mxnet import gluon, init, nd", "_____no_output_____" ], [ "\ndef _conv3x3(channels, stride, in_channels):\n return nn.Conv2D(channels, kernel_size=3, strides=stride, padding=1,\n use_bias=False, in_channels=in_channels)\n\nclass ResnetBlockV1(HybridBlock):\n def __init__(self, channels, stride, in_channels=0, **kwargs):\n super(ResnetBlockV1, self).__init__(**kwargs)\n \n #Common Elements\n self.bn0 = nn.BatchNorm();\n self.relu0 = nn.Activation('relu');\n \n #Branch - 1\n #Identity\n \n \n # Branch - 2\n self.body = nn.HybridSequential(prefix='')\n self.body.add(nn.Conv2D(channels//4, kernel_size=1, strides=stride,\n use_bias=False, in_channels=in_channels))\n self.body.add(nn.BatchNorm())\n self.body.add(nn.Activation('relu'))\n self.body.add(_conv3x3(channels//4, stride, in_channels))\n self.body.add(nn.BatchNorm())\n self.body.add(nn.Activation('relu'))\n self.body.add(nn.Conv2D(channels, kernel_size=1, strides=stride,\n use_bias=False, in_channels=in_channels))\n \n\n def hybrid_forward(self, F, x):\n x = self.bn0(x);\n x = self.relu0(x);\n \n residual = x\n x = self.body(x)\n x = residual+x\n return x", "_____no_output_____" ], [ "# Invoke the block\nblock = ResnetBlockV1(64, 1)\n\n# Initialize network and load block on machine\nctx = [mx.cpu()];\nblock.initialize(init.Xavier(), ctx = ctx);\nblock.collect_params().reset_ctx(ctx)\nblock.hybridize()\n\n# Run data through network\nx = np.zeros((1, 64, 224, 224));\nx = mx.nd.array(x);\ny = block.forward(x);\nprint(x.shape, y.shape)\n\n\n# Export Model to Load on Netron\nblock.export(\"final\", epoch=0);\n\nnetron.start(\"final-symbol.json\", port=8082)", "(1, 64, 224, 224) (1, 64, 224, 224)\nServing 'final-symbol.json' at http://localhost:8082\n" ] ], [ [ "<a id='5-3'></a>\n## Creating block using traditional Pytorch\n\n - Code credits - https://pytorch.org/", "_____no_output_____" ] ], [ [ "# Traiditional-Pytorch\nimport torch\nfrom torch import nn\nfrom torch.jit.annotations import List\nimport torch.nn.functional as F", "_____no_output_____" ], [ "def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass ResnetBottleNeckBlock(nn.Module):\n expansion = 1\n __constants__ = ['downsample']\n\n def __init__(self, inplanes, planes, stride=1, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(ResnetBottleNeckBlock, self).__init__()\n \n norm_layer = nn.BatchNorm2d\n \n #Common elements\n self.bn0 = norm_layer(inplanes);\n self.relu0 = nn.ReLU(inplace=True);\n \n \n # Branch - 1\n #Identity\n \n \n # Branch - 2\n self.conv1 = conv1x1(inplanes, planes//4, stride)\n self.bn1 = norm_layer(planes//4)\n self.relu1 = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes//4, planes//4, stride)\n self.bn2 = norm_layer(planes//4)\n self.relu2 = nn.ReLU(inplace=True)\n \n self.conv3 = conv1x1(planes//4, planes)\n \n self.stride = stride\n\n self.relu = nn.ReLU(inplace=True)\n \n def forward(self, x):\n x = self.bn0(x);\n x = self.relu0(x); \n \n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n \n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu2(out)\n\n out = self.conv3(out)\n\n out += identity\n\n return out", "_____no_output_____" ], [ "# Invoke the block\nblock = ResnetBottleNeckBlock(64, 64, stride=1);\n\n# Initialize network and load block on machine\nlayers = []\nlayers.append(block);\nnet = nn.Sequential(*layers);\n\n# Run data through network\nx = torch.randn(1, 64, 224, 224)\ny = net(x)\nprint(x.shape, y.shape);\n\n# Export Model to Load on Netron\ntorch.onnx.export(net, # model being run\n x, # model input (or a tuple for multiple inputs)\n \"model.onnx\", # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=10, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['output'], # the model's output names\n dynamic_axes={'input' : {0 : 'batch_size'}, # variable lenght axes\n 'output' : {0 : 'batch_size'}})\nnetron.start('model.onnx', port=9998);\n", "torch.Size([1, 64, 224, 224]) torch.Size([1, 64, 224, 224])\nServing 'model.onnx' at http://localhost:9998\n" ] ], [ [ "<a id='5-4'></a>\n## Creating block using traditional Keras\n\n - Code credits: https://keras.io/", "_____no_output_____" ] ], [ [ "# Traditional-Keras\nimport keras\nimport keras.layers as kla\nimport keras.models as kmo\nimport tensorflow as tf\nfrom keras.models import Model\nbackend = 'channels_last'\nfrom keras import layers", "_____no_output_____" ], [ "def resnet_conv_block(input_tensor,\n kernel_size,\n filters,\n stage,\n block,\n strides=(1, 1)):\n\n filters1, filters2, filters3 = filters\n bn_axis = 3\n \n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n \n #Common Elements\n start = layers.BatchNormalization(axis=bn_axis, name=bn_name_base + '0a')(input_tensor)\n start = layers.Activation('relu')(start)\n \n # Branch - 1\n # Identity\n shortcut = start\n \n \n # Branch - 2\n x = layers.Conv2D(filters1, (1, 1), strides=strides,\n kernel_initializer='he_normal',\n name=conv_name_base + '2a')(start)\n x = layers.BatchNormalization(axis=bn_axis, name=bn_name_base + '2a')(x)\n x = layers.Activation('relu')(x)\n \n x = layers.Conv2D(filters2, (3, 3), strides=strides,\n kernel_initializer='he_normal',\n name=conv_name_base + '2b', padding=\"same\")(x)\n x = layers.BatchNormalization(axis=bn_axis, name=bn_name_base + '2b')(x)\n x = layers.Activation('relu')(x)\n\n x = layers.Conv2D(filters3, (1, 1),\n kernel_initializer='he_normal',\n name=conv_name_base + '2c')(x);\n\n \n x = layers.add([x, shortcut])\n x = layers.Activation('relu')(x)\n return x\n\n\ndef create_model(input_shape, kernel_size, filters, stage, block):\n img_input = layers.Input(shape=input_shape);\n x = resnet_conv_block(img_input, kernel_size, filters, stage, block) \n return Model(img_input, x);", "_____no_output_____" ], [ "# Invoke the block\nkernel_size=3;\nfilters=[16, 16, 64];\ninput_shape=(224, 224, 64);\nmodel = create_model(input_shape, kernel_size, filters, 0, \"0\");\n\n# Run data through network\nx = tf.placeholder(tf.float32, shape=(1, 224, 224, 64))\ny = model(x)\nprint(x.shape, y.shape)\n\n# Export Model to Load on Netron\nmodel.save(\"final.h5\");\nnetron.start(\"final.h5\", port=8082)", "(1, 224, 224, 64) (1, 224, 224, 64)\n\nStopping http://localhost:8082\nServing 'final.h5' at http://localhost:8082\n" ] ], [ [ "# Goals Completed\n\n### 1. Learn to implement Resnet V2 Bottleneck Block (Type - 1) using monk\n - Monk's Keras\n - Monk's Pytorch\n - Monk's Mxnet\n \n### 2. Use network Monk's debugger to create complex blocks \n\n\n### 3. Understand how syntactically different it is to implement the same using\n - Traditional Keras\n - Traditional Pytorch\n - Traditional Mxnet", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "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" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
d037b33990eaec3f9e582ea937801bbb495ff5ca
35,412
ipynb
Jupyter Notebook
MovieLens Kaggle Extract.ipynb
AKumar1-lab/Movies_ETL
b35679108c8d054cb91c30c60767c30a856fab9a
[ "MIT" ]
null
null
null
MovieLens Kaggle Extract.ipynb
AKumar1-lab/Movies_ETL
b35679108c8d054cb91c30c60767c30a856fab9a
[ "MIT" ]
null
null
null
MovieLens Kaggle Extract.ipynb
AKumar1-lab/Movies_ETL
b35679108c8d054cb91c30c60767c30a856fab9a
[ "MIT" ]
null
null
null
39.610738
5,548
0.478792
[ [ [ "import pandas as pd", "_____no_output_____" ], [ "file_dir = \"./Resources/\"", "_____no_output_____" ], [ "kaggle_metadata = pd.read_csv(f'{file_dir}movies_metadata.csv', low_memory=False)\nratings = pd.read_csv(f'{file_dir}ratings.csv')", "_____no_output_____" ], [ "kaggle_metadata.sample(n=5)", "_____no_output_____" ], [ "ratings.sample(n=5)", "_____no_output_____" ], [ "kaggle_metadata.dtypes", "_____no_output_____" ], [ "kaggle_metadata['adult'].value_counts()", "_____no_output_____" ], [ "kaggle_metadata[~kaggle_metadata['adult'].isin(['True','False'])]", "_____no_output_____" ], [ "kaggle_metadata = kaggle_metadata[kaggle_metadata['adult'] == 'False'].drop('adult',axis='columns')", "_____no_output_____" ], [ "kaggle_metadata['video'].value_counts()", "_____no_output_____" ], [ "kaggle_metadata['video'] == 'True'", "_____no_output_____" ], [ "kaggle_metadata['video'] = kaggle_metadata['video'] == 'True'", "_____no_output_____" ], [ "kaggle_metadata['budget'] = kaggle_metadata['budget'].astype(int)\nkaggle_metadata['id'] = pd.to_numeric(kaggle_metadata['id'], errors='raise')\nkaggle_metadata['popularity'] = pd.to_numeric(kaggle_metadata['popularity'], errors='raise')", "_____no_output_____" ], [ "kaggle_metadata['release_date'] = pd.to_datetime(kaggle_metadata['release_date'])", "_____no_output_____" ], [ "ratings.info(null_counts=True)", "<ipython-input-15-ed915c4d3989>:1: FutureWarning: null_counts is deprecated. Use show_counts instead\n ratings.info(null_counts=True)\n" ], [ "pd.to_datetime(ratings['timestamp'], unit='s')", "_____no_output_____" ], [ "ratings['timestamp'] = pd.to_datetime(ratings['timestamp'], unit='s')", "_____no_output_____" ], [ "pd.options.display.float_format = '{:20,.2f}'.format\nratings['rating'].plot(kind='hist')\nratings['rating'].describe()", "_____no_output_____" ], [ "# Competing data:\n# Wiki Movielens Resolution\n#--------------------------------------------------------------------------\n# title_wiki title_kaggle\n# running_time runtime\n# budget_wiki budget_kaggle\n# box_office revenue\n# release_date_wiki release_date_kaggle\n# Language original_language\n# Production company(s) production_companies", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d037b44c368c5854c64b9315080ed59d9d68fe0a
46,445
ipynb
Jupyter Notebook
convert/Script/02 - NetworkInspection - LinkStats.ipynb
tscore-utc/scenarios
28c2617d61cd13a89ef28f56cf70f22444af189e
[ "Apache-2.0" ]
1
2021-07-13T23:25:23.000Z
2021-07-13T23:25:23.000Z
convert/Script/02 - NetworkInspection - LinkStats.ipynb
tscore-utc/scenarios
28c2617d61cd13a89ef28f56cf70f22444af189e
[ "Apache-2.0" ]
21
2020-12-02T20:08:31.000Z
2021-05-19T23:37:27.000Z
convert/Script/02 - NetworkInspection - LinkStats.ipynb
tscore-utc/scenarios
28c2617d61cd13a89ef28f56cf70f22444af189e
[ "Apache-2.0" ]
1
2020-11-25T15:16:23.000Z
2020-11-25T15:16:23.000Z
43.32556
256
0.465798
[ [ [ "import pandas as pd\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pyproj import CRS\nimport pathlib\nfrom pathlib import Path\nfrom shapely import wkt\nfrom tqdm import tqdm\n\nimport math\nimport codecs\n\nfrom shapely import wkt\n\nimport folium\nfrom folium import features\nfrom folium import plugins\n\nimport gzip\nfrom xml.etree.ElementTree import Element, SubElement, Comment, tostring\nimport xml.etree.ElementTree as ET\n\n# to read the excel \nfrom openpyxl import load_workbook\nfrom openpyxl import Workbook\n\n# import folium\nfrom shapely.geometry import LineString, MultiLineString\nimport branca.colormap as cmp\nfrom folium.plugins import Search\n\nfrom tqdm import tqdm\nimport time\n\nimport datetime\nfrom datetime import timedelta\n\n# set the working directory\nBASE_DIR = Path.cwd()\n", "_____no_output_____" ], [ "BASE_DIR", "_____no_output_____" ], [ "# save as geojson\ndef get_foldercreation_inf():\n fname = pathlib.Path(\"../SF_all_trips/sf-tscore-all-trips-20PCsample-updatedRideHailFleet-updatedParking__etg/ITERS/it.4/4.linkstats.csv.gz\")\n assert fname.exists(), f'No such file: {fname}' # check that the file exists\n ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)\n return ctime\n# return ctime.strftime(\"%Y-%m-%d\")\n\ndef get_dataframe(_time):\n # linkstats file\n linkstats = pd.read_csv(\"../SF_all_trips/sf-tscore-all-trips-20PCsample-updatedRideHailFleet-updatedParking__etg/ITERS/it.4/4.linkstats.csv.gz\", compression=\"gzip\", low_memory=False)\n time = int(_time)\n linkstats = linkstats[linkstats[\"hour\"]==(time)].copy()\n linkstats=linkstats.add_prefix(\"linkstats_\")\n linkstats.rename(columns={('linkstats_link'): 'id'}, inplace=True)\n linkstats[\"id\"] = linkstats[\"id\"].astype('string')\n date_time = get_foldercreation_inf()\n if int(_time)<24:\n date_time = date_time.strftime(\"%Y-%m-%d\")\n time_stamp = f'{int(_time):02d}'\n linkstats[\"date_time\"] = (date_time + \" \" + \"{}:00:00\".format(f'{int(_time):02d}'))\n else:\n date_time = get_foldercreation_inf() + datetime.timedelta(days=1)\n date_time = date_time.strftime(\"%Y-%m-%d\")\n new_time = int(_time) - 24\n linkstats[\"date_time\"] = (date_time + \" \" + \"{}:00:00\".format(f'{abs(int(new_time)):02d}')) \n \n return linkstats\n\n\n# read the road network\nsf_roadnetwork = gpd.read_file(BASE_DIR.parent.joinpath( 'Network',\"sfNetwork.geojsonl\"))\nsf_roadnetwork = sf_roadnetwork[[\"id\",\"modes\",\"length\",\"lanes\",\"from\",\"to\",\"capacity\",\"geometry\"]]\nsftimevariantnetwork =pd.DataFrame()\n\n\nfor time_hour in tqdm(range(0,30)):\n # get the hour and filter the linkstat file\n linkstats = get_dataframe(str(time_hour))\n # merge with featureclass of SF data\n comparision_network = sf_roadnetwork.merge(linkstats,on=\"id\").copy()\n \n # calculate the freespeed (mph), congested speed (mph), ratio (congestedsped/freespeed)\n # linkstats\n comparision_network[\"linkstats_freespeed_mph\"] = comparision_network[\"linkstats_freespeed\"]*2.23694\n comparision_network[\"linkstats_congspd_mph\"] = (comparision_network[\"linkstats_length\"]/comparision_network[\"linkstats_traveltime\"])*2.23694\n comparision_network[\"linkstats_ratio\"] = comparision_network[\"linkstats_congspd_mph\"] / comparision_network[\"linkstats_freespeed_mph\"] \n comparision_network[\"linkstats_vc_ratio\"] = comparision_network[\"linkstats_volume\"]*5 / comparision_network[\"capacity\"]\n \n if int(time_hour)==0:\n sftimevariantnetwork = comparision_network.copy()\n else:\n sftimevariantnetwork = pd.concat([sftimevariantnetwork,comparision_network], ignore_index=True)\n\n# lastly, export the network\n# sftimevariantnetwork.to_file(BASE_DIR.parent.joinpath(\"exported\", (\"sf_timevariantnetwork.geojson\")), driver='GeoJSON')", "100%|██████████████████████████████████████████████████████████████████████████████████| 30/30 [03:50<00:00, 7.67s/it]\n" ], [ "linkstats.head()", "_____no_output_____" ], [ "# sftimevariantnetwork.to_csv(BASE_DIR.parent.joinpath(\"exported\", (\"sf_timevariantnetwork.csv\")))", "_____no_output_____" ], [ "# read the road network, incase it is already saved in the geojson file\n# sftimevariantnetwork = gpd.read_file(BASE_DIR.parent.joinpath(\"exported\", (\"sf_timevariantnetwork.geojson\")))\n\n# keep only selected columns fields\nsf_timevariantnetwork = sftimevariantnetwork[[\"id\", \"modes\",\"length\",\"lanes\",\"capacity\",\"geometry\",\n 'linkstats_freespeed','linkstats_volume', 'linkstats_traveltime', \n 'date_time', 'linkstats_freespeed_mph', 'linkstats_congspd_mph', 'linkstats_ratio', \"linkstats_vc_ratio\"]]\nsf_timevariantnetwork['date_time']=pd.to_datetime(sf_timevariantnetwork['date_time']).dt.strftime('%Y-%m-%dT%H:%M:%S')\nsf_timevariantnetwork[\"time\"] = pd.to_datetime(sf_timevariantnetwork[\"date_time\"]).dt.strftime('%Y-%m-%dT%H:%M:%S')\n\n\n# add more green shades for 85% --> 100%\n# green_shades = ['#008000', '#198c19', '#329932', '#4ca64c', '#66b266', '#7fbf7f', '#99cc99', '#b2d8b2', '#cce5cc', '#e5f2e5']\n# colors for congstd speed/freespeed ratio\ncolor_range_pct = [\"#ff0000\",\"#ff6666\",\"#ffb2b2\",\"#ffdb99\",\"#ffc966\", \"#ffa500\",'#e5f2e5','#cce5cc','#b2d8b2','#99cc99','#7fbf7f','#66b266','#4ca64c','#329932', '#198c19','#008000']\n# color_range_pct = [\"#ff0000\",\"#ff6666\",\"#ffb2b2\",\"#ffdb99\",\"#ffc966\", \"#ffa500\",\"#cce5cc\",\"#99cc99\",\"#66b266\",\"#008000\"]\nstep_pct = cmp.StepColormap(\n color_range_pct,\n vmin=0, vmax=1,\n index=[0,0.2,0.3,0.5,.6,0.7,0.80,0.85, 0.87,0.89,0.91,0.93,0.95,0.97,0.99,1.00], #for change in the colors, not used fr linear\n caption='% Speeds Difference' #Caption for Color scale or Legend\n)\n\n# colors for congstd speed/freespeed ratio\ncolor_range_pct_vc = ['#008000', '#329932', '#66b266', '#99cc99', '#cce5cc', '#e5f2e5', # green shade\n '#ffa500', \"#ffb732\",'#ffc966', '#ffdb99', \"#ffedcc\", # orange shade\n '#ffe5e5', '#ffcccc','#ffb2b2','#ff9999','#ff6666', '#ff3232', '#ff0000' ] # red shade\n# color_range_pct = [\"#ff0000\",\"#ff6666\",\"#ffb2b2\",\"#ffdb99\",\"#ffc966\", \"#ffa500\",\"#cce5cc\",\"#99cc99\",\"#66b266\",\"#008000\"]\nstep_pct_vc = cmp.StepColormap(\n color_range_pct_vc,\n vmin=0, vmax=1,\n index=[0,0.1,0.2,0.3,0.4,0.5,\n 0.55,0.6,0.65,0.7,0.75,\n 0.80,0.85,0.90,0.95,0.97,0.99,1.00], #for change in the colors, not used fr linear\n caption='Volume-to-Capacity ratio' #Caption for Color scale or Legend\n)\n\n# colors for congested speed and freespeed \ncolor_range = [\"#ff0000\",\"#ff6666\",\"#ffb2b2\",\"#ffa500\",\"#ffc966\",\"#ffdb99\", \"#cce5cc\",\"#99cc99\",\"#66b266\",\"#008000\"]\nstep = cmp.StepColormap(color_range,vmin=0, vmax=100,index=[0,5,10,15,25,35,45,55,65,100], #for change in the colors, not used fr linear\n caption=' Speeds (mph)' #Caption for Color scale or Legend\n )\n\n\ndef getColorMap_pct(x):\n return str(step_pct(x))\n\ndef getColorMap_pct_vc(x):\n return str(step_pct_vc(x))\n\ndef getColorMap(x):\n return str(step(x))\n\nsf_timevariantnetwork[\"fillColor_ratio\"] = sf_timevariantnetwork[\"linkstats_ratio\"].apply(getColorMap_pct)\nsf_timevariantnetwork[\"fillColor_vc_ratio\"] = sf_timevariantnetwork[\"linkstats_vc_ratio\"].apply(getColorMap_pct_vc)\nsf_timevariantnetwork[\"fillColor_freespeed_mph\"] = sf_timevariantnetwork[\"linkstats_freespeed_mph\"].apply(getColorMap)\nsf_timevariantnetwork[\"fillColor_congspd_mph\"] = sf_timevariantnetwork[\"linkstats_congspd_mph\"].apply(getColorMap)", "C:\\Users\\Transportlab\\anaconda3\\envs\\geo_env\\lib\\site-packages\\geopandas\\geodataframe.py:1351: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n super().__setitem__(key, value)\n" ], [ "def coords(geom):\n return list(geom.coords)\n\nsf_timevariantnetwork['points'] = sf_timevariantnetwork.apply(lambda row: coords(row.geometry), axis=1)\n\n# groupby and aggreage columns by segment_links\ndf1 = sf_timevariantnetwork.groupby('id').agg({'modes':'first',\n 'length':'first',\n 'lanes':list,\n 'capacity':list,\n 'geometry':'first',\n 'linkstats_freespeed':list,\n 'linkstats_volume':list,\n 'linkstats_traveltime':list,\n 'date_time':list,\n 'linkstats_freespeed_mph':list,\n 'linkstats_congspd_mph':list,\n 'linkstats_ratio':list,\n 'linkstats_vc_ratio':list,\n 'time':list,\n 'fillColor_ratio':list,\n 'linkstats_volume':list,\n 'linkstats_traveltime':list,\n 'fillColor_freespeed_mph':list,\n 'fillColor_congspd_mph':list,\n 'fillColor_vc_ratio':list,\n 'points':'first'}).reset_index()", "_____no_output_____" ], [ "# Create timemap for ratio_congestedspeed_freespeed\n\ndef coords(geom):\n return list(geom.coords)\n\nfeatures_ratio = [\n {\n 'type':'Feature',\n \"geometry\":{\n 'type': 'LineString',\n 'coordinates': coords(d.geometry),\n },\n 'properties': {\n 'times': d['time'],\n 'color': \"black\",\n 'colors':d[\"fillColor_ratio\"],\n \"weight\":0.6,\n \"fillOpacity\": 0.4,\n }\n }\n for _,d in df1.iterrows()\n]\n\nfrom jinja2 import Template\n_template = Template(\"\"\"\n {% macro script(this, kwargs) %} \n \n L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({\n _getDisplayDateFormat: function(date){\n var newdate = new moment(date);\n console.log(newdate)\n return newdate.format(\"{{this.date_options}}\");\n }\n });\n {{this._parent.get_name()}}.timeDimension = L.timeDimension(\n {\n period: {{ this.period|tojson }},\n }\n );\n var timeDimensionControl = new L.Control.TimeDimensionCustom(\n {{ this.options|tojson }}\n );\n {{this._parent.get_name()}}.addControl(this.timeDimensionControl);\n var geoJsonLayer = L.geoJson({{this.data}}, {\n pointToLayer: function (feature, latLng) {\n if (feature.properties.icon == 'marker') {\n if(feature.properties.iconstyle){\n return new L.Marker(latLng, {\n icon: L.icon(feature.properties.iconstyle)});\n }\n //else\n return new L.Marker(latLng);\n }\n if (feature.properties.icon == 'circle') {\n if (feature.properties.iconstyle) {\n return new L.circleMarker(latLng, feature.properties.iconstyle)\n };\n //else\n return new L.circleMarker(latLng);\n }\n //else\n return new L.Marker(latLng);\n },\n style: function(feature) {\n lastIdx=feature.properties.colors.length-1\n currIdx=feature.properties.colors.indexOf(feature.properties.color);\n if(currIdx==lastIdx){\n feature.properties.color = feature.properties.colors[currIdx+1] \n }\n else{\n feature.properties.color =feature.properties.colors[currIdx+1] \n }\n return {color: feature.properties.color}\n },\n onEachFeature: function(feature, layer) {\n if (feature.properties.popup) {\n layer.bindPopup(feature.properties.popup);\n }\n }\n })\n var {{this.get_name()}} = L.timeDimension.layer.geoJson(\n geoJsonLayer,\n {\n updateTimeDimension: true,\n addlastPoint: {{ this.add_last_point|tojson }},\n duration: {{ this.duration }},\n }\n ).addTo({{this._parent.get_name()}});\n {% endmacro %}\n \"\"\")\n\n\nimport folium\nfrom folium.plugins import TimestampedGeoJson\n\nm = folium.Map(location=[37.760015, -122.447110], zoom_start=13, tiles=\"cartodbpositron\")\n\nt=TimestampedGeoJson({\n 'type': 'FeatureCollection',\n 'features': features_ratio,\n}, transition_time=1500,loop=True,period='PT1H', add_last_point=False,auto_play=True)\nt._template=_template\nt.add_to(m)\nstep_pct.add_to(m)\n\n# Add title\nmap_title = \"Ratio between Congested Speed (mph) and Free Speed (mph)\"\ntitle_html = '''\n <h3 align=\"center\" style=\"font-size:16px\"><b>{}</b></h3>\n '''.format(map_title) \nm.get_root().html.add_child(folium.Element(title_html))\n\nfile_name = BASE_DIR.parent.joinpath(\"exported\", (\"linkstat_ratio_timemap.html\"))\nm.save(str(file_name))\n# m", "_____no_output_____" ], [ "# Create timemap for v/c ratio\n\ndef coords(geom):\n return list(geom.coords)\n\nfeatures_ratio = [\n {\n 'type':'Feature',\n \"geometry\":{\n 'type': 'LineString',\n 'coordinates': coords(d.geometry),\n },\n 'properties': {\n 'times': d['time'],\n 'color': \"black\",\n 'colors':d[\"fillColor_vc_ratio\"],\n \"weight\":0.6,\n \"fillOpacity\": 0.4,\n }\n }\n for _,d in df1.iterrows()\n]\n\nfrom jinja2 import Template\n_template = Template(\"\"\"\n {% macro script(this, kwargs) %} \n \n L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({\n _getDisplayDateFormat: function(date){\n var newdate = new moment(date);\n console.log(newdate)\n return newdate.format(\"{{this.date_options}}\");\n }\n });\n {{this._parent.get_name()}}.timeDimension = L.timeDimension(\n {\n period: {{ this.period|tojson }},\n }\n );\n var timeDimensionControl = new L.Control.TimeDimensionCustom(\n {{ this.options|tojson }}\n );\n {{this._parent.get_name()}}.addControl(this.timeDimensionControl);\n var geoJsonLayer = L.geoJson({{this.data}}, {\n pointToLayer: function (feature, latLng) {\n if (feature.properties.icon == 'marker') {\n if(feature.properties.iconstyle){\n return new L.Marker(latLng, {\n icon: L.icon(feature.properties.iconstyle)});\n }\n //else\n return new L.Marker(latLng);\n }\n if (feature.properties.icon == 'circle') {\n if (feature.properties.iconstyle) {\n return new L.circleMarker(latLng, feature.properties.iconstyle)\n };\n //else\n return new L.circleMarker(latLng);\n }\n //else\n return new L.Marker(latLng);\n },\n style: function(feature) {\n lastIdx=feature.properties.colors.length-1\n currIdx=feature.properties.colors.indexOf(feature.properties.color);\n if(currIdx==lastIdx){\n feature.properties.color = feature.properties.colors[currIdx+1] \n }\n else{\n feature.properties.color =feature.properties.colors[currIdx+1] \n }\n return {color: feature.properties.color}\n },\n onEachFeature: function(feature, layer) {\n if (feature.properties.popup) {\n layer.bindPopup(feature.properties.popup);\n }\n }\n })\n var {{this.get_name()}} = L.timeDimension.layer.geoJson(\n geoJsonLayer,\n {\n updateTimeDimension: true,\n addlastPoint: {{ this.add_last_point|tojson }},\n duration: {{ this.duration }},\n }\n ).addTo({{this._parent.get_name()}});\n {% endmacro %}\n \"\"\")\n\n\nimport folium\nfrom folium.plugins import TimestampedGeoJson\n\nm = folium.Map(location=[37.760015, -122.447110], zoom_start=13, tiles=\"cartodbpositron\")\n\nt=TimestampedGeoJson({\n 'type': 'FeatureCollection',\n 'features': features_ratio,\n}, transition_time=1500,loop=True,period='PT1H', add_last_point=False,auto_play=True)\nt._template=_template\nt.add_to(m)\nstep_pct_vc.add_to(m)\n\n# Add title\nmap_title = \"Volume-to-Capacity Ratio\"\ntitle_html = '''\n <h3 align=\"center\" style=\"font-size:16px\"><b>{}</b></h3>\n '''.format(map_title) \nm.get_root().html.add_child(folium.Element(title_html))\n\nfile_name = BASE_DIR.parent.joinpath(\"exported\",\"extended_run\",(\"linkst_vc_ratio_timemap.html\"))\nm.save(str(file_name))\n# m", "_____no_output_____" ], [ "# Create timemap for freespeed (mph)\n\ndef coords(geom):\n return list(geom.coords)\n\nfeatures_freespeed = [\n {\n 'type':'Feature',\n \"geometry\":{\n 'type': 'LineString',\n 'coordinates': coords(d.geometry),\n },\n 'properties': {\n 'times': d['time'],\n 'color': \"black\",\n 'colors':d[\"fillColor_freespeed_mph\"],\n 'weight':0.6,\n \"fillOpacity\": 0.4, \n }\n }\n for _,d in df1.iterrows()\n]\n\nfrom jinja2 import Template\n_template = Template(\"\"\"\n {% macro script(this, kwargs) %}\n L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({\n _getDisplayDateFormat: function(date){\n var newdate = new moment(date);\n console.log(newdate)\n return newdate.format(\"{{this.date_options}}\");\n }\n });\n {{this._parent.get_name()}}.timeDimension = L.timeDimension(\n {\n period: {{ this.period|tojson }},\n }\n );\n var timeDimensionControl = new L.Control.TimeDimensionCustom(\n {{ this.options|tojson }}\n );\n {{this._parent.get_name()}}.addControl(this.timeDimensionControl);\n var geoJsonLayer = L.geoJson({{this.data}}, {\n pointToLayer: function (feature, latLng) {\n if (feature.properties.icon == 'marker') {\n if(feature.properties.iconstyle){\n return new L.Marker(latLng, {\n icon: L.icon(feature.properties.iconstyle)});\n }\n //else\n return new L.Marker(latLng);\n }\n if (feature.properties.icon == 'circle') {\n if (feature.properties.iconstyle) {\n return new L.circleMarker(latLng, feature.properties.iconstyle)\n };\n //else\n return new L.circleMarker(latLng);\n }\n //else\n return new L.Marker(latLng);\n },\n style: function(feature) {\n lastIdx=feature.properties.colors.length-1\n currIdx=feature.properties.colors.indexOf(feature.properties.color);\n if(currIdx==lastIdx){\n feature.properties.color = feature.properties.colors[currIdx+1] \n }\n else{\n feature.properties.color =feature.properties.colors[currIdx+1] \n }\n return {color: feature.properties.color}\n },\n onEachFeature: function(feature, layer) {\n if (feature.properties.popup) {\n layer.bindPopup(feature.properties.popup);\n }\n }\n })\n var {{this.get_name()}} = L.timeDimension.layer.geoJson(\n geoJsonLayer,\n {\n updateTimeDimension: true,\n addlastPoint: {{ this.add_last_point|tojson }},\n duration: {{ this.duration }},\n }\n ).addTo({{this._parent.get_name()}});\n {% endmacro %}\n \"\"\")\n\n\nimport folium\nfrom folium.plugins import TimestampedGeoJson\n\nm = folium.Map(location=[37.760015, -122.447110], zoom_start=13, tiles=\"cartodbpositron\")\n# Add title\nmap_title = \"Free Speed (mph)\"\ntitle_html = '''\n <h3 align=\"center\" style=\"font-size:16px\"><b>{}</b></h3>\n '''.format(map_title) \nm.get_root().html.add_child(folium.Element(title_html))\n\nt=TimestampedGeoJson({\n 'type': 'FeatureCollection',\n 'features': features_freespeed,\n}, transition_time=1500,loop=True,period='PT1H', add_last_point=False,auto_play=True)\nt._template=_template\nt.add_to(m)\nstep.add_to(m)\n\nfile_name = BASE_DIR.parent.joinpath(\"exported\", (\"linkstat_freespeed_timemap.html\"))\nm.save(str(file_name))\n# m", "_____no_output_____" ], [ "# Create timemap for congested speed (mph)\n\ndef coords(geom):\n return list(geom.coords)\n\nfeatures_congestedspeed = [\n {\n 'type':'Feature',\n \"geometry\":{\n 'type': 'LineString',\n 'coordinates': coords(d.geometry),\n },\n 'properties': {\n 'times': d['time'],\n 'color': \"black\",\n 'colors':d[\"fillColor_congspd_mph\"],\n 'weight':0.6,\n \"fillOpacity\": 0.4,\n \n }\n }\n for _,d in df1.iterrows()\n]\n\nfrom jinja2 import Template\n_template = Template(\"\"\"\n {% macro script(this, kwargs) %}\n L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({\n _getDisplayDateFormat: function(date){\n var newdate = new moment(date);\n console.log(newdate)\n return newdate.format(\"{{this.date_options}}\");\n }\n });\n {{this._parent.get_name()}}.timeDimension = L.timeDimension(\n {\n period: {{ this.period|tojson }},\n }\n );\n var timeDimensionControl = new L.Control.TimeDimensionCustom(\n {{ this.options|tojson }}\n );\n {{this._parent.get_name()}}.addControl(this.timeDimensionControl);\n var geoJsonLayer = L.geoJson({{this.data}}, {\n pointToLayer: function (feature, latLng) {\n if (feature.properties.icon == 'marker') {\n if(feature.properties.iconstyle){\n return new L.Marker(latLng, {\n icon: L.icon(feature.properties.iconstyle)});\n }\n //else\n return new L.Marker(latLng);\n }\n if (feature.properties.icon == 'circle') {\n if (feature.properties.iconstyle) {\n return new L.circleMarker(latLng, feature.properties.iconstyle)\n };\n //else\n return new L.circleMarker(latLng);\n }\n //else\n return new L.Marker(latLng);\n },\n style: function(feature) {\n lastIdx=feature.properties.colors.length-1\n currIdx=feature.properties.colors.indexOf(feature.properties.color);\n if(currIdx==lastIdx){\n feature.properties.color = feature.properties.colors[currIdx+1] \n }\n else{\n feature.properties.color =feature.properties.colors[currIdx+1] \n }\n return {color: feature.properties.color}\n },\n onEachFeature: function(feature, layer) {\n if (feature.properties.popup) {\n layer.bindPopup(feature.properties.popup);\n }\n }\n })\n var {{this.get_name()}} = L.timeDimension.layer.geoJson(\n geoJsonLayer,\n {\n updateTimeDimension: true,\n addlastPoint: {{ this.add_last_point|tojson }},\n duration: {{ this.duration }},\n }\n ).addTo({{this._parent.get_name()}});\n {% endmacro %}\n \"\"\")\n\n\nimport folium\nfrom folium.plugins import TimestampedGeoJson\n\nm = folium.Map(location=[37.760015, -122.447110], zoom_start=13, tiles=\"cartodbpositron\")\n\n\nt=TimestampedGeoJson({\n 'type': 'FeatureCollection',\n 'features': features_congestedspeed,\n}, transition_time=1500,loop=True,period='PT1H', add_last_point=False,auto_play=True)\nt._template=_template\nt.add_to(m)\nstep.add_to(m)\n\n# Add title\nmap_title = \"Congested Speed (mph)\"\ntitle_html = '''\n <h3 align=\"center\" style=\"font-size:16px\"><b>{}</b></h3>\n '''.format(map_title) \nm.get_root().html.add_child(folium.Element(title_html))\n\n\nfile_name = BASE_DIR.parent.joinpath(\"exported\", (\"linkstat_congestedspeed_timemap.html\"))\nm.save(str(file_name))\n# m", "_____no_output_____" ], [ "# get map for each different time", "_____no_output_____" ], [ "# static maps for congestedspeed/freespeed\n\ndef get_dataframe(_time):\n # linkstats file\n linkstats = pd.read_csv(\"../SF_all_trips/sf-tscore-all-trips-20PCsample-updatedRideHailFleet-updatedParking__etg/ITERS/it.4/4.linkstats.csv.gz\", compression=\"gzip\", low_memory=False)\n# unmodified_linkstats = pd.read_csv(BASE_DIR.parent.joinpath(\"runs\", \"sf-tscore-int-int-trips-model-network-events-20PC-sample-bpr-func__tlm\",\"ITERS\",\"it.30\", \"30.linkstats_unmodified.csv.gz\"),compression=\"gzip\", low_memory=False)\n time = int(_time)\n linkstats = linkstats[linkstats[\"hour\"]==(time)].copy()\n linkstats=linkstats.add_prefix(\"linkstats_\")\n linkstats.rename(columns={('linkstats_link'): 'id'}, inplace=True)\n linkstats[\"id\"] = linkstats[\"id\"].astype('string')\n \n return linkstats\n\ndef highlight_function(feature):\n return {\"fillColor\": \"#ffff00\", \"color\": \"#ffff00\", \"weight\": 5,\"fillOpacity\": 0.40 }\n\n\ncolor_range_pct = [\"#ff0000\",\"#ff6666\",\"#ffb2b2\",\"#ffdb99\",\"#ffc966\", \"#ffa500\",'#e5f2e5','#cce5cc','#b2d8b2','#99cc99','#7fbf7f','#66b266','#4ca64c','#329932', '#198c19','#008000']\n\nstep_pct = cmp.StepColormap(\n color_range_pct,\n vmin=0, vmax=1,\n index=[0,0.2,0.3,0.5,.6,0.7,0.80,0.85, 0.87,0.89,0.91,0.93,0.95,0.97,0.99,1.00], #for change in the colors, not used fr linear\n caption='% Speeds Difference' #Caption for Color scale or Legend\n)\n\n# read the road network\nsf_roadnetwork = gpd.read_file(BASE_DIR.parent.joinpath(\"Network\", \"sfNetwork.geojsonl\"))\nsf_roadnetwork = sf_roadnetwork[[\"id\",\"modes\",\"length\",\"lanes\",\"from\",\"to\",\"capacity\",\"geometry\"]]\n\nfor time_hour in tqdm(range(0,30)):\n # set the map\n pct_m = folium.Map([37.760015, -122.447110], zoom_start=13, tiles=\"cartodbpositron\")\n # get the hour and filter the linkstat file\n linkstats = get_dataframe(str(time_hour))\n # merge with featureclass of SF data\n comparision_network = sf_roadnetwork.merge(linkstats,on=\"id\")\n \n # calculate the freespeed (mph), congested speed (mph), ratio (congestedsped/freespeed)\n # linkstats\n comparision_network[\"linkstats_freespeed_mph\"] = comparision_network[\"linkstats_freespeed\"]*2.23694\n comparision_network[\"linkstats_congspd_mph\"] = (comparision_network[\"linkstats_length\"]/comparision_network[\"linkstats_traveltime\"])*2.23694\n comparision_network[\"linkstats_ratio\"] = comparision_network[\"linkstats_congspd_mph\"] / comparision_network[\"linkstats_freespeed_mph\"]\n \n time_stamp = \"\"\n # folium\n if time_hour<30: \n time_stamp = f'{time_hour:02d}'\n layer_name = str(time_stamp) \n \n \n# layer_name=str(str(time_hour) + (' am' if time_hour < 12 else ' pm'))\n ratio_feature_group = folium.FeatureGroup(name=layer_name)\n \n pct_feature_group = folium.GeoJson(comparision_network, \n name = (\"Hour - \" + layer_name),\n style_function=lambda x: {\n \"fillColor\": step_pct(x[\"properties\"][\"linkstats_ratio\"]),\n \"color\": step_pct(x[\"properties\"][\"linkstats_ratio\"]),\n \"fillOpacity\": 0.2,\n \"weight\":1,\n },\n tooltip=folium.GeoJsonTooltip(fields=[\"id\",\"length\", \"linkstats_freespeed_mph\", \"linkstats_traveltime\",\"linkstats_congspd_mph\"], \n aliases=[\"Link ID\", \"Segment Length (m)\", \"Freespeed (mph)\", \"Travel time (sec)\", \"Congested Speed (mph)\"], localize=True),\n popup = folium.GeoJsonPopup(fields=[\"id\",\"length\", \"linkstats_freespeed_mph\", \"linkstats_traveltime\",\"linkstats_congspd_mph\"], \n aliases=[\"Link ID\", \"Segment Length (m)\", \"Freespeed (mph)\", \"Travel time (sec)\", \"Congested Speed (mph)\"], localize=True),\n highlight_function=highlight_function,\n zoom_on_click=True\n ).add_to(ratio_feature_group)\n # Add search functionality to the map\n search_link = Search(layer=pct_feature_group, geom_type=\"LineString\", placeholders = \"Search for Link ID\", \n collapsed=\"False\", search_label = 'id', search_zoom = 17, position='topleft',\n ).add_to(pct_m)\n \n ratio_feature_group.add_to(pct_m)\n folium.LayerControl().add_to(pct_m)\n \n map_title = \"Ratio between Congested Speed and Free Speed\"\n title_html = '''<h3 align=\"center\" style=\"font-size:16px\"><b>{}</b></h3>'''.format(map_title)\n pct_m.get_root().html.add_child(folium.Element(title_html))\n # save the file\n file_name = BASE_DIR.parent.joinpath(\"exported\", (\"linkstat_ratio_timemap_{}.html\").format(time_stamp))\n pct_m.save(str(file_name))", "100%|██████████████████████████████████████████████████████████████████████████████████| 30/30 [32:58<00:00, 65.95s/it]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d037bf708d1a623436f3bba20f3570ef3a645de9
13,064
ipynb
Jupyter Notebook
RocksResnetTrainer.ipynb
malcolmrite-dsi/RockVideoClassifier
6458d5ee3c87fc2077e2bb32474e447c3a95de24
[ "MIT" ]
null
null
null
RocksResnetTrainer.ipynb
malcolmrite-dsi/RockVideoClassifier
6458d5ee3c87fc2077e2bb32474e447c3a95de24
[ "MIT" ]
null
null
null
RocksResnetTrainer.ipynb
malcolmrite-dsi/RockVideoClassifier
6458d5ee3c87fc2077e2bb32474e447c3a95de24
[ "MIT" ]
null
null
null
33.670103
250
0.481246
[ [ [ "<a href=\"https://colab.research.google.com/github/malcolmrite-dsi/RockVideoClassifier/blob/main/RocksResnetTrainer.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "import tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten, Dropout\nfrom tensorflow.keras.applications.resnet import preprocess_input\nfrom tensorflow.keras.applications import xception\nimport pandas as pd\nimport PIL\nimport matplotlib.pyplot as plt\nimport os\nimport shutil", "_____no_output_____" ] ], [ [ "# Training", "_____no_output_____" ] ], [ [ "train_datagen = keras.preprocessing.image.ImageDataGenerator(validation_split=0.2, preprocessing_function=preprocess_input)\n\ntrain_generator = train_datagen.flow_from_directory(\n '/content/drive/My Drive/Module 2 shared folder/samples',\n subset=\"training\",\n seed=3,\n target_size=(64, 64),\n batch_size=64,\n class_mode='categorical')\n\nval_generator = train_datagen.flow_from_directory( '/content/drive/My Drive/Module 2 shared folder/samples', \n subset=\"validation\",\n seed=3,\n target_size=(64, 64),\n batch_size=64,\n class_mode='categorical')", "Found 3132 images belonging to 5 classes.\nFound 781 images belonging to 5 classes.\n" ], [ "train_datagen = keras.preprocessing.image.ImageDataGenerator(preprocessing_function=preprocess_input)\n\ntrain_generator = train_datagen.flow_from_directory(\n '/content/drive/My Drive/Module 2 shared folder/samples',\n subset=\"training\",\n seed=3,\n target_size=(64, 64),\n batch_size=64,\n class_mode='categorical')", "Found 3913 images belonging to 5 classes.\n" ], [ "resnet = keras.applications.ResNet50(include_top=False, pooling=\"max\", input_shape=(64,64,3))", "_____no_output_____" ], [ "# mark loaded layers as not trainable\nfor layer in resnet.layers:\n layer.trainable = False \n", "_____no_output_____" ], [ "data_augmentation = tf.keras.Sequential([\n keras.layers.experimental.preprocessing.RandomFlip(\"horizontal_and_vertical\"),\n #keras.layers.experimental.preprocessing.RandomRotation(0.2),\n])", "_____no_output_____" ], [ "# mark loaded layers as not trainable\n#for layer in resnet.layers:\n\t#layer.trainable = False \n\nflat = Flatten()(resnet.layers[-1].output)\ndense = Dense(1024, activation='relu')(flat)\noutput = Dense(5, activation='softmax')(dense)\nmodel = Model(inputs=resnet.inputs, outputs=output)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ], [ "model.compile(loss=\"categorical_crossentropy\", optimizer=keras.optimizers.Adam(), metrics=[\"categorical_accuracy\"])\ncheckpoint_best = keras.callbacks.ModelCheckpoint(\"/content/drive/My Drive/model_best.h5\", \n monitor='loss', verbose=0, save_best_only=True, save_weights_only=False, save_freq='epoch')\ncheckpoint = keras.callbacks.ModelCheckpoint(\"/content/drive/My Drive/model_last.h5\", \n verbose=0, save_best_only=False, save_weights_only=False, save_freq='epoch')\nmodel.fit(\n train_generator,\n epochs = 5,\n validation_data=val_generator,\n callbacks=[checkpoint_best]\n)", "Epoch 1/5\n49/49 [==============================] - 71s 1s/step - loss: 1.1823 - categorical_accuracy: 0.8065 - val_loss: 0.7923 - val_categorical_accuracy: 0.8502\nEpoch 2/5\n49/49 [==============================] - 72s 1s/step - loss: 0.3338 - categorical_accuracy: 0.9013 - val_loss: 0.5771 - val_categorical_accuracy: 0.8668\nEpoch 3/5\n49/49 [==============================] - 72s 1s/step - loss: 0.1848 - categorical_accuracy: 0.9377 - val_loss: 0.5730 - val_categorical_accuracy: 0.8758\nEpoch 4/5\n49/49 [==============================] - 75s 2s/step - loss: 0.1533 - categorical_accuracy: 0.9496 - val_loss: 0.7109 - val_categorical_accuracy: 0.8630\nEpoch 5/5\n49/49 [==============================] - 73s 1s/step - loss: 0.1125 - categorical_accuracy: 0.9642 - val_loss: 0.7830 - val_categorical_accuracy: 0.8643\n" ], [ "model.evaluate(val_generator)", "13/13 [==============================] - 42s 3s/step - loss: 0.5171 - categorical_accuracy: 0.8912\n" ], [ "model.fit(\n train_generator,\n initial_epoch=10,\n epochs = 20,\n validation_data=val_generator, callbacks=[checkpoint, checkpoint_best]\n)", "Epoch 11/20\n62/62 [==============================] - 87s 1s/step - loss: 0.3099 - categorical_accuracy: 0.9213 - val_loss: 0.3068 - val_categorical_accuracy: 0.9117\nEpoch 12/20\n62/62 [==============================] - 86s 1s/step - loss: 0.1898 - categorical_accuracy: 0.9397 - val_loss: 0.1291 - val_categorical_accuracy: 0.9565\nEpoch 13/20\n62/62 [==============================] - 88s 1s/step - loss: 0.1054 - categorical_accuracy: 0.9635 - val_loss: 0.1378 - val_categorical_accuracy: 0.9693\nEpoch 14/20\n62/62 [==============================] - 88s 1s/step - loss: 0.0665 - categorical_accuracy: 0.9793 - val_loss: 0.0363 - val_categorical_accuracy: 0.9885\nEpoch 15/20\n62/62 [==============================] - 89s 1s/step - loss: 0.0444 - categorical_accuracy: 0.9875 - val_loss: 0.0727 - val_categorical_accuracy: 0.9706\nEpoch 16/20\n62/62 [==============================] - 87s 1s/step - loss: 0.0873 - categorical_accuracy: 0.9683 - val_loss: 0.0584 - val_categorical_accuracy: 0.9821\nEpoch 17/20\n62/62 [==============================] - 90s 1s/step - loss: 0.0384 - categorical_accuracy: 0.9885 - val_loss: 0.0240 - val_categorical_accuracy: 0.9923\nEpoch 18/20\n62/62 [==============================] - 87s 1s/step - loss: 0.0466 - categorical_accuracy: 0.9842 - val_loss: 0.0385 - val_categorical_accuracy: 0.9910\nEpoch 19/20\n62/62 [==============================] - 88s 1s/step - loss: 0.0379 - categorical_accuracy: 0.9880 - val_loss: 0.0192 - val_categorical_accuracy: 0.9949\nEpoch 20/20\n62/62 [==============================] - 89s 1s/step - loss: 0.0262 - categorical_accuracy: 0.9928 - val_loss: 0.0225 - val_categorical_accuracy: 0.9910\n" ], [ "model.save(\"/content/drive/My Drive/model_best_64.h5\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d037c7ba467f0c28fe57c3830bc916eac9d394d1
4,352
ipynb
Jupyter Notebook
notebooks/es/3_script_baseline.ipynb
jarobyte91/post_ocr_correction
bae2e601c838a23cc31a82e10ed5cd1b10ccdac6
[ "MIT" ]
3
2021-11-15T08:29:39.000Z
2021-12-20T21:56:54.000Z
notebooks/es/3_script_baseline.ipynb
jarobyte91/post_ocr_correction
bae2e601c838a23cc31a82e10ed5cd1b10ccdac6
[ "MIT" ]
3
2021-11-15T08:29:36.000Z
2022-01-06T13:52:34.000Z
notebooks/es/3_script_baseline.ipynb
jarobyte91/post_ocr_correction
bae2e601c838a23cc31a82e10ed5cd1b10ccdac6
[ "MIT" ]
1
2021-11-08T20:15:52.000Z
2021-11-08T20:15:52.000Z
36.881356
83
0.438649
[ [ [ "%run scripts/train_models/launch_experiments.py --experiment_id=test --random", "main folder:/home/jarobyte/scratch/guemes/icdar/es/\noutput folder:baseline\n\nModel: Transformer\nTokens in the input vocabulary: 182\nTokens in the output vocabulary: 182\nMax sequence length: 110\nEmbedding dimension: 256\nFeedforward dimension: 1024\nEncoder layers: 2\nDecoder layers: 2\nAttention heads: 8\nActivation: relu\nDropout: 0.4\nTrainable parameters: 3,855,542\n\nTraining started\nEpochs: 10\nLearning rate: 0.0001\nWeight decay: 0.001\nEpoch | Train | Development | Minutes\n | Loss | Error Rate | Loss | Error Rate |\n---------------------------------------------------------------\n 1 | 4.4012 | 83.244 | 4.2320 | 99.960 | 0.0\n 2 | 3.5844 | 77.707 | 3.8039 | 99.089 | 0.0\n 3 | 3.3182 | 77.088 | 3.6094 | 92.277 | 0.0\n 4 | 3.1461 | 75.265 | 3.4594 | 85.485 | 0.0\n 5 | 3.0011 | 72.756 | 3.3018 | 80.733 | 0.0\n 6 | 2.8745 | 70.236 | 3.1664 | 78.208 | 0.1\n 7 | 2.7630 | 68.191 | 3.0840 | 78.000 | 0.1\n 8 | 2.6652 | 66.625 | 3.0250 | 77.842 | 0.1\n 9 | 2.5855 | 65.606 | 2.9725 | 77.554 | 0.1\n 10 | 2.5184 | 64.743 | 2.9266 | 77.337 | 0.1\n\nEvaluating model..\ndisjoint window...\ngreedy_search...\nbeam_search...\nsliding, greedy...\nuniform...\ntriangle...\nbell...\nsliding, beam...\nuniform...\ntriangle...\nbell...\n experiment_id improvement window decoding window_size \\\n0 test -70.150204 disjoint greedy 10 \n1 test -67.381259 disjoint greedy 5 \n2 test -79.538192 disjoint beam 10 \n3 test -78.658891 disjoint beam 5 \n4 test -72.055369 sliding greedy 5 \n5 test -71.941569 sliding greedy 5 \n6 test -71.941569 sliding greedy 5 \n7 test -78.131311 sliding beam 5 \n8 test -78.131311 sliding beam 5 \n9 test -78.131311 sliding beam 5 \n\n inference_seconds cer_before cer_after weighting \n0 0.647468 43.407167 73.857383 NaN \n1 0.584162 43.407167 72.655462 NaN \n2 4.998648 43.407167 77.932442 NaN \n3 4.504213 43.407167 77.550763 NaN \n4 4.149696 43.407167 74.684361 uniform \n5 3.930020 43.407167 74.634964 triangle \n6 3.926667 43.407167 74.634964 bell \n7 23.705193 43.407167 77.321755 uniform \n8 23.494794 43.407167 77.321755 triangle \n9 23.261851 43.407167 77.321755 bell \n" ] ] ]
[ "code" ]
[ [ "code" ] ]
d037d1ba6a7b557b8e580757bd2fbf69b0414a27
13,839
ipynb
Jupyter Notebook
90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb
trivedi-c/atm_Practical3
1cd1e0bd263d274cada781d871ad37314ebe139e
[ "MIT" ]
null
null
null
90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb
trivedi-c/atm_Practical3
1cd1e0bd263d274cada781d871ad37314ebe139e
[ "MIT" ]
null
null
null
90_workshops/202012_EUM_short_course_gridded_dataset/01_introduction_to_python_and_jupyter.ipynb
trivedi-c/atm_Practical3
1cd1e0bd263d274cada781d871ad37314ebe139e
[ "MIT" ]
1
2021-10-30T00:54:07.000Z
2021-10-30T00:54:07.000Z
21.623438
417
0.545415
[ [ [ "<img src='./img/EU-Copernicus-EUM_3Logos.png' alt='Logo EU Copernicus EUMETSAT' align='right' width='40%'></img>", "_____no_output_____" ], [ "<br>", "_____no_output_____" ], [ "<a href=\"./00_index.ipynb\"><< Index</a><span style=\"float:right;\"><a href=\"./02_AC_SAF_GOME-2_L2_produce_gridded_dataset_L3.ipynb\">02 - AC SAF GOME-2 - Produce gridded dataset (L3)>></a> ", "_____no_output_____" ], [ "<br>", "_____no_output_____" ], [ "# Optional: Introduction to Python and Project Jupyter", "_____no_output_____" ], [ "## Project Jupyter", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-success\" align=\"center\">\n<b><i>\"Project Jupyter exists to develop open-source software, open-standards, and services for interactive computing across dozens of programming languages.\"</i></b>\n</div>", "_____no_output_____" ], [ "<br>", "_____no_output_____" ], [ "Project Jupyter offers different tools to facilitate interactive computing, either with a web-based application (`Jupyter Notebooks`), an interactive development environment (`JupyterLab`) or via a `JupyterHub` that brings interactive computing to groups of users.\n\n<br>", "_____no_output_____" ], [ "<center><img src='./img/jupyter_environment.png' alt='Logo Jupyter environment' width='60%'></img></center>", "_____no_output_____" ], [ "* **Jupyter Notebook** is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text.\n\n* **JupyterLab 1.0: Jupyter’s Next-Generation Notebook Interface** <br> JupyterLab is a web-based interactive development environment for Jupyter notebooks, code, and data.\n\n* **JupyterHub** <br>JupyterHub brings the power of notebooks to groups of users. It gives users access to computational environments and resources without burdening the users with installation and maintenance tasks. <br> Users - including students, researchers, and data scientists - can get their work done in their own workspaces on shared resources which can be managed efficiently by system administrators.", "_____no_output_____" ], [ "<hr>", "_____no_output_____" ], [ "## Why Jupyter Notebooks?", "_____no_output_____" ], [ "* Started with Python support, now **support of over 40 programming languages, including Python, R, Julia, ...**\n* Notebooks can **easily be shared via GitHub, NBViewer, etc.**\n* **Code, data and visualizations are combined in one place**\n* A great tool for **teaching**\n* **JupyterHub allows you to access an environment ready to code**", "_____no_output_____" ], [ "## Installation", "_____no_output_____" ], [ "### Installing Jupyter using Anaconda", "_____no_output_____" ], [ "Anaconda comes with the Jupyter Notebook installed. You just have to download Anaconda and following the installation instructions. Once installed, the jupyter notebook can be started with:", "_____no_output_____" ] ], [ [ "jupyter notebook", "_____no_output_____" ] ], [ [ "### Installing Jupyter with pip", "_____no_output_____" ], [ "Experienced Python users may want to install Jupyter using Python's package manager `pip`.\n\nWith `Python3` you do:", "_____no_output_____" ] ], [ [ "python3 -m pip install --upgrade pip\npython3 -m pip install jupyter", "_____no_output_____" ] ], [ [ "In order to run the notebook, you run the same command as with Anaconda at the Terminal :", "_____no_output_____" ] ], [ [ "jupyter notebook", "_____no_output_____" ] ], [ [ "## Jupyter notebooks UI", "_____no_output_____" ], [ "* Notebook dashboard\n * Create new notebook\n* Notebook editor (UI)\n * Menu\n * Toolbar\n * Notebook area and cells\n* Cell types\n * Code\n * Markdown\n* Edit (green) vs. Command mode (blue)", "_____no_output_____" ], [ "<br>\n\n\n<div style='text-align:center;'>\n<figure><img src='./img/notebook_ui.png' width='100%'/>\n <figcaption><i>Notebook editor User Interface (UI)</i></figcaption>\n</figure>\n</div>", "_____no_output_____" ], [ "## Shortcuts", "_____no_output_____" ], [ "Get an overview of the shortcuts by hitting `H` or go to `Help/Keyboard shortcuts`", "_____no_output_____" ], [ "#### Most useful shortcuts", "_____no_output_____" ], [ "* `Esc` - switch to command mode\n* `B` - insert below\n* `A` - insert above\n* `M` - Change current cell to Markdown\n* `Y` - Change current cell to code\n* `DD` - Delete cell\n* `Enter` - go back to edit mode\n* `Esc + F` - Find and replace on your code\n* `Shift + Down / Upwards` - Select multiple cells\n* `Shift + M` - Merge multiple cells", "_____no_output_____" ], [ "## Cell magics", "_____no_output_____" ], [ "Magic commands can make your life a lot easier, as you only have one command instead of an entire function or multiple lines of code.<br>\n> Go to an [extensive overview of magic commands]()", "_____no_output_____" ], [ "### Some of the handy ones", "_____no_output_____" ], [ "**Overview of available magic commands**", "_____no_output_____" ] ], [ [ "%lsmagic", "_____no_output_____" ] ], [ [ "**See and set environment variables**", "_____no_output_____" ] ], [ [ "%env", "_____no_output_____" ] ], [ [ "**Install and list libraries**", "_____no_output_____" ] ], [ [ "!pip install numpy\n!pip list | grep pandas", "_____no_output_____" ] ], [ [ "**Write cell content to a Python file**", "_____no_output_____" ] ], [ [ "%%writefile hello_world.py\n\nprint('Hello World')", "_____no_output_____" ] ], [ [ "**Load a Python file**", "_____no_output_____" ] ], [ [ "%pycat hello_world.py", "_____no_output_____" ] ], [ [ "**Get the time of cell execution**", "_____no_output_____" ] ], [ [ "%%time\n\ntmpList = []\nfor i in range(100):\n tmpList.append(i+i)\n\nprint(tmpList)", "_____no_output_____" ] ], [ [ "**Show matplotlib plots inline**", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "<br>", "_____no_output_____" ], [ "## Sharing Jupyter Notebooks", "_____no_output_____" ], [ "### Sharing static Jupyter Notebooks", "_____no_output_____" ], [ "* [nbviewer](https://nbviewer.jupyter.org/) - A simple way to share Jupyter Notebooks. You can simply paste the GitHub location of your Jupyter notebook there and it is nicely rendered.\n* [GitHub](https://github.com/) - GitHub offers an internal rendering of Jupyter Notebooks. There are some limitations and time delays of the proper rendering. Thus, we would suggest to use `nbviewer` to share nicely rendered Jupyter Notebooks.", "_____no_output_____" ], [ "### Reproducible Jupyter Notebooks", "_____no_output_____" ], [ "<img src=\"./img/mybinder_logo.png\" align=\"left\" width=\"30%\"></img>\n[Binder](https://mybinder.org/) allows you to open notebooks hosted on a Git repo in an executable environment, making the code immediately reproducible by anyone, anywhere.\n\nBinder builds a Docker image of the repo where the notebooks are hosted.\n", "_____no_output_____" ], [ "<br>", "_____no_output_____" ], [ "## Ressources", "_____no_output_____" ], [ "* [Project Jupyter](https://jupyter.org/)\n* [JupyterHub](https://jupyterhub.readthedocs.io/en/stable/)\n* [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/)\n* [nbviewer](https://nbviewer.jupyter.org/)\n* [Binder](https://mybinder.org/)", "_____no_output_____" ], [ "<br>", "_____no_output_____" ], [ "<a href=\"./00_index.ipynb\"><< Index</a><span style=\"float:right;\"><a href=\"./02_AC_SAF_GOME-2_L2_produce_gridded_dataset_L3.ipynb\">02 - AC SAF GOME-2 - Produce gridded dataset (L3)>></a> ", "_____no_output_____" ], [ "<hr>", "_____no_output_____" ], [ "<img src='./img/copernicus_logo.png' alt='Logo EU Copernicus' align='right' width='20%'><br><br><br>\n<br>\n<p style=\"text-align:right;\">This project is licensed under the <a href=\"./LICENSE\">MIT License</a> and is developed under a Copernicus contract.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "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" ] ]
d037e0e606843d8662c1bcbc94622d8e4fd6cafa
5,115
ipynb
Jupyter Notebook
Calculus_Homework/WWB14.1.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
Calculus_Homework/WWB14.1.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
Calculus_Homework/WWB14.1.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
19.597701
132
0.443597
[ [ [ "# reference https://socratic.org/questions/the-top-and-bottom-margins-of-a-poster-are-4-cm-and-the-side-margins-are-each-6-\nfrom IPython.display import Image\nfrom IPython.core.display import HTML \nfrom sympy import *; x,h,y,n,t = symbols(\"x h y n t\"); C, D = symbols(\"C D\", real=True)\nImage(url= \"https://i.imgur.com/LA701Wi.png\")", "_____no_output_____" ], [ "A,a,b = symbols(\"A a b\")\nA = 382 + 2*(a*8) + 2*(b*8)-4*(8*8)\nA", "_____no_output_____" ], [ "Eq(A,a*b)", "_____no_output_____" ], [ "pprint(solve(Eq(A,a*b),a)) # A(b)", "⎡2⋅(8⋅b + 63)⎤\n⎢────────────⎥\n⎣ b - 16 ⎦\n" ], [ "simplify((2*(8*b + 63)/(b - 16))*b) *a * b", "_____no_output_____" ], [ "simplify(diff((2*(8*b + 63)/(b - 16))*b))", "_____no_output_____" ], [ "print(simplify(diff((2*(8*b + 63)/(b - 16))*b)))", "16*(b**2 - 32*b - 126)/(b**2 - 32*b + 256)\n" ], [ "b**2 - 32*b - 126", "_____no_output_____" ], [ "solve(b**2 - 32*b - 126,b)", "_____no_output_____" ], [ "Image(url= \"https://i.imgur.com/3RToGO0.png\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d037e3938548030e946cba9358bae44d06396753
3,422
ipynb
Jupyter Notebook
chapter14/05_local_endpoint_pandas.ipynb
PacktPublishing/Mastering-Azure-Machine-Learning-Second-Edition
1ca0cf19fd49f6781c589ae4d9bde56135791cf1
[ "MIT" ]
1
2022-03-07T20:15:08.000Z
2022-03-07T20:15:08.000Z
chapter14/05_local_endpoint_pandas.ipynb
PacktPublishing/Mastering-Azure-Machine-Learning-Second-Edition
1ca0cf19fd49f6781c589ae4d9bde56135791cf1
[ "MIT" ]
null
null
null
chapter14/05_local_endpoint_pandas.ipynb
PacktPublishing/Mastering-Azure-Machine-Learning-Second-Edition
1ca0cf19fd49f6781c589ae4d9bde56135791cf1
[ "MIT" ]
1
2022-03-22T17:57:41.000Z
2022-03-22T17:57:41.000Z
23.763889
130
0.545587
[ [ [ "from utils import *", "_____no_output_____" ], [ "from azureml.core import Workspace\nfrom azureml.core.authentication import InteractiveLoginAuthentication\n\ninteractive_auth = InteractiveLoginAuthentication(tenant_id=\"c643d8c8-4abb-47ba-808c-bf73f60161f1\")\n\n# Configure workspace\nws = Workspace.from_config(auth=interactive_auth)", "_____no_output_____" ], [ "from azureml.core.model import InferenceConfig\n\nenv = get_env(name=\"sentiment-analysis\", packages=[\"pandas\", \"inference-schema\", \"tensorflow\", \"transformers\"])\n\ninference_config = InferenceConfig(\n environment=env,\n source_directory=\"code\",\n entry_script=\"sentiment_analysis_pandas.py\",\n)", "_____no_output_____" ], [ "from azureml.core.webservice import LocalWebservice\n\ndeployment_config = LocalWebservice.deploy_configuration(port=6789)", "_____no_output_____" ], [ "from azureml.core import Model\n\nservice = Model.deploy(\n ws,\n \"sentiment-analysis-pandas\",\n [],\n inference_config,\n deployment_config,\n overwrite=True,\n)\nservice.wait_for_deployment(show_output=True)", "_____no_output_____" ], [ "print(service.get_logs())", "_____no_output_____" ], [ "import requests\nimport json\n\nuri = service.scoring_uri\nrequests.get(\"http://localhost:6789\")\nheaders = {\"Content-Type\": \"application/json\"}\ndata = {\n \"Inputs\": {\n \"data\": [\n {\"query\": \"My ML skills are quite good.\"}, \n {\"query\": \"I didn't have good experience with ML.\"}\n ]\n }\n}\ndata = json.dumps(data)\nresponse = requests.post(uri, data=data, headers=headers)\nprint(response.text)", "_____no_output_____" ], [ "# service.delete()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d037e7a8d220354df1c70698121cfa4be6a163eb
5,960
ipynb
Jupyter Notebook
6_a_extending_dataframe_capabilities.ipynb
mj111312/pandas_basics
1cc55c5fda3eb579ad34a26ada7dfe70dd5594ec
[ "MIT" ]
42
2016-12-10T19:18:06.000Z
2022-02-25T13:59:20.000Z
6_a_extending_dataframe_capabilities.ipynb
mj111312/pandas_basics
1cc55c5fda3eb579ad34a26ada7dfe70dd5594ec
[ "MIT" ]
null
null
null
6_a_extending_dataframe_capabilities.ipynb
mj111312/pandas_basics
1cc55c5fda3eb579ad34a26ada7dfe70dd5594ec
[ "MIT" ]
28
2016-12-12T06:21:41.000Z
2022-01-18T09:40:11.000Z
20.135135
88
0.407718
[ [ [ "Adding functionality so we can create dataframe from string representation of dict", "_____no_output_____" ] ], [ [ "import ast\ndef str_to_dict(string):\n return ast.literal_eval(string) ", "_____no_output_____" ], [ "import pandas as pd", "_____no_output_____" ], [ "class MySubClass(pd.DataFrame):\n def from_str(self, string):\n df_obj = super().from_dict(str_to_dict(string))\n df_obj.my_string_attribute = string\n return df_obj", "_____no_output_____" ], [ "data = \"{'col_1' : ['a','b'], 'col2': [1, 2]}\"", "_____no_output_____" ], [ "obj = MySubClass().from_str(data)", "_____no_output_____" ], [ "type(obj)", "_____no_output_____" ], [ "obj", "_____no_output_____" ], [ "obj.my_string_attribute", "_____no_output_____" ], [ "sales = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},\n {'account': 'Alpha Co', 'Jan': 200, 'Feb': 210, 'Mar': 215},\n {'account': 'Blue Inc', 'Jan': 50, 'Feb': 90, 'Mar': 95 }]\ndf = MySubClass(sales)", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "type(df)", "_____no_output_____" ] ] ]
[ "raw", "code" ]
[ [ "raw" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d037f59f840aef083579d20f83a0fd694d9a1b16
20,927
ipynb
Jupyter Notebook
MovieLens/Atelier-pyspark-MovieLens.ipynb
duongtoan261196/AI_Framework
deaf0d188620ab793920a8afc90e2286ea96310a
[ "MIT" ]
null
null
null
MovieLens/Atelier-pyspark-MovieLens.ipynb
duongtoan261196/AI_Framework
deaf0d188620ab793920a8afc90e2286ea96310a
[ "MIT" ]
null
null
null
MovieLens/Atelier-pyspark-MovieLens.ipynb
duongtoan261196/AI_Framework
deaf0d188620ab793920a8afc90e2286ea96310a
[ "MIT" ]
null
null
null
36.268631
911
0.623023
[ [ [ "<center>\n<a href=\"http://www.insa-toulouse.fr/\" ><img src=\"http://www.math.univ-toulouse.fr/~besse/Wikistat/Images/logo-insa.jpg\" style=\"float:left; max-width: 120px; display: inline\" alt=\"INSA\"/></a> \n\n<a href=\"http://wikistat.fr/\" ><img src=\"http://www.math.univ-toulouse.fr/~besse/Wikistat/Images/wikistat.jpg\" style=\"max-width: 250px; display: inline\" alt=\"Wikistat\"/></a>\n\n<a href=\"http://www.math.univ-toulouse.fr/\" ><img src=\"http://www.math.univ-toulouse.fr/~besse/Wikistat/Images/logo_imt.jpg\" style=\"float:right; max-width: 200px; display: inline\" alt=\"IMT\"/> </a>\n</center>", "_____no_output_____" ], [ "# [Ateliers: Technologies des grosses données](https://github.com/wikistat/Ateliers-Big-Data)", "_____no_output_____" ], [ "# Recommandation de Films par Filtrage Collaboratif: [NMF](http://wikistat.fr/pdf/st-m-explo-nmf.pdf) de la librairie [SparkML](https://spark.apache.org/docs/latest/ml-guide.html) de <a href=\"http://spark.apache.org/\"><img src=\"http://spark.apache.org/images/spark-logo-trademark.png\" style=\"max-width: 100px; display: inline\" alt=\"Spark\"/></a>", "_____no_output_____" ], [ "## 1. Introduction\n\nCe calepin traite d'un problème classique de recommandation par filtrage collaboratif en utilisant les ressources de la librairie [MLlib de Spark]([http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.recommendation.ALS) avec l'API pyspark. Le problème général est décrit en [introduction](https://github.com/wikistat/Ateliers-Big-Data/tree/master/3-MovieLens) et dans une [vignette](http://wikistat.fr/pdf/st-m-datSc3-colFil.pdf) de [Wikistat](http://wikistat.fr/). Il est appliqué aux données publiques du site [GroupLens](http://grouplens.org/datasets/movielens/). L'objectif est de tester les méthodes et la procédure d'optimisation sur le plus petit jeu de données composé de 100k notes de 943 clients sur 1682 films où chaque client a au moins noté 20 films. Les jeux de données plus gros (1M, 10M, 20M notes) peuvent être utilisés pour \"passer à l'échelle volume\". \n\nCe calepin s'inspire des exemples de la [documentation](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.recommendation.ALS) et d'un [tutoriel](https://github.com/jadianes/spark-movie-lens/blob/master/notebooks/building-recommender.ipynb) de [Jose A. Dianes](https://www.codementor.io/jadianes). Le sujet a été traité lors d'un [Spark Summit](https://databricks-training.s3.amazonaws.com/movie-recommendation-with-mllib.html).\n\nL'objectif est d'utiliser ces seules données pour proposer des recommandations. Les données initiales sont sous la forme d'une matrice **très creuse** (*sparse*) contenant des notes ou évaluations. **Attention**, les \"0\" de la matrice ne sont pas des notes mais des *données manquantes*, le film n'a pas encore été vu ou évalué. \n\nUn algorithme satisfaisant à l'objectif de *complétion de grande matrice creuse*, et implémenté dans un logiciel libre d'accès est disponible dans la librairie [softImpute de R](https://cran.r-project.org/web/packages/softImpute/index.html). SOn utilisaiton est décrite dans un autre [calepin](https://github.com/wikistat/Ateliers-Big-Data/blob/master/3-MovieLens/Atelier-MovieLens-softImpute.ipynb). La version de [NMF](http://wikistat.fr/pdf/st-m-explo-nmf.pdf) de [MLlib de Spark](http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.recommendation.ALS) autorise permet également la complétion.\n\nEn revanche,la version de NMF incluse dans la librairie [Scikit-learn](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html) traite également des [matrices creuses](http://docs.scipy.org/doc/scipy/reference/sparse.html) mais le critère (moindres carrés) optimisé considère les \"0\" comme des notes nulles, pas comme des données manquantes. *Elle n'est pas adaptée au problème de complétion*, contrairement à celle de MLliB. Il faudrait sans doute utiliser la librairie [nonnegfac](https://github.com/kimjingu/nonnegfac-python) en Python de [Kim et al. (2014)](http://link.springer.com/content/pdf/10.1007%2Fs10898-013-0035-4.pdf); **à tester**!\n\nDans la première partie, le plus petit fichier est partagé en trois échantillons: apprentissage, validation et test; l'optimisation du rang de la factorisation (nombre de facteurs latents) est réalisée par minimisation de l'erreur estimée sur l'échantillon de validation.\n\nEnsuite le plus gros fichier est utilisé pour évaluer l'impact de la taille de la base d'apprentissage.", "_____no_output_____" ], [ "## 2 Importation des données en HDFS\nLes données doivent être stockées à un emplacement accessibles de tous les noeuds du cluster pour permettre la construction de la base de données réparties (RDD). Dans une utilisation monoposte (*standalone*) de *Spark*, elles sont simplement chargées dans le répertoire courant. ", "_____no_output_____" ] ], [ [ "sc", "_____no_output_____" ], [ "# Chargement des fichiers si ce n'est déjà fait\n#Renseignez ici le dossier où vous souhaitez stocker le fichier téléchargé.\nDATA_PATH=\"\" \nimport urllib.request\n# fichier réduit\nf = urllib.request.urlretrieve(\"http://www.math.univ-toulouse.fr/~besse/Wikistat/data/ml-ratings100k.csv\",DATA_PATH+\"ml-ratings100k.csv\")", "_____no_output_____" ] ], [ [ "Les données sont lues comme une seule ligne de texte avant d'être restructurées au bon format d'une *matrice creuse* à savoir une liste de triplets contenant les indices de ligne, de colonne et la note pour les seules valeurs renseignées.", "_____no_output_____" ] ], [ [ "# Importer les données au format texte dans un RDD\n\nsmall_ratings_raw_data = sc.textFile(DATA_PATH+\"ml-ratings100k.csv\")\n\n# Identifier et afficher la première ligne\nsmall_ratings_raw_data_header = small_ratings_raw_data.take(1)[0]\nprint(small_ratings_raw_data_header)\n\n# Create RDD without header\nall_lines = small_ratings_raw_data.filter(lambda l : l!=small_ratings_raw_data_header)", "_____no_output_____" ], [ "# Séparer les champs (user, item, note) dans un nouveau RDD\nfrom pyspark.sql import Row\nsplit_lines = all_lines.map(lambda l : l.split(\",\"))\nratingsRDD = split_lines.map(lambda p: Row(user=int(p[0]), item=int(p[1]),\n rating=float(p[2]), timestamp=int(p[3])))\n\n# .cache() : le RDD est conservé en mémoire une fois traité\nratingsRDD.cache()\n\n# Display the two first rows\nratingsRDD.take(2)", "_____no_output_____" ], [ "# Convert RDD to DataFrame\nratingsDF = spark.createDataFrame(ratingsRDD)\nratingsDF.take(2)", "_____no_output_____" ] ], [ [ "## 3. Optimisation du rang sur l'échantillon 10k\nLe fichier comporte 10 000 évaluations croisant les avis de mille utilisateurs sur les films qu'ils ont vus parmi 1700.", "_____no_output_____" ], [ "### 3.1 Constitution des échantillons", "_____no_output_____" ], [ "Séparation aléatoire en trois échantillons apprentissage, validation et test. Le paramètre de rang est optimisé en minimisant l'estimaiton de l'erreur sur l'échantillon test. Cette stratégie, plutôt qu'ue validation croisée est plus adaptée à des données massives.\n", "_____no_output_____" ] ], [ [ "tauxTrain=0.6\ntauxVal=0.2\ntauxTes=0.2\n# Si le total est inférieur à 1, les données sont sous-échantillonnées.\n(trainDF, validDF, testDF) = ratingsDF.randomSplit([tauxTrain, tauxVal, tauxTes])\n# validation et test à prédire, sans les notes\nvalidDF_P = validDF.select(\"user\", \"item\")\ntestDF_P = testDF.select(\"user\", \"item\")", "_____no_output_____" ], [ "trainDF.take(2), validDF_P.take(2), testDF_P.take(2)", "_____no_output_____" ] ], [ [ "### 3.2 Optimisation du rang de la NMF", "_____no_output_____" ], [ "L'erreur d'imputation des données, donc de recommandation, est estimée sur l'échantillon de validation pour différentes valeurs (grille) du rang de la factorisation matricielle. \n\nIl faudrait en principe aussi optimiser la valeur du paramètre de pénalisation pris à 0.1 par défaut.\n\n*Point important:* l'erreur d'ajustement de la factorisation ne prend en compte que les valeurs listées dans la matrice creuses, pas les \"0\" qui sont des données manquantes.", "_____no_output_____" ] ], [ [ "from pyspark.ml.recommendation import ALS\nimport math\nimport collections\n# Initialisation du générateur\nseed = 5\n# Nombre max d'itérations (ALS)\nmaxIter = 10\n# Régularisation L1; à optimiser également\nregularization_parameter = 0.1\n# Choix d'une grille pour les valeurs du rang à optimiser\nranks = [4, 8, 12]\n\n#Initialisation variable \n# création d'un dictionaire pour stocker l'erreur par rang testé\nerrors = collections.defaultdict(float)\ntolerance = 0.02\nmin_error = float('inf')\nbest_rank = -1\nbest_iteration = -1", "_____no_output_____" ], [ "from pyspark.ml.evaluation import RegressionEvaluator\n\nfor rank in ranks:\n als = ALS( rank=rank, seed=seed, maxIter=maxIter,\n regParam=regularization_parameter)\n model = als.fit(trainDF)\n # Prévision de l'échantillon de validation\n predDF = model.transform(validDF).select(\"prediction\",\"rating\")\n #Remove unpredicter row due to no-presence of user in the train dataset\n pred_without_naDF = predDF.na.drop()\n # Calcul du RMSE\n evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"rating\",\n predictionCol=\"prediction\")\n rmse = evaluator.evaluate(pred_without_naDF)\n print(\"Root-mean-square error for rank %d = \"%rank + str(rmse))\n errors[rank] = rmse\n if rmse < min_error:\n min_error = rmse\n best_rank = rank\n# Meilleure solution\nprint('Rang optimal: %s' % best_rank)", "_____no_output_____" ] ], [ [ "### 3.3 Résultats et test", "_____no_output_____" ] ], [ [ "# Quelques prévisions\npred_without_naDF.take(3)", "_____no_output_____" ] ], [ [ "Prévision finale de l'échantillon test.", "_____no_output_____" ] ], [ [ "#On concatane la DataFrame Train et Validatin\ntrainValidDF = trainDF.union(validDF)\n# On crée un model avec le nouveau Dataframe complété d'apprentissage et le rank fixé à la valeur optimal \nals = ALS( rank=best_rank, seed=seed, maxIter=maxIter,\n regParam=regularization_parameter)\nmodel = als.fit(trainValidDF)\n#Prediction sur la DataFrame Test\ntestDF = model.transform(testDF).select(\"prediction\",\"rating\")\n#Remove unpredicter row due to no-presence of user in the trai dataset\npred_without_naDF = predDF.na.drop()\n# Calcul du RMSE\nevaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"rating\",\n predictionCol=\"prediction\")\nrmse = evaluator.evaluate(pred_without_naDF)\nprint(\"Root-mean-square error for rank %d = \"%best_rank + str(rmse))\n\n", "_____no_output_____" ] ], [ [ "## 3 Analyse du fichier complet", "_____no_output_____" ], [ "MovieLens propose un plus gros fichier avec 20M de notes (138000 utilisateurs, 27000 films). Ce fichier est utilisé pour extraire un fichier test de deux millions de notes à reconstruire. Les paramètres précédemment optimisés, ils pourraient sans doute l'être mieux, sont appliqués pour une succesion d'estimation / prévision avec une taille croissante de l'échantillon d'apprentissage. Il aurait été plus élégant d'automatiser le travail dans une boucle mais lorsque les données sont les plus volumineuses des comportement mal contrôlés de Spark peuvent provoquer des plantages par défaut de mémoire.", "_____no_output_____" ], [ "### 3.1 Lecture des données", "_____no_output_____" ], [ "Le fichier est prétraité de manière analogue.", "_____no_output_____" ] ], [ [ "# Chargement des fichiers si ce n'est déjà fait\nimport urllib.request\n# fichier complet mais compressé\nf = urllib.request.urlretrieve(\"http://www.math.univ-toulouse.fr/~besse/Wikistat/data/ml-ratings20M.zip\",DATA_PATH+\"ml-ratings20M.zip\")", "_____no_output_____" ], [ "#Unzip downloaded file\nimport zipfile\nzip_ref = zipfile.ZipFile(DATA_PATH+\"ml-ratings20M.zip\", 'r')\nzip_ref.extractall(DATA_PATH)\nzip_ref.close()", "_____no_output_____" ], [ "# Importer les données au format texte dans un RDD\nratings_raw_data = sc.textFile(DATA_PATH+\"ratings20M.csv\")\n# Identifier et afficher la première ligne\nratings_raw_data_header = ratings_raw_data.take(1)[0]\nratings_raw_data_header\n\n# Create RDD without header\nall_lines = ratings_raw_data.filter(lambda l : l!=ratings_raw_data_header)\n", "_____no_output_____" ], [ "# Séparer les champs (user, item, note) dans un nouveau RDD\nsplit_lines = all_lines.map(lambda l : l.split(\",\"))\nratingsRDD = split_lines.map(lambda p: Row(user=int(p[0]), item=int(p[1]),\n rating=float(p[2]), timestamp=int(p[3])))\n\n# Display the two first rows\nratingsRDD.take(2)", "_____no_output_____" ], [ "# Convert RDD to DataFrame\nratingsDF = spark.createDataFrame(ratingsRDD)\nratingsDF.take(2)", "_____no_output_____" ] ], [ [ "### 3.2 Echantillonnage", "_____no_output_____" ], [ "Extraction de l'échantillon test et éventuellement sous-échantillonnage de l'échantillon d'apprentissage. ", "_____no_output_____" ] ], [ [ "tauxTest=0.1\n# Si le total est inférieur à 1, les données sont sous-échantillonnées.\n(trainTotDF, testDF) = ratingsDF.randomSplit([1-tauxTest, tauxTest])", "_____no_output_____" ], [ "# Sous-échantillonnage de l'apprentissage permettant de \n# tester pour des tailles croissantes de cet échantillon\ntauxEch=0.2\n(trainDF, DropData) = trainTotDF.randomSplit([tauxEch, 1-tauxEch])", "_____no_output_____" ], [ "testDF.take(2), trainDF.take(2)", "_____no_output_____" ] ], [ [ "### 3.3 Estimation du modèle", "_____no_output_____" ], [ "Le modèle est estimé en utilisant les valeurs des paramètres obtenues dans l'étape précédente.", "_____no_output_____" ] ], [ [ "import time\ntime_start=time.time()\n# Initialisation du générateur\nseed = 5\n# Nombre max d'itérations (ALS)\nmaxIter = 10\n# Régularisation L1 (valeur par défaut)\nregularization_parameter = 0.1\nbest_rank = 8\n# Estimation pour chaque valeur de rang\nals = ALS(rank=rank, seed=seed, maxIter=maxIter,\n regParam=regularization_parameter)\nmodel = als.fit(trainDF)\ntime_end=time.time()\ntime_als=(time_end - time_start)\nprint(\"ALS prend %d s\" %(time_als)) ", "_____no_output_____" ] ], [ [ "### 3.4 Prévision de l'échantillon test et erreur", "_____no_output_____" ] ], [ [ "# Prévision de l'échantillon de validation\npredDF = model.transform(testDF).select(\"prediction\",\"rating\")\n#Remove unpredicter row due to no-presence of user in the train dataset\npred_without_naDF = predDF.na.drop()\n# Calcul du RMSE\nevaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"rating\",\n predictionCol=\"prediction\")\nrmse = evaluator.evaluate(pred_without_naDF)\nprint(\"Root-mean-square error for rank %d = \"%best_rank + str(rmse))", "_____no_output_____" ], [ "trainDF.count()", "_____no_output_____" ] ], [ [ "Quelques résultats montrant l'évolution du temps de calcul et de l'erreur de prévision en fonction de la taille de l'échantillon d'apprentissage. Attention, il est probable que la valeur des paramètres optimaux dépendent de la taille de l'échantillon d'apprentissage.\n\nTaille | Temps(s) | RMSE\n-------|-------|------\n217439 | 70 | 1.65\n1029416| 73 | 1.06\n2059855| 72 | 1.05\n4119486| 89 | 0.88\n6176085| 99 | 0.85\n10301909| 117 | 0.83\n12361034| 125 | 0.83\n14414907| 137 | 0.82\n16474087| 148 | 0.818\n18538142| 190 | 0.816\n20596263| 166 | 0.82\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", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d037f8f02b3b550df82b2df8ca255daf4a478eed
13,971
ipynb
Jupyter Notebook
pytorch/notebooks/shallow_NNs-Cifar.ipynb
ChristoferNal/pooling-operations-and-information-theory
0bcb0a3059cb5e949c7d66b7b281e79da9dba0ba
[ "Apache-2.0" ]
3
2020-05-14T08:58:27.000Z
2020-05-20T08:35:23.000Z
pytorch/notebooks/shallow_NNs-Cifar.ipynb
ChristoferNal/pooling-operations-and-information-theory
0bcb0a3059cb5e949c7d66b7b281e79da9dba0ba
[ "Apache-2.0" ]
null
null
null
pytorch/notebooks/shallow_NNs-Cifar.ipynb
ChristoferNal/pooling-operations-and-information-theory
0bcb0a3059cb5e949c7d66b7b281e79da9dba0ba
[ "Apache-2.0" ]
null
null
null
38.700831
184
0.485363
[ [ [ "# Experiments comparing the performance of traditional pooling operations and entropy pooling within a shallow neural network and Lenet. The experiments use cifar10 and cifar100.", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "import torch\nimport torchvision\nimport torchvision.transforms as transforms", "_____no_output_____" ], [ "transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrainset = torchvision.datasets.CIFAR100(root='./data', train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=True, num_workers=8)\n\ntestset = torchvision.datasets.CIFAR100(root='./data', train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False, num_workers=8)\n\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')", "_____no_output_____" ], [ "import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.utils import _pair, _quadruple\nimport time\nfrom skimage.measure import shannon_entropy\nfrom scipy import stats\n\nfrom torch.nn.modules.utils import _pair, _quadruple\nimport time\nfrom skimage.measure import shannon_entropy\nfrom scipy import stats\nimport numpy as np\n\nclass EntropyPool2d(nn.Module):\n\n def __init__(self, kernel_size=3, stride=1, padding=0, same=False, entr='high'):\n super(EntropyPool2d, self).__init__()\n self.k = _pair(kernel_size)\n self.stride = _pair(stride)\n self.padding = _quadruple(padding) # convert to l, r, t, b\n self.same = same\n self.entr = entr\n\n def _padding(self, x):\n if self.same:\n ih, iw = x.size()[2:]\n if ih % self.stride[0] == 0:\n ph = max(self.k[0] - self.stride[0], 0)\n else:\n ph = max(self.k[0] - (ih % self.stride[0]), 0)\n if iw % self.stride[1] == 0:\n pw = max(self.k[1] - self.stride[1], 0)\n else:\n pw = max(self.k[1] - (iw % self.stride[1]), 0)\n pl = pw // 2\n pr = pw - pl\n pt = ph // 2\n pb = ph - pt\n padding = (pl, pr, pt, pb)\n else:\n padding = self.padding\n return padding\n \n def forward(self, x):\n # using existing pytorch functions and tensor ops so that we get autograd, \n # would likely be more efficient to implement from scratch at C/Cuda level\n start = time.time()\n x = F.pad(x, self._padding(x), mode='reflect')\n x_detached = x.cpu().detach()\n x_unique, x_indices, x_inverse, x_counts = np.unique(x_detached,\n return_index=True, \n return_inverse=True, \n return_counts=True) \n freq = torch.FloatTensor([x_counts[i] / len(x_inverse) for i in x_inverse]).cuda()\n x_probs = freq.view(x.shape) \n x_probs = x_probs.unfold(2, self.k[0], self.stride[0]).unfold(3, self.k[1], self.stride[1])\n x_probs = x_probs.contiguous().view(x_probs.size()[:4] + (-1,))\n if self.entr is 'high':\n x_probs, indices = torch.min(x_probs.cuda(), dim=-1)\n elif self.entr is 'low':\n x_probs, indices = torch.max(x_probs.cuda(), dim=-1)\n else:\n raise Exception('Unknown entropy mode: {}'.format(self.entr))\n \n x = x.unfold(2, self.k[0], self.stride[0]).unfold(3, self.k[1], self.stride[1])\n x = x.contiguous().view(x.size()[:4] + (-1,))\n indices = indices.view(indices.size() + (-1,))\n pool = torch.gather(input=x, dim=-1, index=indices)\n \n return pool.squeeze(-1)\n ", "_____no_output_____" ], [ "import torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport time\nfrom sklearn.metrics import f1_score\n\nMAX = 'max'\nAVG = 'avg'\nHIGH_ENTROPY = 'high_entr'\nLOW_ENTROPY = 'low_entr'\n\nclass Net1Pool(nn.Module):\n def __init__(self, num_classes=10, pooling=MAX):\n super(Net1Pool, self).__init__()\n self.conv1 = nn.Conv2d(3, 30, 5)\n \n if pooling is MAX:\n self.pool = nn.MaxPool2d(2, 2)\n elif pooling is AVG:\n self.pool = nn.AvgPool2d(2, 2)\n elif pooling is HIGH_ENTROPY:\n self.pool = EntropyPool2d(2, 2, entr='high')\n elif pooling is LOW_ENTROPY:\n self.pool = EntropyPool2d(2, 2, entr='low')\n \n self.fc0 = nn.Linear(30 * 14 * 14, num_classes)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = x.view(-1, 30 * 14 * 14)\n x = F.relu(self.fc0(x))\n return x\n\n\nclass Net2Pool(nn.Module):\n def __init__(self, num_classes=10, pooling=MAX):\n super(Net2Pool, self).__init__()\n self.conv1 = nn.Conv2d(3, 50, 5, 1)\n self.conv2 = nn.Conv2d(50, 50, 5, 1)\n \n if pooling is MAX:\n self.pool = nn.MaxPool2d(2, 2)\n elif pooling is AVG:\n self.pool = nn.AvgPool2d(2, 2)\n elif pooling is HIGH_ENTROPY:\n self.pool = EntropyPool2d(2, 2, entr='high')\n elif pooling is LOW_ENTROPY:\n self.pool = EntropyPool2d(2, 2, entr='low')\n \n self.fc1 = nn.Linear(5*5*50, 500)\n self.fc2 = nn.Linear(500, num_classes)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = self.pool(x)\n x = F.relu(self.conv2(x))\n x = self.pool(x)\n\n x = x.view(-1, 5*5*50)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return x\n\ndef configure_net(net, device):\n net.to(device)\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n return net, optimizer, criterion\n\ndef train(net, optimizer, criterion, trainloader, device, epochs=10, logging=2000):\n for epoch in range(epochs): \n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n start = time.time()\n inputs, labels = data\n inputs, labels = inputs.to(device), labels.to(device)\n \n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n if i % logging == logging - 1: \n print('[%d, %5d] loss: %.3f duration: %.5f' %\n (epoch + 1, i + 1, running_loss / logging, time.time() - start))\n running_loss = 0.0\n\n print('Finished Training')\n \ndef test(net, testloader, device):\n correct = 0\n total = 0\n predictions = []\n l = []\n with torch.no_grad():\n for data in testloader:\n images, labels = data\n images, labels = images.to(device), labels.to(device)\n\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n predictions.extend(predicted.cpu().numpy())\n l.extend(labels.cpu().numpy())\n\n\n print('Accuracy: {}'.format(100 * correct / total))\n", "_____no_output_____" ], [ "epochs = 10\nlogging = 15000\nnum_classes = 100\n", "_____no_output_____" ], [ "print('- - - - - - - - -- - - - 2 pool - - - - - - - - - - - - - - - -')\nprint('- - - - - - - - -- - - - MAX - - - - - - - - - - - - - - - -')\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nnet, optimizer, criterion = configure_net(Net2Pool(num_classes=num_classes, pooling=MAX), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)\n\nprint('- - - - - - - - -- - - - AVG - - - - - - - - - - - - - - - -')\n\nnet, optimizer, criterion = configure_net(Net2Pool(num_classes=num_classes, pooling=AVG), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)\n\nprint('- - - - - - - - -- - - - HIGH - - - - - - - - - - - - - - - -')\n\nnet, optimizer, criterion = configure_net(Net2Pool(num_classes=num_classes, pooling=HIGH_ENTROPY), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)\n\nprint('- - - - - - - - -- - - - LOW - - - - - - - - - - - - - - - -')\n\nnet, optimizer, criterion = configure_net(Net2Pool(num_classes=num_classes, pooling=LOW_ENTROPY), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)", "_____no_output_____" ], [ "print('- - - - - - - - -- - - - 1 pool - - - - - - - - - - - - - - - -')\nprint('- - - - - - - - -- - - - MAX - - - - - - - - - - - - - - - -')\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nnet, optimizer, criterion = configure_net(Net1Pool(num_classes=num_classes, pooling=MAX), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)\n\nprint('- - - - - - - - -- - - - AVG - - - - - - - - - - - - - - - -')\n\nnet, optimizer, criterion = configure_net(Net1Pool(num_classes=num_classes, pooling=AVG), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)\n\nprint('- - - - - - - - -- - - - HIGH - - - - - - - - - - - - - - - -')\n\nnet, optimizer, criterion = configure_net(Net1Pool(num_classes=num_classes, pooling=HIGH_ENTROPY), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)\n\nprint('- - - - - - - - -- - - - LOW - - - - - - - - - - - - - - - -')\n\nnet, optimizer, criterion = configure_net(Net1Pool(num_classes=num_classes, pooling=LOW_ENTROPY), device)\ntrain(net, optimizer, criterion, trainloader, device, epochs=epochs, logging=logging)\ntest(net, testloader, device)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03809540312f9b660b9231b35b62f1191d93794
12,416
ipynb
Jupyter Notebook
resources/aXeleRate_mark_detector.ipynb
joaopdss/aXelerate
791c8b29056ed11bd0ed306e620664577ec9724c
[ "MIT" ]
148
2020-03-18T01:36:20.000Z
2022-03-24T08:56:45.000Z
resources/aXeleRate_mark_detector.ipynb
joaopdss/aXelerate
791c8b29056ed11bd0ed306e620664577ec9724c
[ "MIT" ]
55
2020-03-29T14:36:44.000Z
2022-02-17T22:35:03.000Z
resources/aXeleRate_mark_detector.ipynb
joaopdss/aXelerate
791c8b29056ed11bd0ed306e620664577ec9724c
[ "MIT" ]
57
2020-04-01T14:22:53.000Z
2022-01-31T13:09:49.000Z
39.794872
547
0.549533
[ [ [ "<a href=\"https://colab.research.google.com/github/AIWintermuteAI/aXeleRate/blob/dev/resources/aXeleRate_mark_detector.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "## M.A.R.K. Detection model Training and Inference\n\nIn this notebook we will use axelerate, Keras-based framework for AI on the edge, to quickly setup model training and then after training session is completed convert it to .tflite and .kmodel formats.\n\nFirst, let's take care of some administrative details. \n\n1) Before we do anything, make sure you have choosen GPU as Runtime type (in Runtime - > Change Runtime type).\n\n2) We need to mount Google Drive for saving our model checkpoints and final converted model(s). Press on Mount Google Drive button in Files tab on your left. \n\nIn the next cell we clone axelerate Github repository and import it. \n\n**It is possible to use pip install or python setup.py install, but in that case you will need to restart the enironment.** Since I'm trying to make the process as streamlined as possibile I'm using sys.path.append for import.", "_____no_output_____" ] ], [ [ "%load_ext tensorboard\n#we need imgaug 0.4 for image augmentations to work properly, see https://stackoverflow.com/questions/62580797/in-colab-doing-image-data-augmentation-with-imgaug-is-not-working-as-intended\n!pip uninstall -y imgaug && pip uninstall -y albumentations && pip install imgaug==0.4\n!git clone https://github.com/AIWintermuteAI/aXeleRate.git\nimport sys\nsys.path.append('/content/aXeleRate')\nfrom axelerate import setup_training, setup_inference", "_____no_output_____" ] ], [ [ "At this step you typically need to get the dataset. You can use !wget command to download it from somewhere on the Internet or !cp to copy from My Drive as in this example\n```\n!cp -r /content/drive/'My Drive'/pascal_20_segmentation.zip .\n!unzip --qq pascal_20_segmentation.zip\n```\nDataset preparation and postprocessing are discussed in the article here:\n\nThe annotation tool I use is LabelImg\nhttps://github.com/tzutalin/labelImg\n\nLet's visualize our detection model test dataset. There are images in validation folder with corresponding annotations in PASCAL-VOC format in validation annotations folder.\n", "_____no_output_____" ] ], [ [ "%matplotlib inline\n!gdown https://drive.google.com/uc?id=1s2h6DI_1tHpLoUWRc_SavvMF9jYG8XSi #dataset\n!gdown https://drive.google.com/uc?id=1-bDRZ9Z2T81SfwhHEfZIMFG7FtMQ5ZiZ #pre-trained model\n\n!unzip --qq mark_dataset.zip\n\nfrom axelerate.networks.common_utils.augment import visualize_detection_dataset\n\nvisualize_detection_dataset(img_folder='mark_detection/imgs_validation', ann_folder='mark_detection/ann_validation', num_imgs=10, img_size=224, augment=True)", "_____no_output_____" ] ], [ [ "Next step is defining a config dictionary. Most lines are self-explanatory.\n\nType is model frontend - Classifier, Detector or Segnet\n\nArchitecture is model backend (feature extractor) \n\n- Full Yolo\n- Tiny Yolo\n- MobileNet1_0\n- MobileNet7_5 \n- MobileNet5_0 \n- MobileNet2_5 \n- SqueezeNet\n- NASNetMobile\n- DenseNet121\n- ResNet50\n\nFor more information on anchors, please read here\nhttps://github.com/pjreddie/darknet/issues/568\n\nLabels are labels present in your dataset.\nIMPORTANT: Please, list all the labels present in the dataset.\n\nobject_scale determines how much to penalize wrong prediction of confidence of object predictors\n\nno_object_scale determines how much to penalize wrong prediction of confidence of non-object predictors\n\ncoord_scale determines how much to penalize wrong position and size predictions (x, y, w, h)\n\nclass_scale determines how much to penalize wrong class prediction\n\nFor converter type you can choose the following:\n\n'k210', 'tflite_fullint', 'tflite_dynamic', 'edgetpu', 'openvino', 'onnx'\n", "_____no_output_____" ], [ "## Parameters for Person Detection\n\nK210, which is where we will run the network, has constrained memory (5.5 RAM) available, so with Micropython firmware, the largest model you can run is about 2 MB, which limits our architecture choice to Tiny Yolo, MobileNet(up to 0.75 alpha) and SqueezeNet. Out of these 3 architectures, only one comes with pre-trained model - MobileNet. So, to save the training time we will use Mobilenet with alpha 0.75, which has ... parameters. For objects that do not have that much variety, you can use MobileNet with lower alpha, down to 0.25.", "_____no_output_____" ] ], [ [ "config = {\n \"model\":{\n \"type\": \"Detector\",\n \"architecture\": \"MobileNet5_0\",\n \"input_size\": 224,\n \"anchors\": [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828],\n \"labels\": [\"mark\"],\n \"coord_scale\" : \t\t1.0,\n \"class_scale\" : \t\t1.0,\n \"object_scale\" : \t\t5.0,\n \"no_object_scale\" : \t1.0\n },\n \"weights\" : {\n \"full\": \t\t\t\t\"\",\n \"backend\": \t\t \"imagenet\"\n },\n \"train\" : {\n \"actual_epoch\": 50,\n \"train_image_folder\": \"mark_detection/imgs\",\n \"train_annot_folder\": \"mark_detection/ann\",\n \"train_times\": 1,\n \"valid_image_folder\": \"mark_detection/imgs_validation\",\n \"valid_annot_folder\": \"mark_detection/ann_validation\",\n \"valid_times\": 1,\n \"valid_metric\": \"mAP\",\n \"batch_size\": 32,\n \"learning_rate\": 1e-3,\n \"saved_folder\": \t\tF\"/content/drive/MyDrive/mark_detector\",\n \"first_trainable_layer\": \"\",\n \"augumentation\":\t\t\t\tTrue,\n \"is_only_detect\" : \t\tFalse\n },\n \"converter\" : {\n \"type\": \t\t\t\t[\"k210\",\"tflite\"]\n }\n }", "_____no_output_____" ] ], [ [ "Let's check what GPU we have been assigned in this Colab session, if any.", "_____no_output_____" ] ], [ [ "from tensorflow.python.client import device_lib\ndevice_lib.list_local_devices()", "_____no_output_____" ] ], [ [ "Also, let's open Tensorboard, where we will be able to watch model training progress in real time. Training and validation logs also will be saved in project folder.\nSince there are no logs before we start the training, tensorboard will be empty. Refresh it after first epoch.", "_____no_output_____" ] ], [ [ "%tensorboard --logdir logs", "_____no_output_____" ] ], [ [ "Finally we start the training by passing config dictionary we have defined earlier to setup_training function. The function will start the training with Checkpoint, Reduce Learning Rate on Plateau and Early Stopping callbacks. After the training has stopped, it will convert the best model into the format you have specified in config and save it to the project folder.", "_____no_output_____" ] ], [ [ "from keras import backend as K \nK.clear_session()\nmodel_path = setup_training(config_dict=config)", "_____no_output_____" ] ], [ [ "After training it is good to check the actual perfomance of your model by doing inference on your validation dataset and visualizing results. This is exactly what next block does. Obviously since our model has only trained on a few images the results are far from stellar, but if you have a good dataset, you'll have better results.", "_____no_output_____" ] ], [ [ "from keras import backend as K \nK.clear_session()\nsetup_inference(config, model_path)", "_____no_output_____" ] ], [ [ "My end results are:\n\n{'fscore': 0.942528735632184, 'precision': 0.9318181818181818, 'recall': 0.9534883720930233}\n\n**You can obtain these results by loading a pre-trained model.**\n\nGood luck and happy training! Have a look at these articles, that would allow you to get the most of Google Colab or connect to local runtime if there are no GPUs available;\n\nhttps://medium.com/@oribarel/getting-the-most-out-of-your-google-colab-2b0585f82403\n\nhttps://research.google.com/colaboratory/local-runtimes.html", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d0382943e26d0deb1b175a9bd9b54f87dfff95c1
615,780
ipynb
Jupyter Notebook
analysis/example/CGMFtkHistoriesExample.ipynb
beykyle/omp-uq
7d9b720d874b634f3a56878ce34f29553441194e
[ "MIT" ]
null
null
null
analysis/example/CGMFtkHistoriesExample.ipynb
beykyle/omp-uq
7d9b720d874b634f3a56878ce34f29553441194e
[ "MIT" ]
null
null
null
analysis/example/CGMFtkHistoriesExample.ipynb
beykyle/omp-uq
7d9b720d874b634f3a56878ce34f29553441194e
[ "MIT" ]
null
null
null
524.068085
57,080
0.943691
[ [ [ "# Example of how to use the CGMFtk package", "_____no_output_____" ] ], [ [ "# Table of Contents\n1. [Import Modules](#import)\n2. [Read the History File](#read)\n3. [Summary Table](#table)\n4. [Histogram Fission Fragment Properties](#ffHistograms)\n5. [Correlated Observables](#correlations)\n6. [Neutron Properties](#neutrons)\n7. [Gamma Properties](#gammas)\n8. [Gamma-ray Timing Information](#timing)\n9. [Angular Correlations](#angles)", "_____no_output_____" ], [ "### 1. import modules for the notebook\n<a id='import'></a>", "_____no_output_____" ] ], [ [ "import numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom CGMFtk import histories as fh", "_____no_output_____" ], [ "# also define some plotting features\nimport matplotlib as mpl\nmpl.rcParams['font.size'] = 12\nmpl.rcParams['font.family'] = 'Helvetica','serif'\nmpl.rcParams['font.weight'] = 'normal'\nmpl.rcParams['axes.labelsize'] = 18.\nmpl.rcParams['xtick.labelsize'] = 18.\nmpl.rcParams['ytick.labelsize'] = 18.\nmpl.rcParams['lines.linewidth'] = 2.\nmpl.rcParams['xtick.major.pad'] = '10'\nmpl.rcParams['ytick.major.pad'] = '10'\nmpl.rcParams['image.cmap'] = 'BuPu'", "_____no_output_____" ], [ "# define a working directory where the history files are stored\nworkdir = './'\nhistFile = 'histories.out'\ntimeFile = 'histories.out'\nyeildFile = 'yeilds.cgmf.0'\n\nnevents = int(1E6)", "_____no_output_____" ] ], [ [ "### 2. Read CGMF history file\n<a id='read'></a>", "_____no_output_____" ] ], [ [ "# run Cf-252 sf with a single OM param file (#42)\ndirectory = \"/home/beykyle/db/projects/OM/KDOMPuq/KDUQSamples\"\nfor filename in os.scandir(directory):\n if filename.is_file() and \"42\" in filename.path:\n #if filename.is_file():\n print(filename.path)\n os.system(\"mpirun -np 8 --use-hwthread-cpus cgmf.mpi.x -t -1 -i 98252 -e 0.0 -n 100 -o\" + filename.path)\n os.system(\"cat histories.cgmf.* > histories.out\")\n os.system(\"rm histories.cgmf.*\")\n \n ", "/home/beykyle/db/projects/OM/KDOMPuq/KDUQSamples/42.json\n" ], [ "print(\"Analyzing histories\")\nhist = fh.Histories(workdir + histFile, nevents=nevents)\n# print the number of events in the file\nprint ('This file contains ',str(hist.getNumberEvents()),' events and ',str(hist.getNumberFragments()),' fission fragments')", "Analyzing histories\nWARNING\nYou asked for 1000000 events and there are only 800 in this history file\nThis file contains 800 events and 1600 fission fragments\n" ] ], [ [ "With the option 'nevents', the number of fission events that are read can be specified:", "_____no_output_____" ], [ "hist = fh.Histories('92235_1MeV.cgmf',nevents=5000)", "_____no_output_____" ], [ "### 3. Summary Table\n<a id='table'></a>", "_____no_output_____" ] ], [ [ "# provide a summary table of the fission events\nhist.summaryTable()", "_____no_output_____" ] ], [ [ "### 4. Fission Fragment Properties\n<a id='ffHistograms'></a>", "_____no_output_____" ], [ "With the histogram function from matplotlib, we can easily plot distributions of the fission fragment characteristics", "_____no_output_____" ] ], [ [ "# plot the distributions of the fission fragments\nA = hist.getA() # get A of all fragments\nAL = hist.getALF() # get A of light fragments\nAH = hist.getAHF() # get A of heavy fragments\nfig = plt.figure(figsize=(8,6))\nbins = np.arange(min(A),max(A))\nh,b = np.histogram(A,bins=bins,density=True)\nplt.plot(b[:-1],h,'-o')\nplt.xlabel('Mass (A)')\nplt.ylabel('Frequency')\nplt.show()\n\nZ = hist.getZ()\nZL = hist.getZLF()\nZH = hist.getZHF()\nfig = plt.figure(figsize=(8,6))\nbins = np.arange(min(Z),max(Z))\nh,b = np.histogram(Z,bins=bins,density=True)\nplt.plot(b[:-1],h,'-o')\nplt.xlabel('Charge (Z)')\nplt.ylabel('Frequency')\nplt.show()\n\nfig = plt.figure(figsize=(8,6))\nTKEpre = hist.getTKEpre() # TKE before neutron emission\nTKEpost = hist.getTKEpost() # TKE after neutron emission\nbins = np.arange(min(TKEpre),max(TKEpre))\nh,b = np.histogram(TKEpre,bins=bins,density=True)\nplt.plot(0.5*(b[:-1]+b[1:]),h,'-o',label='Before neutron emission')\nbins = np.arange(min(TKEpost),max(TKEpost))\nh,b = np.histogram(TKEpost,bins=bins,density=True)\nplt.plot(0.5*(b[:-1]+b[1:]),h,'-o',label='After neutron emission')\nplt.legend()\nplt.xlabel('Total Kinetic Energy (MeV)')\nplt.ylabel('Frequency')\nplt.show()", "_____no_output_____" ] ], [ [ "With the 2D histogram feature, we can see correlations between the calculated features from CGMF", "_____no_output_____" ] ], [ [ "TKEpre = hist.getTKEpre()\nTXE = hist.getTXE()\nbx = np.arange(min(TKEpre),max(TKEpre))\nby = np.arange(min(TXE),max(TXE))\nfig = plt.figure(figsize=(8,6))\nplt.hist2d(TKEpre,TXE,bins=(bx,by),density=True)\nplt.xlabel('Total Kinetic Energy (MeV)')\nplt.ylabel('Total Excitation Energy (MeV)')\nplt.colorbar()\nplt.show()", "_____no_output_____" ] ], [ [ "### 5. Correlated Observables\n<a id='correlations'></a>", "_____no_output_____" ], [ "Many observables within fission are correlated with one another. Sometimes, these are best visualized as two-dimensional histograms as in the TKE-TXE plot directly above. Other times, it is helpful to plot certain observables as a function of mass or TKE. There are routines within CGMFtk that easily construct those, as demonstrated here:", "_____no_output_____" ] ], [ [ "# nubar as a function of mass\n## nubarg, excitation energy, kinetic energy (pre), and spin are available as a function of mass\nnubarA = hist.nubarA()\nTKEA = hist.TKEA()\nfig = plt.figure(figsize=(16,6))\nplt.subplot(121)\nplt.plot(nubarA[0],nubarA[1],'ko')\nplt.xlabel('Mass (u)')\nplt.ylabel(r'$\\overline{\\nu}$')\nplt.subplot(122)\nplt.plot(TKEA[0],TKEA[1],'ko')\nplt.xlabel('Mass (u)')\nplt.ylabel(r'Total Kinetic Energy (MeV)')\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "### 6. Neutron properties\n<a id='neutrons'></a>", "_____no_output_____" ] ], [ [ "# construct and plot the neutron multiplicity distribution\nnu,pnu = hist.Pnu()\nfig = plt.figure(figsize=(8,6))\nplt.plot(nu,pnu,'k*--',markersize=10)\nplt.xlabel(r'$\\nu$')\nplt.ylabel(r'P($\\nu$)')\nplt.show()", "_____no_output_____" ], [ "# construct and plot the prompt neutron spectrum\nfig = plt.figure(figsize=(16,6))\nplt.subplot(121)\nebins,pfns = hist.pfns()\nplt.step(ebins,pfns,where='mid')\nplt.xlim(0,20)\nplt.xlabel('Outgoing neutron energy (MeV)')\nplt.ylabel('PFNS')\nplt.subplot(122)\nplt.step(ebins,pfns,where='mid')\nplt.xlim(0.01,20)\nplt.xscale('log')\nplt.yscale('log')\nplt.xlabel('Outgoing neutron energy (MeV)')\nplt.ylabel('PFNS')\nplt.tight_layout()\nplt.show()", "_____no_output_____" ], [ "# average number of prompt neutrons\nprint ('nubar (per fission event) = ',hist.nubartot())\nprint ('average number of neutrons per fragment = ',hist.nubar())", "nubar (per fission event) = 3.76375\naverage number of neutrons per fragment = 1.881875\n" ], [ "# average neutron energies\nprint ('Neutron energies in the lab:')\nprint ('Average energy of all neutrons = ',hist.meanNeutronElab())\nprint ('Average energy of neutrons from fragments = ',hist.meanNeutronElabFragments())\nprint ('Average energy of neutrons from light fragment = ',hist.meanNeutronElabLF())\nprint ('Average energy of neutrons from heavy fragment = ',hist.meanNeutronElabHF())\nprint (' ')\nprint ('Neutron energies in the center of mass:')\nprint ('Average energy of neutrons from fragments = ',hist.meanNeutronEcmFragments())\nprint ('Average energy of neutrons from light fragment = ',hist.meanNeutronEcmLF())\nprint ('Average energy of neutrons from heavy fragment = ',hist.meanNeutronEcmHF())", "Neutron energies in the lab:\nAverage energy of all neutrons = 2.0337924277648622\nAverage energy of neutrons from fragments = 2.0337924277648622\nAverage energy of neutrons from light fragment = 2.2622832643406268\nAverage energy of neutrons from heavy fragment = 1.7410818181818182\n \nNeutron energies in the center of mass:\nAverage energy of neutrons from fragments = 1.2891006310195947\nAverage energy of neutrons from light fragment = 1.3413187463039622\nAverage energy of neutrons from heavy fragment = 1.2222060606060605\n" ] ], [ [ "Note that the energies are not recorded for the pre-fission neutrons in the center of mass frame", "_____no_output_____" ], [ "### 7. Gamma properties\n<a id='gammas'></a>", "_____no_output_____" ] ], [ [ "# construct and plot the gamma multiplicity distribution\nnug,pnug = hist.Pnug()\nfig = plt.figure(figsize=(8,6))\nplt.plot(nug,pnug,'k*--',markersize=10)\nplt.xlabel(r'$N_\\gamma$')\nplt.ylabel(r'P($N_\\gamma$)')\nplt.show()", "_____no_output_____" ], [ "# construct and plot the prompt neutron spectrum\nfig = plt.figure(figsize=(16,6))\nplt.subplot(121)\nebins,pfgs = hist.pfgs()\nplt.step(ebins,pfgs,where='mid')\nplt.xlim(0,5)\nplt.xlabel(r'Outgoing $\\gamma$ energy (MeV)')\nplt.ylabel('PFGS')\nplt.subplot(122)\nplt.step(ebins,pfgs,where='mid')\nplt.xlim(0.1,5)\nplt.xscale('log')\nplt.yscale('log')\nplt.xlabel(r'Outgoing $\\gamma$ energy (MeV)')\nplt.ylabel('PFGS')\nplt.ylim(1e-2,30)\nplt.tight_layout()\nplt.show()", "_____no_output_____" ], [ "# average number of prompt neutrons\nprint ('nugbar (per fission event) = ',hist.nubargtot())\nprint ('average number of gammas per fragment = ',hist.nubarg())", "nugbar (per fission event) = 9.76625\naverage number of gammas per fragment = 4.883125\n" ], [ "# perform gamma-ray spectroscopy\ngE = 0.2125 # gamma ray at 212.5 keV\ndE = 0.01 # 1% energy resolution\ngspec1 = hist.gammaSpec(gE,dE*gE,post=True)\n\n# calculate the percentage of events for each A/Z\nAs1 = np.unique(gspec1[:,1])\ntotEvents = len(gspec1)\nfracA1 = []\nfor A in As1:\n mask = gspec1[:,1]==A\n fracA1.append(len(gspec1[mask])/totEvents)\nZs1 = np.unique(gspec1[:,0])\nfracZ1 = []\nfor Z in Zs1:\n mask = gspec1[:,0]==Z\n fracZ1.append(len(gspec1[mask])/totEvents)\n\nfig = plt.figure(figsize=(8,6))\nplt.plot(As1,fracA1,'--')\nplt.xlabel('Fission Fragment Mass (A)')\nplt.ylabel('Fraction of Events')\nplt.text(135,0.170,r'$\\epsilon_\\gamma$=212.5 keV',fontsize=18)\nplt.show()\n\nfig = plt.figure(figsize=(8,6))\nplt.plot(Zs1,fracZ1,'--')\nplt.xlabel('Fission Fragment Charge (Z)')\nplt.ylabel('Fraction of Events')\nplt.show()", "_____no_output_____" ], [ "# average neutron energies\nprint ('Gamma energies in the lab:')\nprint ('Average energy of all gammas = ',hist.meanGammaElab())\nprint ('Average energy of gammas from light fragment = ',hist.meanGammaElabLF())\nprint ('Average energy of gammas from heavy fragment = ',hist.meanGammaElabHF())", "Gamma energies in the lab:\nAverage energy of all gammas = 0.7157650070395495\nAverage energy of gammas from light fragment = 0.7317019104946348\nAverage energy of gammas from heavy fragment = 0.7005107715430862\n" ] ], [ [ "Note that in the current version of CGMF, only the doppler shifted lab energies are recorded in the history file", "_____no_output_____" ], [ "### 8. Gamma-ray Timing Information\n<a id='timing'></a>", "_____no_output_____" ], [ "We can also calculate quantities that are related to the time at which the 'late' prompt gamma rays are emitted. When the option -t -1 is included in the run time options for CGMF, these gamma-ray times are printed out in the CGMF history file. The Histories class can read these times based on the header of the CGMF history file.", "_____no_output_____" ] ], [ [ "histTime = fh.Histories(workdir + timeFile, nevents=nevents*2)", "WARNING\nYou asked for 2000000 events and there are only 800 in this history file\n" ], [ "# gamma-ray times can be retrieved through \ngammaAges = histTime.getGammaAges()", "_____no_output_____" ] ], [ [ "The nubargtot function can also be used to construct the average gamma-ray multiplicity per fission event as a function of time. In the call to nubarg() or nubargtot(), timeWindow=True should be included which uses the default timings provided in the function (otherwise, passing a numpy array or list of times to timeWindow will use those times). Optionally, a minimum gamma-ray energy cut-off can also be included, Eth.", "_____no_output_____" ] ], [ [ "times,nubargTime = histTime.nubarg(timeWindow=True) # include timeWindow as a boolean or list of times (in seconds) to activate this feature\nfig = plt.figure(figsize=(8,6))\nplt.plot(times,nubargTime,'o',label='Eth=0. MeV')\ntimes,nubargTime = histTime.nubarg(timeWindow=True,Eth=0.1)\nplt.plot(times,nubargTime,'o',label='Eth=0.1 MeV')\nplt.xlabel('Time since fission (s)')\nplt.ylabel(r'Averge $\\gamma$-ray multiplicity')\nplt.xscale('log')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "The prompt fission gamma-ray spectrum function, pfgs(), can also be used to calculate this quantity within a certain time window since the fission event. The time window is defined using minTime and maxTime to set the lower and upper boundaries.", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(8,6))\nbE,pfgsTest = histTime.pfgs(minTime=5e-8,maxTime=500e-8)\nplt.step(bE,pfgsTest,label='Time window')\nbE,pfgsTest = histTime.pfgs()\nplt.step(bE,pfgsTest,label='All events')\nplt.yscale('log')\nplt.xlim(0,2)\nplt.ylim(0.1,100)\nplt.xlabel('Gamma-ray Energy (MeV)')\nplt.ylabel('Prompt Fission Gamma Spectrum')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "# calculate the gamma-ray multiplicity as a function of time since fission for a specific fission fragment\ntimes,gMultiplicity = histTime.gammaMultiplicity(minTime=1e-8,maxTime=1e-6,Afragment=134,Zfragment=52)\n\n# also compare to an exponential decay with the half life of the state\nf = np.exp(-times*np.log(2)/1.641e-7) # the half life of 134Te is 164.1 ns\nnorm = gMultiplicity[0]/f[0]\n\nfig = plt.figure(figsize=(8,6))\nplt.plot(times*1e9,gMultiplicity/norm,'k-',label='CGMF')\nplt.plot(times*1e9,f,'r--',label=r'exp($-t\\cdot$log(2)/$\\tau_{1/2}$)')\nplt.legend()\nplt.yscale('log')\nplt.xlabel('Time since fission (ns)')\nplt.ylabel(r'N$_\\gamma$(t) (arb. units)')\nplt.show()", "_____no_output_____" ], [ "# calculate the isomeric ratios for specific states in nuclei\n# e.g. isomeric ratio for the 1/2- state in 99Nb, ground state is 9/2+, lifetime is 150 s\nr = histTime.isomericRatio(thresholdTime=1,A=99,Z=41,Jm=0.5,Jgs=4.5)\nprint ('99Nb:',round(r,2)) \n# e.g. isomeric ratio for the 11/2- state in 133Te, ground state is 3/2+, lifetime is 917.4 s\nr = histTime.isomericRatio(thresholdTime=1,A=133,Z=52,Jm=5.5,Jgs=1.5)\nprint ('133Te:',round(r,2))", "99Nb: 1.0\n133Te: 0.14\n" ] ], [ [ "### 9. Angular Correlations\n<a id='angles'></a>", "_____no_output_____" ], [ "For the fission fragment angular distribution with respect to the beam axis/z-axis, there is one option: afterEmission=True/False. afterEmission=True uses these angles after neutron emission and afterEmission=False uses these angles before neutron emission. The default is True.", "_____no_output_____" ] ], [ [ "# calculate cos(theta) between the fragments and z-axis/beam axis\nFFangles = hist.FFangles()\nbins = np.linspace(-1,1,30)\nh,b = np.histogram(FFangles,bins=bins,density=True)\n# only light fragments\nhLight,b = np.histogram(FFangles[::2],bins=bins,density=True)\n# only heavy fragments\nhHeavy,b = np.histogram(FFangles[1::2],bins=bins,density=True)", "_____no_output_____" ], [ "x = 0.5*(b[:-1]+b[1:])\nfig = plt.figure(figsize=(8,6))\nplt.plot(x,h,'k*',label='All Fragments')\nplt.plot(x,hLight,'ro',label='Light Fragments')\nplt.plot(x,hHeavy,'b^',label='Heavy Fragments')\nplt.xlabel(r'cos($\\theta$)')\nplt.ylabel('Frequency')\nplt.ylim(0.45,0.55)\nplt.title('Fission fragment angles with respect to beam axis')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "There are several options when calculating the angles of the neutrons with respect to the beam axis/z-axis. The first is including a neutron threshold energy with keyword, Eth (given in MeV). We can also calculate these angles in the lab frame (lab=True, default) or in the center of mass frame of the compound system (lab=False). Finally, we can include pre-fission neutrons (includePrefission=True, default) or not include them (includePreFission=False). However, the pre-fission neutrons can only be include in the lab frame.", "_____no_output_____" ] ], [ [ "# calculate the angles between the neutrons and the z-axis/beam axis\nnAllLab,nLLab,nHLab = hist.nangles(lab=True) # all neutrons, from the light fragment, from the heavy fragment\nnAllCM,nLCM,nHCM = hist.nangles(lab=False) # center of mass frame of the compound", "_____no_output_____" ], [ "bins = np.linspace(-1,1,30)\nhAllLab,b = np.histogram(nAllLab,bins=bins,density=True)\nhLightLab,b = np.histogram(nLLab,bins=bins,density=True)\nhHeavyLab,b = np.histogram(nHLab,bins=bins,density=True)\nhAllcm,b = np.histogram(nAllCM,bins=bins,density=True)\nhLightcm,b = np.histogram(nLCM,bins=bins,density=True)\nhHeavycm,b = np.histogram(nHCM,bins=bins,density=True)", "_____no_output_____" ], [ "x = 0.5*(b[:-1]+b[1:])\nfig = plt.figure(figsize=(8,6))\nplt.plot(x,hAllLab,'k*',label='All Fragments')\nplt.plot(x,hLightLab,'ro',label='Light Fragments')\nplt.plot(x,hHeavyLab,'b^',label='Heavy Fragments')\nplt.xlabel(r'cos($\\theta$)')\nplt.ylabel('Frequency')\nplt.ylim(0.45,0.55)\nplt.title('Neutron Angles with respect to beam axis in the Lab Frame')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "fig = plt.figure(figsize=(8,6))\nplt.plot(x,hAllLab,'k*',label='Lab Frame')\nplt.plot(x,hAllcm,'ro',label='CoM Frame')\nplt.xlabel(r'cos($\\theta$)')\nplt.ylabel('Frequency')\nplt.ylim(0.45,0.55)\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "There are again several options that we can use when calculating the angles between all pairs of neutrons (from all framgments) and the ligh fragments, all of which have been seen in the last two examples. These include, Eth (neutron threshold energy), afterEmission (fission fragment angles are post or pre neutron emission), and includePrefission (to include or not include pre-fission neutrons).", "_____no_output_____" ] ], [ [ "# calculate the angles between the neutrons and the light fragments\nnFall,nFLight,nFHeavy = hist.nFangles()\nbins = np.linspace(-1,1,30)\nhall,b = np.histogram(nFall,bins=bins,density=True)\nhlight,b = np.histogram(nFLight,bins=bins,density=True)\nhheavy,b = np.histogram(nFHeavy,bins=bins,density=True)", "_____no_output_____" ], [ "x = 0.5*(b[:-1]+b[1:])\nfig = plt.figure(figsize=(8,6))\nplt.plot(x,hall,'k*',label='All Fragments')\nplt.plot(x,hlight,'ro',label='Light Fragments')\nplt.plot(x,hheavy,'b^',label='Heavy Fragments')\nplt.xlabel(r'cos($\\theta$)')\nplt.ylabel('Frequency')\nplt.legend()\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d03832a5e1c033db52a411e4be8954dd0b0eeb08
1,032,575
ipynb
Jupyter Notebook
5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb
shiwei23/Chromatin_Analysis_Scripts
909b9b81de8fcf04dd4c39ac21a84864ce2003ff
[ "MIT" ]
null
null
null
5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb
shiwei23/Chromatin_Analysis_Scripts
909b9b81de8fcf04dd4c39ac21a84864ce2003ff
[ "MIT" ]
null
null
null
5kb_DNA_analysis/single_fov/20210320_updated_single_fov_IgH_batch1_proB_dox+_2color.ipynb
shiwei23/Chromatin_Analysis_Scripts
909b9b81de8fcf04dd4c39ac21a84864ce2003ff
[ "MIT" ]
null
null
null
322.982484
376,973
0.91017
[ [ [ "# 0. required packages for h5py", "_____no_output_____" ] ], [ [ "%run \"..\\..\\Startup_py3.py\"\nsys.path.append(r\"..\\..\\..\\..\\Documents\")\n\nimport ImageAnalysis3 as ia\n%matplotlib notebook\n\nfrom ImageAnalysis3 import *\nprint(os.getpid())\n\nimport h5py\nfrom ImageAnalysis3.classes import _allowed_kwds\nimport ast", "18112\n" ] ], [ [ "# 1. Create field-of-view class", "_____no_output_____" ] ], [ [ "reload(ia)\nreload(classes)\nreload(classes.batch_functions)\nreload(classes.field_of_view)\nreload(io_tools.load)\n\nreload(visual_tools)\nreload(ia.correction_tools)\nreload(ia.correction_tools.alignment)\nreload(ia.spot_tools.matching)\nreload(ia.segmentation_tools.chromosome)\nreload(ia.spot_tools.fitting)\n\nfov_param = {'data_folder':r'\\\\10.245.74.158\\Chromatin_NAS_1\\20210320-proB_Dox_IAA_STI_CTP-08_2color',\n 'save_folder':r'\\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+',\n #'save_folder':r'D:\\Pu_Temp\\202009_IgH_proB_DMSO_2color',\n 'experiment_type': 'DNA',\n 'num_threads': 24,\n 'correction_folder':r'\\\\10.245.74.158\\Chromatin_NAS_0\\Corrections\\20201012-Corrections_2color',\n 'shared_parameters':{\n 'single_im_size':[35,2048,2048],\n 'corr_channels':['750','647'],\n 'num_empty_frames': 0, \n 'corr_hot_pixel':True,\n 'corr_Z_shift':False,\n 'min_num_seeds':500,\n 'max_num_seeds': 2500,\n 'spot_seeding_th':125,\n 'normalize_intensity_local':False,\n 'normalize_intensity_background':False,\n }, \n }", "_____no_output_____" ], [ "fov = classes.field_of_view.Field_of_View(fov_param, _fov_id=30,\n _color_info_kwargs={\n '_color_filename':'Color_Usage_clean',\n }, \n _prioritize_saved_attrs=False,\n )", "Get Folder Names: (ia.get_img_info.get_folders)\n- Number of folders: 78\n- Number of field of views: 64\n- Importing csv file: \\\\10.245.74.158\\Chromatin_NAS_1\\20210320-proB_Dox_IAA_STI_CTP-08_2color\\Analysis\\Color_Usage_clean.csv\n- header: ['Hyb', '750', '647', '488', '405']\n-- Hyb H0R0 exists in this data\n-- DAPI exists in hyb: H0R0\n- 75 folders are found according to color-usage annotation.\n+ loading fov_info from file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ base attributes loaded:['be8ce21d23df451e85292b57a8b61273', 'cand_chrom_coords', 'chrom_coords', 'chrom_im', 'ref_im'] in 11.353s.\n+ loading correction from file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ load bleed correction profile directly from savefile.\n++ load chromatic correction profile directly from savefile.\n++ load chromatic_constants correction profile directly from savefile.\n++ load illumination correction profile directly from savefile.\n+ loading segmentation from file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ base attributes loaded:[] in 0.005s.\n-- saving fov_info to file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ base attributes saved:['analysis_folder', 'annotated_folders', 'be8ce21d23df451e85292b57a8b61273', 'bead_channel_index', 'cand_chrom_coords', 'channels', 'chrom_coords', 'chrom_im', 'color_dic', 'color_filename', 'color_format', 'correction_folder', 'dapi_channel_index', 'data_folder', 'drift', 'drift_filename', 'drift_folder', 'experiment_folder', 'folders', 'fov_id', 'fov_name', 'map_folder', 'num_threads', 'ref_filename', 'ref_id', 'ref_im', 'rotation', 'save_filename', 'save_folder', 'segmentation_dim', 'segmentation_folder', 'shared_parameters', 'use_dapi'] in 18.835s.\n" ] ], [ [ "### 2. Process image into candidate spots", "_____no_output_____" ] ], [ [ "reload(io_tools.load)\nreload(spot_tools.fitting)\nreload(correction_tools.chromatic)\nreload(classes.batch_functions)\n\n# process image into spots\nid_list, spot_list = fov._process_image_to_spots('unique', \n #_sel_ids=np.arange(41,47),\n _load_common_reference=True,\n _load_with_multiple=False,\n _save_images=True,\n _warp_images=False, \n _overwrite_drift=False,\n _overwrite_image=False,\n _overwrite_spot=False,\n _verbose=True)", "-- No folder selected, allow processing all 75 folders\n+ load reference image from file:\\\\10.245.74.158\\Chromatin_NAS_1\\20210320-proB_Dox_IAA_STI_CTP-08_2color\\H0R0\\Conv_zscan_30.dax\n- correct the whole fov for image: \\\\10.245.74.158\\Chromatin_NAS_1\\20210320-proB_Dox_IAA_STI_CTP-08_2color\\H0R0\\Conv_zscan_30.dax\n-- loading illumination correction profile from file:\n\t 488 illumination_correction_488_2048x2048.npy\n-- loading image from file:\\\\10.245.74.158\\Chromatin_NAS_1\\20210320-proB_Dox_IAA_STI_CTP-08_2color\\H0R0\\Conv_zscan_30.dax in 8.178s\n-- removing hot pixels for channels:['488'] in 6.360s\n-- illumination correction for channels: 488, in 1.390s\n-- -- generate translation function with drift:[0. 0. 0.] in 0.000s\n-- finish correction in 16.463s\n-- saving fov_info to file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ base attributes saved:['ref_im'] in 4.984s.\n-- checking unique, region:[41 42] in 0.047s.\n-- checking unique, region:[44 45] in 0.000s.\n-- checking unique, region:[47 48] in 0.016s.\n-- checking unique, region:[50 51] in 0.007s.\n-- checking unique, region:[53 54] in 0.000s.\n-- checking unique, region:[56 57] in 0.009s.\n-- checking unique, region:[60 61] in 0.000s.\n-- checking unique, region:[63 64] in 0.000s.\n-- checking unique, region:[66 67] in 0.016s.\n-- checking unique, region:[69 70] in 0.000s.\n-- checking unique, region:[72 73] in 0.000s.\n-- checking unique, region:[75 76] in 0.016s.\n-- checking unique, region:[78 79] in 0.000s.\n-- checking unique, region:[81 82] in 0.000s.\n-- checking unique, region:[84 85] in 0.016s.\n-- checking unique, region:[87 88] in 0.000s.\n-- checking unique, region:[90 91] in 0.000s.\n-- checking unique, region:[93 94] in 0.016s.\n-- checking unique, region:[96 97] in 0.000s.\n-- checking unique, region:[ 99 100] in 0.000s.\n-- checking unique, region:[102 103] in 0.016s.\n-- checking unique, region:[105 106] in 0.000s.\n-- checking unique, region:[108 109] in 0.000s.\n-- checking unique, region:[111 112] in 0.016s.\n-- checking unique, region:[114 115] in 0.000s.\n-- checking unique, region:[323 321] in 0.000s.\n-- checking unique, region:[326 324] in 0.016s.\n-- checking unique, region:[329 327] in 0.000s.\n-- checking unique, region:[332 330] in 0.000s.\n-- checking unique, region:[335 333] in 0.016s.\n-- checking unique, region:[339 337] in 0.000s.\n-- checking unique, region:[342 340] in 0.000s.\n-- checking unique, region:[345 343] in 0.016s.\n-- checking unique, region:[348 346] in 0.000s.\n-- checking unique, region:[351 349] in 0.000s.\n-- checking unique, region:[354 352] in 0.016s.\n-- checking unique, region:[357 355] in 0.000s.\n-- checking unique, region:[360 358] in 0.000s.\n-- checking unique, region:[363 361] in 0.017s.\n-- checking unique, region:[366 364] in 0.001s.\n-- checking unique, region:[369 367] in 0.000s.\n-- checking unique, region:[375 373] in 0.014s.\n-- checking unique, region:[388 383] in 0.000s.\n-- checking unique, region:[391 386] in 0.013s.\n-- checking unique, region:[394 389] in 0.006s.\n-- checking unique, region:[ 43 392] in 0.006s.\n-- checking unique, region:[ 49 395] in 0.005s.\n-- checking unique, region:[55 46] in 0.006s.\n-- checking unique, region:[62 52] in 0.005s.\n-- checking unique, region:[68 59] in 0.005s.\n-- checking unique, region:[74 65] in 0.004s.\n-- checking unique, region:[80 71] in 0.005s.\n-- checking unique, region:[86 77] in 0.005s.\n-- checking unique, region:[92 83] in 0.005s.\n-- checking unique, region:[98 89] in 0.005s.\n-- checking unique, region:[104 95] in 0.005s.\n-- checking unique, region:[110 101] in 0.004s.\n-- checking unique, region:[325 107] in 0.000s.\n-- checking unique, region:[331 113] in 0.000s.\n-- checking unique, region:[341 328] in 0.014s.\n-- checking unique, region:[347 334] in 0.000s.\n-- checking unique, region:[353 344] in 0.000s.\n-- checking unique, region:[359 350] in 0.016s.\n-- checking unique, region:[365 356] in 0.000s.\n-- checking unique, region:[371 362] in 0.000s.\n-- checking unique, region:[377 368] in 0.016s.\n-- checking unique, region:[384 374] in 0.000s.\n-- checking unique, region:[390 381] in 0.000s.\n-- checking unique, region:[393 387] in 0.017s.\n+ Start multi-processing of pre-processing for 69 images with 24 threads\n++ processed unique ids: [ 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 59\n 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77\n 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95\n 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113\n 114 115 321 323 324 325 326 327 328 329 330 331 332 333 334 335 337 339\n 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357\n 358 359 360 361 362 363 364 365 366 367 368 369 371 373 374 375 377 381\n 383 384 386 387 388 389 390 391 392 393 394 395] in 3189.44s.\n" ] ], [ [ "# 3. Find chromosomes", "_____no_output_____" ], [ "## 3.1 load chromosome image", "_____no_output_____" ] ], [ [ "overwrite_chrom = False\nchrom_im = fov._load_chromosome_image(_type='reverse', \n _overwrite=overwrite_chrom)", "-- choose chrom images from folder: \\.\n- correct the whole fov for image: \\\\10.245.74.158\\Chromatin_NAS_1\\20210320-proB_Dox_IAA_STI_CTP-08_2color\\H0R0\\Conv_zscan_30.dax\n-- loading illumination correction profile from file:\n\t 647 illumination_correction_647_2048x2048.npy\n-- loading chromatic correction profile from file:\n\t 750 chromatic_correction_750_647_35_2048_2048.npy\n\t 647 None\n-- loading image from file:\\\\10.245.74.158\\Chromatin_NAS_1\\20210320-proB_Dox_IAA_STI_CTP-08_2color\\H0R0\\Conv_zscan_30.dax in 8.030s\n-- removing hot pixels for channels:['647'] in 7.033s\n-- illumination correction for channels: 647, in 1.573s\n-- warp image with chromatic correction for channels: [] and drift:[0. 0. 0.] in 0.000s\n-- finish correction in 38.839s\n-- chromosome image has drift: [0. 0. 0.]\n-- saving fov_info to file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ base attributes saved:['chrom_im'] in 5.277s.\n" ] ], [ [ "## 3.2 find candidate chromosomes", "_____no_output_____" ] ], [ [ "chrom_coords = fov._find_candidate_chromosomes_by_segmentation(_filt_size=4,\n _binary_per_th=99.75, \n _morphology_size=2,\n _overwrite=overwrite_chrom)", "+ loading fov_info from file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ base attributes loaded:[] in 4.192s.\n-- adjust seed image with filter size=4\n-- binarize image with threshold: 99.75%\n-- erosion and dialation with size=2.\n-- find close objects.\n-- random walk segmentation, beta=10.\n" ] ], [ [ "## 3.3 select among candidate chromosomes", "_____no_output_____" ] ], [ [ "chrom_coords = fov._select_chromosome_by_candidate_spots(_good_chr_loss_th=0.3,\n _cand_spot_intensity_th=200,\n _save=True, \n _overwrite=overwrite_chrom)", "+ loading fov_info from file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ base attributes loaded:[] in 5.189s.\n+ loading unique from file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n" ] ], [ [ "### visualize chromosomes selections", "_____no_output_____" ] ], [ [ "%matplotlib notebook\n%matplotlib notebook\n## visualize\ncoord_dict = {'coords':[np.flipud(_coord) for _coord in fov.chrom_coords],\n 'class_ids':list(np.zeros(len(fov.chrom_coords),dtype=np.int)),\n }\n\nvisual_tools.imshow_mark_3d_v2([fov.chrom_im], \n given_dic=coord_dict,\n save_file=None,\n )\n", "_____no_output_____" ] ], [ [ "## select spots based on chromosomes", "_____no_output_____" ] ], [ [ "fov._load_from_file('unique')", "+ loading unique from file: \\\\10.245.74.212\\Chromatin_NAS_2\\IgH_analyzed_results\\20210320_IgH_proB_iaa_dox+\\Conv_zscan_30.hdf5\n++ finish loading unique in 0.836s. \n" ], [ "intensity_th = 200\nfrom ImageAnalysis3.spot_tools.picking import assign_spots_to_chromosomes\n\nkept_spots_list = []\nfor _spots in fov.unique_spots_list:\n kept_spots_list.append(_spots[_spots[:,0] > intensity_th])\n# finalize candidate spots\ncand_chr_spots_list = [[] for _ct in fov.chrom_coords]\nfor _spots in kept_spots_list:\n _cands_list = assign_spots_to_chromosomes(_spots, fov.chrom_coords)\n for _i, _cands in enumerate(_cands_list):\n cand_chr_spots_list[_i].append(_cands)\nprint(f\"kept chromosomes: {len(fov.chrom_coords)}\")", "kept chromosomes: 549\n" ], [ "reload(spot_tools.picking)\nfrom ImageAnalysis3.spot_tools.picking import convert_spots_to_hzxys\n\ndna_cand_hzxys_list = [convert_spots_to_hzxys(_spots, fov.shared_parameters['distance_zxy'])\n for _spots in cand_chr_spots_list]\ndna_reg_ids = fov.unique_ids\ndna_reg_channels = fov.unique_channels\nchrom_coords = fov.chrom_coords\n\n\n# select_hzxys close to the chromosome center\ndist_th = 3000 # upper limit is 3000nm\ngood_chr_th = 0.8 # 80% of regions should have candidate spots\n\nsel_dna_cand_hzxys_list = []\nsel_chrom_coords = []\nchr_cand_pers = []\nsel_chr_cand_pers = []\nfor _cand_hzxys, _chrom_coord in zip(dna_cand_hzxys_list, chrom_coords):\n _chr_cand_per = 0\n _sel_cands_list = []\n \n for _cands in _cand_hzxys:\n if len(_cands) == 0:\n _sel_cands_list.append([])\n else:\n _dists = np.linalg.norm(_cands[:,1:4] - _chrom_coord*np.array([200,108,108]), axis=1)\n _sel_cands_list.append(_cands[(_dists < dist_th)])\n _chr_cand_per += 1\n \n _chr_cand_per *= 1/len(_cand_hzxys)\n # append\n if _chr_cand_per >= good_chr_th:\n sel_dna_cand_hzxys_list.append(_sel_cands_list)\n sel_chrom_coords.append(_chrom_coord)\n sel_chr_cand_pers.append(_chr_cand_per)\n \n chr_cand_pers.append(_chr_cand_per)\n \nprint(f\"kept chromosomes: {len(sel_chrom_coords)}\")", "kept chromosomes: 522\n" ] ], [ [ "### EM pick spots", "_____no_output_____" ] ], [ [ "%matplotlib inline\nreload(spot_tools.picking)\nfrom ImageAnalysis3.spot_tools.picking import _maximize_score_spot_picking_of_chr, pick_spots_by_intensities,pick_spots_by_scores, generate_reference_from_population, evaluate_differences\n\nniter= 10\nnum_threads = 24\nref_chr_cts = None\n# initialize\ninit_dna_hzxys = pick_spots_by_intensities(sel_dna_cand_hzxys_list)\n# set save list\nsel_dna_hzxys_list, sel_dna_scores_list, all_dna_scores_list = [init_dna_hzxys], [], []\n\nfor _iter in range(niter):\n print(f\"+ iter:{_iter}\")\n # E: generate reference\n ref_ct_dists, ref_local_dists, ref_ints = generate_reference_from_population(\n sel_dna_hzxys_list[-1], dna_reg_ids, \n sel_dna_hzxys_list[-1], dna_reg_ids,\n ref_channels=dna_reg_channels,\n ref_chr_cts=ref_chr_cts,\n num_threads=num_threads,\n collapse_regions=True,\n split_channels=True,\n verbose=True,\n )\n \n plt.figure(figsize=(4,2), dpi=100)\n for _k, _v in ref_ct_dists.items():\n plt.hist(np.array(_v), bins=np.arange(0,2500,50), alpha=0.5, label=_k)\n plt.legend(fontsize=8)\n plt.title('center dist', fontsize=8)\n plt.show()\n \n plt.figure(figsize=(4,2), dpi=100)\n for _k, _v in ref_local_dists.items():\n plt.hist(np.array(_v), bins=np.arange(0,2500,50), alpha=0.5, label=_k)\n plt.legend(fontsize=8)\n plt.title('local dist', fontsize=8)\n plt.show()\n \n plt.figure(figsize=(4,2), dpi=100)\n for _k, _v in ref_ints.items():\n plt.hist(np.array(_v), bins=np.arange(0,5000,100), alpha=0.5, label=_k)\n plt.legend(fontsize=8)\n plt.title('intensity', fontsize=8)\n plt.show()\n \n # M: pick based on scores\n sel_hzxys_list, sel_scores_list, all_scores_list, other_scores_list = \\\n pick_spots_by_scores(\n sel_dna_cand_hzxys_list, dna_reg_ids,\n ref_channels=dna_reg_channels,\n ref_hzxys_list=sel_dna_hzxys_list[-1], ref_ids=dna_reg_ids, \n ref_ct_dists=ref_ct_dists, ref_local_dists=ref_local_dists, ref_ints=ref_ints, \n ref_chr_cts=ref_chr_cts,\n num_threads=num_threads,\n collapse_regions=True,\n split_intensity_channels=True,\n split_distance_channels=False,\n return_other_scores=True,\n verbose=True,\n )\n # check updating rate\n update_rate = evaluate_differences(sel_hzxys_list, sel_dna_hzxys_list[-1])\n print(f\"-- region kept: {update_rate:.4f}\")\n # append\n sel_dna_hzxys_list.append(sel_hzxys_list)\n sel_dna_scores_list.append(sel_scores_list)\n all_dna_scores_list.append(all_scores_list)\n \n plt.figure(figsize=(4,2), dpi=100)\n plt.hist(np.concatenate([np.concatenate(_scores) \n for _scores in other_scores_list]), \n bins=np.arange(-15, 0, 0.5), alpha=0.5, label='unselected')\n plt.hist(np.ravel([np.array(_sel_scores) \n for _sel_scores in sel_dna_scores_list[-1]]), \n bins=np.arange(-15, 0, 0.5), alpha=0.5, label='selected')\n plt.legend(fontsize=8)\n plt.show()\n \n if update_rate > 0.998:\n break", "+ iter:0\n-- generate reference metrics\n--- multiprocessing expectation step with 24 threads, in 12.560s\n--- collapse all regions into 1d.\n" ], [ "%%timeit \nspot_tools.picking.chromosome_center_dists(sel_dna_hzxys_list[0][0], ref_channels=dna_reg_channels, split_channels=False)", "1.57 ms ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ], [ "%%timeit \nspot_tools.picking.chromosome_center_dists(sel_dna_hzxys_list[0][0], ref_channels=dna_reg_channels, split_channels=True)", "1.78 ms ± 10.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ], [ "from scipy.spatial.distance import pdist, squareform\nsel_iter = -1\n\nfinal_dna_hzxys_list = []\nkept_chr_ids = []\ndistmap_list = []\nscore_th = -5\nint_th = 200\nbad_spot_percentage = 1.0 #0.5\n\nfor _hzxys, _scores in zip(sel_dna_hzxys_list[sel_iter], sel_dna_scores_list[sel_iter]):\n _kept_hzxys = np.array(_hzxys).copy()\n # remove spots by intensity\n _bad_inds = _kept_hzxys[:,0] < int_th\n # remove spots by scores\n _bad_inds += _scores < score_th\n #print(np.mean(_bad_inds))\n _kept_hzxys[_bad_inds] = np.nan\n \n \n if np.mean(np.isnan(_kept_hzxys).sum(1)>0)<bad_spot_percentage:\n kept_chr_ids.append(True)\n final_dna_hzxys_list.append(_kept_hzxys)\n distmap_list.append(squareform(pdist(_kept_hzxys[:,1:4])))\n else:\n kept_chr_ids.append(False)\n\nkept_chr_ids = np.array(kept_chr_ids, dtype=np.bool)\n#kept_chrom_coords = np.array(sel_chrom_coords)[kept_chr_ids]\ndistmap_list = np.array(distmap_list)\nmedian_distmap = np.nanmedian(distmap_list, axis=0)", "E:\\Users\\puzheng\\anaconda3\\lib\\site-packages\\numpy\\lib\\nanfunctions.py:1114: RuntimeWarning: All-NaN slice encountered\n overwrite_input=overwrite_input)\n" ], [ "loss_rates = np.mean(np.sum(np.isnan(final_dna_hzxys_list), axis=2)>0, axis=0)\nprint(np.mean(loss_rates))\nfig, ax = plt.subplots(figsize=(4,2),dpi=200)\nax.plot(loss_rates, '.-')\nax.set_ylim([0,1])\nax.set_xticks(np.arange(0,len(dna_reg_ids),int(len(dna_reg_ids)/5)))\nplt.show()", "0.26291021156088623\n" ], [ "imaging_order = []\nfor _fd, _infos in fov.color_dic.items():\n for _info in _infos:\n if len(_info) > 0 and _info[0] == 'u':\n if int(_info[1:]) in dna_reg_ids:\n imaging_order.append(list(dna_reg_ids).index(int(_info[1:])))\nimaging_order = np.array(imaging_order, dtype=np.int)\n#kept_inds = imaging_order # plot imaging ordered regions\n\n#kept_inds = np.where(loss_rates<0.5)[0] # plot good regions only\nkept_inds = np.arange(len(fov.unique_ids)) # plot all\n\n%matplotlib inline\n\nfig, ax = plt.subplots(figsize=(4,3),dpi=200)\nax = ia.figure_tools.distmap.plot_distance_map(median_distmap[kept_inds][:,kept_inds], \n color_limits=[0,600],\n ax=ax,\n ticks=np.arange(0,150,20), \n figure_dpi=500)\nax.set_title(f\"v-Abl ProB iaa_dox_STI+, n={len(distmap_list)}\", fontsize=7.5)\n\n_ticks = np.arange(0, len(kept_inds), 20)\nax.set_xticks(_ticks)\nax.set_xticklabels(dna_reg_ids[kept_inds][_ticks])\nax.set_xlabel(f\"5kb region id\", fontsize=7, labelpad=2)\nax.set_yticks(_ticks)\nax.set_yticklabels(dna_reg_ids[kept_inds][_ticks])\nax.set_ylabel(f\"5kb region id\", fontsize=7, labelpad=2)\n\n\nax.axvline(x=np.where(fov.unique_ids[kept_inds]>300)[0][0], color=[1,1,0])\nax.axhline(y=np.where(fov.unique_ids[kept_inds]>300)[0][0], color=[1,1,0])\n\nplt.gcf().subplots_adjust(bottom=0.1)\nplt.show()", "_____no_output_____" ] ], [ [ "## visualize single example", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\n\nreload(figure_tools.image)\n\nchrom_id = 3\n\nimport matplotlib\nimport copy\n\nsc_cmap = copy.copy(matplotlib.cm.get_cmap('seismic_r'))\nsc_cmap.set_bad(color=[0.5,0.5,0.5,1])\n\n#valid_inds = np.where(np.isnan(final_dna_hzxys_list[chrom_id]).sum(1) == 0)[0]\nvalid_inds = np.ones(len(final_dna_hzxys_list[chrom_id]), dtype=np.bool) # all spots\n\nfig, ax = plt.subplots(figsize=(4,3),dpi=200)\nax = ia.figure_tools.distmap.plot_distance_map(\n distmap_list[chrom_id][valid_inds][:,valid_inds], \n color_limits=[0,600],\n ax=ax,\n cmap=sc_cmap,\n ticks=np.arange(0,150,20), \n figure_dpi=200)\nax.set_title(f\"proB DMSO chrom: {chrom_id}\", fontsize=7.5)\nplt.gcf().subplots_adjust(bottom=0.1)\nplt.show()\n\nax3d = figure_tools.image.chromosome_structure_3d_rendering(\n final_dna_hzxys_list[chrom_id][valid_inds, 1:], \n marker_edge_line_width=0,\n reference_bar_length=200, image_radius=300, \n line_width=0.5, figure_dpi=300, depthshade=False)\nplt.show()", "_____no_output_____" ], [ "?figure_tools.image.chromosome_structure_3d_rendering", "_____no_output_____" ] ], [ [ "## visualize all fitted spots", "_____no_output_____" ] ], [ [ "with h5py.File(fov.save_filename, \"r\", libver='latest') as _f:\n _grp = _f['unique']\n raw_spots_list = [_spots[_spots[:,0] > 0] for _spots in _grp['raw_spots'][:]]\n spots_list = [_spots[_spots[:,0] > 0] for _spots in _grp['spots'][:]]", "_____no_output_____" ], [ "from scipy.spatial.distance import cdist\npicked_spot_inds_list = []\nfor _i, _id in enumerate(dna_reg_ids):\n _cand_hzxys = spots_list[_i][:,1:4] * fov.shared_parameters['distance_zxy']\n _dists = cdist(np.array(final_dna_hzxys_list)[:,_i,1:], _cand_hzxys)#, axis=1\n _matched_spot_inds = []\n for _ds in _dists:\n if np.sum(np.isnan(_ds)) < len(_ds) and np.nanmin(_ds) < 0.01:\n _matched_spot_inds.append(np.argmin(_ds))\n else:\n _matched_spot_inds.append(np.nan)\n # append\n picked_spot_inds_list.append(np.array(_matched_spot_inds))", "_____no_output_____" ], [ "#vis_inds = [0,1,2,3,4,5]\nvis_inds = np.where(loss_rates > 0.8)[0]\nvis_ims, vis_ids, vis_spot_list, vis_raw_spot_list = [], [], [], []\n\nwith h5py.File(fov.save_filename, \"r\", libver='latest') as _f:\n _grp = _f['unique']\n \n for _ind in vis_inds:\n vis_ims.append(_grp['ims'][_ind])\n vis_ids.append(_grp['ids'][_ind])\n _picked_inds = picked_spot_inds_list[_ind]\n _picked_inds = np.array(_picked_inds[np.isnan(_picked_inds)==False], dtype=np.int)\n vis_spot_list.append(raw_spots_list[_ind][_picked_inds])", "_____no_output_____" ], [ "dna_reg_ids[59]", "_____no_output_____" ], [ "fov.color_dic", "_____no_output_____" ], [ "# visualize_all_chromosomes\n%matplotlib notebook\n%matplotlib notebook\n\n## visualize\ncoord_dict = {'coords':[],\n 'class_ids':[],\n }\nfor _i, _spots in enumerate(vis_spot_list):\n coord_dict['coords'] += list(np.flipud(_spot[1:4]) for _spot in _spots)\n coord_dict['class_ids'] += list(_i * np.ones(len(_spots),dtype=np.int))\n\nfig=plt.figure(figsize=(4,6), dpi=150) \n \nvisual_tools.imshow_mark_3d_v2(vis_ims, \n fig=fig,\n given_dic=coord_dict,\n save_file=None,\n )", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d0383440c18add70fe5072677bf981e62a42213f
219,143
ipynb
Jupyter Notebook
Week11/01-CIFAR10.ipynb
HowardNTUST/HackNTU_Data_2017
ad8e753a16719b6f9396d88b313a5757f5ed4794
[ "MIT" ]
null
null
null
Week11/01-CIFAR10.ipynb
HowardNTUST/HackNTU_Data_2017
ad8e753a16719b6f9396d88b313a5757f5ed4794
[ "MIT" ]
null
null
null
Week11/01-CIFAR10.ipynb
HowardNTUST/HackNTU_Data_2017
ad8e753a16719b6f9396d88b313a5757f5ed4794
[ "MIT" ]
1
2019-02-24T17:41:45.000Z
2019-02-24T17:41:45.000Z
198.499094
60,584
0.841172
[ [ [ "CIFAR10 是另外一個 dataset, 和 mnist 一樣,有十種類別(飛機、汽車、鳥、貓、鹿、狗、青蛙、馬、船、卡車)\n\nhttps://www.cs.toronto.edu/~kriz/cifar.html\n", "_____no_output_____" ] ], [ [ "import keras\nfrom keras.models import Sequential\nfrom PIL import Image\nimport numpy as np\nimport tarfile\n", "Using TensorFlow backend.\n" ], [ "# 讀取 dataset\n# 只有 train 和 test 沒有 validation\nimport pickle\ntrain_X=[]\ntrain_y=[]\ntar_gz = \"../Week06/cifar-10-python.tar.gz\"\nwith tarfile.open(tar_gz) as tarf:\n for i in range(1, 6):\n dataset = \"cifar-10-batches-py/data_batch_%d\"%i\n print(\"load\",dataset)\n with tarf.extractfile(dataset) as f:\n result = pickle.load(f, encoding='latin1')\n train_X.extend(result['data']/255)\n train_y.extend(result['labels'])\n train_X=np.float32(train_X)\n train_y=np.int32(train_y)\n dataset = \"cifar-10-batches-py/test_batch\"\n print(\"load\",dataset)\n with tarf.extractfile(dataset) as f:\n result = pickle.load(f, encoding='latin1')\n test_X=np.float32(result['data']/255)\n test_y=np.int32(result['labels'])\ntrain_Y = np.eye(10)[train_y]\ntest_Y = np.eye(10)[test_y]\nvalidation_data = (test_X[:1000], test_Y[:1000])\ntest_data = (test_X[1000:], test_Y[1000:])\n", "load cifar-10-batches-py/data_batch_1\nload cifar-10-batches-py/data_batch_2\nload cifar-10-batches-py/data_batch_3\nload cifar-10-batches-py/data_batch_4\nload cifar-10-batches-py/data_batch_5\nload cifar-10-batches-py/test_batch\n" ], [ "from IPython.display import display\ndef showX(X):\n int_X = (X*255).clip(0,255).astype('uint8')\n # N*3072 -> N*3*32*32 -> 32 * 32N * 3\n int_X_reshape = np.moveaxis(int_X.reshape(-1,3,32,32), 1, 3)\n int_X_reshape = int_X_reshape.swapaxes(0,1).reshape(32,-1, 3)\n display(Image.fromarray(int_X_reshape))\n# 訓練資料, X 的前 20 筆\nshowX(train_X[:20])\nprint(train_y[:20])\nname_array = np.array(\"飛機、汽車、鳥、貓、鹿、狗、青蛙、馬、船、卡車\".split('、'))\nprint(name_array[train_y[:20]])", "_____no_output_____" ] ], [ [ "將之前的 cnn model 套用過來看看", "_____no_output_____" ] ], [ [ "# %load ../Week06/q_cifar10_cnn.py\nimport keras\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape\nmodel = Sequential()\nmodel.add(Reshape((3, 32, 32), input_shape=(3*32*32,) ))\nmodel.add(Conv2D(filters=32, kernel_size=(3,3), padding='same', activation=\"relu\", data_format='channels_first'))\nmodel.add(MaxPool2D())\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), padding='same', activation=\"relu\", data_format='channels_first'))\nmodel.add(MaxPool2D())\nmodel.add(Reshape((-1,)))\nmodel.add(Dense(units=1024, activation=\"relu\"))\nmodel.add(Dense(units=10, activation=\"softmax\"))\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.fit(train_X, train_Y, validation_data=validation_data, batch_size=100, epochs=10)\nrtn = model.evaluate(*test_data)\nprint(\"\\ntest accuracy=\", rtn[1])", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 21s - loss: 1.5073 - acc: 0.4609 - val_loss: 1.2153 - val_acc: 0.5720\nEpoch 2/10\n50000/50000 [==============================] - 19s - loss: 1.0979 - acc: 0.6102 - val_loss: 1.0003 - val_acc: 0.6350\nEpoch 3/10\n50000/50000 [==============================] - 19s - loss: 0.9107 - acc: 0.6794 - val_loss: 0.9248 - val_acc: 0.6630\nEpoch 4/10\n50000/50000 [==============================] - 19s - loss: 0.7674 - acc: 0.7314 - val_loss: 0.8943 - val_acc: 0.6900\nEpoch 5/10\n50000/50000 [==============================] - 19s - loss: 0.6320 - acc: 0.7805 - val_loss: 0.8766 - val_acc: 0.6940\nEpoch 6/10\n50000/50000 [==============================] - 19s - loss: 0.4970 - acc: 0.8274 - val_loss: 0.9347 - val_acc: 0.6880\nEpoch 7/10\n50000/50000 [==============================] - 19s - loss: 0.3600 - acc: 0.8763 - val_loss: 0.9964 - val_acc: 0.6850\nEpoch 8/10\n50000/50000 [==============================] - 19s - loss: 0.2404 - acc: 0.9215 - val_loss: 1.0836 - val_acc: 0.6910\nEpoch 9/10\n50000/50000 [==============================] - 21s - loss: 0.1482 - acc: 0.9538 - val_loss: 1.2594 - val_acc: 0.6850\nEpoch 10/10\n50000/50000 [==============================] - 27s - loss: 0.0950 - acc: 0.9724 - val_loss: 1.3658 - val_acc: 0.6980\n8992/9000 [============================>.] - ETA: 0s\ntest accuracy= 0.689333333333\n" ], [ "showX(test_X[:15])\npredict_y = model.predict_classes(test_X[:15], verbose=False)\nprint(name_array[predict_y])\nprint(name_array[test_y[:15]])", "_____no_output_____" ], [ "import keras\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout\nmodel = Sequential()\nmodel.add(Reshape((3, 32, 32), input_shape=(3*32*32,) ))\nmodel.add(Conv2D(32, 3, padding='same', activation=\"relu\", data_format='channels_first'))\nmodel.add(MaxPool2D())\nmodel.add(Conv2D(64, 3, padding='same', activation=\"relu\", data_format='channels_first'))\nmodel.add(MaxPool2D())\nmodel.add(Reshape((-1,)))\nmodel.add(Dense(units=1024, activation=\"relu\"))\nmodel.add(Dropout(rate=0.4))\nmodel.add(Dense(units=10, activation=\"softmax\"))\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.fit(train_X, train_Y, validation_data=validation_data, batch_size=100, epochs=10)\nrtn = model.evaluate(*test_data)\nprint(\"\\ntest accuracy=\", rtn[1])", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 29s - loss: 1.5101 - acc: 0.4566 - val_loss: 1.2131 - val_acc: 0.5510\nEpoch 2/10\n50000/50000 [==============================] - 28s - loss: 1.1424 - acc: 0.5938 - val_loss: 1.0331 - val_acc: 0.6420\nEpoch 3/10\n50000/50000 [==============================] - 29s - loss: 0.9835 - acc: 0.6518 - val_loss: 0.9500 - val_acc: 0.6670\nEpoch 4/10\n50000/50000 [==============================] - 20s - loss: 0.8547 - acc: 0.6977 - val_loss: 0.8837 - val_acc: 0.6850\nEpoch 5/10\n50000/50000 [==============================] - 19s - loss: 0.7475 - acc: 0.7369 - val_loss: 0.8432 - val_acc: 0.7010\nEpoch 6/10\n50000/50000 [==============================] - 19s - loss: 0.6412 - acc: 0.7723 - val_loss: 0.8798 - val_acc: 0.6880\nEpoch 7/10\n50000/50000 [==============================] - 19s - loss: 0.5418 - acc: 0.8087 - val_loss: 0.8449 - val_acc: 0.7030\nEpoch 8/10\n50000/50000 [==============================] - 19s - loss: 0.4443 - acc: 0.8445 - val_loss: 0.8894 - val_acc: 0.6980\nEpoch 9/10\n50000/50000 [==============================] - 19s - loss: 0.3657 - acc: 0.8729 - val_loss: 0.9427 - val_acc: 0.6860\nEpoch 10/10\n50000/50000 [==============================] - 19s - loss: 0.3048 - acc: 0.8943 - val_loss: 0.9797 - val_acc: 0.6930\n9000/9000 [==============================] - 1s \n\ntest accuracy= 0.702444444444\n" ], [ "model.fit(train_X, train_Y, validation_data=validation_data, batch_size=100, epochs=10)\nrtn = model.evaluate(*test_data)\nprint(\"\\ntest accuracy=\", rtn[1])", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 19s - loss: 0.2504 - acc: 0.9149 - val_loss: 1.0555 - val_acc: 0.7100\nEpoch 2/10\n50000/50000 [==============================] - 19s - loss: 0.2059 - acc: 0.9283 - val_loss: 1.0203 - val_acc: 0.7090\nEpoch 3/10\n50000/50000 [==============================] - 19s - loss: 0.1726 - acc: 0.9415 - val_loss: 1.1048 - val_acc: 0.7000\nEpoch 4/10\n50000/50000 [==============================] - 19s - loss: 0.1542 - acc: 0.9465 - val_loss: 1.1567 - val_acc: 0.7000\nEpoch 5/10\n50000/50000 [==============================] - 19s - loss: 0.1387 - acc: 0.9524 - val_loss: 1.2201 - val_acc: 0.6980\nEpoch 6/10\n50000/50000 [==============================] - 19s - loss: 0.1261 - acc: 0.9572 - val_loss: 1.2735 - val_acc: 0.7040\nEpoch 7/10\n50000/50000 [==============================] - 19s - loss: 0.1148 - acc: 0.9609 - val_loss: 1.2635 - val_acc: 0.6950\nEpoch 8/10\n50000/50000 [==============================] - 19s - loss: 0.1076 - acc: 0.9632 - val_loss: 1.2785 - val_acc: 0.6860\nEpoch 9/10\n50000/50000 [==============================] - 19s - loss: 0.0964 - acc: 0.9673 - val_loss: 1.4299 - val_acc: 0.6860\nEpoch 10/10\n50000/50000 [==============================] - 19s - loss: 0.0961 - acc: 0.9680 - val_loss: 1.3541 - val_acc: 0.6950\n8736/9000 [============================>.] - ETA: 0s\ntest accuracy= 0.690333333333\n" ], [ "showX(test_X[:15])\npredict_y = model.predict_classes(test_X[:15], verbose=False)\nprint(name_array[predict_y])\nprint(name_array[test_y[:15]])", "_____no_output_____" ] ], [ [ "不同的 activation\nhttps://keras.io/activations/", "_____no_output_____" ] ], [ [ "# 先定義一個工具\ndef add_layers(model, *layers):\n for l in layers:\n model.add(l)", "_____no_output_____" ], [ "import keras\nfrom keras.engine.topology import Layer\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout\n\ndef MyConv2D(filters, kernel_size, **kwargs):\n return (Conv2D(filters=filters, kernel_size=kernel_size, \n padding='same', data_format='channels_first', **kwargs),\n Activation(\"elu\"))\nmodel = Sequential()\nadd_layers( model,\n Reshape((3, 32, 32), input_shape=(3*32*32,)),\n *MyConv2D(32, 3),\n MaxPool2D(),\n *MyConv2D(64, 3),\n MaxPool2D(),\n Reshape((-1,)),\n Dense(units=1024, activation=\"elu\"),\n Dropout(rate=0.4),\n Dense(units=10, activation=\"softmax\")\n)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.fit(train_X, train_Y, validation_data=validation_data, batch_size=100, epochs=10)\nrtn = model.evaluate(*test_data)\nprint(\"\\ntest accuracy=\", rtn[1])", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 19s - loss: 1.4263 - acc: 0.5103 - val_loss: 1.0930 - val_acc: 0.6240\nEpoch 2/10\n50000/50000 [==============================] - 19s - loss: 1.0308 - acc: 0.6406 - val_loss: 0.9959 - val_acc: 0.6400\nEpoch 3/10\n50000/50000 [==============================] - 18s - loss: 0.9083 - acc: 0.6827 - val_loss: 0.9100 - val_acc: 0.6790\nEpoch 4/10\n50000/50000 [==============================] - 18s - loss: 0.8233 - acc: 0.7120 - val_loss: 0.9503 - val_acc: 0.6750\nEpoch 5/10\n50000/50000 [==============================] - 19s - loss: 0.7499 - acc: 0.7368 - val_loss: 0.9357 - val_acc: 0.6810\nEpoch 6/10\n50000/50000 [==============================] - 18s - loss: 0.6773 - acc: 0.7627 - val_loss: 0.9786 - val_acc: 0.6790\nEpoch 7/10\n50000/50000 [==============================] - 19s - loss: 0.6140 - acc: 0.7839 - val_loss: 1.0009 - val_acc: 0.6740\nEpoch 8/10\n50000/50000 [==============================] - 19s - loss: 0.5556 - acc: 0.8050 - val_loss: 1.0503 - val_acc: 0.6660\nEpoch 9/10\n50000/50000 [==============================] - 19s - loss: 0.4912 - acc: 0.8256 - val_loss: 1.1419 - val_acc: 0.6610\nEpoch 10/10\n50000/50000 [==============================] - 19s - loss: 0.4269 - acc: 0.8477 - val_loss: 1.1387 - val_acc: 0.6710\n8640/9000 [===========================>..] - ETA: 0s\ntest accuracy= 0.653666666667\n" ], [ "import keras\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout, BatchNormalization\n# 先處理資料\n\n#GCN\ntrain_X_mean = np.mean(train_X, axis=0, keepdims=True)\ntrain_X_std = np.std(train_X, axis=0, keepdims=True)\npreprocessed_train_X = (train_X-train_X_mean)/train_X_std\npreprocessed_test_X = (test_X-train_X_mean)/train_X_std\npreprocessed_validation_data = (preprocessed_test_X[:1000], test_Y[:1000])\npreprocessed_test_data = (preprocessed_test_X[1000:], test_Y[1000:])\n\n\ndef MyConv2D(filters, kernel_size, **kwargs):\n return (Conv2D(filters=filters, kernel_size=kernel_size, \n padding='same', data_format='channels_first', **kwargs),\n Activation(\"relu\"))\ndef add_layers(model, *layers):\n for l in layers:\n model.add(l)\nmodel = Sequential()\nadd_layers( model,\n Reshape((3, 32, 32), input_shape=(3*32*32,)),\n *MyConv2D(32, 3),\n MaxPool2D(),\n *MyConv2D(64, 3),\n MaxPool2D(),\n Reshape((-1,)),\n Dense(units=1024, activation=\"relu\"),\n Dropout(rate=0.4),\n Dense(units=10, activation=\"softmax\")\n)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.fit(preprocessed_train_X, train_Y, validation_data=preprocessed_validation_data, \n batch_size=100, epochs=10)\nrtn = model.evaluate(*preprocessed_test_data)\nprint(\"\\ntest accuracy=\", rtn[1])", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 19s - loss: 1.5286 - acc: 0.4543 - val_loss: 1.1498 - val_acc: 0.6020\nEpoch 2/10\n50000/50000 [==============================] - 19s - loss: 1.0738 - acc: 0.6200 - val_loss: 1.0352 - val_acc: 0.6340\nEpoch 3/10\n50000/50000 [==============================] - 19s - loss: 0.8797 - acc: 0.6888 - val_loss: 0.9085 - val_acc: 0.6720\nEpoch 4/10\n50000/50000 [==============================] - 18s - loss: 0.7187 - acc: 0.7481 - val_loss: 0.8152 - val_acc: 0.7040\nEpoch 5/10\n50000/50000 [==============================] - 19s - loss: 0.5719 - acc: 0.7980 - val_loss: 0.8395 - val_acc: 0.7110\nEpoch 6/10\n50000/50000 [==============================] - 19s - loss: 0.4424 - acc: 0.8460 - val_loss: 0.8739 - val_acc: 0.7140\nEpoch 7/10\n50000/50000 [==============================] - 18s - loss: 0.3275 - acc: 0.8860 - val_loss: 0.9208 - val_acc: 0.7170\nEpoch 8/10\n50000/50000 [==============================] - 18s - loss: 0.2517 - acc: 0.9131 - val_loss: 0.9607 - val_acc: 0.7130\nEpoch 9/10\n50000/50000 [==============================] - 19s - loss: 0.1930 - acc: 0.9334 - val_loss: 1.1707 - val_acc: 0.7090\nEpoch 10/10\n50000/50000 [==============================] - 18s - loss: 0.1592 - acc: 0.9462 - val_loss: 1.0804 - val_acc: 0.7220\n9000/9000 [==============================] - 1s \n\ntest accuracy= 0.701555555556\n" ], [ "import keras\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout, BatchNormalization\n# 先處理資料\n\n#GCN\ntrain_X_mean = np.mean(train_X, axis=0, keepdims=True)\ntrain_X_std = np.std(train_X, axis=0, keepdims=True)\npreprocessed_train_X = (train_X-train_X_mean)/train_X_std\npreprocessed_test_X = (test_X-train_X_mean)/train_X_std\npreprocessed_validation_data = (preprocessed_test_X[:1000], test_Y[:1000])\npreprocessed_test_data = (preprocessed_test_X[1000:], test_Y[1000:])\n\n\ndef MyConv2D(filters, kernel_size, **kwargs):\n return (Conv2D(filters=filters, kernel_size=kernel_size, \n padding='same', data_format='channels_first', **kwargs),\n BatchNormalization(axis=1),\n Activation(\"relu\"))\ndef add_layers(model, *layers):\n for l in layers:\n model.add(l)\nmodel = Sequential()\nadd_layers( model,\n Reshape((3, 32, 32), input_shape=(3*32*32,)),\n *MyConv2D(32, 3),\n MaxPool2D(),\n *MyConv2D(64, 3),\n MaxPool2D(),\n Reshape((-1,)),\n Dense(units=1024, activation=\"relu\"), \n Dropout(0.4),\n Dense(units=10, activation=\"softmax\")\n)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.fit(preprocessed_train_X, train_Y, validation_data=preprocessed_validation_data, \n batch_size=100, epochs=10)\nrtn = model.evaluate(*preprocessed_test_data)\nprint(\"\\ntest accuracy=\", rtn[1])", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 57s - loss: 13.2463 - acc: 0.1721 - val_loss: 13.4396 - val_acc: 0.1640\nEpoch 2/10\n50000/50000 [==============================] - 56s - loss: 10.0067 - acc: 0.2496 - val_loss: 1.5723 - val_acc: 0.4020\nEpoch 3/10\n50000/50000 [==============================] - 57s - loss: 1.5455 - acc: 0.4333 - val_loss: 1.3153 - val_acc: 0.5190\nEpoch 4/10\n50000/50000 [==============================] - 57s - loss: 1.3747 - acc: 0.5027 - val_loss: 1.1882 - val_acc: 0.5760\nEpoch 5/10\n50000/50000 [==============================] - 56s - loss: 1.2656 - acc: 0.5405 - val_loss: 1.1008 - val_acc: 0.6060\nEpoch 6/10\n50000/50000 [==============================] - 57s - loss: 1.1868 - acc: 0.5729 - val_loss: 1.1156 - val_acc: 0.5970\nEpoch 7/10\n50000/50000 [==============================] - 56s - loss: 1.1118 - acc: 0.6008 - val_loss: 1.0348 - val_acc: 0.6390\nEpoch 8/10\n50000/50000 [==============================] - 57s - loss: 1.0523 - acc: 0.6248 - val_loss: 0.9923 - val_acc: 0.6450\nEpoch 9/10\n50000/50000 [==============================] - 57s - loss: 1.0043 - acc: 0.6419 - val_loss: 0.9261 - val_acc: 0.6870\nEpoch 10/10\n50000/50000 [==============================] - 56s - loss: 0.9496 - acc: 0.6605 - val_loss: 0.9329 - val_acc: 0.6740\n8960/9000 [============================>.] - ETA: 0s\ntest accuracy= 0.658888888889\n" ], [ "model.fit(preprocessed_train_X, train_Y, validation_data=preprocessed_validation_data, \n batch_size=100, epochs=10)\nrtn = model.evaluate(*preprocessed_test_data)\nprint(\"\\ntest accuracy=\", rtn[1])", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 57s - loss: 0.9230 - acc: 0.6706 - val_loss: 0.8536 - val_acc: 0.6970\nEpoch 2/10\n50000/50000 [==============================] - 56s - loss: 0.8806 - acc: 0.6831 - val_loss: 0.8638 - val_acc: 0.6960\nEpoch 3/10\n50000/50000 [==============================] - 57s - loss: 0.8451 - acc: 0.6952 - val_loss: 0.8458 - val_acc: 0.7070\nEpoch 4/10\n50000/50000 [==============================] - 57s - loss: 0.8141 - acc: 0.7065 - val_loss: 0.9286 - val_acc: 0.6890\nEpoch 5/10\n50000/50000 [==============================] - 56s - loss: 0.7863 - acc: 0.7146 - val_loss: 0.8840 - val_acc: 0.6960\nEpoch 6/10\n50000/50000 [==============================] - 57s - loss: 0.7515 - acc: 0.7270 - val_loss: 0.8758 - val_acc: 0.7130\nEpoch 7/10\n50000/50000 [==============================] - 58s - loss: 0.7189 - acc: 0.7376 - val_loss: 0.8990 - val_acc: 0.6990\nEpoch 8/10\n50000/50000 [==============================] - 59s - loss: 0.6998 - acc: 0.7451 - val_loss: 0.8612 - val_acc: 0.7110\nEpoch 9/10\n50000/50000 [==============================] - 58s - loss: 0.6715 - acc: 0.7524 - val_loss: 0.8580 - val_acc: 0.7060\nEpoch 10/10\n50000/50000 [==============================] - 57s - loss: 0.6469 - acc: 0.7644 - val_loss: 0.8518 - val_acc: 0.7030\n8960/9000 [============================>.] - ETA: 0s\ntest accuracy= 0.706555555556\n" ], [ "def zca_whitening_matrix(X):\n \"\"\"\n Function to compute ZCA whitening matrix (aka Mahalanobis whitening).\n INPUT: X: [M x N] matrix.\n Rows: Variables\n Columns: Observations\n OUTPUT: ZCAMatrix: [M x M] matrix\n \"\"\"\n X = X.T\n # Covariance matrix [column-wise variables]: Sigma = (X-mu)' * (X-mu) / N\n sigma = np.cov(X, rowvar=True) # [M x M]\n # Singular Value Decomposition. X = U * np.diag(S) * V\n U,S,V = np.linalg.svd(sigma)\n # U: [M x M] eigenvectors of sigma.\n # S: [M x 1] eigenvalues of sigma.\n # V: [M x M] transpose of U\n # Whitening constant: prevents division by zero\n epsilon = 1e-5\n # ZCA Whitening matrix: U * Lambda * U'\n ZCAMatrix = np.dot(U, np.dot(np.diag(1.0/np.sqrt(S + epsilon)), U.T)) # [M x M]\n return ZCAMatrix.T\n# ZCAMatrix = zca_whitening_matrix(X0)\n# new_train_X= ((train_X-train_X_mean)/train_X_std) @ ZCAMatrix", "_____no_output_____" ], [ "# 參考 https://keras.io/preprocessing/image/\n\n# 輸入改成 tensor4\ntrain_X = train_X.reshape(-1, 3, 32, 32)\ntest_X = test_X.reshape(-1, 3, 32, 32)\n\ndef MyConv2D(filters, kernel_size, **kwargs):\n return (Conv2D(filters=filters, kernel_size=kernel_size, \n padding='same', data_format='channels_first', **kwargs),\n BatchNormalization(axis=1),\n Activation(\"relu\"))\nmodel = Sequential()\nadd_layers( model,\n *MyConv2D(32, 3, input_shape=(3,32,32)),\n MaxPool2D(),\n *MyConv2D(64, 3),\n MaxPool2D(),\n Reshape((-1,)),\n Dense(units=1024, activation=\"relu\"), \n Dropout(0.4),\n Dense(units=10, activation=\"softmax\")\n)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n# 使用 keras 的功能\nfrom keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n zca_whitening=True,\n data_format=\"channels_first\")\n\n# compute quantities required for featurewise normalization\n# (std, mean, and principal components if ZCA whitening is applied)\ndatagen.fit(train_X)\n\n\np_train_X, p_train_Y = datagen.flow(train_X, train_Y, batch_size=len(train_X), shuffle=False).next()\n# 順序都沒變\nassert (p_train_Y == train_Y).all()\n\np_test_X, p_test_Y = datagen.flow(test_X, test_Y, batch_size=len(test_X), shuffle=False).next()\n# 順序都沒變\nassert (p_test_Y == test_Y).all()\n# 不需要這兩個\ndel p_train_Y, p_test_Y\n\n\np_validation_data = (p_test_X[:1000], test_Y[:1000])\np_test_data = (p_test_X[1000:], test_Y[1000:])\nmodel.fit(p_train_X, train_Y, validation_data=p_validation_data, \n batch_size=100, epochs=10)\nrtn = model.evaluate(*p_test_data)\nprint(\"\\ntest accuracy=\", rtn[1])\n", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n50000/50000 [==============================] - 59s - loss: 4.1387 - acc: 0.2103 - val_loss: 1.9535 - val_acc: 0.2730\nEpoch 2/10\n50000/50000 [==============================] - 58s - loss: 1.6590 - acc: 0.3671 - val_loss: 1.3423 - val_acc: 0.5450\nEpoch 3/10\n50000/50000 [==============================] - 59s - loss: 1.4440 - acc: 0.4645 - val_loss: 1.2077 - val_acc: 0.5660\nEpoch 4/10\n50000/50000 [==============================] - 59s - loss: 1.3028 - acc: 0.5202 - val_loss: 1.0343 - val_acc: 0.6300\nEpoch 5/10\n50000/50000 [==============================] - 58s - loss: 1.2161 - acc: 0.5540 - val_loss: 1.1199 - val_acc: 0.6130\nEpoch 6/10\n50000/50000 [==============================] - 58s - loss: 1.1516 - acc: 0.5752 - val_loss: 1.0667 - val_acc: 0.6310\nEpoch 7/10\n50000/50000 [==============================] - 57s - loss: 1.1062 - acc: 0.5923 - val_loss: 1.0645 - val_acc: 0.6160\nEpoch 8/10\n50000/50000 [==============================] - 57s - loss: 1.0729 - acc: 0.6030 - val_loss: 1.0230 - val_acc: 0.6330\nEpoch 9/10\n50000/50000 [==============================] - 58s - loss: 1.0288 - acc: 0.6178 - val_loss: 0.9881 - val_acc: 0.6540\nEpoch 10/10\n50000/50000 [==============================] - 57s - loss: 1.0024 - acc: 0.6277 - val_loss: 1.0081 - val_acc: 0.6570\n8960/9000 [============================>.] - ETA: 0s\ntest accuracy= 0.660666666667\n" ] ], [ [ "使用動態資料處理\n```python\n# fits the model on batches with real-time data augmentation:\ntrain_generator = datagen.flow(train_X, train_Y, batch_size=100, shuffle=False)\ntest_generator = datagen.flow(*test_data, batch_size=100, shuffle=False)\nmodel.fit_generator(train_generator,\n steps_per_epoch=len(train_X), \n #validation_data=datagen.flow(*validation_data, batch_size=100),\n #validation_steps=1000,\n epochs=10)\nrtn = model.evaluate_generator(test_generator, steps=9000)\n```", "_____no_output_____" ] ], [ [ "import keras\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout, BatchNormalization\n# 輸入改成 tensor4\ntrain_X = train_X.reshape(-1, 3, 32, 32)\ntest_X = test_X.reshape(-1, 3, 32, 32)\n\ndef MyConv2D(filters, kernel_size, **kwargs):\n return (Conv2D(filters=filters, kernel_size=kernel_size, \n padding='same', data_format='channels_first', **kwargs),\n BatchNormalization(axis=1),\n Activation(\"elu\"))\nmodel = Sequential()\nadd_layers( model,\n *MyConv2D(64, 3, input_shape=(3,32,32)),\n *MyConv2D(64, 3),\n MaxPool2D(),\n *MyConv2D(128, 3),\n *MyConv2D(128, 3),\n MaxPool2D(),\n *MyConv2D(256, 3),\n *MyConv2D(256, 3),\n Reshape((-1,)),\n Dense(units=1024),\n BatchNormalization(),\n Activation(\"elu\"),\n Dropout(0.4),\n Dense(units=10, activation=\"softmax\")\n)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n# 使用 keras 的功能\nfrom keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n zca_whitening=True,\n data_format=\"channels_first\")\n\n# compute quantities required for featurewise normalization\n# (std, mean, and principal components if ZCA whitening is applied)\ndatagen.fit(train_X)\n\n\np_train_X, p_train_Y = datagen.flow(train_X, train_Y, batch_size=len(train_X), shuffle=False).next()\n# 順序都沒變\nassert (p_train_Y == train_Y).all()\n\np_test_X, p_test_Y = datagen.flow(test_X, test_Y, batch_size=len(test_X), shuffle=False).next()\n# 順序都沒變\nassert (p_test_Y == test_Y).all()\n# 不需要這兩個\ndel p_train_Y, p_test_Y\n\n\np_validation_data = (p_test_X[:1000], test_Y[:1000])\np_test_data = (p_test_X[1000:], test_Y[1000:])\nmodel.fit(p_train_X, train_Y, validation_data=p_validation_data, \n batch_size=100, epochs=10)\nrtn = model.evaluate(*p_test_data)\nprint(\"\\ntest accuracy=\", rtn[1])\n", "Train on 50000 samples, validate on 1000 samples\nEpoch 1/10\n" ], [ "model.fit(p_train_X, train_Y, validation_data=p_validation_data, \n batch_size=100, epochs=10)\nrtn = model.evaluate(*p_test_data)", "_____no_output_____" ] ], [ [ "lasagne 中相同的\n```python\n_ = InputLayer(shape=(None, 3*32*32), input_var=input_var)\n_ = DropoutLayer(_, 0.2)\n_ = ReshapeLayer(_, ([0], 3, 32, 32))\n_ = conv(_, 96, 3)\n_ = conv(_, 96, 3)\n_ = MaxPool2DDNNLayer(_, 3, 2)\n_ = DropoutLayer(_, 0.5)\n_ = conv(_, 192, 3)\n_ = conv(_, 192, 3)\n_ = MaxPool2DDNNLayer(_, 3, 2)\n_ = DropoutLayer(_, 0.5)\n_ = conv(_, 192, 3)\n_ = conv(_, 192, 1)\n_ = conv(_, 10, 1)\n_ = Pool2DDNNLayer(_, 7, mode='average_exc_pad')\n_ = FlattenLayer(_)\nl_out = NonlinearityLayer(_, nonlinearity=lasagne.nonlinearities.softmax)\n```", "_____no_output_____" ] ], [ [ "import keras\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout, BatchNormalization, GlobalAveragePooling2D\n# 輸入改成 tensor4\ntrain_X = train_X.reshape(-1, 3, 32, 32)\ntest_X = test_X.reshape(-1, 3, 32, 32)\n\ndef MyConv2D(filters, kernel_size, **kwargs):\n return (Conv2D(filters=filters, kernel_size=kernel_size, \n padding='same', data_format='channels_first', **kwargs),\n BatchNormalization(axis=1, momentum=0.9),\n Activation(\"relu\"))\nmodel = Sequential()\nadd_layers( model,\n Dropout(0.2, input_shape=(3,32,32)),\n *MyConv2D(96, 3),\n *MyConv2D(96, 3),\n MaxPool2D(3, 2),\n *MyConv2D(192, 3),\n *MyConv2D(192, 3),\n MaxPool2D(3, 2),\n Dropout(0.5),\n *MyConv2D(192, 3),\n *MyConv2D(192, 1),\n *MyConv2D(10, 1),\n GlobalAveragePooling2D(data_format='channels_first'),\n Activation(\"softmax\")\n)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nmodel.fit(p_train_X, train_Y, validation_data=p_validation_data, \n batch_size=100, epochs=50)\nrtn = model.evaluate(*p_test_data)\nprint(\"\\ntest accuracy=\", rtn[1])\n", "_____no_output_____" ], [ "import keras\nfrom keras.layers import Dense, Activation, Conv2D, MaxPool2D, Reshape, Dropout, BatchNormalization, GlobalAveragePooling2D\n# 輸入改成 tensor4\ntrain_X = train_X.reshape(-1, 3, 32, 32)\ntest_X = test_X.reshape(-1, 3, 32, 32)\n\ndef MyConv2D(filters, kernel_size, **kwargs):\n return (Conv2D(filters=filters, kernel_size=kernel_size, \n padding='same', data_format='channels_first', **kwargs),\n BatchNormalization(axis=1, momentum=0.9),\n Activation(\"relu\"))\nmodel = Sequential()\nadd_layers( model,\n Dropout(0.2, input_shape=(3,32,32)),\n *MyConv2D(96, 3),\n *MyConv2D(96, 3),\n MaxPool2D(3, 2),\n *MyConv2D(192, 3),\n *MyConv2D(192, 3),\n MaxPool2D(3, 2),\n Dropout(0.5),\n *MyConv2D(192, 3),\n *MyConv2D(192, 1),\n *MyConv2D(10, 1),\n GlobalAveragePooling2D(data_format='channels_first'),\n Activation(\"softmax\")\n)\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n# 使用 keras 的功能\nfrom keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n zca_whitening=True,\n data_format=\"channels_first\")\n\n# compute quantities required for featurewise normalization\n# (std, mean, and principal components if ZCA whitening is applied)\ndatagen.fit(train_X)\n\n\np_train_X, p_train_Y = datagen.flow(train_X, train_Y, batch_size=len(train_X), shuffle=False).next()\n# 順序都沒變\nassert (p_train_Y == train_Y).all()\n\np_test_X, p_test_Y = datagen.flow(test_X, test_Y, batch_size=len(test_X), shuffle=False).next()\n# 順序都沒變\nassert (p_test_Y == test_Y).all()\n# 不需要這兩個\ndel p_train_Y, p_test_Y\n\n\np_validation_data = (p_test_X[:1000], test_Y[:1000])\np_test_data = (p_test_X[1000:], test_Y[1000:])\nmodel.fit(p_train_X, train_Y, validation_data=p_validation_data, \n batch_size=100, epochs=10)\nrtn = model.evaluate(*p_test_data)\nprint(\"\\ntest accuracy=\", rtn[1])\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d0384220d50cb29063de6bb548101cc868684be6
78,060
ipynb
Jupyter Notebook
notebooks/ankitesh-devlog/08_Preprocess_to_onehot.ipynb
ankitesh97/CBRAIN-CAM
cec46f1e5736aeedde480bdc0754c00bf0e06cf5
[ "MIT" ]
null
null
null
notebooks/ankitesh-devlog/08_Preprocess_to_onehot.ipynb
ankitesh97/CBRAIN-CAM
cec46f1e5736aeedde480bdc0754c00bf0e06cf5
[ "MIT" ]
null
null
null
notebooks/ankitesh-devlog/08_Preprocess_to_onehot.ipynb
ankitesh97/CBRAIN-CAM
cec46f1e5736aeedde480bdc0754c00bf0e06cf5
[ "MIT" ]
null
null
null
58.647633
4,413
0.56495
[ [ [ "import sys\nsys.path.insert(1,\"/home1/07064/tg863631/anaconda3/envs/CbrainCustomLayer/lib/python3.6/site-packages\") #work around for h5py\nfrom cbrain.imports import *\nfrom cbrain.cam_constants import *\nfrom cbrain.utils import *\nfrom cbrain.layers import *\nfrom cbrain.data_generator import DataGenerator\nimport tensorflow as tf\nfrom tensorflow import math as tfm\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\n# import tensorflow_probability as tfp\nimport xarray as xr\nimport numpy as np\nfrom cbrain.model_diagnostics import ModelDiagnostics\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.image as imag\nimport scipy.integrate as sin\nimport matplotlib.ticker as mticker\nimport pickle\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.losses import *\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nimport datetime\nfrom cbrain.climate_invariant import *\nimport yaml\nfrom cbrain.imports import *\nfrom cbrain.utils import *\nfrom cbrain.normalization import *\nimport h5py\nfrom sklearn.preprocessing import OneHotEncoder", "_____no_output_____" ] ], [ [ "## Preprocess the data and dump to a new file", "_____no_output_____" ] ], [ [ "DATA_PATH = '/fast/ankitesh/data/'\nTRAINFILE = 'CI_SP_M4K_train_shuffle.nc'\nVALIDFILE = 'CI_SP_M4K_valid.nc'\nNORMFILE = 'CI_SP_M4K_NORM_norm.nc'\npercentile_path='/export/nfs0home/ankitesg/data/percentile_data.pkl'\ndata_name='M4K'\nbin_size = 1000\nscale_dict = load_pickle('/export/nfs0home/ankitesg/CBrain_project/CBRAIN-CAM/nn_config/scale_dicts/009_Wm2_scaling.pkl')", "_____no_output_____" ], [ "percentile_bins = load_pickle(percentile_path)['Percentile'][data_name]\nenc = OneHotEncoder(sparse=False)\nclasses = np.arange(bin_size+2)\nenc.fit(classes.reshape(-1,1))", "_____no_output_____" ], [ "data_ds = xr.open_dataset(f\"{DATA_PATH}{TRAINFILE}\")\nn = data_ds['vars'].shape[0]", "_____no_output_____" ], [ "data_ds", "_____no_output_____" ], [ "coords = list(data_ds['vars'].var_names.values)\ncoords = coords + ['PHQ_BIN']*30+['TPHYSTND_BIN']*30+['FSNT_BIN','FSNS_BIN','FLNT_BIN','FLNS_BIN']", "_____no_output_____" ], [ "def _transform_to_one_hot(Y):\n '''\n return shape = batch_size X 64 X bin_size\n '''\n\n Y_trans = []\n out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\n var_dict = {}\n var_dict['PHQ'] = Y[:,:30]\n var_dict['TPHYSTND'] = Y[:,30:60]\n var_dict['FSNT'] = Y[:,60]\n var_dict['FSNS'] = Y[:,61]\n var_dict['FLNT'] = Y[:,62]\n var_dict['FLNS'] = Y[:,63]\n perc = percentile_bins\n for var in out_vars[:2]:\n all_levels_one_hot = []\n for ilev in range(30):\n bin_index = np.digitize(var_dict[var][:,ilev],perc[var][ilev])\n one_hot = enc.transform(bin_index.reshape(-1,1))\n all_levels_one_hot.append(one_hot)\n var_one_hot = np.stack(all_levels_one_hot,axis=1) \n Y_trans.append(var_one_hot)\n for var in out_vars[2:]:\n bin_index = np.digitize(var_dict[var][:], perc[var])\n one_hot = enc.transform(bin_index.reshape(-1,1))[:,np.newaxis,:]\n Y_trans.append(one_hot)\n\n Y_concatenated = np.concatenate(Y_trans,axis=1)\n return Y_concatenated", "_____no_output_____" ], [ "inp_vars = ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX']\ninp_coords = coords[:64]\nout_coords = coords[64:128]\nbin_coords = list(range(bin_size+2))", "_____no_output_____" ], [ "all_data_arrays = []\nbatch_size = 4096\nnorm_ds = xr.open_dataset(f'{DATA_PATH}{NORMFILE}')\noutput_transform = DictNormalizer(norm_ds, ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS'], scale_dict)\nfor i in range(0,n,batch_size):\n all_vars = data_ds['vars'][i:i+batch_size]\n inp_vals = all_vars[:,:64]\n out_vals = all_vars[:,64:128]\n out_vals = output_transform.transform(out_vals)\n one_hot = _transform_to_one_hot(out_vals)\n sample_coords = list(range(i,i+all_vars.shape[0]))\n x3 = xr.Dataset(\n {\n \"X\": ((\"sample\", \"inp_coords\"),inp_vals),\n \"Y_raw\":((\"sample\",\"out_cords\"),out_vals),\n \"Y\": ((\"sample\", \"out_coords\",\"bin_index\"), one_hot),\n },\n coords={\"sample\": sample_coords, \"inp_coords\": inp_coords,\"out_coords\":out_coords,\"bin_index\":bin_coords},\n )\n all_data_arrays.append(x3)\n if(int(i/batch_size+1)%100 == 0):\n print(\"saving this batch\")\n final_da = xr.combine_by_coords(all_data_arrays)\n final_da.to_netcdf(f'/scratch/ankitesh/data/new_data_for_v2_{int(i/batch_size+1)}.nc')\n all_data_arrays = []\n print(int(i/batch_size), end='\\r')", "saving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\n10343\r" ], [ "final_da = xr.combine_by_coords(all_data_arrays)", "_____no_output_____" ], [ "final_da", "_____no_output_____" ], [ "data_ds = xr.open_dataset(f\"{DATA_PATH}{VALIDFILE}\")\nn = data_ds['vars'].shape[0]", "_____no_output_____" ], [ "coords = list(data_ds['vars'].var_names.values)\ncoords = coords + ['PHQ_BIN']*30+['TPHYSTND_BIN']*30+['FSNT_BIN','FSNS_BIN','FLNT_BIN','FLNS_BIN']", "_____no_output_____" ], [ "all_data_arrays = []\nbatch_size = 4096\nnorm_ds = xr.open_dataset(f'{DATA_PATH}{NORMFILE}')\noutput_transform = DictNormalizer(norm_ds, ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS'], scale_dict)\nfor i in range(0,n,batch_size):\n all_vars = data_ds['vars'][i:i+batch_size]\n inp_vals = all_vars[:,:64]\n out_vals = all_vars[:,64:128]\n out_vals = output_transform.transform(out_vals)\n one_hot = _transform_to_one_hot(out_vals)\n sample_coords = list(range(i,i+all_vars.shape[0]))\n x3 = xr.Dataset(\n {\n \"X\": ((\"sample\", \"inp_coords\"),inp_vals),\n \"Y_raw\":((\"sample\",\"out_cords\"),out_vals),\n \"Y\": ((\"sample\", \"out_coords\",\"bin_index\"), one_hot),\n },\n coords={\"sample\": sample_coords, \"inp_coords\": inp_coords,\"out_coords\":out_coords,\"bin_index\":bin_coords},\n )\n all_data_arrays.append(x3)\n if(int(i/batch_size+1)%100 == 0):\n print(\"saving this batch\")\n final_da = xr.combine_by_coords(all_data_arrays)\n final_da.to_netcdf(f'/scratch/ankitesh/data/new_data_valid_for_v2_{int(i/batch_size+1)}.nc')\n all_data_arrays = []\n print(int(i/batch_size), end='\\r')\nfinal_da = xr.combine_by_coords(all_data_arrays)\nfinal_da.to_netcdf(f'/scratch/ankitesh/data/new_data_valid_for_v2_{int(i/batch_size+1)}.nc')", "saving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\nsaving this batch\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03844585b0c3fb4dd624b54ec5dfb089a49e9a2
525,988
ipynb
Jupyter Notebook
L1 regularized regression.ipynb
simonster/JuliaCon2015
33e79eeb918e46a0420bc3b10805209eeff384e1
[ "CC-BY-4.0" ]
2
2015-08-25T21:11:04.000Z
2016-06-30T18:09:57.000Z
L1 regularized regression.ipynb
simonster/JuliaCon2015
33e79eeb918e46a0420bc3b10805209eeff384e1
[ "CC-BY-4.0" ]
null
null
null
L1 regularized regression.ipynb
simonster/JuliaCon2015
33e79eeb918e46a0420bc3b10805209eeff384e1
[ "CC-BY-4.0" ]
null
null
null
113.310642
48,729
0.414928
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d03847bcdd65839a2fad0e47c5382b4a5cee06a8
191,121
ipynb
Jupyter Notebook
Module2/Manipulating_Data.ipynb
akielbowicz/DAT210x
3f2978dcb3583db3a98fd4143a2f821bbf05b6ac
[ "MIT" ]
null
null
null
Module2/Manipulating_Data.ipynb
akielbowicz/DAT210x
3f2978dcb3583db3a98fd4143a2f821bbf05b6ac
[ "MIT" ]
null
null
null
Module2/Manipulating_Data.ipynb
akielbowicz/DAT210x
3f2978dcb3583db3a98fd4143a2f821bbf05b6ac
[ "MIT" ]
null
null
null
89.350631
123,820
0.724442
[ [ [ "import pandas as pd", "_____no_output_____" ], [ "df = pd.read_csv('Datasets/direct_marketing.csv')\ndf.head()", "_____no_output_____" ] ], [ [ "## Slicing", "_____no_output_____" ] ], [ [ "df.recency\ndf['recency']\ndf[['recency']]\ndf.loc[:,'recency']\ndf.loc[:,['recency']]\ndf.iloc[:,0]\ndf.iloc[:,[0]]", "_____no_output_____" ] ], [ [ "## Boolean Indexing", "_____no_output_____" ] ], [ [ "df.recency < 7\ndf[ df.recency < 7 ]\ndf[ (df.recency < 7) & (df.newbie == 0) ]\n", "_____no_output_____" ], [ "df[df.recency < 7] = -100", "_____no_output_____" ], [ "ordered_satisfaction = ['Very Unhappy', 'Unhappy', 'Neutral', 'Happy', 'Very Happy']\ndf = pd.DataFrame({'satisfaction':['Mad', 'Happy', 'Unhappy', 'Neutral']})\ndf.satisfaction = df.satisfaction.astype(\"category\",\n ordered=True,\n categories=ordered_satisfaction\n).cat.codes", "/home/sasha/miniconda3/envs/pwpyfds/lib/python3.7/site-packages/ipykernel_launcher.py:5: FutureWarning: specifying 'categories' or 'ordered' in .astype() is deprecated; pass a CategoricalDtype instead\n \"\"\"\n" ], [ "df['satisfaction']", "_____no_output_____" ], [ "df = pd.DataFrame({'vertebrates':[\n... 'Bird',\n... 'Bird',\n... 'Mammal',\n... 'Fish',\n... 'Amphibian',\n... 'Reptile',\n... 'Mammal',\n... ]})", "_____no_output_____" ], [ "df.vertebrates.astype('category').cat.codes, df.vertebrates.astype('category').cat.categories", "_____no_output_____" ], [ "pd.get_dummies(df, columns=['vertebrates'])", "_____no_output_____" ] ], [ [ "## Feature Representation", "_____no_output_____" ], [ "### Pure Textual Features", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import CountVectorizer\n\t\ncorpus = [\n \"Authman ran faster than Harry because he is an athlete.\",\n \"Authman and Harry ran faster and faster.\",\n ]\n\t", "_____no_output_____" ], [ "bow = CountVectorizer()\nX = bow.fit_transform(corpus) # Sparse Matrix", "_____no_output_____" ], [ "bow.get_feature_names()", "_____no_output_____" ], [ "X.toarray()", "_____no_output_____" ] ], [ [ "# Graphical Features", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom imageio import imread\n\t\n# Load the image up\nimg = imread('imageio:chelsea.png')\n\t\n# Is the image too big? Resample it down by an order of magnitude\nimg = img[::2, ::2]\n\t\n# Scale colors from (0-255) to (0-1), then reshape to 1D array per pixel, e.g. grayscale\n# If you had color images and wanted to preserve all color channels, use .reshape(-1,3)\nX = (img / 255.0).reshape(-1)", "_____no_output_____" ], [ "plt.imshow(img)", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ] ], [ [ "## Audio Features", "_____no_output_____" ] ], [ [ "import scipy.io.wavfile as wavfile\n\t\nsample_rate, audio_data = wavfile.read('sound.wav')\nprint(audio_data)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d03871a97056ca955d8c80b0e912c3461c51bbfc
4,810
ipynb
Jupyter Notebook
package_expos/Docutils/README.ipynb
hanisaf/advanced-data-management-and-analytics-spring2021
35178f14b942f2accbcfcbaa5a27e134a9a9f96b
[ "MIT" ]
6
2021-01-21T17:53:34.000Z
2021-04-20T17:37:50.000Z
package_expos/Docutils/README.ipynb
hanisaf/advanced-data-management-and-analytics-spring2021
35178f14b942f2accbcfcbaa5a27e134a9a9f96b
[ "MIT" ]
null
null
null
package_expos/Docutils/README.ipynb
hanisaf/advanced-data-management-and-analytics-spring2021
35178f14b942f2accbcfcbaa5a27e134a9a9f96b
[ "MIT" ]
13
2021-01-20T16:11:55.000Z
2021-04-28T21:38:07.000Z
27.485714
279
0.575884
[ [ [ "# Docutils", "_____no_output_____" ], [ "## Presentation", "_____no_output_____" ], [ "Click [__here__] (youtube link) for the video presentation", "_____no_output_____" ], [ "## Summary of Support Files", "_____no_output_____" ], [ "- `demo.ipynb`: the notebook containing this tutorial code\n- `test.csv`: a small file data used in the tutorial code", "_____no_output_____" ], [ "## Installation Instructions", "_____no_output_____" ], [ "Use `!pip install docutils` to install the `docutils` package. Next, use `import docutils`to import the package into your notebook.\n\nFor example, to import specific modules from `docutils` package use the following line of code:\n `from docutils import core, io`\n \nBelow is a list of modules and subpackages as apart of the `docutils` package:", "_____no_output_____" ], [ "## Guide", "_____no_output_____" ], [ "__docutils 0.17.1 version__\n\n- Author: David Goodger\n- Contact: goodger@python.org\n\n[Docutils](https://pypi.org/project/docutils/) is an open-source, modular text processing system for processing plaintext documentation into a more useful format. Formats include HTML, man-pages, OpenDocument, LaTeX, or XML.\n\nDocutils supports reStructuredText for input, an easy-to-read, what-you-see-is-what-you-get plaintext markup syntax.\n\nDocutils is short for \"Python Documentation Utilities\".", "_____no_output_____" ], [ "Support for the following sources has been implemented:\n - Standalone files\n - `PEPs (Python Enhancement Proposals)`\n \nSupport for these sources is currently being developed:\n - Inline documentation\n - Wikis\n - Email and more", "_____no_output_____" ], [ "Docutils Distribution Consists of:\n - the `docutils` package (or library)\n - front-end tools\n - test suite\n - documentation.\n ", "_____no_output_____" ], [ "## Notable docutils Modules & Subpackages\n-----------------------------\nModule | Definition\n------------- | -------------\n__core__ | Contains the ``Publisher`` class and ``publish_()``convenience functions\n__io__ | Provides a uniform API for low-level input and output\n__nodes__ | Docutils document tree (doctree) node class library\n\n\n-----------------------------\nSubpackages | Definition\n------------- | -------------\n**languages** | Language-specific mappings of terms\n**parsers** | Syntax-specific input parser modules or packages\n**readers** | Context-specific input handlers which understand the data source and manage a parser\n", "_____no_output_____" ], [ "Below is an overview of the `docutils` package:\n![alt text](docutils.png \"Docutils\")\n", "_____no_output_____" ], [ "## Main Use Applications of Package", "_____no_output_____" ], [ "The reStructured Text component of the `docutils` package makes it easy to convert between different formats, especially from plain text to a static website. It is unique because it is extensible. Better than simpler markups. \n\nAdditionally, users can pair `docutils` with `Sphinx` to convert text to html. The `Sphinx` package is built on the `docutils` package. The docutils parser creates the parse tree as a representation of the text in the memory for the Sphinx application and .rst environment.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d0387905f3b70d405105713d61aa055d74dda53e
551
ipynb
Jupyter Notebook
tests/data/add_installation_cells/import_numpy.ipynb
fem-on-colab/open-in-colab-workflow
d5309ff527cbea8a536a8890c88a8cc39bdb8b3c
[ "MIT" ]
null
null
null
tests/data/add_installation_cells/import_numpy.ipynb
fem-on-colab/open-in-colab-workflow
d5309ff527cbea8a536a8890c88a8cc39bdb8b3c
[ "MIT" ]
null
null
null
tests/data/add_installation_cells/import_numpy.ipynb
fem-on-colab/open-in-colab-workflow
d5309ff527cbea8a536a8890c88a8cc39bdb8b3c
[ "MIT" ]
null
null
null
16.69697
42
0.526316
[ [ [ "import numpy # noqa: F401", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
d0388cf138521cd15e529f000581cc45eeda0012
351,719
ipynb
Jupyter Notebook
scripts/triple-harmonic-restraint.ipynb
yabmtm/position-restraints
46981285dfa8755c5e9844b8ea0eba04b6ad3d5c
[ "MIT" ]
null
null
null
scripts/triple-harmonic-restraint.ipynb
yabmtm/position-restraints
46981285dfa8755c5e9844b8ea0eba04b6ad3d5c
[ "MIT" ]
null
null
null
scripts/triple-harmonic-restraint.ipynb
yabmtm/position-restraints
46981285dfa8755c5e9844b8ea0eba04b6ad3d5c
[ "MIT" ]
null
null
null
79.466561
43,164
0.672233
[ [ [ "import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom scipy.spatial.transform import Rotation as R\nimport copy\n\n# Let's write an expanded-ensemble Sampler() class\n\nclass EESampler_RigidThreeParticle(object):\n \"\"\"An expanded-ensemble Sampler class for a rigid-triangle 3-particle/3-restraint system.\"\"\"\n \n def __init__(self, k_values=[0.0, 0.5, 1.0, 2.0, 5.0, 10., 15., 20., 50., 100., 200., 400., 800.], L=8.0,\n x0=np.array([[0.,0.,0.],[1.,0.,0.], [2.,1.,0.]]),\n a1=np.array([[0.,0.,0.],[1.,0.,0.], [2.,1.,0.]])):\n \"\"\"Initialize the class.\n \n INPUT\n k -- a np.array() of force constant values (kJ/nm^2)\n L -- the length of the cubic box (nm), extending from -L/2 to L/2.\n x0 -- the initial positions of the particles (np.array of shape (3,3))\n a1 -- position of the harmonic anchors (np.array of shape (3,3))\n \"\"\"\n \n self.k_values = np.array(k_values) # kJ/mol/nm^2)\n self.L = L # nm\n self.x0 = x0 # np.array with shape (3,3) and units nm\n self.a1 = a1 # \"\n \n # Calculate distance between particles 1 and 2\n self.d0 = self.distance(x0[0,:], x0[1,:]) # the initial distance between p2 - p1, as a reference\n self.d = copy.copy(self.d0)\n print('self.d', self.d)\n \n # Calculate the altitude (height), c, of triangle where p1-p2 is the base\n ### 1. First calculate the area of the triangle as A = (1/2)||v \\cross w||\n p1, p2, p3 = x0[0,:], x0[1,:], x0[2,:] \n v, w = p2-p1, p3-p1\n area = 0.5*np.linalg.norm( np.cross(v,w) )\n ### 2. Then since A = 1/2 * base * height, the height is c = 2*area/base\n self.c0 = 2.0 * area / np.linalg.norm(v)\n self.c = copy.copy(self.c0)\n print('self.c', self.c)\n \n # calculate e, the projection of p3-p1 = w in the p2-p1 = v direction\n unit_vec_along_p12 = v / self.d\n self.e = np.abs(np.dot(w,unit_vec_along_p12))\n print('self.e', self.e)\n \n self.d3 = np.linalg.norm(w) # the initial distance between p3 - p1, as a reference\n \n \n self.k_index = 0 # thermodynamic index\n\n self.n_ensembles = self.k_values.shape[0]\n\n self.x = copy.copy(self.x0)\n self.U = self.energy(self.x, self.k_values[self.k_index])\n \n \n ### Monte Carlo and Wang-Landau (WL) settings\n self.dx = 0.2 # Gaussian translation step size \n self.dtheta = 0.2 # Gaussian step size for angular (in radians)\n \n self.RT = 2.479 # in kJ/mol at 298 K\n \n self.all_pbc_shifts = []\n for i in [-L, 0, L]:\n for j in [-L, 0, L]:\n for k in [-L, 0, L]:\n self.all_pbc_shifts.append([i,j,k])\n self.all_pbc_shifts = np.array(self.all_pbc_shifts)\n # print('self.all_pbc_shifts', self.all_pbc_shifts)\n \n self.wl_increment = 5.0 # in kT\n self.wl_scaling = 0.5 # (0.5 is a la R. E. Belardinelli, and V. D. Pereyra, JCP 2007), 0.8 is MRS\n self.flatness = 0.8 # if all histogram values are within flatness*100\n # percent of the mean counts, decrease wl_increment and reset histogram\n self.wl_increment_freq = 10 # frequency to update wl sampling\n self.g = np.zeros(self.n_ensembles) # bias energies\n self.h = np.zeros(self.n_ensembles) # histogram counts\n \n self.use_1_over_t = False # switch to updating increment as c_1_over_t/(nsteps) when\n self.c_1_over_t = 10.0 # the wl_increment < c_1_over_t/(nsteps) \n # (a la R. E. Belardinelli, and V. D. Pereyra, JCP 2007)\n self.has_switched_to_1_over_t = False\n self.steps_before_1_over_t = 10000 # wait at least these number of steps before switching to 1/t\n self.print_every = 10000 \n self.traj_every = 100 \n \n def theory_dg_in_kT(self, verbose=True):\n \"\"\"Returns the theoretical value for the 3-restraint potential at all k_values.\"\"\"\n if verbose:\n print('self.d', self.d)\n print('self.c', self.c)\n print('self.e', self.e)\n print('self.L', self.L)\n\n kc_coeff = 1.0 + (self.e/self.d)**2.0\n if verbose:\n print('kc_coeff', kc_coeff)\n kp1_coeff = 1.0 + (self.c**2 + self.e**2)/(self.d**2.0)\n if verbose:\n print('kp1_coeff', kp1_coeff)\n\n '''\n theory_dG_in_kT = -1.0*( 3.0/2.0*np.log(2.0*np.pi*ee.RT/(3.0*ee.k_values[1:])) \\ # translational\n + 1.0/2.0*np.log(2.0*np.pi*ee.RT/(2.0*ee.k_values[1:])) \\ # rot about d\n + 1.0/2.0*np.log(2.0*np.pi*ee.RT/(kc_coeff*ee.k_values[1:])) \\ # rot about c\n + 1.0/2.0*np.log(2.0*np.pi*ee.RT/(kp1_coeff*ee.k_values[1:])) \\ # rot out of page\n - np.log( ee.L**3 * 8.0 * (np.pi**2) * (ee.d)**2 * ee.c ) )\n '''\n\n theory_dG_in_kT = -1.0*( 3.0/2.0*np.log(2.0*np.pi*self.RT/(3.0*self.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*self.RT/(self.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*self.RT/(kc_coeff*self.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*self.RT/(kp1_coeff*self.k_values[1:])) \\\n - np.log( self.L**3 * 8.0 * (np.pi**2) * (self.d)**2 * self.c ) )\n return theory_dG_in_kT\n \n def energy(self, x, k):\n \"\"\"Returns the energy of the harmonic potential in units kJ/mol, for position x.\"\"\"\n return 0.5*k* np.sum((x-self.a1)*(x-self.a1))\n \n def distance(self, p1, p2):\n \"\"\"Return the distance between two particles (np.array of shape (3,))\"\"\"\n return np.sqrt( np.dot(p2-p1,p2-p1) ) \n \n def sample(self, nsteps, verbose=True):\n \"\"\"Perform WL expanded ensemble sampling with MC position moves.\"\"\"\n \n # store transition counts\n T_counts = np.zeros( (self.n_ensembles, self.n_ensembles) )\n accepted = 0\n data = []\n \n for step in range(nsteps):\n\n ########################\n ### MC moves\n \n # Before we do any moves, we need to reassemble the rod if it has\n # disjointed from any periodic box separations.\n p1, p2, p3 = self.x[0,:], self.x[1,:], self.x[2,:]\n \n tol = 1e-3\n # print('p1, p2', p1, p2, 'self.distance(p1, p2)', self.distance(p1, p2), 'self.d', self.d)\n p2_distance_deviation = np.abs(self.distance(p1, p2) - self.d0)\n p3_distance_deviation = np.abs(self.distance(p1, p3) - self.d3)\n if p2_distance_deviation + p3_distance_deviation > tol:\n # print(step, 'points out of the box. Reassembling...') \n ## Find all images of the second and third particles\n all_images_p2 = np.tile(p2, 27).reshape(27, 3) + self.all_pbc_shifts\n all_images_p3 = np.tile(p3, 27).reshape(27, 3) + self.all_pbc_shifts\n ### select the image that is the closest to particle 1 (note: this only works of self.d < L/2)\n p2_displacements = all_images_p2 - np.tile(p1, 27).reshape(27, 3)\n p3_displacements = all_images_p3 - np.tile(p1, 27).reshape(27, 3)\n # print('displacements', displacements)\n p2_sq_distances = np.sum(p2_displacements * p2_displacements, axis=1)\n p3_sq_distances = np.sum(p3_displacements * p3_displacements, axis=1)\n # print('sq_distances', sq_distances)\n p2_closest_index = np.argmin(p2_sq_distances) \n p2 = all_images_p2[p2_closest_index,:]\n p3_closest_index = np.argmin(p3_sq_distances) \n p3 = all_images_p3[p3_closest_index,:]\n x_assembled = np.array([list(p1),list(p2),list(p3)])\n # print('step', step, 'x_assembled', x_assembled)\n \n # For debugging, store the distance betwen the poarticles for the reassembled rod\n self.d = self.distance(x_assembled[0,:], x_assembled[1,:])\n \n # For debugging, store the triangle altitude c\n v, w = p2-p1, p3-p1\n self.c = np.linalg.norm( np.cross(v,w) ) / np.linalg.norm(v)\n \n # propose a MC translation move\n nudge = np.random.randn(3)\n x_new = x_assembled + self.dx*np.tile(nudge, 3).reshape(3,3)\n \n # propose a rotation move\n \n ## get a random vector on the unit sphere\n vec = 2.0*np.random.random(3) - 1.0\n while np.dot(vec,vec) > 1.0:\n vec = 2.0*np.random.random(3) - 1.0\n vec = vec/np.sqrt( np.dot(vec,vec) ) \n \n ## Find the rotation transformation about this axis\n rotation_radians = self.dtheta*np.random.randn()\n rotation_vector = rotation_radians * vec\n rotation = R.from_rotvec(rotation_vector)\n \n ## Translate the rigid rod to the origin\n midpoint = (x_new[0,:] + x_new[1,:] + x_new[2,:])/3.0\n x_new -= np.tile(midpoint, 3).reshape(3,3)\n ## Rotate it\n x_new_rotated = rotation.apply(x_new)\n # print(x_new_rotated)\n ## Translate it back\n x_new_rotated += np.tile(midpoint, 3).reshape(3,3)\n \n # if any coordinate of x_new goes outside the box, wrap it back in:\n x_new = ((x_new_rotated + np.array([self.L/2., self.L/2., self.L/2.])) % self.L) - np.array([self.L/2., self.L/2., self.L/2.]) \n U_new = self.energy(x_new, self.k_values[self.k_index])\n # print('step', step, 'self.x', 'x_new', self.x, x_new)\n # print('\\tself.U', 'U_new', self.U, U_new)\n \n \n # accept MC move according to the metropolis criterion\n accept = False\n P_accept = min(1., np.exp(-(U_new - self.U)/self.RT))\n if np.random.rand() < P_accept:\n accept = True\n if accept:\n accepted += 1\n self.x = x_new\n self.U = U_new\n\n ########################\n ### WL moves\n ### next, update the WL histogams and propose a WL move\n \n if (step%self.wl_increment_freq == 1):\n\n # WL histograms\n self.g[self.k_index] -= self.wl_increment\n self.h[self.k_index] += 1.0\n\n # reset the bias to i=0 reference\n self.g -= self.g[0]\n\n # attempt a move to a neighboring ensemble\n wl_accept = False\n if np.random.rand() < 0.5:\n k_index_new = self.k_index + 1\n else:\n k_index_new = self.k_index - 1\n\n if (k_index_new >= 0) and (k_index_new < self.n_ensembles):\n energies = self.energy(self.x, self.k_values) \n P_wl_accept = min(1., np.exp( -(energies[k_index_new]/self.RT - self.g[k_index_new] - energies[self.k_index]/self.RT + self.g[self.k_index] )))\n if np.random.rand() < P_wl_accept: #print(f'2 - is now {particles[x]}')\n wl_accept = True \n if wl_accept:\n T_counts[self.k_index, k_index_new] += 1.0\n self.k_index = k_index_new\n else:\n T_counts[self.k_index,self.k_index] += 1.0\n\n\n # check if the histogram is flat enough\n mean_counts = self.h.mean()\n\n which_are_flat_enough = (self.h > self.flatness*mean_counts)*(self.h < (2.0-self.flatness)*mean_counts)\n if step%self.print_every == 0:\n print('h', self.h, 'mean_counts', mean_counts)\n print('which_are_flat_enough', which_are_flat_enough)\n\n if step >= self.steps_before_1_over_t:\n if (self.has_switched_to_1_over_t == False) and (self.wl_increment < self.c_1_over_t/float(step)):\n print('#### Switching to 1/t method ( wl_increment =', self.wl_increment, ') ####')\n self.has_switched_to_1_over_t = True\n\n if np.sum( which_are_flat_enough.astype(int) ) == self.n_ensembles:\n if self.has_switched_to_1_over_t:\n self.wl_increment = self.c_1_over_t/float(step)\n else:\n self.wl_increment *= self.wl_scaling\n self.h = np.zeros(self.n_ensembles)\n\n # print a status report\n if step%self.print_every == 0:\n print('step', step, '| λ index', self.k_index, '| wl_increment =', self.wl_increment, 'kT')\n if not verbose: # just post first and last ensemble info\n print('%8d\\t%8d\\t%3.4f'%(0, self.h[0], self.g[0]))\n print('%8d\\t%8d\\t%3.4f'%(self.n_ensembles, self.h[-1], self.g[-1]))\n if verbose:\n print('# ensemble\\tk_value\\thistogram\\tg (kT)')\n for k in range(self.n_ensembles):\n outstr = '%8d\\t%4.1f\\t%8d\\t%3.4f'%(k, self.k_values[k], self.h[k], self.g[k])\n if k == self.k_index:\n outstr += ' <<'\n print(outstr)\n print()\n\n # store sample in trajectory\n if step%self.traj_every == 0:\n dhdl = self.energy(self.x, self.k_values) - self.energy(self.x, self.k_index)\n data.append([step, self.k_index,\n self.x[0,0], self.x[0,1], self.x[0,2],\n self.x[1,0], self.x[1,1], self.x[1,2],\n self.x[2,0], self.x[2,1], self.x[2,2],\n self.d, self.c,\n self.wl_increment, self.g[-1], dhdl, T_counts])\n\n\n trajectory = pd.DataFrame(data, columns=['step', 'lambda',\n 'x1', 'y1', 'z1', 'x2', 'y2', 'z2', 'x3', 'y3', 'z3', 'distance', 'height',\n 'increment','free_energy','dhdl', 'transition_matrix'])\n print(accepted)\n return trajectory\n\n\n ", "_____no_output_____" ], [ "ee = EESampler_RigidThreeParticle()\n", "self.d 1.0\nself.c 1.0\nself.e 2.0\n" ], [ "ee = EESampler_RigidThreeParticle()\n\nnsteps = 2000000\ntraj = ee.sample(nsteps)\n# print(traj['dhdl'])\n\nstep = traj.loc[:,'step'].values\np1 = np.zeros((step.shape[0], 3))\np1[:,0] = traj.loc[:,'x1'].values\np1[:,1] = traj.loc[:,'y1'].values\np1[:,2] = traj.loc[:,'z1'].values\np2 = np.zeros((step.shape[0], 3))\np2[:,0] = traj.loc[:,'x2'].values\np2[:,1] = traj.loc[:,'y2'].values\np2[:,2] = traj.loc[:,'z2'].values\nd = traj.loc[:,'distance'].values\nc = traj.loc[:,'height'].values\n\nimport matplotlib\nfrom matplotlib import pyplot as plt\nplt.figure(figsize=(10,4))\nplt.subplot(1,3,1)\nplt.plot(step, p1)\nplt.plot(step, p2)\nplt.subplot(1,3,2)\nplt.plot(step, d)\nplt.subplot(1,3,3)\nplt.plot(step, c)\n", "self.d 1.0\nself.c 1.0\nself.e 2.0\nstep 0 | λ index 0 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 0\t0.0000 <<\n 1\t 0.5\t 0\t0.0000\n 2\t 1.0\t 0\t0.0000\n 3\t 2.0\t 0\t0.0000\n 4\t 5.0\t 0\t0.0000\n 5\t10.0\t 0\t0.0000\n 6\t15.0\t 0\t0.0000\n 7\t20.0\t 0\t0.0000\n 8\t50.0\t 0\t0.0000\n 9\t100.0\t 0\t0.0000\n 10\t200.0\t 0\t0.0000\n 11\t400.0\t 0\t0.0000\n 12\t800.0\t 0\t0.0000\n\nstep 10000 | λ index 11 | wl_increment = 2.5 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 0\t0.0000\n 1\t 0.5\t 0\t-5.0000\n 2\t 1.0\t 0\t-10.0000\n 3\t 2.0\t 0\t-10.0000\n 4\t 5.0\t 0\t-10.0000\n 5\t10.0\t 6\t0.0000\n 6\t15.0\t 6\t0.0000\n 7\t20.0\t 5\t2.5000\n 8\t50.0\t 19\t2.5000\n 9\t100.0\t 25\t7.5000\n 10\t200.0\t 30\t10.0000\n 11\t400.0\t 33\t7.5000 <<\n 12\t800.0\t 33\t12.5000\n\nstep 20000 | λ index 10 | wl_increment = 2.5 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 113\t0.0000\n 1\t 0.5\t 106\t12.5000\n 2\t 1.0\t 103\t15.0000\n 3\t 2.0\t 102\t17.5000\n 4\t 5.0\t 100\t22.5000\n 5\t10.0\t 101\t45.0000\n 6\t15.0\t 101\t45.0000\n 7\t20.0\t 94\t62.5000\n 8\t50.0\t 96\t92.5000\n 9\t100.0\t 85\t140.0000\n 10\t200.0\t 68\t197.5000 <<\n 11\t400.0\t 51\t245.0000\n 12\t800.0\t 37\t285.0000\n\nstep 30000 | λ index 6 | wl_increment = 1.25 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 93\t0.0000\n 1\t 0.5\t 99\t5.0000\n 2\t 1.0\t 97\t10.0000\n 3\t 2.0\t 93\t17.5000\n 4\t 5.0\t 81\t37.5000\n 5\t10.0\t 71\t72.5000\n 6\t15.0\t 42\t108.7500 <<\n 7\t20.0\t 23\t142.5000\n 8\t50.0\t 20\t148.7500\n 9\t100.0\t 24\t156.2500\n 10\t200.0\t 46\t163.7500\n 11\t400.0\t 61\t182.5000\n 12\t800.0\t 82\t186.2500\n\nstep 40000 | λ index 6 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 0\t0.0000\n 1\t 0.5\t 0\t2.5000\n 2\t 1.0\t 0\t6.2500\n 3\t 2.0\t 0\t10.0000\n 4\t 5.0\t 0\t23.7500\n 5\t10.0\t 8\t30.0000\n 6\t15.0\t 24\t30.0000 <<\n 7\t20.0\t 36\t31.2500\n 8\t50.0\t 64\t38.7500\n 9\t100.0\t 69\t45.6250\n 10\t200.0\t 73\t61.8750\n 11\t400.0\t 90\t92.5000\n 12\t800.0\t 84\t148.7500\n\nstep 50000 | λ index 10 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 36\t0.0000\n 1\t 0.5\t 41\t-0.6250\n 2\t 1.0\t 47\t-0.6250\n 3\t 2.0\t 50\t1.2500\n 4\t 5.0\t 61\t8.1250\n 5\t10.0\t 68\t15.0000\n 6\t15.0\t 81\t16.8750\n 7\t20.0\t 89\t20.6250\n 8\t50.0\t 126\t22.5000\n 9\t100.0\t 140\t23.7500\n 10\t200.0\t 168\t25.0000 <<\n 11\t400.0\t 231\t26.8750\n 12\t800.0\t 310\t30.0000\n\nstep 60000 | λ index 12 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 142\t0.0000\n 1\t 0.5\t 134\t7.5000\n 2\t 1.0\t 125\t16.8750\n 3\t 2.0\t 124\t21.2500\n 4\t 5.0\t 124\t35.0000\n 5\t10.0\t 140\t36.2500\n 6\t15.0\t 154\t37.5000\n 7\t20.0\t 169\t36.8750\n 8\t50.0\t 207\t38.1250\n 9\t100.0\t 215\t43.1250\n 10\t200.0\t 240\t46.2500\n 11\t400.0\t 300\t50.0000\n 12\t800.0\t 374\t56.2500 <<\n\nstep 70000 | λ index 1 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 195\t0.0000\n 1\t 0.5\t 194\t3.1250 <<\n 2\t 1.0\t 195\t6.2500\n 3\t 2.0\t 196\t9.3750\n 4\t 5.0\t 212\t13.1250\n 5\t10.0\t 225\t16.2500\n 6\t15.0\t 239\t17.5000\n 7\t20.0\t 248\t20.6250\n 8\t50.0\t 286\t21.8750\n 9\t100.0\t 303\t21.2500\n 10\t200.0\t 329\t23.7500\n 11\t400.0\t 383\t31.2500\n 12\t800.0\t 443\t46.2500\n\nstep 80000 | λ index 9 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 266\t0.0000\n 1\t 0.5\t 268\t1.2500\n 2\t 1.0\t 272\t2.5000\n 3\t 2.0\t 271\t6.8750\n 4\t 5.0\t 288\t10.0000\n 5\t10.0\t 301\t13.1250\n 6\t15.0\t 320\t11.2500\n 7\t20.0\t 332\t12.5000\n 8\t50.0\t 363\t18.1250\n 9\t100.0\t 374\t21.2500 <<\n 10\t200.0\t 400\t23.7500\n 11\t400.0\t 457\t29.3750\n 12\t800.0\t 536\t32.5000\n\nstep 90000 | λ index 1 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 367\t0.0000\n 1\t 0.5\t 370\t0.6250 <<\n 2\t 1.0\t 373\t2.5000\n 3\t 2.0\t 368\t9.3750\n 4\t 5.0\t 363\t26.2500\n 5\t10.0\t 373\t31.2500\n 6\t15.0\t 387\t32.5000\n 7\t20.0\t 399\t33.7500\n 8\t50.0\t 434\t36.8750\n 9\t100.0\t 441\t42.5000\n 10\t200.0\t 466\t45.6250\n 11\t400.0\t 519\t53.7500\n 12\t800.0\t 588\t63.1250\n\nstep 100000 | λ index 3 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 421\t0.0000\n 1\t 0.5\t 416\t5.6250\n 2\t 1.0\t 426\t3.1250\n 3\t 2.0\t 431\t3.7500 <<\n 4\t 5.0\t 448\t6.8750\n 5\t10.0\t 460\t10.6250\n 6\t15.0\t 469\t15.0000\n 7\t20.0\t 477\t18.7500\n 8\t50.0\t 514\t20.6250\n 9\t100.0\t 528\t21.8750\n 10\t200.0\t 554\t24.3750\n 11\t400.0\t 615\t27.5000\n 12\t800.0\t 689\t33.7500\n\nstep 110000 | λ index 7 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 512\t0.0000\n 1\t 0.5\t 512\t2.5000\n 2\t 1.0\t 511\t6.8750\n 3\t 2.0\t 510\t11.2500\n 4\t 5.0\t 523\t16.8750\n 5\t10.0\t 536\t20.0000\n 6\t15.0\t 549\t21.8750\n 7\t20.0\t 560\t23.7500 <<\n 8\t50.0\t 591\t29.3750\n 9\t100.0\t 602\t32.5000\n 10\t200.0\t 617\t41.8750\n 11\t400.0\t 675\t46.8750\n 12\t800.0\t 750\t52.5000\n\nstep 120000 | λ index 11 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 577\t0.0000\n 1\t 0.5\t 577\t2.5000\n 2\t 1.0\t 581\t3.7500\n 3\t 2.0\t 580\t8.1250\n 4\t 5.0\t 597\t11.2500\n 5\t10.0\t 611\t13.7500\n 6\t15.0\t 625\t15.0000\n 7\t20.0\t 636\t16.8750\n 8\t50.0\t 668\t21.8750\n 9\t100.0\t 678\t25.6250\n 10\t200.0\t 709\t25.0000\n 11\t400.0\t 769\t28.7500 <<\n 12\t800.0\t 840\t36.8750\n\nstep 130000 | λ index 8 | wl_increment = 0.625 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 667\t0.0000\n 1\t 0.5\t 668\t1.8750\n 2\t 1.0\t 671\t3.7500\n 3\t 2.0\t 664\t11.8750\n 4\t 5.0\t 666\t24.3750\n 5\t10.0\t 682\t25.6250\n 6\t15.0\t 697\t26.2500\n 7\t20.0\t 714\t24.3750\n 8\t50.0\t 750\t26.8750 <<\n 9\t100.0\t 759\t31.2500\n 10\t200.0\t 773\t41.2500\n 11\t400.0\t 828\t48.1250\n 12\t800.0\t 909\t50.0000\n\nstep 140000 | λ index 5 | wl_increment = 0.3125 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 0\t0.0000\n 1\t 0.5\t 0\t3.1250\n 2\t 1.0\t 0\t7.5000\n 3\t 2.0\t 0\t15.6250\n 4\t 5.0\t 32\t21.2500\n 5\t10.0\t 45\t23.4375 <<\n 6\t15.0\t 49\t24.0625\n 7\t20.0\t 51\t25.3125\n 8\t50.0\t 55\t27.1875\n 9\t100.0\t 55\t29.0625\n 10\t200.0\t 73\t31.5625\n 11\t400.0\t 111\t35.3125\n 12\t800.0\t 129\t40.9375\n\nstep 150000 | λ index 3 | wl_increment = 0.3125 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 43\t0.0000\n 1\t 0.5\t 47\t1.8750\n 2\t 1.0\t 60\t2.1875\n 3\t 2.0\t 80\t4.0625 <<\n 4\t 5.0\t 120\t7.1875\n 5\t10.0\t 132\t9.6875\n 6\t15.0\t 129\t12.5000\n 7\t20.0\t 130\t14.0625\n 8\t50.0\t 135\t15.6250\n 9\t100.0\t 139\t16.2500\n 10\t200.0\t 158\t18.4375\n 11\t400.0\t 201\t20.6250\n 12\t800.0\t 226\t24.0625\n\nstep 160000 | λ index 9 | wl_increment = 0.3125 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 122\t0.0000\n 1\t 0.5\t 126\t1.8750\n 2\t 1.0\t 136\t3.1250\n 3\t 2.0\t 160\t3.7500\n 4\t 5.0\t 203\t5.9375\n 5\t10.0\t 212\t9.3750\n 6\t15.0\t 217\t9.6875\n 7\t20.0\t 219\t10.9375\n 8\t50.0\t 213\t15.9375\n 9\t100.0\t 206\t20.0000 <<\n 10\t200.0\t 228\t21.2500\n 11\t400.0\t 268\t24.3750\n 12\t800.0\t 290\t28.7500\n\n" ], [ "### compare result with experiment\n\nee_temp = EESampler_RigidThreeParticle()\n\ntheory_dG_in_kT = ee_temp.theory_dg_in_kT()\nprint('theory_dG_in_kT', theory_dG_in_kT)\n\nprint('ee.g',ee.g)\nplt.figure(figsize=(10,4))\n\n# Plot the final free energy estimates as a function of k\nplt.subplot(1,2,1)\nplt.plot(ee.k_values, ee.g, 'o-', label='EE result')\nplt.plot(ee.k_values[1:], theory_dG_in_kT, 'o-', label='theory')\nplt.xlabel('$k$ (kJ/nm$^2$)')\nplt.ylabel('$\\Delta G_{rest}$ (kT)')\n#lt.xscale('log')\nplt.legend(loc='best')\n\n# Plot the convergence of the free energy\nstep = traj.loc[:,'step'].values\nfree_energy = traj.loc[:,'free_energy'].values\nplt.subplot(1,2,2)\nplt.plot(step, free_energy, 'r-')\nplt.xlabel('step')\nplt.ylabel('$\\Delta G_{rest}$ (kT)')\n# plt.legend(loc='best')\n\n\n", "self.d 1.0\nself.c 1.0\nself.e 2.0\nself.d 1.0\nself.c 1.0\nself.e 2.0\nself.L 8.0\nkc_coeff 5.0\nkp1_coeff 6.0\ntheory_dG_in_kT [ 3.63910456 5.7185461 7.79798765 10.54685984 12.62630138 13.84269671\n 14.70574292 17.45461512 19.53405666 21.6134982 23.69293975 25.77238129]\nee.g [ 0. 3.6289978 5.2804184 7.11612701 9.68471527 11.73103333\n 12.99034119 13.8904953 16.87911987 19.1463089 21.32175446 23.47545624\n 25.64460754]\n" ] ], [ [ "### Let's try parameters from an actual simulation: REF_RL/RUN0\n", "_____no_output_____" ] ], [ [ "\"\"\"\n[tud67309@login2 RUN0]$ cat LIG_res.itp\n;LIG_res.itp\n[ position_restraints ]\n;i funct fcx fcy fcz\n6 1 800 800 800\n35 1 800 800 800\n23 1 800 800 800\n\"\"\"\n\n# From LIG_h.pdb:\n\"\"\"\nATOM 6 C28 LIG A 1 11.765 -16.536 1.909 1.00 0.00 C \n...\nATOM 23 C23 LIG A 1 12.358 -10.647 7.766 1.00 0.00 C \n...\nATOM 35 C17 LIG A 1 20.883 -7.674 2.314 1.00 0.00 C \n\"\"\"\n\nx0 = np.zeros((3,3))\nx0[0,:] = np.array([1.1765, -1.6536, 0.1909]) # converted to nm\nx0[1,:] = np.array([1.2358, -1.0647, 0.7766]) # converted to nm\nx0[2,:] = np.array([2.0883, -0.7674, 0.2314]) # converted to nm\n\nV0 = 1660.0 # in Å^3 is the standard volume\nL0 = ((1660.0)**(1/3)) * 0.1 # converted to nm\nprint('L0', L0, 'nm')\n\n\nee_REF0 = EESampler_RigidThreeParticle(L=L0, x0=x0, a1=x0)\n\ntheory_dG_in_kT = ee_REF0.theory_dg_in_kT()\nprint('theory_dG_in_kT', theory_dG_in_kT)\n\nprint('ee_REF0.g', ee_REF0.g)\nplt.figure(figsize=(10,4))\n\n# Plot the final free energy estimates as a function of k\nplt.subplot(1,2,1)\n#plt.plot(ee.k_values, ee.g, 'o-', label='EE result')\nplt.plot(ee_REF0.k_values[1:], theory_dG_in_kT, 'o-', label='theory')\nplt.xlabel('$k$ (kJ/nm$^2$)')\nplt.ylabel('$\\Delta G_{rest}$ (kT)')\nplt.legend(loc='best')", "L0 1.1840481475428983 nm\nself.d 0.8326849284092993\nself.c 1.0486785581066906\nself.e 0.720168877255378\nself.d 0.8326849284092993\nself.c 1.0486785581066906\nself.e 0.720168877255378\nself.L 1.1840481475428983\nkc_coeff 1.7480098038626308\nkp1_coeff 3.334083521100217\ntheory_dG_in_kT [-2.88375874 -0.80431719 1.27512435 4.02399654 6.10343808 7.31983341\n 8.18287963 10.93175182 13.01119336 15.09063491 17.17007645 19.24951799]\nee_REF0.g [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" ] ], [ [ "### REF_RL/RUN1", "_____no_output_____" ] ], [ [ "\"\"\"\n$ cat LIG_res.itp\n;LIG_res.itp\n[ position_restraints ]\n;i funct fcx fcy fcz\n11 1 800 800 800\n25 1 800 800 800\n2 1 800 800 800\n\"\"\"\n\n# From LIG_h.pdb:\n\"\"\"\nATOM 2 C12 LIG A 1 6.050 0.774 17.871 1.00 0.00 C \nATOM 11 C15 LIG A 1 2.770 2.355 21.054 1.00 0.00 C \nATOM 25 C4 LIG A 1 13.466 -1.210 22.191 1.00 0.00 C \n\"\"\"\n\nx0 = np.zeros((3,3))\nx0[0,:] = np.array([0.6050, 0.0774, 1.7871]) # converted to nm\nx0[1,:] = np.array([0.2770, 0.2355, 2.1054]) # converted to nm\nx0[2,:] = np.array([1.3466, -0.1210, 2.2191]) # converted to nm\n\nV0 = 1660.0 # in Å^3 is the standard volume\nL0 = ((1660.0)**(1/3)) * 0.1 # converted to nm\nprint('L0', L0, 'nm')\n\n\nee_REF1 = EESampler_RigidThreeParticle(L=L0, x0=x0, a1=x0)\n\n# The *theory* for the triple-restraint rigid rotor says that \n# dG/kT = -ln ( [(2*\\pi)/(\\beta *3k )]^{3/2} / L^3\n# [(2*\\pi)/(\\beta*2k))]^{1/2} * [(2*\\pi)/(\\beta *(2+c^2/(d/2)^2)k )]^{1/2} / 4 \\pi (d/2)^2\n# [(2*\\pi)/(\\beta *k )]^{1/2} / 2 \\pi c\n\nprint('ee_REF1.d', ee_REF1.d)\nprint('ee_REF1.c', ee_REF1.c)\nprint('ee_REF1.L', ee_REF1.L)\n\nk_prime_coeff = 2.0 + (ee.c/(ee.d/2.))**2.0\nprint('k_prime_coeff', k_prime_coeff)\n\ntheory_dG_in_kT = -1.0*( 3.0/2.0*np.log(2.0*np.pi*ee_REF1.RT/(3.0*ee_REF1.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee_REF1.RT/(2.0*ee_REF1.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee_REF1.RT/(k_prime_coeff*ee_REF0.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee_REF1.RT/ee_REF1.k_values[1:]) \\\n - np.log( ee_REF1.L**3 * 8.0 * (np.pi**2) * (ee_REF1.d/2.0)**2 * ee_REF1.c ) )\n\nprint('theory_dG_in_kT', theory_dG_in_kT)\n\nprint('ee_REF1.g', ee_REF1.g)\nplt.figure(figsize=(10,4))\n\n# Plot the final free energy estimates as a function of k\nplt.subplot(1,2,1)\n#plt.plot(ee.k_values, ee.g, 'o-', label='EE result')\nplt.plot(ee_REF1.k_values[1:], theory_dG_in_kT, 'o-', label='theory')\nplt.xlabel('$k$ (kJ/nm$^2$)')\nplt.ylabel('$\\Delta G_{rest}$ (kT)')\nplt.legend(loc='best')", "L0 1.1840481475428983 nm\nself.d 0.4836264053998706\nself.c 0.834018605392616\nee_REF1.d 0.4836264053998706\nee_REF1.c 0.834018605392616\nee_REF1.L 1.1840481475428983\nk_prime_coeff 5.999999999996005\ntheory_dG_in_kT [-5.57122688 -3.49178533 -1.41234379 1.3365284 3.41596994 4.63236527\n 5.49541149 8.24428368 10.32372522 12.40316677 14.48260831 16.56204985]\nee_REF1.g [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" ] ], [ [ "### REF_RL/RUN2", "_____no_output_____" ] ], [ [ "\"\"\";LIG_res.itp\n[ position_restraints ]\n;i funct fcx fcy fcz\n13 1 800 800 800\n19 1 800 800 800\n9 1 800 800 800\n\"\"\"\n\n# From LIG_h.pdb:\n\"\"\"\nATOM 9 C2 LIG A 1 12.189 0.731 23.852 1.00 0.00 C \nATOM 13 CL LIG A 1 14.006 -1.527 21.119 1.00 0.00 Cl \nATOM 19 C13 LIG A 1 3.244 2.176 20.610 1.00 0.00 C \n\"\"\"\n\nx0 = np.zeros((3,3))\nx0[0,:] = 0.1*np.array([12.189, 0.731, 23.852]) # converted to nm\nx0[1,:] = 0.1*np.array([14.006, -1.527, 21.119]) # converted to nm\nx0[2,:] = 0.1*np.array([ 3.244, 2.176, 20.610]) # converted to nm\n\nV0 = 1660.0 # in Å^3 is the standard volume\nL0 = ((1660.0)**(1/3)) * 0.1 # converted to nm\nprint('L0', L0, 'nm')\n\n\nee_REF2 = EESampler_RigidThreeParticle(L=L0, x0=x0, a1=x0)\n\n# The *theory* for the triple-restraint rigid rotor says that \n# dG/kT = -ln ( [(2*\\pi)/(\\beta *3k )]^{3/2} / L^3\n# [(2*\\pi)/(\\beta*2k))]^{1/2} * [(2*\\pi)/(\\beta *(2+c^2/(d/2)^2)k )]^{1/2} / 4 \\pi (d/2)^2\n# [(2*\\pi)/(\\beta *k )]^{1/2} / 2 \\pi c\n\nprint('ee_REF1.d', ee_REF2.d)\nprint('ee_REF1.c', ee_REF2.c)\nprint('ee_REF1.L', ee_REF2.L)\n\nk_prime_coeff = 2.0 + (ee.c/(ee.d/2.))**2.0\nprint('k_prime_coeff', k_prime_coeff)\n\ntheory_dG_in_kT = -1.0*( 3.0/2.0*np.log(2.0*np.pi*ee_REF2.RT/(3.0*ee_REF2.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee_REF2.RT/(2.0*ee_REF2.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee_REF2.RT/(k_prime_coeff*ee_REF0.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee_REF2.RT/ee_REF2.k_values[1:]) \\\n - np.log( ee_REF2.L**3 * 8.0 * (np.pi**2) * (ee_REF2.d/2.0)**2 * ee_REF2.c ) )\n\nprint('theory_dG_in_kT', theory_dG_in_kT)\n\nprint('ee_REF2.g', ee_REF2.g)\nplt.figure(figsize=(10,4))\n\n# Plot the final free energy estimates as a function of k\nplt.subplot(1,2,1)\n#plt.plot(ee.k_values, ee.g, 'o-', label='EE result')\nplt.plot(ee_REF2.k_values[1:], theory_dG_in_kT, 'o-', label='theory')\nplt.xlabel('$k$ (kJ/nm$^2$)')\nplt.ylabel('$\\Delta G_{rest}$ (kT)')\nplt.legend(loc='best')", "L0 1.1840481475428983 nm\nself.d 0.3983634270361678\nself.c 0.9244294074859049\nee_REF1.d 0.3983634270361678\nee_REF1.c 0.9244294074859049\nee_REF1.L 1.1840481475428983\nk_prime_coeff 5.999999999996005\ntheory_dG_in_kT [-5.85620189 -3.77676035 -1.69731881 1.05155339 3.13099493 4.34739025\n 5.21043647 7.95930867 10.03875021 12.11819175 14.19763329 16.27707483]\nee_REF2.g [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" ], [ "nsteps = 100000\ntraj = ee.sample(nsteps)\n# print(traj['dhdl'])\n\nstep = traj.loc[:,'step'].values\np1 = np.zeros((step.shape[0], 3))\np1[:,0] = traj.loc[:,'x1'].values\np1[:,1] = traj.loc[:,'y1'].values\np1[:,2] = traj.loc[:,'z1'].values\np2 = np.zeros((step.shape[0], 3))\np2[:,0] = traj.loc[:,'x2'].values\np2[:,1] = traj.loc[:,'y2'].values\np2[:,2] = traj.loc[:,'z2'].values\nd = traj.loc[:,'distance'].values\nc = traj.loc[:,'height'].values\n\nimport matplotlib\nfrom matplotlib import pyplot as plt\nplt.figure(figsize=(10,4))\nplt.subplot(1,3,1)\nplt.plot(step, p1)\nplt.plot(step, p2)\nplt.subplot(1,3,2)\nplt.plot(step, d)\nplt.subplot(1,3,3)\nplt.plot(step, c)", "step 0 | λ index 0 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 0\t0.0000 <<\n 1\t 0.5\t 0\t0.0000\n 2\t 1.0\t 0\t0.0000\n 3\t 2.0\t 0\t0.0000\n 4\t 5.0\t 0\t0.0000\n 5\t10.0\t 0\t0.0000\n 6\t15.0\t 0\t0.0000\n 7\t20.0\t 0\t0.0000\n 8\t50.0\t 0\t0.0000\n 9\t100.0\t 0\t0.0000\n 10\t200.0\t 0\t0.0000\n 11\t400.0\t 0\t0.0000\n 12\t800.0\t 0\t0.0000\n\nstep 10000 | λ index 2 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 106\t0.0000\n 1\t 0.5\t 106\t0.0000\n 2\t 1.0\t 107\t-5.0000 <<\n 3\t 2.0\t 107\t-5.0000\n 4\t 5.0\t 103\t15.0000\n 5\t10.0\t 99\t35.0000\n 6\t15.0\t 98\t40.0000\n 7\t20.0\t 95\t55.0000\n 8\t50.0\t 85\t105.0000\n 9\t100.0\t 67\t195.0000\n 10\t200.0\t 27\t395.0000\n 11\t400.0\t 0\t530.0000\n 12\t800.0\t 0\t530.0000\n\nstep 20000 | λ index 8 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 192\t0.0000\n 1\t 0.5\t 192\t0.0000\n 2\t 1.0\t 190\t10.0000\n 3\t 2.0\t 189\t15.0000\n 4\t 5.0\t 188\t20.0000\n 5\t10.0\t 187\t25.0000\n 6\t15.0\t 183\t45.0000\n 7\t20.0\t 180\t60.0000\n 8\t50.0\t 168\t120.0000 <<\n 9\t100.0\t 154\t190.0000\n 10\t200.0\t 122\t350.0000\n 11\t400.0\t 55\t685.0000\n 12\t800.0\t 0\t960.0000\n\nstep 30000 | λ index 2 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 276\t0.0000\n 1\t 0.5\t 277\t-5.0000\n 2\t 1.0\t 276\t0.0000 <<\n 3\t 2.0\t 276\t0.0000\n 4\t 5.0\t 273\t15.0000\n 5\t10.0\t 271\t25.0000\n 6\t15.0\t 271\t25.0000\n 7\t20.0\t 269\t35.0000\n 8\t50.0\t 251\t125.0000\n 9\t100.0\t 233\t215.0000\n 10\t200.0\t 198\t390.0000\n 11\t400.0\t 129\t735.0000\n 12\t800.0\t 0\t1380.0000\n\nstep 40000 | λ index 3 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 359\t0.0000\n 1\t 0.5\t 359\t0.0000\n 2\t 1.0\t 359\t0.0000\n 3\t 2.0\t 359\t0.0000 <<\n 4\t 5.0\t 358\t5.0000\n 5\t10.0\t 354\t25.0000\n 6\t15.0\t 349\t50.0000\n 7\t20.0\t 345\t70.0000\n 8\t50.0\t 329\t150.0000\n 9\t100.0\t 307\t260.0000\n 10\t200.0\t 270\t445.0000\n 11\t400.0\t 198\t805.0000\n 12\t800.0\t 54\t1525.0000\n\nstep 50000 | λ index 2 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 441\t0.0000\n 1\t 0.5\t 441\t0.0000\n 2\t 1.0\t 438\t15.0000 <<\n 3\t 2.0\t 437\t20.0000\n 4\t 5.0\t 435\t30.0000\n 5\t10.0\t 431\t50.0000\n 6\t15.0\t 426\t75.0000\n 7\t20.0\t 423\t90.0000\n 8\t50.0\t 405\t180.0000\n 9\t100.0\t 379\t310.0000\n 10\t200.0\t 335\t530.0000\n 11\t400.0\t 268\t865.0000\n 12\t800.0\t 141\t1500.0000\n\nstep 60000 | λ index 2 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 503\t0.0000\n 1\t 0.5\t 503\t0.0000\n 2\t 1.0\t 503\t0.0000 <<\n 3\t 2.0\t 506\t-15.0000\n 4\t 5.0\t 504\t-5.0000\n 5\t10.0\t 503\t0.0000\n 6\t15.0\t 501\t10.0000\n 7\t20.0\t 500\t15.0000\n 8\t50.0\t 488\t75.0000\n 9\t100.0\t 466\t185.0000\n 10\t200.0\t 430\t365.0000\n 11\t400.0\t 363\t700.0000\n 12\t800.0\t 230\t1365.0000\n\nstep 70000 | λ index 10 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 590\t0.0000\n 1\t 0.5\t 590\t0.0000\n 2\t 1.0\t 590\t0.0000\n 3\t 2.0\t 588\t10.0000\n 4\t 5.0\t 583\t35.0000\n 5\t10.0\t 582\t40.0000\n 6\t15.0\t 580\t50.0000\n 7\t20.0\t 578\t60.0000\n 8\t50.0\t 567\t115.0000\n 9\t100.0\t 548\t210.0000\n 10\t200.0\t 507\t415.0000 <<\n 11\t400.0\t 426\t820.0000\n 12\t800.0\t 271\t1595.0000\n\nstep 80000 | λ index 12 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 665\t0.0000\n 1\t 0.5\t 666\t-5.0000\n 2\t 1.0\t 666\t-5.0000\n 3\t 2.0\t 663\t10.0000\n 4\t 5.0\t 661\t20.0000\n 5\t10.0\t 659\t30.0000\n 6\t15.0\t 657\t40.0000\n 7\t20.0\t 652\t65.0000\n 8\t50.0\t 640\t125.0000\n 9\t100.0\t 621\t220.0000\n 10\t200.0\t 586\t395.0000\n 11\t400.0\t 510\t775.0000\n 12\t800.0\t 354\t1555.0000 <<\n\nstep 90000 | λ index 0 | wl_increment = 5.0 kT\n# ensemble\tk_value\thistogram\tg (kT)\n 0\t 0.0\t 750\t0.0000 <<\n 1\t 0.5\t 749\t5.0000\n 2\t 1.0\t 750\t0.0000\n 3\t 2.0\t 749\t5.0000\n 4\t 5.0\t 744\t30.0000\n 5\t10.0\t 743\t35.0000\n 6\t15.0\t 740\t50.0000\n 7\t20.0\t 739\t55.0000\n 8\t50.0\t 724\t130.0000\n 9\t100.0\t 698\t260.0000\n 10\t200.0\t 650\t500.0000\n 11\t400.0\t 561\t945.0000\n 12\t800.0\t 403\t1735.0000\n\n24970\n" ], [ "# The *theory* for the triple-restraint rigid rotor says that \n# dG/kT = -ln ( [(2*\\pi)/(\\beta *3k )]^{3/2} / L^3\n# [(2*\\pi)/(\\beta*2k))]^{1/2} * [(2*\\pi)/(\\beta *(2+c^2/(d/2)^2)k )]^{1/2} / 4 \\pi (d/2)^2\n# [(2*\\pi)/(\\beta *k )]^{1/2} / 2 \\pi c\n\nprint('ee.d', ee.d)\nprint('ee.c', ee.c)\nprint('ee.L', ee.L)\n\nk_prime_coeff = 2.0 + (ee.c/(ee.d/2.))**2.0\nprint('k_prime_coeff', k_prime_coeff)\n\ntheory_dG_in_kT = -1.0*( 3.0/2.0*np.log(2.0*np.pi*ee.RT/(3.0*ee.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee.RT/(2.0*ee.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee.RT/(k_prime_coeff*ee.k_values[1:])) \\\n + 1.0/2.0*np.log(2.0*np.pi*ee.RT/ee.k_values[1:]) \\\n - np.log( ee.L**3 * 8.0 * (np.pi**2) * (ee.d/2.0)**2 * ee.c ) )\n\nprint('theory_dG_in_kT', theory_dG_in_kT)\n\nprint('ee.g',ee.g)\nplt.figure(figsize=(10,4))\n\n# Plot the final free energy estimates as a function of k\nplt.subplot(1,2,1)\n#plt.plot(ee.k_values, ee.g, 'o-', label='EE result')\nplt.plot(ee.k_values[1:], theory_dG_in_kT, 'o-', label='theory')\nplt.xlabel('$k$ (kJ/nm$^2$)')\nplt.ylabel('$\\Delta G_{rest}$ (kT)')\nplt.legend(loc='best')\n\n# Plot the convergence of the free energy\nstep = traj.loc[:,'step'].values\nfree_energy = traj.loc[:,'free_energy'].values\nplt.subplot(1,2,2)\nplt.plot(step, free_energy, 'r-')\nplt.xlabel('step')\nplt.ylabel('$\\Delta G_{rest}$ (kT)')\n# plt.legend(loc='best')\n\n\n", "ee.d 0.5844506200868992\nee.c 0.40967777340459033\nee.L 1.1840481475428983\nk_prime_coeff 3.965391840602323\ntheory_dG_in_kT [-6.1104699 -4.03102836 -1.95158682 0.79728538 2.87672692 4.09312225\n 4.95616846 7.70504066 9.7844822 11.86392374 13.94336528 16.02280683]\nee.g [ 0. 5. 5. 20. 35. 70. 75. 95. 200. 330. 605. 1045.\n 1725.]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d0388d50badabff005b175e888a7082bbad6deea
24,076
ipynb
Jupyter Notebook
Calculus_Homework/WWB17.2.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
Calculus_Homework/WWB17.2.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
Calculus_Homework/WWB17.2.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
100.736402
19,524
0.864139
[ [ [ "from IPython.display import Image\nfrom IPython.core.display import HTML \nfrom sympy import *\nImage(url= \"https://i.imgur.com/mlreXuN.png\")", "_____no_output_____" ], [ "Image(url= \"https://i.imgur.com/ZspIgwo.png\")\n#https://www.albert.io/blog/how-to-use-the-midpoint-rule-in-ap-calculus/", "_____no_output_____" ], [ "x,a,b,n = symbols('x a b n')\n\nf = lambda x: 25- x**2\na = 0\nb = 5\nn = 5\ndx = (b-a)/n\nmylist = []\n\n#right hand sum\nfor i in range(1,6):\n g = f(i)* dx\n\n print(g)\n print('i =',i)\n print(' ')\n mylist.append(g)\n\nprint(\"total = \",sum(mylist[0:10]))", "24.0\ni = 1\n \n21.0\ni = 2\n \n16.0\ni = 3\n \n9.0\ni = 4\n \n0.0\ni = 5\n \ntotal = 70.0\n" ], [ "x,a,b,n = symbols('x a b n')\n\nf = lambda x: 25- x**2\na = 0\nb = 5\nn = 5\ndx = (b-a)/n\nmylist = []\n\n#left hand sum\nfor i in range(0,5):\n g = f(i)* dx\n\n print(g)\n print('i =',i)\n print(' ')\n mylist.append(g)\n\nprint(\"total = \",sum(mylist[0:10]))", "25.0\ni = 0\n \n24.0\ni = 1\n \n21.0\ni = 2\n \n16.0\ni = 3\n \n9.0\ni = 4\n \ntotal = 95.0\n" ], [ "plot(f(x))", "_____no_output_____" ], [ "Image(url= \"https://i.imgur.com/UZzymrR.png\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
d03895cd876bbb8bea93c6c4bf7fe75bc1800580
131,924
ipynb
Jupyter Notebook
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
d7a71a340ef696c1a92cc9129c3f10f5b9084e57
[ "MIT" ]
null
null
null
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
d7a71a340ef696c1a92cc9129c3f10f5b9084e57
[ "MIT" ]
null
null
null
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
d7a71a340ef696c1a92cc9129c3f10f5b9084e57
[ "MIT" ]
null
null
null
68.853862
1,825
0.639247
[ [ [ "# Creating a Sentiment Analysis Web App\n## Using PyTorch and SageMaker\n\n_Deep Learning Nanodegree Program | Deployment_\n\n---\n\nNow that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to enter a movie review. The web page will then send the review off to our deployed model which will predict the sentiment of the entered review.\n\n## Instructions\n\nSome template code has already been provided for you, and you will need to implement additional functionality to successfully complete this notebook. You will not need to modify the included code beyond what is requested. Sections that begin with '**TODO**' in the header indicate that you need to complete or implement some portion within them. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `# TODO: ...` comment. Please be sure to read the instructions carefully!\n\nIn addition to implementing code, there will be questions for you to answer which relate to the task and your implementation. Each section where you will answer a question is preceded by a '**Question:**' header. Carefully read each question and provide your answer below the '**Answer:**' header by editing the Markdown cell.\n\n> **Note**: Code and Markdown cells can be executed using the **Shift+Enter** keyboard shortcut. In addition, a cell can be edited by typically clicking it (double-click for Markdown cells) or by pressing **Enter** while it is highlighted.\n\n## General Outline\n\nRecall the general outline for SageMaker projects using a notebook instance.\n\n1. Download or otherwise retrieve the data.\n2. Process / Prepare the data.\n3. Upload the processed data to S3.\n4. Train a chosen model.\n5. Test the trained model (typically using a batch transform job).\n6. Deploy the trained model.\n7. Use the deployed model.\n\nFor this project, you will be following the steps in the general outline with some modifications. \n\nFirst, you will not be testing the model in its own step. You will still be testing the model, however, you will do it by deploying your model and then using the deployed model by sending the test data to it. One of the reasons for doing this is so that you can make sure that your deployed model is working correctly before moving forward.\n\nIn addition, you will deploy and use your trained model a second time. In the second iteration you will customize the way that your trained model is deployed by including some of your own code. In addition, your newly deployed model will be used in the sentiment analysis web app.", "_____no_output_____" ], [ "## Step 1: Downloading the data\n\nAs in the XGBoost in SageMaker notebook, we will be using the [IMDb dataset](http://ai.stanford.edu/~amaas/data/sentiment/)\n\n> Maas, Andrew L., et al. [Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/data/sentiment/). In _Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies_. Association for Computational Linguistics, 2011.", "_____no_output_____" ] ], [ [ "%mkdir ../data\n!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data", "mkdir: cannot create directory ‘../data’: File exists\n--2020-10-07 18:13:58-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\nResolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10\nConnecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 84125825 (80M) [application/x-gzip]\nSaving to: ‘../data/aclImdb_v1.tar.gz’\n\n../data/aclImdb_v1. 100%[===================>] 80.23M 9.44MB/s in 10s \n\n2020-10-07 18:14:08 (7.99 MB/s) - ‘../data/aclImdb_v1.tar.gz’ saved [84125825/84125825]\n\n" ] ], [ [ "## Step 2: Preparing and Processing the data\n\nAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a training set and a testing set.", "_____no_output_____" ] ], [ [ "import os\nimport glob\n\ndef read_imdb_data(data_dir='../data/aclImdb'):\n data = {}\n labels = {}\n \n for data_type in ['train', 'test']:\n data[data_type] = {}\n labels[data_type] = {}\n \n for sentiment in ['pos', 'neg']:\n data[data_type][sentiment] = []\n labels[data_type][sentiment] = []\n \n path = os.path.join(data_dir, data_type, sentiment, '*.txt')\n files = glob.glob(path)\n \n for f in files:\n with open(f) as review:\n data[data_type][sentiment].append(review.read())\n # Here we represent a positive review by '1' and a negative review by '0'\n labels[data_type][sentiment].append(1 if sentiment == 'pos' else 0)\n \n assert len(data[data_type][sentiment]) == len(labels[data_type][sentiment]), \\\n \"{}/{} data size does not match labels size\".format(data_type, sentiment)\n \n return data, labels", "_____no_output_____" ], [ "data, labels = read_imdb_data()\nprint(\"IMDB reviews: train = {} pos / {} neg, test = {} pos / {} neg\".format(\n len(data['train']['pos']), len(data['train']['neg']),\n len(data['test']['pos']), len(data['test']['neg'])))", "IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg\n" ] ], [ [ "Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records.", "_____no_output_____" ] ], [ [ "from sklearn.utils import shuffle\n\ndef prepare_imdb_data(data, labels):\n \"\"\"Prepare training and test sets from IMDb movie reviews.\"\"\"\n \n #Combine positive and negative reviews and labels\n data_train = data['train']['pos'] + data['train']['neg']\n data_test = data['test']['pos'] + data['test']['neg']\n labels_train = labels['train']['pos'] + labels['train']['neg']\n labels_test = labels['test']['pos'] + labels['test']['neg']\n \n #Shuffle reviews and corresponding labels within training and test sets\n data_train, labels_train = shuffle(data_train, labels_train)\n data_test, labels_test = shuffle(data_test, labels_test)\n \n # Return a unified training data, test data, training labels, test labets\n return data_train, data_test, labels_train, labels_test", "_____no_output_____" ], [ "train_X, test_X, train_y, test_y = prepare_imdb_data(data, labels)\nprint(\"IMDb reviews (combined): train = {}, test = {}\".format(len(train_X), len(test_X)))", "IMDb reviews (combined): train = 25000, test = 25000\n" ] ], [ [ "Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loaded correctly.", "_____no_output_____" ] ], [ [ "print(train_X[100])\nprint(train_y[100])", "\"The Straight Story\" is a truly beautiful movie about an elderly man named Alvin Straight, who rides his lawnmower across the country to visit his estranged, dying brother. But that's just the basic synapsis...this movie is about so much more than that. This was Richard's Farnworth's last role before he died, and it's definitely one that he will be remembered for. He's a stubborn old man, not unlike a lot of the old men that you and I probably know. <br /><br />\"The Straight Story\" is a movie that everyone should watch at least once in their lives. It will reach down and touch some part of you, at least if you have a heart, it will.\n1\n" ] ], [ [ "The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis.", "_____no_output_____" ] ], [ [ "import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\n\nimport re\nfrom bs4 import BeautifulSoup\n\ndef review_to_words(review):\n nltk.download(\"stopwords\", quiet=True)\n stemmer = PorterStemmer()\n \n text = BeautifulSoup(review, \"html.parser\").get_text() # Remove HTML tags\n text = re.sub(r\"[^a-zA-Z0-9]\", \" \", text.lower()) # Convert to lower case\n words = text.split() # Split string into words\n words = [w for w in words if w not in stopwords.words(\"english\")] # Remove stopwords\n words = [PorterStemmer().stem(w) for w in words] # stem\n \n return words", "_____no_output_____" ], [ "import re\n\nREPLACE_NO_SPACE = re.compile(\"(\\.)|(\\;)|(\\:)|(\\!)|(\\')|(\\?)|(\\,)|(\\\")|(\\()|(\\))|(\\[)|(\\])\")\nREPLACE_WITH_SPACE = re.compile(\"(<br\\s*/><br\\s*/>)|(\\-)|(\\/)\")\n\ndef review_to_words_2(review):\n words = REPLACE_NO_SPACE.sub(\"\", review.lower())\n words = REPLACE_WITH_SPACE.sub(\" \", words)\n return words", "_____no_output_____" ] ], [ [ "The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set.", "_____no_output_____" ] ], [ [ "# TODO: Apply review_to_words to a review (train_X[100] or any other review)\nreview_to_words(train_X[100])", "_____no_output_____" ] ], [ [ "**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do to the input?", "_____no_output_____" ], [ "**Answer:**1)remove any non-alpha numeric characters (like punctuation), which are not useful, to improve the accuracy 2) remove all the Remove all the predefined english stopwords, like is, a, of, the, to, his......which are neutral words,to improve the accuracy 3) convert all in lower cases 4) get the only stem parts of the words", "_____no_output_____" ], [ "The method below applies the `review_to_words` method to each of the reviews in the training and testing datasets. In addition it caches the results. This is because performing this processing step can take a long time. This way if you are unable to complete the notebook in the current session, you can come back without needing to process the data a second time.", "_____no_output_____" ] ], [ [ "import pickle\n\ncache_dir = os.path.join(\"../cache\", \"sentiment_analysis\") # where to store cache files\nos.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists\n\ndef preprocess_data(data_train, data_test, labels_train, labels_test,\n cache_dir=cache_dir, cache_file=\"preprocessed_data.pkl\"):\n \"\"\"Convert each review to words; read from cache if available.\"\"\"\n\n # If cache_file is not None, try to read from it first\n cache_data = None\n if cache_file is not None:\n try:\n with open(os.path.join(cache_dir, cache_file), \"rb\") as f:\n cache_data = pickle.load(f)\n print(\"Read preprocessed data from cache file:\", cache_file)\n except:\n pass # unable to read from cache, but that's okay\n \n # If cache is missing, then do the heavy lifting\n if cache_data is None:\n # Preprocess training and test data to obtain words for each review\n #words_train = list(map(review_to_words, data_train))\n #words_test = list(map(review_to_words, data_test))\n words_train = [review_to_words(review) for review in data_train]\n words_test = [review_to_words(review) for review in data_test]\n \n # Write to cache file for future runs\n if cache_file is not None:\n cache_data = dict(words_train=words_train, words_test=words_test,\n labels_train=labels_train, labels_test=labels_test)\n with open(os.path.join(cache_dir, cache_file), \"wb\") as f:\n pickle.dump(cache_data, f)\n print(\"Wrote preprocessed data to cache file:\", cache_file)\n else:\n # Unpack data loaded from cache file\n words_train, words_test, labels_train, labels_test = (cache_data['words_train'],\n cache_data['words_test'], cache_data['labels_train'], cache_data['labels_test'])\n \n return words_train, words_test, labels_train, labels_test", "_____no_output_____" ], [ "# Preprocess data\ntrain_X, test_X, train_y, test_y = preprocess_data(train_X, test_X, train_y, test_y)", "Read preprocessed data from cache file: preprocessed_data.pkl\n" ] ], [ [ "## Transform the data\n\nIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of course, some of the words that appear in the reviews occur very infrequently and so likely don't contain much information for the purposes of sentiment analysis. The way we will deal with this problem is that we will fix the size of our working vocabulary and we will only include the words that appear most frequently. We will then combine all of the infrequent words into a single category and, in our case, we will label it as `1`.\n\nSince we will be using a recurrent neural network, it will be convenient if the length of each review is the same. To do this, we will fix a size for our reviews and then pad short reviews with the category 'no word' (which we will label `0`) and truncate long reviews.", "_____no_output_____" ], [ "### (TODO) Create a word dictionary\n\nTo begin with, we need to construct a way to map words that appear in the reviews to integers. Here we fix the size of our vocabulary (including the 'no word' and 'infrequent' categories) to be `5000` but you may wish to change this to see how it affects the model.\n\n> **TODO:** Complete the implementation for the `build_dict()` method below. Note that even though the vocab_size is set to `5000`, we only want to construct a mapping for the most frequently appearing `4998` words. This is because we want to reserve the special labels `0` for 'no word' and `1` for 'infrequent word'.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom collections import Counter\ndef build_dict(data, vocab_size = 5000):\n \"\"\"Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer.\"\"\"\n \n # TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and that a\n # sentence is a list of words.\n \n word_count ={} # A dict storing the words that appear in the reviews along with how often they occur\n ####Begin: Yanfei First Try#############\n #word_count =Counter(x for xs in data for x in set(xs)) # it is a sorted dictionary already, with the most frequently appearing word in word_count[0], the last frequently appearing word in word_count[-1]\n # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and\n # sorted_words[-1] is the least frequently appearing word.\n #words_sorted=sorted(words.items(), key=lambda x: x[1], reverse=True) # it seems not nesseary, since it is a sorted dictionary already, with the most frequently appearing word first, the last frequently appearing word last\n # sorted_words = None\n # sorted_words = list(word_count.keys()) \n ####End: Yanfei First Try#############\n \n ####Begin: Yanfei Second Try############\n review_words = []\n for review_id in range(len(data)):\n for review_word in data[review_id]:\n review_words.append(review_word)\n word_count = Counter(review_words)\n sorted_words = sorted(word_count, key=word_count.get, reverse=True) # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and\n # sorted_words[-1] is the least frequently appearing word.\n ###End: Yanfei Second Try###############\n \n ####Begin: Yanfei Third Try############\n # word_count =Counter(x for xs in data for x in set(xs))\n # sorted_words = sorted(word_count, key=word_count.get, reverse=True) # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and\n # sorted_words[-1] is the least frequently appearing word.\n ###End: Yanfei Third Try###############\n \n word_dict = {} # This is what we are building, a dictionary that translates words into integers\n for idx, word in enumerate(sorted_words[:vocab_size - 2]): # The -2 is so that we save room for the 'no word'\n word_dict[word] = idx + 2 # 'infrequent' labels\n \n return word_dict", "_____no_output_____" ], [ "word_dict = build_dict(train_X)", "_____no_output_____" ] ], [ [ "**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set?", "_____no_output_____" ], [ "**Answer:**['one', 'come', 'cartoon', 'long', 'minut'], yes, it make sense to see it in the movie review.", "_____no_output_____" ] ], [ [ "# TODO: Use this space to determine the five most frequently appearing words in the training set.\n list(word_dict.keys())[0:5] ", "_____no_output_____" ] ], [ [ "### Save `word_dict`\n\nLater on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use.", "_____no_output_____" ] ], [ [ "data_dir = '../data/pytorch' # The folder we will use for storing data\nif not os.path.exists(data_dir): # Make sure that the folder exists\n os.makedirs(data_dir)", "_____no_output_____" ], [ "with open(os.path.join(data_dir, 'word_dict.pkl'), \"wb\") as f:\n pickle.dump(word_dict, f)", "_____no_output_____" ] ], [ [ "### Transform the reviews\n\nNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`.", "_____no_output_____" ] ], [ [ "def convert_and_pad(word_dict, sentence, pad=500):\n NOWORD = 0 # We will use 0 to represent the 'no word' category\n INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict\n \n working_sentence = [NOWORD] * pad\n \n for word_index, word in enumerate(sentence[:pad]):\n if word in word_dict:\n working_sentence[word_index] = word_dict[word]\n else:\n working_sentence[word_index] = INFREQ\n \n return working_sentence, min(len(sentence), pad)\n\ndef convert_and_pad_data(word_dict, data, pad=500):\n result = []\n lengths = []\n \n for sentence in data:\n converted, leng = convert_and_pad(word_dict, sentence, pad)\n result.append(converted)\n lengths.append(leng)\n \n return np.array(result), np.array(lengths)", "_____no_output_____" ], [ "train_X, train_X_len = convert_and_pad_data(word_dict, train_X)\ntest_X, test_X_len = convert_and_pad_data(word_dict, test_X)", "_____no_output_____" ] ], [ [ "As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set?", "_____no_output_____" ] ], [ [ "# Use this cell to examine one of the processed reviews to make sure everything is working as intended.\nprint(len(train_X))\nprint(len(train_X_len))\nprint(len(test_X))\nprint(len(test_X_len))\nprint(len(train_X[100]))\nprint(train_X[100])", "25000\n25000\n25000\n25000\n500\n[ 421 1135 141 12 4 169 866 1219 1180 119 71 114 248 262\n 51 16 227 84 570 729 1067 3953 1 1 62 569 267 945\n 747 225 1020 629 3519 2255 386 4562 1695 506 4407 702 144 4\n 402 900 296 32 131 196 92 8 151 154 2694 729 1161 5\n 50 12 322 729 181 86 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0]\n" ] ], [ [ "**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem?", "_____no_output_____" ], [ "**Answer:** it can be a problem. we should only have access to the training set so our transformer can only use the training set to construct a representation. The picke file take long time to process until finished. preprocess_data faces problem when the pickle file is not ready yet.\nconvert_and_pad_data may have problem if the review is too long (now size ist limited to 500)-> we will lost the information. Maybe we extract the total different meaning of the original review, when the critical comments in the last part of the review.", "_____no_output_____" ], [ "## Step 3: Upload the data to S3\n\nAs in the XGBoost notebook, we will need to upload the training dataset to S3 in order for our training code to access it. For now we will save it locally and we will upload to S3 later on.\n\n### Save the processed training dataset locally\n\nIt is important to note the format of the data that we are saving as we will need to know it when we write the training code. In our case, each row of the dataset has the form `label`, `length`, `review[500]` where `review[500]` is a sequence of `500` integers representing the words in the review.", "_____no_output_____" ] ], [ [ "import pandas as pd\n \npd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \\\n .to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)", "_____no_output_____" ] ], [ [ "### Uploading the training data\n\n\nNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model.", "_____no_output_____" ] ], [ [ "import sagemaker\n\nsagemaker_session = sagemaker.Session()\n\nbucket = sagemaker_session.default_bucket()\nprefix = 'sagemaker/sentiment_rnn'\n\nrole = sagemaker.get_execution_role()", "_____no_output_____" ], [ "input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)", "_____no_output_____" ] ], [ [ "**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also in the S3 training bucket) and that we will need to make sure it gets saved in the model directory.", "_____no_output_____" ], [ "## Step 4: Build and Train the PyTorch Model\n\nIn the XGBoost notebook we discussed what a model is in the SageMaker framework. In particular, a model comprises three objects\n\n - Model Artifacts,\n - Training Code, and\n - Inference Code,\n \neach of which interact with one another. In the XGBoost example we used training and inference code that was provided by Amazon. Here we will still be using containers provided by Amazon with the added benefit of being able to include our own custom code.\n\nWe will start by implementing our own neural network in PyTorch along with a training script. For the purposes of this project we have provided the necessary model object in the `model.py` file, inside of the `train` folder. You can see the provided implementation by running the cell below.", "_____no_output_____" ] ], [ [ "!pygmentize train/model.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mnn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\r\n\u001b[34mclass\u001b[39;49;00m \u001b[04m\u001b[32mLSTMClassifier\u001b[39;49;00m(nn.Module):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m This is the simple RNN model we will be using to perform Sentiment Analysis.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32m__init__\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, embedding_dim, hidden_dim, vocab_size):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Initialize the model by settingg up the various layers.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n \u001b[36msuper\u001b[39;49;00m(LSTMClassifier, \u001b[36mself\u001b[39;49;00m).\u001b[32m__init__\u001b[39;49;00m()\r\n\r\n \u001b[36mself\u001b[39;49;00m.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=\u001b[34m0\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.lstm = nn.LSTM(embedding_dim, hidden_dim)\r\n \u001b[36mself\u001b[39;49;00m.dense = nn.Linear(in_features=hidden_dim, out_features=\u001b[34m1\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.sig = nn.Sigmoid()\r\n \r\n \u001b[36mself\u001b[39;49;00m.word_dict = \u001b[34mNone\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32mforward\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, x):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Perform a forward pass of our model on some input.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n x = x.t()\r\n lengths = x[\u001b[34m0\u001b[39;49;00m,:]\r\n reviews = x[\u001b[34m1\u001b[39;49;00m:,:]\r\n embeds = \u001b[36mself\u001b[39;49;00m.embedding(reviews)\r\n lstm_out, _ = \u001b[36mself\u001b[39;49;00m.lstm(embeds)\r\n out = \u001b[36mself\u001b[39;49;00m.dense(lstm_out)\r\n out = out[lengths - \u001b[34m1\u001b[39;49;00m, \u001b[36mrange\u001b[39;49;00m(\u001b[36mlen\u001b[39;49;00m(lengths))]\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mself\u001b[39;49;00m.sig(out.squeeze())\r\n" ] ], [ [ "The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training script so that if we wish to modify them we do not need to modify the script itself. We will see how to do this later on. To start we will write some of the training code in the notebook so that we can more easily diagnose any issues that arise.\n\nFirst we will load a small portion of the training data set to use as a sample. It would be very time consuming to try and train the model completely in the notebook as we do not have access to a gpu and the compute instance that we are using is not particularly powerful. However, we can work on a small bit of the data to get a feel for how our training script is behaving.", "_____no_output_____" ] ], [ [ "import torch\nimport torch.utils.data\n\n# Read in only the first 250 rows\ntrain_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250)\n\n# Turn the input pandas dataframe into tensors\ntrain_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze()\ntrain_sample_X = torch.from_numpy(train_sample.drop([0], axis=1).values).long()\n\n# Build the dataset\ntrain_sample_ds = torch.utils.data.TensorDataset(train_sample_X, train_sample_y)\n# Build the dataloader\ntrain_sample_dl = torch.utils.data.DataLoader(train_sample_ds, batch_size=50)", "_____no_output_____" ] ], [ [ "### (TODO) Writing the training method\n\nNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later.", "_____no_output_____" ] ], [ [ "def train(model, train_loader, epochs, optimizer, loss_fn, device):\n for epoch in range(1, epochs + 1):\n model.train()\n total_loss = 0\n for batch in train_loader: \n batch_X, batch_y = batch\n \n batch_X = batch_X.to(device)\n batch_y = batch_y.to(device)\n \n # TODO: Complete this train method to train the model provided.\n optimizer.zero_grad()\n out = model(batch_X)\n #model.zero_grad()\n #out = model.forward(batch_X)\n loss = loss_fn(out, batch_y)\n loss.backward()\n optimizer.step()\n total_loss += loss.data.item()\n print(\"Epoch: {}, BCELoss: {}\".format(epoch, total_loss / len(train_loader)))", "_____no_output_____" ] ], [ [ "Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early when they are easier to diagnose.", "_____no_output_____" ] ], [ [ "import torch.optim as optim\nfrom train.model import LSTMClassifier\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = LSTMClassifier(32, 100, 5000).to(device)\noptimizer = optim.Adam(model.parameters())\nloss_fn = torch.nn.BCELoss()\n\ntrain(model, train_sample_dl, 5, optimizer, loss_fn, device)", "Epoch: 1, BCELoss: 0.6912282586097718\nEpoch: 2, BCELoss: 0.6808721899986268\nEpoch: 3, BCELoss: 0.6719786524772644\nEpoch: 4, BCELoss: 0.6623488545417786\nEpoch: 5, BCELoss: 0.65109281539917\n" ] ], [ [ "In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one) for a `requirements.txt` file and install any required Python libraries, after which the training script will be run.", "_____no_output_____" ], [ "### (TODO) Training the model\n\nWhen a PyTorch model is constructed in SageMaker, an entry point must be specified. This is the Python file which will be executed when the model is trained. Inside of the `train` directory is a file called `train.py` which has been provided and which contains most of the necessary code to train our model. The only thing that is missing is the implementation of the `train()` method which you wrote earlier in this notebook.\n\n**TODO**: Copy the `train()` method written above and paste it into the `train/train.py` file where required.\n\nThe way that SageMaker passes hyperparameters to the training script is by way of arguments. These arguments can then be parsed and used in the training script. To see how this is done take a look at the provided `train/train.py` file.", "_____no_output_____" ] ], [ [ "from sagemaker.pytorch import PyTorch\n\nestimator = PyTorch(entry_point=\"train.py\",\n source_dir=\"train\",\n role=role,\n framework_version='0.4.0',\n train_instance_count=1,\n train_instance_type='ml.p2.xlarge', #original: train_instance_type='ml.p2.xlarge', the support center haven't processed my ticket\n hyperparameters={\n 'epochs': 10,\n 'hidden_dim': 200,\n })", "_____no_output_____" ], [ "estimator.fit({'training': input_data})", "'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n" ] ], [ [ "## Step 5: Testing the model\n\nAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly.\n\n## Step 6: Deploy the model for testing\n\nNow that we have trained our model, we would like to test it to see how it performs. Currently our model takes input of the form `review_length, review[500]` where `review[500]` is a sequence of `500` integers which describe the words present in the review, encoded using `word_dict`. Fortunately for us, SageMaker provides built-in inference code for models with simple inputs such as this.\n\nThere is one thing that we need to provide, however, and that is a function which loads the saved model. This function must be called `model_fn()` and takes as its only parameter a path to the directory where the model artifacts are stored. This function must also be present in the python file which we specified as the entry point. In our case the model loading function has been provided and so no changes need to be made.\n\n**NOTE**: When the built-in inference code is run it must import the `model_fn()` method from the `train.py` file. This is why the training code is wrapped in a main guard ( ie, `if __name__ == '__main__':` )\n\nSince we don't need to change anything in the code that was uploaded during training, we can simply deploy the current model as-is.\n\n**NOTE:** When deploying a model you are asking SageMaker to launch an compute instance that will wait for data to be sent to it. As a result, this compute instance will continue to run until *you* shut it down. This is important to know since the cost of a deployed endpoint depends on how long it has been running for.\n\nIn other words **If you are no longer using a deployed endpoint, shut it down!**\n\n**TODO:** Deploy the trained model.", "_____no_output_____" ] ], [ [ "estimator.model_data", "_____no_output_____" ], [ "training_job_name=estimator.latest_training_job.name", "_____no_output_____" ], [ "# TODO: Deploy the trained model\npredictor = estimator.deploy(initial_instance_count = 1, instance_type = 'ml.m4.xlarge')\n#original: train_instance_type='ml.p2.xlarge', the support center haven't processed my ticket", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\nUsing already existing model: sagemaker-pytorch-2020-10-08-10-19-04-219\n" ], [ "model_predict = PyTorchModel(model_data=estimator.model_data,\n role = role,\n framework_version='0.4.0',\n entry_point=\"train.py\",\n source_dir=\"train\")\npredictor_predict = model_predict.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n" ], [ "predictor_predict.endpoint", "_____no_output_____" ], [ "predictor = estimator.deploy(initial_instance_count = 1, instance_type = 'ml.p2.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n" ] ], [ [ "## Step 7 - Use the model for testing\n\nOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is.", "_____no_output_____" ] ], [ [ "test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1)", "_____no_output_____" ], [ "# We split the data into chunks and send each chunk seperately, accumulating the results.\n\ndef predict(data, rows=512):\n split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))\n predictions = np.array([])\n for array in split_array:\n predictions = np.append(predictions, predictor.predict(array))\n \n return predictions", "_____no_output_____" ], [ "predictions = predict(test_X.values)\npredictions = [round(num) for num in predictions]", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(test_y, predictions)", "_____no_output_____" ] ], [ [ "**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis?", "_____no_output_____" ], [ "**Answer:**XGBoost has a better accuray score than this model and run much faster. The trainning job for XGBoost takes only 3 minutes, but this model takes 2 hours. I think XGBoost is better for sentiment analysis. Actually this two accuray score is close to each other, may this model can be improved somehow.", "_____no_output_____" ], [ "### (TODO) More testing\n\nWe now have a trained model which has been deployed and which we can send processed reviews to and which returns the predicted sentiment. However, ultimately we would like to be able to send our model an unprocessed review. That is, we would like to send the review itself as a string. For example, suppose we wish to send the following review to our model.", "_____no_output_____" ] ], [ [ "test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.'", "_____no_output_____" ] ], [ [ "The question we now need to answer is, how do we send this review to our model?\n\nRecall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews.\n - Removed any html tags and stemmed the input\n - Encoded the review as a sequence of integers using `word_dict`\n \nIn order process the review we will need to repeat these two steps.\n\n**TODO**: Using the `review_to_words` and `convert_and_pad` methods from section one, convert `test_review` into a numpy array `test_data` suitable to send to our model. Remember that our model expects input of the form `review_length, review[500]`.", "_____no_output_____" ] ], [ [ "# TODO: Convert test_review into a form usable by the model and save the results in test_data\ntest_data = None\ntest_words = review_to_words(test_review)\ntest_data, test_data_len = convert_and_pad(word_dict, test_words)", "_____no_output_____" ] ], [ [ "Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review.", "_____no_output_____" ] ], [ [ "predictor.predict(test_data)", "_____no_output_____" ] ], [ [ "Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive.", "_____no_output_____" ], [ "### Delete the endpoint\n\nOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delete it.", "_____no_output_____" ] ], [ [ "estimator.delete_endpoint()", "_____no_output_____" ] ], [ [ "## Step 6 (again) - Deploy the model for the web app\n\nNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.\n\nAs we saw above, by default the estimator which we created, when deployed, will use the entry script and directory which we provided when creating the model. However, since we now wish to accept a string as input and our model expects a processed review, we need to write some custom inference code.\n\nWe will store the code that we write in the `serve` directory. Provided in this directory is the `model.py` file that we used to construct our model, a `utils.py` file which contains the `review_to_words` and `convert_and_pad` pre-processing functions which we used during the initial data processing, and `predict.py`, the file which will contain our custom inference code. Note also that `requirements.txt` is present which will tell SageMaker what Python libraries are required by our custom inference code.\n\nWhen deploying a PyTorch model in SageMaker, you are expected to provide four functions which the SageMaker inference container will use.\n - `model_fn`: This function is the same function that we used in the training script and it tells SageMaker how to load our model.\n - `input_fn`: This function receives the raw serialized input that has been sent to the model's endpoint and its job is to de-serialize and make the input available for the inference code.\n - `output_fn`: This function takes the output of the inference code and its job is to serialize this output and return it to the caller of the model's endpoint.\n - `predict_fn`: The heart of the inference script, this is where the actual prediction is done and is the function which you will need to complete.\n\nFor the simple website that we are constructing during this project, the `input_fn` and `output_fn` methods are relatively straightforward. We only require being able to accept a string as input and we expect to return a single value as output. You might imagine though that in a more complex application the input or output may be image data or some other binary data which would require some effort to serialize.\n\n### (TODO) Writing inference code\n\nBefore writing our custom inference code, we will begin by taking a look at the code which has been provided.", "_____no_output_____" ] ], [ [ "!pygmentize serve/predict.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36margparse\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mjson\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mos\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpickle\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msys\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msagemaker_containers\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpandas\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mpd\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mnumpy\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnp\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mnn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36moptim\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36moptim\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mutils\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mdata\u001b[39;49;00m\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mmodel\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m LSTMClassifier\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mutils\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m review_to_words, convert_and_pad\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mmodel_fn\u001b[39;49;00m(model_dir):\r\n \u001b[33m\"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\u001b[39;49;00m\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mLoading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n\r\n \u001b[37m# First, load the parameters used to create the model.\u001b[39;49;00m\r\n model_info = {}\r\n model_info_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel_info.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_info_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model_info = torch.load(f)\r\n\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mmodel_info: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(model_info))\r\n\r\n \u001b[37m# Determine the device and construct the model.\u001b[39;49;00m\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n model = LSTMClassifier(model_info[\u001b[33m'\u001b[39;49;00m\u001b[33membedding_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mhidden_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mvocab_size\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m])\r\n\r\n \u001b[37m# Load the store model parameters.\u001b[39;49;00m\r\n model_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.load_state_dict(torch.load(f))\r\n\r\n \u001b[37m# Load the saved word_dict.\u001b[39;49;00m\r\n word_dict_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mword_dict.pkl\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(word_dict_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.word_dict = pickle.load(f)\r\n\r\n model.to(device).eval()\r\n\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mDone loading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m model\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32minput_fn\u001b[39;49;00m(serialized_input_data, content_type):\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mDeserializing the input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mif\u001b[39;49;00m content_type == \u001b[33m'\u001b[39;49;00m\u001b[33mtext/plain\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m:\r\n data = serialized_input_data.decode(\u001b[33m'\u001b[39;49;00m\u001b[33mutf-8\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m data\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mRequested unsupported ContentType in content_type: \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m + content_type)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32moutput_fn\u001b[39;49;00m(prediction_output, accept):\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mSerializing the generated output.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mstr\u001b[39;49;00m(prediction_output)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mpredict_fn\u001b[39;49;00m(input_data, model):\r\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mInferring sentiment of input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \r\n \u001b[34mif\u001b[39;49;00m model.word_dict \u001b[35mis\u001b[39;49;00m \u001b[34mNone\u001b[39;49;00m:\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mModel has not been loaded properly, no word_dict.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \r\n \u001b[37m# TODO: Process input_data so that it is ready to be sent to our model.\u001b[39;49;00m\r\n \u001b[37m# You should produce two variables:\u001b[39;49;00m\r\n \u001b[37m# data_X - A sequence of length 500 which represents the converted review\u001b[39;49;00m\r\n \u001b[37m# data_len - The length of the review\u001b[39;49;00m\r\n \r\n data_X = \u001b[34mNone\u001b[39;49;00m\r\n data_len = \u001b[34mNone\u001b[39;49;00m\r\n words = review_to_words(input_data)\r\n data_X, data_len = convert_and_pad(model.word_dict, words)\r\n \u001b[37m# Using data_X and data_len we construct an appropriate input tensor. Remember\u001b[39;49;00m\r\n \u001b[37m# that our model expects input data of the form 'len, review[500]'.\u001b[39;49;00m\r\n data_pack = np.hstack((data_len, data_X))\r\n data_pack = data_pack.reshape(\u001b[34m1\u001b[39;49;00m, -\u001b[34m1\u001b[39;49;00m)\r\n \r\n data = torch.from_numpy(data_pack)\r\n data = data.to(device)\r\n\r\n \u001b[37m# Make sure to put the model into evaluation mode\u001b[39;49;00m\r\n model.eval()\r\n\r\n \u001b[37m# TODO: Compute the result of applying the model to the input data. The variable `result` should\u001b[39;49;00m\r\n \u001b[37m# be a numpy array which contains a single integer which is either 1 or 0\u001b[39;49;00m\r\n\r\n result = \u001b[34mNone\u001b[39;49;00m\r\n \u001b[34mwith\u001b[39;49;00m torch.no_grad():\r\n output = model.forward(data)\r\n result = \u001b[36mint\u001b[39;49;00m(np.round(output.numpy()))\r\n \u001b[34mreturn\u001b[39;49;00m result\r\n" ] ], [ [ "As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory.\n\n**TODO**: Complete the `predict_fn()` method in the `serve/predict.py` file.", "_____no_output_____" ], [ "### Deploying the model\n\nNow that the custom inference code has been written, we will create and deploy our model. To begin with, we need to construct a new PyTorchModel object which points to the model artifacts created during training and also points to the inference code that we wish to use. Then we can call the deploy method to launch the deployment container.\n\n**NOTE**: The default behaviour for a deployed PyTorch model is to assume that any input passed to the predictor is a `numpy` array. In our case we want to send a string so we need to construct a simple wrapper around the `RealTimePredictor` class to accomodate simple strings. In a more complicated situation you may want to provide a serialization object, for example if you wanted to sent image data.", "_____no_output_____" ] ], [ [ "from sagemaker.predictor import RealTimePredictor\nfrom sagemaker.pytorch import PyTorchModel\n\nclass StringPredictor(RealTimePredictor):\n def __init__(self, endpoint_name, sagemaker_session):\n super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain')\n\nmodel = PyTorchModel(model_data=estimator.model_data,\n role = role,\n framework_version='0.4.0',\n entry_point='predict.py',\n source_dir='serve',\n predictor_cls=StringPredictor)\npredictor = model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\n" ] ], [ [ "### Testing the model\n\nNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is that the amount of time it takes for our model to process the input and then perform inference is quite long and so testing the entire data set would be prohibitive.", "_____no_output_____" ] ], [ [ "import glob\n\ndef test_reviews(data_dir='../data/aclImdb', stop=250):\n \n results = []\n ground = []\n \n # We make sure to test both positive and negative reviews \n for sentiment in ['pos', 'neg']:\n \n path = os.path.join(data_dir, 'test', sentiment, '*.txt')\n files = glob.glob(path)\n \n files_read = 0\n \n print('Starting ', sentiment, ' files')\n \n # Iterate through the files and send them to the predictor\n for f in files:\n with open(f) as review:\n # First, we store the ground truth (was the review positive or negative)\n if sentiment == 'pos':\n ground.append(1)\n else:\n ground.append(0)\n # Read in the review and convert to 'utf-8' for transmission via HTTP\n review_input = review.read().encode('utf-8')\n # Send the review to the predictor and store the results\n results.append(int(predictor.predict(review_input)))\n \n # Sending reviews to our endpoint one at a time takes a while so we\n # only send a small number of reviews\n files_read += 1\n if files_read == stop:\n break\n \n return ground, results", "_____no_output_____" ], [ "ground, results = test_reviews()", "Starting pos files\nStarting neg files\n" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(ground, results)", "_____no_output_____" ] ], [ [ "As an additional test, we can try sending the `test_review` that we looked at earlier.", "_____no_output_____" ] ], [ [ "predictor.predict(test_review)", "_____no_output_____" ] ], [ [ "Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back.", "_____no_output_____" ], [ "## Step 7 (again): Use the model for the web app\n\n> **TODO:** This entire section and the next contain tasks for you to complete, mostly using the AWS console.\n\nSo far we have been accessing our model endpoint by constructing a predictor object which uses the endpoint and then just using the predictor object to perform inference. What if we wanted to create a web app which accessed our model? The way things are set up currently makes that not possible since in order to access a SageMaker endpoint the app would first have to authenticate with AWS using an IAM role which included access to SageMaker endpoints. However, there is an easier way! We just need to use some additional AWS services.\n\n<img src=\"Web App Diagram.svg\">\n\nThe diagram above gives an overview of how the various services will work together. On the far right is the model which we trained above and which is deployed using SageMaker. On the far left is our web app that collects a user's movie review, sends it off and expects a positive or negative sentiment in return.\n\nIn the middle is where some of the magic happens. We will construct a Lambda function, which you can think of as a straightforward Python function that can be executed whenever a specified event occurs. We will give this function permission to send and recieve data from a SageMaker endpoint.\n\nLastly, the method we will use to execute the Lambda function is a new endpoint that we will create using API Gateway. This endpoint will be a url that listens for data to be sent to it. Once it gets some data it will pass that data on to the Lambda function and then return whatever the Lambda function returns. Essentially it will act as an interface that lets our web app communicate with the Lambda function.\n\n### Setting up a Lambda function\n\nThe first thing we are going to do is set up a Lambda function. This Lambda function will be executed whenever our public API has data sent to it. When it is executed it will receive the data, perform any sort of processing that is required, send the data (the review) to the SageMaker endpoint we've created and then return the result.\n\n#### Part A: Create an IAM Role for the Lambda function\n\nSince we want the Lambda function to call a SageMaker endpoint, we need to make sure that it has permission to do so. To do this, we will construct a role that we can later give the Lambda function.\n\nUsing the AWS Console, navigate to the **IAM** page and click on **Roles**. Then, click on **Create role**. Make sure that the **AWS service** is the type of trusted entity selected and choose **Lambda** as the service that will use this role, then click **Next: Permissions**.\n\nIn the search box type `sagemaker` and select the check box next to the **AmazonSageMakerFullAccess** policy. Then, click on **Next: Review**.\n\nLastly, give this role a name. Make sure you use a name that you will remember later on, for example `LambdaSageMakerRole`. Then, click on **Create role**.\n\n#### Part B: Create a Lambda function\n\nNow it is time to actually create the Lambda function.\n\nUsing the AWS Console, navigate to the AWS Lambda page and click on **Create a function**. When you get to the next page, make sure that **Author from scratch** is selected. Now, name your Lambda function, using a name that you will remember later on, for example `sentiment_analysis_func`. Make sure that the **Python 3.6** runtime is selected and then choose the role that you created in the previous part. Then, click on **Create Function**.\n\nOn the next page you will see some information about the Lambda function you've just created. If you scroll down you should see an editor in which you can write the code that will be executed when your Lambda function is triggered. In our example, we will use the code below. \n\n```python\n# We need to use the low-level library to interact with SageMaker since the SageMaker API\n# is not available natively through Lambda.\nimport boto3\n\ndef lambda_handler(event, context):\n\n # The SageMaker runtime is what allows us to invoke the endpoint that we've created.\n runtime = boto3.Session().client('sagemaker-runtime')\n\n # Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given\n response = runtime.invoke_endpoint(EndpointName = '**ENDPOINT NAME HERE**', # The name of the endpoint we created\n ContentType = 'text/plain', # The data format that is expected\n Body = event['body']) # The actual review\n\n # The response is an HTTP response whose body contains the result of our inference\n result = response['Body'].read().decode('utf-8')\n\n return {\n 'statusCode' : 200,\n 'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' },\n 'body' : result\n }\n```\n\nOnce you have copy and pasted the code above into the Lambda code editor, replace the `**ENDPOINT NAME HERE**` portion with the name of the endpoint that we deployed earlier. You can determine the name of the endpoint using the code cell below.", "_____no_output_____" ] ], [ [ "predictor.endpoint", "_____no_output_____" ] ], [ [ "Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function.\n\n### Setting up API Gateway\n\nNow that our Lambda function is set up, it is time to create a new API using API Gateway that will trigger the Lambda function we have just created.\n\nUsing AWS Console, navigate to **Amazon API Gateway** and then click on **Get started**.\n\nOn the next page, make sure that **New API** is selected and give the new api a name, for example, `sentiment_analysis_api`. Then, click on **Create API**.\n\nNow we have created an API, however it doesn't currently do anything. What we want it to do is to trigger the Lambda function that we created earlier.\n\nSelect the **Actions** dropdown menu and click **Create Method**. A new blank method will be created, select its dropdown menu and select **POST**, then click on the check mark beside it.\n\nFor the integration point, make sure that **Lambda Function** is selected and click on the **Use Lambda Proxy integration**. This option makes sure that the data that is sent to the API is then sent directly to the Lambda function with no processing. It also means that the return value must be a proper response object as it will also not be processed by API Gateway.\n\nType the name of the Lambda function you created earlier into the **Lambda Function** text entry box and then click on **Save**. Click on **OK** in the pop-up box that then appears, giving permission to API Gateway to invoke the Lambda function you created.\n\nThe last step in creating the API Gateway is to select the **Actions** dropdown and click on **Deploy API**. You will need to create a new Deployment stage and name it anything you like, for example `prod`.\n\nYou have now successfully set up a public API to access your SageMaker model. Make sure to copy or write down the URL provided to invoke your newly created public API as this will be needed in the next step. This URL can be found at the top of the page, highlighted in blue next to the text **Invoke URL**.", "_____no_output_____" ], [ "## Step 4: Deploying our web app\n\nNow that we have a publicly available API, we can start using it in a web app. For our purposes, we have provided a simple static html file which can make use of the public api you created earlier.\n\nIn the `website` folder there should be a file called `index.html`. Download the file to your computer and open that file up in a text editor of your choice. There should be a line which contains **\\*\\*REPLACE WITH PUBLIC API URL\\*\\***. Replace this string with the url that you wrote down in the last step and then save the file.\n\nNow, if you open `index.html` on your local computer, your browser will behave as a local web server and you can use the provided site to interact with your SageMaker model.\n\nIf you'd like to go further, you can host this html file anywhere you'd like, for example using github or hosting a static site on Amazon's S3. Once you have done this you can share the link with anyone you'd like and have them play with it too!\n\n> **Important Note** In order for the web app to communicate with the SageMaker endpoint, the endpoint has to actually be deployed and running. This means that you are paying for it. Make sure that the endpoint is running when you want to use the web app but that you shut it down when you don't need it, otherwise you will end up with a surprisingly large AWS bill.\n\n**TODO:** Make sure that you include the edited `index.html` file in your project submission.", "_____no_output_____" ], [ "Now that your web app is working, trying playing around with it and see how well it works.\n\n**Question**: Give an example of a review that you entered into your web app. What was the predicted sentiment of your example review?", "_____no_output_____" ], [ "**Answer:**", "_____no_output_____" ], [ "### Delete the endpoint\n\nRemember to always shut down your endpoint if you are no longer using it. You are charged for the length of time that the endpoint is running so if you forget and leave it on you could end up with an unexpectedly large bill.", "_____no_output_____" ] ], [ [ "predictor.delete_endpoint()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
d038a048ac41b963508d67484bd15f86de224a96
23,497
ipynb
Jupyter Notebook
_sources/contents/Python/Statistics.ipynb
mulaab/datasains
53ab639a7b76c444b84d944ff0a92490267d3319
[ "MIT" ]
5
2021-10-07T22:58:45.000Z
2022-03-30T05:36:30.000Z
_sources/contents/Python/Statistics.ipynb
mulaab/datasains
53ab639a7b76c444b84d944ff0a92490267d3319
[ "MIT" ]
2
2021-12-02T14:17:21.000Z
2022-02-09T11:33:04.000Z
_sources/contents/Python/Statistics.ipynb
mulaab/datasains
53ab639a7b76c444b84d944ff0a92490267d3319
[ "MIT" ]
3
2021-12-01T16:41:48.000Z
2022-03-30T05:36:41.000Z
73.428125
14,716
0.788952
[ [ [ "## Statistics", "_____no_output_____" ], [ "### Questions", "_____no_output_____" ], [ "```{admonition} Problem: JOIN Dataframes\n:class: dropdown, tip\nCan you tell me the ways in which 2 pandas data frames can be joined?\n```", "_____no_output_____" ], [ "```{admonition} Solution:\n:class: dropdown\nA very high level difference is that merge() is used to combine two (or more) dataframes on the basis of values of common columns (indices can also be used, use left_index=True and/or right_index=True), and concat() is used to append one (or more) dataframes one below the other (or sideways, depending on whether the axis option is set to 0 or 1).\n\njoin() is used to merge 2 dataframes on the basis of the index; instead of using merge() with the option left_index=True we can use join().\n\n![Combine DataFrames](images/image1.PNG)\n```", "_____no_output_____" ], [ "```{admonition} Problem: [GOOGLE] Normal Distribution\n:class: dropdown, tip\n\nWrite a function to generate N samples from a normal distribution and plot the histogram.\n```", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\ndef normal_sample_generator(N):\n # can be done using np.random.randn or stats.norm.rvs\n #x = np.random.randn(N)\n x = stats.norm.rvs(size=N)\n num_bins = 20\n plt.hist(x, bins=num_bins, facecolor='blue', alpha=0.5)\n\n y = np.linspace(-4, 4, N)\n bin_width = (x.max() - x.min()) / num_bins\n plt.plot(y, stats.norm.pdf(y) * N * bin_width)\n\n plt.show()\n\nnormal_sample_generator(10000)", "_____no_output_____" ] ], [ [ "```{admonition} Problem: [UBER] Bernoulli trial generator\n:class: dropdown, tip\n\nGiven a random Bernoulli trial generator, write a function to return a value sampled from a normal distribution.\n```", "_____no_output_____" ], [ "```{admonition} Solution:\n:class: dropdown\nSolution pending, [Reference material link](Given a random Bernoulli trial generator, how do you return a value sampled from a normal distribution?)\n```", "_____no_output_____" ], [ "```{admonition} Problem: [PINTEREST] Interquartile Distance\n:class: dropdown, tip\n\nGiven an array of unsorted random numbers (decimals) find the interquartile distance.\n```", "_____no_output_____" ] ], [ [ "# Interquartile distance is the difference between first and third quartile\n\n# first let's generate a list of random numbers\n\nimport random\nimport numpy as np\n\nli = [round(random.uniform(33.33, 66.66), 2) for i in range(50)]\nprint(li)\n\nqtl_1 = np.quantile(li,.25)\nqtl_3 = np.quantile(li,.75)\n\nprint(\"Interquartile distance: \", qtl_1 - qtl_3)", "[54.81, 65.68, 63.85, 58.29, 60.14, 53.23, 52.58, 51.62, 61.6, 57.85, 51.37, 38.7, 35.87, 33.95, 61.65, 33.59, 61.33, 44.97, 62.49, 39.67, 51.03, 45.79, 60.99, 60.49, 64.8, 46.16, 46.61, 34.06, 37.78, 56.72, 39.62, 61.38, 55.27, 40.53, 49.31, 58.95, 37.49, 34.39, 60.47, 56.12, 61.41, 34.56, 58.18, 56.35, 63.59, 50.59, 61.51, 42.02, 52.43, 56.71]\nInterquartile distance: -17.7275\n" ] ], [ [ "````{admonition} Problem: [GENENTECH] Imputing the mdeian\n:class: dropdown, tip\n\nWrite a function cheese_median to impute the median price of the selected California cheeses in place of the missing values. You may assume at least one cheese is not missing its price.\n\nInput:\n\n```python\nimport pandas as pd\n\ncheeses = {\"Name\": [\"Bohemian Goat\", \"Central Coast Bleu\", \"Cowgirl Mozzarella\", \"Cypress Grove Cheddar\", \"Oakdale Colby\"], \"Price\" : [15.00, None, 30.00, None, 45.00]}\n\ndf_cheeses = pd.DataFrame(cheeses)\n```\n\n| Name | Price |\n|:---------------------:|:-----:|\n| Bohemian Goat | 15.00 |\n| Central Coast Bleu | 30.00 |\n| Cowgirl Mozzarella | 30.00 |\n| Cypress Grove Cheddar | 30.00 |\n| Oakdale Colby | 45.00 |\n\n````", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ncheeses = {\"Name\": [\"Bohemian Goat\", \"Central Coast Bleu\", \"Cowgirl Mozzarella\", \"Cypress Grove Cheddar\", \"Oakdale Colby\"], \"Price\" : [15.00, None, 30.00, None, 45.00]}\n\ndf_cheeses = pd.DataFrame(cheeses)\n\ndf_cheeses['Price'] = df_cheeses['Price'].fillna(df_cheeses['Price'].median())\ndf_cheeses.head()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d038ad3c60811f36f4ac210aad51370fe4abb7fb
279,963
ipynb
Jupyter Notebook
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
8e25cb4b7dd373278ae6f0383556e5fcc8ddebaf
[ "MIT" ]
6
2021-05-19T11:14:36.000Z
2021-05-25T12:30:50.000Z
real_estate.ipynb
shhubhxm/HousePricePrediction-ML_model
8e25cb4b7dd373278ae6f0383556e5fcc8ddebaf
[ "MIT" ]
null
null
null
real_estate.ipynb
shhubhxm/HousePricePrediction-ML_model
8e25cb4b7dd373278ae6f0383556e5fcc8ddebaf
[ "MIT" ]
null
null
null
180.040514
142,584
0.889071
[ [ [ "# Real Estate Price Prediction", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ], [ "df = pd.read_csv(\"data.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df['CHAS'].value_counts()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 506 entries, 0 to 505\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 CRIM 506 non-null float64\n 1 ZN 506 non-null float64\n 2 INDUS 506 non-null float64\n 3 CHAS 506 non-null int64 \n 4 NOX 506 non-null float64\n 5 RM 506 non-null float64\n 6 AGE 506 non-null float64\n 7 DIS 506 non-null float64\n 8 RAD 506 non-null int64 \n 9 TAX 506 non-null int64 \n 10 PTRATIO 506 non-null float64\n 11 B 506 non-null float64\n 12 LSTAT 506 non-null float64\n 13 MEDV 506 non-null float64\ndtypes: float64(11), int64(3)\nmemory usage: 55.5 KB\n" ], [ "df.describe()", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "df.hist(bins=50, figsize=(20,15))", "_____no_output_____" ] ], [ [ "## train_test_split", "_____no_output_____" ] ], [ [ "import numpy as np\ndef split_train_test(data, test_ratio):\n np.random.seed(42)\n shuffled = np.random.permutation(len(data))\n test_set_size = int(len(data) * test_ratio)\n test_indices = shuffled[:test_set_size]\n train_indices = shuffled[test_set_size:]\n return data.iloc[train_indices], data.iloc[test_indices]", "_____no_output_____" ], [ "train_set, test_set = split_train_test(df, 0.2)", "_____no_output_____" ], [ "print(f\"The length of train dataset is: {len(train_set)}\")", "The length of train dataset is: 405\n" ], [ "print(f\"The length of train dataset is: {len(test_set)}\")", "The length of train dataset is: 101\n" ], [ "def data_percent_allocation(train_set, test_set):\n total = len(df)\n train_percent = round((len(train_set)/total) * 100)\n test_percent = round((len(test_set)/total) * 100)\n return train_percent, test_percent", "_____no_output_____" ], [ "data_percent_allocation(train_set, test_set)", "_____no_output_____" ] ], [ [ "## train_test_split from sklearn", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(df, test_size = 0.2, random_state = 42)\nprint(f\"The length of train dataset is: {len(train_set)}\")\nprint(f\"The length of train dataset is: {len(test_set)}\")", "The length of train dataset is: 404\nThe length of train dataset is: 102\n" ], [ "from sklearn.model_selection import StratifiedShuffleSplit\nsplit = StratifiedShuffleSplit(n_splits = 1, test_size = 0.2, random_state = 42)\nfor train_index, test_index in split.split(df, df['CHAS']):\n strat_train_set = df.loc[train_index]\n strat_test_set = df.loc[test_index] ", "_____no_output_____" ], [ "strat_test_set['CHAS'].value_counts()", "_____no_output_____" ], [ "test_set['CHAS'].value_counts()", "_____no_output_____" ], [ "strat_train_set['CHAS'].value_counts()", "_____no_output_____" ], [ "train_set['CHAS'].value_counts()", "_____no_output_____" ] ], [ [ "### Stratified learning equal splitting of zero and ones", "_____no_output_____" ] ], [ [ "95/7", "_____no_output_____" ], [ "376/28", "_____no_output_____" ], [ "df = strat_train_set.copy()", "_____no_output_____" ] ], [ [ "## Corelations", "_____no_output_____" ] ], [ [ "from pandas.plotting import scatter_matrix\nattributes = [\"MEDV\", \"RM\", \"ZN\" , \"LSTAT\"]\nscatter_matrix(df[attributes], figsize = (12,8))", "_____no_output_____" ], [ "df.plot(kind=\"scatter\", x=\"RM\", y=\"MEDV\", alpha=1)", "_____no_output_____" ] ], [ [ "### Trying out attribute combinations", "_____no_output_____" ] ], [ [ "df[\"TAXRM\"] = df[\"TAX\"]/df[\"RM\"]", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "corr_matrix = df.corr()\ncorr_matrix['MEDV'].sort_values(ascending=False)\n# 1 means strong positive corr and -1 means strong negative corr.\n# EX: if RM will increase our final result(MEDV) in prediction will also increase.", "_____no_output_____" ], [ "df.plot(kind=\"scatter\", x=\"TAXRM\", y=\"MEDV\", alpha=1)", "_____no_output_____" ], [ "df = strat_train_set.drop(\"MEDV\", axis=1)\ndf_labels = strat_train_set[\"MEDV\"].copy()", "_____no_output_____" ] ], [ [ "## Pipeline", "_____no_output_____" ] ], [ [ "from sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer\n\nmy_pipeline = Pipeline([\n ('imputer', SimpleImputer(strategy=\"median\")),\n ('std_scaler', StandardScaler()),\n])", "_____no_output_____" ], [ "df_numpy = my_pipeline.fit_transform(df)", "_____no_output_____" ], [ "df_numpy \n#Numpy array of df as models will take numpy array as input.", "_____no_output_____" ], [ "df_numpy.shape", "_____no_output_____" ] ], [ [ "## Model Selection", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\n# model = LinearRegression()\n# model = DecisionTreeRegressor()\nmodel = RandomForestRegressor()\nmodel.fit(df_numpy, df_labels)", "_____no_output_____" ], [ "some_data = df.iloc[:5]", "_____no_output_____" ], [ "some_labels = df_labels.iloc[:5]", "_____no_output_____" ], [ "prepared_data = my_pipeline.transform(some_data)", "_____no_output_____" ], [ "model.predict(prepared_data)", "_____no_output_____" ], [ "list(some_labels)", "_____no_output_____" ] ], [ [ "## Evaluating the model", "_____no_output_____" ] ], [ [ "from sklearn.metrics import mean_squared_error\ndf_predictions = model.predict(df_numpy)\nmse = mean_squared_error(df_labels, df_predictions)\nrmse = np.sqrt(mse)\nrmse", "_____no_output_____" ], [ "# from sklearn.metrics import accuracy_score\n# accuracy_score(some_data, some_labels, normalize=False)", "_____no_output_____" ] ], [ [ "## Cross Validation", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import cross_val_score\nscores = cross_val_score(model, df_numpy, df_labels, scoring=\"neg_mean_squared_error\", cv=10)\nrmse_scores = np.sqrt(-scores)", "_____no_output_____" ], [ "rmse_scores", "_____no_output_____" ], [ "def print_scores(scores):\n print(\"Scores:\", scores)\n print(\"\\nMean:\", scores.mean())\n print(\"\\nStandard deviation:\", scores.std())", "_____no_output_____" ], [ "print_scores(rmse_scores)", "Scores: [2.79289168 2.69441597 4.40018895 2.56972379 3.33073436 2.62687167\n 4.77007351 3.27403209 3.38378214 3.16691711]\n\nMean: 3.3009631251857217\n\nStandard deviation: 0.7076841067486248\n" ] ], [ [ "### Saving Model", "_____no_output_____" ] ], [ [ "from joblib import dump, load\ndump(model, 'final_model.joblib')\ndump(model, 'final_model.sav')", "_____no_output_____" ] ], [ [ "## Testing model on test data", "_____no_output_____" ] ], [ [ "X_test = strat_test_set.drop(\"MEDV\", axis=1)\nY_test = strat_test_set[\"MEDV\"].copy()\nX_test_prepared = my_pipeline.transform(X_test)\nfinal_predictions = model.predict(X_test_prepared)\nfinal_mse = mean_squared_error(Y_test, final_predictions)\nfinal_rmse = np.sqrt(final_mse)", "_____no_output_____" ], [ "final_rmse", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d038b3509aff1f348f4994c9caf974d615a74464
809,423
ipynb
Jupyter Notebook
doc/ex4_update_in_place.ipynb
gribeill/QGL
ce96caac94b9a5ee621a9bb9c56a14bf23c750e5
[ "Apache-2.0" ]
33
2016-01-29T20:25:08.000Z
2021-11-17T11:41:26.000Z
doc/ex4_update_in_place.ipynb
gribeill/QGL
ce96caac94b9a5ee621a9bb9c56a14bf23c750e5
[ "Apache-2.0" ]
261
2016-01-22T02:35:16.000Z
2021-07-01T17:06:46.000Z
doc/ex4_update_in_place.ipynb
gribeill/QGL
ce96caac94b9a5ee621a9bb9c56a14bf23c750e5
[ "Apache-2.0" ]
9
2016-01-22T20:17:42.000Z
2020-12-24T00:36:03.000Z
26.29021
138
0.545587
[ [ [ "# In-Place Waveform Library Updates\nThis example notebook shows how one can update pulses data in-place without recompiling.\n\n© Raytheon BBN Technologies 2020", "_____no_output_____" ], [ "Set the `SAVE_WF_OFFSETS` flag in order that QGL will output a map of the waveform data within the compiled binary waveform library.", "_____no_output_____" ] ], [ [ "from QGL import *\nimport QGL\nimport os.path\nimport pickle\nQGL.drivers.APS2Pattern.SAVE_WF_OFFSETS = True", "_____no_output_____" ] ], [ [ "Create the usual channel library with a couple of AWGs.", "_____no_output_____" ] ], [ [ "cl = ChannelLibrary(\":memory:\")\nq1 = cl.new_qubit(\"q1\")\naps2_1 = cl.new_APS2(\"BBNAPS1\", address=\"192.168.5.101\") \naps2_2 = cl.new_APS2(\"BBNAPS2\", address=\"192.168.5.102\")\ndig_1 = cl.new_X6(\"X6_1\", address=0)\nh1 = cl.new_source(\"Holz1\", \"HolzworthHS9000\", \"HS9004A-009-1\", power=-30)\nh2 = cl.new_source(\"Holz2\", \"HolzworthHS9000\", \"HS9004A-009-2\", power=-30) \ncl.set_control(q1, aps2_1, generator=h1)\ncl.set_measure(q1, aps2_2, dig_1.ch(1), generator=h2)\ncl.set_master(aps2_1, aps2_1.ch(\"m2\"))\ncl[\"q1\"].measure_chan.frequency = 0e6\ncl.commit()", "Creating engine...\n" ] ], [ [ "Compile a simple sequence.", "_____no_output_____" ] ], [ [ "mf = RabiAmp(cl[\"q1\"], np.linspace(-1, 1, 11))\nplot_pulse_files(mf, time=True)", "Compiled 11 sequences.\n<module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'>\n<module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'>\n" ] ], [ [ "Open the offsets file (in the same directory as the `.aps2` files, one per AWG slice.)", "_____no_output_____" ] ], [ [ "offset_f = os.path.join(os.path.dirname(mf), \"Rabi-BBNAPS1.offsets\")\nwith open(offset_f, \"rb\") as FID:\n offsets = pickle.load(FID)\noffsets", "_____no_output_____" ] ], [ [ "Let's replace every single pulse with a fixed amplitude `Utheta`", "_____no_output_____" ] ], [ [ "pulses = {l: Utheta(q1, amp=0.1, phase=0) for l in offsets}\nwfm_f = os.path.join(os.path.dirname(mf), \"Rabi-BBNAPS1.aps2\")\nQGL.drivers.APS2Pattern.update_wf_library(wfm_f, pulses, offsets)", "_____no_output_____" ] ], [ [ "We see that the data in the file has been updated.", "_____no_output_____" ] ], [ [ "plot_pulse_files(mf, time=True)", "<module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'>\n<module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'>\n" ] ], [ [ "## Profiling \nHow long does this take?", "_____no_output_____" ] ], [ [ "%timeit mf = RabiAmp(cl[\"q1\"], np.linspace(-1, 1, 100))", "Compiled 100 sequences.\nCompiled 100 sequences.\nCompiled 100 sequences.\nCompiled 100 sequences.\nCompiled 100 sequences.\nCompiled 100 sequences.\nCompiled 100 sequences.\nCompiled 100 sequences.\n317 ms ± 6.15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ] ], [ [ "Getting the offsets is fast, and only needs to be done once", "_____no_output_____" ] ], [ [ "def get_offsets():\n offset_f = os.path.join(os.path.dirname(mf), \"Rabi-BBNAPS1.offsets\")\n with open(offset_f, \"rb\") as FID:\n offsets = pickle.load(FID)\n return offsets\n%timeit offsets = get_offsets()", "61.1 µs ± 638 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n" ], [ "%timeit pulses = {l: Utheta(q1, amp=0.1, phase=0) for l in offsets}", "39.3 µs ± 1.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n" ], [ "wfm_f = os.path.join(os.path.dirname(mf), \"Rabi-BBNAPS1.aps2\")\n%timeit QGL.drivers.APS2Pattern.update_wf_library(wfm_f, pulses, offsets)\n# %timeit QGL.drivers.APS2Pattern.update_wf_library(\"/Users/growland/workspace/AWG/Rabi/Rabi-BBNAPS1.aps2\", pulses, offsets)", "1.25 ms ± 19.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] ], [ [ "Moral of the story: 300 ms for initial compilation, and roughly 1.3 ms for update_in_place. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
d038c0465e9a548b88c2d0b173c402a56519ee22
38,988
ipynb
Jupyter Notebook
2_Bash/Bash gff fasta exercises/bash_bioinfo.ipynb
davideippolito/PLB
ecd18e79274cfa46aae53f1332973faf470fdb93
[ "MIT" ]
null
null
null
2_Bash/Bash gff fasta exercises/bash_bioinfo.ipynb
davideippolito/PLB
ecd18e79274cfa46aae53f1332973faf470fdb93
[ "MIT" ]
null
null
null
2_Bash/Bash gff fasta exercises/bash_bioinfo.ipynb
davideippolito/PLB
ecd18e79274cfa46aae53f1332973faf470fdb93
[ "MIT" ]
null
null
null
35.124324
383
0.545501
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d038c8f9c849845e7e96b85044867398fe6e9365
337,047
ipynb
Jupyter Notebook
LinMLTBS.ipynb
MusabNaik/LinMLTBS
a3a2e4a26ddcda61c709d08fd596d527373b2a52
[ "MIT" ]
null
null
null
LinMLTBS.ipynb
MusabNaik/LinMLTBS
a3a2e4a26ddcda61c709d08fd596d527373b2a52
[ "MIT" ]
null
null
null
LinMLTBS.ipynb
MusabNaik/LinMLTBS
a3a2e4a26ddcda61c709d08fd596d527373b2a52
[ "MIT" ]
1
2021-03-05T18:34:53.000Z
2021-03-05T18:34:53.000Z
97.893407
1,667
0.581512
[ [ [ "%load_ext Cython\nimport numpy as np\nnp.set_printoptions(precision=2,suppress=True,linewidth=250,threshold=2000)", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport pyBigWig\nimport math\nimport csv\nimport multiprocessing", "_____no_output_____" ], [ "bw = pyBigWig.open(\"/home/musab/bigwig/wgEncodeSydhTfbsHepg2Arid3anb100279IggrabSig.bigWig\")\nchromo = 'chr14'\ntotal_size = bw.chroms()[chromo]\nF=bw.values(chromo,0,total_size,numpy=True)\nF[np.isnan(F)] = 0", "_____no_output_____" ], [ "%%cython -a\n\nimport numpy as np\nimport pandas as pd\nimport math\nimport copy\nimport os\nimport cython\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef V_BC ( long i, long j,double [::1] CP,double [::1] CiP):\n cdef double P_SUM,iP_SUM\n \n if i == 1:\n P_SUM = CP[j-1]\n iP_SUM = CiP[j-1]\n else:\n P_SUM = CP[j-1]-CP[i-2]\n iP_SUM = CiP[j-1]-CiP[i-2]\n \n try:\n return (P_SUM*(iP_SUM/P_SUM)**2)\n except:\n return 0\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef mean( long i, long j,double [::1] CP,double [::1] Cip):\n cdef double P_SUM,iP_SUM\n \n if i == 1:\n P_SUM = CP[j-1]\n iP_SUM = Cip[j-1]\n else:\n P_SUM = CP[j-1]-CP[i-2]\n iP_SUM = Cip[j-1]-Cip[i-2]\n \n try:\n return iP_SUM/P_SUM\n except:\n return 0\n \n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef lookup(long col,long j,long row,double [:,::1] C,double [::1] CP,double [::1] CiP):\n return C[col+j,j] + V_BC(col+(j+1) , row+(j+1),CP,CiP) \n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef SMAWK(long [::1] mri,long [::1] mci, long j,double [:,::1] C,long [:,::1] D,long [::1]mposi,double [::1] CP,double [::1] CiP):\n cdef long [::1] aci\n cdef long [::1] bri\n\n if mci.shape[0] != mri.shape[0]:\n aci=REDUCE(mri,mci,j,C,CP,CiP)\n else:\n aci=mci\n\n if (mri.shape[0]==1 and aci.shape[0]==1):\n C[mri[0]+j+1,j+1]= lookup(aci[0],j,mri[0],C,CP,CiP)\n mposi[mri[0]]=D[mri[0]+j,j]=aci[0]\n\n return \n\n bri = mri[1::2].copy()\n\n SMAWK(bri,aci,j,C,D,mposi,CP,CiP)\n MFILL(mri,aci,j,C,D,mposi,CP,CiP)\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef REDUCE( long [::1] rows, long [::1] cols, long j,double [:,::1] C,double [::1] CP,double [::1] CiP):\n cdef long p = rows.shape[0]\n cdef long ncols = cols.shape[0]\n cdef long m = cols.shape[0]\n \n predd = np.arange(-1,m+1,dtype=np.int64)\n cdef long [::1] pred = predd\n valuee = np.full((m+1),-1,dtype=np.double)\n cdef double [::1] value = valuee\n\n cdef long a=2 \n cdef long b=1 \n \n rett = np.empty(p,dtype=np.int64)\n cdef long [::1] ret = rett\n cdef long lc = ncols+1\n \n \n value[1]=lookup(cols[0],j,rows[0],C,CP,CiP) \n\n while m > p:\n if value[pred[a]] == -1:\n value[pred[a]] = (lookup(cols[pred[a]-1] ,j, rows[b-1],C,CP,CiP) if cols[pred[a]-1] <= rows[b-1] else 0)\n\n if value[pred[a]] >= (lookup(cols[a-1] ,j, rows[b-1],C,CP,CiP) if cols[a-1] <= rows[b-1] else 0) :\n if b < p :\n b = b+1\n value[a] = (lookup(cols[a-1] ,j, rows[b-1],C,CP,CiP) if cols[a-1] <= rows[b-1] else 0)\n else:\n pred[a+1] = pred[a]\n m = m-1\n\n a = a+1\n\n else:\n pred[a] = pred[pred[a]]\n m = m-1\n if b != 1:\n b = b-1\n else:\n a = a+1\n\n for i in range(p-1,-1,-1):\n ret[i]=cols[pred[lc]-1]\n lc=pred[lc]\n return ret\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef MFILL( long [::1] ari, long [::1] aci, long j,double [:,::1] C,long [:,::1] D,long [::1]mposi,double [::1] CP,double [::1] CiP):\n cdef long m = ari.shape[0]\n cdef long n = aci.shape[0]\n cdef long ii = n-1\n cdef long start\n\n if (m % 2) == 0:\n start = m-2\n else:\n start = m-1\n\n cdef long s,e,ar,ac,i\n cdef double MAX,cc,vv,CURRENT_MAT\n for i in range(start,-1,-2):\n if (i==0):\n s=int(aci[i])\n e=int(mposi[ari[i+1]])\n\n elif (i==m-1):\n s=int(mposi[ari[i-1]])\n e=int(aci[n-1])\n\n else:\n s=int(mposi[ari[i-1]])\n e=int(mposi[ari[i+1]])\n\n if(e > ari[i]):\n e=int(ari[i]) \n\n MAX = 0\n while True:\n ac = aci[ii]\n ar = ari[i]\n if (ac > ar):\n pass \n else:\n CURRENT_MAT = lookup(ac,j,ar,C,CP,CiP)\n\n if (MAX < CURRENT_MAT):\n MAX = CURRENT_MAT\n mposi[ar]=ac\n C[ar+j+1,j+1]=MAX\n D[ar+j,j]=ac+j\n if(ac<=s or ii==-1):\n break\n ii-=1\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ncdef findBestK( long n, long k,long [:,::1] D,double [::1] P,double [::1] CP,double [::1] Cip,double [::1] CF):\n cdef double E1 = 0\n cdef double mean1 = mean(1,n,CP,Cip)\n cdef long J,kk,j,a,K,i,t\n for J in range(1,n):\n E1 += (P[J])*(abs(J-mean1))\n\n cdef double bestAlpha = 0\n cdef long bestK = 0\n\n cdef double Dk,Ek,meanK,A,alpha\n cdef long [::1] T\n cdef long [::1] bestT\n \n for kk in range(k,1,-1):\n T = np.zeros(kk+2,dtype=np.int64)\n T[0] = 1\n T[kk+1] = n\n i = n\n for j in range(kk,0,-1):\n T[j] = D[i-1,j]\n i = int(D[i-1,j])\n if i < 1:\n i=1\n\n Dk = mean(T[kk],T[kk+1],CP,Cip)-mean(T[0],T[1],CP,Cip)\n Ek = 1\n\n for K in range(kk+1):\n meanK = mean(T[K],T[K+1],CP,Cip)\n for J in range(T[K],T[K+1]):\n Ek += (P[J])*(abs(J-meanK))\n\n A = 1\n for a in range (kk+1):\n t = T[a]\n A += P[t]\n\n A *= math.sqrt(kk)\n alpha=((((E1/Ek)*Dk)**2)/A) \n\n if alpha > bestAlpha :\n bestK = kk\n bestT = T\n bestAlpha = alpha\n\n cdef double [::1] vol= np.empty(bestK)\n cdef double [::1] leng = np.empty(bestK)\n if bestK != 0:\n for i in range (1,bestK+1):\n vol[i-1]=(CF[bestT[i]]-CF[bestT[i-1]])\n leng[i-1]=(bestT[i]-bestT[i-1])\n else:\n bestT = np.empty(0,dtype=long)\n \n return bestT,bestK,vol,leng\n\n@cython.boundscheck(False)\n@cython.wraparound(False) \ndef L(float [::1] F, long k):\n import matplotlib.pyplot as plt\n import numpy as np\n import pandas as pd\n import math\n import copy\n import time\n import os\n\n \n cdef long n = len(F)\n cdef double F_SUM = sum(F)\n if F_SUM == 0:\n return [],0,[],[]\n\n CC = np.zeros((n+1,k+2),dtype=np.float64)\n DD = np.zeros((n+1,k+2),dtype=np.int64)\n cdef double [:, ::1] C = CC\n cdef long[:, ::1] D = DD \n cdef long sizeMAT \n cdef long[::1] mposi \n\n cdef double [::1] P = np.empty(n)\n cdef double [::1] CP = np.empty(n)\n cdef double [::1] CF = np.empty(n)\n cdef double [::1] CiP = np.empty(n)\n cdef double [::1] Cip = np.empty(n)\n cdef double PP,iP,ip\n cdef double firstValue = F[0]/F_SUM\n CF[0]=(F[0])\n P[0]=(firstValue)\n CP[0]=(firstValue)\n CiP[0]=(firstValue)\n Cip[0]=(firstValue)\n cdef long i,j,dl\n \n for i in range(1,n):\n CF[i]=(CF[i-1]+F[i])\n PP = F[i]/F_SUM\n iP = PP * i\n ip = PP * (i+1)\n P[i]=(PP)\n CP[i]=(CP[i-1]+PP)\n CiP[i]=(CiP[i-1]+iP)\n Cip[i]=(Cip[i-1]+ip)\n \n mminTj = np.zeros(k+2,dtype=np.int64)\n mmaxTj = np.zeros(k+2,dtype=np.int64)\n cdef long[::1] minTj = mminTj\n cdef long[::1] maxTj = mmaxTj\n\n for j in range(0,k+2):\n if j == k+1:\n minTj[j] = n\n else:\n minTj[j] = j\n\n for j in range(0,k+2):\n if j == 0:\n maxTj[j] = 0\n else:\n maxTj[j] = n-k+j-1 \n\n cdef long l,tj,ex=k-2\n cdef double v,f\n cdef long [::1] initial_rc \n for j in range (0,k+1): \n\n if j == 0:\n for tj in range(minTj[j+1],maxTj[j+1]+1+ex):\n C[tj,j+1]=V_BC(1,tj,CP,CiP)\n \n else: \n if (j>=(3)):\n ex-=1\n sizeMAT = n-k+1+ex\n \n if (j != k):\n mposi = np.zeros(sizeMAT-1,dtype=np.int64)\n initial_rc = np.arange(0,sizeMAT-1,dtype=int)\n SMAWK(initial_rc,initial_rc,j,C,D,mposi,CP,CiP)\n else:\n dl = minTj[k]\n for l in range(minTj[k],maxTj[k]+1):\n f = V_BC(l+1,minTj[k+1],CP,CiP)\n v = f + C[l,k]\n if (C[minTj[k+1],k+1] < v ):\n C[minTj[k+1],k+1] = v\n dl = l\n D[maxTj[k],k]=dl\n\n D[n,k+1] = n\n\n cdef long [::1] bestT\n cdef long bestK\n cdef double [::1] vol\n cdef double [::1] leng\n bestT,bestK,vol,leng = findBestK(n,k,D,P,CP,Cip,CF)\n return (bestT,bestK,vol,leng) ", "_____no_output_____" ], [ "def window(tup):\n start = tup[0]\n end = tup[1]\n froM = start\n winSize = 10000\n to = froM+winSize\n '''\n fname = str(str(chromo)+\"-\"+str(start)+\"-\"+str(end)+\".csv\")\n with open(fname, 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([\"START\", \"END\", \"LENGTH\", \"VOLUME\", \"RANGE\"])\n '''\n df = pd.DataFrame(columns=[\"CHR\",\"START\", \"END\", \"LENGTH\", \"VOLUME\", \"RANGE\"])\n while(froM < end):\n try:\n bestT=[]\n bestK=0\n sF=F[froM:to]\n if len(sF) != winSize:\n sF=np.append(sF,np.zeros(winSize - len(sF),dtype=sF.dtype))\n bestT,bestK,vol,leng=(L(sF,6))\n\n '''\n with open(fname, 'a', newline='') as file:\n writer = csv.writer(file)\n for i in range(bestK):\n writer.writerow([froM+bestT[i],froM+bestT[i+1],leng[i],vol[i],str(str(froM)+':'+str(to))])\n '''\n if bestK != 0:\n for i in range(bestK):\n df = df.append({\"CHR\":chromo,\"START\":froM+bestT[i],\"END\":froM+bestT[i+1], \"LENGTH\":leng[i], \"VOLUME\":vol[i], \"RANGE\":str(str(froM)+':'+str(to))},ignore_index=True)\n\n if bestK == 0:\n froM+=winSize\n else:\n froM+=bestT[bestK]\n to = froM+winSize\n\n except Exception as e:\n print(\"From:{}, To:{}, bestK={}\".format(froM,to,bestK))\n print('from Window, ',e)\n froM+=winSize\n to=froM+winSize\n \n return df", "_____no_output_____" ], [ "%%time\n\npath=\"/home/musab/chip-seq/GM12878-H3K27Ac_COPY/\"\nfile = \"wgEncodeBroadHistoneGm12878H3k27acStdSig.bigWig\"\nbw = pyBigWig.open(str(path+file))\nfull_result_list = []\nfor chromo in bw.chroms():\n\n total_size = bw.chroms()[chromo]\n F=bw.values(chromo,0,total_size,numpy=True)\n F[np.isnan(F)] = 0\n\n\n n = multiprocessing.cpu_count()\n frag = math.ceil(total_size/n)\n job = []\n st=0\n while (st<total_size):\n en =st+frag\n job.append((st,en))\n st = en+1\n\n pool = multiprocessing.Pool(processes=n)\n r = pool.map(window,job)\n \n result = pd.concat(r)\n result = result.reset_index(drop=True)\n full_result_list.extend(r)\n\n result.to_csv(str(path+\"results/\"+chromo+'.csv'), index=False)\n pool.close()\n pool.join()\n print(\"Chromo {} Done !\".format(chromo))\n \nfull_result = pd.concat(full_result_list)\nfull_result = full_result.reset_index(drop=True)\nfull_result.to_csv(str(path+\"results/\"+'full.csv'), index=False)", "Chromo chr1 Done !\nChromo chr10 Done !\nChromo chr11 Done !\nChromo chr12 Done !\nChromo chr13 Done !\nChromo chr14 Done !\nChromo chr15 Done !\nChromo chr16 Done !\nChromo chr17 Done !\nChromo chr18 Done !\nChromo chr19 Done !\nChromo chr2 Done !\nChromo chr20 Done !\nChromo chr21 Done !\nChromo chr22 Done !\nChromo chr3 Done !\nChromo chr4 Done !\nChromo chr5 Done !\nChromo chr6 Done !\nChromo chr7 Done !\nChromo chr8 Done !\nChromo chr9 Done !\nChromo chrX Done !\nCPU times: user 46.2 s, sys: 21.6 s, total: 1min 7s\nWall time: 28min 31s\n" ], [ "import os\nimport glob\nimport pandas as pd\nimport math\nos.chdir(\"/home/musab/chip-seq/GM12878-H3K27Ac/results/\")\n\nextension = 'csv'\nall_filenames = [i for i in glob.glob('*.{}'.format(extension))]\n\n#combine all files in the list\ncombined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ])\ncombined_csv = combined_csv.sort_values('VOLUME', ascending=False)\n#export to csv\n# del(combined_csv['RANGE'])\n# del(combined_csv['VOLUME'])\n# del(combined_csv['LENGTH'])\n\n#combined_csv.to_csv( \"annotate.bed\", header=False,index=False, sep='\\t',encoding='utf-8-sig')", "_____no_output_____" ], [ "anno = combined_csv", "_____no_output_____" ], [ "del(anno['RANGE'])\ndel(anno['VOLUME'])\ndel(anno['LENGTH'])", "_____no_output_____" ], [ "length = anno.shape[0]", "_____no_output_____" ], [ "annotate = anno.head(math.ceil(40821*1.5))#math.ceil(length*0.01))", "_____no_output_____" ], [ "annotate.shape", "_____no_output_____" ], [ "annotate.to_csv( \"anno_1.5.bed\", header=False,index=False, sep='\\t',encoding='utf-8-sig')", "_____no_output_____" ], [ "annotate.tail()", "_____no_output_____" ], [ "anno.tail()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d038cd41b959015ec1e2e830ad266352a9c1817e
9,171
ipynb
Jupyter Notebook
tutorials/tutorial09_inflows.ipynb
nskh/flow
77da84e768958c823ea191dc0508369319858bbe
[ "MIT" ]
null
null
null
tutorials/tutorial09_inflows.ipynb
nskh/flow
77da84e768958c823ea191dc0508369319858bbe
[ "MIT" ]
null
null
null
tutorials/tutorial09_inflows.ipynb
nskh/flow
77da84e768958c823ea191dc0508369319858bbe
[ "MIT" ]
null
null
null
37.896694
425
0.596009
[ [ [ "# Tutorial 09: Inflows\n\nThis tutorial walks you through the process of introducing inflows of vehicles into a network. Inflows allow us to simulate open networks where vehicles may enter (and potentially exit) the network. This exercise is organized as follows: in section 1 we prepare our inflows variables to support inflows into a merge network supplied by Flow, and in section 2 we simulate the merge network in the presence of inflows.\n\n## 1. Adding Inflows\n\nFor this exercise, we will simulate inflows through a highway network with an on-merge. As we will see, the perturbations caused by vehicles entering through the on-merge leads the formation of congested waves downstream in the main highway.\n\nWe begin by importing the merge scenario class provided by Flow.", "_____no_output_____" ] ], [ [ "from flow.scenarios.merge import MergeScenario", "_____no_output_____" ] ], [ [ "A schematic of the above network is availabe in the figure below. As we can see, the edges at the start of the main highway and the on-merge are named \"inflow_highway\" and \"inflow_merge\" respectively. These names will be important to us when we begin specifying our inflows into the network.\n\n<img src=\"img/merge_scheme.png\" width=\"750\">\n\nWe will also define the types of vehicles that are placed in the network. These types of vehicles will also be of significance to us once the inflows are being defined. For this exercise, we add only one type of vehicle to the network, with the vehicle identifier \"human\":", "_____no_output_____" ] ], [ [ "from flow.core.vehicles import Vehicles\nfrom flow.controllers import IDMController\n\n# create an empty vehicles object\nvehicles = Vehicles()\n\n# add some vehicles to this object of type \"human\"\nvehicles.add(\"human\", \n acceleration_controller=(IDMController, {}),\n speed_mode=\"no_collide\", # we use the speed mode \"no_collide\" for better dynamics at the merge\n num_vehicles=20)", "_____no_output_____" ] ], [ [ "Next, we are ready to import and create an empty inflows object.", "_____no_output_____" ] ], [ [ "from flow.core.params import InFlows\n\ninflow = InFlows()", "_____no_output_____" ] ], [ [ "The `InFlows` object is provided as an input during the scenario creation process via the `NetParams` parameter. Introducing these inflows into the network is handled by the backend scenario generation processes during instantiation of the scenario object.\n\nIn order to add new inflows of vehicles of pre-defined types onto specific edges and lanes in the network, we use the `InFlows` object's `add` method. This function accepts the following parameters:\n\n* **veh_type**: type of vehicles entering the edge, must match one of the types set in the Vehicles class\n* **edge**: starting edge for vehicles in this inflow, must match an edge name in the network\n* **veh_per_hour**: number of vehicles entering from the edge per hour, may not be achievable due to congestion and safe driving behavior\n* other parameters, including: **start**, **end**, and **probability**. See documentation for more information.\n\nIn addition to the above parameters, several optional inputs to the `add` method may be found within sumo's documentation at: http://sumo.dlr.de/wiki/Definition_of_Vehicles,_Vehicle_Types,_and_Routes. Some important features include:\n\n* **departLane**: specifies which lane vehicles will enter from on the edge, may be specified as \"all\" or \"random\"\n* **departSpeed**: speed of the vehicles once they enter the network\n\nWe begin by adding inflows of vehicles at a rate of 2000 veh/hr through *all* lanes on the main highways as follows:", "_____no_output_____" ] ], [ [ "inflow.add(veh_type=\"human\",\n edge=\"inflow_highway\",\n vehs_per_hour=2000,\n departSpeed=10,\n departLane=\"random\")", "_____no_output_____" ] ], [ [ "Next, we specify a second inflow of vehicles through the on-merge lane at a rate of only 100 veh/hr.", "_____no_output_____" ] ], [ [ "inflow.add(veh_type=\"human\",\n edge=\"inflow_merge\",\n vehs_per_hour=100,\n departSpeed=10,\n departLane=\"random\")", "_____no_output_____" ] ], [ [ "## 2. Running Simulations with Inflows\n\nWe are now ready to test our inflows in simulation. As mentioned in section 1, the inflows are specified in the `NetParams` object, in addition to all other network-specific parameters. For the merge network, this is done as follows: ", "_____no_output_____" ] ], [ [ "from flow.scenarios.merge import ADDITIONAL_NET_PARAMS\nfrom flow.core.params import NetParams\n\nadditional_net_params = ADDITIONAL_NET_PARAMS.copy()\n\n# we choose to make the main highway slightly longer\nadditional_net_params[\"pre_merge_length\"] = 500\n\nnet_params = NetParams(inflows=inflow, # our inflows\n no_internal_links=False,\n additional_params=additional_net_params)", "_____no_output_____" ] ], [ [ "Finally, we execute the simulation following simulation creation techniques we learned from exercise 1 using the below code block. Running this simulation, we see an excessive number of vehicles entering from the main highway, but only a sparse number of vehicles entering from the on-merge. Nevertheless, this volume of merging vehicles is sufficient to form congestive patterns within the main highway.", "_____no_output_____" ] ], [ [ "from flow.core.params import SumoParams, EnvParams, InitialConfig\nfrom flow.envs.loop.loop_accel import AccelEnv, ADDITIONAL_ENV_PARAMS\nfrom flow.core.experiment import SumoExperiment\n\nsumo_params = SumoParams(render=True,\n sim_step=0.2)\n\nenv_params = EnvParams(additional_params=ADDITIONAL_ENV_PARAMS)\n\ninitial_config = InitialConfig()\n\nscenario = MergeScenario(name=\"merge-example\",\n vehicles=vehicles,\n net_params=net_params,\n initial_config=initial_config)\n\nenv = AccelEnv(env_params, sumo_params, scenario)\n\nexp = SumoExperiment(env, scenario)\n\n_ = exp.run(1, 1500)", "**********************************************************\n**********************************************************\n**********************************************************\nWARNING: Inflows will cause computational performance to\nsignificantly decrease after large number of rollouts. In \norder to avoid this, set SumoParams(restart_instance=True).\n**********************************************************\n**********************************************************\n**********************************************************\nRound 0, return: 461.69990202420087\nAverage, std return: 461.69990202420087, 0.0\nAverage, std speed: 4.068107238565223, 0.0\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" ] ]
d038d0e5621e5692a84151111d531a03c1ac0bab
70,173
ipynb
Jupyter Notebook
01_visualize_valfar.ipynb
fendouai/2018_mldm-deep_metric_learing
e82bdb430fe035734139b902620ffbcb893c471d
[ "Apache-2.0" ]
18
2019-10-03T19:25:06.000Z
2019-10-16T02:06:47.000Z
01_visualize_valfar.ipynb
stefanthaler/2018_mldm-deep_metric_learing
57e71f3d3d4c16833351d438f0c1e96387fe7587
[ "Apache-2.0" ]
null
null
null
01_visualize_valfar.ipynb
stefanthaler/2018_mldm-deep_metric_learing
57e71f3d3d4c16833351d438f0c1e96387fe7587
[ "Apache-2.0" ]
2
2019-03-29T01:44:57.000Z
2019-04-03T08:20:18.000Z
331.004717
61,954
0.910208
[ [ [ "%matplotlib inline\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))\n", "_____no_output_____" ], [ "import numpy as np\nnp.set_printoptions(precision=3, suppress=True)\nimport library.helpers as h\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.metrics import auc\nfrom scipy.integrate import simps\nfrom scipy.interpolate import interp1d\n\n\nLOG_NAME = \"unix_forensic\"\nVIZUALIZATIONS_DIR = \"visualizations\"\n\nfig = plt.figure(figsize=(10,10))\n\n# TODO redo this one [ \nMODEL_NAMES = [ \"lstm-ae\", \"triplet-la\", \"triplet-jd-la-all-40-70-all-all\", \"triplet-jd-la-non-60-65-non-non\", \"triplet-jd-la-00500-60-65-all-all-00001\", \n \"triplet-jd-la-00500-60-65-all-00001-non\", \"triplet-jd-la-01000-60-65-all-all-00001\", \"triplet-jd-la-05000-60-65-all-all-00001\", \"jd-la-x05000-pt60-nt65-llall-lcall-ee00001-ep20\", \"jd-la-xnon-pt40-nt70-llall-lcall-ee00001-ep50\"] \n\n\nMODEL_NAMES_JD = [\n \"triplet-jd-la-all-40-70-all-all\", # baseline, all labels\n \"triplet-jd-la-non-60-65-non-non\",\"triplet-jd-la-non-40-70-non-non\", # jd no labels, 10 ep\n \"jd-la-xnon-pt60-nt65-llnon-lcnon-eenon-ep50\", \n \"jd-la-xnon-pt30-nt75-llnon-lcnon-eenon-ep50\"\n #\"jd-la-x02000-pt55-nt65-llnon-lc00003-ee00002-ep10\",\"jd-la-x02000-pt55-nt65-llnon-lc00003-ee00002-ep20\",\n #\"triplet-jd-la-05000-60-65-all-all-00001\", \"jd-la-x05000-pt60-nt65-llall-lcall-ee00001-ep20\",\n] \n\nMODEL_NAMES_LA = [\n \"triplet-jd-la-all-40-70-all-all\", # baseline, all labels\n \"jd-la-x00500-pt30-nt70-llall-lcall-ee00002-ep30\", # 500 labels \n \"jd-la-x01000-pt30-nt70-llall-lcall-ee00002-ep30\", # 1000 labels\n \"jd-la-x02000-pt30-nt70-llall-lcall-ee00002-ep30\", # 2000 labels\n \"jd-la-x02500-pt30-nt70-llall-lcall-ee00002-ep30\", # 2500 labels \n \"jd-la-x05000-pt30-nt70-llall-lcall-ee00002-ep30\", # 5000 labels \n] \n\nMODEL_NAMES_NT60 = [\n \"jd-la-xnon-pt10-nt60-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt20-nt60-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt30-nt60-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt40-nt60-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt50-nt60-llnon-lcnon-ee00002-ep30\",\n]\n\nMODEL_NAMES_NT70 = [\n \"jd-la-xnon-pt10-nt70-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt20-nt70-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt30-nt70-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt40-nt70-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt50-nt70-llnon-lcnon-ee00002-ep30\",\n \"jd-la-xnon-pt60-nt70-llnon-lcnon-ee00002-ep30\"\n]\n\nMODEL_NAMES_NT80 = [\n \"jd-la-xnon-pt10-nt80-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt20-nt80-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt30-nt80-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt40-nt80-llnon-lcnon-ee00002-ep30\", # \n \"jd-la-xnon-pt50-nt80-llnon-lcnon-ee00002-ep30\",\n \"jd-la-xnon-pt60-nt80-llnon-lcnon-ee00002-ep30\",\n \"jd-la-xnon-pt70-nt80-llnon-lcnon-ee00002-ep30\"\n]\n\nMODEL_NAMES_10 = [\n #\"jd-la-xnon-pt10-nt90-llnon-lcnon-ee00002-ep20\",\n #\"jd-la-xnon-pt20-nt90-llnon-lcnon-ee00002-ep20\",\n #\"jd-la-xnon-pt30-nt90-llnon-lcnon-ee00002-ep20\",\n #\"jd-la-xnon-pt40-nt90-llnon-lcnon-ee00002-ep20\",\n \"jd-la-xnon-pt50-nt90-llnon-lcnon-ee00002-ep20\",\n \"jd-la-xnon-pt52-nt70-llnon-lcnon-ee00002-ep30\",\n #\"jd-la-xnon-pt60-nt90-llnon-lcnon-ee00002-ep20\",\n #\"jd-la-xnon-pt70-nt90-llnon-lcnon-ee00002-ep20\",\n #\"jd-la-xnon-pt80-nt90-llnon-lcnon-ee00002-ep20\",\n \"jd-la-xnon-pt52-nt90-llnon-lcnon-ee00002-ep200\",\n \n]\n\n\n\nMODEL_NAMES = MODEL_NAMES_LA\n\n# \"triplet-jd-la-2000-55-70-40\", \"lstm-ae\", \"triplet-la\", \"triplet-jd-la-3000-55-70-55-30\", \"triplet-jd-la-ma-1500\"\n# [\"triplet-jd-la-2000-55-70-40\",\"triplet-jd-la-3000-55-70-55-30\",\"triplet-jd-la-3000-50-70-55-30\"]\n# [ \"triplet-jd-la-1500-055-70-40\", \"triplet-jd-la-1500-55-75-40\"]\n# \"triplet-jd-la-1500-060-70-40\", \"triplet-jd-la-1500-055-70-40\", \"triplet-jd-la-1500-050-70-40\",\n# [\"triplet-jd-la-1500-050-065-25\", \"triplet-jd-la-1500-065-070-25\", \"triplet-jd-la-1500-060-060-25\"]\n\n#[\"triplet-jd-la-ma-500-02-03\",\"triplet-jd-la-ma-750\",\"triplet-jd-la-ma-1000\", # \"#4169e1\",\n# \"triplet-jd-la-ma-1500\",\n# \"triplet-jaccard\",\"triplet-jaccard-margin\",\n# \"triplet-label\", # all labels\n# \"lstm-ae\"]\nCOLORS = h.get_N_HexCol(len(MODEL_NAMES)+1)\n\nfac_n = np.arange(0, 1.0, 0.0005)\n\nbaseline_valid_accepts = h.load_from_json(\"data/ji_%s_basline-jaccard_valid.json\"%LOG_NAME)\nbaseline_false_accepts = [np.round(f,5) for f in h.load_from_json(\"data/ji_%s_basline-jaccard_false.json\"%LOG_NAME)]\n\ninterpolated_vac = interp1d(baseline_false_accepts, baseline_valid_accepts)\nvac_n = interpolated_vac(fac_n)\nauc_score = auc(fac_n, vac_n)\n\n\nplt.plot( fac_n, interpolated_vac(fac_n), color='r', label=\"%0.3f,baseline\"%auc_score)\nplt.xscale(\"log\")\n\n\nfor i, model_name in enumerate(MODEL_NAMES):\n #print(model_name)\n valid_accepts = h.load_from_json(\"data/%s_%s_valid.json\"%(model_name, LOG_NAME))\n false_accepts = h.load_from_json(\"data/%s_%s_false.json\"%(model_name, LOG_NAME))\n interpolated_vac = interp1d(false_accepts, valid_accepts)\n auc_score = auc(fac_n, interpolated_vac(fac_n))\n plt.plot( fac_n, interpolated_vac(fac_n) , color=COLORS[i+1], label=\"%0.3f, %s\"%(auc_score, model_name))\n\nplt.title(\"VAR/FAR (%s) LA\"%LOG_NAME)\nplt.xlabel('FAR')\nplt.ylabel('VAL')\nplt.legend(loc='lower right')\nplt.show()\n#plt.savefig(\"%s/roc_%s.png\"%(VIZUALIZATIONS_DIR, LOG_NAME))\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
d038dd05d3942648eeecacfd1f639996581caba5
13,476
ipynb
Jupyter Notebook
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
ab1185ffbc4d136d900ef8fd11f9fcf44239f608
[ "MIT" ]
null
null
null
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
ab1185ffbc4d136d900ef8fd11f9fcf44239f608
[ "MIT" ]
2
2020-10-17T01:39:37.000Z
2020-10-17T09:08:30.000Z
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
ab1185ffbc4d136d900ef8fd11f9fcf44239f608
[ "MIT" ]
null
null
null
28.016632
833
0.523969
[ [ [ "# IPython magics\n\nThis notebook is used for testing nbqa with ipython magics.", "_____no_output_____" ] ], [ [ "from random import randint\nfrom IPython import get_ipython", "_____no_output_____" ] ], [ [ "## Cell magics", "_____no_output_____" ] ], [ [ "%%bash\n\nfor n in {1..10}\ndo\n echo -n \"$n \"\ndone", "1 2 3 4 5 6 7 8 9 10 " ], [ "%%time\n\nimport operator\n\n\ndef compute(operand1,operand2, bin_op):\n \"\"\"Perform input binary operation over the given operands.\"\"\"\n return bin_op(operand1, operand2)\n\n\ncompute(5,1, operator.add)", "CPU times: user 31 µs, sys: 4 µs, total: 35 µs\nWall time: 37.9 µs\n" ] ], [ [ "## Help Magics", "_____no_output_____" ] ], [ [ "str.split??", "\u001b[0;31mSignature:\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m/\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msep\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmaxsplit\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;31mDocstring:\u001b[0m\nReturn a list of the words in the string, using sep as the delimiter string.\n\nsep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\nmaxsplit\n Maximum number of splits to do.\n -1 (the default value) means no limit.\n\u001b[0;31mType:\u001b[0m method_descriptor\n" ], [ "# would this comment also be considered as magic?\nstr.split?", "\u001b[0;31mSignature:\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m/\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msep\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmaxsplit\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;31mDocstring:\u001b[0m\nReturn a list of the words in the string, using sep as the delimiter string.\n\nsep\n The delimiter according which to split the string.\n None (the default value) means split according to any whitespace,\n and discard empty strings from the result.\nmaxsplit\n Maximum number of splits to do.\n -1 (the default value) means no limit.\n\u001b[0;31mType:\u001b[0m method_descriptor\n" ], [ " ?str.splitlines", "\u001b[0;31mSignature:\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msplitlines\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m/\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkeepends\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;31mDocstring:\u001b[0m\nReturn a list of the lines in the string, breaking at line boundaries.\n\nLine breaks are not included in the resulting list unless keepends is given and\ntrue.\n\u001b[0;31mType:\u001b[0m method_descriptor\n" ] ], [ [ "## Shell magics", "_____no_output_____" ] ], [ [ " !grep -r '%%HTML' . | wc -l", "2\n" ], [ "flake8_version = !pip list 2>&1 | grep flake8\n\nif flake8_version:\n print(flake8_version)", "['flake8 3.8.4']\n" ] ], [ [ "## Line magics", "_____no_output_____" ] ], [ [ " %time randint(5,10)", "CPU times: user 77 µs, sys: 9 µs, total: 86 µs\nWall time: 201 µs\n" ], [ "if __debug__:\n %time compute(5,1, operator.mul)", "CPU times: user 6 µs, sys: 0 ns, total: 6 µs\nWall time: 9.54 µs\n" ], [ "%time get_ipython().run_line_magic(\"lsmagic\", \"\")", "CPU times: user 102 µs, sys: 13 µs, total: 115 µs\nWall time: 124 µs\n" ], [ "import pprint\nimport sys\n\n%time pretty_print_object = pprint.PrettyPrinter(\\\n indent=4, width=80, stream=sys.stdout, compact=True, depth=5\\\n )", "CPU times: user 29 µs, sys: 0 ns, total: 29 µs\nWall time: 33.4 µs\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d038dec301248a6c3af96d59c4a81d664f7bae3b
267,747
ipynb
Jupyter Notebook
beta_binomial_baseball.ipynb
thomasmartins/pystan_misc
3f580274e432d8a63c8a9ab41dfc4ddcd71bcd12
[ "MIT" ]
null
null
null
beta_binomial_baseball.ipynb
thomasmartins/pystan_misc
3f580274e432d8a63c8a9ab41dfc4ddcd71bcd12
[ "MIT" ]
null
null
null
beta_binomial_baseball.ipynb
thomasmartins/pystan_misc
3f580274e432d8a63c8a9ab41dfc4ddcd71bcd12
[ "MIT" ]
null
null
null
420.985849
175,688
0.917814
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pystan\nimport pybaseball\nimport arviz as az", "_____no_output_____" ], [ "player_names = [\"Peter Alonso\",\"Keston Hiura\",\"Fernando Tatis Jr.\",\"Harold Ramirez\",\"Jose Trevino\",\"Yordan Alvarez\",\"Vladimir Guerrero Jr.\",\"Steve Wilkerson\"]", "_____no_output_____" ], [ "batter_data = pybaseball.batting_stats(2019)", "_____no_output_____" ], [ "batter_data = batter_data.loc[batter_data['Name'].isin(player_names)].set_index(\"Name\")\nbatter_data", "_____no_output_____" ], [ "binomial_data = {}\nfor player in batter_data.index:\n hits = int(batter_data.loc[player][\"H\"])\n ab_minus_hits = int(batter_data.loc[player][\"AB\"]) - hits\n ab_outcomes = [0]*ab_minus_hits + [1]*hits\n binomial_data.update({player:ab_outcomes})\nat_bat_totals = {}\nfor player in batter_data.index:\n at_bat_count = int(batter_data.loc[player][\"AB\"])\n at_bat_totals.update({player:at_bat_count})\nhit_totals = {}\nfor player in batter_data.index:\n hit_count = int(batter_data.loc[player][\"H\"])\n hit_totals.update({player:hit_count})", "_____no_output_____" ] ], [ [ "$BA_i \\sim Beta(81,219)$\n\n$y_i \\sim Bin(AB_i,BA_i)$\n\n$i=1,2,...,8$", "_____no_output_____" ] ], [ [ "#https://mc-stan.org/users/documentation/case-studies/rstan_workflow.html\n#https://people.duke.edu/~ccc14/sta-663/PyStan.html\n#http://varianceexplained.org/statistics/beta_distribution_and_baseball/\n\nmodel_code = '''\ndata {\n int<lower=0> N;\n int<lower=0> at_bats[N];\n int<lower=0> hits[N];\n real<lower=0> A;\n real<lower=0> B;\n}\nparameters {\n real<lower=0,upper=1> AVG[N];\n}\nmodel {\n AVG ~ beta(A, B);\n hits ~ binomial(at_bats, AVG);\n}\ngenerated quantities {\n vector[N] log_lik;\n vector[N] predicted_hits;\n for (i in 1:N) {\n log_lik[i] = binomial_lpmf(hits[i] | at_bats[i], AVG[i]);\n predicted_hits[i] = binomial_rng(at_bats[i], AVG[i]);\n }\n}\n'''\n\nmodel_data = dict(N=8, hits=list(hit_totals.values()),at_bats=list(at_bat_totals.values()),A=81,B=219)\nstan_model = pystan.StanModel(model_code=model_code)\nfit = stan_model.sampling(data=model_data)\n", "INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_4d40fdfa42b9a644c6433b2a714e9368 NOW.\n" ], [ "print(fit)", "Inference for Stan model: anon_model_4d40fdfa42b9a644c6433b2a714e9368.\n4 chains, each with iter=2000; warmup=1000; thin=1; \npost-warmup draws per chain=1000, total post-warmup draws=4000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\nAVG[1] 0.26 1.7e-4 0.01 0.24 0.25 0.26 0.27 0.29 7260 1.0\nAVG[2] 0.29 2.2e-4 0.02 0.26 0.28 0.29 0.3 0.33 6842 1.0\nAVG[3] 0.3 2.2e-4 0.02 0.26 0.28 0.29 0.31 0.33 6528 1.0\nAVG[4] 0.29 2.1e-4 0.02 0.25 0.27 0.29 0.3 0.32 7373 1.0\nAVG[5] 0.27 2.1e-4 0.02 0.24 0.26 0.27 0.28 0.3 5894 1.0\nAVG[6] 0.27 2.0e-4 0.02 0.24 0.26 0.27 0.28 0.31 6362 1.0\nAVG[7] 0.27 2.7e-4 0.02 0.23 0.25 0.27 0.28 0.31 5854 1.0\nAVG[8] 0.25 2.1e-4 0.02 0.22 0.24 0.25 0.26 0.28 6435 1.0\nlog_lik[1] -3.64 0.01 0.49 -5.01 -3.74 -3.45 -3.33 -3.29 1873 1.0\nlog_lik[2] -3.62 0.01 0.7 -5.54 -3.9 -3.38 -3.12 -3.03 3387 1.0\nlog_lik[3] -3.71 0.01 0.73 -5.63 -4.01 -3.47 -3.18 -3.06 4215 1.0\nlog_lik[4] -3.48 0.01 0.58 -5.12 -3.67 -3.26 -3.07 -3.02 2921 1.0\nlog_lik[5] -3.49 0.01 0.44 -4.69 -3.58 -3.33 -3.21 -3.18 1371 1.0\nlog_lik[6] -3.42 9.4e-3 0.39 -4.54 -3.52 -3.27 -3.17 -3.14 1673 1.0\nlog_lik[7] -2.64 5.1e-3 0.22 -3.24 -2.7 -2.56 -2.5 -2.49 1877 1.0\nlog_lik[8] -3.6 0.01 0.73 -5.56 -3.88 -3.36 -3.06 -2.95 3949 1.0\npredicted_hits[1] 157.05 0.2 13.74 131.0 148.0 157.0 166.0 184.0 4592 1.0\npredicted_hits[2] 91.42 0.14 10.18 72.0 84.0 91.0 98.0 111.0 4960 1.0\npredicted_hits[3] 98.44 0.15 10.08 79.0 92.0 98.0 105.0 119.0 4683 1.0\npredicted_hits[4] 90.08 0.15 9.96 71.0 83.0 90.0 97.0 110.0 4394 1.0\npredicted_hits[5] 125.81 0.18 12.17 103.0 118.0 125.0 134.0 151.0 4739 1.0\npredicted_hits[6] 115.5 0.18 11.65 93.0 108.0 115.0 123.0 139.0 4335 1.0\npredicted_hits[7] 32.09 0.08 5.42 22.0 28.0 32.0 36.0 43.0 4109 1.0\npredicted_hits[8] 81.14 0.14 9.27 64.0 75.0 81.0 87.0 100.0 4561 1.0\nlp__ -3107 0.05 1.95 -3111 -3108 -3107 -3105 -3104 1748 1.0\n\nSamples were drawn using NUTS at Thu Nov 21 20:41:52 2019.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "prior_model_code = '''\ndata {\n int<lower=0> N;\n real<lower=0> A;\n real<lower=0> B;\n}\n\nparameters {\n real<lower=0,upper=1> AVG[N];\n}\n\nmodel {\n AVG ~ beta(A, B);\n }\n'''\n\nprior_model_data = dict(N=8,A=81,B=219)\nstan_model_prior = pystan.StanModel(model_code=prior_model_code)\nprior_fit = stan_model_prior.sampling(data=prior_model_data)", "INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_390c11193c42041ad1d6bfb9bf37ebfd NOW.\n" ], [ "stan_data = az.from_pystan(posterior=fit,\n prior=prior_fit,\n observed_data=\"hits\",\n posterior_predictive=\"predicted_hits\",\n log_likelihood=\"log_lik\",\n posterior_model=stan_model,\n coords={\"player\":list(hit_totals.keys())},\n dims={'AVG': ['player'], 'hits': ['player'], 'log_lik': ['player'], 'predicted_hits': ['player']})", "_____no_output_____" ], [ "density_plots = az.plot_density([stan_data.posterior,stan_data.prior],data_labels=[\"Posterior\",\"Prior\"])", "_____no_output_____" ], [ "az.plot_ppc(stan_data, data_pairs = {\"hits\" : \"predicted_hits\"},flatten=[\"player\"])", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d038e7f3242cea980d0b0a65b4bb7491f14d557c
1,077
ipynb
Jupyter Notebook
code_listings/03.00-Introduction-to-Pandas.ipynb
cesar-rocha/PythonDataScienceHandbook
96c7f75d49b26a35bf76307bca86533061731859
[ "MIT" ]
1
2021-06-02T19:42:47.000Z
2021-06-02T19:42:47.000Z
code_listings/03.00-Introduction-to-Pandas.ipynb
matt-staton/PythonDataScienceHandbook
96c7f75d49b26a35bf76307bca86533061731859
[ "MIT" ]
null
null
null
code_listings/03.00-Introduction-to-Pandas.ipynb
matt-staton/PythonDataScienceHandbook
96c7f75d49b26a35bf76307bca86533061731859
[ "MIT" ]
1
2019-06-14T13:38:46.000Z
2019-06-14T13:38:46.000Z
16.074627
36
0.491179
[ [ [ "# Introduction to Pandas", "_____no_output_____" ] ], [ [ "import pandas\npandas.__version__", "_____no_output_____" ], [ "import pandas as pd", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
d038e835e82bc81e66fa281aada602e677f2e28b
555,230
ipynb
Jupyter Notebook
example_notebooks/sub_daily_data_yosemite_temps.ipynb
aws-kh/neural_prophet
71f4a2ae93550873c96e01c71175dd01a0184e96
[ "MIT" ]
3
2021-12-14T19:47:38.000Z
2022-01-13T14:50:13.000Z
example_notebooks/sub_daily_data_yosemite_temps.ipynb
aws-kh/neural_prophet
71f4a2ae93550873c96e01c71175dd01a0184e96
[ "MIT" ]
null
null
null
example_notebooks/sub_daily_data_yosemite_temps.ipynb
aws-kh/neural_prophet
71f4a2ae93550873c96e01c71175dd01a0184e96
[ "MIT" ]
1
2021-09-25T10:59:02.000Z
2021-09-25T10:59:02.000Z
2,303.858921
221,952
0.962275
[ [ [ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ourownstory/neural_prophet/blob/master/example_notebooks/sub_daily_data_yosemite_temps.ipynb)", "_____no_output_____" ], [ "# Sub-daily data\nNeuralProphet can make forecasts for time series with sub-daily observations by passing in a dataframe with timestamps in the ds column. The format of the timestamps should be `YYYY-MM-DD HH:MM:SS` - see the example csv [here](https://github.com/ourownstory/neural_prophet/blob/master/example_data/yosemite_temps.csv). When sub-daily data are used, daily seasonality will automatically be fit. \n\nHere we fit NeuralProphet to data with 5-minute resolution (daily temperatures at Yosemite). ", "_____no_output_____" ] ], [ [ "if 'google.colab' in str(get_ipython()):\n !pip install git+https://github.com/ourownstory/neural_prophet.git # may take a while\n #!pip install neuralprophet # much faster, but may not have the latest upgrades/bugfixes\n data_location = \"https://raw.githubusercontent.com/ourownstory/neural_prophet/master/\"\nelse:\n data_location = \"../\"", "_____no_output_____" ], [ "import pandas as pd\nfrom neuralprophet import NeuralProphet, set_log_level\n# set_log_level(\"ERROR\")\ndf = pd.read_csv(data_location + \"example_data/yosemite_temps.csv\")", "_____no_output_____" ] ], [ [ "Now we will attempt to forecast the next 7 days. The `5min` data resulution means that we have `60/5*24=288` daily values. Thus, we want to forecast `7*288` periods ahead.\n\nUsing some common sense, we set:\n* First, we disable weekly seasonality, as nature does not follow the human week's calendar.\n* Second, we disable changepoints, as the dataset only contains two months of data", "_____no_output_____" ] ], [ [ "m = NeuralProphet(\n n_changepoints=0,\n weekly_seasonality=False,\n)\nmetrics = m.fit(df, freq='5min')\nfuture = m.make_future_dataframe(df, periods=7*288, n_historic_predictions=len(df))\nforecast = m.predict(future)\nfig = m.plot(forecast)\n# fig_comp = m.plot_components(forecast)\nfig_param = m.plot_parameters()", "INFO - (NP.forecaster._handle_missing_data) - 12 NaN values in column y were auto-imputed.\nINFO - (NP.utils.set_auto_seasonalities) - Disabling yearly seasonality. Run NeuralProphet with yearly_seasonality=True to override this.\nINFO - (NP.config.set_auto_batch_epoch) - Auto-set batch_size to 128\nINFO - (NP.config.set_auto_batch_epoch) - Auto-set epochs to 6\n" ] ], [ [ "The daily seasonality seems to make sense, when we account for the time being recorded in GMT, while Yosemite local time is GMT-8.\n\n## Improving trend and seasonality \nAs we have `288` daily values recorded, we can increase the flexibility of `daily_seasonality`, without danger of overfitting. \n\nFurther, we may want to re-visit our decision to disable changepoints, as the data clearly shows changes in trend, as is typical with the weather. We make the following changes:\n* increase the `changepoints_range`, as the we are doing a short-term prediction\n* inrease the `n_changepoints` to allow to fit to the sudden changes in trend\n* carefully regularize the trend changepoints by setting `trend_reg` in order to avoid overfitting", "_____no_output_____" ] ], [ [ "m = NeuralProphet(\n changepoints_range=0.95,\n n_changepoints=50,\n trend_reg=1.5,\n weekly_seasonality=False,\n daily_seasonality=10,\n)\nmetrics = m.fit(df, freq='5min')\nfuture = m.make_future_dataframe(df, periods=60//5*24*7, n_historic_predictions=len(df))\nforecast = m.predict(future)\nfig = m.plot(forecast)\n# fig_comp = m.plot_components(forecast)\nfig_param = m.plot_parameters()", "INFO - (NP.config.__post_init__) - Note: Trend changepoint regularization is experimental.\nINFO - (NP.forecaster._handle_missing_data) - 12 NaN values in column y were auto-imputed.\nINFO - (NP.utils.set_auto_seasonalities) - Disabling yearly seasonality. Run NeuralProphet with yearly_seasonality=True to override this.\nINFO - (NP.config.set_auto_batch_epoch) - Auto-set batch_size to 128\nINFO - (NP.config.set_auto_batch_epoch) - Auto-set epochs to 6\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d038eb49b0ee83c2bb0acc3b2fc673f2e9f16dc6
49,649
ipynb
Jupyter Notebook
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
9bc88454e73885fe7290fed5894d0e1311349a4c
[ "MIT" ]
null
null
null
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
9bc88454e73885fe7290fed5894d0e1311349a4c
[ "MIT" ]
null
null
null
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
9bc88454e73885fe7290fed5894d0e1311349a4c
[ "MIT" ]
null
null
null
222.641256
43,268
0.915023
[ [ [ "# Deep Deterministic Policy Gradients (DDPG)\n---\nIn this notebook, we train DDPG with OpenAI Gym's Pendulum-v0 environment.\n\n### 1. Import the Necessary Packages", "_____no_output_____" ] ], [ [ "import gym\nimport random\nimport torch\nimport numpy as np\nfrom collections import deque\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom ddpg_agent import Agent", "_____no_output_____" ] ], [ [ "### 2. Instantiate the Environment and Agent", "_____no_output_____" ] ], [ [ "env = gym.make('Pendulum-v0')\nenv.seed(2)\nagent = Agent(state_size=3, action_size=1, random_seed=2)", "_____no_output_____" ] ], [ [ "\nObservation\nType: Box(3)\n\n|Num \t|Observation \t|Min| \tMax|\n| --- | --- | --- |--- |\n0 |\tcos(theta) \t| -1.0 \t|1.0|\n1 |\tsin(theta) \t|-1.0 \t|1.0|\n2 |\ttheta dot \t|-8.0 \t|8.0|\n\nActions\nType: Box(1)\n\n| Num \t| Action | \tMin \t| Max| \n| --- | --- | --- |--- |\n| 0 \t| Joint effort \t| -2.0 \t| 2.0| ", "_____no_output_____" ], [ "### 3. Train the Agent with DDPG", "_____no_output_____" ] ], [ [ "def ddpg(n_episodes=100, max_t=300, print_every=100):\n scores_deque = deque(maxlen=print_every)\n scores = []\n for i_episode in range(1, n_episodes+1):\n state = env.reset()\n agent.reset()\n score = 0\n for t in range(max_t):\n action = agent.act(state)\n next_state, reward, done, _ = env.step(action)\n agent.step(state, action, reward, next_state, done)\n state = next_state\n score += reward\n if done:\n break \n scores_deque.append(score)\n scores.append(score)\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)), end=\"\")\n torch.save(agent.actor_local.state_dict(), 'checkpoint_actor.pth')\n torch.save(agent.critic_local.state_dict(), 'checkpoint_critic.pth')\n if i_episode % print_every == 0:\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n \n return scores\n\nscores = ddpg()\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(np.arange(1, len(scores)+1), scores)\nplt.ylabel('Score')\nplt.xlabel('Episode #')\nplt.show()", "Episode 100\tAverage Score: -595.74\n" ] ], [ [ "### 4. Watch a Smart Agent!", "_____no_output_____" ] ], [ [ "agent.actor_local.load_state_dict(torch.load('checkpoint_actor.pth'))\nagent.critic_local.load_state_dict(torch.load('checkpoint_critic.pth'))\n\nstate = env.reset()\nfor t in range(500):\n action = agent.act(state, add_noise=False)\n env.render()\n state, reward, done, _ = env.step(action)\n if done:\n break \n\nenv.close()", "_____no_output_____" ] ], [ [ "### 6. Explore\n\nIn this exercise, we have provided a sample DDPG agent and demonstrated how to use it to solve an OpenAI Gym environment. To continue your learning, you are encouraged to complete any (or all!) of the following tasks:\n- Amend the various hyperparameters and network architecture to see if you can get your agent to solve the environment faster than this benchmark implementation. Once you build intuition for the hyperparameters that work well with this environment, try solving a different OpenAI Gym task!\n- Write your own DDPG implementation. Use this code as reference only when needed -- try as much as you can to write your own algorithm from scratch.\n- You may also like to implement prioritized experience replay, to see if it speeds learning. \n- The current implementation adds Ornsetein-Uhlenbeck noise to the action space. However, it has [been shown](https://blog.openai.com/better-exploration-with-parameter-noise/) that adding noise to the parameters of the neural network policy can improve performance. Make this change to the code, to verify it for yourself!\n- Write a blog post explaining the intuition behind the DDPG algorithm and demonstrating how to use it to solve an RL environment of your choosing. ", "_____no_output_____" ] ], [ [ "int(1e5)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d038f12b5641a6fac6455095c03777f6d72a660d
2,123
ipynb
Jupyter Notebook
nglview/tests/notebooks/test_color_by.ipynb
i386uk/nglview
39e207e474ef85feb0e4928d02d2d68428435b15
[ "MIT" ]
null
null
null
nglview/tests/notebooks/test_color_by.ipynb
i386uk/nglview
39e207e474ef85feb0e4928d02d2d68428435b15
[ "MIT" ]
null
null
null
nglview/tests/notebooks/test_color_by.ipynb
i386uk/nglview
39e207e474ef85feb0e4928d02d2d68428435b15
[ "MIT" ]
1
2021-11-19T02:03:46.000Z
2021-11-19T02:03:46.000Z
16.330769
54
0.49788
[ [ [ "import nglview as nv\nfrom nglview.utils import get_colors_from_b64\n\nview = nv.demo()\nview", "_____no_output_____" ], [ "view.add_surface(opacity=0.4)", "_____no_output_____" ], [ "view.render_image()", "_____no_output_____" ], [ "c0 = get_colors_from_b64(view._image_data)", "_____no_output_____" ], [ "view.color_by('residueindex')", "_____no_output_____" ], [ "view.render_image()", "_____no_output_____" ], [ "c1 = get_colors_from_b64(view._image_data)", "_____no_output_____" ], [ "assert c0 != c1", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d038fb9a6205e7291114579c4a19caceb6f2632b
3,134
ipynb
Jupyter Notebook
Code/1.Basics/1.Data structures and Objects/5.dictionaries.ipynb
davidMartinVergues/PYTHON
dd39d3aabfc43b3cb09aadb2919e51d03364117d
[ "DOC" ]
null
null
null
Code/1.Basics/1.Data structures and Objects/5.dictionaries.ipynb
davidMartinVergues/PYTHON
dd39d3aabfc43b3cb09aadb2919e51d03364117d
[ "DOC" ]
null
null
null
Code/1.Basics/1.Data structures and Objects/5.dictionaries.ipynb
davidMartinVergues/PYTHON
dd39d3aabfc43b3cb09aadb2919e51d03364117d
[ "DOC" ]
null
null
null
22.710145
108
0.485003
[ [ [ "\nprices_lookup = {'apple':2.88, 'oranges':3.56, 'milk':6.12}\n\nprint('precio de las manzanas {:<10.5f} €'.format(prices_lookup['apple']))\n # precio de las manzanas 2.88000 €\n\nprices_lookup # {'apple': 2.88, 'oranges': 3.56, 'milk': 6.12}\n", "precio de las manzanas 2.88000 €\n" ], [ "d = {'numbers':123,'list':[1,2,3],'dict':{'nombre':'david','apellido':'martin'}}\n\nd['numbers'] # 123\nd['list'][0] #1\nprint('me llamo {} {} '.format(d['dict']['nombre'], d['dict']['apellido'])) # me llamo david martin \n", "123\n1\nme llamo david martin \n" ], [ "prices_lookup = {'apple':2.88, 'oranges':3.56, 'milk':6.12}\n\nprices_lookup['melon'] = 5.86\n\nprices_lookup['apple']= 3.30\n\nprices_lookup # {'apple': 3.3, 'oranges': 3.56, 'milk': 6.12, 'melon': 5.86}\n\ndel prices_lookup['melon']\n\nprices_lookup # {'apple': 3.3, 'oranges': 3.56, 'milk': 6.12}\n\nprices_lookup.keys() # dict_keys(['apple', 'oranges', 'milk'])\n\nprices_lookup.values() # dict_values([3.3, 3.56, 6.12])\n\nprices_lookup.items() # dict_items([('apple', 3.3), ('oranges', 3.56), ('milk', 6.12)])\n\n\n", "_____no_output_____" ], [ " d= {1:'david'}\n\n d", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
d038fe9cd5f84c880df52aaec101ba5257528899
54,668
ipynb
Jupyter Notebook
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
efe0881be047fc2b0518f80cf42c059280598187
[ "FSFAP" ]
35
2021-07-29T16:15:16.000Z
2022-03-20T16:14:38.000Z
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
efe0881be047fc2b0518f80cf42c059280598187
[ "FSFAP" ]
1
2021-05-05T19:54:15.000Z
2021-05-05T19:54:15.000Z
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
efe0881be047fc2b0518f80cf42c059280598187
[ "FSFAP" ]
40
2021-07-25T19:13:25.000Z
2022-03-25T17:55:42.000Z
48.208113
9,644
0.728964
[ [ [ "<center>\n <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n</center>\n\n# Classes and Objects in Python\n\nEstimated time needed: **40** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n- Work with classes and objects\n- Identify and define attributes and methods\n", "_____no_output_____" ], [ "<h2>Table of Contents</h2>\n<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n <ul>\n <li>\n <a href=\"#intro\">Introduction to Classes and Objects</a>\n <ul>\n <li><a href=\"create\">Creating a class</a></li>\n <li><a href=\"instance\">Instances of a Class: Objects and Attributes</a></li>\n <li><a href=\"method\">Methods</a></li>\n </ul>\n </li>\n <li><a href=\"creating\">Creating a class</a></li>\n <li><a href=\"circle\">Creating an instance of a class Circle</a></li>\n <li><a href=\"rect\">The Rectangle Class</a></li>\n </ul>\n \n</div>\n\n<hr>\n", "_____no_output_____" ], [ "<h2 id=\"intro\">Introduction to Classes and Objects</h2>\n", "_____no_output_____" ], [ "<h3>Creating a Class</h3>\n", "_____no_output_____" ], [ "The first part of creating a class is giving it a name: In this notebook, we will create two classes, Circle and Rectangle. We need to determine all the data that make up that class, and we call that an attribute. Think about this step as creating a blue print that we will use to create objects. In figure 1 we see two classes, circle and rectangle. Each has their attributes, they are variables. The class circle has the attribute radius and color, while the rectangle has the attribute height and width. Let’s use the visual examples of these shapes before we get to the code, as this will help you get accustomed to the vocabulary.\n", "_____no_output_____" ], [ "<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/ClassesClass.png\" width=\"500\" />\n", "_____no_output_____" ], [ "<i>Figure 1: Classes circle and rectangle, and each has their own attributes. The class circle has the attribute radius and colour, the rectangle has the attribute height and width.</i>\n", "_____no_output_____" ], [ "<h3 id=\"instance\">Instances of a Class: Objects and Attributes</h3>\n", "_____no_output_____" ], [ "An instance of an object is the realisation of a class, and in Figure 2 we see three instances of the class circle. We give each object a name: red circle, yellow circle and green circle. Each object has different attributes, so let's focus on the attribute of colour for each object.\n", "_____no_output_____" ], [ "<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/ClassesObj.png\" width=\"500\" />\n", "_____no_output_____" ], [ "<i>Figure 2: Three instances of the class circle or three objects of type circle.</i>\n", "_____no_output_____" ], [ " The colour attribute for the red circle is the colour red, for the green circle object the colour attribute is green, and for the yellow circle the colour attribute is yellow. \n", "_____no_output_____" ], [ "<h3 id=\"method\">Methods</h3>\n", "_____no_output_____" ], [ "Methods give you a way to change or interact with the object; they are functions that interact with objects. For example, let’s say we would like to increase the radius by a specified amount of a circle. We can create a method called **add_radius(r)** that increases the radius by **r**. This is shown in figure 3, where after applying the method to the \"orange circle object\", the radius of the object increases accordingly. The “dot” notation means to apply the method to the object, which is essentially applying a function to the information in the object.\n", "_____no_output_____" ], [ "<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/ClassesMethod.png\" width=\"500\" /> \n", "_____no_output_____" ], [ "<i>Figure 3: Applying the method “add_radius” to the object orange circle object.</i>\n", "_____no_output_____" ], [ "<hr>\n", "_____no_output_____" ], [ "<h2 id=\"creating\">Creating a Class</h2>\n", "_____no_output_____" ], [ "Now we are going to create a class circle, but first, we are going to import a library to draw the objects: \n", "_____no_output_____" ] ], [ [ "# Import the library\n\nimport matplotlib.pyplot as plt\n%matplotlib inline ", "_____no_output_____" ] ], [ [ " The first step in creating your own class is to use the <code>class</code> keyword, then the name of the class as shown in Figure 4. In this course the class parent will always be object: \n", "_____no_output_____" ], [ "<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/ClassesDefine.png\" width=\"400\" />\n", "_____no_output_____" ], [ "<i>Figure 4: Creating a class Circle.</i>\n", "_____no_output_____" ], [ "The next step is a special method called a constructor <code>__init__</code>, which is used to initialize the object. The input are data attributes. The term <code>self</code> contains all the attributes in the set. For example the <code>self.color</code> gives the value of the attribute color and <code>self.radius</code> will give you the radius of the object. We also have the method <code>add_radius()</code> with the parameter <code>r</code>, the method adds the value of <code>r</code> to the attribute radius. To access the radius we use the syntax <code>self.radius</code>. The labeled syntax is summarized in Figure 5:\n", "_____no_output_____" ], [ "<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/ClassesCircle.png\" width=\"600\" />\n", "_____no_output_____" ], [ "<i>Figure 5: Labeled syntax of the object circle.</i>\n", "_____no_output_____" ], [ "The actual object is shown below. We include the method <code>drawCircle</code> to display the image of a circle. We set the default radius to 3 and the default colour to blue:\n", "_____no_output_____" ] ], [ [ "# Create a class Circle\n\nclass Circle(object):\n \n # Constructor\n def __init__(self, radius=3, color='blue'):\n self.radius = radius\n self.color = color \n \n # Method\n def add_radius(self, r):\n self.radius = self.radius + r\n return(self.radius)\n \n # Method\n def drawCircle(self):\n plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))\n plt.axis('scaled')\n plt.show() ", "_____no_output_____" ] ], [ [ "<hr>\n", "_____no_output_____" ], [ "<h2 id=\"circle\">Creating an instance of a class Circle</h2>\n", "_____no_output_____" ], [ "Let’s create the object <code>RedCircle</code> of type Circle to do the following:\n", "_____no_output_____" ] ], [ [ "# Create an object RedCircle\n\nRedCircle = Circle(10, 'red')", "_____no_output_____" ] ], [ [ "We can use the <code>dir</code> command to get a list of the object's methods. Many of them are default Python methods.\n", "_____no_output_____" ] ], [ [ "# Find out the methods can be used on the object RedCircle\n\ndir(RedCircle)", "_____no_output_____" ] ], [ [ "We can look at the data attributes of the object: \n", "_____no_output_____" ] ], [ [ "# Print the object attribute radius\n\nRedCircle.radius", "_____no_output_____" ], [ "# Print the object attribute color\n\nRedCircle.color", "_____no_output_____" ] ], [ [ " We can change the object's data attributes: \n", "_____no_output_____" ] ], [ [ "# Set the object attribute radius\n\nRedCircle.radius = 1\nRedCircle.radius", "_____no_output_____" ] ], [ [ " We can draw the object by using the method <code>drawCircle()</code>:\n", "_____no_output_____" ] ], [ [ "# Call the method drawCircle\n\nRedCircle.drawCircle()", "_____no_output_____" ] ], [ [ "We can increase the radius of the circle by applying the method <code>add_radius()</code>. Let increases the radius by 2 and then by 5: \n", "_____no_output_____" ] ], [ [ "# Use method to change the object attribute radius\n\nprint('Radius of object:',RedCircle.radius)\nRedCircle.add_radius(2)\nprint('Radius of object of after applying the method add_radius(2):',RedCircle.radius)\nRedCircle.add_radius(5)\nprint('Radius of object of after applying the method add_radius(5):',RedCircle.radius)\nRedCircle.add_radius(6)\nprint('Radius of object of after applying the method add radius(6):',RedCircle.radius)", "Radius of object: 1\nRadius of object of after applying the method add_radius(2): 3\nRadius of object of after applying the method add_radius(5): 8\nRadius of object of after applying the method add radius(6): 14\n" ] ], [ [ " Let’s create a blue circle. As the default colour is blue, all we have to do is specify what the radius is:\n", "_____no_output_____" ] ], [ [ "# Create a blue circle with a given radius\n\nBlueCircle = Circle(radius=100)", "_____no_output_____" ] ], [ [ " As before we can access the attributes of the instance of the class by using the dot notation:\n", "_____no_output_____" ] ], [ [ "# Print the object attribute radius\n\nBlueCircle.radius", "_____no_output_____" ], [ "# Print the object attribute color\n\nBlueCircle.color", "_____no_output_____" ] ], [ [ " We can draw the object by using the method <code>drawCircle()</code>:\n", "_____no_output_____" ] ], [ [ "# Call the method drawCircle\n\nBlueCircle.drawCircle()", "_____no_output_____" ] ], [ [ "Compare the x and y axis of the figure to the figure for <code>RedCircle</code>; they are different.\n", "_____no_output_____" ], [ "<hr>\n", "_____no_output_____" ], [ "<h2 id=\"rect\">The Rectangle Class</h2>\n", "_____no_output_____" ], [ "Let's create a class rectangle with the attributes of height, width and color. We will only add the method to draw the rectangle object:\n", "_____no_output_____" ] ], [ [ "# Create a new Rectangle class for creating a rectangle object\n\nclass Rectangle(object):\n \n # Constructor\n def __init__(self, width=2, height=3, color='r'):\n self.height = height \n self.width = width\n self.color = color\n \n # Method\n def drawRectangle(self):\n plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height ,fc=self.color))\n plt.axis('scaled')\n plt.show()\n ", "_____no_output_____" ] ], [ [ "Let’s create the object <code>SkinnyBlueRectangle</code> of type Rectangle. Its width will be 2 and height will be 3, and the color will be blue:\n", "_____no_output_____" ] ], [ [ "# Create a new object rectangle\n\nSkinnyBlueRectangle = Rectangle(2, 10, 'blue')", "_____no_output_____" ] ], [ [ " As before we can access the attributes of the instance of the class by using the dot notation:\n", "_____no_output_____" ] ], [ [ "# Print the object attribute height\n\nSkinnyBlueRectangle.height ", "_____no_output_____" ], [ "# Print the object attribute width\n\nSkinnyBlueRectangle.width", "_____no_output_____" ], [ "# Print the object attribute color\n\nSkinnyBlueRectangle.color", "_____no_output_____" ] ], [ [ " We can draw the object:\n", "_____no_output_____" ] ], [ [ "# Use the drawRectangle method to draw the shape\n\nSkinnyBlueRectangle.drawRectangle()", "_____no_output_____" ] ], [ [ "Let’s create the object <code>FatYellowRectangle</code> of type Rectangle :\n", "_____no_output_____" ] ], [ [ "# Create a new object rectangle\n\nFatYellowRectangle = Rectangle(20, 5, 'yellow')", "_____no_output_____" ] ], [ [ " We can access the attributes of the instance of the class by using the dot notation:\n", "_____no_output_____" ] ], [ [ "# Print the object attribute height\n\nFatYellowRectangle.height ", "_____no_output_____" ], [ "# Print the object attribute width\n\nFatYellowRectangle.width", "_____no_output_____" ], [ "# Print the object attribute color\n\nFatYellowRectangle.color", "_____no_output_____" ] ], [ [ " We can draw the object:\n", "_____no_output_____" ] ], [ [ "# Use the drawRectangle method to draw the shape\n\nFatYellowRectangle.drawRectangle()", "_____no_output_____" ] ], [ [ "<hr>\n", "_____no_output_____" ], [ "<h2 id=\"rect\">Exercises</h2>\n", "_____no_output_____" ], [ "<h4> Text Analysis </h4>\n", "_____no_output_____" ], [ "You have been recruited by your friend, a linguistics enthusiast, to create a utility tool that can perform analysis on a given piece of text. Complete the class\n'analysedText' with the following methods -\n\n<ul>\n <li> Constructor - Takes argument 'text',makes it lower case and removes all punctuation. Assume only the following punctuation is used - period (.), exclamation mark (!), comma (,) and question mark (?). Store the argument in \"fmtText\" \n <li> freqAll - returns a dictionary of all unique words in the text along with the number of their occurences.\n <li> freqOf - returns the frequency of the word passed in argument.\n</ul>\n The skeleton code has been given to you. Docstrings can be ignored for the purpose of the exercise. <br>\n <i> Hint: Some useful functions are <code>replace()</code>, <code>lower()</code>, <code>split()</code>, <code>count()</code> </i><br>\n", "_____no_output_____" ] ], [ [ "class analysedText(object):\n \n def __init__ (self, text):\n \n reArrText = text.lower()\n \n reArrText = reArrText.replace('.','').replace('!','').replace(',','').replace('?','')\n \n self.fmtText = reArrText\n \n def freqAll(self): \n \n wordList = self.fmtText.split(' ')\n \n \n freqMap = {}\n for word in set(wordList): # use set to remove duplicates in list\n freqMap[word] = wordList.count(word)\n \n return freqMap\n \n def freqOf(self,word):\n \n freqDict = self.freqAll()\n \n if word in freqDict:\n return freqDict[word]\n else:\n return 0\n", "_____no_output_____" ] ], [ [ "Execute the block below to check your progress.\n", "_____no_output_____" ] ], [ [ "import sys\n\nsampleMap = {'eirmod': 1,'sed': 1, 'amet': 2, 'diam': 5, 'consetetur': 1, 'labore': 1, 'tempor': 1, 'dolor': 1, 'magna': 2, 'et': 3, 'nonumy': 1, 'ipsum': 1, 'lorem': 2}\n\ndef testMsg(passed):\n if passed:\n return 'Test Passed'\n else :\n return 'Test Failed'\n\nprint(\"Constructor: \")\ntry:\n samplePassage = analysedText(\"Lorem ipsum dolor! diam amet, consetetur Lorem magna. sed diam nonumy eirmod tempor. diam et labore? et diam magna. et diam amet.\")\n print(testMsg(samplePassage.fmtText == \"lorem ipsum dolor diam amet consetetur lorem magna sed diam nonumy eirmod tempor diam et labore et diam magna et diam amet\"))\nexcept:\n print(\"Error detected. Recheck your function \" )\nprint(\"freqAll: \",)\ntry:\n wordMap = samplePassage.freqAll()\n print(testMsg(wordMap==sampleMap))\nexcept:\n print(\"Error detected. Recheck your function \" )\nprint(\"freqOf: \")\ntry:\n passed = True\n for word in sampleMap:\n if samplePassage.freqOf(word) != sampleMap[word]:\n passed = False\n break\n print(testMsg(passed))\n \nexcept:\n print(\"Error detected. Recheck your function \" )\n ", "Constructor: \nTest Passed\nfreqAll: \nTest Passed\nfreqOf: \nTest Passed\n" ] ], [ [ "<details><summary>Click here for the solution</summary>\n\n```python\nclass analysedText(object):\n \n def __init__ (self, text):\n # remove punctuation\n formattedText = text.replace('.','').replace('!','').replace('?','').replace(',','')\n \n # make text lowercase\n formattedText = formattedText.lower()\n \n self.fmtText = formattedText\n \n def freqAll(self): \n # split text into words\n wordList = self.fmtText.split(' ')\n \n # Create dictionary\n freqMap = {}\n for word in set(wordList): # use set to remove duplicates in list\n freqMap[word] = wordList.count(word)\n \n return freqMap\n \n def freqOf(self,word):\n # get frequency map\n freqDict = self.freqAll()\n \n if word in freqDict:\n return freqDict[word]\n else:\n return 0\n \n```\n\n</details>\n \n", "_____no_output_____" ], [ "<hr>\n<h2>The last exercise!</h2>\n<p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href=\"https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/\" target=\"_blank\">this article</a> to learn how to share your work.\n<hr>\n", "_____no_output_____" ], [ "## Author\n\n<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n\n## Other contributors\n\n<a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ---------- | ---------------------------------- |\n| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n| | | | |\n| | | | |\n\n<hr/>\n\n## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "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" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
d038ff388c0c2295354209826f30c5e359ce9f17
986,894
ipynb
Jupyter Notebook
LSTM1.ipynb
CSCI4850/S19-team3-project
688555727fd6467f00b26a2d9d6ea87d5f2484e8
[ "MIT" ]
null
null
null
LSTM1.ipynb
CSCI4850/S19-team3-project
688555727fd6467f00b26a2d9d6ea87d5f2484e8
[ "MIT" ]
null
null
null
LSTM1.ipynb
CSCI4850/S19-team3-project
688555727fd6467f00b26a2d9d6ea87d5f2484e8
[ "MIT" ]
1
2019-03-18T15:21:06.000Z
2019-03-18T15:21:06.000Z
403.802782
24,296
0.940518
[ [ [ "# Analyzing the Effects of Non-Academic Features on Student Performance", "_____no_output_____" ] ], [ [ "# For reading data sets\nimport pandas\n# For lots of awesome things\nimport numpy as np\n# Need this for LabelEncoder\nfrom sklearn import preprocessing\n# For building our net\nimport keras\n# For plotting\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Read in data", "_____no_output_____" ], [ "### Data is seperated by a semicolon (delimiter=\";\") containing column names as the first row of the file (header = 0).", "_____no_output_____" ] ], [ [ "# Read in student data\nstudent_data = np.array(pandas.read_table(\"./student-por.csv\",\ndelimiter=\";\", header=0))\n\n# Display student data\nstudent_data", "_____no_output_____" ] ], [ [ "### Determine what the column labels are...", "_____no_output_____" ] ], [ [ "# Descriptions for each feature (found in the header)\nfeature_descrips = np.array(pandas.read_csv(\"./student-por.csv\",\ndelimiter=\";\", header=None, nrows=1))\n\n# Display descriptions\nprint(feature_descrips)", "[['school' 'sex' 'age' 'address' 'famsize' 'Pstatus' 'Medu' 'Fedu' 'Mjob'\n 'Fjob' 'reason' 'guardian' 'traveltime' 'studytime' 'failures'\n 'schoolsup' 'famsup' 'paid' 'activities' 'nursery' 'higher' 'internet'\n 'romantic' 'famrel' 'freetime' 'goout' 'Dalc' 'Walc' 'health'\n 'absences' 'G1' 'G2' 'G3']]\n" ] ], [ [ "### ...and give them clearer descriptions.", "_____no_output_____" ] ], [ [ "# More detailed descriptions\nfeature_descrips = np.array([\"School\", \"Sex\", \"Age\", \"Urban or Rural Address\", \"Family Size\", \n \"Parent's Cohabitation status\", \"Mother's Education\", \"Father's Education\",\n \"Mother's Job\", \"Father's Job\", \"Reason for Choosing School\", \n \"Student's Gaurdain\", \"Home to School Travel Time\", \"Weekly Study Time\",\n \"Number of Past Class Failures\", \"Extra Educational Support\", \n \"Family Educational Support\", \"Extra Paid Classes\", \"Extra Curricular Activities\",\n \"Attended Nursery School\", \"Wants to Take Higher Education\", \"Internet Access at Home\", \n \"In a Romantic Relationship\", \"Quality of Family Relationships\",\n \"Free Time After School\", \"Time Spent Going out With Friends\", \n \"Workday Alcohol Consumption\", \"Weekend Alcohol Consumption\", \n \"Current Health Status\", \"Number of Student Absences\", \"First Period Grade\",\n \"Second Period Grade\", \"Final Grade\"])", "_____no_output_____" ] ], [ [ "# Data Cleanup", "_____no_output_____" ], [ "## Shuffle data", "_____no_output_____" ], [ "### We sampled 2 schools, and right now our data has each school grouped together. We need to get rid of this grouping for training later down the road.", "_____no_output_____" ] ], [ [ "# Shuffle the data!\nnp.random.shuffle(student_data)\nstudent_data", "_____no_output_____" ] ], [ [ "## Alphabetically classify scores", "_____no_output_____" ], [ "### Because our data is sampled from Portugal, we have to modify their scoring system a bit to represent something more like ours.\n### 0 = F\n### 1 = D\n### 2 = C\n### 3 = B\n### 4 = A", "_____no_output_____" ] ], [ [ "# Array holding final scores for every student\nscores = student_data[:,32]\n\n# Iterate through list of scores, changing them from a 0-19 value\n## to a 0-4 value (representing F-A)\nfor i in range(len(scores)):\n if(scores[i] > 18):\n scores[i] = 4\n elif(scores[i] > 16):\n scores[i] = 3\n elif(scores[i] > 14):\n scores[i] = 2\n elif(scores[i] > 12):\n scores[i] = 1\n else:\n scores[i] = 0\n \n# Update the final scores in student_data to reflect these changes\nfor i in range(len(scores)):\n student_data[i,32] = scores[i]\n \n# Display new data. Hint: Look at the last column\nstudent_data", "_____no_output_____" ] ], [ [ "## Encoding non-numeric data to integers", "_____no_output_____" ] ], [ [ "# One student sample\nstudent_data[0,:]", "_____no_output_____" ] ], [ [ "### We have some qualitative data from the questionaire that needs to be converted to represent numbers.", "_____no_output_____" ] ], [ [ "# Label Encoder\nle = preprocessing.LabelEncoder()\n\n# Columns that hold non-numeric data\nindices = np.array([0,1,3,4,5,8,9,10,11,15,16,17,18,19,20,21,22])\n\n# Transform the non-numeric data in these columns to integers\nfor i in range(len(indices)):\n column = indices[i]\n le.fit(student_data[:,column])\n student_data[:,column] = le.transform(student_data[:,column])", "_____no_output_____" ], [ "student_data[0,:]", "_____no_output_____" ] ], [ [ "## Encoding 0's to -1 for binomial data.", "_____no_output_____" ], [ "### We want our weights to change because 0 represents something! Therefore, we need to encode 0's to -1's so the weights will change with that input.", "_____no_output_____" ] ], [ [ "# Columns that hold binomial data\nindices = np.array([0,1,3,4,5,15,16,17,18,19,20,21,22])\n\n# Change 0's to -1's\nfor i in range(len(indices)):\n column = indices[i]\n \n # values of current feature\n feature = student_data[:,column]\n \n # change values to -1 if equal to 0\n feature = np.where(feature==0, -1, feature)\n student_data[:,column] = feature\n \nstudent_data[0,:]", "_____no_output_____" ] ], [ [ "## Standardizing the nominal and numerical data.", "_____no_output_____" ], [ "### We need our input to matter equally (Everyone is important!). We do this by standardizing our data (get a mean of 0 and a stardard deviation of 1).", "_____no_output_____" ] ], [ [ "scaler = preprocessing.StandardScaler()", "_____no_output_____" ], [ "temp = student_data[:,[2,6,7,8,9,10,11,12,13,14,23,24,25,26,27,28,29,30,31]]\nprint(student_data[0,:])\nStandardized = scaler.fit_transform(temp)", "[-1 -1 16 1 -1 1 4 3 1 2 1 1 1 2 0 -1 1 -1 1 1 1 1 -1 4 3 5 1 5 2 2 14 14\n 2]\n" ], [ "print('Mean:', round(Standardized.mean()))\nprint('Standard deviation:', Standardized.std())", "Mean: -0.0\nStandard deviation: 1.0\n" ], [ "student_data[:,[2,6,7,8,9,10,11,12,13,14,23,24,25,26,27,28,29,30,31]] = Standardized", "_____no_output_____" ], [ "student_data[0,:]", "_____no_output_____" ] ], [ [ "## Convert results to one-hot encoding", "_____no_output_____" ] ], [ [ "# Final grades\nresults = student_data[:,32]\n\n# Take a look at first 5 final grades\nprint(\"First 5 final grades:\", results[0:5])\n\n# All unique values for final grades (0-4 representing F-A)\npossible_results = np.unique(student_data[:,32]).T\nprint(\"All possible results:\", possible_results)", "First 5 final grades: [2 3 0 1 1]\nAll possible results: [0 1 2 3 4]\n" ], [ "# One-hot encode final grades (results) which will be used as our output\n# The length of the \"ID\" should be as long as the total number of possible results so each results\n## gets its own, personal one-hot encoding\ny = keras.utils.to_categorical(results,len(possible_results))\n\n# Take a look at the first 5 final grades now (no longer numbers but arrays)\ny[0:5]", "_____no_output_____" ], [ "# our input, all features except final grades\nx = student_data[:,0:32]", "_____no_output_____" ] ], [ [ "# Model Building", "_____no_output_____" ], [ "#### Now let's create a function that will build a model for us. This will come in handy later on. Our model will have two hidden layers. The first hidden layer will have an input size of 800, and the second will have an input size of 400. The optimizer that we are using is adamax which is good at ignoring noise in a datset. The loss function we are using is called categorical cross entropy and which is useful for trying to classify or label something. In this case, we are trying to classify students by letter grades, so this loss function will be of great use to us.", "_____no_output_____" ] ], [ [ "# Function to create network given model\ndef create_network(model):\n # Specify input/output size\n input_size = x.shape[1]\n output_size = y.shape[1]\n\n # Create the hidden layer\n model.add(keras.layers.Dense(800, input_dim = input_size, activation = 'relu'))\n\n # Additional hidden layer\n model.add(keras.layers.Dense(400,activation='relu'))\n\n # Output layer\n model.add(keras.layers.Dense(output_size,activation='softmax'))\n\n # Compile - why using adamax?\n model.compile(loss='categorical_crossentropy',\n optimizer='adamax', \n metrics=['accuracy'])", "_____no_output_____" ], [ "# Feed-forward model\nmodel = keras.Sequential()\ncreate_network(model)", "_____no_output_____" ] ], [ [ "# Initial Test of the Network", "_____no_output_____" ] ], [ [ "# Split data into training and testing data\nx_train = x[0:518,:]\nx_test = x[519:649,:]\n\ny_train = y[0:518,:]\ny_test = y[519:649,:]", "_____no_output_____" ], [ "# Train on training data! \n# We're saving this information in the variable -history- so we can take a look at it later\nhistory = model.fit(x_train, y_train,\n batch_size = 32, \n epochs = 7, \n verbose = 0, \n validation_split = 0.2)", "_____no_output_____" ], [ "# Validate using data the network hasn't seen before (testing data)\n# Save this info in -score- so we can take a look at it\nscore = model.evaluate(x_test,y_test, verbose=0)\n\n# Check it's effectiveness\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])", "Test loss: 0.49870656898173576\nTest accuracy: 0.7692307692307693\n" ], [ "# Plot the data\ndef plot(history):\n\n plt.figure(1)\n\n # Summarize history for accuracy\n\n plt.subplot(211)\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train','test'], loc ='upper left')\n\n # Summarize history for loss\n\n plt.subplot(212)\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train','test'], loc ='upper left')\n\n # Display plot\n \n plt.tight_layout()\n plt.show()", "_____no_output_____" ], [ "# Plot current training and validation accuracy and loss\nplot(history)", "_____no_output_____" ] ], [ [ "# Training and Testing Without Individual Features", "_____no_output_____" ] ], [ [ "# Analyze the effects of removing one feature on training\ndef remove_and_analyze(feature):\n # Told you those feature descriptions would be useful\n print(\"Without feature\", feature, \":\", feature_descrips[feature])\n \n # Create feed-forward network\n model = keras.Sequential()\n create_network(model)\n \n # Remove feature from columns (axis 1)\n x = np.delete(student_data, feature, axis = 1)\n \n # Split data into training and testing data\n x_train = x[0:518,:]\n x_test = x[519:649,:]\n \n # Train on training data!\n history = model.fit(x_train, y_train,\n batch_size = 32, \n epochs = 7, \n verbose = 0, \n validation_split = 0.2)\n \n # Validate using data the network hasn't seen before (testing data)\n score = model.evaluate(x_test,y_test, verbose=0)\n \n # Check it's effectiveness\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])\n \n # Plot the data\n plot(history)", "_____no_output_____" ], [ "# Analyze the effects of removing one feature on training\n# Do this for all input features\nfor i in range(student_data.shape[1]-1):\n remove_and_analyze(i)\n print(\"\\n \\n \\n\")", "Without feature 0 : School\nTest loss: 0.1621086014179477\nTest accuracy: 0.9461538461538461\n" ] ], [ [ "# Training and Testing Without Five Features", "_____no_output_____" ] ], [ [ "# Delete the five features that most negatively impact accuracy\nx = np.delete(student_data, 21, axis = 1)\nx = np.delete(x, 20, axis = 1)\nx = np.delete(x, 9, axis = 1)\nx = np.delete(x, 8, axis = 1)\nx = np.delete(x, 7, axis = 1)\n\n# Create feed-forward network\nmodel = keras.Sequential()\ncreate_network(model)\n\n# Split data into training and testing data\nx_train = x[0:518,:]\nx_test = x[519:649,:]\n\n# Train on training data!\nhistory = model.fit(x_train, y_train,\n batch_size = 32, \n epochs = 7, \n verbose = 0, \n validation_split = 0.2)\n\n# Validate using data the network hasn't seen before (testing data)\nscore = model.evaluate(x_test,y_test, verbose=0)\n\n# Check it's effectiveness\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\n# Plot the data\nplot(history)", "Test loss: 0.1731401116976765\nTest accuracy: 0.9307692307692308\n" ] ], [ [ "# Grade Distribution Analysis", "_____no_output_____" ] ], [ [ "# Function for analyzing the percent of students with each grade [F,D,C,B,A]\ndef analyze(array):\n \n # To hold the total number of students with a certain final grade\n # Index 0 - F. Index 4 - A\n sums = np.array([0,0,0,0,0])\n \n # Iterate through array. Update sums according to whether a student got a final grade of a(n)\n for i in range(len(array)):\n # F\n if(array[i]==0):\n sums[0] += 1\n # D\n elif(array[i]==1):\n sums[1] +=1\n # C\n elif(array[i]==2):\n sums[2] +=1\n # B\n elif(array[i]==3):\n sums[3] +=1\n # A\n else:\n sums[4] += 1\n \n # Total number of students\n total = sums[0] + sums[1] + sums[2] + sums[3] + sums[4]\n \n # Hold percentage of students with grade of [F,D,C,B,A]\n percentages = np.array([sums[0]/total*100, \n sums[1]/total*100, \n sums[2]/total*100, \n sums[3]/total*100, \n sums[4]/total*100])\n \n # One bar for each of the 5 grades\n x = np.array([1,2,3,4,5])\n \n # Descriptions for each bar. None on y-axis\n plt.xticks(np.arange(6), ('', 'F', 'D', 'C', 'B','A'))\n \n # X axis - grades. Y axis - percentage of students with each grade\n plt.bar(x,percentages)\n plt.xlabel(\"Grades\")\n plt.ylabel(\"Percentage of Students\")\n \n # Display bar graph\n plt.show()\n \n # Display percentages\n print(percentages)", "_____no_output_____" ] ], [ [ "## Family Educational Support", "_____no_output_____" ] ], [ [ "# Array holding final grades of all students who have family educational support\nfam_sup = []\n# Array holding final grades of all students who have family educational support\nno_fam_sup = []\n\n# Iterate through all student samples\nfor i in range(student_data.shape[0]):\n \n # Does the student have family educational support? (-1 no, 1 yes)\n sup = student_data[i][16]\n \n # Append student's final grade to corresponding array\n if(sup==1):\n fam_sup.append(student_data[i][32])\n else:\n no_fam_sup.append(student_data[i][32])", "_____no_output_____" ] ], [ [ "### Family Educational Support", "_____no_output_____" ] ], [ [ "analyze(fam_sup)", "_____no_output_____" ] ], [ [ "### No Family Educational Support", "_____no_output_____" ] ], [ [ "analyze(no_fam_sup)", "_____no_output_____" ] ], [ [ "## Reason for choosing school", "_____no_output_____" ] ], [ [ "# Each array holds the grades of students who chose to go to their school for that reason\n# Close to home\nreason1 = []\n# School reputation\nreason2 = []\n# Course prefrence\nreason3 = []\n# Other\nreason4 = []\n\n# Values that represent these unique reasons. They are not integer numbers like in the previous\n## example. They're floatig point numbers so we'll save them so we can compare them to the value\n## of this feature in each sample\nunique_reasons = np.unique(student_data[:,10])\n\n# Iterate through all student samples and append final grades to corresponding arrays \nfor i in range(student_data.shape[0]):\n \n reason = student_data[i][10]\n \n if(reason==unique_reasons[0]):\n reason1.append(student_data[i][32])\n elif(reason==unique_reasons[1]):\n reason2.append(student_data[i][32])\n elif(reason==unique_reasons[2]):\n reason3.append(student_data[i][32])\n else:\n reason4.append(student_data[i][32])", "_____no_output_____" ] ], [ [ "### Reason 1: Close to Home", "_____no_output_____" ] ], [ [ "analyze(reason1)", "_____no_output_____" ] ], [ [ "### Reason 2: School Reputation", "_____no_output_____" ] ], [ [ "analyze(reason2)", "_____no_output_____" ] ], [ [ "### Reason 3: Course Prefrence", "_____no_output_____" ] ], [ [ "analyze(reason3)", "_____no_output_____" ] ], [ [ "### Reason 4: Other", "_____no_output_____" ] ], [ [ "analyze(reason4)", "_____no_output_____" ] ], [ [ "## Frequency of Going Out With Friends", "_____no_output_____" ] ], [ [ "# Each array holds the grades of students who go out with friends for that specified amount of time \n# (1 - very low, 5 - very high)\ngo_out1 = []\ngo_out2 = []\ngo_out3 = []\ngo_out4 = []\ngo_out5 = []\n\n# Floating point values representing frequency\nunique = np.unique(student_data[:,25])\n\n# Iterate through all student samples and append final grades to corresponding arrays \nfor i in range(student_data.shape[0]):\n \n frequency = student_data[i][25]\n \n if(frequency==unique[0]):\n go_out1.append(student_data[i][32])\n elif(frequency==unique[1]):\n go_out2.append(student_data[i][32])\n elif(frequency==unique[2]):\n go_out3.append(student_data[i][32])\n elif(frequency==unique[3]):\n go_out4.append(student_data[i][32])\n else:\n go_out5.append(student_data[i][32])", "_____no_output_____" ], [ "analyze(go_out1)\nanalyze(go_out2)\nanalyze(go_out3)\nanalyze(go_out4)\nanalyze(go_out5)", "_____no_output_____" ] ], [ [ "## Free Time after School", "_____no_output_____" ] ], [ [ "# Each array holds the grades of students who have the specified amount of free time after school \n# (1 - very low, 5 - very high)\nfree1 = []\nfree2 = []\nfree3 = []\nfree4 = []\nfree5 = []\n\n# Floating point values representing frequency\nunique = np.unique(student_data[:,24])\n\n# Iterate through all student samples and append final grades to corresponding arrays \nfor i in range(student_data.shape[0]):\n \n frequency = student_data[i][24]\n \n if(frequency==unique[0]):\n free1.append(student_data[i][32])\n elif(frequency==unique[1]):\n free2.append(student_data[i][32])\n elif(frequency==unique[2]):\n free3.append(student_data[i][32])\n elif(frequency==unique[3]):\n free4.append(student_data[i][32])\n else:\n free5.append(student_data[i][32])", "_____no_output_____" ], [ "analyze(free1)\nanalyze(free2)\nanalyze(free3)\nanalyze(free4)\nanalyze(free5)", "_____no_output_____" ] ], [ [ "## Paid Classes", "_____no_output_____" ] ], [ [ "# Array holding final grades of all students who have extra paid classes\npaid_class = []\n# Array holding final grades of all students who do not have extra paid classes\nno_paid_class = []\n\n# Iterate through all student samples and append final grades to corresponding arrays \nfor i in range(student_data.shape[0]):\n \n paid = student_data[i][17]\n \n if(paid==1):\n paid_class.append(student_data[i][32])\n else:\n no_paid_class.append(student_data[i][32])", "_____no_output_____" ] ], [ [ "### Extra Paid Classes", "_____no_output_____" ] ], [ [ "analyze(paid_class)", "_____no_output_____" ] ], [ [ "### No Extra Paid Classes", "_____no_output_____" ] ], [ [ "analyze(no_paid_class)", "_____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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d03905e9203e49a61ee3db8425fcefe43269f4bf
26,000
ipynb
Jupyter Notebook
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
1dde5fffd3397c752e814e8dee6e8eeeeee96012
[ "Unlicense" ]
null
null
null
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
1dde5fffd3397c752e814e8dee6e8eeeeee96012
[ "Unlicense" ]
null
null
null
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
1dde5fffd3397c752e814e8dee6e8eeeeee96012
[ "Unlicense" ]
2
2019-10-24T02:40:45.000Z
2019-11-14T15:07:13.000Z
32.622334
2,531
0.502077
[ [ [ "users = [\n{ \"id\": 0, \"name\": \"Hero\" },\n{ \"id\": 1, \"name\": \"Dunn\" },\n{ \"id\": 2, \"name\": \"Sue\" },\n{ \"id\": 3, \"name\": \"Chi\" },\n{ \"id\": 4, \"name\": \"Thor\" },\n{ \"id\": 5, \"name\": \"Clive\" },\n{ \"id\": 6, \"name\": \"Hicks\" },\n{ \"id\": 7, \"name\": \"Devin\" },\n{ \"id\": 8, \"name\": \"Kate\" },\n{ \"id\": 9, \"name\": \"Klein\" }\n]\n\n# “friendship” data, represented as a list of pairs of IDs\n# the tuple (0, 1) indicates that the data scientist with id 0 (Hero) and\n# the data scientist with id 1 (Dunn) are friends.\n\nfriendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),\n (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]", "_____no_output_____" ] ], [ [ "# 1) Add a list of friends to each user", "_____no_output_____" ] ], [ [ "# set each user’s friends property to an empty list:\nfor user in users:\n user[\"friends\"] = []\n\nprint users", "[{'friends': [], 'id': 0, 'name': 'Hero'}, {'friends': [], 'id': 1, 'name': 'Dunn'}, {'friends': [], 'id': 2, 'name': 'Sue'}, {'friends': [], 'id': 3, 'name': 'Chi'}, {'friends': [], 'id': 4, 'name': 'Thor'}, {'friends': [], 'id': 5, 'name': 'Clive'}, {'friends': [], 'id': 6, 'name': 'Hicks'}, {'friends': [], 'id': 7, 'name': 'Devin'}, {'friends': [], 'id': 8, 'name': 'Kate'}, {'friends': [], 'id': 9, 'name': 'Klein'}]\n" ], [ "print users[0]['friends']", "[]\n" ], [ "# then we populate the lists using the friendships data:\n\nfor i, j in friendships:\n # this works because users[i] is the user whose id is i\n users[i][\"friends\"].append(users[j]) # add i as a friend of j\n users[j][\"friends\"].append(users[i]) # add j as a friend of i\nprint users[0]", "{'friends': [{'friends': [{...}, {'friends': [{...}, {...}, {'friends': [{...}, {...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 2, 'name': 'Sue'}, {'friends': [{...}, {'friends': [{...}, {...}, {...}], 'id': 2, 'name': 'Sue'}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 1, 'name': 'Dunn'}, {'friends': [{...}, {'friends': [{...}, {...}, {'friends': [{...}, {...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 1, 'name': 'Dunn'}, {'friends': [{'friends': [{...}, {...}, {...}], 'id': 1, 'name': 'Dunn'}, {...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 2, 'name': 'Sue'}], 'id': 0, 'name': 'Hero'}\n" ] ], [ [ "# 2) what’s the average number of connections", "_____no_output_____" ], [ "Once each user dict contains a list of friends, we can easily ask questions of our\ngraph, like “what’s the average number of connections?”\nFirst we find the total number of connections, by summing up the lengths of all the\nfriends lists:", "_____no_output_____" ] ], [ [ "def number_of_friends(user):\n \"\"\"how many friends does _user_ have?\"\"\"\n return len(user[\"friends\"]) # length of friend_ids list\n\ntotal_connections = sum(number_of_friends(user)\n for user in users) # 24\nprint total_connections", "24\n" ], [ "# And then we just divide by the number of users:\nfrom __future__ import division # integer division is lame\n\nnum_users = len(users) # length of the users list\nprint num_users\navg_connections = total_connections / num_users # 2.4\nprint avg_connections", "10\n2.4\n" ] ], [ [ "It’s also easy to find the most connected people—they’re the people who have the largest\nnumber of friends.\n\nSince there aren’t very many users, we can sort them from “most friends” to “least\nfriends”:", "_____no_output_____" ] ], [ [ "# create a list (user_id, number_of_friends)\nnum_friends_by_id = [(user[\"id\"], number_of_friends(user))\n for user in users]\nprint num_friends_by_id\n\nsorted(num_friends_by_id, # get it sorted\n key=lambda (user_id, num_friends): num_friends, # by num_friends\n reverse=True) # largest to smallest\n\n\n# each pair is (user_id, num_friends)\n# [(1, 3), (2, 3), (3, 3), (5, 3), (8, 3),\n# (0, 2), (4, 2), (6, 2), (7, 2), (9, 1)]", "[(0, 2), (1, 3), (2, 3), (3, 3), (4, 2), (5, 3), (6, 2), (7, 2), (8, 3), (9, 1)]\n" ] ], [ [ "# 3) Data Scientists You May Know", "_____no_output_____" ], [ "Your first instinct is to suggest that a user might know the friends of friends. These\nare easy to compute: for each of a user’s friends, iterate over that person’s friends, and\ncollect all the results:", "_____no_output_____" ] ], [ [ "def friends_of_friend_ids_bad(user):\n # \"foaf\" is short for \"friend of a friend\"\n return [foaf[\"id\"]\n for friend in user[\"friends\"] # for each of user's friends\n for foaf in friend[\"friends\"]] # get each of _their_ friends", "_____no_output_____" ], [ "friends_of_friend_ids_bad(users[0])", "_____no_output_____" ] ], [ [ "It includes user 0 (twice), since Hero is indeed friends with both of his friends. It\nincludes users 1 and 2, although they are both friends with Hero already. And it\nincludes user 3 twice, as Chi is reachable through two different friends:", "_____no_output_____" ] ], [ [ "print [friend[\"id\"] for friend in users[0][\"friends\"]] # [1, 2]\nprint [friend[\"id\"] for friend in users[1][\"friends\"]] # [0, 2, 3]\nprint [friend[\"id\"] for friend in users[2][\"friends\"]] # [0, 1, 3]", "[1, 2]\n[0, 2, 3]\n[0, 1, 3]\n" ] ], [ [ "Knowing that people are friends-of-friends in multiple ways seems like interesting\ninformation, so maybe instead we should produce a count of mutual friends. And we\ndefinitely should use a helper function to exclude people already known to the user:", "_____no_output_____" ] ], [ [ "from collections import Counter # not loaded by default\n\ndef not_the_same(user, other_user):\n \"\"\"two users are not the same if they have different ids\"\"\"\n return user[\"id\"] != other_user[\"id\"]\n\ndef not_friends(user, other_user):\n \"\"\"other_user is not a friend if he's not in user[\"friends\"];\n that is, if he's not_the_same as all the people in user[\"friends\"]\"\"\"\n return all(not_the_same(friend, other_user)\n for friend in user[\"friends\"])\n\ndef friends_of_friend_ids(user):\n return Counter(foaf[\"id\"]\n for friend in user[\"friends\"] # for each of my friends\n for foaf in friend[\"friends\"] # count *their* friends\n if not_the_same(user, foaf) # who aren't me\n and not_friends(user, foaf)) # and aren't my friends\n\nprint friends_of_friend_ids(users[3]) # Counter({0: 2, 5: 1})", "Counter({0: 2, 5: 1})\n" ] ], [ [ "This correctly tells Chi (id 3) that she has two mutual friends with Hero (id 0) but\nonly one mutual friend with Clive (id 5).", "_____no_output_____" ], [ "As a data scientist, you know that you also might enjoy meeting users with similar\ninterests. (This is a good example of the “substantive expertise” aspect of data science.)\nAfter asking around, you manage to get your hands on this data, as a list of\npairs (user_id, interest):", "_____no_output_____" ] ], [ [ "interests = [\n(0, \"Hadoop\"), (0, \"Big Data\"), (0, \"HBase\"), (0, \"Java\"),\n(0, \"Spark\"), (0, \"Storm\"), (0, \"Cassandra\"),\n(1, \"NoSQL\"), (1, \"MongoDB\"), (1, \"Cassandra\"), (1, \"HBase\"),\n(1, \"Postgres\"), (2, \"Python\"), (2, \"scikit-learn\"), (2, \"scipy\"),\n(2, \"numpy\"), (2, \"statsmodels\"), (2, \"pandas\"), (3, \"R\"), (3, \"Python\"),\n(3, \"statistics\"), (3, \"regression\"), (3, \"probability\"),\n(4, \"machine learning\"), (4, \"regression\"), (4, \"decision trees\"),\n(4, \"libsvm\"), (5, \"Python\"), (5, \"R\"), (5, \"Java\"), (5, \"C++\"),\n(5, \"Haskell\"), (5, \"programming languages\"), (6, \"statistics\"),\n(6, \"probability\"), (6, \"mathematics\"), (6, \"theory\"),\n(7, \"machine learning\"), (7, \"scikit-learn\"), (7, \"Mahout\"),\n(7, \"neural networks\"), (8, \"neural networks\"), (8, \"deep learning\"),\n(8, \"Big Data\"), (8, \"artificial intelligence\"), (9, \"Hadoop\"),\n(9, \"Java\"), (9, \"MapReduce\"), (9, \"Big Data\")\n]", "_____no_output_____" ] ], [ [ "For example, Thor (id 4) has no friends in common with Devin (id 7), but they share\nan interest in machine learning.\n\nIt’s easy to build a function that finds users with a certain interest:", "_____no_output_____" ] ], [ [ "def data_scientists_who_like(target_interest):\n return [user_id\n for user_id, user_interest in interests\n if user_interest == target_interest]\n\ndata_scientists_who_like('Java')", "_____no_output_____" ] ], [ [ "This works, but it has to examine the whole list of interests for every search. If we\nhave a lot of users and interests (or if we just want to do a lot of searches), we’re probably\nbetter off building an index from interests to users:", "_____no_output_____" ] ], [ [ "from collections import defaultdict\n\n# keys are interests, values are lists of user_ids with that interest\nuser_ids_by_interest = defaultdict(list)\n\nfor user_id, interest in interests:\n user_ids_by_interest[interest].append(user_id)\n\nprint user_ids_by_interest", "defaultdict(<type 'list'>, {'Java': [0, 5, 9], 'neural networks': [7, 8], 'NoSQL': [1], 'Hadoop': [0, 9], 'Mahout': [7], 'Storm': [0], 'regression': [3, 4], 'statistics': [3, 6], 'probability': [3, 6], 'programming languages': [5], 'Python': [2, 3, 5], 'deep learning': [8], 'Haskell': [5], 'mathematics': [6], 'Spark': [0], 'numpy': [2], 'pandas': [2], 'artificial intelligence': [8], 'theory': [6], 'libsvm': [4], 'C++': [5], 'R': [3, 5], 'HBase': [0, 1], 'Postgres': [1], 'decision trees': [4], 'Big Data': [0, 8, 9], 'MongoDB': [1], 'scikit-learn': [2, 7], 'MapReduce': [9], 'machine learning': [4, 7], 'scipy': [2], 'statsmodels': [2], 'Cassandra': [0, 1]})\n" ], [ "# And another from users to interests:\n# keys are user_ids, values are lists of interests for that user_id\ninterests_by_user_id = defaultdict(list)\n\nfor user_id, interest in interests:\n interests_by_user_id[user_id].append(interest)\n \nprint interests_by_user_id", "defaultdict(<type 'list'>, {0: ['Hadoop', 'Big Data', 'HBase', 'Java', 'Spark', 'Storm', 'Cassandra'], 1: ['NoSQL', 'MongoDB', 'Cassandra', 'HBase', 'Postgres'], 2: ['Python', 'scikit-learn', 'scipy', 'numpy', 'statsmodels', 'pandas'], 3: ['R', 'Python', 'statistics', 'regression', 'probability'], 4: ['machine learning', 'regression', 'decision trees', 'libsvm'], 5: ['Python', 'R', 'Java', 'C++', 'Haskell', 'programming languages'], 6: ['statistics', 'probability', 'mathematics', 'theory'], 7: ['machine learning', 'scikit-learn', 'Mahout', 'neural networks'], 8: ['neural networks', 'deep learning', 'Big Data', 'artificial intelligence'], 9: ['Hadoop', 'Java', 'MapReduce', 'Big Data']})\n" ] ], [ [ "Now it’s easy to find who has the most interests in common with a given user:\n- Iterate over the user’s interests.\n- For each interest, iterate over the other users with that interest.\n- Keep count of how many times we see each other user.", "_____no_output_____" ] ], [ [ "def most_common_interests_with(user):\n return Counter(interested_user_id\n for interest in interests_by_user_id[user[\"id\"]]\n for interested_user_id in user_ids_by_interest[interest]\n if interested_user_id != user[\"id\"])", "_____no_output_____" ] ], [ [ "# 4) Salaries and Experience", "_____no_output_____" ] ], [ [ "# Salary data is of course sensitive,\n# but he manages to provide you an anonymous data set containing each user’s\n# salary (in dollars) and tenure as a data scientist (in years):\n \nsalaries_and_tenures = [(83000, 8.7), (88000, 8.1),\n (48000, 0.7), (76000, 6),\n (69000, 6.5), (76000, 7.5),\n (60000, 2.5), (83000, 10),\n (48000, 1.9), (63000, 4.2)]", "_____no_output_____" ] ], [ [ "It seems pretty clear that people with more experience tend to earn more. How can\nyou turn this into a fun fact? Your first idea is to look at the average salary for each\ntenure:", "_____no_output_____" ] ], [ [ "# keys are years, values are lists of the salaries for each tenure\nsalary_by_tenure = defaultdict(list)\n\nfor salary, tenure in salaries_and_tenures:\n salary_by_tenure[tenure].append(salary)\n \nprint salary_by_tenure\n\n# keys are years, each value is average salary for that tenure\naverage_salary_by_tenure = {\n tenure : sum(salaries) / len(salaries)\n for tenure, salaries in salary_by_tenure.items()\n}\n\nprint average_salary_by_tenure", "defaultdict(<type 'list'>, {6.5: [69000], 7.5: [76000], 6: [76000], 10: [83000], 8.1: [88000], 4.2: [63000], 0.7: [48000], 8.7: [83000], 1.9: [48000], 2.5: [60000]})\n{6.5: 69000.0, 7.5: 76000.0, 6: 76000.0, 10: 83000.0, 8.1: 88000.0, 4.2: 63000.0, 8.7: 83000.0, 0.7: 48000.0, 1.9: 48000.0, 2.5: 60000.0}\n" ] ], [ [ "This turns out to be not particularly useful, as none of the users have the same tenure, which means we’re just reporting the individual users’ salaries.", "_____no_output_____" ] ], [ [ "# It might be more helpful to bucket the tenures:\ndef tenure_bucket(tenure):\n if tenure < 2:\n return \"less than two\"\n elif tenure < 5:\n return \"between two and five\"\n else:\n return \"more than five\"", "_____no_output_____" ], [ "# Then group together the salaries corresponding to each bucket:\n\n# keys are tenure buckets, values are lists of salaries for that bucket\nsalary_by_tenure_bucket = defaultdict(list)\n\nfor salary, tenure in salaries_and_tenures:\n bucket = tenure_bucket(tenure)\n salary_by_tenure_bucket[bucket].append(salary)\n \n# And finally compute the average salary for each group:\n\n# keys are tenure buckets, values are average salary for that bucket\naverage_salary_by_bucket = {\n tenure_bucket : sum(salaries) / len(salaries)\n for tenure_bucket, salaries in salary_by_tenure_bucket.iteritems()\n}\n\nprint average_salary_by_bucket", "{'more than five': 79166.66666666667, 'between two and five': 61500.0, 'less than two': 48000.0}\n" ] ], [ [ "# 5) Paid Accounts", "_____no_output_____" ] ], [ [ "def predict_paid_or_unpaid(years_experience):\n if years_experience < 3.0:\n return \"paid\"\n elif years_experience < 8.5:\n return \"unpaid\"\n else:\n return \"paid\"", "_____no_output_____" ] ], [ [ "# 6) Topics of Interest", "_____no_output_____" ], [ "One simple (if not particularly exciting) way to find the most popular interests is simply\nto count the words:\n1. Lowercase each interest (since different users may or may not capitalize their\ninterests).\n2. Split it into words.\n3. Count the results.", "_____no_output_____" ] ], [ [ "words_and_counts = Counter(word\n for user, interest in interests\n for word in interest.lower().split())\n\nprint words_and_counts", "Counter({'learning': 3, 'java': 3, 'python': 3, 'big': 3, 'data': 3, 'hbase': 2, 'regression': 2, 'cassandra': 2, 'statistics': 2, 'probability': 2, 'hadoop': 2, 'networks': 2, 'machine': 2, 'neural': 2, 'scikit-learn': 2, 'r': 2, 'nosql': 1, 'programming': 1, 'deep': 1, 'haskell': 1, 'languages': 1, 'decision': 1, 'artificial': 1, 'storm': 1, 'mongodb': 1, 'intelligence': 1, 'mathematics': 1, 'numpy': 1, 'pandas': 1, 'postgres': 1, 'libsvm': 1, 'trees': 1, 'scipy': 1, 'spark': 1, 'mapreduce': 1, 'c++': 1, 'theory': 1, 'statsmodels': 1, 'mahout': 1})\n" ] ], [ [ "This makes it easy to list out the words that occur more than once:", "_____no_output_____" ] ], [ [ "for word, count in words_and_counts.most_common():\n if count > 1:\n print word, count", "learning 3\njava 3\npython 3\nbig 3\ndata 3\nhbase 2\nregression 2\ncassandra 2\nstatistics 2\nprobability 2\nhadoop 2\nnetworks 2\nmachine 2\nneural 2\nscikit-learn 2\nr 2\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0390fe0e749bec2a142b84efd1c59b97fd38077
159,998
ipynb
Jupyter Notebook
lottery-linear.ipynb
diewland/ml-lottery
aca321e55e98d4a20198cb6353410dcb44dd2061
[ "MIT" ]
null
null
null
lottery-linear.ipynb
diewland/ml-lottery
aca321e55e98d4a20198cb6353410dcb44dd2061
[ "MIT" ]
null
null
null
lottery-linear.ipynb
diewland/ml-lottery
aca321e55e98d4a20198cb6353410dcb44dd2061
[ "MIT" ]
null
null
null
197.284834
118,912
0.88408
[ [ [ "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\nlottery_dataframe = pd.read_csv(\"lottery.csv\", sep=\",\")\nlottery_dataframe = lottery_dataframe.reindex(np.random.permutation(lottery_dataframe.index))", "_____no_output_____" ], [ "def preprocess_features(lottery_dataframe):\n selected_features = lottery_dataframe[\n [\"day\",\n \"month\",\n \"year\",\n #\"no1\",\n #\"top2\",\n #\"top3\",\n #\"front3_1\",\n #\"front3_2\",\n #\"bottom3_1\", \n #\"bottom3_2\"\n ]]\n return selected_features\n\ndef preprocess_targets(lottery_dataframe):\n output_targets = pd.DataFrame()\n output_targets[\"bottom2\"] = lottery_dataframe[\"bottom2\"]\n return output_targets", "_____no_output_____" ], [ "# Choose the first 578 (out of 684) examples for training.\ntraining_examples = preprocess_features(lottery_dataframe.head(578))\ntraining_targets = preprocess_targets(lottery_dataframe.head(578))\n\n# Choose the last 106 (out of 684) examples for validation.\nvalidation_examples = preprocess_features(lottery_dataframe.tail(106))\nvalidation_targets = preprocess_targets(lottery_dataframe.tail(106))\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())", "Training examples summary:\n" ], [ "def construct_feature_columns(input_features):\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 neural network model.\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 feature_columns,\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 feature_columns: A `set` specifying the input feature columns to use.\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.FtrlOptimizer(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=feature_columns,\n optimizer=my_optimizer\n )\n \n training_input_fn = lambda: my_input_fn(training_examples, \n training_targets[\"bottom2\"], \n batch_size=batch_size)\n predict_training_input_fn = lambda: my_input_fn(training_examples, \n training_targets[\"bottom2\"], \n num_epochs=1, \n shuffle=False)\n predict_validation_input_fn = lambda: my_input_fn(validation_examples, \n validation_targets[\"bottom2\"], \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 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, validation_predictions", "_____no_output_____" ], [ "r, p = train_model(\n learning_rate=0.001,\n steps=5000,\n batch_size=10,\n feature_columns=construct_feature_columns(training_examples),\n training_examples=training_examples,\n training_targets=training_targets,\n validation_examples=validation_examples,\n validation_targets=validation_targets)", "Training model...\nRMSE (on training data):\n period 00 : 28.87\n period 01 : 28.87\n period 02 : 28.87\n period 03 : 28.87\n period 04 : 28.87\n period 05 : 28.88\n period 06 : 28.87\n period 07 : 28.87\n period 08 : 28.87\n period 09 : 28.87\nModel training finished.\n" ], [ "my_target = validation_targets.copy()\nmy_target['predict'] = p\nmy_target\n\n# Output a graph of loss metrics over periods.\nplt.ylabel(\"target\")\nplt.xlabel(\"predict\")\nplt.title(\"bottom2\")\nplt.tight_layout()\nplt.plot(validation_targets, label=\"Target\")\nplt.plot(p, label=\"Predict\")\nplt.legend()\n\nmy_target", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d039286003a56d65e4ebef9942c4e64606d26402
209,799
ipynb
Jupyter Notebook
18cse102-Assignment3.ipynb
Sonam-khatua/18CSE102
a640ae1089b5cedd408a8e23902a0c000de89e83
[ "Apache-2.0" ]
null
null
null
18cse102-Assignment3.ipynb
Sonam-khatua/18CSE102
a640ae1089b5cedd408a8e23902a0c000de89e83
[ "Apache-2.0" ]
null
null
null
18cse102-Assignment3.ipynb
Sonam-khatua/18CSE102
a640ae1089b5cedd408a8e23902a0c000de89e83
[ "Apache-2.0" ]
null
null
null
157.03518
39,064
0.85151
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "import pandas as pd", "_____no_output_____" ], [ "data=pd.read_csv(\"Social_Network_Ads.csv\")", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ], [ "data.tail()", "_____no_output_____" ], [ "data.dropna(axis=0,inplace=True)", "_____no_output_____" ], [ "data.shape", "_____no_output_____" ], [ "data.head(5)", "_____no_output_____" ], [ "plt.scatter(data['Age'],data['EstimatedSalary'],c='blue')\nplt.xlabel('Age(months)')\nplt.ylabel('EstimatedSalary')\nplt.show()", "_____no_output_____" ], [ "plt.hist(data['Gender'])\nplt.show()", "_____no_output_____" ], [ "plt.hist(data['EstimatedSalary'])", "_____no_output_____" ], [ "plt.hist(data['Age'],color='orange',edgecolor='white',bins=5)\nplt.title=(\"histogram of ages\")\nplt.xlabel(\"frequencies\")\nplt.ylabel(\"Age\")\nplt.show()", "_____no_output_____" ], [ "import seaborn as sns", "_____no_output_____" ], [ "sns.set(style='darkgrid')\nsns.regplot(x=data['Age'],y=data['EstimatedSalary'])", "_____no_output_____" ], [ "sns.set(style='darkgrid')\nsns.regplot(x=data['Age'],y=data['EstimatedSalary'],marker='*',fit_reg=False)", "_____no_output_____" ], [ "sns.distplot(data['Age'])", "_____no_output_____" ], [ "sns.distplot(data['Age'],kde=False)", "_____no_output_____" ], [ "sns.distplot(data['Age'],kde=False,bins=5)", "_____no_output_____" ], [ "sns.countplot(x=\"Purchased\",data=data)", "_____no_output_____" ], [ "sns.boxplot(y=data['EstimatedSalary'])", "_____no_output_____" ], [ "sns.b", "_____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" ] ]
d0392b7a072121ba40ef6106592cc48a107e9810
314,501
ipynb
Jupyter Notebook
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
379e062cf58d83ff57a456552bb956df68381fdd
[ "MIT" ]
2
2020-01-25T08:31:14.000Z
2022-03-23T18:24:03.000Z
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
379e062cf58d83ff57a456552bb956df68381fdd
[ "MIT" ]
null
null
null
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
379e062cf58d83ff57a456552bb956df68381fdd
[ "MIT" ]
null
null
null
301.534995
102,272
0.912283
[ [ [ "# LOFO Feature Importance\nhttps://github.com/aerdem4/lofo-importance", "_____no_output_____" ] ], [ [ "!pip install lofo-importance", "Collecting lofo-importance\r\n Downloading https://files.pythonhosted.org/packages/43/8e/c43fb5e6a56e6e028b24c93bee6282726534abeb42c1cd12d41fecd5443b/lofo_importance-0.2.0-py3-none-any.whl\r\nRequirement already satisfied: lightgbm in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (2.2.3)\r\nRequirement already satisfied: matplotlib in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (3.0.3)\r\nRequirement already satisfied: scikit-learn in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (0.20.3)\r\nRequirement already satisfied: numpy in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (1.16.3)\r\nRequirement already satisfied: ipywidgets in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (7.2.1)\r\nRequirement already satisfied: jupyter in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (1.0.0)\r\nRequirement already satisfied: tqdm in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (4.31.1)\r\nRequirement already satisfied: pandas in /opt/conda/lib/python3.6/site-packages (from lofo-importance) (0.23.4)\r\nRequirement already satisfied: scipy in /opt/conda/lib/python3.6/site-packages (from lightgbm->lofo-importance) (1.1.0)\r\nRequirement already satisfied: python-dateutil>=2.1 in /opt/conda/lib/python3.6/site-packages (from matplotlib->lofo-importance) (2.6.0)\r\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/lib/python3.6/site-packages (from matplotlib->lofo-importance) (2.2.0)\r\nRequirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.6/site-packages (from matplotlib->lofo-importance) (0.10.0)\r\nRequirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.6/site-packages (from matplotlib->lofo-importance) (1.0.1)\r\nRequirement already satisfied: ipykernel>=4.5.1 in /opt/conda/lib/python3.6/site-packages (from ipywidgets->lofo-importance) (4.8.2)\r\nRequirement already satisfied: traitlets>=4.3.1 in /opt/conda/lib/python3.6/site-packages (from ipywidgets->lofo-importance) (4.3.2)\r\nRequirement already satisfied: nbformat>=4.2.0 in /opt/conda/lib/python3.6/site-packages (from ipywidgets->lofo-importance) (4.4.0)\r\nRequirement already satisfied: widgetsnbextension~=3.2.0 in /opt/conda/lib/python3.6/site-packages (from ipywidgets->lofo-importance) (3.2.1)\r\nRequirement already satisfied: ipython>=4.0.0 in /opt/conda/lib/python3.6/site-packages (from ipywidgets->lofo-importance) (6.4.0)\r\nRequirement already satisfied: notebook in /opt/conda/lib/python3.6/site-packages (from jupyter->lofo-importance) (5.5.0)\r\nRequirement already satisfied: qtconsole in /opt/conda/lib/python3.6/site-packages (from jupyter->lofo-importance) (4.3.1)\r\nRequirement already satisfied: jupyter-console in /opt/conda/lib/python3.6/site-packages (from jupyter->lofo-importance) (5.2.0)\r\nRequirement already satisfied: nbconvert in /opt/conda/lib/python3.6/site-packages (from jupyter->lofo-importance) (5.3.1)\r\nRequirement already satisfied: pytz>=2011k in /opt/conda/lib/python3.6/site-packages (from pandas->lofo-importance) (2018.4)\r\nRequirement already satisfied: six>=1.5 in /opt/conda/lib/python3.6/site-packages (from python-dateutil>=2.1->matplotlib->lofo-importance) (1.12.0)\r\nRequirement already satisfied: setuptools in /opt/conda/lib/python3.6/site-packages (from kiwisolver>=1.0.1->matplotlib->lofo-importance) (39.1.0)\r\nRequirement already satisfied: jupyter_client in /opt/conda/lib/python3.6/site-packages (from ipykernel>=4.5.1->ipywidgets->lofo-importance) (5.2.3)\r\nRequirement already satisfied: tornado>=4.0 in /opt/conda/lib/python3.6/site-packages (from ipykernel>=4.5.1->ipywidgets->lofo-importance) (5.0.2)\r\nRequirement already satisfied: ipython_genutils in /opt/conda/lib/python3.6/site-packages (from traitlets>=4.3.1->ipywidgets->lofo-importance) (0.2.0)\r\nRequirement already satisfied: decorator in /opt/conda/lib/python3.6/site-packages (from traitlets>=4.3.1->ipywidgets->lofo-importance) (4.3.0)\r\nRequirement already satisfied: jsonschema!=2.5.0,>=2.4 in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2.0->ipywidgets->lofo-importance) (2.6.0)\r\nRequirement already satisfied: jupyter_core in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2.0->ipywidgets->lofo-importance) (4.4.0)\r\nRequirement already satisfied: prompt-toolkit<2.0.0,>=1.0.15 in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0->ipywidgets->lofo-importance) (1.0.15)\r\nRequirement already satisfied: simplegeneric>0.8 in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0->ipywidgets->lofo-importance) (0.8.1)\r\nRequirement already satisfied: pygments in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0->ipywidgets->lofo-importance) (2.2.0)\r\nRequirement already satisfied: backcall in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0->ipywidgets->lofo-importance) (0.1.0)\r\nRequirement already satisfied: pexpect; sys_platform != \"win32\" in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0->ipywidgets->lofo-importance) (4.5.0)\r\nRequirement already satisfied: jedi>=0.10 in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0->ipywidgets->lofo-importance) (0.12.0)\r\nRequirement already satisfied: pickleshare in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0->ipywidgets->lofo-importance) (0.7.4)\r\nRequirement already satisfied: Send2Trash in /opt/conda/lib/python3.6/site-packages (from notebook->jupyter->lofo-importance) (1.5.0)\r\nRequirement already satisfied: terminado>=0.8.1 in /opt/conda/lib/python3.6/site-packages (from notebook->jupyter->lofo-importance) (0.8.1)\r\nRequirement already satisfied: jinja2 in /opt/conda/lib/python3.6/site-packages (from notebook->jupyter->lofo-importance) (2.10)\r\nRequirement already satisfied: pyzmq>=17 in /opt/conda/lib/python3.6/site-packages (from notebook->jupyter->lofo-importance) (17.0.0)\r\nRequirement already satisfied: mistune>=0.7.4 in /opt/conda/lib/python3.6/site-packages (from nbconvert->jupyter->lofo-importance) (0.8.3)\r\nRequirement already satisfied: entrypoints>=0.2.2 in /opt/conda/lib/python3.6/site-packages (from nbconvert->jupyter->lofo-importance) (0.2.3)\r\nRequirement already satisfied: bleach in /opt/conda/lib/python3.6/site-packages (from nbconvert->jupyter->lofo-importance) (2.1.3)\r\nRequirement already satisfied: pandocfilters>=1.4.1 in /opt/conda/lib/python3.6/site-packages (from nbconvert->jupyter->lofo-importance) (1.4.2)\r\nRequirement already satisfied: testpath in /opt/conda/lib/python3.6/site-packages (from nbconvert->jupyter->lofo-importance) (0.3.1)\r\nRequirement already satisfied: wcwidth in /opt/conda/lib/python3.6/site-packages (from prompt-toolkit<2.0.0,>=1.0.15->ipython>=4.0.0->ipywidgets->lofo-importance) (0.1.7)\r\nRequirement already satisfied: ptyprocess>=0.5 in /opt/conda/lib/python3.6/site-packages (from pexpect; sys_platform != \"win32\"->ipython>=4.0.0->ipywidgets->lofo-importance) (0.5.2)\r\nRequirement already satisfied: parso>=0.2.0 in /opt/conda/lib/python3.6/site-packages (from jedi>=0.10->ipython>=4.0.0->ipywidgets->lofo-importance) (0.2.0)\r\nRequirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from jinja2->notebook->jupyter->lofo-importance) (1.0)\r\nRequirement already satisfied: html5lib!=1.0b1,!=1.0b2,!=1.0b3,!=1.0b4,!=1.0b5,!=1.0b6,!=1.0b7,!=1.0b8,>=0.99999999pre in /opt/conda/lib/python3.6/site-packages (from bleach->nbconvert->jupyter->lofo-importance) (1.0.1)\r\nRequirement already satisfied: webencodings in /opt/conda/lib/python3.6/site-packages (from html5lib!=1.0b1,!=1.0b2,!=1.0b3,!=1.0b4,!=1.0b5,!=1.0b6,!=1.0b7,!=1.0b8,>=0.99999999pre->bleach->nbconvert->jupyter->lofo-importance) (0.5.1)\r\nInstalling collected packages: lofo-importance\r\nSuccessfully installed lofo-importance-0.2.0\r\n\u001b[33mYou are using pip version 19.0.3, however version 19.1.1 is available.\r\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\r\n" ], [ "import numpy as np\nimport pandas as pd\n\ndf = pd.read_csv(\"../input/train.csv\", index_col='id')\ndf['wheezy-copper-turtle-magic'] = df['wheezy-copper-turtle-magic'].astype('category')\ndf.shape", "_____no_output_____" ] ], [ [ "### Use the best model in public kernels", "_____no_output_____" ] ], [ [ "from sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\n\ndef get_model():\n return Pipeline([('scaler', StandardScaler()),\n ('qda', QuadraticDiscriminantAnalysis(reg_param=0.111))\n ])", "_____no_output_____" ] ], [ [ "### Top 20 Features for wheezy-copper-turtle-magic = 0", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import KFold, StratifiedKFold, train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom lofo import LOFOImportance, FLOFOImportance, plot_importance\n\n\nfeatures = [c for c in df.columns if c not in ['id', 'target', 'wheezy-copper-turtle-magic']]\n\n\ndef get_lofo_importance(wctm_num):\n sub_df = df[df['wheezy-copper-turtle-magic'] == wctm_num]\n sub_features = [f for f in features if sub_df[f].std() > 1.5]\n lofo_imp = LOFOImportance(sub_df, target=\"target\",\n features=sub_features, \n cv=StratifiedKFold(n_splits=4, random_state=42, shuffle=True), scoring=\"roc_auc\",\n model=get_model(), n_jobs=4)\n return lofo_imp.get_importance()\n\nplot_importance(get_lofo_importance(0), figsize=(12, 12))", "/opt/conda/lib/python3.6/site-packages/lofo/lofo_importance.py:32: UserWarning: Warning: If your model is multithreaded, please initialise the number of jobs of LOFO to be equal to 1, otherwise you may experience issues.\n warnings.warn(warning_str)\n" ] ], [ [ "### Top 20 Features for wheezy-copper-turtle-magic = 1", "_____no_output_____" ] ], [ [ "plot_importance(get_lofo_importance(1), figsize=(12, 12))", "/opt/conda/lib/python3.6/site-packages/lofo/lofo_importance.py:32: UserWarning: Warning: If your model is multithreaded, please initialise the number of jobs of LOFO to be equal to 1, otherwise you may experience issues.\n warnings.warn(warning_str)\n" ] ], [ [ "### Top 20 Features for wheezy-copper-turtle-magic = 2", "_____no_output_____" ] ], [ [ "plot_importance(get_lofo_importance(2), figsize=(12, 12))", "/opt/conda/lib/python3.6/site-packages/lofo/lofo_importance.py:32: UserWarning: Warning: If your model is multithreaded, please initialise the number of jobs of LOFO to be equal to 1, otherwise you may experience issues.\n warnings.warn(warning_str)\n" ] ], [ [ "### Find the most harmful features for each wheezy-copper-turtle-magic", "_____no_output_____" ] ], [ [ "from tqdm import tqdm_notebook\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfeatures_to_remove = []\npotential_gain = []\n\nfor i in tqdm_notebook(range(512)):\n imp = get_lofo_importance(i)\n features_to_remove.append(imp[\"feature\"].values[-1])\n potential_gain.append(-imp[\"importance_mean\"].values[-1])\n \nprint(\"Potential gain (AUC):\", np.round(np.mean(potential_gain), 5))", "_____no_output_____" ], [ "features_to_remove", "_____no_output_____" ] ], [ [ "# Create submission using the current best kernel\nhttps://www.kaggle.com/tunguz/ig-pca-nusvc-knn-qda-lr-stack by Bojan Tunguz", "_____no_output_____" ] ], [ [ "import numpy as np, pandas as pd\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import svm, neighbors, linear_model, neural_network\nfrom sklearn.svm import NuSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom tqdm import tqdm\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.feature_selection import VarianceThreshold\n\ntrain = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\n\noof_svnu = np.zeros(len(train)) \npred_te_svnu = np.zeros(len(test))\n\noof_svc = np.zeros(len(train)) \npred_te_svc = np.zeros(len(test))\n\noof_knn = np.zeros(len(train)) \npred_te_knn = np.zeros(len(test))\n\noof_lr = np.zeros(len(train)) \npred_te_lr = np.zeros(len(test))\n\noof_mlp = np.zeros(len(train)) \npred_te_mlp = np.zeros(len(test))\n\noof_qda = np.zeros(len(train)) \npred_te_qda = np.zeros(len(test))\n\ndefault_cols = [c for c in train.columns if c not in ['id', 'target', 'wheezy-copper-turtle-magic']]\n\nfor i in range(512):\n cols = [c for c in default_cols if c != features_to_remove[i]]\n \n train2 = train[train['wheezy-copper-turtle-magic']==i]\n test2 = test[test['wheezy-copper-turtle-magic']==i]\n idx1 = train2.index; idx2 = test2.index\n train2.reset_index(drop=True,inplace=True)\n\n data = pd.concat([pd.DataFrame(train2[cols]), pd.DataFrame(test2[cols])])\n data2 = StandardScaler().fit_transform(PCA(svd_solver='full',n_components='mle').fit_transform(data[cols]))\n train3 = data2[:train2.shape[0]]; test3 = data2[train2.shape[0]:]\n \n data2 = StandardScaler().fit_transform(VarianceThreshold(threshold=1.5).fit_transform(data[cols]))\n train4 = data2[:train2.shape[0]]; test4 = data2[train2.shape[0]:]\n \n # STRATIFIED K FOLD (Using splits=25 scores 0.002 better but is slower)\n skf = StratifiedKFold(n_splits=5, random_state=42)\n for train_index, test_index in skf.split(train2, train2['target']):\n\n clf = NuSVC(probability=True, kernel='poly', degree=4, gamma='auto', random_state=4, nu=0.59, coef0=0.053)\n clf.fit(train3[train_index,:],train2.loc[train_index]['target'])\n oof_svnu[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]\n pred_te_svnu[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits\n \n clf = neighbors.KNeighborsClassifier(n_neighbors=17, p=2.9)\n clf.fit(train3[train_index,:],train2.loc[train_index]['target'])\n oof_knn[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]\n pred_te_knn[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits\n \n clf = linear_model.LogisticRegression(solver='saga',penalty='l1',C=0.1)\n clf.fit(train3[train_index,:],train2.loc[train_index]['target'])\n oof_lr[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]\n pred_te_lr[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits\n \n clf = neural_network.MLPClassifier(random_state=3, activation='relu', solver='lbfgs', tol=1e-06, hidden_layer_sizes=(250, ))\n clf.fit(train3[train_index,:],train2.loc[train_index]['target'])\n oof_mlp[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]\n pred_te_mlp[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits\n \n clf = svm.SVC(probability=True, kernel='poly', degree=4, gamma='auto', random_state=42)\n clf.fit(train3[train_index,:],train2.loc[train_index]['target'])\n oof_svc[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]\n pred_te_svc[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits\n \n clf = QuadraticDiscriminantAnalysis(reg_param=0.111)\n clf.fit(train4[train_index,:],train2.loc[train_index]['target'])\n oof_qda[idx1[test_index]] = clf.predict_proba(train4[test_index,:])[:,1]\n pred_te_qda[idx2] += clf.predict_proba(test4)[:,1] / skf.n_splits\n \n \nprint('lr', roc_auc_score(train['target'], oof_lr))\nprint('knn', roc_auc_score(train['target'], oof_knn))\nprint('svc', roc_auc_score(train['target'], oof_svc))\nprint('svcnu', roc_auc_score(train['target'], oof_svnu))\nprint('mlp', roc_auc_score(train['target'], oof_mlp))\nprint('qda', roc_auc_score(train['target'], oof_qda))\nprint('blend 1', roc_auc_score(train['target'], oof_svnu*0.7 + oof_svc*0.05 + oof_knn*0.2 + oof_mlp*0.05))\nprint('blend 2', roc_auc_score(train['target'], oof_qda*0.5+oof_svnu*0.35 + oof_svc*0.025 + oof_knn*0.1 + oof_mlp*0.025))\n\noof_svnu = oof_svnu.reshape(-1, 1)\npred_te_svnu = pred_te_svnu.reshape(-1, 1)\noof_svc = oof_svc.reshape(-1, 1)\npred_te_svc = pred_te_svc.reshape(-1, 1)\noof_knn = oof_knn.reshape(-1, 1)\npred_te_knn = pred_te_knn.reshape(-1, 1)\noof_mlp = oof_mlp.reshape(-1, 1)\npred_te_mlp = pred_te_mlp.reshape(-1, 1)\noof_lr = oof_lr.reshape(-1, 1)\npred_te_lr = pred_te_lr.reshape(-1, 1)\noof_qda = oof_qda.reshape(-1, 1)\npred_te_qda = pred_te_qda.reshape(-1, 1)\n\ntr = np.concatenate((oof_svnu, oof_svc, oof_knn, oof_mlp, oof_lr, oof_qda), axis=1)\nte = np.concatenate((pred_te_svnu, pred_te_svc, pred_te_knn, pred_te_mlp, pred_te_lr, pred_te_qda), axis=1)\nprint(tr.shape, te.shape)\n\noof_lrr = np.zeros(len(train)) \npred_te_lrr = np.zeros(len(test))\nskf = StratifiedKFold(n_splits=5, random_state=42)\n\nfor train_index, test_index in skf.split(tr, train['target']):\n lrr = linear_model.LogisticRegression()\n lrr.fit(tr[train_index], train['target'][train_index])\n oof_lrr[test_index] = lrr.predict_proba(tr[test_index,:])[:,1]\n pred_te_lrr += lrr.predict_proba(te)[:,1] / skf.n_splits\n \nprint('stack CV score =',round(roc_auc_score(train['target'],oof_lrr),6))\n\nsub = pd.read_csv('../input/sample_submission.csv')\n\nsub['target'] = pred_te_lrr\nsub.to_csv('submission_stack.csv', index=False)", "lr 0.790131655722408\nknn 0.9016209110875143\nsvc 0.9496455309107024\nsvcnu 0.9602070184471454\nmlp 0.9099946396711365\nqda 0.9645745359410043\nblend 1 0.9606747834832012\nblend 2 0.9658290716499904\n(262144, 6) (131073, 6)\nstack CV score = 0.965867\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d039321969de4a6f9e276e0c0e605881f60b4827
7,098
ipynb
Jupyter Notebook
encode-mirna-2018-01.ipynb
detrout/encode4-curation
c4d7904a8013a276c2771afaeb28db94b73ff020
[ "BSD-3-Clause" ]
null
null
null
encode-mirna-2018-01.ipynb
detrout/encode4-curation
c4d7904a8013a276c2771afaeb28db94b73ff020
[ "BSD-3-Clause" ]
null
null
null
encode-mirna-2018-01.ipynb
detrout/encode4-curation
c4d7904a8013a276c2771afaeb28db94b73ff020
[ "BSD-3-Clause" ]
null
null
null
22.896774
117
0.551705
[ [ [ "Submitting various things for end of grant.", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport requests\nimport pandas\nimport paramiko\nimport json\nfrom IPython import display", "_____no_output_____" ], [ "from curation_common import *\nfrom htsworkflow.submission.encoded import DCCValidator", "_____no_output_____" ], [ "PANDAS_ODF = os.path.expanduser('~/src/odf_pandas')\nif PANDAS_ODF not in sys.path:\n sys.path.append(PANDAS_ODF)\n from pandasodf import ODFReader", "_____no_output_____" ], [ "import gcat", "_____no_output_____" ], [ "from htsworkflow.submission.encoded import Document\nfrom htsworkflow.submission.aws_submission import run_aws_cp", "_____no_output_____" ], [ "# live server & control file\n#server = ENCODED('www.encodeproject.org')\nspreadsheet_name = \"ENCODE_test_miRNA_experiments_01112018\"\n\n# test server & datafile\nserver = ENCODED('test.encodedcc.org')\n#spreadsheet_name = os.path.expanduser('~diane/woldlab/ENCODE/C1-encode3-limb-2017-testserver.ods')\n\nserver.load_netrc()\nvalidator = DCCValidator(server)", "_____no_output_____" ], [ "award = 'UM1HG009443'", "_____no_output_____" ] ], [ [ "# Submit Documents", "_____no_output_____" ], [ "Example Document submission", "_____no_output_____" ] ], [ [ "#atac_uuid = '0fc44318-b802-474e-8199-f3b6d708eb6f'\n#atac = Document(os.path.expanduser('~/proj/encode3-curation/Wold_Lab_ATAC_Seq_protocol_December_2016.pdf'),\n# 'general protocol',\n# 'ATAC-Seq experiment protocol for Wold lab',\n# )\n#body = atac.create_if_needed(server, atac_uuid)\n#print(body['@id'])", "_____no_output_____" ] ], [ [ "# Submit Annotations", "_____no_output_____" ] ], [ [ "#sheet = gcat.get_file(spreadsheet_name, fmt='pandas_excel')\n#annotations = sheet.parse('Annotations', header=0)\n#created = server.post_sheet('/annotations/', annotations, verbose=True, dry_run=True)\n#print(len(created))", "_____no_output_____" ], [ "#if created:\n# annotations.to_excel('/tmp/annotations.xlsx', index=False)", "_____no_output_____" ] ], [ [ "# Register Biosamples", "_____no_output_____" ] ], [ [ "book = gcat.get_file(spreadsheet_name, fmt='pandas_excel')\nbiosample = book.parse('Biosamples', header=0)\ncreated = server.post_sheet('/biosamples/', biosample, \n verbose=True, \n dry_run=True, \n validator=validator)\nprint(len(created))", "_____no_output_____" ], [ "if created:\n biosample.to_excel('/dev/shm/biosamples.xlsx', index=False)", "_____no_output_____" ] ], [ [ "# Register Libraries", "_____no_output_____" ] ], [ [ "print(spreadsheet_name)\nbook = gcat.get_file(spreadsheet_name, fmt='pandas_excel')\nlibraries = book.parse('Libraries', header=0)\ncreated = server.post_sheet('/libraries/', libraries, verbose=True, dry_run=True, validator=validator)\nprint(len(created))", "_____no_output_____" ], [ "if created:\n libraries.to_excel('/dev/shm/libraries.xlsx', index=False)", "_____no_output_____" ] ], [ [ "# Register Experiments", "_____no_output_____" ] ], [ [ "print(server.server)\nbook = gcat.get_file(spreadsheet_name, fmt='pandas_excel')\nexperiments = book.parse('Experiments', header=0)\ncreated = server.post_sheet('/experiments/', experiments, verbose=True, dry_run=False, validator=validator)\nprint(len(created))", "_____no_output_____" ], [ "if created:\n experiments.to_excel('/dev/shm/experiments.xlsx', index=False)", "_____no_output_____" ] ], [ [ "# Register Replicates", "_____no_output_____" ] ], [ [ "print(server.server)\nprint(spreadsheet_name)\nbook = gcat.get_file(spreadsheet_name, fmt='pandas_excel')\nreplicates = book.parse('Replicates', header=0)\ncreated = server.post_sheet('/replicates/', replicates, verbose=True, dry_run=True, validator=validator)\nprint(len(created))", "_____no_output_____" ], [ "if created:\n replicates.to_excel('/dev/shm/replicates.xlsx', index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d039376ee9ede5ea2d31182d9002772219773702
40,727
ipynb
Jupyter Notebook
KNNProjectSid.ipynb
SidSachdev/KNN-ML-
0b4b011faf1b75802ec8f9c24e85b140ada02e61
[ "Apache-2.0" ]
null
null
null
KNNProjectSid.ipynb
SidSachdev/KNN-ML-
0b4b011faf1b75802ec8f9c24e85b140ada02e61
[ "Apache-2.0" ]
null
null
null
KNNProjectSid.ipynb
SidSachdev/KNN-ML-
0b4b011faf1b75802ec8f9c24e85b140ada02e61
[ "Apache-2.0" ]
null
null
null
61.243609
23,304
0.733322
[ [ [ "import pandas as pd \nimport numpy as np", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimport seaborn as sns", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ], [ "data = pd.read_csv(\"KNN_Project_Data\")", "_____no_output_____" ], [ "data.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1000 entries, 0 to 999\nData columns (total 11 columns):\nXVPM 1000 non-null float64\nGWYH 1000 non-null float64\nTRAT 1000 non-null float64\nTLLZ 1000 non-null float64\nIGGA 1000 non-null float64\nHYKR 1000 non-null float64\nEDFS 1000 non-null float64\nGUUB 1000 non-null float64\nMGJM 1000 non-null float64\nJHZC 1000 non-null float64\nTARGET CLASS 1000 non-null int64\ndtypes: float64(10), int64(1)\nmemory usage: 86.0 KB\n" ], [ "data.head()", "_____no_output_____" ], [ "from sklearn.preprocessing import StandardScaler", "_____no_output_____" ], [ "scaler = StandardScaler()", "_____no_output_____" ], [ "scaler", "_____no_output_____" ], [ "scaler.fit(data.drop('TARGET CLASS',axis=1))", "_____no_output_____" ], [ "scaled_features = scaler.transform(data.drop('TARGET CLASS',axis=1))", "_____no_output_____" ], [ "df_feat = pd.DataFrame(scaled_features,columns=data.columns[:-1])\ndf_feat.head()", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "X_train, X_test, y_train, y_test = train_test_split(scaled_features, data['TARGET CLASS'], test_size=0.3, random_state=101)", "_____no_output_____" ], [ "from sklearn.neighbors import KNeighborsClassifier", "_____no_output_____" ], [ "knn = KNeighborsClassifier(n_neighbors=1)", "_____no_output_____" ], [ "knn.fit(X_train,y_train)", "_____no_output_____" ], [ "pred = knn.predict(X_test)", "_____no_output_____" ], [ "from sklearn.metrics import classification_report,confusion_matrix", "_____no_output_____" ], [ "print(confusion_matrix(y_test,pred))", "[[109 43]\n [ 41 107]]\n" ], [ "print(classification_report(y_test,pred))", " precision recall f1-score support\n\n 0 0.73 0.72 0.72 152\n 1 0.71 0.72 0.72 148\n\navg / total 0.72 0.72 0.72 300\n\n" ], [ "error_rate = []\n\n# Will take some time\nfor i in range(1,40):\n \n knn = KNeighborsClassifier(n_neighbors=i)\n knn.fit(X_train,y_train)\n pred_i = knn.predict(X_test)\n error_rate.append(np.mean(pred_i != y_test))", "_____no_output_____" ], [ "plt.figure(figsize=(10,6))\nplt.plot(range(1,40),error_rate,color='blue', linestyle='dashed', marker='o',\n markerfacecolor='red', markersize=10)\nplt.title('Error Rate vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Error Rate')", "_____no_output_____" ], [ "knn = KNeighborsClassifier(n_neighbors=30)\n\nknn.fit(X_train,y_train)\npred = knn.predict(X_test)\n\nprint('WITH K=1')\nprint('\\n')\nprint(confusion_matrix(y_test,pred))\nprint('\\n')\nprint(classification_report(y_test,pred))", "WITH K=1\n\n\n[[124 28]\n [ 24 124]]\n\n\n precision recall f1-score support\n\n 0 0.84 0.82 0.83 152\n 1 0.82 0.84 0.83 148\n\navg / total 0.83 0.83 0.83 300\n\n" ] ] ]
[ "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" ] ]
d03958f3c69d69c53b73fc1f3d0d831115668f26
639,896
ipynb
Jupyter Notebook
Setup Bayesian Framework - Fragility.ipynb
adam2392/bayesianfragility
2fba14cbd1a30191f2214caab655194a3006ac04
[ "Apache-2.0" ]
null
null
null
Setup Bayesian Framework - Fragility.ipynb
adam2392/bayesianfragility
2fba14cbd1a30191f2214caab655194a3006ac04
[ "Apache-2.0" ]
3
2020-03-24T15:41:31.000Z
2020-11-18T21:16:19.000Z
Setup Bayesian Framework - Fragility.ipynb
adam2392/bayesianfragility
2fba14cbd1a30191f2214caab655194a3006ac04
[ "Apache-2.0" ]
null
null
null
2,590.672065
492,540
0.962249
[ [ [ "import numpy as np\nimport pandas as pd\nimport os\nimport scipy\nimport scipy.io\n\nimport sys\n\nimport pystan\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\nnp.random.seed(1234)\n%matplotlib inline", "_____no_output_____" ], [ "patient = 'la01_ictal'\nresultsdir = os.path.join('/Volumes/ADAM LI/pydata/output/pert/', patient)\nfilename = patient + '_pertmodel.npz'\nfiletoload = os.path.join(resultsdir, filename)\n\n# load data\ndata = np.load(filetoload)\npertmats = data['pertmats']\n\nprint pertmats.shape\nprint data.keys()", "/Volumes/ADAM LI/pydata/output/pert/la01_ictal/la01_ictal_pertmodel.npz\n/Volumes/ADAM LI/pydata/converted/\n" ], [ " ### Set the font dictionaries (for plot title and axis titles)\ntitle_font = {'fontname':'Arial', 'size':'34', 'color':'black', 'weight':'normal',\n 'verticalalignment':'bottom'} # Bottom vertical alignment for more space\naxis_font = {'fontname':'Arial', 'size':'30'}\n\n# Begin Plotting\nsns.set(font_scale=2.5)\nfig, ax = plt.subplots(figsize=(30,23))\nsns.heatmap(ax=ax, data=pertmats, cmap=plt.cm.jet, cbar=True, \n cbar_kws={'label': 'Fragility Metric'})\nax.set_title(patient + ' Fragility Heatmap', **title_font)\n", "_____no_output_____" ], [ "perturbation_code = \"\"\"\ndata {\n int<lower=0> N; // number of contacts\n int<lower=0> T; // number of time windows\n real matrix pert[N, T];\n}\nparameters {\n real<lower=0, upper=1> p[N]; // parameters of probability in EZ\n}\nmodel {\n p ~ normal(0.5, 1); // prior on parameter EZ probabilities\n pert ~ normal(0.25, 0.5); // prior on observations perturbation distribution\n \n for (chan in 1:N) {\n fragility[chan] ~ model(p, std)\n }\n}\n\"\"\"\n\n# schools_dat = {'J': 8,\n# 'y': [28, 8, -3, 7, -1, 1, 18, 12],\n# 'sigma': [15, 10, 16, 11, 9, 11, 10, 18]}\n\n# sm = pystan.StanModel(model_code=schools_code)\n# fit = sm.sampling(data=schools_dat, iter=1000, chains=4)\n\nprint fit\nfit.plot()", "Inference for Stan model: anon_model_cbe9cd2f1e5ab5d1c7cce1f23ca970b4.\n4 chains, each with iter=1000; warmup=500; thin=1; \npost-warmup draws per chain=500, total post-warmup draws=2000.\n\n mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat\nmu 8.16 0.13 4.78 -0.71 4.96 8.01 11.1 18.29 1294.0 1.0\ntau 6.62 0.17 5.28 0.26 2.53 5.45 9.33 20.18 926.0 1.0\neta[0] 0.38 0.02 0.92 -1.49 -0.22 0.4 1.02 2.12 2000.0 1.0\neta[1] 0.01 0.02 0.87 -1.73 -0.54 7.7e-3 0.58 1.73 2000.0 1.0\neta[2] -0.17 0.02 0.95 -2.08 -0.79 -0.17 0.49 1.67 2000.0 1.0\neta[3] -0.04 0.02 0.86 -1.69 -0.61 -0.05 0.53 1.65 2000.0 1.0\neta[4] -0.38 0.02 0.88 -2.02 -0.96 -0.42 0.16 1.45 2000.0 1.0\neta[5] -0.25 0.02 0.89 -2.02 -0.81 -0.25 0.33 1.51 2000.0 1.0\neta[6] 0.33 0.02 0.87 -1.46 -0.24 0.35 0.91 2.08 2000.0 1.0\neta[7] 0.07 0.02 0.92 -1.74 -0.53 0.07 0.65 1.97 2000.0 1.0\ntheta[0] 11.48 0.21 8.2 -2.08 6.25 10.37 15.87 31.44 1493.0 1.0\ntheta[1] 7.97 0.14 6.29 -4.61 3.97 7.83 11.88 21.02 2000.0 1.0\ntheta[2] 6.47 0.19 7.88 -11.5 2.15 6.86 11.32 21.46 1722.0 1.0\ntheta[3] 7.65 0.14 6.42 -5.85 3.74 7.7 11.71 21.11 2000.0 1.0\ntheta[4] 5.08 0.14 6.33 -8.27 1.31 5.54 9.27 16.44 2000.0 1.0\ntheta[5] 6.11 0.15 6.77 -8.29 2.25 6.52 10.34 18.67 2000.0 1.0\ntheta[6] 10.7 0.15 6.66 -1.37 6.46 10.09 14.68 25.49 2000.0 1.0\ntheta[7] 8.73 0.18 7.89 -6.63 4.18 8.55 12.95 25.0 2000.0 1.0\nlp__ -4.78 0.1 2.71 -10.99 -6.33 -4.54 -2.81 -0.33 668.0 1.0\n\nSamples were drawn using NUTS at Sat Dec 9 14:04:41 2017.\nFor each parameter, n_eff is a crude measure of effective sample size,\nand Rhat is the potential scale reduction factor on split chains (at \nconvergence, Rhat=1).\n" ], [ "la = fit.extract(permuted=True) # return a dictionary of arrays\nmu = la['mu']\n\n## return an array of three dimensions: iterations, chains, parameters\na = fit.extract(permuted=False)", "WARNING:root:`dtypes` ignored when `permuted` is False.\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
d0396ae98de80530f81e3080cca28197423b61c6
133,663
ipynb
Jupyter Notebook
keras/170711-music-tagging.ipynb
aidiary/notebooks
1bb9338441e12ee52e287ea40179a5f271a5a2be
[ "MIT" ]
3
2018-02-03T09:33:51.000Z
2020-11-23T08:46:43.000Z
keras/170711-music-tagging.ipynb
aidiary/notebooks
1bb9338441e12ee52e287ea40179a5f271a5a2be
[ "MIT" ]
null
null
null
keras/170711-music-tagging.ipynb
aidiary/notebooks
1bb9338441e12ee52e287ea40179a5f271a5a2be
[ "MIT" ]
null
null
null
58.038645
27,484
0.551267
[ [ [ "# End-to-end learning for music audio\n\n- http://qiita.com/himono/items/a94969e35fa8d71f876c", "_____no_output_____" ], [ "```\n# データのダウンロード\nwget http://mi.soi.city.ac.uk/datasets/magnatagatune/mp3.zip.001\nwget http://mi.soi.city.ac.uk/datasets/magnatagatune/mp3.zip.002\nwget http://mi.soi.city.ac.uk/datasets/magnatagatune/mp3.zip.003\n\n# 結合\ncat data/mp3.zip.* > data/music.zip\n\n# 解凍\nunzip data/music.zip -d music\n```", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport os\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## MP3ファイルのロード", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom pydub import AudioSegment\n\ndef mp3_to_array(file):\n # MP3 => RAW\n song = AudioSegment.from_mp3(file)\n song_arr = np.fromstring(song._data, np.int16)\n return song_arr", "_____no_output_____" ], [ "%ls data/music/1/ambient_teknology-phoenix-01-ambient_teknology-0-29.mp3", "data/music/1/ambient_teknology-phoenix-01-ambient_teknology-0-29.mp3\r\n" ], [ "file = 'data/music/1/ambient_teknology-phoenix-01-ambient_teknology-0-29.mp3'\nsong = mp3_to_array(file)", "_____no_output_____" ], [ "plt.plot(song)", "_____no_output_____" ] ], [ [ "## 楽曲タグデータをロード\n\n- ランダムに3000曲を抽出\n- よく使われるタグ50個を抽出\n- 各曲には複数のタグがついている", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ntags_df = pd.read_csv('data/annotations_final.csv', delim_whitespace=True)\n# 全体をランダムにサンプリング\ntags_df = tags_df.sample(frac=1)\n# 最初の3000曲を使う\ntags_df = tags_df[:3000]\n\ntags_df", "_____no_output_____" ], [ "top50_tags = tags_df.iloc[:, 1:189].sum().sort_values(ascending=False).index[:50].tolist()\ny = tags_df[top50_tags].values\ny", "_____no_output_____" ] ], [ [ "## 楽曲データをロード\n\n- tags_dfのmp3_pathからファイルパスを取得\n- mp3_to_array()でnumpy arrayをロード\n- (samples, features, channels) になるようにreshape\n- 音声波形は1次元なのでchannelsは1\n- 訓練データはすべて同じサイズなのでfeaturesは同じになるはず(パディング不要)", "_____no_output_____" ] ], [ [ "files = tags_df.mp3_path.values\nfiles = [os.path.join('data', 'music', x) for x in files]", "_____no_output_____" ], [ "X = np.array([mp3_to_array(file) for file in files])\nX = X.reshape(X.shape[0], X.shape[1], 1)", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ] ], [ [ "## 訓練データとテストデータに分割", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\nrandom_state = 42\n\ntrain_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.2, random_state=random_state)", "_____no_output_____" ], [ "print(train_x.shape)\nprint(test_x.shape)\nprint(train_y.shape)\nprint(test_y.shape)", "(2400, 465984, 1)\n(600, 465984, 1)\n(2400, 50)\n(600, 50)\n" ], [ "plt.plot(train_x[0])", "_____no_output_____" ], [ "np.save('train_x.npy', train_x)\nnp.save('test_x.npy', test_x)\nnp.save('train_y.npy', train_y)\nnp.save('test_y.npy', test_y)", "_____no_output_____" ] ], [ [ "## 訓練", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten, Input, Conv1D, MaxPooling1D\nfrom keras.callbacks import CSVLogger, ModelCheckpoint\n\ntrain_x = np.load('train_x.npy')\ntrain_y = np.load('train_y.npy')\n\ntest_x = np.load('test_x.npy')\ntest_y = np.load('test_y.npy')\n\nprint(train_x.shape)\nprint(train_y.shape)\nprint(test_x.shape)\nprint(test_y.shape)\n\nfeatures = train_x.shape[1]\n\nx_inputs = Input(shape=(features, 1), name='x_inputs')\nx = Conv1D(128, 256, strides=256, padding='valid', activation='relu')(x_inputs) # strided conv\nx = Conv1D(32, 8, activation='relu')(x)\nx = MaxPooling1D(4)(x)\nx = Conv1D(32, 8, activation='relu')(x)\nx = MaxPooling1D(4)(x)\nx = Conv1D(32, 8, activation='relu')(x)\nx = MaxPooling1D(4)(x)\nx = Conv1D(32, 8, activation='relu')(x)\nx = MaxPooling1D(4)(x)\nx = Flatten()(x)\nx = Dense(100, activation='relu')(x)\nx_outputs = Dense(50, activation='sigmoid', name='x_outputs')(x)\n\nmodel = Model(inputs=x_inputs, outputs=x_outputs)\nmodel.compile(optimizer='adam',\n loss='categorical_crossentropy')\n\nlogger = CSVLogger('history.log')\ncheckpoint = ModelCheckpoint(\n 'model.{epoch:02d}-{val_loss:.3f}.h5',\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n mode='auto')\n\nmodel.fit(train_x, train_y, batch_size=600, epochs=50,\n validation_data=[test_x, test_y],\n callbacks=[logger, checkpoint])", "_____no_output_____" ] ], [ [ "## 予測\n\n- taggerは複数のタグを出力するのでevaluate()ではダメ?", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom keras.models import load_model\nfrom sklearn.metrics import roc_auc_score\n\ntest_x = np.load('test_x.npy')\ntest_y = np.load('test_y.npy')\n\nmodel = load_model('model.22-9.187-0.202.h5')\n\npred_y = model.predict(test_x, batch_size=50)\nprint(roc_auc_score(test_y, pred_y))\nprint(model.evaluate(test_x, test_y))", "Using TensorFlow backend.\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d03971e3154a0799cad9ad471c2a5c46614b06d3
34,736
ipynb
Jupyter Notebook
DataCrunch.ipynb
sweg44/datacrunch-notebooks
175e32107877d3c7c5249e39cc52dee7db16f6de
[ "MIT" ]
null
null
null
DataCrunch.ipynb
sweg44/datacrunch-notebooks
175e32107877d3c7c5249e39cc52dee7db16f6de
[ "MIT" ]
null
null
null
DataCrunch.ipynb
sweg44/datacrunch-notebooks
175e32107877d3c7c5249e39cc52dee7db16f6de
[ "MIT" ]
null
null
null
39.607754
172
0.428086
[ [ [ "import pandas as pd\nimport numpy as np\n\nimport requests\n\nimport tensorflow as tf\nimport autokeras as ak\nimport kerastuner\nimport tensorflow_addons as tfa\n\nRS = 69420", "_____no_output_____" ], [ "# Data Download (may take a few minutes depending on your network)\ntrain_datalink_X = 'https://tournament.datacrunch.com/data/X_train.csv' \ntrain_datalink_y = 'https://tournament.datacrunch.com/data/y_train.csv' \nhackathon_data_link = 'https://tournament.datacrunch.com/data/X_test.csv' ", "_____no_output_____" ], [ "# Data for training\ntrain_data = pd.read_csv(train_datalink_X)\n# Data for which you will submit your prediction\ntest_data = pd.read_csv(hackathon_data_link)\n# Targets to be predicted\ntrain_targets = pd.read_csv(train_datalink_y)", "_____no_output_____" ], [ "train_data", "_____no_output_____" ], [ "#If you don't want to work with time series (Later going to produce new models for each moon)\ntrain_data = train_data.drop(columns=['Moons', 'id'])\ntest_data = test_data.drop(columns=['Moons', 'id'])", "_____no_output_____" ], [ "X, y = train_data, train_targets\n\nX.shape, y.shape", "_____no_output_____" ], [ "from sklearn.model_selection import TimeSeriesSplit\ntscv = TimeSeriesSplit()\nprint(tscv)\n\nfor train_index, test_index in tscv.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n y_train, y_test = y.iloc[train_index], y.iloc[test_index]", "TimeSeriesSplit(max_train_size=None, n_splits=5)\nTRAIN: [ 0 1 2 ... 15177 15178 15179] TEST: [15180 15181 15182 ... 30356 30357 30358]\nTRAIN: [ 0 1 2 ... 30356 30357 30358] TEST: [30359 30360 30361 ... 45535 45536 45537]\nTRAIN: [ 0 1 2 ... 45535 45536 45537] TEST: [45538 45539 45540 ... 60714 60715 60716]\nTRAIN: [ 0 1 2 ... 60714 60715 60716] TEST: [60717 60718 60719 ... 75893 75894 75895]\nTRAIN: [ 0 1 2 ... 75893 75894 75895] TEST: [75896 75897 75898 ... 91072 91073 91074]\n" ], [ "X_train.shape, y_train.shape, y_test.shape, X_test.shape", "_____no_output_____" ], [ "from sklearn.preprocessing import MinMaxScaler\nsc = MinMaxScaler()\n\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)", "_____no_output_____" ], [ "# Initialize the structured data classifier.\nrmse_metrics = tf.metrics.RootMeanSquaredError()\nclf = ak.StructuredDataRegressor(overwrite=False,\n project_name='DataCrunchAK',\n directory=r\"D:\\DataCrunch\",\n metrics=[rmse_metrics],\n objective=kerastuner.Objective(\"val_loss\", direction='min'),\n seed=RS,\n max_trials=100)", "INFO:tensorflow:Reloading Oracle from existing project D:\\DataCrunch\\DataCrunchAK\\oracle.json\nINFO:tensorflow:Reloading Tuner from D:\\DataCrunch\\DataCrunchAK\\tuner0.json\n" ], [ "from tensorflow.keras.callbacks import EarlyStopping\nes = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)", "_____no_output_____" ], [ "%%time\nclf.fit(X_train, y_train,\n epochs=75,\n batch_size=512,\n validation_split=0.2,\n callbacks=[es],\n verbose=1)", "Trial 10 Complete [00h 02m 12s]\nval_loss: 0.09039796143770218\n\nBest val_loss So Far: 0.08909150958061218\nTotal elapsed time: 00h 11m 26s\n\nSearch: Running Trial #11\n\nHyperparameter |Value |Best Value So Far \nstructured_data...|True |True \nstructured_data...|False |False \nstructured_data...|3 |3 \nstructured_data...|32 |32 \nstructured_data...|0 |0 \nstructured_data...|32 |32 \nregression_head...|0 |0 \noptimizer |sgd |adam \nlearning_rate |0.001 |0.001 \nstructured_data...|32 |32 \n\nEpoch 1/75\n120/120 [==============================] - 2s 14ms/step - loss: 0.2303 - root_mean_squared_error: 0.4178 - val_loss: 0.1776 - val_root_mean_squared_error: 0.4215\nEpoch 2/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1846 - root_mean_squared_error: 0.4296 - val_loss: 0.1628 - val_root_mean_squared_error: 0.4035\nEpoch 3/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1700 - root_mean_squared_error: 0.4122 - val_loss: 0.1567 - val_root_mean_squared_error: 0.3959\nEpoch 4/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1634 - root_mean_squared_error: 0.4043 - val_loss: 0.1529 - val_root_mean_squared_error: 0.3910\nEpoch 5/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1592 - root_mean_squared_error: 0.3990 - val_loss: 0.1497 - val_root_mean_squared_error: 0.3870\nEpoch 6/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1559 - root_mean_squared_error: 0.3949 - val_loss: 0.1470 - val_root_mean_squared_error: 0.3834\nEpoch 7/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1531 - root_mean_squared_error: 0.3913 - val_loss: 0.1445 - val_root_mean_squared_error: 0.3802\nEpoch 8/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1506 - root_mean_squared_error: 0.3881 - val_loss: 0.1423 - val_root_mean_squared_error: 0.3773\nEpoch 9/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1484 - root_mean_squared_error: 0.3852 - val_loss: 0.1403 - val_root_mean_squared_error: 0.3746\nEpoch 10/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1464 - root_mean_squared_error: 0.3826 - val_loss: 0.1385 - val_root_mean_squared_error: 0.3722\nEpoch 11/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1445 - root_mean_squared_error: 0.3802 - val_loss: 0.1369 - val_root_mean_squared_error: 0.3700\nEpoch 12/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1429 - root_mean_squared_error: 0.3780 - val_loss: 0.1354 - val_root_mean_squared_error: 0.3679\nEpoch 13/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1414 - root_mean_squared_error: 0.3760 - val_loss: 0.1340 - val_root_mean_squared_error: 0.3660\nEpoch 14/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1400 - root_mean_squared_error: 0.3742 - val_loss: 0.1327 - val_root_mean_squared_error: 0.3643\nEpoch 15/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1387 - root_mean_squared_error: 0.3725 - val_loss: 0.1315 - val_root_mean_squared_error: 0.3626\nEpoch 16/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1376 - root_mean_squared_error: 0.3709 - val_loss: 0.1304 - val_root_mean_squared_error: 0.3611\nEpoch 17/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1365 - root_mean_squared_error: 0.3694 - val_loss: 0.1294 - val_root_mean_squared_error: 0.3597\nEpoch 18/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1355 - root_mean_squared_error: 0.3680 - val_loss: 0.1284 - val_root_mean_squared_error: 0.3584\nEpoch 19/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1345 - root_mean_squared_error: 0.3668 - val_loss: 0.1275 - val_root_mean_squared_error: 0.3571\nEpoch 20/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1336 - root_mean_squared_error: 0.3656 - val_loss: 0.1267 - val_root_mean_squared_error: 0.3559\nEpoch 21/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1328 - root_mean_squared_error: 0.3644 - val_loss: 0.1259 - val_root_mean_squared_error: 0.3548\nEpoch 22/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1320 - root_mean_squared_error: 0.3633 - val_loss: 0.1251 - val_root_mean_squared_error: 0.3537\nEpoch 23/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1313 - root_mean_squared_error: 0.3623 - val_loss: 0.1244 - val_root_mean_squared_error: 0.3527\nEpoch 24/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1306 - root_mean_squared_error: 0.3614 - val_loss: 0.1237 - val_root_mean_squared_error: 0.3518\nEpoch 25/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1299 - root_mean_squared_error: 0.3604 - val_loss: 0.1231 - val_root_mean_squared_error: 0.3509\nEpoch 26/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1293 - root_mean_squared_error: 0.3596 - val_loss: 0.1225 - val_root_mean_squared_error: 0.3500\nEpoch 27/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1287 - root_mean_squared_error: 0.3587 - val_loss: 0.1219 - val_root_mean_squared_error: 0.3492\nEpoch 28/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1281 - root_mean_squared_error: 0.3580 - val_loss: 0.1214 - val_root_mean_squared_error: 0.3484\nEpoch 29/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1276 - root_mean_squared_error: 0.3572 - val_loss: 0.1209 - val_root_mean_squared_error: 0.3476\nEpoch 30/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1271 - root_mean_squared_error: 0.3565 - val_loss: 0.1203 - val_root_mean_squared_error: 0.3469\nEpoch 31/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1266 - root_mean_squared_error: 0.3558 - val_loss: 0.1199 - val_root_mean_squared_error: 0.3462\nEpoch 32/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1261 - root_mean_squared_error: 0.3551 - val_loss: 0.1194 - val_root_mean_squared_error: 0.3456\nEpoch 33/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1257 - root_mean_squared_error: 0.3545 - val_loss: 0.1190 - val_root_mean_squared_error: 0.3449\nEpoch 34/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1253 - root_mean_squared_error: 0.3539 - val_loss: 0.1185 - val_root_mean_squared_error: 0.3443\nEpoch 35/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1248 - root_mean_squared_error: 0.3533 - val_loss: 0.1181 - val_root_mean_squared_error: 0.3437\nEpoch 36/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1244 - root_mean_squared_error: 0.3527 - val_loss: 0.1177 - val_root_mean_squared_error: 0.3431\nEpoch 37/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1241 - root_mean_squared_error: 0.3522 - val_loss: 0.1174 - val_root_mean_squared_error: 0.3426\nEpoch 38/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1237 - root_mean_squared_error: 0.3517 - val_loss: 0.1170 - val_root_mean_squared_error: 0.3421\nEpoch 39/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1233 - root_mean_squared_error: 0.3512 - val_loss: 0.1167 - val_root_mean_squared_error: 0.3415\nEpoch 40/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1230 - root_mean_squared_error: 0.3507 - val_loss: 0.1163 - val_root_mean_squared_error: 0.3410\nEpoch 41/75\n120/120 [==============================] - 1s 11ms/step - loss: 0.1227 - root_mean_squared_error: 0.3502 - val_loss: 0.1160 - val_root_mean_squared_error: 0.3406\nEpoch 42/75\n120/120 [==============================] - 1s 12ms/step - loss: 0.1224 - root_mean_squared_error: 0.3498 - val_loss: 0.1157 - val_root_mean_squared_error: 0.3401\nEpoch 43/75\n" ], [ "model = clf.export_model()\nmodel.summary()", "_____no_output_____" ], [ "model.evaluate(X_test, y_test)", "_____no_output_____" ], [ "preds = model.predict(test_data)", "_____no_output_____" ], [ "train_targets", "_____no_output_____" ], [ "sc_preds = MinMaxScaler(feature_range=(0.001, 0.999))\npreds_sc = sc_preds.fit_transform(preds)", "_____no_output_____" ], [ "prediction = pd.DataFrame(columns=['target_r', 'target_g', 'target_b'])\nprediction['target_r'] = preds_sc[:, 0]\nprediction['target_g'] = preds_sc[:, 1]\nprediction['target_b'] = preds_sc[:, 2]", "_____no_output_____" ], [ "prediction", "_____no_output_____" ], [ "# prediction.to_csv('1051.csv')", "_____no_output_____" ], [ "prediction.plot(kind='box')", "_____no_output_____" ], [ "API_KEY = 'F1awQwoH9yW7AgG18Nf8XlZNW9xp23b8vY2hHgMxdDimd3u7Z6Q5brcLydHR'\n\nr = requests.post(\"https://tournament.datacrunch.com/api/submission\",\n files = {\n \"file\": (\"x\", prediction.to_csv().encode('ascii'))\n },\n data = {\n \"apiKey\": API_KEY\n },\n)\n\nif r.status_code == 200:\n print(\"Submission submitted :)\")\nelif r.status_code == 423:\n print(\"ERR: Submissions are close\")\n print(\"You can only submit during rounds eg: Friday 7pm GMT+1 to Sunday midnight GMT+1.\")\n print(\"Or the server is currently crunching the submitted files, please wait some time before retrying.\")\nelif r.status_code == 422:\n print(\"ERR: API Key is missing or empty\")\n print(\"Did you forget to fill the API_KEY variable?\")\nelif r.status_code == 404:\n print(\"ERR: Unknown API Key\")\n print(\"You should check that the provided API key is valid and is the same as the one you've received by email.\")\nelif r.status_code == 400:\n print(\"ERR: The file must not be empty\")\n print(\"You have send a empty file.\")\nelif r.status_code == 401:\n print(\"ERR: Your email hasn't been verified\")\n print(\"Please verify your email or contact a cruncher.\")\nelif r.status_code == 429:\n print(\"ERR: Too many submissions\")\nelse:\n print(\"ERR: Server returned: \" + str(r.status_code))\n print(\"Ouch! It seems that we were not expecting this kind of result from the server, if the probleme persist, contact a cruncher.\")", "_____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" ] ]
d039750fdb84abb2d31a0d0446b0e7608a00c90d
31,420
ipynb
Jupyter Notebook
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
3a47a51876f2226c2975b92ffb65b2d1d2bf5054
[ "MIT" ]
null
null
null
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
3a47a51876f2226c2975b92ffb65b2d1d2bf5054
[ "MIT" ]
null
null
null
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
3a47a51876f2226c2975b92ffb65b2d1d2bf5054
[ "MIT" ]
null
null
null
47.896341
10,036
0.681891
[ [ [ "import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "df1 = pd.read_csv('data/Salary_Data.csv')", "_____no_output_____" ], [ "df1.head()", "_____no_output_____" ], [ "df1.shape", "_____no_output_____" ], [ "sns.scatterplot(data=df1,x='YearsExperience',y='Salary')\nplt.show()", "_____no_output_____" ], [ "y = df1.iloc[:,1].values\ny", "_____no_output_____" ], [ "x = df1.iloc[:,:1].values\nx", "_____no_output_____" ] ], [ [ "# Splitting data for Training and Testing", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "X_train,X_test,Y_train,Y_test = train_test_split(x,y,train_size=0.7,random_state=0)", "_____no_output_____" ], [ "X_train.shape", "_____no_output_____" ], [ "X_test.shape", "_____no_output_____" ], [ "Y_train.shape", "_____no_output_____" ], [ "Y_test.shape", "_____no_output_____" ] ], [ [ "# Creating a ML Model", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression", "_____no_output_____" ], [ "regressor = LinearRegression()", "_____no_output_____" ], [ "regressor.fit(X_train,Y_train)", "_____no_output_____" ], [ "y_predict = regressor.predict(X_test)", "_____no_output_____" ], [ "y_predict", "_____no_output_____" ], [ "Y_test", "_____no_output_____" ] ], [ [ "# Model Coefficients ", "_____no_output_____" ] ], [ [ "regressor.intercept_", "_____no_output_____" ], [ "regressor.coef_", "_____no_output_____" ] ], [ [ "# Equation of Line --> y = 9360.26* x + 26777.39", "_____no_output_____" ], [ "# Model Evaluation", "_____no_output_____" ] ], [ [ "from sklearn import metrics", "_____no_output_____" ], [ "MAE = metrics.mean_absolute_error(Y_test,y_predict)\nMAE", "_____no_output_____" ], [ "MSE = metrics.mean_squared_error(Y_test,y_predict)\nMSE", "_____no_output_____" ], [ "RMSE = np.sqrt(MSE)\nRMSE", "_____no_output_____" ], [ "R2 = metrics.r2_score(Y_test,y_predict)\nR2", "_____no_output_____" ] ], [ [ "# Hands on Task", "_____no_output_____" ] ], [ [ "df1 = pd.read_csv('data/auto-mpg.csv')\ndf1.head()", "_____no_output_____" ] ], [ [ "# HandsOn - TASK\n\n### 1. Create a Machine Learning Model for predicting Mpg from all the input features in the data.\n\n1. EDA\n2. Data Clearning & Pre-Processing\n3. Build ML Model\n4. Model Evaluation.\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d0397a33dafe481957e294a0d63c253492d459f7
2,807
ipynb
Jupyter Notebook
digital-image-processing/notebooks/segmentation/plot_marked_watershed.ipynb
sinamedialab/courses
720a78ebf4b4fb77f57a73870480233646f9a51d
[ "MIT" ]
null
null
null
digital-image-processing/notebooks/segmentation/plot_marked_watershed.ipynb
sinamedialab/courses
720a78ebf4b4fb77f57a73870480233646f9a51d
[ "MIT" ]
null
null
null
digital-image-processing/notebooks/segmentation/plot_marked_watershed.ipynb
sinamedialab/courses
720a78ebf4b4fb77f57a73870480233646f9a51d
[ "MIT" ]
null
null
null
51.981481
1,349
0.636979
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\n# Markers for watershed transform\n\nThe watershed is a classical algorithm used for **segmentation**, that\nis, for separating different objects in an image.\n\nHere a marker image is built from the region of low gradient inside the image.\nIn a gradient image, the areas of high values provide barriers that help to\nsegment the image.\nUsing markers on the lower values will ensure that the segmented objects are\nfound.\n\nSee Wikipedia_ for more details on the algorithm.\n\n", "_____no_output_____" ] ], [ [ "from scipy import ndimage as ndi\nimport matplotlib.pyplot as plt\n\nfrom skimage.morphology import disk\nfrom skimage.segmentation import watershed\nfrom skimage import data\nfrom skimage.filters import rank\nfrom skimage.util import img_as_ubyte\n\n\nimage = img_as_ubyte(data.camera())\n\n# denoise image\ndenoised = rank.median(image, disk(2))\n\n# find continuous region (low gradient -\n# where less than 10 for this image) --> markers\n# disk(5) is used here to get a more smooth image\nmarkers = rank.gradient(denoised, disk(5)) < 10\nmarkers = ndi.label(markers)[0]\n\n# local gradient (disk(2) is used to keep edges thin)\ngradient = rank.gradient(denoised, disk(2))\n\n# process the watershed\nlabels = watershed(gradient, markers)\n\n# display results\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8),\n sharex=True, sharey=True)\nax = axes.ravel()\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].set_title(\"Original\")\n\nax[1].imshow(gradient, cmap=plt.cm.nipy_spectral)\nax[1].set_title(\"Local Gradient\")\n\nax[2].imshow(markers, cmap=plt.cm.nipy_spectral)\nax[2].set_title(\"Markers\")\n\nax[3].imshow(image, cmap=plt.cm.gray)\nax[3].imshow(labels, cmap=plt.cm.nipy_spectral, alpha=.7)\nax[3].set_title(\"Segmented\")\n\nfor a in ax:\n a.axis('off')\n\nfig.tight_layout()\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ] ]
d03984e821a2af854e8d1119cd6f74962fa85b58
5,133
ipynb
Jupyter Notebook
bronze/B07_Probabilistic_Bit_Solutions.ipynb
KuantumTurkiye/bronze
b3e7dd06eab8e90c3584fc5b94a53ebb2f2555e4
[ "Apache-2.0", "CC-BY-4.0" ]
1
2021-01-31T12:53:57.000Z
2021-01-31T12:53:57.000Z
bronze/B07_Probabilistic_Bit_Solutions.ipynb
KuantumTurkiye/bronze
b3e7dd06eab8e90c3584fc5b94a53ebb2f2555e4
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
bronze/B07_Probabilistic_Bit_Solutions.ipynb
KuantumTurkiye/bronze
b3e7dd06eab8e90c3584fc5b94a53ebb2f2555e4
[ "Apache-2.0", "CC-BY-4.0" ]
1
2021-01-24T20:29:18.000Z
2021-01-24T20:29:18.000Z
39.790698
309
0.51354
[ [ [ "<table> <tr>\n <td style=\"background-color:#ffffff;\">\n <a href=\"http://qworld.lu.lv\" target=\"_blank\"><img src=\"..\\images\\qworld.jpg\" width=\"25%\" align=\"left\"> </a></td>\n <td style=\"background-color:#ffffff;vertical-align:bottom;text-align:right;\">\n prepared by <a href=\"http://abu.lu.lv\" target=\"_blank\">Abuzer Yakaryilmaz</a> (<a href=\"http://qworld.lu.lv/index.php/qlatvia/\" target=\"_blank\">QLatvia</a>)\n </td> \n</tr></table>", "_____no_output_____" ], [ "<table width=\"100%\"><tr><td style=\"color:#bbbbbb;background-color:#ffffff;font-size:11px;font-style:italic;text-align:right;\">This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. </td></tr></table>\n$ \\newcommand{\\bra}[1]{\\langle #1|} $\n$ \\newcommand{\\ket}[1]{|#1\\rangle} $\n$ \\newcommand{\\braket}[2]{\\langle #1|#2\\rangle} $\n$ \\newcommand{\\dot}[2]{ #1 \\cdot #2} $\n$ \\newcommand{\\biginner}[2]{\\left\\langle #1,#2\\right\\rangle} $\n$ \\newcommand{\\mymatrix}[2]{\\left( \\begin{array}{#1} #2\\end{array} \\right)} $\n$ \\newcommand{\\myvector}[1]{\\mymatrix{c}{#1}} $\n$ \\newcommand{\\myrvector}[1]{\\mymatrix{r}{#1}} $\n$ \\newcommand{\\mypar}[1]{\\left( #1 \\right)} $\n$ \\newcommand{\\mybigpar}[1]{ \\Big( #1 \\Big)} $\n$ \\newcommand{\\sqrttwo}{\\frac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\dsqrttwo}{\\dfrac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\onehalf}{\\frac{1}{2}} $\n$ \\newcommand{\\donehalf}{\\dfrac{1}{2}} $\n$ \\newcommand{\\hadamard}{ \\mymatrix{rr}{ \\sqrttwo & \\sqrttwo \\\\ \\sqrttwo & -\\sqrttwo }} $\n$ \\newcommand{\\vzero}{\\myvector{1\\\\0}} $\n$ \\newcommand{\\vone}{\\myvector{0\\\\1}} $\n$ \\newcommand{\\stateplus}{\\myvector{ \\sqrttwo \\\\ \\sqrttwo } } $\n$ \\newcommand{\\stateminus}{ \\myrvector{ \\sqrttwo \\\\ -\\sqrttwo } } $\n$ \\newcommand{\\myarray}[2]{ \\begin{array}{#1}#2\\end{array}} $\n$ \\newcommand{\\X}{ \\mymatrix{cc}{0 & 1 \\\\ 1 & 0} } $\n$ \\newcommand{\\I}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & 1} } $\n$ \\newcommand{\\Z}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & -1} } $\n$ \\newcommand{\\Htwo}{ \\mymatrix{rrrr}{ \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} } } $\n$ \\newcommand{\\CNOT}{ \\mymatrix{cccc}{1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 0} } $\n$ \\newcommand{\\norm}[1]{ \\left\\lVert #1 \\right\\rVert } $\n$ \\newcommand{\\pstate}[1]{ \\lceil \\mspace{-1mu} #1 \\mspace{-1.5mu} \\rfloor } $", "_____no_output_____" ], [ "<h2> <font color=\"blue\"> Solutions for </font>Probabilistic Bit</h2>", "_____no_output_____" ], [ "<a id=\"task2\"></a>\n<h3> Task 2 </h3>\n\nSuppose that Fyodor hiddenly rolls a loaded (tricky) dice with the bias \n\n$$ Pr(1):Pr(2):Pr(3):Pr(4):Pr(5):Pr(6) = 7:5:4:2:6:1 . $$\n\nRepresent your information on the result as a column vector. Remark that the size of your column should be 6.\n\nYou may use python for your calculations.", "_____no_output_____" ], [ "<h3>Solution</h3>", "_____no_output_____" ] ], [ [ "# all portions are stored in a list \nall_portions = [7,5,4,2,6,1];\n\n# let's calculate the total portion\ntotal_portion = 0\nfor i in range(6):\n total_portion = total_portion + all_portions[i]\n\nprint(\"total portion is\",total_portion)\n\n# find the weight of one portion\none_portion = 1/total_portion\nprint(\"the weight of one portion is\",one_portion)\n\nprint() # print an empty line\n# now we can calculate the probabilities of rolling 1,2,3,4,5, and 6\nfor i in range(6):\n print(\"the probability of rolling\",(i+1),\"is\",(one_portion*all_portions[i]))", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
d039a40bd0a4ce1db25035ac9d73e21ef9ace37c
32,189
ipynb
Jupyter Notebook
COLAB/DUCE.ipynb
Pritam-Patra/Discounted-Udemy-Course-Enroller
8c1366eb15eef888f463cef32cb9efe5a9060730
[ "MIT" ]
null
null
null
COLAB/DUCE.ipynb
Pritam-Patra/Discounted-Udemy-Course-Enroller
8c1366eb15eef888f463cef32cb9efe5a9060730
[ "MIT" ]
null
null
null
COLAB/DUCE.ipynb
Pritam-Patra/Discounted-Udemy-Course-Enroller
8c1366eb15eef888f463cef32cb9efe5a9060730
[ "MIT" ]
null
null
null
42.521797
209
0.415266
[ [ [ "#@title Paste the values then click run\n#@markdown <a href=\"https://techtanic.github.io/duce\" target=\"_blank\">Website</a>\nemail = \"rfrf445fr@gmail.com\" #@param {type: \"string\"}\npassword = \"1234test\" #@param {type: \"string\"}\n\nimport os\nfor index,item in enumerate([\"requests\",\"bs4\",\"html5lib\",\"colorama\",\"tqdm\",\"cloudscraper\"]):\n print(f\"installing {index}/5\")\n os.system(f\"pip3 install {item} -U\")\n\n\nfrom functools import partial\nfrom tqdm import tqdm\ntqdm = partial(tqdm, position=0, leave=True)\n\nfrom colorama import Fore, Back, Style\n\n# colors foreground text:\nfc = Fore.CYAN\nfg = Fore.GREEN\nfw = Fore.WHITE\nfr = Fore.RED\nfb = Fore.BLUE\nflb = Fore.LIGHTBLUE_EX\nfbl = Fore.BLACK\nfy = Fore.YELLOW\nfm = Fore.MAGENTA\n\n\n# colors background text:\nbc = Back.CYAN\nbg = Back.GREEN\nbw = Back.WHITE\nbr = Back.RED\nbb = Back.BLUE\nby = Back.YELLOW\nbm = Back.MAGENTA\n\n# colors style text:\nsd = Style.DIM\nsn = Style.NORMAL\nsb = Style.BRIGHT\n\n\nimport json\nimport random\nimport re\nimport threading\nimport time\nimport traceback\nfrom urllib.parse import parse_qs, unquote, urlsplit\nfrom decimal import Decimal\nimport requests\nimport cloudscraper\nfrom bs4 import BeautifulSoup as bs\n\n# DUCE-CLI\ndef remove_suffix(input_string:str, suffix:str)->str:\n if suffix and input_string.endswith(suffix):\n return input_string[: -len(suffix)]\n return input_string\n\n\ndef remove_prefix(input_string:str, prefix:str)->str:\n if prefix and input_string.startswith(prefix):\n return input_string[len(prefix) :]\n return input_string\n# Scraper\ndef discudemy():\n global du_links\n du_links = []\n big_all = []\n head = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36 Edg/89.0.774.77\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n }\n\n for page in range(1, 4):\n r = requests.get(\"https://www.discudemy.com/all/\" + str(page), headers=head)\n soup = bs(r.content, \"html5lib\")\n small_all = soup.find_all(\"section\", \"card\")\n big_all.extend(small_all)\n du_bar = tqdm(total=len(big_all), desc=\"Discudemy\")\n for index, item in enumerate(big_all):\n du_bar.update(1)\n title = item.string\n url = item[\"href\"].split(\"/\")[4]\n r = requests.get(\"https://www.discudemy.com/go/\" + url, headers=head)\n soup = bs(r.content, \"html5lib\")\n du_links.append(title + \"|:|\" + soup.find(\"a\", id=\"couponLink\").string)\n du_bar.close()\n\n\ndef udemy_freebies():\n global uf_links\n uf_links = []\n big_all = []\n\n for page in range(1, 3):\n r = requests.get(\n \"https://www.udemyfreebies.com/free-udemy-courses/\" + str(page)\n )\n soup = bs(r.content, \"html5lib\")\n small_all = soup.find_all(\"a\", {\"class\": \"theme-img\"})\n big_all.extend(small_all)\n uf_bar = tqdm(total=len(big_all), desc=\"Udemy Freebies\")\n\n for index, item in enumerate(big_all):\n uf_bar.update(1)\n title = item.img[\"alt\"]\n link = requests.get(\n \"https://www.udemyfreebies.com/out/\" + item[\"href\"].split(\"/\")[4]\n ).url\n uf_links.append(title + \"|:|\" + link)\n uf_bar.close()\n\n\ndef tutorialbar():\n\n global tb_links\n tb_links = []\n big_all = []\n\n for page in range(1, 4):\n r = requests.get(\"https://www.tutorialbar.com/all-courses/page/\" + str(page))\n soup = bs(r.content, \"html5lib\")\n small_all = soup.find_all(\n \"h3\", class_=\"mb15 mt0 font110 mobfont100 fontnormal lineheight20\"\n )\n big_all.extend(small_all)\n tb_bar = tqdm(total=len(big_all), desc=\"Tutorial Bar\")\n\n for index, item in enumerate(big_all):\n tb_bar.update(1)\n title = item.a.string\n url = item.a[\"href\"]\n r = requests.get(url)\n soup = bs(r.content, \"html5lib\")\n link = soup.find(\"a\", class_=\"btn_offer_block re_track_btn\")[\"href\"]\n if \"www.udemy.com\" in link:\n tb_links.append(title + \"|:|\" + link)\n tb_bar.close()\n\n\ndef real_discount():\n\n global rd_links\n rd_links = []\n big_all = []\n\n for page in range(1, 3):\n r = requests.get(\"https://real.discount/stores/Udemy?page=\" + str(page))\n soup = bs(r.content, \"html5lib\")\n small_all = soup.find_all(\"div\", class_=\"col-xl-4 col-md-6\")\n big_all.extend(small_all)\n rd_bar = tqdm(total=len(big_all), desc=\"Real Discount\")\n\n for index, item in enumerate(big_all):\n rd_bar.update(1)\n title = item.h3.string\n url = \"https://real.discount\" + item.a[\"href\"]\n r = requests.get(url)\n soup = bs(r.content, \"html5lib\")\n link = soup.find(\"div\", class_=\"col-xs-12 col-md-12 col-sm-12 text-center\").a[\n \"href\"\n ]\n if link.startswith(\"http://click.linksynergy.com\"):\n link = parse_qs(link)[\"RD_PARM1\"][0]\n rd_links.append(title+\"|:|\"+link)\n rd_bar.close()\n\n\ndef coursevania():\n\n global cv_links\n cv_links = []\n r = requests.get(\"https://coursevania.com/courses/\")\n soup = bs(r.content, \"html5lib\")\n\n nonce = json.loads([script.string for script in soup.find_all('script') if script.string and \"load_content\" in script.string][0].strip(\"_mlv = norsecat;\\n\"))[\"load_content\"]\n\n r = requests.get(\n \"https://coursevania.com/wp-admin/admin-ajax.php?&template=courses/grid&args={%22posts_per_page%22:%2230%22}&action=stm_lms_load_content&nonce=\"\n + nonce\n + \"&sort=date_high\"\n ).json()\n soup = bs(r[\"content\"], \"html5lib\")\n small_all = soup.find_all(\"div\", {\"class\": \"stm_lms_courses__single--title\"})\n cv_bar = tqdm(total=len(small_all), desc=\"Course Vania\")\n\n for index, item in enumerate(small_all):\n cv_bar.update(1)\n title = item.h5.string\n r = requests.get(item.a[\"href\"])\n soup = bs(r.content, \"html5lib\")\n cv_links.append(\n title + \"|:|\" + soup.find(\"div\", {\"class\": \"stm-lms-buy-buttons\"}).a[\"href\"]\n )\n cv_bar.close()\n\n\ndef idcoupons():\n\n global idc_links\n idc_links = []\n big_all = []\n for page in range(1, 6):\n r = requests.get(\n \"https://idownloadcoupon.com/product-category/udemy-2/page/\" + str(page)\n )\n soup = bs(r.content, \"html5lib\")\n small_all = soup.find_all(\"a\", attrs={\"class\": \"button product_type_external\"})\n big_all.extend(small_all)\n idc_bar = tqdm(total=len(big_all), desc=\"IDownloadCoupons\")\n\n for index, item in enumerate(big_all):\n idc_bar.update(1)\n title = item[\"aria-label\"]\n link = unquote(item[\"href\"])\n if link.startswith(\"https://ad.admitad.com\"):\n link = parse_qs(link)[\"ulp\"][0]\n elif link.startswith(\"https://click.linksynergy.com\"):\n link = parse_qs(link)[\"murl\"][0]\n idc_links.append(title + \"|:|\" + link)\n idc_bar.close()\n\ndef enext() -> list:\n en_links = []\n r = requests.get(\"https://e-next.in/e/udemycoupons.php\")\n soup = bs(r.content, \"html5lib\")\n big_all = soup.find(\"div\", {\"class\": \"scroll-box\"}).find_all(\"p\", {\"class\": \"p2\"})\n en_bar = tqdm(total=len(big_all), desc=\"E-next\")\n for i in big_all:\n en_bar.update(1)\n title = i.text[11:].strip().removesuffix(\"Enroll Now free\").strip()\n link = i.a[\"href\"]\n en_links.append(title + \"|:|\" + link)\n en_bar.close()\n\n\n# Constants\n\nversion = \"v1.6\"\n\n\ndef create_scrape_obj():\n funcs = {\n \"Discudemy\": threading.Thread(target=discudemy, daemon=True),\n \"Udemy Freebies\": threading.Thread(target=udemy_freebies, daemon=True),\n \"Tutorial Bar\": threading.Thread(target=tutorialbar, daemon=True),\n \"Real Discount\": threading.Thread(target=real_discount, daemon=True),\n \"Course Vania\": threading.Thread(target=coursevania, daemon=True),\n \"IDownloadCoupons\": threading.Thread(target=idcoupons, daemon=True),\n \"E-next\": threading.Thread(target=enext, daemon=True),\n }\n return funcs\n\n\n################\n\n\n\ndef cookiejar(\n client_id,\n access_token,\n csrf_token,\n):\n cookies = dict(\n client_id=client_id,\n access_token=access_token,\n csrf_token=csrf_token,\n )\n return cookies\n\ndef get_course_id(url):\n r = requests.get(url, allow_redirects=False)\n if r.status_code in (404, 302, 301):\n return False\n if \"/course/draft/\" in url:\n return False\n soup = bs(r.content, \"html5lib\")\n\n try:\n courseid = soup.find(\n \"div\",\n attrs={\"data-content-group\": \"Landing Page\"},\n )[\"data-course-id\"]\n except:\n courseid = soup.find(\n \"body\", attrs={\"data-module-id\": \"course-landing-page/udlite\"}\n )[\"data-clp-course-id\"]\n # with open(\"problem.txt\",\"w\",encoding=\"utf-8\") as f:\n # f.write(str(soup))\n return courseid\n\n\ndef get_course_coupon(url):\n query = urlsplit(url).query\n params = parse_qs(query)\n try:\n params = {k: v[0] for k, v in params.items()}\n return params[\"couponCode\"]\n except:\n return \"\"\n\n\n\ndef course_landing_api(courseid):\n r = s.get(\n \"https://www.udemy.com/api-2.0/course-landing-components/\"\n + courseid\n + \"/me/?components=purchase\"\n ).json()\n try:\n purchased = r[\"purchase\"][\"data\"][\"purchase_date\"]\n except:\n purchased = False\n try:\n amount = r[\"purchase\"][\"data\"][\"list_price\"][\"amount\"]\n except:\n print(r[\"purchase\"][\"data\"])\n\n return purchased, Decimal(amount)\n\n\ndef remove_duplicates(l):\n l = l[::-1]\n for i in l:\n while l.count(i) > 1:\n l.remove(i)\n return l[::-1]\n\ndef update_available():\n if remove_prefix(version,\"v\") < remove_prefix(requests.get(\n \"https://api.github.com/repos/techtanic/Discounted-Udemy-Course-Enroller/releases/latest\"\n ).json()[\"tag_name\"],\"v\"):\n print(by + fr + \" Update Available \")\n else:\n return\n\n\ndef check_login():\n \n for retry in range(4):\n \n s = cloudscraper.CloudScraper()\n\n r = s.get(\n \"https://www.udemy.com/join/signup-popup/\",\n )\n soup = bs(r.text, \"html5lib\")\n\n csrf_token = soup.find(\"input\", {\"name\": \"csrfmiddlewaretoken\"})[\"value\"]\n\n data = {\n \"email\": email,\n \"password\": password,\n \"locale\": \"en_US\",\n \"csrfmiddlewaretoken\": csrf_token,\n }\n \n s.headers.update({\"Referer\": \"https://www.udemy.com/join/signup-popup/\"})\n try:\n r = s.post(\n \"https://www.udemy.com/join/login-popup/?locale=en_US\",\n data=data,\n allow_redirects=False,\n )\n except cloudscraper.exceptions.CloudflareChallengeError:\n if retry == 3:\n print(\"Cloudflare is blocking your requests try again after an hour\")\n !kill -9 -1\n retry -= 1\n continue\n if r.status_code != 302:\n soup = bs(r.content, \"html5lib\")\n txt = soup.find(\"div\", class_=\"alert alert-danger js-error-alert\").text.strip()\n if txt[0] == \"Y\":\n print(\"Too many logins per hour try later\")\n elif txt[0] == \"T\":\n print(\"Email or password incorrect\")\n else:\n print(txt)\n time.sleep(1)\n !kill -9 -1\n cookies = cookiejar(r.cookies[\"client_id\"], r.cookies[\"access_token\"], csrf_token)\n\n head = {\n \"authorization\": \"Bearer \" + r.cookies[\"access_token\"],\n \"accept\": \"application/json, text/plain, */*\",\n \"x-requested-with\": \"XMLHttpRequest\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36 Edg/89.0.774.77\",\n \"x-forwarded-for\": str(\n \".\".join(map(str, (random.randint(0, 255) for _ in range(4))))\n ),\n \"x-udemy-authorization\": \"Bearer \" + r.cookies[\"access_token\"],\n \"content-type\": \"application/json;charset=UTF-8\",\n \"origin\": \"https://www.udemy.com\",\n \"referer\": \"https://www.udemy.com/\",\n \"dnt\": \"1\",\n }\n \n s = requests.session()\n s.cookies.update(cookies)\n s.headers.update(head)\n s.keep_alive = False\n \n r = s.get(\n \"https://www.udemy.com/api-2.0/contexts/me/?me=True&Config=True\"\n ).json()\n currency = r[\"Config\"][\"price_country\"][\"currency\"]\n user = \"\"\n user = r[\"me\"][\"display_name\"]\n\n return head, user, currency, s\n\n\n# -----------------\ndef free_checkout(coupon, courseid):\n payload = (\n '{\"checkout_environment\":\"Marketplace\",\"checkout_event\":\"Submit\",\"shopping_info\":{\"items\":[{\"discountInfo\":{\"code\":\"'\n + coupon\n + '\"},\"buyable\":{\"type\":\"course\",\"id\":'\n + str(courseid)\n + ',\"context\":{}},\"price\":{\"amount\":0,\"currency\":\"'\n + currency\n + '\"}}]},\"payment_info\":{\"payment_vendor\":\"Free\",\"payment_method\":\"free-method\"}}'\n )\n\n r = s.post(\n \"https://www.udemy.com/payment/checkout-submit/\",\n data=payload,\n verify=False,\n )\n return r.json()\n\n\ndef free_enroll(courseid):\n\n s.get(\n \"https://www.udemy.com/course/subscribe/?courseId=\" + str(courseid)\n )\n\n r = s.get(\n \"https://www.udemy.com/api-2.0/users/me/subscribed-courses/\"\n + str(courseid)\n + \"/?fields%5Bcourse%5D=%40default%2Cbuyable_object_type%2Cprimary_subcategory%2Cis_private\"\n )\n return r.json()\n\n\n# -----------------\n\n\ndef auto(list_st):\n\n se_c, ae_c, e_c, ex_c, as_c = 0, 0, 0, 0, 0\n for index, link in enumerate(list_st):\n title = link.split(\"|:|\")\n print(fy + str(index) + \" \" + title[0], end=\" \")\n link = title[1]\n print(fb + link)\n course_id = get_course_id(link)\n if course_id:\n coupon_id = get_course_coupon(link)\n purchased, amount = course_landing_api(course_id)\n\n if not purchased:\n\n if coupon_id:\n slp = \"\"\n\n js = free_checkout(coupon_id, course_id)\n try:\n if js[\"status\"] == \"succeeded\":\n print(fg + \"Successfully Enrolled\\n\")\n se_c += 1\n as_c += amount\n\n elif js[\"status\"] == \"failed\":\n # print(js)\n print(fr + \"Coupon Expired\\n\")\n e_c += 1\n\n except:\n try:\n msg = js[\"detail\"]\n print(fr + msg)\n print()\n slp = int(re.search(r\"\\d+\", msg).group(0))\n except:\n # print(js)\n print(fr + \"Expired Coupon\\n\")\n e_c += 1\n\n if slp != \"\":\n slp += 5\n print(\n fr\n + \">>> Pausing execution of script for \"\n + str(slp)\n + \" seconds\\n\",\n )\n time.sleep(slp)\n else:\n time.sleep(4)\n\n elif not coupon_id:\n js = free_enroll(course_id)\n try:\n if js[\"_class\"] == \"course\":\n print(fg + \"Successfully Subscribed\\n\")\n se_c += 1\n as_c += amount\n\n except:\n print(fr + \"COUPON MIGHT HAVE EXPIRED\\n\")\n e_c += 1\n\n elif purchased:\n print(flb + purchased)\n print()\n ae_c += 1\n\n elif not course_id:\n print(fr + \"Course Doesn't exist\\n\")\n\n print(f\"Successfully Enrolled: {se_c}\")\n print(f\"Already Enrolled: {ae_c}\")\n print(f\"Amount Saved: ${round(as_c,2)}\")\n print(f\"Expired Courses: {e_c}\")\n print(f\"Excluded Courses: {ex_c}\")\n\n\ndef random_color():\n col = [\"green\", \"yellow\", \"white\"]\n return random.choice(col)\n\n\n##########################################\n\n\ndef main1():\n try:\n links_ls = []\n for index in all_functions:\n all_functions[index].start()\n time.sleep(0.09)\n for t in all_functions:\n all_functions[t].join()\n time.sleep(1)\n\n for link_list in [\n \"du_links\",\n \"uf_links\",\n \"tb_links\",\n \"rd_links\",\n \"cv_links\",\n \"idc_links\",\n \"en_links\",\n ]:\n try:\n links_ls += eval(link_list)\n except:\n pass\n\n auto(remove_duplicates(links_ls))\n\n except:\n e = traceback.format_exc()\n print(e)\n\n############## MAIN ############# MAIN############## MAIN ############# MAIN ############## MAIN ############# MAIN ###########\n\nprint(fb+\"Trying to login\")\ntry:\n head, user, currency, s= check_login()\n print(fg+f\"Logged in as {user}\")\nexcept Exception as e:\n print(fr+f\"Login Error\")\n e = traceback.format_exc()\n print(e)\ntry:\n update_available()\nexcept:\n pass\n\n\nall_functions = create_scrape_obj()\ntm = threading.Thread(target=main1, daemon=True)\ntm.start()\n\ntm.join()\ntry:\n update_available()\nexcept:\n pass", "installing 0/5\ninstalling 1/5\ninstalling 2/5\ninstalling 3/5\ninstalling 4/5\ninstalling 5/5\n\u001b[34mTrying to login\nToo many logins per hour try later\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
d039be7610e171badc42d09a6fa2e15814541a09
320,686
ipynb
Jupyter Notebook
11_3_develop_new_OD_demand_estimator_Tiergarten_Dijkstra_multi_class/04_demands_adjustment_Tiergarten_multi_class.ipynb
jingzbu/InverseVITraffic
c0d33d91bdd3c014147d58866c1a2b99fb8a9608
[ "MIT" ]
null
null
null
11_3_develop_new_OD_demand_estimator_Tiergarten_Dijkstra_multi_class/04_demands_adjustment_Tiergarten_multi_class.ipynb
jingzbu/InverseVITraffic
c0d33d91bdd3c014147d58866c1a2b99fb8a9608
[ "MIT" ]
null
null
null
11_3_develop_new_OD_demand_estimator_Tiergarten_Dijkstra_multi_class/04_demands_adjustment_Tiergarten_multi_class.ipynb
jingzbu/InverseVITraffic
c0d33d91bdd3c014147d58866c1a2b99fb8a9608
[ "MIT" ]
null
null
null
216.826234
42,430
0.897707
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d039ce30643afc74ced48c342cdbce30a1742926
27,004
ipynb
Jupyter Notebook
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
0cf029aa6e9805d3175932bba1a36ddb816d290b
[ "MIT" ]
null
null
null
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
0cf029aa6e9805d3175932bba1a36ddb816d290b
[ "MIT" ]
null
null
null
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
0cf029aa6e9805d3175932bba1a36ddb816d290b
[ "MIT" ]
null
null
null
38.412518
577
0.486706
[ [ [ "# Porto Seguro's Safe Driving Prediction\n\nPorto Seguro, one of Brazil’s largest auto and homeowner insurance companies, completely agrees. Inaccuracies in car insurance company’s claim predictions raise the cost of insurance for good drivers and reduce the price for bad ones.\n\nIn the [Porto Seguro Safe Driver Prediction competition](https://www.kaggle.com/c/porto-seguro-safe-driver-prediction), the challenge is to build a model that predicts the probability that a driver will initiate an auto insurance claim in the next year. While Porto Seguro has used machine learning for the past 20 years, they’re looking to Kaggle’s machine learning community to explore new, more powerful methods. A more accurate prediction will allow them to further tailor their prices, and hopefully make auto insurance coverage more accessible to more drivers.\n\nLucky for you, a machine learning model was built to solve the Porto Seguro problem by the data scientist on your team. The solution notebook has steps to load data, split the data into test and train sets, train, evaluate and save a LightGBM model that will be used for the future challenges.\n\n#### Hint: use shift + enter to run the code cells below. Once the cell turns from [*] to [#], you can be sure the cell has run. ", "_____no_output_____" ], [ "## Import Needed Packages\n\nImport the packages needed for this solution notebook. The most widely used packages for machine learning for [scikit-learn](https://scikit-learn.org/stable/), [pandas](https://pandas.pydata.org/docs/getting_started/index.html#getting-started), and [numpy](https://numpy.org/). These packages have various features, as well as a lot of clustering, regression and classification algorithms that make it a good choice for data mining and data analysis. In this notebook, we're using a training function from [lightgbm](https://lightgbm.readthedocs.io/en/latest/index.html).", "_____no_output_____" ] ], [ [ "import os\nimport numpy as np\nimport pandas as pd\nimport lightgbm\nfrom sklearn.model_selection import train_test_split\nimport joblib\nfrom sklearn import metrics", "_____no_output_____" ] ], [ [ "## Load Data\n\nLoad the training dataset from the ./data/ directory. Df.shape() allows you to view the dimensions of the dataset you are passing in. If you want to view the first 5 rows of data, df.head() allows for this.", "_____no_output_____" ] ], [ [ "DATA_DIR = \"../data\"\ndata_df = pd.read_csv(os.path.join(DATA_DIR, 'porto_seguro_safe_driver_prediction_input.csv'))\nprint(data_df.shape)\ndata_df.head()", "(595212, 59)\n" ] ], [ [ "## Split Data into Train and Validatation Sets\n\nPartitioning data into training, validation, and holdout sets allows you to develop highly accurate models that are relevant to data that you collect in the future, not just the data the model was trained on. \n\nIn machine learning, features are the measurable property of the object you’re trying to analyze. Typically, features are the columns of the data that you are training your model with minus the label. In machine learning, a label (categorical) or target (regression) is the output you get from your model after training it.", "_____no_output_____" ] ], [ [ "features = data_df.drop(['target', 'id'], axis = 1)\nlabels = np.array(data_df['target'])\nfeatures_train, features_valid, labels_train, labels_valid = train_test_split(features, labels, test_size=0.2, random_state=0)\n\ntrain_data = lightgbm.Dataset(features_train, label=labels_train)\nvalid_data = lightgbm.Dataset(features_valid, label=labels_valid, free_raw_data=False)", "_____no_output_____" ] ], [ [ "## Train Model\n\nA machine learning model is an algorithm which learns features from the given data to produce labels which may be continuous or categorical ( regression and classification respectively ). In other words, it tries to relate the given data with its labels, just as the human brain does.\n\nIn this cell, the data scientist used an algorithm called [LightGBM](https://lightgbm.readthedocs.io/en/latest/), which primarily used for unbalanced datasets. AUC will be explained in the next cell.", "_____no_output_____" ] ], [ [ "parameters = {\n 'learning_rate': 0.02,\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n 'metric': 'auc',\n 'sub_feature': 0.7,\n 'num_leaves': 60,\n 'min_data': 100,\n 'min_hessian': 1,\n 'verbose': 4\n}\n \nmodel = lightgbm.train(parameters,\n train_data,\n valid_sets=valid_data,\n num_boost_round=500,\n early_stopping_rounds=20)", "[1]\tvalid_0's auc: 0.595844\nTraining until validation scores don't improve for 20 rounds\n[2]\tvalid_0's auc: 0.605252\n[3]\tvalid_0's auc: 0.612784\n[4]\tvalid_0's auc: 0.61756\n[5]\tvalid_0's auc: 0.620129\n[6]\tvalid_0's auc: 0.622447\n[7]\tvalid_0's auc: 0.622163\n[8]\tvalid_0's auc: 0.622112\n[9]\tvalid_0's auc: 0.622581\n[10]\tvalid_0's auc: 0.622278\n[11]\tvalid_0's auc: 0.622433\n[12]\tvalid_0's auc: 0.623423\n[13]\tvalid_0's auc: 0.623618\n[14]\tvalid_0's auc: 0.62414\n[15]\tvalid_0's auc: 0.624421\n[16]\tvalid_0's auc: 0.624512\n[17]\tvalid_0's auc: 0.625151\n[18]\tvalid_0's auc: 0.62529\n[19]\tvalid_0's auc: 0.625437\n[20]\tvalid_0's auc: 0.62563\n[21]\tvalid_0's auc: 0.625963\n[22]\tvalid_0's auc: 0.626147\n[23]\tvalid_0's auc: 0.626383\n[24]\tvalid_0's auc: 0.626618\n[25]\tvalid_0's auc: 0.626586\n[26]\tvalid_0's auc: 0.626839\n[27]\tvalid_0's auc: 0.626972\n[28]\tvalid_0's auc: 0.626935\n[29]\tvalid_0's auc: 0.626946\n[30]\tvalid_0's auc: 0.627204\n[31]\tvalid_0's auc: 0.627252\n[32]\tvalid_0's auc: 0.627302\n[33]\tvalid_0's auc: 0.627249\n[34]\tvalid_0's auc: 0.627517\n[35]\tvalid_0's auc: 0.627755\n[36]\tvalid_0's auc: 0.62766\n[37]\tvalid_0's auc: 0.627483\n[38]\tvalid_0's auc: 0.627578\n[39]\tvalid_0's auc: 0.627433\n[40]\tvalid_0's auc: 0.627573\n[41]\tvalid_0's auc: 0.627908\n[42]\tvalid_0's auc: 0.627968\n[43]\tvalid_0's auc: 0.628082\n[44]\tvalid_0's auc: 0.628398\n[45]\tvalid_0's auc: 0.628763\n[46]\tvalid_0's auc: 0.629011\n[47]\tvalid_0's auc: 0.629321\n[48]\tvalid_0's auc: 0.629341\n[49]\tvalid_0's auc: 0.629353\n[50]\tvalid_0's auc: 0.629291\n[51]\tvalid_0's auc: 0.629447\n[52]\tvalid_0's auc: 0.629507\n[53]\tvalid_0's auc: 0.629725\n[54]\tvalid_0's auc: 0.630048\n[55]\tvalid_0's auc: 0.630085\n[56]\tvalid_0's auc: 0.630035\n[57]\tvalid_0's auc: 0.630236\n[58]\tvalid_0's auc: 0.630486\n[59]\tvalid_0's auc: 0.630663\n[60]\tvalid_0's auc: 0.630787\n[61]\tvalid_0's auc: 0.630932\n[62]\tvalid_0's auc: 0.631004\n[63]\tvalid_0's auc: 0.631161\n[64]\tvalid_0's auc: 0.631407\n[65]\tvalid_0's auc: 0.631408\n[66]\tvalid_0's auc: 0.631515\n[67]\tvalid_0's auc: 0.631631\n[68]\tvalid_0's auc: 0.631628\n[69]\tvalid_0's auc: 0.631703\n[70]\tvalid_0's auc: 0.631781\n[71]\tvalid_0's auc: 0.631786\n[72]\tvalid_0's auc: 0.631779\n[73]\tvalid_0's auc: 0.632022\n[74]\tvalid_0's auc: 0.632086\n[75]\tvalid_0's auc: 0.632107\n[76]\tvalid_0's auc: 0.632201\n[77]\tvalid_0's auc: 0.632165\n[78]\tvalid_0's auc: 0.632335\n[79]\tvalid_0's auc: 0.632446\n[80]\tvalid_0's auc: 0.63254\n[81]\tvalid_0's auc: 0.632654\n[82]\tvalid_0's auc: 0.632663\n[83]\tvalid_0's auc: 0.632811\n[84]\tvalid_0's auc: 0.63291\n[85]\tvalid_0's auc: 0.632993\n[86]\tvalid_0's auc: 0.632962\n[87]\tvalid_0's auc: 0.632941\n[88]\tvalid_0's auc: 0.633062\n[89]\tvalid_0's auc: 0.633144\n[90]\tvalid_0's auc: 0.633242\n[91]\tvalid_0's auc: 0.633336\n[92]\tvalid_0's auc: 0.633453\n[93]\tvalid_0's auc: 0.633556\n[94]\tvalid_0's auc: 0.633648\n[95]\tvalid_0's auc: 0.633762\n[96]\tvalid_0's auc: 0.633831\n[97]\tvalid_0's auc: 0.633922\n[98]\tvalid_0's auc: 0.633908\n[99]\tvalid_0's auc: 0.633958\n[100]\tvalid_0's auc: 0.634122\n[101]\tvalid_0's auc: 0.634278\n[102]\tvalid_0's auc: 0.634301\n[103]\tvalid_0's auc: 0.634313\n[104]\tvalid_0's auc: 0.634366\n[105]\tvalid_0's auc: 0.634497\n[106]\tvalid_0's auc: 0.634442\n[107]\tvalid_0's auc: 0.634487\n[108]\tvalid_0's auc: 0.634578\n[109]\tvalid_0's auc: 0.634676\n[110]\tvalid_0's auc: 0.63479\n[111]\tvalid_0's auc: 0.634846\n[112]\tvalid_0's auc: 0.634918\n[113]\tvalid_0's auc: 0.63501\n[114]\tvalid_0's auc: 0.634965\n[115]\tvalid_0's auc: 0.635029\n[116]\tvalid_0's auc: 0.635077\n[117]\tvalid_0's auc: 0.635075\n[118]\tvalid_0's auc: 0.6352\n[119]\tvalid_0's auc: 0.635215\n[120]\tvalid_0's auc: 0.635231\n[121]\tvalid_0's auc: 0.635276\n[122]\tvalid_0's auc: 0.635268\n[123]\tvalid_0's auc: 0.635221\n[124]\tvalid_0's auc: 0.635178\n[125]\tvalid_0's auc: 0.635221\n[126]\tvalid_0's auc: 0.635288\n[127]\tvalid_0's auc: 0.635345\n[128]\tvalid_0's auc: 0.635348\n[129]\tvalid_0's auc: 0.635414\n[130]\tvalid_0's auc: 0.635418\n[131]\tvalid_0's auc: 0.635352\n[132]\tvalid_0's auc: 0.635402\n[133]\tvalid_0's auc: 0.635497\n[134]\tvalid_0's auc: 0.635545\n[135]\tvalid_0's auc: 0.63565\n[136]\tvalid_0's auc: 0.635622\n[137]\tvalid_0's auc: 0.635664\n[138]\tvalid_0's auc: 0.635781\n[139]\tvalid_0's auc: 0.635735\n[140]\tvalid_0's auc: 0.635719\n[141]\tvalid_0's auc: 0.635815\n[142]\tvalid_0's auc: 0.635799\n[143]\tvalid_0's auc: 0.63583\n[144]\tvalid_0's auc: 0.635898\n[145]\tvalid_0's auc: 0.635924\n[146]\tvalid_0's auc: 0.635885\n[147]\tvalid_0's auc: 0.635919\n[148]\tvalid_0's auc: 0.63598\n[149]\tvalid_0's auc: 0.636035\n[150]\tvalid_0's auc: 0.636087\n[151]\tvalid_0's auc: 0.636139\n[152]\tvalid_0's auc: 0.63617\n[153]\tvalid_0's auc: 0.636128\n[154]\tvalid_0's auc: 0.636096\n[155]\tvalid_0's auc: 0.636206\n[156]\tvalid_0's auc: 0.636259\n[157]\tvalid_0's auc: 0.636289\n[158]\tvalid_0's auc: 0.636283\n[159]\tvalid_0's auc: 0.636287\n[160]\tvalid_0's auc: 0.636293\n[161]\tvalid_0's auc: 0.636324\n[162]\tvalid_0's auc: 0.63633\n[163]\tvalid_0's auc: 0.636367\n[164]\tvalid_0's auc: 0.636438\n[165]\tvalid_0's auc: 0.636483\n[166]\tvalid_0's auc: 0.636577\n[167]\tvalid_0's auc: 0.636645\n[168]\tvalid_0's auc: 0.63659\n[169]\tvalid_0's auc: 0.636595\n[170]\tvalid_0's auc: 0.636672\n[171]\tvalid_0's auc: 0.636719\n[172]\tvalid_0's auc: 0.636755\n[173]\tvalid_0's auc: 0.636833\n[174]\tvalid_0's auc: 0.636908\n[175]\tvalid_0's auc: 0.636929\n[176]\tvalid_0's auc: 0.636928\n[177]\tvalid_0's auc: 0.636962\n[178]\tvalid_0's auc: 0.636969\n[179]\tvalid_0's auc: 0.636995\n[180]\tvalid_0's auc: 0.637059\n[181]\tvalid_0's auc: 0.637089\n[182]\tvalid_0's auc: 0.637085\n[183]\tvalid_0's auc: 0.637121\n[184]\tvalid_0's auc: 0.637131\n[185]\tvalid_0's auc: 0.637133\n[186]\tvalid_0's auc: 0.637144\n[187]\tvalid_0's auc: 0.637189\n[188]\tvalid_0's auc: 0.637173\n[189]\tvalid_0's auc: 0.63719\n[190]\tvalid_0's auc: 0.637205\n[191]\tvalid_0's auc: 0.637131\n[192]\tvalid_0's auc: 0.637159\n[193]\tvalid_0's auc: 0.637185\n[194]\tvalid_0's auc: 0.63719\n[195]\tvalid_0's auc: 0.637224\n[196]\tvalid_0's auc: 0.637219\n[197]\tvalid_0's auc: 0.637193\n[198]\tvalid_0's auc: 0.637297\n[199]\tvalid_0's auc: 0.637329\n[200]\tvalid_0's auc: 0.6373\n[201]\tvalid_0's auc: 0.637257\n[202]\tvalid_0's auc: 0.637253\n[203]\tvalid_0's auc: 0.637261\n[204]\tvalid_0's auc: 0.637252\n[205]\tvalid_0's auc: 0.637273\n[206]\tvalid_0's auc: 0.637297\n[207]\tvalid_0's auc: 0.637345\n[208]\tvalid_0's auc: 0.637401\n[209]\tvalid_0's auc: 0.637456\n[210]\tvalid_0's auc: 0.637392\n[211]\tvalid_0's auc: 0.637373\n[212]\tvalid_0's auc: 0.63741\n[213]\tvalid_0's auc: 0.637459\n[214]\tvalid_0's auc: 0.637496\n[215]\tvalid_0's auc: 0.637539\n[216]\tvalid_0's auc: 0.637546\n[217]\tvalid_0's auc: 0.637535\n[218]\tvalid_0's auc: 0.637511\n[219]\tvalid_0's auc: 0.6375\n[220]\tvalid_0's auc: 0.637502\n[221]\tvalid_0's auc: 0.637493\n[222]\tvalid_0's auc: 0.637431\n[223]\tvalid_0's auc: 0.637413\n[224]\tvalid_0's auc: 0.637421\n[225]\tvalid_0's auc: 0.637368\n[226]\tvalid_0's auc: 0.637374\n[227]\tvalid_0's auc: 0.637374\n[228]\tvalid_0's auc: 0.637413\n[229]\tvalid_0's auc: 0.637429\n[230]\tvalid_0's auc: 0.637437\n[231]\tvalid_0's auc: 0.637488\n[232]\tvalid_0's auc: 0.637531\n[233]\tvalid_0's auc: 0.637529\n[234]\tvalid_0's auc: 0.637567\n[235]\tvalid_0's auc: 0.637599\n[236]\tvalid_0's auc: 0.637624\n[237]\tvalid_0's auc: 0.637659\n[238]\tvalid_0's auc: 0.637586\n[239]\tvalid_0's auc: 0.637656\n[240]\tvalid_0's auc: 0.637684\n[241]\tvalid_0's auc: 0.637682\n[242]\tvalid_0's auc: 0.637751\n[243]\tvalid_0's auc: 0.637722\n[244]\tvalid_0's auc: 0.637714\n[245]\tvalid_0's auc: 0.637647\n[246]\tvalid_0's auc: 0.637679\n[247]\tvalid_0's auc: 0.637679\n[248]\tvalid_0's auc: 0.637735\n[249]\tvalid_0's auc: 0.6377\n[250]\tvalid_0's auc: 0.637738\n[251]\tvalid_0's auc: 0.637708\n[252]\tvalid_0's auc: 0.637688\n[253]\tvalid_0's auc: 0.637725\n[254]\tvalid_0's auc: 0.637697\n[255]\tvalid_0's auc: 0.637689\n[256]\tvalid_0's auc: 0.637714\n[257]\tvalid_0's auc: 0.637688\n[258]\tvalid_0's auc: 0.637732\n[259]\tvalid_0's auc: 0.637703\n[260]\tvalid_0's auc: 0.63775\n[261]\tvalid_0's auc: 0.637715\n[262]\tvalid_0's auc: 0.637711\nEarly stopping, best iteration is:\n[242]\tvalid_0's auc: 0.637751\n" ] ], [ [ "## Evaluate Model\n\nEvaluating performance is an essential task in machine learning. In this case, because this is a classification problem, the data scientist elected to use an AUC - ROC Curve. When we need to check or visualize the performance of the multi - class classification problem, we use AUC (Area Under The Curve) ROC (Receiver Operating Characteristics) curve. It is one of the most important evaluation metrics for checking any classification model’s performance.\n\n<img src=\"https://www.researchgate.net/profile/Oxana_Trifonova/publication/276079439/figure/fig2/AS:614187332034565@1523445079168/An-example-of-ROC-curves-with-good-AUC-09-and-satisfactory-AUC-065-parameters.png\"\n alt=\"Markdown Monster icon\"\n style=\"float: left; margin-right: 12px; width: 320px; height: 239px;\" />", "_____no_output_____" ] ], [ [ "predictions = model.predict(valid_data.data)\nfpr, tpr, thresholds = metrics.roc_curve(valid_data.label, predictions)\nmodel_metrics = {\"auc\": (metrics.auc(fpr, tpr))}\nprint(model_metrics)", "{'auc': 0.6377511613946426}\n" ] ], [ [ "## Save Model\n \nIn machine learning, we need to save the trained models in a file and restore them in order to reuse it to compare the model with other models, to test the model on a new data. The saving of data is called Serializaion, while restoring the data is called Deserialization.", "_____no_output_____" ] ], [ [ "model_name = \"lgbm_binary_model.pkl\"\njoblib.dump(value=model, filename=model_name)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d039ce780837e90118be7da89b074f418e1f21de
565,377
ipynb
Jupyter Notebook
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
5c5e3c76c344303c6df5fb80517fdee5a70afbf6
[ "MIT" ]
null
null
null
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
5c5e3c76c344303c6df5fb80517fdee5a70afbf6
[ "MIT" ]
null
null
null
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
5c5e3c76c344303c6df5fb80517fdee5a70afbf6
[ "MIT" ]
null
null
null
489.928076
177,124
0.938563
[ [ [ "%matplotlib inline\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.style.use('ggplot')\nimport pickle\n\nfrom sklearn.preprocessing import LabelEncoder\nimport seaborn as sns\ncolor = sns.color_palette()\nsns.set(rc={'figure.figsize':(12,8)})\n\nimport sklearn\nfrom sklearn.preprocessing import MinMaxScaler,StandardScaler,LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn import metrics\n\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "df=pd.read_csv('Cardata-Cleaned.csv',index_col=0)", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 1050 entries, 0 to 1049\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Car Name 1050 non-null object \n 1 Car url 1050 non-null object \n 2 Car Brand 1050 non-null object \n 3 Year 1050 non-null int64 \n 4 Selling Price 1050 non-null float64\n 5 Current Value 1050 non-null float64\n 6 KMs Driven 1050 non-null int64 \n 7 Fuel 1050 non-null object \n 8 Seller Type 1050 non-null object \n 9 max_power 1050 non-null float64\n 10 Transmission 1050 non-null object \n 11 Owner 1050 non-null object \n 12 Mileage 1050 non-null float64\n 13 Engine 1050 non-null int64 \n 14 Drive Type 975 non-null object \n 15 Seats 1050 non-null int64 \n 16 Gear Box 1050 non-null int64 \ndtypes: float64(4), int64(5), object(8)\nmemory usage: 147.7+ KB\n" ] ], [ [ "# Exploratory Data Analysis (EDA)", "_____no_output_____" ], [ "## Univariate Analysis", "_____no_output_____" ] ], [ [ "cat_cols = ['Fuel','Seller Type','Transmission','Owner']\ni=0\nwhile i < 4:\n fig = plt.figure(figsize=[15,6])\n \n plt.subplot(1,2,1)\n sns.countplot(x=cat_cols[i], data=df)\n i += 1\n \n plt.subplot(1,2,2)\n sns.countplot(x=cat_cols[i], data=df)\n i += 1\n \n plt.show()\n", "_____no_output_____" ], [ "num_cols = ['Selling Price','Current Value','KMs Driven','Year','max_power','Mileage','Engine','Gear Box']\ni=0\nwhile i < 8:\n fig = plt.figure(figsize=[15,20])\n plt.subplot(4,2,1)\n sns.boxplot(x=num_cols[i], data=df)\n i += 1\n plt.subplot(4,2,2)\n sns.boxplot(x=num_cols[i], data=df)\n i += 1\n ", "_____no_output_____" ] ], [ [ "## Bivariate Analysis", "_____no_output_____" ] ], [ [ "sns.set(rc={'figure.figsize':(15,15)})\nsns.heatmap(df.corr(),annot=True)", "_____no_output_____" ], [ "print(df['Fuel'].value_counts(),'\\n')\nprint(df['Seller Type'].value_counts(),'\\n')\nprint(df['Transmission'].value_counts(),'\\n')\nprint(df['Owner'].value_counts(),'\\n')", "Petrol 606\nDiesel 442\nElectric 1\nCNG 1\nName: Fuel, dtype: int64 \n\nDealer 722\nIndividual 328\nName: Seller Type, dtype: int64 \n\nManual 905\nAutomatic 145\nName: Transmission, dtype: int64 \n\nFirst Owner 895\nSecond Owner 131\nThird Owner 16\nFourth & Above Owner 8\nName: Owner, dtype: int64 \n\n" ], [ "df.pivot_table(values='Selling Price', index = 'Seller Type', columns= 'Fuel')", "_____no_output_____" ] ], [ [ "# Data Preparation", "_____no_output_____" ], [ "## Creating Dummies for Categorical Features", "_____no_output_____" ] ], [ [ "label_encoder = LabelEncoder()\ndf['Owner']= label_encoder.fit_transform(df['Owner'])", "_____no_output_____" ], [ "final_dataset=df[['Year','Selling Price','Current Value','KMs Driven','Fuel',\n 'Seller Type','max_power','Transmission','Owner','Mileage','Engine','Seats','Gear Box']]", "_____no_output_____" ], [ "final_dataset=pd.get_dummies(final_dataset,drop_first=True)", "_____no_output_____" ], [ "sns.set(rc={'figure.figsize':(15,15)})\nsns.heatmap(final_dataset.corr(),annot=True,cmap=\"RdBu\")", "_____no_output_____" ], [ "final_dataset.corr()['Selling Price'].sort_values(ascending=False)", "_____no_output_____" ], [ "y = final_dataset['Selling Price']\nX = final_dataset.drop('Selling Price',axis=1)", "_____no_output_____" ] ], [ [ "## Feature Importance", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import ExtraTreesRegressor\n\nmodel = ExtraTreesRegressor()\nmodel.fit(X,y)", "_____no_output_____" ], [ "print(model.feature_importances_)", "[1.00727101e-01 4.54874134e-01 1.46965566e-02 1.04696153e-01\n 2.05634981e-03 7.69684617e-03 4.27790659e-02 9.61168352e-02\n 1.14777042e-01 1.01498910e-02 2.35535683e-06 3.42311824e-03\n 7.75940956e-03 4.02451420e-02]\n" ], [ "sns.set(rc={'figure.figsize':(12,8)})\n\nfeat_importances = pd.Series(model.feature_importances_, index=X.columns)\nfeat_importances.nlargest(5).plot(kind='barh')\nplt.show()", "_____no_output_____" ], [ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\nprint(\"x train: \",X_train.shape)\nprint(\"x test: \",X_test.shape)\nprint(\"y train: \",y_train.shape)\nprint(\"y test: \",y_test.shape)", "x train: (735, 14)\nx test: (315, 14)\ny train: (735,)\ny test: (315,)\n" ], [ "CV = []\nR2_train = []\nR2_test = []\nMAE=[]\nMSE=[]\nRMSE=[]\n\ndef car_pred_model(model):\n \n \n # R2 score of train set\n y_pred_train = model.predict(X_train)\n R2_train_model = r2_score(y_train,y_pred_train)\n R2_train.append(round(R2_train_model,2))\n \n # R2 score of test set\n y_pred_test = model.predict(X_test)\n R2_test_model = r2_score(y_test,y_pred_test)\n R2_test.append(round(R2_test_model,2))\n \n # R2 mean of train set using Cross validation\n cross_val = cross_val_score(model ,X_train ,y_train ,cv=5)\n cv_mean = cross_val.mean()\n CV.append(round(cv_mean,2))\n \n print(\"Train R2-score :\",round(R2_train_model,2))\n print(\"Test R2-score :\",round(R2_test_model,2))\n print(\"Train CV scores :\",cross_val)\n print(\"Train CV mean :\",round(cv_mean,2))\n \n MAE.append(metrics.mean_absolute_error(y_test, y_pred_test))\n MSE.append(metrics.mean_squared_error(y_test, y_pred_test))\n RMSE.append(np.sqrt(metrics.mean_squared_error(y_test, y_pred_test)))\n \n print('MAE:', metrics.mean_absolute_error(y_test, y_pred_test))\n print('MSE:', metrics.mean_squared_error(y_test, y_pred_test))\n print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred_test)))\n \n \n fig, ax = plt.subplots(1,2,figsize = (12,6))\n ax[0].set_title('Residual Plot of Train samples')\n sns.distplot((y_test-y_pred_test),hist = True,ax = ax[0])\n ax[0].set_xlabel('y_train - y_pred_train')\n \n # Y_test vs Y_train scatter plot\n ax[1].set_title('y_test vs y_pred_test')\n ax[1].scatter(x = y_test, y = y_pred_test)\n ax[1].set_xlabel('y_test')\n ax[1].set_ylabel('y_pred_test')\n \n plt.show()", "_____no_output_____" ] ], [ [ "## Linear Regression", "_____no_output_____" ] ], [ [ "\nlr = LinearRegression()\nlr.fit(X_train,y_train)\n\ncar_pred_model(lr)", "Train R2-score : 0.83\nTest R2-score : 0.88\nTrain CV scores : [0.87318862 0.23054545 0.81581846 0.86005821 0.79216413]\nTrain CV mean : 0.71\nMAE: 1.3212115374204905\nMSE: 5.731984478802555\nRMSE: 2.3941563187900985\n" ] ], [ [ "## Ridge", "_____no_output_____" ] ], [ [ "\n# Creating Ridge model object\nrg = Ridge()\n# range of alpha \nalpha = np.logspace(-3,3,num=14)\n\n# Creating RandomizedSearchCV to find the best estimator of hyperparameter\nrg_rs = RandomizedSearchCV(estimator = rg, param_distributions = dict(alpha=alpha))\n\nrg_rs.fit(X_train,y_train)\n\ncar_pred_model(rg_rs)", "Train R2-score : 0.83\nTest R2-score : 0.89\nTrain CV scores : [0.87345385 0.19438248 0.81973301 0.87546861 0.79190635]\nTrain CV mean : 0.71\nMAE: 1.259204342611868\nMSE: 5.417232953632579\nRMSE: 2.327494995404411\n" ] ], [ [ "## Lasso", "_____no_output_____" ] ], [ [ "\nls = Lasso()\nalpha = np.logspace(-3,3,num=14) # range for alpha\n\nls_rs = RandomizedSearchCV(estimator = ls, param_distributions = dict(alpha=alpha))\n\nls_rs.fit(X_train,y_train)\ncar_pred_model(ls_rs)", "Train R2-score : 0.83\nTest R2-score : 0.88\nTrain CV scores : [0.87434025 0.22872808 0.82137491 0.87579026 0.79292455]\nTrain CV mean : 0.72\nMAE: 1.28454046198753\nMSE: 5.66135888360262\nRMSE: 2.379361024225332\n" ] ], [ [ "## Random Forest", "_____no_output_____" ] ], [ [ "\nrf = RandomForestRegressor()\n\n# Number of trees in Random forest\nn_estimators=list(range(500,1000,100))\n# Maximum number of levels in a tree\nmax_depth=list(range(4,9,4))\n# Minimum number of samples required to split an internal node\nmin_samples_split=list(range(4,9,2))\n# Minimum number of samples required to be at a leaf node.\nmin_samples_leaf=[1,2,5,7]\n# Number of fearures to be considered at each split\nmax_features=['auto','sqrt']\n\n# Hyperparameters dict\nparam_grid = {\"n_estimators\":n_estimators,\n \"max_depth\":max_depth,\n \"min_samples_split\":min_samples_split,\n \"min_samples_leaf\":min_samples_leaf,\n \"max_features\":max_features}\n\nrf_rs = RandomizedSearchCV(estimator = rf, param_distributions = param_grid,cv = 5, random_state=42, n_jobs = 1)\nrf_rs.fit(X_train,y_train)", "_____no_output_____" ], [ "car_pred_model(rf_rs)", "Train R2-score : 0.96\nTest R2-score : 0.92\nTrain CV scores : [0.90932922 0.55268803 0.77245254 0.92139404 0.90756667]\nTrain CV mean : 0.81\nMAE: 0.796357939896497\nMSE: 3.7897916295929766\nRMSE: 1.9467387163132541\n" ] ], [ [ "## Gradient Boosting", "_____no_output_____" ] ], [ [ "\ngb = GradientBoostingRegressor()\n\n# Rate at which correcting is being made\nlearning_rate = [0.001, 0.01, 0.1, 0.2]\n# Number of trees in Gradient boosting\nn_estimators=list(range(500,1000,100))\n# Maximum number of levels in a tree\nmax_depth=list(range(4,9,4))\n# Minimum number of samples required to split an internal node\nmin_samples_split=list(range(4,9,2))\n# Minimum number of samples required to be at a leaf node.\nmin_samples_leaf=[1,2,5,7]\n# Number of fearures to be considered at each split\nmax_features=['auto','sqrt']\n\n# Hyperparameters dict\nparam_grid = {\"learning_rate\":learning_rate,\n \"n_estimators\":n_estimators,\n \"max_depth\":max_depth,\n \"min_samples_split\":min_samples_split,\n \"min_samples_leaf\":min_samples_leaf,\n \"max_features\":max_features}\n\ngb_rs = RandomizedSearchCV(estimator = gb, param_distributions = param_grid,cv = 5, random_state=42, n_jobs = 1)\n\ngb_rs.fit(X_train,y_train)\n\ncar_pred_model(gb_rs)", "Train R2-score : 0.98\nTest R2-score : 0.92\nTrain CV scores : [0.92462522 0.54253837 0.79010633 0.94300397 0.92394372]\nTrain CV mean : 0.82\nMAE: 0.8893903439168446\nMSE: 3.6312438716414492\nRMSE: 1.905582292015081\n" ], [ "gb_rs.best_params_", "_____no_output_____" ], [ "gb_rs.best_score_", "_____no_output_____" ], [ "Models = [\"Linear Regression\",\"Ridge\",\"Lasso\",\"RandomForest Regressor\",\"GradientBoosting Regressor\"]\n\nscore_comparison=pd.DataFrame({'Model': Models,'R Squared(Train)': R2_train,'R Squared(Test)': R2_test,'CV score mean(Train)': CV,\n 'Mean Absolute Error':MAE,'Mean Squared Error':MSE, 'Root Mean Squared Error':RMSE})\n", "_____no_output_____" ], [ "score_comparison", "_____no_output_____" ], [ "file = open('random_forest_regression_model.pkl', 'wb')\n\n# dump information to that file\npickle.dump(rf_rs, file)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d039d5395099888abd85aada26b24384f633cacf
113,641
ipynb
Jupyter Notebook
neutrinomass/analysis/numbers_and_barcharts.ipynb
johngarg/neutrinomass
a4f1adf6abf10de16f34c7f89164342ba5857329
[ "MIT" ]
3
2020-09-28T14:38:45.000Z
2021-11-05T08:45:05.000Z
neutrinomass/analysis/numbers_and_barcharts.ipynb
johngarg/neutrinomass
a4f1adf6abf10de16f34c7f89164342ba5857329
[ "MIT" ]
null
null
null
neutrinomass/analysis/numbers_and_barcharts.ipynb
johngarg/neutrinomass
a4f1adf6abf10de16f34c7f89164342ba5857329
[ "MIT" ]
1
2020-10-29T23:25:14.000Z
2020-10-29T23:25:14.000Z
251.418142
52,288
0.901717
[ [ [ "import os\nimport pickle\n\nfrom neutrinomass.completions import EffectiveOperator, Completion\nfrom neutrinomass.database import ExoticField\nfrom neutrinomass.database import ModelDataFrame, EXOTICS, TERMS, MVDF\nfrom neutrinomass.completions import EFF_OPERATORS\nfrom neutrinomass.completions import DERIV_EFF_OPERATORS", "_____no_output_____" ], [ "DATA_PATH = \"/home/garj/work/neutrinomass/neutrinomass/database\"\nDATA = pickle.load(open(os.path.join(DATA_PATH, \"unfiltered.p\"), \"rb\"))", "_____no_output_____" ], [ "UNF = ModelDataFrame.new(data=DATA, exotics=EXOTICS, terms=TERMS)\n\nSTR_UNF = UNF.drop_duplicates([\"stringent_num\"], keep=\"first\")\nLAGS = len(STR_UNF)\nprint(f\"Number of neutrino-mass mechanisms: {LAGS}\")\n\nDEMO_UNF = UNF.drop_duplicates([\"democratic_num\"], keep=\"first\")\nMODELS = len(DEMO_UNF)\nprint(f\"Number of models: {MODELS}\")\n\nSTR_MVDF = MVDF.drop_duplicates([\"stringent_num\"], keep=\"first\")\nprint(f\"Number of filtered neutrino-mass mechanisms: {len(STR_MVDF)}\")\n\nDEMO_MVDF = MVDF.drop_duplicates([\"democratic_num\"], keep=\"first\")\nprint(f\"Number of filtered neutrino-mass mechanisms: {len(DEMO_MVDF)}\")", "Number of neutrino-mass mechanisms: 430810\nNumber of models: 141989\nNumber of filtered neutrino-mass mechanisms: 11483\nNumber of filtered neutrino-mass mechanisms: 11216\n" ], [ "FIL_DF = MVDF.drop_duplicates(['democratic_num', 'dim'], keep=\"first\")\nUNF_DF = UNF.drop_duplicates(['democratic_num', 'dim'], keep=\"first\")\n\nprint(f\"After filtering, there are {len(FIL_DF[FIL_DF['dim'] == 5])} models derived from dimension-5 operators.\")\nprint(f\"After filtering, there are {len(FIL_DF[FIL_DF['dim'] == 9])} models derived from dimension-9 operators.\")\nprint(f\"After filtering, there are {len(FIL_DF[FIL_DF['dim'] == 11])} models derived from dimension-11 operators.\")\nprint(f\"The total of these is {len(FIL_DF[FIL_DF['dim'] == 5]) + len(FIL_DF[FIL_DF['dim'] == 9]) + len(FIL_DF[FIL_DF['dim'] == 11])}\")\n\nOPS = {**EFF_OPERATORS, **DERIV_EFF_OPERATORS}\nlabels, total, demo, dimensions = [], [], [], []\nfor k in OPS:\n labels.append(k)\n total.append(len(UNF_DF[UNF_DF[\"op\"] == k]))\n demo.append(len(FIL_DF[FIL_DF[\"op\"] == k]))\n dimensions.append(OPS[k].mass_dimension)", "After filtering, there are 3 models derived from dimension-5 operators.\nAfter filtering, there are 244 models derived from dimension-9 operators.\nAfter filtering, there are 10969 models derived from dimension-11 operators.\nThe total of these is 11216\n" ], [ "NHL = STR_UNF.terms[(\"F,00,0,0,0\", \"H\", \"L\")]\nNHSigma = STR_UNF.terms[(\"F,00,2,0,0\", \"H\", \"L\")]\nHHXi1 = STR_UNF.terms[(\"H\", \"H\", \"S,00,2,-1,0\")]\nLLXi1 = STR_UNF.terms[(\"L\", \"L\", \"S,00,2,1,0\")]\n\nN = STR_UNF.exotics[\"F,00,0,0,0\"]\nSigma = STR_UNF.exotics[\"F,00,2,0,0\"]\nXi1 = STR_UNF.exotics[\"S,00,2,1,0\"]", "_____no_output_____" ], [ "N_NHL_lags = len(STR_UNF[STR_UNF[\"stringent_num\"] % NHL == 0])\nN_other_lags = len(STR_UNF[(STR_UNF[\"stringent_num\"] % NHL != 0) & (STR_UNF[\"democratic_num\"] % N == 0)])\n\nSigma_NHSigma_lags = len(STR_UNF[STR_UNF[\"stringent_num\"] % NHSigma == 0])\nSigma_other_lags = len(STR_UNF[(STR_UNF[\"stringent_num\"] % NHSigma != 0) & (STR_UNF[\"democratic_num\"] % Sigma == 0)])\n\nXi1_HHXi1_lags = len(STR_UNF[STR_UNF[\"stringent_num\"] % HHXi1 == 0])\nXi1_LLXi1_lags = len(STR_UNF[STR_UNF[\"stringent_num\"] % LLXi1 == 0])\nXi1_both_lags = len(STR_UNF[(STR_UNF[\"stringent_num\"] % HHXi1 == 0) & (STR_UNF[\"stringent_num\"] % LLXi1 == 0)])\nXi1_other_lags = len(STR_UNF[(STR_UNF[\"stringent_num\"] % HHXi1 != 0) & (STR_UNF[\"stringent_num\"] % LLXi1 != 0) & (STR_UNF[\"democratic_num\"] % Xi1 == 0)])", "_____no_output_____" ], [ "N_models = len(DEMO_UNF[DEMO_UNF[\"democratic_num\"] % N == 0])\nSigma_models = len(DEMO_UNF[DEMO_UNF[\"democratic_num\"] % Sigma == 0])\nXi1_models = len(DEMO_UNF[DEMO_UNF[\"democratic_num\"] % Xi1 == 0])", "_____no_output_____" ], [ "# latex table\nprint(r\"\"\"\n \\begin{tabular}{ccll}\n \\toprule\n Field & Interactions & Lagrangians & Collected models \\\\\n \\midrule\n \\multirow{2}{*}{$N \\sim (\\mathbf{1}, \\mathbf{1}, 0)_{F}$} & $L H N$ & %s (%s) & \\multirow{2}{*}{%s (%s)} \\\\\n & Other & %s (%s) & \\\\\n \\midrule\n \\multirow{2}{*}{$\\Sigma \\sim (\\mathbf{1}, \\mathbf{3}, 0)_{F}$} & $L H \\Sigma$ & %s (%s) & \\multirow{2}{*}{%s (%s)} \\\\\n & Other & %s (%s) & \\\\\n \\midrule\n \\multirow{4}{*}{$\\Xi_{1} \\sim (\\mathbf{1}, \\mathbf{3}, 1)_{S}$} & $L L \\Xi_{1}$ & %s (%s) & \\multirow{4}{*}{%s (%s)} \\\\\n & $H H \\Xi_{1}^{\\dagger}$ & %s (%s) & \\\\\n & Both & %s (%s) & \\\\\n & Other & %s (%s) & \\\\\n \\bottomrule\n \\end{tabular}\n\"\"\" % (\n f\"{N_NHL_lags:,}\", f\"{100 * N_NHL_lags / LAGS:.1f}\\%\",\n f\"{N_models:,}\", f\"{100 * N_models / MODELS:.1f}\\%\",\n f\"{N_other_lags:,}\", f\"{100 * N_other_lags / LAGS:.1f}\\%\",\n\n \n f\"{Sigma_NHSigma_lags:,}\", f\"{100 * Sigma_NHSigma_lags / LAGS:.1f}\\%\",\n f\"{Sigma_models:,}\", f\"{100 * Sigma_models / MODELS:.1f}\\%\",\n f\"{Sigma_other_lags:,}\", f\"{100 * Sigma_other_lags / LAGS:.1f}\\%\",\n\n \n f\"{Xi1_LLXi1_lags:,}\", f\"{100 * Xi1_LLXi1_lags / LAGS:.1f}\\%\",\n f\"{Xi1_models:,}\", f\"{100 * Xi1_models / MODELS:.1f}\\%\",\n f\"{Xi1_HHXi1_lags:,}\", f\"{100 * Xi1_HHXi1_lags / LAGS:.1f}\\%\",\n f\"{Xi1_both_lags:,}\", f\"{100 * Xi1_both_lags / LAGS:.1f}\\%\",\n f\"{Xi1_other_lags:,}\", f\"{100 * Xi1_other_lags / LAGS:.1f}\\%\",\n)\n)", "\n \\begin{tabular}{ccll}\n \\toprule\n Field & Interactions & Lagrangians & Collected models \\\\\n \\midrule\n \\multirow{2}{*}{$N \\sim (\\mathbf{1}, \\mathbf{1}, 0)_{F}$} & $L H N$ & 51,245 (11.9\\%) & \\multirow{2}{*}{17,139 (12.1\\%)} \\\\\n & Other & 12,433 (2.9\\%) & \\\\\n \\midrule\n \\multirow{2}{*}{$\\Sigma \\sim (\\mathbf{1}, \\mathbf{3}, 0)_{F}$} & $L H \\Sigma$ & 87,535 (20.3\\%) & \\multirow{2}{*}{31,629 (22.3\\%)} \\\\\n & Other & 28,157 (6.5\\%) & \\\\\n \\midrule\n \\multirow{4}{*}{$\\Xi_{1} \\sim (\\mathbf{1}, \\mathbf{3}, 1)_{S}$} & $L L \\Xi_{1}$ & 59,791 (13.9\\%) & \\multirow{4}{*}{51,576 (36.3\\%)} \\\\\n & $H H \\Xi_{1}^{\\dagger}$ & 95,410 (22.1\\%) & \\\\\n & Both & 10,323 (2.4\\%) & \\\\\n & Other & 30,761 (7.1\\%) & \\\\\n \\bottomrule\n \\end{tabular}\n\n" ], [ "import matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nSMALL_SIZE = 15\nMEDIUM_SIZE = 20\nBIGGER_SIZE = 20\n\nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n\nplt.tight_layout()\n\nplt.rcParams.update({\n \"text.usetex\": True,\n \"font.family\": \"serif\",\n \"font.serif\": [\"Computer Modern Roman\"]}\n)\n\nsns.set_palette(\"muted\")", "_____no_output_____" ], [ "latex_labels = []\nfor l in labels:\n if \"pp\" in l:\n new_l = l.replace(\"pp\", \"^{\\prime\\prime}\")\n elif \"p\" in l:\n new_l = l.replace(\"p\", \"^\\prime\")\n else:\n new_l = l\n latex_labels.append(\"$\" + new_l + \"$\")\n\nfilter_bar_df = pd.DataFrame(data={\n \"Operator\": latex_labels, \n \"Unfiltered\": total, \n \"Democratic\": demo,\n \"Dimension\": dimensions\n})\n\ndemo_5 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 5][\"Democratic\"])\ndemo_7 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 7][\"Democratic\"])\ndemo_9 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 9][\"Democratic\"])\ndemo_11 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 11][\"Democratic\"])\n\n\nunf_5 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 5][\"Unfiltered\"])\nunf_7 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 7][\"Unfiltered\"])\nunf_9 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 9][\"Unfiltered\"])\nunf_11 = sum(filter_bar_df[filter_bar_df[\"Dimension\"] == 11][\"Unfiltered\"])\n\nbarplot_df = pd.DataFrame(\n {'Dimension': [5, 7, 9, 11], \n 'Democratic': [demo_5, demo_7, demo_9, demo_11], \n 'Unfiltered': [unf_5-demo_5, unf_7-demo_7, unf_9-demo_9, unf_11-demo_11]}\n)", "_____no_output_____" ], [ "ax = barplot_df.plot.bar(x=\"Dimension\", stacked=True, rot=0)\nax.set_yscale(\"log\")\nax.set_ylabel(\"Number of models\")\nplt.tight_layout()\nplt.savefig(\"/home/garj/filter_barchart_dimension.pdf\")\nplt.savefig(\"/home/garj/filter_barchart_dimension.png\")", "_____no_output_____" ], [ "ops_filter_bar_df = filter_bar_df[filter_bar_df[\"Dimension\"] < 11]\n\nf, ax = plt.subplots(figsize=(7, 10))\n\nsns.barplot(x=\"Unfiltered\", y=\"Operator\", data=ops_filter_bar_df, label=\"Unfiltered\", color=sns.color_palette()[1])\nsns.barplot(x=\"Democratic\", y=\"Operator\", data=ops_filter_bar_df, label=\"Democratic\", color=sns.color_palette()[0])\nax.set_xscale(\"log\")\nax.legend(ncol=2, loc=\"upper right\", frameon=True)\nax.set(xlim=(0, 10000), ylabel=\"Operator\", xlabel=\"Number of models\")\n\nax.text(x=2000, y=7, s=\"$d < 11$\", fontsize=20)\n \nfor tick in ax.yaxis.get_major_ticks()[1::2]:\n tick.set_pad(40)\n\nplt.tight_layout()\nplt.savefig(\"/home/garj/filter_barchart_operators579.pdf\")\nplt.savefig(\"/home/garj/filter_barchart_operators579.png\")", "/usr/local/easybuild-2019/easybuild/software/mpi/gcc/8.3.0/openmpi/3.1.4/jupyter/1.0.0-python-3.7.4/lib/python3.7/site-packages/ipykernel_launcher.py:9: UserWarning: Attempted to set non-positive left xlim on a log-scaled axis.\nInvalid limit will be ignored.\n if __name__ == '__main__':\n" ], [ "import seaborn as sns\nimport matplotlib.pyplot as plt\n\nops_filter_bar_df = filter_bar_df[filter_bar_df[\"Dimension\"] == 11]\n\nf, ax = plt.subplots(figsize=(7, 15))\n\nsns.barplot(x=\"Unfiltered\", y=\"Operator\", data=ops_filter_bar_df, label=\"Unfiltered\", color=sns.color_palette()[1])\nsns.barplot(x=\"Democratic\", y=\"Operator\", data=ops_filter_bar_df, label=\"Democratic\", color=sns.color_palette()[0])\nax.set_xscale(\"log\")\nax.legend(ncol=2, loc=\"upper right\", frameon=True)\nax.set(xlim=(0, 100000), ylabel=\"Operator\", xlabel=\"Number of models\")\n\nax.text(x=12000, y=9, s=\"$d = 11$\", fontsize=22)\n \nfor tick in ax.yaxis.get_major_ticks()[1::2]:\n tick.set_pad(40)\n\nplt.tight_layout()\nplt.savefig(\"/home/garj/filter_barchart_operators11.pdf\")\nplt.savefig(\"/home/garj/filter_barchart_operators11.png\")", "/usr/local/easybuild-2019/easybuild/software/mpi/gcc/8.3.0/openmpi/3.1.4/jupyter/1.0.0-python-3.7.4/lib/python3.7/site-packages/ipykernel_launcher.py:12: UserWarning: Attempted to set non-positive left xlim on a log-scaled axis.\nInvalid limit will be ignored.\n if sys.path[0] == '':\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d039ddecd045d15ff495293dcf25a714f4731785
286,352
ipynb
Jupyter Notebook
Notebooks/machine_learning/knn_Classifier.ipynb
BCHSI/NLP-Project
c5bf0feeb5f94a69808bfee8f193194e9949296d
[ "MIT" ]
null
null
null
Notebooks/machine_learning/knn_Classifier.ipynb
BCHSI/NLP-Project
c5bf0feeb5f94a69808bfee8f193194e9949296d
[ "MIT" ]
null
null
null
Notebooks/machine_learning/knn_Classifier.ipynb
BCHSI/NLP-Project
c5bf0feeb5f94a69808bfee8f193194e9949296d
[ "MIT" ]
null
null
null
255.671429
185,280
0.901202
[ [ [ "import numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "df=pd.read_csv('data_1000.csv')", "_____no_output_____" ], [ "data=df[['correct_answ','bleu_score','levenstein_sim','cosine_sim','jaccard_sim']]", "_____no_output_____" ], [ "data.head(10)", "_____no_output_____" ], [ "data.describe()", "_____no_output_____" ], [ "data.boxplot(by='correct_answ', column=['bleu_score', 'levenstein_sim', 'cosine_sim', 'jaccard_sim'], \n grid=True, figsize=(15,15))", "_____no_output_____" ], [ "X=data[['bleu_score','levenstein_sim','cosine_sim','jaccard_sim']]\ny=data['correct_answ']", "_____no_output_____" ], [ "X.hist(bins=50,figsize=(20,15))", "_____no_output_____" ], [ "from pandas.plotting import scatter_matrix\nscatter_matrix(X, figsize=(14, 10))", "_____no_output_____" ], [ "corr_matrix = data.corr()\ncorr_matrix[\"correct_answ\"].sort_values(ascending=False)", "_____no_output_____" ], [ "data['cos_lev']=data['cosine_sim']+data['levenstein_sim']\ndata['cos_bleu']=data['cosine_sim']+data['bleu_score']\ndata['cos_jac']=data['cosine_sim']+data['jaccard_sim']\ndata['lev_bleu']=data['levenstein_sim']+data['bleu_score']\ndata['lev_jac']=data['levenstein_sim']+data['jaccard_sim']\ndata['bleu_jac']=data['bleu_score']+data['jaccard_sim']", "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"Entry point for launching an IPython kernel.\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n This is separate from the ipykernel package so we can avoid doing imports until\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n after removing the cwd from sys.path.\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:5: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:6: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n" ], [ "corr_matrix = data.corr()\ncorr_matrix[\"correct_answ\"].sort_values(ascending=False)\ncorr_matrix", "_____no_output_____" ], [ "X=data[['bleu_score','levenstein_sim','cosine_sim','jaccard_sim','cos_lev','cos_bleu','cos_jac','lev_bleu','lev_jac','bleu_jac']]\ny=data[['correct_answ']]", "_____no_output_____" ], [ "from sklearn.model_selection import StratifiedShuffleSplit\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\n\nfor train_index, test_index in split.split(data, data[\"correct_answ\"]):\n strat_train_set = data.loc[train_index]\n strat_test_set = data.loc[test_index]", "_____no_output_____" ], [ "data[\"correct_answ\"].value_counts() / len(data)", "_____no_output_____" ], [ "strat_train_set[\"correct_answ\"].value_counts() / len(strat_train_set)", "_____no_output_____" ], [ "strat_test_set[\"correct_answ\"].value_counts() / len(strat_test_set)", "_____no_output_____" ], [ "training = strat_train_set.copy()\ntesting=strat_test_set.copy()", "_____no_output_____" ], [ "X_training=training[['bleu_score','levenstein_sim','cosine_sim','jaccard_sim','cos_lev','cos_bleu','cos_jac','lev_bleu','lev_jac','bleu_jac']]\ny_training=training[['correct_answ']]\nX_testing=testing[['bleu_score','levenstein_sim','cosine_sim','jaccard_sim','cos_lev','cos_bleu','cos_jac','lev_bleu','lev_jac','bleu_jac']]\ny_testing=testing[['correct_answ']]\n", "_____no_output_____" ], [ "from sklearn.neighbors import KNeighborsClassifier\nclf = KNeighborsClassifier(n_neighbors=2).fit(X_training,y_training)\ny_training_prediction = clf.predict(X_training)\ny_testing_prediction = clf.predict(X_testing)", "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:2: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n \n" ], [ "#K_fold confusion_matrix for training sets & Precision score & Recall score\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import precision_score, recall_score\nfrom sklearn.base import clone\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score\nskfolds = StratifiedKFold(n_splits=3, random_state=42)\nfor train_index, test_index in skfolds.split(X_training, y_training):\n clone_clf = clone(clf)\n X_train_folds = X_training.iloc[train_index]\n y_train_folds = y_training.iloc[train_index]\n X_test_fold = X_training.iloc[test_index]\n y_test_fold = y_training.iloc[test_index]\n clone_clf.fit(X_train_folds, y_train_folds)\n y_pred = clone_clf.predict(X_test_fold)\n recall_score(y_test_fold,y_pred)\n print(confusion_matrix(y_test_fold,y_pred))\n print('precision_score: ',precision_score(y_test_fold,y_pred))\n print('recall_score: ',recall_score(y_test_fold,y_pred))\n print('f1_socre: ',f1_score(y_test_fold, y_pred))\n print('')\n print('\\n')\n \n\"\"\" n_correct = sum(y_pred == y_test_fold)\n print(n_correct / len(y_pred)) \"\"\"\n", "[[ 54 3]\n [ 10 205]]\nprecision_score: 0.9855769230769231\nrecall_score: 0.9534883720930233\nf1_socre: 0.9692671394799054\n\n\n\n[[ 54 2]\n [ 18 197]]\nprecision_score: 0.9899497487437185\nrecall_score: 0.9162790697674419\nf1_socre: 0.9516908212560387\n\n\n\n[[ 55 2]\n [ 20 194]]\nprecision_score: 0.9897959183673469\nrecall_score: 0.9065420560747663\nf1_socre: 0.9463414634146342\n\n\n\n" ], [ "# cross_validation score for training sets\nfrom sklearn.model_selection import cross_val_score\ncross_val_score(clf, X_training, y_training, cv=3, scoring=\"accuracy\")", "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/model_selection/_validation.py:515: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n estimator.fit(X_train, y_train, **fit_params)\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/model_selection/_validation.py:515: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n estimator.fit(X_train, y_train, **fit_params)\n/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/model_selection/_validation.py:515: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n estimator.fit(X_train, y_train, **fit_params)\n" ], [ "# testing data validation\nfrom sklearn.metrics import confusion_matrix\nprint('confusion_matrix: \\n',confusion_matrix(y_testing,y_testing_prediction))\nprint('precision_score: ',precision_score(y_testing,y_testing_prediction))\nprint('recall_score: ',recall_score(y_testing,y_testing_prediction))\nprint('f1_socre: ',f1_score(y_testing,y_testing_prediction))\nfrom sklearn.model_selection import cross_val_score\nprint('accuracy: ',cross_val_score(clf, X_testing, y_testing, cv=3, scoring=\"accuracy\"))", "confusion_matrix: \n [[ 40 2]\n [ 12 150]]\nprecision_score: 0.9868421052631579\nrecall_score: 0.9259259259259259\nf1_socre: 0.9554140127388535\naccuracy: [0.82352941 0.79411765 0.91176471]\n" ], [ "import matplotlib.pyplot ", "_____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" ] ]
d03a1fe74ba82fe499f7e4590ecf05889c8543de
14,888
ipynb
Jupyter Notebook
notebooks/Defining-a-POMDP-with-the-Explicit-Interface.ipynb
sylvaticus/POMDPExamples.jl
cdc8339db795b7d57b80550b52e1d708a584bb9c
[ "MIT" ]
14
2018-10-28T20:54:57.000Z
2021-12-31T07:00:05.000Z
notebooks/Defining-a-POMDP-with-the-Explicit-Interface.ipynb
sylvaticus/POMDPExamples.jl
cdc8339db795b7d57b80550b52e1d708a584bb9c
[ "MIT" ]
14
2018-09-28T04:51:39.000Z
2020-10-21T18:42:33.000Z
notebooks/Defining-a-POMDP-with-the-Explicit-Interface.ipynb
sylvaticus/POMDPExamples.jl
cdc8339db795b7d57b80550b52e1d708a584bb9c
[ "MIT" ]
29
2019-02-06T18:10:04.000Z
2022-02-28T18:34:52.000Z
36.400978
604
0.612305
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d03a245e69bf3a459238875395ab85ef4e1c840a
1,481
ipynb
Jupyter Notebook
HomeWork/Day_054_HW.ipynb
rugl/3rd-ML100Days
4c0c0427f623421574a0012b9069c43c27418691
[ "Apache-2.0" ]
null
null
null
HomeWork/Day_054_HW.ipynb
rugl/3rd-ML100Days
4c0c0427f623421574a0012b9069c43c27418691
[ "Apache-2.0" ]
null
null
null
HomeWork/Day_054_HW.ipynb
rugl/3rd-ML100Days
4c0c0427f623421574a0012b9069c43c27418691
[ "Apache-2.0" ]
null
null
null
17.22093
60
0.512492
[ [ [ "# 作業\n* 試著想想看, 非監督學習是否有可能使用評價函數 (Metric) 來鑑別好壞呢? \n(Hint : 可以分為 \"有目標值\" 與 \"無目標值\" 兩個方向思考)", "_____no_output_____" ], [ "## 與監督模型不同,非監督因為沒有目標值,因此無法使用⽬標值的預測與實際差距,來評估模型的優劣", "_____no_output_____" ], [ "# 評估⽅式類型", "_____no_output_____" ], [ "# 1.有⽬標值的分群(資料集有標籤只是先做分群)", "_____no_output_____" ], [ "如果資料有⽬標值,只是先忽略⽬標值做非監督學習,則只要微調後,就可以使預算原本監督的測量函數評估準確度", "_____no_output_____" ], [ "# 2.無⽬標值的分群(資料集無標籤只好先做分群)", "_____no_output_____" ], [ "但通常沒有⽬標值/⽬標值非常少才會預測非監督模型,這種情況下,只能使絲網資料本⾝的分佈資訊,來來做模型的評估", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d03a47fc3600ffa22a02efc72f16ace1720fe6da
2,780
ipynb
Jupyter Notebook
nbfiles/10_bull.ipynb
StevenPZChan/pythonchallenge
84c0e7458189f6d74e2cfbd169d854dae11d07a9
[ "MIT" ]
null
null
null
nbfiles/10_bull.ipynb
StevenPZChan/pythonchallenge
84c0e7458189f6d74e2cfbd169d854dae11d07a9
[ "MIT" ]
null
null
null
nbfiles/10_bull.ipynb
StevenPZChan/pythonchallenge
84c0e7458189f6d74e2cfbd169d854dae11d07a9
[ "MIT" ]
null
null
null
25.272727
130
0.528058
[ [ [ "继续挑战\n\n---\n### 第10题地址[bull.html](http://www.pythonchallenge.com/pc/return/bull.html)\n* <img src=\"http://huge:file@www.pythonchallenge.com/pc/return/bull.jpg\" alt=\"bull.jpg\" width=\"30%\" height=\"30%\">\n* 网页标题是`what are you looking at?`,题目内容是`len(a[30]) = ?`,源码里面没有隐藏内容", "_____no_output_____" ], [ "看到上一题画出来的牛的真面目了!<br>\n同样以牛的轮廓圈起来的区域有一个[超链接](http://www.pythonchallenge.com/pc/return/sequence.txt),点进去是这样的内容\n> a = [1, 11, 21, 1211, 111221, ", "_____no_output_____" ], [ "这样的话,结合题目内容一看,思路也是很清晰的。<br>\n`a`是一个数列,我们要求出`a[30]`的位数。关键是`a`数列是什么规律呢?<br>\n懂行的一看就懂了,反而是数学太好的想不出来,因为它不是任何的数学规律。\n> 外观数列(Look-and-say sequence)第n项描述了第n-1项的数字分布。它以1开始:\n> 1. 1:读作1个“1”,即11\n> 1. 11:读作2个“1”,即21\n> 1. 21:读作1个“2”,1个“1”,即1211\n> 1. 1211:读作1个“1”,1个“2”,2个“1”,即111221\n> 1. 111221:读作3个“1”,2个“2”,1个“1”,即312211\n> \n> 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ... (OEIS中的数列A005150)\n> ###### From [wikipedia.org](https://zh.wikipedia.org/wiki/%E5%A4%96%E8%A7%80%E6%95%B8%E5%88%97)\n\n废话不多说,直接上代码,用正则应该会容易一些:", "_____no_output_____" ] ], [ [ "from itertools import islice\nimport re\n\ndef look_and_say():\n num = '1'\n while True:\n yield num\n m = re.findall(r'((\\d)\\2*)', num)\n num = ''.join(str(len(pat[0])) + pat[1] for pat in m)\n\na = list(islice(look_and_say(), 31))\nprint(len(a[30]))", "5808\n" ] ], [ [ "将网址改成[5808.html](http://www.pythonchallenge.com/pc/return/5808.html),打开来到下一题。", "_____no_output_____" ], [ "### 总结:题目很好理解,数列不难,正则很好用。\n###### 本题代码地址[10_bull.ipynb](https://github.com/StevenPZChan/pythonchallenge/blob/notebook/nbfiles/10_bull.ipynb)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d03a4960e08bf74d4aca96278721c05dc6c50d22
126,795
ipynb
Jupyter Notebook
from github/Stock-Trading-Environment/Get Details (v11)-Copy1 - points.ipynb
LaoKpa/reinforcement_trader
1465731269e6d58900a28a040346bf45ffb5cf97
[ "MIT" ]
7
2020-09-28T23:36:40.000Z
2022-02-22T02:00:32.000Z
from github/Stock-Trading-Environment/Get Details (v11)-Copy1 - points.ipynb
LaoKpa/reinforcement_trader
1465731269e6d58900a28a040346bf45ffb5cf97
[ "MIT" ]
4
2020-11-13T18:48:52.000Z
2022-02-10T01:29:47.000Z
from github/Stock-Trading-Environment/Get Details (v11)-Copy1 - points.ipynb
lzcaisg/reinforcement_trader
1465731269e6d58900a28a040346bf45ffb5cf97
[ "MIT" ]
3
2020-11-23T17:31:59.000Z
2021-04-08T10:55:03.000Z
432.74744
73,308
0.945755
[ [ [ "import pickle\nfrom os import path\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "DIR = \"./output/11\"\nrecord = pickle.load(open(path.join(DIR,\"sp500_3dim_10k-Training_detailed-ModelNo-0.out\"), \"rb\"))\ndf = pd.DataFrame(record)\n", "_____no_output_____" ], [ "plt.scatter(df['date'], df['action'])", "C:\\Users\\lzcai\\Anaconda3\\lib\\site-packages\\pandas\\plotting\\_matplotlib\\converter.py:103: FutureWarning: Using an implicitly registered datetime converter for a matplotlib plotting method. The converter was registered by pandas on import. Future versions of pandas will require you to explicitly register matplotlib converters.\n\nTo register the converters:\n\t>>> from pandas.plotting import register_matplotlib_converters\n\t>>> register_matplotlib_converters()\n warnings.warn(msg, FutureWarning)\n" ], [ "plt.scatter(df['date'], df['action'])", "_____no_output_____" ], [ "plt.scatter(df['date'], df['action'])", "_____no_output_____" ], [ "plt.scatter(df['date'], df['action'])", "_____no_output_____" ], [ "plt.scatter(df['date'], df['action'])", "_____no_output_____" ], [ "plt.scatter(df['date'], df['action'])", "_____no_output_____" ], [ "DIR = \"./output/11\"\nplt.figure(figsize=(20,10))\nfor i in range(10):\n try:\n if i == 0:\n ax0 = plt.subplot(2, 5, 1)\n else:\n plt.subplot(2, 5, i+1, sharex=ax0, sharey = ax0)\n record = pickle.load(open(path.join(DIR,\"sp500_3dim_10k-Training_detailed-ModelNo-\"+str(i)+\".out\"), \"rb\"))\n df = pd.DataFrame(record)\n plt.scatter(df['date'], df['action'])\n except Exception as e:\n print(e)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03a512673055dd673bfc975e468d613619520d9
2,659
ipynb
Jupyter Notebook
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
4939b03dc487b2a7c89039e51ac0e55fb06311e1
[ "MIT" ]
5
2021-08-19T05:06:07.000Z
2022-03-20T12:28:48.000Z
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
4939b03dc487b2a7c89039e51ac0e55fb06311e1
[ "MIT" ]
null
null
null
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
4939b03dc487b2a7c89039e51ac0e55fb06311e1
[ "MIT" ]
1
2022-03-03T19:38:13.000Z
2022-03-03T19:38:13.000Z
18.088435
103
0.499812
[ [ [ "#### Import Libraries", "_____no_output_____" ] ], [ [ "import cv2\nimport numpy as np", "_____no_output_____" ] ], [ [ "#### Load Image", "_____no_output_____" ] ], [ [ "image_data = cv2.imread(r'D:\\Computer Vision Bootcamp\\images\\expert.png')", "_____no_output_____" ] ], [ [ "#### Image Shape", "_____no_output_____" ] ], [ [ "print(image_data.shape)", "(512, 512, 3)\n" ] ], [ [ "#### Show Image at window", "_____no_output_____" ] ], [ [ "cv2.imshow('First Image', image_data)\ncv2.waitKey(6000) ### The window will automatically close after the 6 seconds.\ncv2.destroyAllWindows()", "_____no_output_____" ] ], [ [ "#### Show Image at GrayScale", "_____no_output_____" ] ], [ [ "image_data = cv2.imread(r'D:\\imsanjoykb.github.io\\images\\expert.png',0) ## 0 for grayscale\ncv2.imshow('First Image', image_data)\ncv2.waitKey(6000)\ncv2.destroyAllWindows()", "_____no_output_____" ] ], [ [ "#### Saving The Image", "_____no_output_____" ] ], [ [ "cv2.imwrite('D:\\Computer Vision Bootcamp\\images\\expert_output.png',image_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" ], [ "code" ] ]
d03a5ecb8f8680672b74b59cfb5dd7e6a23924cc
939,851
ipynb
Jupyter Notebook
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
258dd316894c8fcac2d0b7be1be3c18714164e49
[ "MIT" ]
null
null
null
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
258dd316894c8fcac2d0b7be1be3c18714164e49
[ "MIT" ]
null
null
null
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
258dd316894c8fcac2d0b7be1be3c18714164e49
[ "MIT" ]
null
null
null
1,307.164117
889,168
0.957676
[ [ [ "## CIFAR10 using a simple deep networks\n\nCredits: \\\nhttps://medium.com/@sergioalves94/deep-learning-in-pytorch-with-cifar-10-dataset-858b504a6b54 \\\nhttps://jovian.ai/aakashns/05-cifar10-cnn", "_____no_output_____" ] ], [ [ "import torch\nimport torchvision\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.datasets import CIFAR10\nfrom torchvision.transforms import ToTensor\nfrom torchvision.utils import make_grid\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data import random_split\nfrom torchsummary import summary\n%matplotlib inline", "_____no_output_____" ] ], [ [ "### Exploring the data", "_____no_output_____" ] ], [ [ "# Dowload the dataset\ndataset = CIFAR10(root='data/', download=True, transform=ToTensor())", "Files already downloaded and verified\n" ], [ "test_dataset = CIFAR10(root='data/', train=False, transform=ToTensor())", "_____no_output_____" ] ], [ [ "Import the datasets and convert the images into PyTorch tensors.", "_____no_output_____" ] ], [ [ "classes = dataset.classes\nclasses", "_____no_output_____" ], [ "class_count = {}\nfor _, index in dataset:\n label = classes[index]\n if label not in class_count:\n class_count[label] = 0\n class_count[label] += 1\nclass_count", "_____no_output_____" ] ], [ [ "Split the dataset into two groups: training and validation datasets.", "_____no_output_____" ] ], [ [ "torch.manual_seed(43)\nval_size = 5000\ntrain_size = len(dataset) - val_size", "_____no_output_____" ], [ "train_ds, val_ds = random_split(dataset, [train_size, val_size])\nlen(train_ds), len(val_ds)", "_____no_output_____" ], [ "batch_size=128", "_____no_output_____" ], [ "train_loader = DataLoader(train_ds, batch_size, shuffle=True, num_workers=4, pin_memory=True)\nval_loader = DataLoader(val_ds, batch_size*2, num_workers=4, pin_memory=True)\ntest_loader = DataLoader(test_dataset, batch_size*2, num_workers=4, pin_memory=True)", "_____no_output_____" ] ], [ [ "we set `pin_memory=True` because we will push the data from the CPU into the GPU and this parameter lets theDataLoader allocate the samples in page-locked memory, which speeds-up the transfer", "_____no_output_____" ] ], [ [ "for images, _ in train_loader:\n print('images.shape:', images.shape)\n plt.figure(figsize=(16,8))\n plt.axis('off')\n plt.imshow(make_grid(images, nrow=16).permute((1, 2, 0)))\n break", "images.shape: torch.Size([128, 3, 32, 32])\n" ] ], [ [ "### Model", "_____no_output_____" ] ], [ [ "def accuracy(outputs, labels):\n _, preds = torch.max(outputs, dim=1)\n return torch.tensor(torch.sum(preds == labels).item() / len(preds))", "_____no_output_____" ], [ "class ImageClassificationBase(nn.Module):\n def training_step(self, batch):\n images, labels = batch \n out = self(images) # Generate predictions\n loss = F.cross_entropy(out, labels) # Calculate loss\n return loss\n \n def validation_step(self, batch):\n images, labels = batch \n out = self(images) # Generate predictions\n loss = F.cross_entropy(out, labels) # Calculate loss\n acc = accuracy(out, labels) # Calculate accuracy\n return {'val_loss': loss.detach(), 'val_acc': acc}\n \n def validation_epoch_end(self, outputs):\n batch_losses = [x['val_loss'] for x in outputs]\n epoch_loss = torch.stack(batch_losses).mean() # Combine losses\n batch_accs = [x['val_acc'] for x in outputs]\n epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies\n return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}\n \n def epoch_end(self, epoch, result):\n print(\"Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}\".format(epoch,\n result['val_loss'], result['val_acc']))", "_____no_output_____" ], [ "def evaluate(model, val_loader):\n outputs = [model.validation_step(batch) for batch in val_loader]\n return model.validation_epoch_end(outputs)\n\ndef fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):\n history = []\n optimizer = opt_func(model.parameters(), lr)\n for epoch in range(epochs):\n # Training Phase \n for batch in train_loader:\n loss = model.training_step(batch)\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n # Validation phase\n result = evaluate(model, val_loader)\n model.epoch_end(epoch, result)\n history.append(result)\n return history", "_____no_output_____" ], [ "torch.cuda.is_available()", "_____no_output_____" ], [ "def get_default_device():\n \"\"\"Pick GPU if available, else CPU\"\"\"\n if torch.cuda.is_available():\n return torch.device('cuda')\n else:\n return torch.device('cpu')", "_____no_output_____" ], [ "device = get_default_device()\ndevice", "_____no_output_____" ], [ "def to_device(data, device):\n \"\"\"Move tensor(s) to chosen device\"\"\"\n if isinstance(data, (list,tuple)):\n return [to_device(x, device) for x in data]\n return data.to(device, non_blocking=True)\n\nclass DeviceDataLoader():\n \"\"\"Wrap a dataloader to move data to a device\"\"\"\n def __init__(self, dl, device):\n self.dl = dl\n self.device = device\n \n def __iter__(self):\n \"\"\"Yield a batch of data after moving it to device\"\"\"\n for b in self.dl: \n yield to_device(b, self.device)\n\n def __len__(self):\n \"\"\"Number of batches\"\"\"\n return len(self.dl)", "_____no_output_____" ], [ "def plot_losses(history):\n losses = [x['val_loss'] for x in history]\n plt.plot(losses, '-x')\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.title('Loss vs. No. of epochs')", "_____no_output_____" ], [ "train_loader = DeviceDataLoader(train_loader, device)\nval_loader = DeviceDataLoader(val_loader, device)\ntest_loader = DeviceDataLoader(test_loader, device)", "_____no_output_____" ] ], [ [ "### Training the model", "_____no_output_____" ] ], [ [ "input_size = 3*32*32\noutput_size = 10", "_____no_output_____" ], [ "class CIFAR10Model(ImageClassificationBase):\n def __init__(self):\n super().__init__()\n self.linear1 = nn.Linear(input_size, 256)\n self.linear2 = nn.Linear(256, 128)\n self.linear3 = nn.Linear(128, output_size)\n \n def forward(self, xb):\n # Flatten images into vectors\n out = xb.view(xb.size(0), -1)\n # Apply layers & activation functions\n out = self.linear1(out)\n out = F.relu(out)\n out = self.linear2(out)\n out = F.relu(out)\n out = self.linear3(out)\n return out", "_____no_output_____" ], [ "model = to_device(CIFAR10Model(), device)", "_____no_output_____" ], [ "summary(model, (3, 32, 32))", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Linear-1 [-1, 256] 786,688\n Linear-2 [-1, 128] 32,896\n Linear-3 [-1, 10] 1,290\n================================================================\nTotal params: 820,874\nTrainable params: 820,874\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.01\nForward/backward pass size (MB): 0.00\nParams size (MB): 3.13\nEstimated Total Size (MB): 3.15\n----------------------------------------------------------------\n" ], [ "history = [evaluate(model, val_loader)]\nhistory", "_____no_output_____" ], [ "history += fit(10, 1e-1, model, train_loader, val_loader)", "Epoch [0], val_loss: 1.8614, val_acc: 0.3336\nEpoch [1], val_loss: 1.7899, val_acc: 0.3604\nEpoch [2], val_loss: 1.7589, val_acc: 0.3701\nEpoch [3], val_loss: 1.6140, val_acc: 0.4274\nEpoch [4], val_loss: 1.7845, val_acc: 0.3774\nEpoch [5], val_loss: 1.6244, val_acc: 0.4186\nEpoch [6], val_loss: 1.6018, val_acc: 0.4373\nEpoch [7], val_loss: 1.6215, val_acc: 0.4074\nEpoch [8], val_loss: 1.5601, val_acc: 0.4507\nEpoch [9], val_loss: 1.7971, val_acc: 0.3764\n" ], [ "history += fit(10, 1e-2, model, train_loader, val_loader)", "Epoch [0], val_loss: 1.4325, val_acc: 0.4970\nEpoch [1], val_loss: 1.4302, val_acc: 0.4950\nEpoch [2], val_loss: 1.4260, val_acc: 0.4990\nEpoch [3], val_loss: 1.4190, val_acc: 0.5024\nEpoch [4], val_loss: 1.4146, val_acc: 0.4997\nEpoch [5], val_loss: 1.4153, val_acc: 0.5058\nEpoch [6], val_loss: 1.4158, val_acc: 0.5011\nEpoch [7], val_loss: 1.4083, val_acc: 0.5065\nEpoch [8], val_loss: 1.4087, val_acc: 0.5066\nEpoch [9], val_loss: 1.4045, val_acc: 0.5058\n" ], [ "history += fit(10, 1e-3, model, train_loader, val_loader)", "Epoch [0], val_loss: 1.4017, val_acc: 0.5093\nEpoch [1], val_loss: 1.4007, val_acc: 0.5087\nEpoch [2], val_loss: 1.4002, val_acc: 0.5110\nEpoch [3], val_loss: 1.4007, val_acc: 0.5081\nEpoch [4], val_loss: 1.3997, val_acc: 0.5097\nEpoch [5], val_loss: 1.3992, val_acc: 0.5102\nEpoch [6], val_loss: 1.3991, val_acc: 0.5107\nEpoch [7], val_loss: 1.3989, val_acc: 0.5122\nEpoch [8], val_loss: 1.3988, val_acc: 0.5097\nEpoch [9], val_loss: 1.3983, val_acc: 0.5099\n" ], [ "plot_losses(history)", "_____no_output_____" ], [ "def plot_accuracies(history):\n accuracies = [x['val_acc'] for x in history]\n plt.plot(accuracies, '-x')\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.title('Accuracy vs. No. of epochs')", "_____no_output_____" ], [ "plot_accuracies(history)", "_____no_output_____" ], [ "## test set:\nevaluate(model, test_loader)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03a6a1b06ed136b7b73ad7b2fe88d29c4c40b3b
28,999
ipynb
Jupyter Notebook
9_video_classification_eco/9-4_3_ECO_DataLoader.ipynb
ziippy/pytorch_deep_learning_with_12models
59e742caf328b54405d61db4fbd088c455cbcf23
[ "MIT" ]
null
null
null
9_video_classification_eco/9-4_3_ECO_DataLoader.ipynb
ziippy/pytorch_deep_learning_with_12models
59e742caf328b54405d61db4fbd088c455cbcf23
[ "MIT" ]
null
null
null
9_video_classification_eco/9-4_3_ECO_DataLoader.ipynb
ziippy/pytorch_deep_learning_with_12models
59e742caf328b54405d61db4fbd088c455cbcf23
[ "MIT" ]
null
null
null
33.066135
120
0.480465
[ [ [ "# Kinetics 데이터 세트로 ECO용 DataLoader 작성\n\nKineteics 동영상 데이터를 사용해, ECO용 DataLoader를 만듭니다\n", "_____no_output_____" ], [ "# 9.4 학습 목표\n\n1.\tKinetics 동영상 데이터 세트를 다운로드할 수 있다\n2.\t동영상 데이터를 프레임별 화상 데이터로 변환할 수 있다\n3.\tECO에서 사용하기 위한 DataLoader를 구현할 수 있다\n", "_____no_output_____" ], [ "# 사전 준비\n\n- 이 책의 지시에 따라 Kinetics 동영상 데이터와, 화상 데이터를 frame별로 화상 데이터로 변환하는 조작을 수행해주세요\n\n- 가상 환경 pytorch_p36에서 실행합니다", "_____no_output_____" ] ], [ [ "import os\nfrom PIL import Image\nimport csv\nimport numpy as np\n\nimport torch\nimport torch.utils.data\nfrom torch import nn\n\nimport torchvision", "_____no_output_____" ] ], [ [ "# 동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트를 작성", "_____no_output_____" ] ], [ [ "def make_datapath_list(root_path):\n \"\"\"\n 동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트를 작성한다.\n root_path : str, 데이터 폴더로의 root 경로\n Returns: ret : video_list, 동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트\n \"\"\"\n\n # 동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트\n video_list = list()\n\n # root_path의 클래스 종류와 경로를 취득\n class_list = os.listdir(path=root_path)\n\n # 각 클래스의 동영상 파일을 화상으로 만든 폴더의 경로를 취득\n for class_list_i in (class_list): # 클래스별로 루프\n\n # 클래스의 폴더 경로를 취득\n class_path = os.path.join(root_path, class_list_i)\n\n # 각 클래스의 폴더 내 화상 폴더를 취득하는 루프\n for file_name in os.listdir(class_path):\n\n # 파일명과 확장자로 분할\n name, ext = os.path.splitext(file_name)\n\n # mp4 파일이 아니거나, 폴더 등은 무시\n if ext == '.mp4':\n continue\n\n # 동영상 파일을 화상으로 분할해 저장한 폴더의 경로를 취득\n video_img_directory_path = os.path.join(class_path, name)\n\n # vieo_list에 추가\n video_list.append(video_img_directory_path)\n\n return video_list\n\n\n# 동작 확인\nroot_path = './data/kinetics_videos/'\nvideo_list = make_datapath_list(root_path)\nprint(video_list[0])\nprint(video_list[1])\n", "./data/kinetics_videos/arm wrestling/C4lCVBZ3ux0_000028_000038\n./data/kinetics_videos/arm wrestling/ehLnj7pXnYE_000027_000037\n" ] ], [ [ "# 동영상 전처리 클래스를 작성", "_____no_output_____" ] ], [ [ "class VideoTransform():\n \"\"\"\n 동영상을 화상으로 만드는 전처리 클래스. 학습시와 추론시 다르게 작동합니다.\n 동영상을 화상으로 분할하고 있으므로, 분할된 화상을 한꺼번에 전처리하는 점에 주의하십시오.\n \"\"\"\n\n def __init__(self, resize, crop_size, mean, std):\n self.data_transform = {\n 'train': torchvision.transforms.Compose([\n # DataAugumentation() # 이번에는 생략\n GroupResize(int(resize)), # 화상을 한꺼번에 리사이즈\n GroupCenterCrop(crop_size), # 화상을 한꺼번에 center crop\n GroupToTensor(), # 데이터를 PyTorch 텐서로\n GroupImgNormalize(mean, std), # 데이터를 표준화\n Stack() # 여러 화상을 frames차원으로 결합시킨다\n ]),\n 'val': torchvision.transforms.Compose([\n GroupResize(int(resize)), # 화상을 한꺼번에 리사이즈\n GroupCenterCrop(crop_size), # 화상을 한꺼번에 center crop\n GroupToTensor(), # 데이터를 PyTorch 텐서로\n GroupImgNormalize(mean, std), # 데이터를 표준화\n Stack() # 여러 화상을 frames차원으로 결합시킨다\n ])\n }\n\n def __call__(self, img_group, phase):\n \"\"\"\n Parameters\n ----------\n phase : 'train' or 'val'\n 전처리 모드 지정\n \"\"\"\n return self.data_transform[phase](img_group)\n", "_____no_output_____" ], [ "# 전처리로 사용할 클래스들을 정의\nclass GroupResize():\n '''화상 크기를 한꺼번에 재조정(rescale)하는 클래스.\n 화상의 짧은 변의 길이가 resize로 변환된다.\n 화면 비율은 유지된다.\n '''\n\n def __init__(self, resize, interpolation=Image.BILINEAR):\n '''rescale 처리 준비'''\n self.rescaler = torchvision.transforms.Resize(resize, interpolation)\n\n def __call__(self, img_group):\n '''img_group(리스트)의 각 img에 rescale 실시'''\n return [self.rescaler(img) for img in img_group]\n\n\nclass GroupCenterCrop():\n '''화상을 한꺼번에 center crop 하는 클래스.\n (crop_size, crop_size)의 화상을 잘라낸다.\n '''\n\n def __init__(self, crop_size):\n '''center crop 처리를 준비'''\n self.ccrop = torchvision.transforms.CenterCrop(crop_size)\n\n def __call__(self, img_group):\n '''img_group(리스트)의 각 img에 center crop 실시'''\n return [self.ccrop(img) for img in img_group]\n\n\nclass GroupToTensor():\n '''화상을 한꺼번에 텐서로 만드는 클래스.\n '''\n\n def __init__(self):\n '''텐서화하는 처리를 준비'''\n self.to_tensor = torchvision.transforms.ToTensor()\n\n def __call__(self, img_group):\n '''img_group(리스트)의 각 img에 텐서화 실시\n 0부터 1까지가 아니라, 0부터 255까지를 다루므로, 255를 곱해서 계산한다.\n 0부터 255로 다루는 것은, 학습된 데이터 형식에 맞추기 위함\n '''\n\n return [self.to_tensor(img)*255 for img in img_group]\n\n\nclass GroupImgNormalize():\n '''화상을 한꺼번에 표준화하는 클래스.\n '''\n\n def __init__(self, mean, std):\n '''표준화 처리를 준비'''\n self.normlize = torchvision.transforms.Normalize(mean, std)\n\n def __call__(self, img_group):\n '''img_group(리스트)의 각 img에 표준화 실시'''\n return [self.normlize(img) for img in img_group]\n\n\nclass Stack():\n '''화상을 하나의 텐서로 정리하는 클래스.\n '''\n\n def __call__(self, img_group):\n '''img_group은 torch.Size([3, 224, 224])를 요소로 하는 리스트\n '''\n ret = torch.cat([(x.flip(dims=[0])).unsqueeze(dim=0)\n for x in img_group], dim=0) # frames 차원으로 결합\n # x.flip(dims=[0])은 색상 채널을 RGB에서 BGR으로 순서를 바꾸고 있습니다(원래의 학습 데이터가 BGR이었기 때문입니다)\n # unsqueeze(dim=0)은 새롭게 frames용의 차원을 작성하고 있습니다\n\n return ret\n", "_____no_output_____" ] ], [ [ "# Dataset 작성", "_____no_output_____" ] ], [ [ "# Kinetics-400의 라벨명을 ID로 변환하는 사전과, 반대로 ID를 라벨명으로 변환하는 사전을 준비\ndef get_label_id_dictionary(label_dicitionary_path='./video_download/kinetics_400_label_dicitionary.csv'):\n label_id_dict = {}\n id_label_dict = {}\n\n with open(label_dicitionary_path, encoding=\"utf-8_sig\") as f:\n\n # 읽어들이기\n reader = csv.DictReader(f, delimiter=\",\", quotechar='\"')\n\n # 1행씩 읽어, 사전형 변수에 추가합니다\n for row in reader:\n label_id_dict.setdefault(\n row[\"class_label\"], int(row[\"label_id\"])-1)\n id_label_dict.setdefault(\n int(row[\"label_id\"])-1, row[\"class_label\"])\n\n return label_id_dict, id_label_dict\n\n\n# 확인\nlabel_dicitionary_path = './video_download/kinetics_400_label_dicitionary.csv'\nlabel_id_dict, id_label_dict = get_label_id_dictionary(label_dicitionary_path)\nlabel_id_dict\n", "_____no_output_____" ], [ "class VideoDataset(torch.utils.data.Dataset):\n \"\"\"\n 동영상 Dataset\n \"\"\"\n\n def __init__(self, video_list, label_id_dict, num_segments, phase, transform, img_tmpl='image_{:05d}.jpg'):\n self.video_list = video_list # 동영상 폴더의 경로 리스트\n self.label_id_dict = label_id_dict # 라벨명을 id로 변환하는 사전형 변수\n self.num_segments = num_segments # 동영상을 어떻게 분할해 사용할지를 결정\n self.phase = phase # train or val\n self.transform = transform # 전처리\n self.img_tmpl = img_tmpl # 읽어들일 화상 파일명의 템플릿\n\n def __len__(self):\n '''동영상 수를 반환'''\n return len(self.video_list)\n\n def __getitem__(self, index):\n '''\n 전처리한 화상들의 데이터와 라벨, 라벨 ID를 취득\n '''\n imgs_transformed, label, label_id, dir_path = self.pull_item(index)\n return imgs_transformed, label, label_id, dir_path\n\n def pull_item(self, index):\n '''전처리한 화상들의 데이터와 라벨, 라벨 ID를 취득'''\n\n # 1. 화상들을 리스트에서 읽기\n dir_path = self.video_list[index] # 화상이 저장된 폴더\n indices = self._get_indices(dir_path) # 읽어들일 화상 idx를 구하기\n img_group = self._load_imgs(\n dir_path, self.img_tmpl, indices) # 리스트로 읽기\n\n # 2. 라벨을 취득해 id로 변환\n label = (dir_path.split('/')[3].split('/')[0])\n label_id = self.label_id_dict[label] # id를 취득\n\n # 3. 전처리 실시\n imgs_transformed = self.transform(img_group, phase=self.phase)\n\n return imgs_transformed, label, label_id, dir_path\n\n def _load_imgs(self, dir_path, img_tmpl, indices):\n '''화상을 한꺼번에 읽어들여, 리스트화하는 함수'''\n img_group = [] # 화상을 저장할 리스트\n\n for idx in indices:\n # 화상 경로 취득\n file_path = os.path.join(dir_path, img_tmpl.format(idx))\n\n # 화상 읽기\n img = Image.open(file_path).convert('RGB')\n\n # 리스트에 추가\n img_group.append(img)\n return img_group\n\n def _get_indices(self, dir_path):\n \"\"\"\n 동영상 전체를 self.num_segment로 분할했을 때의 동영상 idx의 리스트를 취득\n \"\"\"\n # 동영상 프레임 수 구하기\n file_list = os.listdir(path=dir_path)\n num_frames = len(file_list)\n\n # 동영상의 간격을 구하기\n tick = (num_frames) / float(self.num_segments)\n # 250 / 16 = 15.625\n # 동영상 간격으로 꺼낼 때 idx를 리스트로 구하기\n indices = np.array([int(tick / 2.0 + tick * x)\n for x in range(self.num_segments)])+1\n # 250frame에서 16frame 추출의 경우\n # indices = [ 8 24 40 55 71 86 102 118 133 149 165 180 196 211 227 243]\n\n return indices\n", "_____no_output_____" ], [ "# 동작 확인\n\n# vieo_list 작성\nroot_path = './data/kinetics_videos/'\nvideo_list = make_datapath_list(root_path)\n\n# 전처리 설정\nresize, crop_size = 224, 224\nmean, std = [104, 117, 123], [1, 1, 1]\nvideo_transform = VideoTransform(resize, crop_size, mean, std)\n\n# Dataset 작성\n# num_segments는 동영상을 어떻게 분할해 사용할지 정한다\nval_dataset = VideoDataset(video_list, label_id_dict, num_segments=16,\n phase=\"val\", transform=video_transform, img_tmpl='image_{:05d}.jpg')\n\n# 데이터를 꺼내는 예\n# 출력은 imgs_transformed, label, label_id, dir_path\nindex = 0\nprint(val_dataset.__getitem__(index)[0].shape) # 동영상의 텐서\nprint(val_dataset.__getitem__(index)[1]) # 라벨\nprint(val_dataset.__getitem__(index)[2]) # 라벨ID\nprint(val_dataset.__getitem__(index)[3]) # 동영상 경로\n", "torch.Size([16, 3, 224, 224])\narm wrestling\n6\n./data/kinetics_videos/arm wrestling/C4lCVBZ3ux0_000028_000038\n" ], [ "# DataLoader로 합니다\nbatch_size = 8\nval_dataloader = torch.utils.data.DataLoader(\n val_dataset, batch_size=batch_size, shuffle=False)\n\n# 동작 확인\nbatch_iterator = iter(val_dataloader) # 반복자로 변환\nimgs_transformeds, labels, label_ids, dir_path = next(\n batch_iterator) # 1번째 요소를 꺼낸다\nprint(imgs_transformeds.shape)\n", "torch.Size([8, 16, 3, 224, 224])\n" ] ], [ [ "끝", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
d03a7c84df28348ed4943bbb23b7ca5653698164
84,989
ipynb
Jupyter Notebook
ICCT_hr/examples/01/.ipynb_checkpoints/M-02-Kompleksni_brojevi_polarni_sustav-checkpoint.ipynb
ICCTerasmus/ICCT
fcd56ab6b5fddc00f72521cc87accfdbec6068f6
[ "BSD-3-Clause" ]
6
2021-05-22T18:42:14.000Z
2021-10-03T14:10:22.000Z
ICCT_hr/examples/01/.ipynb_checkpoints/M-02-Kompleksni_brojevi_polarni_sustav-checkpoint.ipynb
ICCTerasmus/ICCT
fcd56ab6b5fddc00f72521cc87accfdbec6068f6
[ "BSD-3-Clause" ]
null
null
null
ICCT_hr/examples/01/.ipynb_checkpoints/M-02-Kompleksni_brojevi_polarni_sustav-checkpoint.ipynb
ICCTerasmus/ICCT
fcd56ab6b5fddc00f72521cc87accfdbec6068f6
[ "BSD-3-Clause" ]
2
2021-05-24T11:40:09.000Z
2021-08-29T16:36:18.000Z
64.483308
31,940
0.65925
[ [ [ "from IPython.display import HTML\n\n# Cell visibility - COMPLETE:\n#tag = HTML('''<style>\n#div.input {\n# display:none;\n#}\n#</style>''')\n#display(tag)\n\n#Cell visibility - TOGGLE:\ntag = HTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide()\n } else {\n $('div.input').show()\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\n<p style=\"text-align:right\">\nPromijeni vidljivost <a href=\"javascript:code_toggle()\">ovdje</a>.</p>''')\ndisplay(tag)", "_____no_output_____" ] ], [ [ "## Kompleksni brojevi u polarnom obliku\n\nU ovome interaktivnom primjeru, kompleksni brojevi se vizualiziraju u kompleksnoj ravnini, a određuju se koristeći polarni oblik. Kompleksni brojevi se, dakle, određuju modulom (duljinom odgovarajućeg vektora) i argumentom (kutom odgovarajućeg vektora). Možete testirati osnovne matematičke operacije nad kompleksnim brojevima: zbrajanje, oduzimanje, množenje i dijeljenje. Svi se rezultati prikazuju na odgovarajućem grafu, kao i u matematičkoj notaciji zasnovanoj na polarnom obliku kompleksnog broja.\n\nKompleksnim brojevima možete manipulirati izravno na grafu (jednostavnim klikom) i / ili istovremeno koristiti odgovarajuća polja za unos modula i argumenta. Kako bi se osigurala bolja vidljivost vektora na grafu, modul kompleksnog broja je ograničen na $\\pm10$.", "_____no_output_____" ] ], [ [ "%matplotlib notebook\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport ipywidgets as widgets\nfrom IPython.display import display\nfrom IPython.display import HTML\nimport math\n\nred_patch = mpatches.Patch(color='red', label='z1')\nblue_patch = mpatches.Patch(color='blue', label='z2')\ngreen_patch = mpatches.Patch(color='green', label='z1 + z2')\nyellow_patch = mpatches.Patch(color='yellow', label='z1 - z2')\nblack_patch = mpatches.Patch(color='black', label='z1 * z2')\nmagenta_patch = mpatches.Patch(color='magenta', label='z1 / z2')\n\n# Init values\n\nXLIM = 5\nYLIM = 5\nvectors_index_first = False;\nV = [None, None]\nV_complex = [None, None]\n\n# Complex plane\n\nfig = plt.figure(num='Kompleksni brojevi u polarnom obliku')\nax = fig.add_subplot(1, 1, 1)\n\ndef get_interval(lim):\n if lim <= 10:\n return 1\n if lim < 75:\n return 5\n if lim > 100:\n return 25\n return 10\n \ndef set_ticks():\n \n XLIMc = int((XLIM / 10) + 1) * 10\n YLIMc = int((YLIM / 10) + 1) * 10\n \n if XLIMc > 150:\n XLIMc += 10\n if YLIMc > 150:\n YLIMc += 10\n \n xstep = get_interval(XLIMc)\n ystep = get_interval(YLIMc)\n \n \n #print(stepx, stepy)\n major_ticks = np.arange(-XLIMc, XLIMc, xstep)\n major_ticks_y = np.arange(-YLIMc, YLIMc, ystep)\n ax.set_xticks(major_ticks)\n ax.set_yticks(major_ticks_y)\n ax.grid(which='both')\n\ndef clear_plot():\n plt.cla()\n set_ticks()\n ax.set_xlabel('Re')\n ax.set_ylabel('Im')\n plt.ylim([-YLIM, YLIM])\n plt.xlim([-XLIM, XLIM])\n plt.legend(handles=[red_patch, blue_patch, green_patch, yellow_patch, black_patch, magenta_patch])\n\nclear_plot()\nset_ticks()\nplt.show()\nset_ticks()\n\n\n# Conversion functions\ndef com_to_trig(real, im):\n r = math.sqrt(real**2 + im**2)\n if abs(real) <= 1e-6 and im > 0:\n arg = 90\n return r, arg\n \n if abs(real) < 1e-6 and im < 0:\n arg = 270\n return r, arg\n \n if abs(im) < 1e-6 and real > 0:\n arg = 0\n return r, arg\n \n if abs(im) < 1e-6 and real < 0:\n arg = 180\n return r, arg\n \n if im != 0 and real !=0:\n arg = np.arctan(im / real) * 180 / np.pi\n if im > 0 and real < 0:\n arg += 180\n \n if im < 0 and real > 0:\n arg +=360\n \n if im < 0 and real < 0:\n arg += 180\n return r, arg\n \n if abs(im) < 1e-6 and abs(real) < 1e-6:\n arg = 0\n return r, arg\n \ndef trig_to_com(r, arg):\n re = r * np.cos(arg * np.pi / 180.)\n im = r * np.sin(arg * np.pi / 180.)\n return (re, im)\n\n# Set a complex number using direct manipulation on the plot \ndef set_vector(i, data_x, data_y):\n clear_plot()\n V.pop(i)\n V.insert(i, (0, 0, round(data_x, 2), round(data_y, 2)))\n V_complex.pop(i)\n V_complex.insert(i, complex(round(data_x, 2), round(data_y, 2)))\n if i == 0:\n ax.arrow(*V[0], head_width=0.25, head_length=0.5, color=\"r\", length_includes_head=True)\n z, arg = com_to_trig(data_x, data_y)\n a1.value = round(z, 2)\n b1.value = round(arg, 2)\n if V[1] != None:\n ax.arrow(*V[1], head_width=0.25, head_length=0.5, color=\"b\", length_includes_head=True)\n elif i == 1:\n ax.arrow(*V[1], head_width=0.25, head_length=0.5, color=\"b\", length_includes_head=True) \n z, arg = com_to_trig(data_x, data_y)\n a2.value = round(z, 2)\n b2.value = round(arg, 2)\n if V[0] != None:\n ax.arrow(*V[0], head_width=0.25, head_length=0.5, color=\"r\", length_includes_head=True)\n max_bound()\n \n \ndef onclick(event):\n global vectors_index_first\n vectors_index_first = not vectors_index_first\n x = event.xdata\n y = event.ydata\n if (x > 10):\n x = 10.0\n if (x < - 10):\n x = -10.0\n \n if (y > 10):\n y = 10.0\n \n if (y < - 10):\n y = -10.0\n \n if vectors_index_first: \n set_vector(0, x, y)\n else:\n set_vector(1, x, y)\n \nfig.canvas.mpl_connect('button_press_event', onclick)\n\n \n# Widgets\na1 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 10, step = 0.5)\nb1 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 360, step = 10)\nbutton_set_z1 = widgets.Button(description=\"Prikaži z1\")\n\na2 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 10, step = 0.5)\nb2 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 360, step = 10)\nbutton_set_z2 = widgets.Button(description=\"Prikaži z2\")\n\nbox_layout_z1 = widgets.Layout(border='solid red', padding='10px')\nbox_layout_z2 = widgets.Layout(border='solid blue', padding='10px')\nbox_layout_opers = widgets.Layout(border='solid black', padding='10px')\n\nitems_z1 = [widgets.Label(\"z1: Duljina (|z1|) = \"), a1, widgets.Label(\"Kut (\\u2221)= \"), b1, button_set_z1]\nitems_z2 = [widgets.Label(\"z2: Duljina (|z2|) = \"), a2, widgets.Label(\"Kut (\\u2221)= \"), b2, button_set_z2]\ndisplay(widgets.Box(children=items_z1, layout=box_layout_z1))\ndisplay(widgets.Box(children=items_z2, layout=box_layout_z2))\n\nbutton_add = widgets.Button(description=\"Zbroji\")\nbutton_substract = widgets.Button(description=\"Oduzmi\")\nbutton_multiply = widgets.Button(description=\"Pomnoži\")\nbutton_divide = widgets.Button(description=\"Podijeli\")\nbutton_reset = widgets.Button(description=\"Resetiraj\")\noutput = widgets.Output()\n\nprint('Operacije nad kompleksnim brojevima:')\nitems_operations = [button_add, button_substract, button_multiply, button_divide, button_reset]\ndisplay(widgets.Box(children=items_operations))\ndisplay(output)\n\n# Set complex number using input widgets (Text and Button)\ndef on_button_set_z1_clicked(b):\n z1_old = V[0];\n re, im = trig_to_com(a1.value, b1.value)\n z1_new = (0, 0, re, im)\n if z1_old != z1_new:\n set_vector(0, re, im)\n change_lims()\n \ndef on_button_set_z2_clicked(b):\n z2_old = V[1];\n re, im = trig_to_com(a2.value, b2.value)\n z2_new = (0, 0, re, im)\n if z2_old != z2_new:\n set_vector(1, re, im)\n change_lims() \n\n# Complex number operations:\ndef perform_operation(oper):\n global XLIM, YLIM\n if (V_complex[0] != None) and (V_complex[1] != None):\n if (oper == '+'):\n result = V_complex[0] + V_complex[1]\n v_color = \"g\"\n elif (oper == '-'):\n result = V_complex[0] - V_complex[1]\n v_color = \"y\"\n elif (oper == '*'):\n result = V_complex[0] * V_complex[1]\n v_color = \"black\"\n elif (oper == '/'):\n result = V_complex[0] / V_complex[1]\n v_color = \"magenta\"\n result = complex(round(result.real, 2), round(result.imag, 2))\n ax.arrow(0, 0, result.real, result.imag, head_width=0.25, head_length=0.15, color=v_color, length_includes_head=True)\n \n if abs(result.real) > XLIM:\n XLIM = round(abs(result.real) + 1)\n if abs(result.imag) > YLIM:\n YLIM = round(abs(result.imag) + 1)\n change_lims()\n \n with output:\n z1, ang1 = com_to_trig(V_complex[0].real, V_complex[0].imag )\n z2, ang2 = com_to_trig(V_complex[1].real, V_complex[1].imag)\n z3, ang3 = com_to_trig(result.real, result.imag)\n z1 = round(z1, 2)\n ang1 = round(ang1, 2)\n z2 = round(z2, 2)\n ang2 = round(ang2, 2)\n z3 = round(z3, 2)\n ang3 = round(ang3, 2)\n \n print(\"{}*(cos({}) + i*sin({}))\".format(z1,ang1,ang1), oper, \n \"{}*(cos({}) + i*sin({}))\".format(z2,ang2,ang2), \"=\",\n \"{}*(cos({}) + i*sin({}))\".format(z3,ang3,ang3))\n \n print('{} \\u2221{}'.format(z1, ang1), oper,\n '{} \\u2221{}'.format(z2, ang2), \"=\",\n '{} \\u2221{}'.format(z3, ang3))\n \n \ndef on_button_add_clicked(b):\n perform_operation(\"+\")\n \ndef on_button_substract_clicked(b):\n perform_operation(\"-\")\n\ndef on_button_multiply_clicked(b):\n perform_operation(\"*\")\n\ndef on_button_divide_clicked(b):\n perform_operation(\"/\")\n \n \n# Plot init methods \ndef on_button_reset_clicked(b):\n global V, V_complex, XLIM, YLIM\n with output:\n output.clear_output()\n clear_plot()\n vectors_index_first = False;\n V = [None, None]\n V_complex = [None, None]\n a1.value = 0\n b1.value = 0\n a2.value = 0\n b2.value = 0\n XLIM = 5\n YLIM = 5\n change_lims()\n \ndef clear_plot():\n plt.cla()\n set_ticks()\n ax.set_xlabel('Re')\n ax.set_ylabel('Im')\n plt.ylim([-YLIM, YLIM])\n plt.xlim([-XLIM, XLIM])\n plt.legend(handles=[red_patch, blue_patch, green_patch, yellow_patch, black_patch, magenta_patch])\n\ndef change_lims():\n set_ticks()\n plt.ylim([-YLIM, YLIM])\n plt.xlim([-XLIM, XLIM])\n set_ticks()\n \ndef max_bound():\n global XLIM, YLIM\n mx = 0\n my = 0\n if V_complex[0] != None:\n z = V_complex[0]\n if abs(z.real) > mx:\n mx = abs(z.real)\n if abs(z.imag) > my:\n my = abs(z.imag)\n if V_complex[1] != None:\n z = V_complex[1]\n if abs(z.real) > mx:\n mx = abs(z.real)\n if abs(z.imag) > my:\n my = abs(z.imag)\n if mx > XLIM:\n XLIM = round(mx + 1)\n elif mx <=5:\n XLIM = 5\n if my > YLIM:\n YLIM = round(my + 1)\n elif my <=5:\n YLIM = 5\n change_lims()\n\n# Button events\nbutton_set_z1.on_click(on_button_set_z1_clicked)\nbutton_set_z2.on_click(on_button_set_z2_clicked)\nbutton_add.on_click(on_button_add_clicked)\nbutton_substract.on_click(on_button_substract_clicked)\nbutton_multiply.on_click(on_button_multiply_clicked)\nbutton_divide.on_click(on_button_divide_clicked)\nbutton_reset.on_click(on_button_reset_clicked)\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ] ]
d03a7ffedc4935f6d3a6f78d8a62422434e6fdc8
191,859
ipynb
Jupyter Notebook
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
4719afdb6e90e9deb91268fe9a88e1cbf2b34a86
[ "BSD-3-Clause" ]
null
null
null
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
4719afdb6e90e9deb91268fe9a88e1cbf2b34a86
[ "BSD-3-Clause" ]
null
null
null
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
4719afdb6e90e9deb91268fe9a88e1cbf2b34a86
[ "BSD-3-Clause" ]
null
null
null
264.268595
54,224
0.923621
[ [ [ "# Tutorial 09: Standard problem 5\n\n> Interactive online tutorial:\n> [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ubermag/oommfc/master?filepath=docs%2Fipynb%2Findex.ipynb)\n\n## Problem specification\n\nThe sample is a thin film cuboid with dimensions:\n\n- length $l_{x} = 100 \\,\\text{nm}$,\n- width $l_{y} = 100 \\,\\text{nm}$, and\n- thickness $l_{z} = 10 \\,\\text{nm}$.\n\nThe material parameters (similar to permalloy) are:\n\n- exchange energy constant $A = 1.3 \\times 10^{-11} \\,\\text{J/m}$,\n- magnetisation saturation $M_\\text{s} = 8 \\times 10^{5} \\,\\text{A/m}$.\n\nDynamics parameters are: $\\gamma_{0} = 2.211 \\times 10^{5} \\,\\text{m}\\,\\text{A}^{-1}\\,\\text{s}^{-1}$ and Gilbert damping $\\alpha=0.02$.\n\nIn the standard problem 5, the system is firstly relaxed at zero external magnetic field, starting from the vortex state. Secondly spin-polarised current is applied in the $x$ direction with $u_{x} = -72.35$ and $\\beta=0.05$.\n\nMore detailed specification of Standard problem 5 can be found in Ref. 1.\n\n## Simulation\n\nIn the first step, we import the required `discretisedfield` and `oommfc` modules.", "_____no_output_____" ] ], [ [ "import oommfc as oc\nimport discretisedfield as df\nimport micromagneticmodel as mm", "_____no_output_____" ] ], [ [ "Now, we can set all required geometry and material parameters.", "_____no_output_____" ] ], [ [ "# Geometry\nlx = 100e-9 # x dimension of the sample(m)\nly = 100e-9 # y dimension of the sample (m)\nlz = 10e-9 # sample thickness (m)\ndx = dy = dz = 5e-9 #discretisation cell (nm)\n\n# Material (permalloy) parameters\nMs = 8e5 # saturation magnetisation (A/m)\nA = 1.3e-11 # exchange energy constant (J/m)\n\n# Dynamics (LLG equation) parameters\ngamma0 = 2.211e5 # gyromagnetic ratio (m/As)\nalpha = 0.1 # Gilbert damping\nux = -72.35 # velocity in x direction\nbeta = 0.05 # non-adiabatic STT parameter", "_____no_output_____" ] ], [ [ "As usual, we create the system object with `stdprob5` name.", "_____no_output_____" ] ], [ [ "system = mm.System(name='stdprob5')", "_____no_output_____" ] ], [ [ "The mesh is created by providing two points `p1` and `p2` between which the mesh domain spans and the size of a discretisation cell. We choose the discretisation to be $(5, 5, 5) \\,\\text{nm}$.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nregion = df.Region(p1=(0, 0, 0), p2=(lx, ly, lz))\nmesh = df.Mesh(region=region, cell=(dx, dy, dz))\nmesh.k3d()", "_____no_output_____" ] ], [ [ "**Hamiltonian:** In the second step, we define the system's Hamiltonian. In this standard problem, the Hamiltonian contains only exchange and demagnetisation energy terms. Please note that in the first simulation stage, there is no applied external magnetic field. Therefore, we do not add Zeeman energy term to the Hamiltonian.", "_____no_output_____" ] ], [ [ "system.energy = mm.Exchange(A=A) + mm.Demag()\nsystem.energy", "_____no_output_____" ] ], [ [ "**Magnetisation:** We initialise the system using the initial magnetisation function.", "_____no_output_____" ] ], [ [ "def m_vortex(pos):\n x, y, z = pos[0]/1e-9-50, pos[1]/1e-9-50, pos[2]/1e-9\n \n return (-y, x, 10)\n\nsystem.m = df.Field(mesh, dim=3, value=m_vortex, norm=Ms)\nsystem.m.plane(z=0).mpl()", "_____no_output_____" ] ], [ [ "**Dynamics:** In the first (relaxation) stage, we minimise the system's energy and therefore we do not need to specify the dynamics equation.\n\n**Minimisation:** Now, we minimise the system's energy using `MinDriver`.", "_____no_output_____" ] ], [ [ "md = oc.MinDriver()\nmd.drive(system)", "Running OOMMF (ExeOOMMFRunner) [2020/06/14 11:28]... (2.1 s)\n" ], [ "system.m.plane(z=0).mpl()", "_____no_output_____" ] ], [ [ "## Spin-polarised current", "_____no_output_____" ], [ "In the second part of simulation, we need to specify the dynamics equation for the system.", "_____no_output_____" ] ], [ [ "system.dynamics += mm.Precession(gamma0=gamma0) + mm.Damping(alpha=alpha) + mm.ZhangLi(u=ux, beta=beta)\nsystem.dynamics", "_____no_output_____" ] ], [ [ "Now, we can drive the system for $8 \\,\\text{ns}$ and save the magnetisation in $n=100$ steps.", "_____no_output_____" ] ], [ [ "td = oc.TimeDriver()\ntd.drive(system, t=8e-9, n=100)", "Running OOMMF (ExeOOMMFRunner) [2020/06/14 11:28]... (17.4 s)\n" ] ], [ [ "The vortex after $8 \\,\\text{ns}$ is now displaced from the centre.", "_____no_output_____" ] ], [ [ "system.m.plane(z=0).mpl()", "_____no_output_____" ], [ "system.table.data.plot('t', 'mx')", "_____no_output_____" ] ], [ [ "## References\n\n[1] µMAG Site Directory: http://www.ctcms.nist.gov/~rdm/mumag.org.html", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d03a8d34333204366ff0e13a50a1aaef1d972924
4,410
ipynb
Jupyter Notebook
submission_createcsv.ipynb
georgehtliu/ignition-hack-2020
ec30cc572cab832b2846f5727b9097c2b0725da4
[ "MIT" ]
1
2020-08-24T02:49:08.000Z
2020-08-24T02:49:08.000Z
submission_createcsv.ipynb
georgehtliu/ignition-hack-2020
ec30cc572cab832b2846f5727b9097c2b0725da4
[ "MIT" ]
null
null
null
submission_createcsv.ipynb
georgehtliu/ignition-hack-2020
ec30cc572cab832b2846f5727b9097c2b0725da4
[ "MIT" ]
1
2020-11-13T12:36:15.000Z
2020-11-13T12:36:15.000Z
26.727273
249
0.492971
[ [ [ "<a href=\"https://colab.research.google.com/github/georgehtliu/sentiment-analyzer/blob/master/submission_createcsv.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Importing Libraries\nJoblib used for ease of importing files. Pandas used for data manipulation.", "_____no_output_____" ] ], [ [ "import joblib\nimport pandas as pd", "_____no_output_____" ] ], [ [ "# Importing Classifier, Vectorizer, and Judgement Data\nSupport for importing from local storage as well as importing from Google Drive for Google Colab.", "_____no_output_____" ] ], [ [ "# Assuming files are stored locally in the same directory.\nclf_log = joblib.load(SentimentNewton_Log.pkl)\n\nvectorizer = joblib.load(Vectorizer.pkl)\n\njudge_data_path = \"judgement_data.csv\"\n\n# Uncomment to import files from Google Drive on Google Colab\n\"\"\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\nclf_path = input('Please enter path to SentimentNewton_Log')\nclf_log = joblib.load(clf_path)\n\nvect_path = input('Please enter path to Vectorizer')\nvectorizer = joblib.load(vect_path)\n\njudge_data_path = input(\"Please enter the path to your judgement_data.csv file in your Google Drive.\")\n\"\"\"", "_____no_output_____" ] ], [ [ "# Processing Imported Files\nPreparing dataframe and vectors.", "_____no_output_____" ] ], [ [ "# Convert csv file to dataframe\ndf_judge = pd.read_csv(judge_data_path)\ndf_mini = df_judge\n\nX = df_mini['Text']\nX_vectors= vectorizer.transform(X)", "_____no_output_____" ] ], [ [ "# Writing to CSV File\nEdit the *csv_path* variable to decide where the csv will be stored.", "_____no_output_____" ] ], [ [ "csv_path = '/content/drive/My Drive/predicted_labels.csv'\n\ndf_mini['Sentiment'] = clf_log.predict(X_vectors)\ndf_mini.to_csv(csv_path) \nprint(\"Done!\")", "Done!\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d03a915a121d543c1a99ec62d57ccc1bcc275e09
337,425
ipynb
Jupyter Notebook
Cluster.ipynb
CaseOLAP/IonChannel
e4cd947ff0b74cdc78bdde56b454139145361a47
[ "MIT" ]
null
null
null
Cluster.ipynb
CaseOLAP/IonChannel
e4cd947ff0b74cdc78bdde56b454139145361a47
[ "MIT" ]
null
null
null
Cluster.ipynb
CaseOLAP/IonChannel
e4cd947ff0b74cdc78bdde56b454139145361a47
[ "MIT" ]
null
null
null
529.709576
211,756
0.930865
[ [ [ "## Hierarchical Clustering", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nsns.set()\n%matplotlib inline\nimport json", "_____no_output_____" ], [ "data = pd.read_csv('../result/caseolap.csv')\ndata = data.set_index('protein')\nndf = data\nndf.head(2)", "_____no_output_____" ], [ "ndf.shape", "_____no_output_____" ], [ "ndata = ndf.copy(deep = True)\nndf.describe()", "_____no_output_____" ] ], [ [ "#### Clustering", "_____no_output_____" ] ], [ [ "size=(25,25)\ng = sns.clustermap(ndf.T.corr(),\\\n figsize=size,\\\n cmap = \"YlGnBu\",\\\n metric='seuclidean')\n\n\n\ng.savefig('plots/cluster.pdf', format='pdf', dpi=300)\ng.savefig('plots/cluster.png', format='png', dpi=300)\n\nindx = g.dendrogram_row.reordered_ind", "_____no_output_____" ], [ "protein_cluster = []\nfor num in indx:\n for i,ndx in enumerate(ndf.index):\n if num == i:\n protein_cluster.append({'id':i,\"protein\": ndx,\\\n 'CM' : list(ndf.loc[ndx,:])[0],\\\n 'ARR': list(ndf.loc[ndx,:])[1],\\\n 'CHD' : list(ndf.loc[ndx,:])[2],\\\n 'VD' : list(ndf.loc[ndx,:])[3],\\\n 'IHD' : list(ndf.loc[ndx,:])[4],\\\n 'CCS' : list(ndf.loc[ndx,:])[5],\\\n 'VOO' : list(ndf.loc[ndx,:])[6],\\\n 'OHD' : list(ndf.loc[ndx,:])[7]})\n ", "_____no_output_____" ], [ "protein_cluster_df = pd.DataFrame(protein_cluster)\nprotein_cluster_df = protein_cluster_df.set_index(\"protein\")", "_____no_output_____" ], [ "protein_cluster_df = protein_cluster_df.drop([\"id\"], axis = 1)\nprotein_cluster_df.head()", "_____no_output_____" ] ], [ [ "#### Barplot", "_____no_output_____" ] ], [ [ "protein_cluster_df.plot.barh(stacked=True,figsize=(10,20))\nplt.gca().invert_yaxis()\nplt.legend(fontsize =10)\nplt.savefig('plots/cluster-bar.pdf')\nplt.savefig('plots/cluster-bar.png')", "_____no_output_____" ], [ "with open(\"data/id2name.json\",\"r\")as f:\n id2name = json.load(f)\n\nnames = []\nfor item in protein_cluster_df.index:\n names.append(id2name[item])\n\nprotein_cluster_df['names'] =names\nprotein_cluster_df.head(1)", "_____no_output_____" ], [ "protein_cluster_df.to_csv(\"data/protein-cluster-bar-data.csv\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d03a9ad2b7e0e4442d5cca5d4ceca5d187595ad6
437,019
ipynb
Jupyter Notebook
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
b66adc1e6cbbbb5785aaf8d3cdd97460d1bf74a3
[ "MIT" ]
2
2020-12-15T09:21:05.000Z
2022-01-06T19:41:21.000Z
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
b66adc1e6cbbbb5785aaf8d3cdd97460d1bf74a3
[ "MIT" ]
null
null
null
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
b66adc1e6cbbbb5785aaf8d3cdd97460d1bf74a3
[ "MIT" ]
null
null
null
437,019
437,019
0.815136
[ [ [ "Mount my google drive, where I stored the dataset.", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "_____no_output_____" ] ], [ [ "**Download dependencies**", "_____no_output_____" ] ], [ [ "!pip3 install sklearn matplotlib GPUtil", "Collecting sklearn\n Downloading https://files.pythonhosted.org/packages/1e/7a/dbb3be0ce9bd5c8b7e3d87328e79063f8b263b2b1bfa4774cb1147bfcd3f/sklearn-0.0.tar.gz\nCollecting matplotlib\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/4e/11/06958a2b895a3853206dea1fb2a5b11bf044f626f90745987612af9c8f2c/matplotlib-3.1.2-cp36-cp36m-manylinux1_x86_64.whl (13.1MB)\n\u001b[K |████████████████████████████████| 13.1MB 11.3MB/s eta 0:00:01\n\u001b[?25hCollecting GPUtil\n Downloading https://files.pythonhosted.org/packages/ed/0e/5c61eedde9f6c87713e89d794f01e378cfd9565847d4576fa627d758c554/GPUtil-1.4.0.tar.gz\nCollecting scikit-learn\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/2e/d0/860c4f6a7027e00acff373d9f5327f4ae3ed5872234b3cbdd7bcb52e5eff/scikit_learn-0.22-cp36-cp36m-manylinux1_x86_64.whl (7.0MB)\n\u001b[K |████████████████████████████████| 7.0MB 9.6MB/s eta 0:00:01\n\u001b[?25hCollecting kiwisolver>=1.0.1\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/f8/a1/5742b56282449b1c0968197f63eae486eca2c35dcd334bab75ad524e0de1/kiwisolver-1.1.0-cp36-cp36m-manylinux1_x86_64.whl (90kB)\n\u001b[K |████████████████████████████████| 92kB 10.3MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2.8.1)\nRequirement already satisfied: numpy>=1.11 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (1.18.0)\nCollecting cycler>=0.10\n Downloading https://files.pythonhosted.org/packages/f7/d2/e07d3ebb2bd7af696440ce7e754c59dd546ffe1bbe732c8ab68b9c834e61/cycler-0.10.0-py2.py3-none-any.whl\nCollecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/5d/bc/1e58593167fade7b544bfe9502a26dc860940a79ab306e651e7f13be68c2/pyparsing-2.4.6-py2.py3-none-any.whl (67kB)\n\u001b[K |████████████████████████████████| 71kB 6.5MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn) (1.4.1)\nCollecting joblib>=0.11\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/28/5c/cf6a2b65a321c4a209efcdf64c2689efae2cb62661f8f6f4bb28547cf1bf/joblib-0.14.1-py2.py3-none-any.whl (294kB)\n\u001b[K |████████████████████████████████| 296kB 17.6MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from kiwisolver>=1.0.1->matplotlib) (42.0.2)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.1->matplotlib) (1.13.0)\nBuilding wheels for collected packages: sklearn, GPUtil\n Building wheel for sklearn (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for sklearn: filename=sklearn-0.0-py2.py3-none-any.whl size=2397 sha256=3f58b247fe7b967d5a01c9e82c9229ecf61904d71eb561d4706c8c6edb3683b4\n Stored in directory: /root/.cache/pip/wheels/76/03/bb/589d421d27431bcd2c6da284d5f2286c8e3b2ea3cf1594c074\n Building wheel for GPUtil (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for GPUtil: filename=GPUtil-1.4.0-cp36-none-any.whl size=8219 sha256=a42823d1f13786526074e2b9f963cc44198281e834d62dc78606fb7e68c55339\n Stored in directory: /root/.cache/pip/wheels/3d/77/07/80562de4bb0786e5ea186911a2c831fdd0018bda69beab71fd\nSuccessfully built sklearn GPUtil\nInstalling collected packages: joblib, scikit-learn, sklearn, kiwisolver, cycler, pyparsing, matplotlib, GPUtil\nSuccessfully installed GPUtil-1.4.0 cycler-0.10.0 joblib-0.14.1 kiwisolver-1.1.0 matplotlib-3.1.2 pyparsing-2.4.6 scikit-learn-0.22 sklearn-0.0\n" ], [ "!pip3 install torch torchvision", "Collecting torch\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/88/95/90e8c4c31cfc67248bf944ba42029295b77159982f532c5689bcfe4e9108/torch-1.3.1-cp36-cp36m-manylinux1_x86_64.whl (734.6MB)\n\u001b[K |████████████████████████████████| 734.6MB 56kB/s s eta 0:00:01 |▉ | 18.6MB 3.0MB/s eta 0:03:57 |▉ | 19.9MB 3.0MB/s eta 0:03:56 |███████▉ | 178.8MB 21.2MB/s eta 0:00:27 |████████▎ | 190.0MB 21.2MB/s eta 0:00:26 |████████▍ | 193.0MB 4.0MB/s eta 0:02:14 |██████████▍ | 237.8MB 16.2MB/s eta 0:00:31 |██████████▌ | 240.1MB 16.2MB/s eta 0:00:31 |██████████▊ | 244.9MB 16.2MB/s eta 0:00:31 |██████████▊ | 246.1MB 16.2MB/s eta 0:00:31 |███████████ | 254.7MB 26.0MB/s eta 0:00:19 |██████████████▌ | 333.4MB 26.9MB/s eta 0:00:15 |██████████████████▊ | 429.2MB 12.5MB/s eta 0:00:25 |██████████████████████▊ | 521.4MB 22.4MB/s eta 0:00:10 |████████████████████████▌ | 563.3MB 18.3MB/s eta 0:00:10 |██████████████████████████▉ | 615.9MB 23.2MB/s eta 0:00:06 |███████████████████████████▊ | 635.2MB 23.2MB/s eta 0:00:05 |████████████████████████████ | 642.2MB 23.2MB/s eta 0:00:04 |█████████████████████████████▎ | 672.9MB 14.3MB/s eta 0:00:05 |███████████████████████████████ | 713.0MB 18.8MB/s eta 0:00:02\n\u001b[?25hCollecting torchvision\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/9b/e2/2b1f88a363ae37b2ba52cfb785ddfb3dd5f7e7ec9459e96fd8299b84ae39/torchvision-0.4.2-cp36-cp36m-manylinux1_x86_64.whl (10.2MB)\n\u001b[K |████████████████████████████████| 10.2MB 15.3MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch) (1.18.0)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.13.0)\nCollecting pillow>=4.1.1\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/10/5c/0e94e689de2476c4c5e644a3bd223a1c1b9e2bdb7c510191750be74fa786/Pillow-6.2.1-cp36-cp36m-manylinux1_x86_64.whl (2.1MB)\n\u001b[K |████████████████████████████████| 2.1MB 21.9MB/s eta 0:00:01 |██▋ | 174kB 21.9MB/s eta 0:00:01\n\u001b[?25hInstalling collected packages: torch, pillow, torchvision\nSuccessfully installed pillow-6.2.1 torch-1.3.1 torchvision-0.4.2\n" ] ], [ [ "**Download Data**", "_____no_output_____" ], [ "In order to acquire the dataset please navigate to:\n\nhttps://ieee-dataport.org/documents/cervigram-image-dataset\n\nUnzip the dataset into the folder \"dataset\".\n\nFor your environment, please adjust the paths accordingly.", "_____no_output_____" ] ], [ [ "!rm -vrf \"dataset\"\n!mkdir \"dataset\"\n# !cp -r \"/content/drive/My Drive/Studiu doctorat leziuni cervicale/cervigram-image-dataset-v2.zip\" \"dataset/cervigram-image-dataset-v2.zip\"\n!cp -r \"cervigram-image-dataset-v2.zip\" \"dataset/cervigram-image-dataset-v2.zip\"\n!unzip \"dataset/cervigram-image-dataset-v2.zip\" -d \"dataset\"", "removed directory 'dataset'\nArchive: dataset/cervigram-image-dataset-v2.zip\n creating: dataset/data/\n creating: dataset/data/test/\n creating: dataset/data/test/0/\n creating: dataset/data/test/0/20151103002/\n inflating: dataset/data/test/0/20151103002/20151103113458.jpg \n inflating: dataset/data/test/0/20151103002/20151103113637.jpg \n inflating: dataset/data/test/0/20151103002/20151103113659.jpg \n inflating: dataset/data/test/0/20151103002/20151103113722.jpg \n inflating: dataset/data/test/0/20151103002/20151103113752.jpg \n inflating: dataset/data/test/0/20151103002/20151103113755.jpg \n inflating: dataset/data/test/0/20151103002/20151103113833.jpg \n creating: dataset/data/test/0/20151103005/\n inflating: dataset/data/test/0/20151103005/20151103161719.jpg \n inflating: dataset/data/test/0/20151103005/20151103161836.jpg \n inflating: dataset/data/test/0/20151103005/20151103161908.jpg \n inflating: dataset/data/test/0/20151103005/20151103161938.jpg \n inflating: dataset/data/test/0/20151103005/20151103162027.jpg \n inflating: dataset/data/test/0/20151103005/20151103162122.jpg \n inflating: dataset/data/test/0/20151103005/20151103162254.jpg \n creating: dataset/data/test/0/20151106002/\n inflating: dataset/data/test/0/20151106002/20151106101644.jpg \n inflating: dataset/data/test/0/20151106002/20151106101845.jpg \n inflating: dataset/data/test/0/20151106002/20151106101905.jpg \n inflating: dataset/data/test/0/20151106002/20151106101935.jpg \n inflating: dataset/data/test/0/20151106002/20151106101957.jpg \n inflating: dataset/data/test/0/20151106002/20151106102000.jpg \n inflating: dataset/data/test/0/20151106002/20151106102110.jpg \n creating: dataset/data/test/0/20151111002/\n inflating: dataset/data/test/0/20151111002/20151111144157.jpg \n inflating: dataset/data/test/0/20151111002/20151111144348.jpg \n inflating: dataset/data/test/0/20151111002/20151111144420.jpg \n inflating: dataset/data/test/0/20151111002/20151111144506.jpg \n inflating: dataset/data/test/0/20151111002/20151111144511.jpg \n inflating: dataset/data/test/0/20151111002/20151111144515.jpg \n inflating: dataset/data/test/0/20151111002/20151111144654.jpg \n creating: dataset/data/test/0/20151111004/\n inflating: dataset/data/test/0/20151111004/20151111150820.jpg \n inflating: dataset/data/test/0/20151111004/20151111151033.jpg \n inflating: dataset/data/test/0/20151111004/20151111151104.jpg \n inflating: dataset/data/test/0/20151111004/20151111151127.jpg \n inflating: dataset/data/test/0/20151111004/20151111151152.jpg \n inflating: dataset/data/test/0/20151111004/20151111151160.jpg \n inflating: dataset/data/test/0/20151111004/20151111151245.jpg \n creating: dataset/data/test/0/20151111007/\n inflating: dataset/data/test/0/20151111007/20151111154450.jpg \n inflating: dataset/data/test/0/20151111007/20151111154626.jpg \n inflating: dataset/data/test/0/20151111007/20151111154652.jpg \n inflating: dataset/data/test/0/20151111007/20151111154725.jpg \n inflating: dataset/data/test/0/20151111007/20151111154740.jpg \n inflating: dataset/data/test/0/20151111007/20151111154800.jpg \n inflating: dataset/data/test/0/20151111007/20151111154900.jpg \n creating: dataset/data/test/0/20151111010/\n inflating: dataset/data/test/0/20151111010/20151111162830.jpg \n inflating: dataset/data/test/0/20151111010/20151111162959.jpg \n inflating: dataset/data/test/0/20151111010/20151111163012.jpg \n inflating: dataset/data/test/0/20151111010/20151111163041.jpg \n inflating: dataset/data/test/0/20151111010/20151111163105.jpg \n inflating: dataset/data/test/0/20151111010/20151111163115.jpg \n inflating: dataset/data/test/0/20151111010/20151111163257.jpg \n creating: dataset/data/test/0/20151113012/\n inflating: dataset/data/test/0/20151113012/20151113163733.jpg \n inflating: dataset/data/test/0/20151113012/20151113163859.jpg \n inflating: dataset/data/test/0/20151113012/20151113163928.jpg \n inflating: dataset/data/test/0/20151113012/20151113164000.jpg \n inflating: dataset/data/test/0/20151113012/20151113164028.jpg \n inflating: dataset/data/test/0/20151113012/20151113164100.jpg \n inflating: dataset/data/test/0/20151113012/20151113164201.jpg \n creating: dataset/data/test/0/20151117005/\n inflating: dataset/data/test/0/20151117005/20151117111950.jpg \n inflating: dataset/data/test/0/20151117005/20151117112126.jpg \n inflating: dataset/data/test/0/20151117005/20151117112146.jpg \n inflating: dataset/data/test/0/20151117005/20151117112246.jpg \n inflating: dataset/data/test/0/20151117005/20151117112314.jpg \n inflating: dataset/data/test/0/20151117005/20151117112400.jpg \n inflating: dataset/data/test/0/20151117005/20151117112508.jpg \n creating: dataset/data/test/0/20151118006/\n inflating: dataset/data/test/0/20151118006/20151118144223.jpg \n inflating: dataset/data/test/0/20151118006/20151118144344.jpg \n inflating: dataset/data/test/0/20151118006/20151118144414.jpg \n inflating: dataset/data/test/0/20151118006/20151118144448.jpg \n inflating: dataset/data/test/0/20151118006/20151118144519.jpg \n inflating: dataset/data/test/0/20151118006/20151118144600.jpg \n inflating: dataset/data/test/0/20151118006/20151118144610.jpg \n creating: dataset/data/test/0/20151118009/\n inflating: dataset/data/test/0/20151118009/20151118160649.jpg \n inflating: dataset/data/test/0/20151118009/20151118160839.jpg \n inflating: dataset/data/test/0/20151118009/20151118160853.jpg \n inflating: dataset/data/test/0/20151118009/20151118160924.jpg \n inflating: dataset/data/test/0/20151118009/20151118160952.jpg \n inflating: dataset/data/test/0/20151118009/20151118160970.jpg \n inflating: dataset/data/test/0/20151118009/20151118161030.jpg \n creating: dataset/data/test/0/20151118011/\n inflating: dataset/data/test/0/20151118011/20151118162920.jpg \n inflating: dataset/data/test/0/20151118011/20151118163100.jpg \n inflating: dataset/data/test/0/20151118011/20151118163137.jpg \n inflating: dataset/data/test/0/20151118011/20151118163150.jpg \n inflating: dataset/data/test/0/20151118011/20151118163215.jpg \n inflating: dataset/data/test/0/20151118011/20151118163218.jpg \n inflating: dataset/data/test/0/20151118011/20151118163318.jpg \n creating: dataset/data/test/1/\n creating: dataset/data/test/1/162231763/\n inflating: dataset/data/test/1/162231763/162231763Image0.jpg \n inflating: dataset/data/test/1/162231763/162231763Image2.jpg \n inflating: dataset/data/test/1/162231763/162231763Image3.jpg \n inflating: dataset/data/test/1/162231763/162231763Image5.jpg \n inflating: dataset/data/test/1/162231763/162231763Image6.jpg \n inflating: dataset/data/test/1/162231763/162231763Image7.jpg \n inflating: dataset/data/test/1/162231763/162231763Image8.jpg \n creating: dataset/data/test/1/163856190/\n inflating: dataset/data/test/1/163856190/163856190Image0.jpg \n inflating: dataset/data/test/1/163856190/163856190Image2.jpg \n inflating: dataset/data/test/1/163856190/163856190Image3.jpg \n inflating: dataset/data/test/1/163856190/163856190Image5.jpg \n inflating: dataset/data/test/1/163856190/163856190Image6.jpg \n inflating: dataset/data/test/1/163856190/163856190Image7.jpg \n inflating: dataset/data/test/1/163856190/163856190Image9.jpg \n creating: dataset/data/test/1/164145173/\n inflating: dataset/data/test/1/164145173/164145173Image0.jpg \n inflating: dataset/data/test/1/164145173/164145173Image2.jpg \n inflating: dataset/data/test/1/164145173/164145173Image3.jpg \n inflating: dataset/data/test/1/164145173/164145173Image4.jpg \n inflating: dataset/data/test/1/164145173/164145173Image6.jpg \n inflating: dataset/data/test/1/164145173/164145173Image7.jpg \n inflating: dataset/data/test/1/164145173/164145173Image8.jpg \n creating: dataset/data/test/1/165554510/\n inflating: dataset/data/test/1/165554510/165554510Image0.jpg \n inflating: dataset/data/test/1/165554510/165554510Image3.jpg \n inflating: dataset/data/test/1/165554510/165554510Image4.jpg \n inflating: dataset/data/test/1/165554510/165554510Image5.jpg \n inflating: dataset/data/test/1/165554510/165554510Image6.jpg \n inflating: dataset/data/test/1/165554510/165554510Image7.jpg \n inflating: dataset/data/test/1/165554510/165554510Image8.jpg \n creating: dataset/data/test/1/171212253/\n inflating: dataset/data/test/1/171212253/171212253Image0.jpg \n inflating: dataset/data/test/1/171212253/171212253Image3.jpg \n inflating: dataset/data/test/1/171212253/171212253Image4.jpg \n inflating: dataset/data/test/1/171212253/171212253Image5.jpg \n inflating: dataset/data/test/1/171212253/171212253Image6.jpg \n inflating: dataset/data/test/1/171212253/171212253Image8.jpg \n inflating: dataset/data/test/1/171212253/171212253Image9.jpg \n creating: dataset/data/test/1/20150729004/\n inflating: dataset/data/test/1/20150729004/20150729142418.jpg \n inflating: dataset/data/test/1/20150729004/20150729142536.jpg \n inflating: dataset/data/test/1/20150729004/20150729142617.jpg \n inflating: dataset/data/test/1/20150729004/20150729142638.jpg \n inflating: dataset/data/test/1/20150729004/20150729142712.jpg \n inflating: dataset/data/test/1/20150729004/20150729142728.jpg \n inflating: dataset/data/test/1/20150729004/20150729143009.jpg \n creating: dataset/data/test/1/20150731002/\n inflating: dataset/data/test/1/20150731002/20150731164116.jpg \n inflating: dataset/data/test/1/20150731002/20150731164301.jpg \n inflating: dataset/data/test/1/20150731002/20150731164316.jpg \n inflating: dataset/data/test/1/20150731002/20150731164344.jpg \n inflating: dataset/data/test/1/20150731002/20150731164411.jpg \n inflating: dataset/data/test/1/20150731002/20150731164418.jpg \n inflating: dataset/data/test/1/20150731002/20150731164556.jpg \n creating: dataset/data/test/1/20150812006/\n inflating: dataset/data/test/1/20150812006/20150812143825.jpg \n inflating: dataset/data/test/1/20150812006/20150812143943.jpg \n inflating: dataset/data/test/1/20150812006/20150812144013.jpg \n inflating: dataset/data/test/1/20150812006/20150812144047.jpg \n inflating: dataset/data/test/1/20150812006/20150812144114.jpg \n inflating: dataset/data/test/1/20150812006/20150812144206.jpg \n inflating: dataset/data/test/1/20150812006/20150812144318.jpg \n creating: dataset/data/test/1/20150818001/\n inflating: dataset/data/test/1/20150818001/20150818113423.jpg \n inflating: dataset/data/test/1/20150818001/20150818113549.jpg \n inflating: dataset/data/test/1/20150818001/20150818113620.jpg \n inflating: dataset/data/test/1/20150818001/20150818113649.jpg \n inflating: dataset/data/test/1/20150818001/20150818113719.jpg \n inflating: dataset/data/test/1/20150818001/20150818113721.jpg \n inflating: dataset/data/test/1/20150818001/20150818113827.jpg \n creating: dataset/data/test/1/20150819006/\n inflating: dataset/data/test/1/20150819006/20150819152524.jpg \n inflating: dataset/data/test/1/20150819006/20150819152652.jpg \n inflating: dataset/data/test/1/20150819006/20150819152726.jpg \n inflating: dataset/data/test/1/20150819006/20150819152755.jpg \n inflating: dataset/data/test/1/20150819006/20150819152825.jpg \n inflating: dataset/data/test/1/20150819006/20150819152827.jpg \n inflating: dataset/data/test/1/20150819006/20150819152905.jpg \n creating: dataset/data/test/1/20150819011/\n inflating: dataset/data/test/1/20150819011/20150819163415.jpg \n inflating: dataset/data/test/1/20150819011/20150819163538.jpg \n inflating: dataset/data/test/1/20150819011/20150819163608.jpg \n inflating: dataset/data/test/1/20150819011/20150819163638.jpg \n inflating: dataset/data/test/1/20150819011/20150819163708.jpg \n inflating: dataset/data/test/1/20150819011/20150819163778.jpg \n inflating: dataset/data/test/1/20150819011/20150819163805.jpg \n creating: dataset/data/test/1/20150826008/\n inflating: dataset/data/test/1/20150826008/20150826153113.jpg \n inflating: dataset/data/test/1/20150826008/20150826153241.jpg \n inflating: dataset/data/test/1/20150826008/20150826153310.jpg \n inflating: dataset/data/test/1/20150826008/20150826153340.jpg \n inflating: dataset/data/test/1/20150826008/20150826153410.jpg \n inflating: dataset/data/test/1/20150826008/20150826153425.jpg \n inflating: dataset/data/test/1/20150826008/20150826153539.jpg \n creating: dataset/data/test/2/\n creating: dataset/data/test/2/162021000/\n inflating: dataset/data/test/2/162021000/162021000Image0.jpg \n inflating: dataset/data/test/2/162021000/162021000Image100.jpg \n inflating: dataset/data/test/2/162021000/162021000Image3.jpg \n inflating: dataset/data/test/2/162021000/162021000Image6.jpg \n inflating: dataset/data/test/2/162021000/162021000Image70.jpg \n inflating: dataset/data/test/2/162021000/162021000Image8.jpg \n inflating: dataset/data/test/2/162021000/162021000Image9.jpg \n creating: dataset/data/test/2/162334723/\n inflating: dataset/data/test/2/162334723/162334723Image0.jpg \n inflating: dataset/data/test/2/162334723/162334723Image10.jpg \n inflating: dataset/data/test/2/162334723/162334723Image12.jpg \n inflating: dataset/data/test/2/162334723/162334723Image2.jpg \n inflating: dataset/data/test/2/162334723/162334723Image4.jpg \n inflating: dataset/data/test/2/162334723/162334723Image8.jpg \n inflating: dataset/data/test/2/162334723/162334723Image9.jpg \n creating: dataset/data/test/2/162403397/\n inflating: dataset/data/test/2/162403397/162403397Image0.jpg \n inflating: dataset/data/test/2/162403397/162403397Image1.jpg \n inflating: dataset/data/test/2/162403397/162403397Image100.jpg \n inflating: dataset/data/test/2/162403397/162403397Image3.jpg \n inflating: dataset/data/test/2/162403397/162403397Image4.jpg \n inflating: dataset/data/test/2/162403397/162403397Image80.jpg \n inflating: dataset/data/test/2/162403397/162403397Image9.jpg \n creating: dataset/data/test/2/163138313/\n inflating: dataset/data/test/2/163138313/163138313Image0.jpg \n inflating: dataset/data/test/2/163138313/163138313Image2.jpg \n inflating: dataset/data/test/2/163138313/163138313Image3.jpg \n inflating: dataset/data/test/2/163138313/163138313Image4.jpg \n inflating: dataset/data/test/2/163138313/163138313Image5.jpg \n" ] ], [ [ "**Constants**", "_____no_output_____" ], [ "For your environment, please modify the paths accordingly. ", "_____no_output_____" ] ], [ [ "# TRAIN_PATH = '/content/dataset/data/train/'\n# TEST_PATH = '/content/dataset/data/test/'\nTRAIN_PATH = 'dataset/data/train/'\nTEST_PATH = 'dataset/data/test/'\n\nCROP_SIZE = 260\nIMAGE_SIZE = 224\nBATCH_SIZE = 100", "_____no_output_____" ] ], [ [ "**Imports**", "_____no_output_____" ] ], [ [ "import torch as t\nimport torchvision as tv\nimport numpy as np\nimport PIL as pil\nimport matplotlib.pyplot as plt\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import DataLoader\nfrom torch.nn import Linear, BCEWithLogitsLoss\nimport sklearn as sk\nimport sklearn.metrics\nfrom os import listdir\nimport time\nimport random\nimport GPUtil", "_____no_output_____" ] ], [ [ "**Memory Stats**", "_____no_output_____" ] ], [ [ "import GPUtil\ndef memory_stats():\n for gpu in GPUtil.getGPUs():\n print(\"GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB\".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal))\nmemory_stats()", "GPU RAM Free: 10721MB | Used: 267MB | Util 2% | Total 10988MB\nGPU RAM Free: 10988MB | Used: 1MB | Util 0% | Total 10989MB\nGPU RAM Free: 10988MB | Used: 1MB | Util 0% | Total 10989MB\nGPU RAM Free: 10988MB | Used: 1MB | Util 0% | Total 10989MB\n" ] ], [ [ "**Deterministic Measurements**", "_____no_output_____" ], [ "This statements help making the experiments reproducible by fixing the random seeds. Despite fixing the random seeds, experiments are usually not reproducible using different PyTorch releases, commits, platforms or between CPU and GPU executions. Please find more details in the PyTorch documentation:\n\nhttps://pytorch.org/docs/stable/notes/randomness.html", "_____no_output_____" ] ], [ [ "SEED = 0\nt.manual_seed(SEED)\nt.cuda.manual_seed(SEED)\nt.backends.cudnn.deterministic = True\nt.backends.cudnn.benchmark = False\nnp.random.seed(SEED)\nrandom.seed(SEED)", "_____no_output_____" ] ], [ [ "**Loading Data**", "_____no_output_____" ], [ "The dataset is structured in multiple small folders of 7 images each. This generator iterates through the folders and returns the category and 7 paths: one for each image in the folder. The paths are ordered; the order is important since each folder contains 3 types of images, first 5 are with acetic acid solution and the last two are through a green lens and having iodine solution(a solution of a dark red color).", "_____no_output_____" ] ], [ [ "def sortByLastDigits(elem):\n chars = [c for c in elem if c.isdigit()]\n return 0 if len(chars) == 0 else int(''.join(chars))\n\ndef getImagesPaths(root_path):\n for class_folder in [root_path + f for f in listdir(root_path)]:\n category = int(class_folder[-1])\n for case_folder in listdir(class_folder):\n case_folder_path = class_folder + '/' + case_folder + '/'\n img_files = [case_folder_path + file_name for file_name in listdir(case_folder_path)]\n yield category, sorted(img_files, key = sortByLastDigits)", "_____no_output_____" ] ], [ [ "We define 3 datasets, which load 3 kinds of images: natural images, images taken through a green lens and images where the doctor applied iodine solution (which gives a dark red color). Each dataset has dynamic and static transformations which could be applied to the data. The static transformations are applied on the initialization of the dataset, while the dynamic ones are applied when loading each batch of data. ", "_____no_output_____" ] ], [ [ "class SimpleImagesDataset(t.utils.data.Dataset):\n def __init__(self, root_path, transforms_x_static = None, transforms_x_dynamic = None, transforms_y_static = None, transforms_y_dynamic = None):\n self.dataset = []\n self.transforms_x = transforms_x_dynamic\n self.transforms_y = transforms_y_dynamic\n for category, img_files in getImagesPaths(root_path):\n for i in range(5):\n img = pil.Image.open(img_files[i])\n if transforms_x_static != None:\n img = transforms_x_static(img)\n if transforms_y_static != None:\n category = transforms_y_static(category)\n self.dataset.append((img, category)) \n \n def __getitem__(self, i):\n x, y = self.dataset[i]\n if self.transforms_x != None:\n x = self.transforms_x(x)\n if self.transforms_y != None:\n y = self.transforms_y(y)\n return x, y\n\n def __len__(self):\n return len(self.dataset)\n\nclass GreenLensImagesDataset(SimpleImagesDataset):\n def __init__(self, root_path, transforms_x_static = None, transforms_x_dynamic = None, transforms_y_static = None, transforms_y_dynamic = None):\n self.dataset = []\n self.transforms_x = transforms_x_dynamic\n self.transforms_y = transforms_y_dynamic\n for category, img_files in getImagesPaths(root_path):\n # Only the green lens image\n img = pil.Image.open(img_files[-2]) \n if transforms_x_static != None:\n img = transforms_x_static(img)\n if transforms_y_static != None:\n category = transforms_y_static(category)\n self.dataset.append((img, category)) \n\nclass RedImagesDataset(SimpleImagesDataset):\n def __init__(self, root_path, transforms_x_static = None, transforms_x_dynamic = None, transforms_y_static = None, transforms_y_dynamic = None):\n self.dataset = []\n self.transforms_x = transforms_x_dynamic\n self.transforms_y = transforms_y_dynamic\n for category, img_files in getImagesPaths(root_path):\n # Only the green lens image\n img = pil.Image.open(img_files[-1]) \n if transforms_x_static != None:\n img = transforms_x_static(img)\n if transforms_y_static != None:\n category = transforms_y_static(category)\n self.dataset.append((img, category)) ", "_____no_output_____" ] ], [ [ "**Preprocess Data**", "_____no_output_____" ], [ "Convert pytorch tensor to numpy array.", "_____no_output_____" ] ], [ [ "def to_numpy(x):\n return x.cpu().detach().numpy()", "_____no_output_____" ] ], [ [ "Data transformations for the test and training sets.", "_____no_output_____" ] ], [ [ "norm_mean = [0.485, 0.456, 0.406]\nnorm_std = [0.229, 0.224, 0.225]\n\ntransforms_train = tv.transforms.Compose([\n tv.transforms.RandomAffine(degrees = 45, translate = None, scale = (1., 2.), shear = 30),\n # tv.transforms.CenterCrop(CROP_SIZE),\n tv.transforms.Resize(IMAGE_SIZE),\n tv.transforms.RandomHorizontalFlip(),\n tv.transforms.ToTensor(),\n tv.transforms.Lambda(lambda t: t.cuda()),\n tv.transforms.Normalize(mean=norm_mean, std=norm_std) \n])\n\ntransforms_test = tv.transforms.Compose([\n # tv.transforms.CenterCrop(CROP_SIZE),\n tv.transforms.Resize(IMAGE_SIZE),\n tv.transforms.ToTensor(),\n tv.transforms.Normalize(mean=norm_mean, std=norm_std) \n])\n\ny_transform = tv.transforms.Lambda(lambda y: t.tensor(y, dtype=t.long, device = 'cuda:0'))", "_____no_output_____" ] ], [ [ "Initialize pytorch datasets and loaders for training and test.", "_____no_output_____" ] ], [ [ "def create_loaders(dataset_class):\n dataset_train = dataset_class(TRAIN_PATH, transforms_x_dynamic = transforms_train, transforms_y_dynamic = y_transform)\n dataset_test = dataset_class(TEST_PATH, transforms_x_static = transforms_test, \n transforms_x_dynamic = tv.transforms.Lambda(lambda t: t.cuda()), transforms_y_dynamic = y_transform)\n\n loader_train = DataLoader(dataset_train, BATCH_SIZE, shuffle = True, num_workers = 0)\n loader_test = DataLoader(dataset_test, BATCH_SIZE, shuffle = False, num_workers = 0)\n return loader_train, loader_test, len(dataset_train), len(dataset_test)", "_____no_output_____" ], [ "loader_train_simple_img, loader_test_simple_img, len_train, len_test = create_loaders(SimpleImagesDataset)", "_____no_output_____" ] ], [ [ "**Visualize Data**", "_____no_output_____" ], [ "Load a few images so that we can see the effects of the data augmentation on the training set.", "_____no_output_____" ] ], [ [ "def plot_one_prediction(x, label, pred): \n x, label, pred = to_numpy(x), to_numpy(label), to_numpy(pred)\n x = np.transpose(x, [1, 2, 0])\n if x.shape[-1] == 1:\n x = x.squeeze()\n x = x * np.array(norm_std) + np.array(norm_mean)\n plt.title(label, color = 'green' if label == pred else 'red')\n plt.imshow(x)\n\ndef plot_predictions(imgs, labels, preds): \n fig = plt.figure(figsize = (20, 5))\n for i in range(20):\n fig.add_subplot(2, 10, i + 1, xticks = [], yticks = [])\n plot_one_prediction(imgs[i], labels[i], preds[i])", "_____no_output_____" ], [ "# x, y = next(iter(loader_train_simple_img))\n# plot_predictions(x, y, y)", "_____no_output_____" ] ], [ [ "**Model**", "_____no_output_____" ], [ "Define a few models to experiment with.", "_____no_output_____" ] ], [ [ "def get_mobilenet_v2():\n model = t.hub.load('pytorch/vision', 'mobilenet_v2', pretrained=True)\n model.classifier[1] = Linear(in_features=1280, out_features=4, bias=True)\n model = model.cuda()\n return model\n\ndef get_vgg_19():\n model = tv.models.vgg19(pretrained = True)\n model = model.cuda()\n model.classifier[6].out_features = 4\n return model\n\ndef get_res_next_101():\n model = t.hub.load('facebookresearch/WSL-Images', 'resnext101_32x8d_wsl')\n model.fc.out_features = 4\n model = model.cuda()\n return model\n\ndef get_resnet_18():\n model = tv.models.resnet18(pretrained = True)\n model.fc.out_features = 4\n model = model.cuda()\n return model\n\ndef get_dense_net():\n model = tv.models.densenet121(pretrained = True)\n model.classifier.out_features = 4\n model = model.cuda()\n return model\n\nclass MobileNetV2_FullConv(t.nn.Module):\n def __init__(self):\n super().__init__()\n self.cnn = get_mobilenet_v2().features\n self.cnn[18] = t.nn.Sequential(\n tv.models.mobilenet.ConvBNReLU(320, 32, kernel_size=1),\n t.nn.Dropout2d(p = .7)\n )\n self.fc = t.nn.Linear(32, 4)\n\n def forward(self, x):\n x = self.cnn(x)\n x = x.mean([2, 3])\n x = self.fc(x);\n return x", "_____no_output_____" ], [ "model_simple = t.nn.DataParallel(get_mobilenet_v2())", "Using cache found in /root/.cache/torch/hub/pytorch_vision_master\n" ] ], [ [ "**Train & Evaluate**", "_____no_output_____" ], [ "Timer utility function. This is used to measure the execution speed.", "_____no_output_____" ] ], [ [ "time_start = 0\n\ndef timer_start():\n global time_start\n time_start = time.time()\n\ndef timer_end():\n return time.time() - time_start", "_____no_output_____" ] ], [ [ "This function trains the network and evaluates it at the same time. It outputs the metrics recorded during the training for both train and test. We are measuring accuracy and the loss. The function also saves a checkpoint of the model every time the accuracy is improved. In the end we will have a checkpoint of the model which gave the best accuracy.", "_____no_output_____" ] ], [ [ "def train_eval(optimizer, model, loader_train, loader_test, chekpoint_name, epochs):\n metrics = {\n 'losses_train': [],\n 'losses_test': [],\n\n 'acc_train': [],\n 'acc_test': [],\n\n 'prec_train': [],\n 'prec_test': [],\n\n 'rec_train': [],\n 'rec_test': [],\n\n 'f_score_train': [],\n 'f_score_test': []\n }\n\n best_acc = 0\n \n loss_fn = t.nn.CrossEntropyLoss()\n \n try: \n for epoch in range(epochs):\n timer_start()\n train_epoch_loss, train_epoch_acc, train_epoch_precision, train_epoch_recall, train_epoch_f_score = 0, 0, 0, 0, 0\n test_epoch_loss, test_epoch_acc, test_epoch_precision, test_epoch_recall, test_epoch_f_score = 0, 0, 0, 0, 0\n\n # Train\n model.train()\n for x, y in loader_train:\n y_pred = model.forward(x)\n loss = loss_fn(y_pred, y)\n loss.backward()\n optimizer.step()\n# memory_stats()\n optimizer.zero_grad()\n y_pred, y = to_numpy(y_pred), to_numpy(y)\n pred = y_pred.argmax(axis = 1)\n ratio = len(y) / len_train\n train_epoch_loss += (loss.item() * ratio)\n train_epoch_acc += (sk.metrics.accuracy_score(y, pred) * ratio)\n precision, recall, f_score, _ = sk.metrics.precision_recall_fscore_support(y, pred, average = 'macro')\n train_epoch_precision += (precision * ratio)\n train_epoch_recall += (recall * ratio)\n train_epoch_f_score += (f_score * ratio)\n metrics['losses_train'].append(train_epoch_loss)\n metrics['acc_train'].append(train_epoch_acc)\n metrics['prec_train'].append(train_epoch_precision)\n metrics['rec_train'].append(train_epoch_recall)\n metrics['f_score_train'].append(train_epoch_f_score)\n \n # Evaluate\n model.eval()\n with t.no_grad():\n for x, y in loader_test:\n y_pred = model.forward(x)\n loss = loss_fn(y_pred, y)\n y_pred, y = to_numpy(y_pred), to_numpy(y)\n pred = y_pred.argmax(axis = 1)\n ratio = len(y) / len_test\n test_epoch_loss += (loss * ratio)\n test_epoch_acc += (sk.metrics.accuracy_score(y, pred) * ratio )\n precision, recall, f_score, _ = sk.metrics.precision_recall_fscore_support(y, pred, average = 'macro')\n test_epoch_precision += (precision * ratio)\n test_epoch_recall += (recall * ratio)\n test_epoch_f_score += (f_score * ratio)\n metrics['losses_test'].append(test_epoch_loss)\n metrics['acc_test'].append(test_epoch_acc)\n metrics['prec_test'].append(test_epoch_precision)\n metrics['rec_test'].append(test_epoch_recall)\n metrics['f_score_test'].append(test_epoch_f_score)\n \n if metrics['acc_test'][-1] > best_acc:\n best_acc = metrics['acc_test'][-1]\n t.save({'model': model.state_dict()}, 'checkpint {}.tar'.format(chekpoint_name))\n print('Epoch {} acc {} prec {} rec {} f {} minutes {}'.format(\n epoch + 1, metrics['acc_test'][-1], metrics['prec_test'][-1], metrics['rec_test'][-1], metrics['f_score_test'][-1], timer_end() / 60))\n except KeyboardInterrupt as e:\n print(e) \n print('Ended training')\n return metrics", "_____no_output_____" ] ], [ [ "Plot a metric for both train and test.", "_____no_output_____" ] ], [ [ "def plot_train_test(train, test, title, y_title):\n plt.plot(range(len(train)), train, label = 'train')\n plt.plot(range(len(test)), test, label = 'test')\n plt.xlabel('Epochs')\n plt.ylabel(y_title)\n plt.title(title)\n plt.legend()\n plt.show()", "_____no_output_____" ] ], [ [ "Plot precision - recall curve", "_____no_output_____" ] ], [ [ "def plot_precision_recall(metrics):\n plt.scatter(metrics['prec_train'], metrics['rec_train'], label = 'train')\n plt.scatter(metrics['prec_test'], metrics['rec_test'], label = 'test')\n plt.legend()\n plt.title('Precision-Recall')\n plt.xlabel('Precision')\n plt.ylabel('Recall')", "_____no_output_____" ] ], [ [ "Train a model for several epochs. The steps_learning parameter is a list of tuples. Each tuple specifies the steps and the learning rate.", "_____no_output_____" ] ], [ [ "def do_train(model, loader_train, loader_test, checkpoint_name, steps_learning):\n for steps, learn_rate in steps_learning:\n metrics = train_eval(t.optim.Adam(model.parameters(), lr = learn_rate, weight_decay = 0), model, loader_train, loader_test, checkpoint_name, steps)\n print('Best test accuracy :', max(metrics['acc_test']))\n plot_train_test(metrics['losses_train'], metrics['losses_test'], 'Loss (lr = {})'.format(learn_rate))\n plot_train_test(metrics['acc_train'], metrics['acc_test'], 'Accuracy (lr = {})'.format(learn_rate))", "_____no_output_____" ] ], [ [ "Perform actual training.", "_____no_output_____" ] ], [ [ "def do_train(model, loader_train, loader_test, checkpoint_name, steps_learning):\n t.cuda.empty_cache()\n for steps, learn_rate in steps_learning:\n metrics = train_eval(t.optim.Adam(model.parameters(), lr = learn_rate, weight_decay = 0), model, loader_train, loader_test, checkpoint_name, steps)\n \n index_max = np.array(metrics['acc_test']).argmax()\n print('Best test accuracy :', metrics['acc_test'][index_max])\n print('Corresponding precision :', metrics['prec_test'][index_max])\n print('Corresponding recall :', metrics['rec_test'][index_max])\n print('Corresponding f1 score :', metrics['f_score_test'][index_max])\n\n plot_train_test(metrics['losses_train'], metrics['losses_test'], 'Loss (lr = {})'.format(learn_rate), 'Loss')\n plot_train_test(metrics['acc_train'], metrics['acc_test'], 'Accuracy (lr = {})'.format(learn_rate), 'Accuracy')\n plot_train_test(metrics['prec_train'], metrics['prec_test'], 'Precision (lr = {})'.format(learn_rate), 'Precision')\n plot_train_test(metrics['rec_train'], metrics['rec_test'], 'Recall (lr = {})'.format(learn_rate), 'Recall')\n plot_train_test(metrics['f_score_train'], metrics['f_score_test'], 'F1 Score (lr = {})'.format(learn_rate), 'F1 Score')\n plot_precision_recall(metrics)", "_____no_output_____" ], [ "do_train(model_simple, loader_train_simple_img, loader_test_simple_img, 'simple_1', [(50, 1e-4)])", "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py:1268: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n _warn_prf(average, modifier, msg_start, len(result))\n/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py:1268: UndefinedMetricWarning: Recall and F-score are ill-defined and being set to 0.0 in labels with no true samples. Use `zero_division` parameter to control this behavior.\n _warn_prf(average, modifier, msg_start, len(result))\n" ], [ "# checkpoint = t.load('/content/checkpint simple_1.tar')\n# model_simple.load_state_dict(checkpoint['model'])", "_____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", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d03aa407b705095c19cfbe149cc5442635e258d1
24,634
ipynb
Jupyter Notebook
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
b5b957065b3bda8f7f5ce9a1a742606261b7a4c0
[ "Apache-2.0" ]
null
null
null
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
b5b957065b3bda8f7f5ce9a1a742606261b7a4c0
[ "Apache-2.0" ]
null
null
null
docs/dialect/graphblas_dialect_tutorials/graphblas_lower/graphblas_matrix_multiply.ipynb
chelini/mlir-graphblas-1
b5b957065b3bda8f7f5ce9a1a742606261b7a4c0
[ "Apache-2.0" ]
null
null
null
28.185355
472
0.515913
[ [ [ "# graphblas.matrix_multiply\n\nThis example will go over how to use the `--graphblas-lower` pass from `graphblas-opt` to lower the `graphblas.matrix_multiply` op.\n\nLet’s first import some necessary modules and generate an instance of our JIT engine.", "_____no_output_____" ] ], [ [ "import mlir_graphblas\nimport mlir_graphblas.sparse_utils\nimport numpy as np\n\nengine = mlir_graphblas.MlirJitEngine()", "_____no_output_____" ] ], [ [ "Here are the passes we'll use.", "_____no_output_____" ] ], [ [ "passes = [\n \"--graphblas-lower\",\n \"--sparsification\",\n \"--sparse-tensor-conversion\",\n \"--linalg-bufferize\",\n \"--func-bufferize\",\n \"--tensor-bufferize\",\n \"--tensor-constant-bufferize\",\n \"--finalizing-bufferize\",\n \"--convert-linalg-to-loops\",\n \"--convert-scf-to-std\",\n \"--convert-std-to-llvm\",\n]", "_____no_output_____" ] ], [ [ "Similar to our examples using the GraphBLAS dialect, we'll need some helper functions to convert sparse tensors to dense tensors. \n\nWe'll also need some helpers to convert our sparse matrices to CSC format. ", "_____no_output_____" ] ], [ [ "mlir_text = \"\"\"\n#trait_densify_csr = {\n indexing_maps = [\n affine_map<(i,j) -> (i,j)>,\n affine_map<(i,j) -> (i,j)>\n ],\n iterator_types = [\"parallel\", \"parallel\"]\n}\n\n#CSR64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (i,j)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\nfunc @csr_densify4x4(%argA: tensor<4x4xf64, #CSR64>) -> tensor<4x4xf64> {\n %output_storage = constant dense<0.0> : tensor<4x4xf64>\n %0 = linalg.generic #trait_densify_csr\n ins(%argA: tensor<4x4xf64, #CSR64>)\n outs(%output_storage: tensor<4x4xf64>) {\n ^bb(%A: f64, %x: f64):\n linalg.yield %A : f64\n } -> tensor<4x4xf64>\n return %0 : tensor<4x4xf64>\n}\n\n#trait_densify_csc = {\n indexing_maps = [\n affine_map<(i,j) -> (j,i)>,\n affine_map<(i,j) -> (i,j)>\n ],\n iterator_types = [\"parallel\", \"parallel\"]\n}\n\n#CSC64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (j,i)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\nfunc @csc_densify4x4(%argA: tensor<4x4xf64, #CSC64>) -> tensor<4x4xf64> {\n %output_storage = constant dense<0.0> : tensor<4x4xf64>\n %0 = linalg.generic #trait_densify_csc\n ins(%argA: tensor<4x4xf64, #CSC64>)\n outs(%output_storage: tensor<4x4xf64>) {\n ^bb(%A: f64, %x: f64):\n linalg.yield %A : f64\n } -> tensor<4x4xf64>\n return %0 : tensor<4x4xf64>\n}\n\nfunc @convert_csr_to_csc(%sparse_tensor: tensor<?x?xf64, #CSR64>) -> tensor<?x?xf64, #CSC64> {\n %answer = graphblas.convert_layout %sparse_tensor : tensor<?x?xf64, #CSR64> to tensor<?x?xf64, #CSC64>\n return %answer : tensor<?x?xf64, #CSC64>\n}\n\"\"\"", "_____no_output_____" ] ], [ [ "Let's compile our MLIR code. ", "_____no_output_____" ] ], [ [ "engine.add(mlir_text, passes)", "_____no_output_____" ] ], [ [ "## Overview of graphblas.matrix_multiply\n\nHere, we'll show how to use the `graphblas.matrix_multiply` op. \n\n`graphblas.matrix_multiply` takes a sparse matrix operand in CSR format, a sparse matrix operand in CSC format, and a `semiring` attribute. \n\nThe single `semiring` attribute indicates an element-wise operator and an aggregation operator. For example, the plus-times semiring indicates an element-wise operator of multiplication and an aggregation operator of addition/summation. For more details about semirings, see [here](https://en.wikipedia.org/wiki/GraphBLAS).\n\n`graphblas.matrix_multiply` applies the semiring's element-wise operator and aggregation operator in matrix-multiply order over the two given sparse matrices. For example, using `graphblas.matrix_multiply` with the plus-times semiring will get a matrix that is the result of a conventional matrix multiply.\n\n\nHere's an example use of the `graphblas.matrix_multiply` op:\n```\n%answer = graphblas.matrix_multiply %argA, %argB, %mask { semiring = \"plus_times\" } : (tensor<2x2xf64, #CSR64>, tensor<2x2xf64, #CSC64>, tensor<2x2xf64, #CSR64>) to tensor<2x2xf64, #CSR64>\n```\n\nThe supported options for the `semiring` attribute are \"plus_pair\", \"plus_plus\", and \"plus_times\".\n\n`graphblas.matrix_multiply` can also take an optional mask operand (a CSR matrix) as shown in this example:\n```\n%answer = graphblas.matrix_multiply %argA, %argB, %mask { semiring = \"plus_times\" } : (tensor<2x3xf64, #CSR64>, tensor<3x2xf64, #CSC64>, tensor<2x2xf64, #CSR64>) to tensor<2x2xf64, #CSR64>\n```\n\nThe mask operand must have the same shape as the output matrix. The mask operand acts as a boolean mask (though doesn't necessarily have to have a boolean element type) for the result, which increases performance since the mask will indicate which values in the output do not have to be calculated.\n\n`graphblas.matrix_multiply` can also take an optional [region](https://mlir.llvm.org/docs/LangRef/#regions) as shown in this example:\n```\n%cf4 = constant 4.0 : f64\n%answer = graphblas.matrix_multiply %argA, %argB { semiring = \"plus_times\" } : (tensor<?x?xf64, #CSR64>, tensor<?x?xf64, #CSC64>) to tensor<?x?xf64, #CSR64> {\n ^bb0(%value: f64):\n %result = std.addf %value, %cf4: f64\n graphblas.yield %result : f64\n }\n```\nThe NumPy equivalent of this code would be `answer = (argA @ argB) + 4.0`.\n\nThe region specifies element-wise post-processing done on values that survived the masking (applies to all elements if no mask). We'll go into deeper details later on on how to write a region using `graphblas.yield`. \n\nLet's create some example input matrices.", "_____no_output_____" ] ], [ [ "indices = np.array(\n [\n [0, 3],\n [1, 3],\n [2, 0],\n [3, 0],\n [3, 1],\n ],\n dtype=np.uint64,\n)\nvalues = np.array([1, 2, 3, 4, 5], dtype=np.float64)\nsizes = np.array([4, 4], dtype=np.uint64)\nsparsity = np.array([False, True], dtype=np.bool8)\n\nA = mlir_graphblas.sparse_utils.MLIRSparseTensor(indices, values, sizes, sparsity)", "_____no_output_____" ], [ "indices = np.array(\n [\n [0, 1],\n [0, 3],\n [1, 1],\n [1, 3],\n [2, 0],\n [2, 2],\n [3, 0],\n [3, 2],\n ],\n dtype=np.uint64,\n)\nvalues = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.float64)\nsizes = np.array([4, 4], dtype=np.uint64)\nsparsity = np.array([False, True], dtype=np.bool8)\n\nB_csr = mlir_graphblas.sparse_utils.MLIRSparseTensor(indices, values, sizes, sparsity)\nB = engine.convert_csr_to_csc(B_csr)", "_____no_output_____" ], [ "indices = np.array(\n [\n [0, 1],\n [0, 2],\n [1, 1],\n [1, 2],\n [2, 1],\n [2, 2],\n [3, 1],\n [3, 2],\n ],\n dtype=np.uint64,\n)\nvalues = np.array([1, 1, 1, 1, 1, 1, 1, 1], dtype=np.float64)\nsizes = np.array([4, 4], dtype=np.uint64)\nsparsity = np.array([False, True], dtype=np.bool8)\n\nmask = mlir_graphblas.sparse_utils.MLIRSparseTensor(indices, values, sizes, sparsity)", "_____no_output_____" ], [ "A_dense = engine.csr_densify4x4(A)", "_____no_output_____" ], [ "A_dense", "_____no_output_____" ], [ "B_dense = engine.csc_densify4x4(B)", "_____no_output_____" ], [ "B_dense", "_____no_output_____" ], [ "mask_dense = engine.csr_densify4x4(mask)", "_____no_output_____" ], [ "mask_dense", "_____no_output_____" ] ], [ [ "## graphblas.matrix_multiply (Plus-Times Semiring)\n\nHere, we'll simply perform a conventional matrix-multiply by using `graphblas.matrix_multiply` with the plus-times semiring.", "_____no_output_____" ] ], [ [ "mlir_text = \"\"\"\n#CSR64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (i,j)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\n#CSC64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (j,i)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\nmodule {\n func @matrix_multiply_plus_times(%a: tensor<?x?xf64, #CSR64>, %b: tensor<?x?xf64, #CSC64>) -> tensor<?x?xf64, #CSR64> {\n %answer = graphblas.matrix_multiply %a, %b { semiring = \"plus_times\" } : (tensor<?x?xf64, #CSR64>, tensor<?x?xf64, #CSC64>) to tensor<?x?xf64, #CSR64>\n return %answer : tensor<?x?xf64, #CSR64>\n }\n}\n\"\"\"", "_____no_output_____" ], [ "engine.add(mlir_text, passes)", "_____no_output_____" ], [ "sparse_matmul_result = engine.matrix_multiply_plus_times(A, B)", "_____no_output_____" ], [ "engine.csr_densify4x4(sparse_matmul_result)", "_____no_output_____" ] ], [ [ "The result looks sane. Let's verify that it has the same behavior as NumPy.", "_____no_output_____" ] ], [ [ "np.all(A_dense @ B_dense == engine.csr_densify4x4(sparse_matmul_result))", "_____no_output_____" ] ], [ [ "## graphblas.matrix_multiply (Plus-Plus Semiring with Mask)\n\nHere, we'll perform a matrix-multiply with the plus-plus semiring. We'll show the result with and without a mask to demonstrate how the masking works.", "_____no_output_____" ] ], [ [ "mlir_text = \"\"\"\n#CSR64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (i,j)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\n#CSC64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (j,i)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\nmodule {\n func @matrix_multiply_plus_plus_no_mask(%a: tensor<?x?xf64, #CSR64>, %b: tensor<?x?xf64, #CSC64>) -> tensor<?x?xf64, #CSR64> {\n %answer = graphblas.matrix_multiply %a, %b { semiring = \"plus_plus\" } : (tensor<?x?xf64, #CSR64>, tensor<?x?xf64, #CSC64>) to tensor<?x?xf64, #CSR64>\n return %answer : tensor<?x?xf64, #CSR64>\n }\n \n func @matrix_multiply_plus_plus(%a: tensor<?x?xf64, #CSR64>, %b: tensor<?x?xf64, #CSC64>, %m: tensor<?x?xf64, #CSR64>) -> tensor<?x?xf64, #CSR64> {\n %answer = graphblas.matrix_multiply %a, %b, %m { semiring = \"plus_plus\" } : (tensor<?x?xf64, #CSR64>, tensor<?x?xf64, #CSC64>, tensor<?x?xf64, #CSR64>) to tensor<?x?xf64, #CSR64>\n return %answer : tensor<?x?xf64, #CSR64>\n }\n}\n\"\"\"", "_____no_output_____" ], [ "engine.add(mlir_text, passes)", "_____no_output_____" ], [ "no_mask_result = engine.matrix_multiply_plus_plus_no_mask(A, B)\nwith_mask_result = engine.matrix_multiply_plus_plus(A, B, mask)", "_____no_output_____" ], [ "engine.csr_densify4x4(no_mask_result)", "_____no_output_____" ], [ "engine.csr_densify4x4(with_mask_result)", "_____no_output_____" ] ], [ [ "Note how the results in the masked output only have elements present in the positions where the mask had elements present. \n\nSince we can't verify the results via NumPy given that it doesn't support semirings in its matrix multiply implementation, we'll leave the task of verifying the results as an exercise for the reader. Note that if we're applying the element-wise operation to the values at two positions (one each sparse tensor) and one position has a value but not the other does not, then the element-wise operation for these two positions will contribute no value to be aggregated.", "_____no_output_____" ], [ "## graphblas.matrix_multiply (Plus-Pair Semiring with Region)\n\nHere, we'll perform a matrix-multiply with the plus-pair semiring. We'll show the result without using a region and with a region. \n\nThe element-wise operation of the plus-pair semiring is defined as `pair(x, y) = 1`.", "_____no_output_____" ] ], [ [ "mlir_text = \"\"\"\n#CSR64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (i,j)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\n#CSC64 = #sparse_tensor.encoding<{\n dimLevelType = [ \"dense\", \"compressed\" ],\n dimOrdering = affine_map<(i,j) -> (j,i)>,\n pointerBitWidth = 64,\n indexBitWidth = 64\n}>\n\nmodule {\n func @matrix_multiply_plus_pair_no_region(%a: tensor<?x?xf64, #CSR64>, %b: tensor<?x?xf64, #CSC64>) -> tensor<?x?xf64, #CSR64> {\n %answer = graphblas.matrix_multiply %a, %b { semiring = \"plus_pair\" } : (tensor<?x?xf64, #CSR64>, tensor<?x?xf64, #CSC64>) to tensor<?x?xf64, #CSR64>\n return %answer : tensor<?x?xf64, #CSR64>\n }\n \n func @matrix_multiply_plus_pair_and_square(%a: tensor<?x?xf64, #CSR64>, %b: tensor<?x?xf64, #CSC64>) -> tensor<?x?xf64, #CSR64> {\n %answer = graphblas.matrix_multiply %a, %b { semiring = \"plus_pair\" } : (tensor<?x?xf64, #CSR64>, tensor<?x?xf64, #CSC64>) to tensor<?x?xf64, #CSR64> {\n ^bb0(%value: f64):\n %result = std.mulf %value, %value: f64\n graphblas.yield %result : f64\n }\n return %answer : tensor<?x?xf64, #CSR64>\n }\n}\n\"\"\"", "_____no_output_____" ], [ "engine.add(mlir_text, passes)", "_____no_output_____" ] ], [ [ "The code in the region of `matrix_multiply_plus_pair_and_square` simply squares each individual element's value. The use of `graphblas.yield` is used here to indicate the result of each element-wise squaring.\n\nLet's first get our results without the region. ", "_____no_output_____" ], [ "`matrix_multiply_plus_pair_no_region` simply does a matrix multiply with the plus-pair semiring.", "_____no_output_____" ] ], [ [ "no_region_result = engine.matrix_multiply_plus_pair_no_region(A, B)", "_____no_output_____" ], [ "engine.csr_densify4x4(no_region_result)", "_____no_output_____" ] ], [ [ "Let's now get the results from `matrix_multiply_plus_pair_and_square`.", "_____no_output_____" ] ], [ [ "with_region_result = engine.matrix_multiply_plus_pair_and_square(A, B)", "_____no_output_____" ], [ "engine.csr_densify4x4(with_region_result)", "_____no_output_____" ] ], [ [ "Let's verify that our results are sane.", "_____no_output_____" ] ], [ [ "np.all(engine.csr_densify4x4(with_region_result) == engine.csr_densify4x4(no_region_result)**2)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d03aaeecc50011cd046711db1d86a7fbe05143b3
1,019,865
ipynb
Jupyter Notebook
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
ef19f6320329ff28351e7d4e3baad855c6605fa0
[ "MIT" ]
null
null
null
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
ef19f6320329ff28351e7d4e3baad855c6605fa0
[ "MIT" ]
null
null
null
CNN_Examples/ComputerVision0.ipynb
cathyXie08/Deep-Learning-Course-Examples
ef19f6320329ff28351e7d4e3baad855c6605fa0
[ "MIT" ]
null
null
null
533.681319
210,190
0.925645
[ [ [ "<a href=\"https://colab.research.google.com/github/ProfessorDong/Deep-Learning-Course-Examples/blob/master/CNN_Examples/ComputerVision0.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "#Classify 10 different object with Convolutional Neural Network\n\n\n###Dataset\nThe dataset we will use is built into tensorflow and called the [**CIFAR Image Dataset.**](https://www.cs.toronto.edu/~kriz/cifar.html) It contains 60,000 32x32 color images with 6000 images of each class. \n\nThe labels in this dataset are the following:\n- Airplane\n- Automobile\n- Bird\n- Cat\n- Deer\n- Dog\n- Frog\n- Horse\n- Ship\n- Truck\n\n*This tutorial is based on the guide from the TensorFlow documentation: https://www.tensorflow.org/tutorials/images/cnn*\n\n\n\n", "_____no_output_____" ], [ "Load Python libraries", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "Load the image data and split into \"train\" and \"test\" data\n\nNormalize the pixel values to be between 0 and 1\n\nDefine class names", "_____no_output_____" ] ], [ [ "", "Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n170500096/170498071 [==============================] - 6s 0us/step\n170508288/170498071 [==============================] - 6s 0us/step\n" ] ], [ [ "Show an example image", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "##CNN Architecture\nA common architecture for a CNN is a stack of Conv2D and MaxPooling2D layers followed by a few denesly connected layers. \n\nThe stack of convolutional and maxPooling layers extract the features from the image. Then these features are flattened and fed to densly connected layers that determine the class of an image based on the presence of features.\n\n##Add Convolutional Layers\n\n**Layer 1**\n\nThe input shape of our data will be 32, 32, 3 and we will process 32 filters of size 3x3 over our input data. We will also apply the activation function relu to the output of each convolution operation.\n\n**Layer 2**\n\nThis layer will perform the max pooling operation using 2x2 samples and a stride of 2.\n\n**Other Layers**\n\nThe next set of layers do very similar things but take as input the feature map from the previous layer. They also increase the frequency of filters from 32 to 64. We can do this as our data shrinks in spacial dimensions as it passed through the layers, meaning we can afford (computationally) to add more depth.", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "Show model summary:\n\nTotal trainable parameters: 56,320\n\nThe depth of the feature map increases but the spacial dimensions reduce.", "_____no_output_____" ] ], [ [ "", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 30, 30, 32) 896 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 15, 15, 32) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 13, 13, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 6, 6, 64) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 4, 4, 64) 36928 \n=================================================================\nTotal params: 56,320\nTrainable params: 56,320\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "###Feature Maps\nThe term *feature map* stands for a 3D tensor with two spacial axes (width and height) and one depth axis. Our convolutional layers take feature maps as their input and return a new feature map that reprsents the prescence of spcific filters from the previous feature map. These are what we call *response maps*.", "_____no_output_____" ], [ "##Add Dense Layers\nSo far, we have just completed the **convolutional base**. Now we need to take these extracted features and add a way to classify them. \n\nAdd a fully connected layer with 64 output nodes\n\nAdd a fully connected layer with 10 (final) output nodes\n", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "Show model summary\n\nTotal trainable parameters: 122,570", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "##Train the Model\nTrain and compile the model using the recommended hyper paramaters from tensorflow.", "_____no_output_____" ] ], [ [ "", "Epoch 1/20\n1563/1563 [==============================] - 73s 46ms/step - loss: 1.5072 - accuracy: 0.4521 - val_loss: 1.2174 - val_accuracy: 0.5625\nEpoch 2/20\n1563/1563 [==============================] - 73s 47ms/step - loss: 1.1273 - accuracy: 0.6023 - val_loss: 1.0827 - val_accuracy: 0.6188\nEpoch 3/20\n1563/1563 [==============================] - 73s 47ms/step - loss: 0.9765 - accuracy: 0.6570 - val_loss: 1.0449 - val_accuracy: 0.6384\nEpoch 4/20\n1563/1563 [==============================] - 72s 46ms/step - loss: 0.8798 - accuracy: 0.6915 - val_loss: 0.8968 - val_accuracy: 0.6851\nEpoch 5/20\n1563/1563 [==============================] - 72s 46ms/step - loss: 0.8064 - accuracy: 0.7164 - val_loss: 0.8853 - val_accuracy: 0.6925\nEpoch 6/20\n1563/1563 [==============================] - 72s 46ms/step - loss: 0.7510 - accuracy: 0.7363 - val_loss: 0.8763 - val_accuracy: 0.6962\nEpoch 7/20\n1563/1563 [==============================] - 71s 46ms/step - loss: 0.6987 - accuracy: 0.7545 - val_loss: 0.8531 - val_accuracy: 0.7117\nEpoch 8/20\n1563/1563 [==============================] - 71s 46ms/step - loss: 0.6545 - accuracy: 0.7691 - val_loss: 0.8763 - val_accuracy: 0.7056\nEpoch 9/20\n1563/1563 [==============================] - 71s 45ms/step - loss: 0.6118 - accuracy: 0.7854 - val_loss: 0.8917 - val_accuracy: 0.6949\nEpoch 10/20\n1563/1563 [==============================] - 71s 46ms/step - loss: 0.5772 - accuracy: 0.7950 - val_loss: 0.8671 - val_accuracy: 0.7168\nEpoch 11/20\n1563/1563 [==============================] - 71s 46ms/step - loss: 0.5333 - accuracy: 0.8107 - val_loss: 0.9228 - val_accuracy: 0.7059\nEpoch 12/20\n1563/1563 [==============================] - 71s 46ms/step - loss: 0.5090 - accuracy: 0.8201 - val_loss: 0.9081 - val_accuracy: 0.7130\nEpoch 13/20\n1563/1563 [==============================] - 71s 45ms/step - loss: 0.4747 - accuracy: 0.8336 - val_loss: 0.9726 - val_accuracy: 0.7093\nEpoch 14/20\n1563/1563 [==============================] - 72s 46ms/step - loss: 0.4438 - accuracy: 0.8427 - val_loss: 0.9797 - val_accuracy: 0.7149\nEpoch 15/20\n1563/1563 [==============================] - 73s 47ms/step - loss: 0.4202 - accuracy: 0.8507 - val_loss: 1.0394 - val_accuracy: 0.7029\nEpoch 16/20\n1563/1563 [==============================] - 74s 47ms/step - loss: 0.3906 - accuracy: 0.8599 - val_loss: 1.0597 - val_accuracy: 0.7083\nEpoch 17/20\n1563/1563 [==============================] - 73s 47ms/step - loss: 0.3653 - accuracy: 0.8686 - val_loss: 1.0889 - val_accuracy: 0.7080\nEpoch 18/20\n1563/1563 [==============================] - 73s 47ms/step - loss: 0.3456 - accuracy: 0.8767 - val_loss: 1.1832 - val_accuracy: 0.6971\nEpoch 19/20\n1563/1563 [==============================] - 73s 47ms/step - loss: 0.3234 - accuracy: 0.8840 - val_loss: 1.2505 - val_accuracy: 0.6977\nEpoch 20/20\n1563/1563 [==============================] - 73s 47ms/step - loss: 0.3007 - accuracy: 0.8932 - val_loss: 1.2848 - val_accuracy: 0.6964\n" ] ], [ [ "##Evaluate the Model\nWe evaluate how well the model performs by looking at it's performance on the test data set.\n\nYou should get an accuracy of about 70%. This isn't bad for a simple model like this, but we'll dive into some better approaches for computer vision.\n", "_____no_output_____" ] ], [ [ "", "313/313 - 3s - loss: 1.2848 - accuracy: 0.6964\n0.696399986743927\n" ] ], [ [ "##Working with Small Datasets\nIn the situation where you don't have millions of images it is difficult to train a CNN from scratch that performs very well. This is why we will learn about a few techniques we can use to train CNN's on small datasets of just a few thousand images. ", "_____no_output_____" ], [ "###Data Augmentation\nTo avoid overfitting and create a larger dataset from a smaller one we can use a technique called data augmentation. This is to perform random transofrmations on our images so that our model can generalize better. These transformations can be things like compressions, rotations, stretches and even color changes. \n\nFortunately, Keras can help us do this. Look at the code below to an example of data augmentation.\n\n", "_____no_output_____" ] ], [ [ "from keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# creates a data generator object that transforms images\ndatagen = ImageDataGenerator(\nrotation_range=40,\nwidth_shift_range=0.2,\nheight_shift_range=0.2,\nshear_range=0.2,\nzoom_range=0.2,\nhorizontal_flip=True,\nfill_mode='nearest')\n\n# pick an image to transform\ntest_img = train_images[20]\nimg = image.img_to_array(test_img) # convert image to numpy arry\nimg = img.reshape((1,) + img.shape) # reshape image\n\ni = 0\n\nfor batch in datagen.flow(img, save_prefix='test', save_format='jpeg'): # this loops runs forever until we break, saving images to current directory with specified prefix\n plt.figure(i)\n plot = plt.imshow(image.img_to_array(batch[0]))\n i += 1\n if i > 4: # show 4 images\n break\n\nplt.show()\n", "_____no_output_____" ] ], [ [ "#Use a Pretrained Model\nIn this section we will combine the tecniques we learned above and use a pretrained model and fine tuning to classify images of dogs and cats using a small dataset.\n\n##Pretrained Models\nIn this section we will use a pretrained CNN as part of our own custom network to improve the accuracy of our model. We know that CNN's alone (with no dense layers) don't do anything other than map the presence of features from our input. This means we can use a pretrained CNN, one trained on millions of images, as the start of our model. This will allow us to have a very good convolutional base before adding our own dense layered classifier at the end. In fact, by using this techique we can train a very good classifier for a realtively small dataset (< 10,000 images). This is because the ConvNet already has a very good idea of what features to look for in an image and can find them very effectively. So, if we can determine the presence of features all the rest of the model needs to do is determine which combination of features makes a specific image.\n\n##Fine Tuning\nWhen we employ the technique defined above, we will often want to tweak the final layers in our convolutional base to work better for our specific problem. This involves not touching or retraining the earlier layers in our convolutional base but only adjusting the final few. We do this because the first layers in our base are very good at extracting low level features lile lines and edges, things that are similar for any kind of image. Where the later layers are better at picking up very specific features like shapes or even eyes. If we adjust the final layers than we can look for only features relevant to our very specific problem.\n\n\n*This tutorial is based on the following guide from the TensorFlow documentation: https://www.tensorflow.org/tutorials/images/transfer_learning*\n", "_____no_output_____" ] ], [ [ "#Imports\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nkeras = tf.keras", "_____no_output_____" ] ], [ [ "###Load the Dataset\nWe will load the *cats_vs_dogs* dataset from the modoule tensorflow_datatsets.\n\nThis dataset contains (image, label) pairs where images have different dimensions and 3 color channels.\n\n", "_____no_output_____" ] ], [ [ "import tensorflow_datasets as tfds\ntfds.disable_progress_bar()\n\n# split the data manually into 80% training, 10% testing, 10% validation\n(raw_train, raw_validation, raw_test), metadata = tfds.load(\n 'cats_vs_dogs',\n split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],\n with_info=True,\n as_supervised=True,\n)", "\u001b[1mDownloading and preparing dataset cats_vs_dogs/4.0.0 (download: 786.68 MiB, generated: Unknown size, total: 786.68 MiB) to /root/tensorflow_datasets/cats_vs_dogs/4.0.0...\u001b[0m\n" ] ], [ [ "Display images from the dataset", "_____no_output_____" ] ], [ [ "get_label_name = metadata.features['label'].int2str # creates a function object that we can use to get labels\n\nfor image, label in raw_train.take(5):\n plt.figure()\n plt.imshow(image)\n plt.title(get_label_name(label))", "_____no_output_____" ] ], [ [ "###Data Preprocessing\nSince the sizes of our images are all different, we need to convert them all to the same size. We can create a function that will do that for us below.\n\n", "_____no_output_____" ] ], [ [ "IMG_SIZE = 160 # All images will be resized to 160x160\n\ndef format_example(image, label):\n \"\"\"\n returns an image that is reshaped to IMG_SIZE\n \"\"\"\n image = tf.cast(image, tf.float32)\n image = (image/127.5) - 1\n image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))\n return image, label", "_____no_output_____" ] ], [ [ "Now we can apply this function to all our images using ```.map()```.", "_____no_output_____" ] ], [ [ "train = raw_train.map(format_example)\nvalidation = raw_validation.map(format_example)\ntest = raw_test.map(format_example)", "_____no_output_____" ] ], [ [ "Let's have a look at our images now.", "_____no_output_____" ] ], [ [ "for image, label in train.take(2):\n plt.figure()\n plt.imshow(image)\n plt.title(get_label_name(label))", "WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\nWARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\n" ] ], [ [ "Finally we will shuffle and batch the images.", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 32\nSHUFFLE_BUFFER_SIZE = 1000\n\ntrain_batches = train.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)\nvalidation_batches = validation.batch(BATCH_SIZE)\ntest_batches = test.batch(BATCH_SIZE)", "_____no_output_____" ] ], [ [ "Now if we look at the shape of an original image vs the new image we will see it has been changed.", "_____no_output_____" ] ], [ [ "for img, label in raw_train.take(2):\n print(\"Original shape:\", img.shape)\n\nfor img, label in train.take(2):\n print(\"New shape:\", img.shape)", "Original shape: (262, 350, 3)\nOriginal shape: (409, 336, 3)\nNew shape: (160, 160, 3)\nNew shape: (160, 160, 3)\n" ] ], [ [ "##Pick a Pretrained Model\nThe model we are going to use as the convolutional base for our model is the **MobileNet V2** developed at Google. This model is trained on 1.4 million images and has 1000 different classes.\n\nWe want to use this model but only its convolutional base. So, when we load in the model, we'll specify that we don't want to load the top (classification) layer. We'll tell the model what input shape to expect and to use the predetermined weights from *imagenet* (Googles dataset).\n\n", "_____no_output_____" ] ], [ [ "IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)\n\n# Create the base model from the pre-trained model MobileNet V2\nbase_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,\n include_top=False,\n weights='imagenet')", "Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet_v2/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_160_no_top.h5\n9412608/9406464 [==============================] - 0s 0us/step\n9420800/9406464 [==============================] - 0s 0us/step\n" ], [ "base_model.summary()", "Model: \"mobilenetv2_1.00_160\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) [(None, 160, 160, 3) 0 \n__________________________________________________________________________________________________\nConv1 (Conv2D) (None, 80, 80, 32) 864 input_1[0][0] \n__________________________________________________________________________________________________\nbn_Conv1 (BatchNormalization) (None, 80, 80, 32) 128 Conv1[0][0] \n__________________________________________________________________________________________________\nConv1_relu (ReLU) (None, 80, 80, 32) 0 bn_Conv1[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise (Depthw (None, 80, 80, 32) 288 Conv1_relu[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise_BN (Bat (None, 80, 80, 32) 128 expanded_conv_depthwise[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise_relu (R (None, 80, 80, 32) 0 expanded_conv_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_project (Conv2D) (None, 80, 80, 16) 512 expanded_conv_depthwise_relu[0][0\n__________________________________________________________________________________________________\nexpanded_conv_project_BN (Batch (None, 80, 80, 16) 64 expanded_conv_project[0][0] \n__________________________________________________________________________________________________\nblock_1_expand (Conv2D) (None, 80, 80, 96) 1536 expanded_conv_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_expand_BN (BatchNormali (None, 80, 80, 96) 384 block_1_expand[0][0] \n__________________________________________________________________________________________________\nblock_1_expand_relu (ReLU) (None, 80, 80, 96) 0 block_1_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_pad (ZeroPadding2D) (None, 81, 81, 96) 0 block_1_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise (DepthwiseCon (None, 40, 40, 96) 864 block_1_pad[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise_BN (BatchNorm (None, 40, 40, 96) 384 block_1_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise_relu (ReLU) (None, 40, 40, 96) 0 block_1_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_project (Conv2D) (None, 40, 40, 24) 2304 block_1_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_1_project_BN (BatchNormal (None, 40, 40, 24) 96 block_1_project[0][0] \n__________________________________________________________________________________________________\nblock_2_expand (Conv2D) (None, 40, 40, 144) 3456 block_1_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_expand_BN (BatchNormali (None, 40, 40, 144) 576 block_2_expand[0][0] \n__________________________________________________________________________________________________\nblock_2_expand_relu (ReLU) (None, 40, 40, 144) 0 block_2_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise (DepthwiseCon (None, 40, 40, 144) 1296 block_2_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise_BN (BatchNorm (None, 40, 40, 144) 576 block_2_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise_relu (ReLU) (None, 40, 40, 144) 0 block_2_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_project (Conv2D) (None, 40, 40, 24) 3456 block_2_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_2_project_BN (BatchNormal (None, 40, 40, 24) 96 block_2_project[0][0] \n__________________________________________________________________________________________________\nblock_2_add (Add) (None, 40, 40, 24) 0 block_1_project_BN[0][0] \n block_2_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_expand (Conv2D) (None, 40, 40, 144) 3456 block_2_add[0][0] \n__________________________________________________________________________________________________\nblock_3_expand_BN (BatchNormali (None, 40, 40, 144) 576 block_3_expand[0][0] \n__________________________________________________________________________________________________\nblock_3_expand_relu (ReLU) (None, 40, 40, 144) 0 block_3_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_pad (ZeroPadding2D) (None, 41, 41, 144) 0 block_3_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise (DepthwiseCon (None, 20, 20, 144) 1296 block_3_pad[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise_BN (BatchNorm (None, 20, 20, 144) 576 block_3_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise_relu (ReLU) (None, 20, 20, 144) 0 block_3_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_project (Conv2D) (None, 20, 20, 32) 4608 block_3_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_3_project_BN (BatchNormal (None, 20, 20, 32) 128 block_3_project[0][0] \n__________________________________________________________________________________________________\nblock_4_expand (Conv2D) (None, 20, 20, 192) 6144 block_3_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_expand_BN (BatchNormali (None, 20, 20, 192) 768 block_4_expand[0][0] \n__________________________________________________________________________________________________\nblock_4_expand_relu (ReLU) (None, 20, 20, 192) 0 block_4_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise (DepthwiseCon (None, 20, 20, 192) 1728 block_4_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise_BN (BatchNorm (None, 20, 20, 192) 768 block_4_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise_relu (ReLU) (None, 20, 20, 192) 0 block_4_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_project (Conv2D) (None, 20, 20, 32) 6144 block_4_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_4_project_BN (BatchNormal (None, 20, 20, 32) 128 block_4_project[0][0] \n__________________________________________________________________________________________________\nblock_4_add (Add) (None, 20, 20, 32) 0 block_3_project_BN[0][0] \n block_4_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_expand (Conv2D) (None, 20, 20, 192) 6144 block_4_add[0][0] \n__________________________________________________________________________________________________\nblock_5_expand_BN (BatchNormali (None, 20, 20, 192) 768 block_5_expand[0][0] \n__________________________________________________________________________________________________\nblock_5_expand_relu (ReLU) (None, 20, 20, 192) 0 block_5_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise (DepthwiseCon (None, 20, 20, 192) 1728 block_5_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise_BN (BatchNorm (None, 20, 20, 192) 768 block_5_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise_relu (ReLU) (None, 20, 20, 192) 0 block_5_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_project (Conv2D) (None, 20, 20, 32) 6144 block_5_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_5_project_BN (BatchNormal (None, 20, 20, 32) 128 block_5_project[0][0] \n__________________________________________________________________________________________________\nblock_5_add (Add) (None, 20, 20, 32) 0 block_4_add[0][0] \n block_5_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_expand (Conv2D) (None, 20, 20, 192) 6144 block_5_add[0][0] \n__________________________________________________________________________________________________\nblock_6_expand_BN (BatchNormali (None, 20, 20, 192) 768 block_6_expand[0][0] \n__________________________________________________________________________________________________\nblock_6_expand_relu (ReLU) (None, 20, 20, 192) 0 block_6_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_pad (ZeroPadding2D) (None, 21, 21, 192) 0 block_6_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise (DepthwiseCon (None, 10, 10, 192) 1728 block_6_pad[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise_BN (BatchNorm (None, 10, 10, 192) 768 block_6_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise_relu (ReLU) (None, 10, 10, 192) 0 block_6_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_project (Conv2D) (None, 10, 10, 64) 12288 block_6_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_6_project_BN (BatchNormal (None, 10, 10, 64) 256 block_6_project[0][0] \n__________________________________________________________________________________________________\nblock_7_expand (Conv2D) (None, 10, 10, 384) 24576 block_6_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_expand_BN (BatchNormali (None, 10, 10, 384) 1536 block_7_expand[0][0] \n__________________________________________________________________________________________________\nblock_7_expand_relu (ReLU) (None, 10, 10, 384) 0 block_7_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise (DepthwiseCon (None, 10, 10, 384) 3456 block_7_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise_BN (BatchNorm (None, 10, 10, 384) 1536 block_7_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_7_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_project (Conv2D) (None, 10, 10, 64) 24576 block_7_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_7_project_BN (BatchNormal (None, 10, 10, 64) 256 block_7_project[0][0] \n__________________________________________________________________________________________________\nblock_7_add (Add) (None, 10, 10, 64) 0 block_6_project_BN[0][0] \n block_7_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_expand (Conv2D) (None, 10, 10, 384) 24576 block_7_add[0][0] \n__________________________________________________________________________________________________\nblock_8_expand_BN (BatchNormali (None, 10, 10, 384) 1536 block_8_expand[0][0] \n__________________________________________________________________________________________________\nblock_8_expand_relu (ReLU) (None, 10, 10, 384) 0 block_8_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise (DepthwiseCon (None, 10, 10, 384) 3456 block_8_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise_BN (BatchNorm (None, 10, 10, 384) 1536 block_8_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_8_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_project (Conv2D) (None, 10, 10, 64) 24576 block_8_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_8_project_BN (BatchNormal (None, 10, 10, 64) 256 block_8_project[0][0] \n__________________________________________________________________________________________________\nblock_8_add (Add) (None, 10, 10, 64) 0 block_7_add[0][0] \n block_8_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_expand (Conv2D) (None, 10, 10, 384) 24576 block_8_add[0][0] \n__________________________________________________________________________________________________\nblock_9_expand_BN (BatchNormali (None, 10, 10, 384) 1536 block_9_expand[0][0] \n__________________________________________________________________________________________________\nblock_9_expand_relu (ReLU) (None, 10, 10, 384) 0 block_9_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise (DepthwiseCon (None, 10, 10, 384) 3456 block_9_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise_BN (BatchNorm (None, 10, 10, 384) 1536 block_9_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_9_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_project (Conv2D) (None, 10, 10, 64) 24576 block_9_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_9_project_BN (BatchNormal (None, 10, 10, 64) 256 block_9_project[0][0] \n__________________________________________________________________________________________________\nblock_9_add (Add) (None, 10, 10, 64) 0 block_8_add[0][0] \n block_9_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_expand (Conv2D) (None, 10, 10, 384) 24576 block_9_add[0][0] \n__________________________________________________________________________________________________\nblock_10_expand_BN (BatchNormal (None, 10, 10, 384) 1536 block_10_expand[0][0] \n__________________________________________________________________________________________________\nblock_10_expand_relu (ReLU) (None, 10, 10, 384) 0 block_10_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise (DepthwiseCo (None, 10, 10, 384) 3456 block_10_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise_BN (BatchNor (None, 10, 10, 384) 1536 block_10_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_10_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_project (Conv2D) (None, 10, 10, 96) 36864 block_10_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_10_project_BN (BatchNorma (None, 10, 10, 96) 384 block_10_project[0][0] \n__________________________________________________________________________________________________\nblock_11_expand (Conv2D) (None, 10, 10, 576) 55296 block_10_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_expand_BN (BatchNormal (None, 10, 10, 576) 2304 block_11_expand[0][0] \n__________________________________________________________________________________________________\nblock_11_expand_relu (ReLU) (None, 10, 10, 576) 0 block_11_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise (DepthwiseCo (None, 10, 10, 576) 5184 block_11_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise_BN (BatchNor (None, 10, 10, 576) 2304 block_11_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise_relu (ReLU) (None, 10, 10, 576) 0 block_11_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_project (Conv2D) (None, 10, 10, 96) 55296 block_11_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_11_project_BN (BatchNorma (None, 10, 10, 96) 384 block_11_project[0][0] \n__________________________________________________________________________________________________\nblock_11_add (Add) (None, 10, 10, 96) 0 block_10_project_BN[0][0] \n block_11_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_expand (Conv2D) (None, 10, 10, 576) 55296 block_11_add[0][0] \n__________________________________________________________________________________________________\nblock_12_expand_BN (BatchNormal (None, 10, 10, 576) 2304 block_12_expand[0][0] \n__________________________________________________________________________________________________\nblock_12_expand_relu (ReLU) (None, 10, 10, 576) 0 block_12_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise (DepthwiseCo (None, 10, 10, 576) 5184 block_12_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise_BN (BatchNor (None, 10, 10, 576) 2304 block_12_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise_relu (ReLU) (None, 10, 10, 576) 0 block_12_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_project (Conv2D) (None, 10, 10, 96) 55296 block_12_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_12_project_BN (BatchNorma (None, 10, 10, 96) 384 block_12_project[0][0] \n__________________________________________________________________________________________________\nblock_12_add (Add) (None, 10, 10, 96) 0 block_11_add[0][0] \n block_12_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_expand (Conv2D) (None, 10, 10, 576) 55296 block_12_add[0][0] \n__________________________________________________________________________________________________\nblock_13_expand_BN (BatchNormal (None, 10, 10, 576) 2304 block_13_expand[0][0] \n__________________________________________________________________________________________________\nblock_13_expand_relu (ReLU) (None, 10, 10, 576) 0 block_13_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_pad (ZeroPadding2D) (None, 11, 11, 576) 0 block_13_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise (DepthwiseCo (None, 5, 5, 576) 5184 block_13_pad[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise_BN (BatchNor (None, 5, 5, 576) 2304 block_13_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise_relu (ReLU) (None, 5, 5, 576) 0 block_13_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_project (Conv2D) (None, 5, 5, 160) 92160 block_13_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_13_project_BN (BatchNorma (None, 5, 5, 160) 640 block_13_project[0][0] \n__________________________________________________________________________________________________\nblock_14_expand (Conv2D) (None, 5, 5, 960) 153600 block_13_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_expand_BN (BatchNormal (None, 5, 5, 960) 3840 block_14_expand[0][0] \n__________________________________________________________________________________________________\nblock_14_expand_relu (ReLU) (None, 5, 5, 960) 0 block_14_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise (DepthwiseCo (None, 5, 5, 960) 8640 block_14_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise_BN (BatchNor (None, 5, 5, 960) 3840 block_14_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise_relu (ReLU) (None, 5, 5, 960) 0 block_14_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_project (Conv2D) (None, 5, 5, 160) 153600 block_14_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_14_project_BN (BatchNorma (None, 5, 5, 160) 640 block_14_project[0][0] \n__________________________________________________________________________________________________\nblock_14_add (Add) (None, 5, 5, 160) 0 block_13_project_BN[0][0] \n block_14_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_expand (Conv2D) (None, 5, 5, 960) 153600 block_14_add[0][0] \n__________________________________________________________________________________________________\nblock_15_expand_BN (BatchNormal (None, 5, 5, 960) 3840 block_15_expand[0][0] \n__________________________________________________________________________________________________\nblock_15_expand_relu (ReLU) (None, 5, 5, 960) 0 block_15_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise (DepthwiseCo (None, 5, 5, 960) 8640 block_15_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise_BN (BatchNor (None, 5, 5, 960) 3840 block_15_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise_relu (ReLU) (None, 5, 5, 960) 0 block_15_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_project (Conv2D) (None, 5, 5, 160) 153600 block_15_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_15_project_BN (BatchNorma (None, 5, 5, 160) 640 block_15_project[0][0] \n__________________________________________________________________________________________________\nblock_15_add (Add) (None, 5, 5, 160) 0 block_14_add[0][0] \n block_15_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_expand (Conv2D) (None, 5, 5, 960) 153600 block_15_add[0][0] \n__________________________________________________________________________________________________\nblock_16_expand_BN (BatchNormal (None, 5, 5, 960) 3840 block_16_expand[0][0] \n__________________________________________________________________________________________________\nblock_16_expand_relu (ReLU) (None, 5, 5, 960) 0 block_16_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise (DepthwiseCo (None, 5, 5, 960) 8640 block_16_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise_BN (BatchNor (None, 5, 5, 960) 3840 block_16_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise_relu (ReLU) (None, 5, 5, 960) 0 block_16_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_project (Conv2D) (None, 5, 5, 320) 307200 block_16_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_16_project_BN (BatchNorma (None, 5, 5, 320) 1280 block_16_project[0][0] \n__________________________________________________________________________________________________\nConv_1 (Conv2D) (None, 5, 5, 1280) 409600 block_16_project_BN[0][0] \n__________________________________________________________________________________________________\nConv_1_bn (BatchNormalization) (None, 5, 5, 1280) 5120 Conv_1[0][0] \n__________________________________________________________________________________________________\nout_relu (ReLU) (None, 5, 5, 1280) 0 Conv_1_bn[0][0] \n==================================================================================================\nTotal params: 2,257,984\nTrainable params: 2,223,872\nNon-trainable params: 34,112\n__________________________________________________________________________________________________\n" ] ], [ [ "At this point this *base_model* will simply output a shape (32, 5, 5, 1280) tensor that is a feature extraction from our original (1, 160, 160, 3) image. The 32 means that we have 32 layers of differnt filters/features.", "_____no_output_____" ] ], [ [ "for image, _ in train_batches.take(1):\n pass\n\nfeature_batch = base_model(image)\nprint(feature_batch.shape)", "(32, 5, 5, 1280)\n" ] ], [ [ "###Freeze the Base\nThe term **freezing** refers to disabling the training property of a layer. It simply means we won’t make any changes to the weights of any layers that are frozen during training. This is important as we don't want to change the convolutional base that already has learned weights.\n\n", "_____no_output_____" ] ], [ [ "base_model.trainable = False", "_____no_output_____" ], [ "base_model.summary()", "Model: \"mobilenetv2_1.00_160\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) [(None, 160, 160, 3) 0 \n__________________________________________________________________________________________________\nConv1 (Conv2D) (None, 80, 80, 32) 864 input_1[0][0] \n__________________________________________________________________________________________________\nbn_Conv1 (BatchNormalization) (None, 80, 80, 32) 128 Conv1[0][0] \n__________________________________________________________________________________________________\nConv1_relu (ReLU) (None, 80, 80, 32) 0 bn_Conv1[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise (Depthw (None, 80, 80, 32) 288 Conv1_relu[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise_BN (Bat (None, 80, 80, 32) 128 expanded_conv_depthwise[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise_relu (R (None, 80, 80, 32) 0 expanded_conv_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_project (Conv2D) (None, 80, 80, 16) 512 expanded_conv_depthwise_relu[0][0\n__________________________________________________________________________________________________\nexpanded_conv_project_BN (Batch (None, 80, 80, 16) 64 expanded_conv_project[0][0] \n__________________________________________________________________________________________________\nblock_1_expand (Conv2D) (None, 80, 80, 96) 1536 expanded_conv_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_expand_BN (BatchNormali (None, 80, 80, 96) 384 block_1_expand[0][0] \n__________________________________________________________________________________________________\nblock_1_expand_relu (ReLU) (None, 80, 80, 96) 0 block_1_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_pad (ZeroPadding2D) (None, 81, 81, 96) 0 block_1_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise (DepthwiseCon (None, 40, 40, 96) 864 block_1_pad[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise_BN (BatchNorm (None, 40, 40, 96) 384 block_1_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise_relu (ReLU) (None, 40, 40, 96) 0 block_1_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_project (Conv2D) (None, 40, 40, 24) 2304 block_1_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_1_project_BN (BatchNormal (None, 40, 40, 24) 96 block_1_project[0][0] \n__________________________________________________________________________________________________\nblock_2_expand (Conv2D) (None, 40, 40, 144) 3456 block_1_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_expand_BN (BatchNormali (None, 40, 40, 144) 576 block_2_expand[0][0] \n__________________________________________________________________________________________________\nblock_2_expand_relu (ReLU) (None, 40, 40, 144) 0 block_2_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise (DepthwiseCon (None, 40, 40, 144) 1296 block_2_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise_BN (BatchNorm (None, 40, 40, 144) 576 block_2_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise_relu (ReLU) (None, 40, 40, 144) 0 block_2_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_project (Conv2D) (None, 40, 40, 24) 3456 block_2_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_2_project_BN (BatchNormal (None, 40, 40, 24) 96 block_2_project[0][0] \n__________________________________________________________________________________________________\nblock_2_add (Add) (None, 40, 40, 24) 0 block_1_project_BN[0][0] \n block_2_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_expand (Conv2D) (None, 40, 40, 144) 3456 block_2_add[0][0] \n__________________________________________________________________________________________________\nblock_3_expand_BN (BatchNormali (None, 40, 40, 144) 576 block_3_expand[0][0] \n__________________________________________________________________________________________________\nblock_3_expand_relu (ReLU) (None, 40, 40, 144) 0 block_3_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_pad (ZeroPadding2D) (None, 41, 41, 144) 0 block_3_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise (DepthwiseCon (None, 20, 20, 144) 1296 block_3_pad[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise_BN (BatchNorm (None, 20, 20, 144) 576 block_3_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise_relu (ReLU) (None, 20, 20, 144) 0 block_3_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_project (Conv2D) (None, 20, 20, 32) 4608 block_3_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_3_project_BN (BatchNormal (None, 20, 20, 32) 128 block_3_project[0][0] \n__________________________________________________________________________________________________\nblock_4_expand (Conv2D) (None, 20, 20, 192) 6144 block_3_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_expand_BN (BatchNormali (None, 20, 20, 192) 768 block_4_expand[0][0] \n__________________________________________________________________________________________________\nblock_4_expand_relu (ReLU) (None, 20, 20, 192) 0 block_4_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise (DepthwiseCon (None, 20, 20, 192) 1728 block_4_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise_BN (BatchNorm (None, 20, 20, 192) 768 block_4_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise_relu (ReLU) (None, 20, 20, 192) 0 block_4_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_project (Conv2D) (None, 20, 20, 32) 6144 block_4_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_4_project_BN (BatchNormal (None, 20, 20, 32) 128 block_4_project[0][0] \n__________________________________________________________________________________________________\nblock_4_add (Add) (None, 20, 20, 32) 0 block_3_project_BN[0][0] \n block_4_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_expand (Conv2D) (None, 20, 20, 192) 6144 block_4_add[0][0] \n__________________________________________________________________________________________________\nblock_5_expand_BN (BatchNormali (None, 20, 20, 192) 768 block_5_expand[0][0] \n__________________________________________________________________________________________________\nblock_5_expand_relu (ReLU) (None, 20, 20, 192) 0 block_5_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise (DepthwiseCon (None, 20, 20, 192) 1728 block_5_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise_BN (BatchNorm (None, 20, 20, 192) 768 block_5_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise_relu (ReLU) (None, 20, 20, 192) 0 block_5_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_project (Conv2D) (None, 20, 20, 32) 6144 block_5_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_5_project_BN (BatchNormal (None, 20, 20, 32) 128 block_5_project[0][0] \n__________________________________________________________________________________________________\nblock_5_add (Add) (None, 20, 20, 32) 0 block_4_add[0][0] \n block_5_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_expand (Conv2D) (None, 20, 20, 192) 6144 block_5_add[0][0] \n__________________________________________________________________________________________________\nblock_6_expand_BN (BatchNormali (None, 20, 20, 192) 768 block_6_expand[0][0] \n__________________________________________________________________________________________________\nblock_6_expand_relu (ReLU) (None, 20, 20, 192) 0 block_6_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_pad (ZeroPadding2D) (None, 21, 21, 192) 0 block_6_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise (DepthwiseCon (None, 10, 10, 192) 1728 block_6_pad[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise_BN (BatchNorm (None, 10, 10, 192) 768 block_6_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise_relu (ReLU) (None, 10, 10, 192) 0 block_6_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_project (Conv2D) (None, 10, 10, 64) 12288 block_6_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_6_project_BN (BatchNormal (None, 10, 10, 64) 256 block_6_project[0][0] \n__________________________________________________________________________________________________\nblock_7_expand (Conv2D) (None, 10, 10, 384) 24576 block_6_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_expand_BN (BatchNormali (None, 10, 10, 384) 1536 block_7_expand[0][0] \n__________________________________________________________________________________________________\nblock_7_expand_relu (ReLU) (None, 10, 10, 384) 0 block_7_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise (DepthwiseCon (None, 10, 10, 384) 3456 block_7_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise_BN (BatchNorm (None, 10, 10, 384) 1536 block_7_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_7_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_project (Conv2D) (None, 10, 10, 64) 24576 block_7_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_7_project_BN (BatchNormal (None, 10, 10, 64) 256 block_7_project[0][0] \n__________________________________________________________________________________________________\nblock_7_add (Add) (None, 10, 10, 64) 0 block_6_project_BN[0][0] \n block_7_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_expand (Conv2D) (None, 10, 10, 384) 24576 block_7_add[0][0] \n__________________________________________________________________________________________________\nblock_8_expand_BN (BatchNormali (None, 10, 10, 384) 1536 block_8_expand[0][0] \n__________________________________________________________________________________________________\nblock_8_expand_relu (ReLU) (None, 10, 10, 384) 0 block_8_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise (DepthwiseCon (None, 10, 10, 384) 3456 block_8_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise_BN (BatchNorm (None, 10, 10, 384) 1536 block_8_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_8_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_project (Conv2D) (None, 10, 10, 64) 24576 block_8_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_8_project_BN (BatchNormal (None, 10, 10, 64) 256 block_8_project[0][0] \n__________________________________________________________________________________________________\nblock_8_add (Add) (None, 10, 10, 64) 0 block_7_add[0][0] \n block_8_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_expand (Conv2D) (None, 10, 10, 384) 24576 block_8_add[0][0] \n__________________________________________________________________________________________________\nblock_9_expand_BN (BatchNormali (None, 10, 10, 384) 1536 block_9_expand[0][0] \n__________________________________________________________________________________________________\nblock_9_expand_relu (ReLU) (None, 10, 10, 384) 0 block_9_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise (DepthwiseCon (None, 10, 10, 384) 3456 block_9_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise_BN (BatchNorm (None, 10, 10, 384) 1536 block_9_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_9_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_project (Conv2D) (None, 10, 10, 64) 24576 block_9_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_9_project_BN (BatchNormal (None, 10, 10, 64) 256 block_9_project[0][0] \n__________________________________________________________________________________________________\nblock_9_add (Add) (None, 10, 10, 64) 0 block_8_add[0][0] \n block_9_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_expand (Conv2D) (None, 10, 10, 384) 24576 block_9_add[0][0] \n__________________________________________________________________________________________________\nblock_10_expand_BN (BatchNormal (None, 10, 10, 384) 1536 block_10_expand[0][0] \n__________________________________________________________________________________________________\nblock_10_expand_relu (ReLU) (None, 10, 10, 384) 0 block_10_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise (DepthwiseCo (None, 10, 10, 384) 3456 block_10_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise_BN (BatchNor (None, 10, 10, 384) 1536 block_10_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise_relu (ReLU) (None, 10, 10, 384) 0 block_10_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_project (Conv2D) (None, 10, 10, 96) 36864 block_10_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_10_project_BN (BatchNorma (None, 10, 10, 96) 384 block_10_project[0][0] \n__________________________________________________________________________________________________\nblock_11_expand (Conv2D) (None, 10, 10, 576) 55296 block_10_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_expand_BN (BatchNormal (None, 10, 10, 576) 2304 block_11_expand[0][0] \n__________________________________________________________________________________________________\nblock_11_expand_relu (ReLU) (None, 10, 10, 576) 0 block_11_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise (DepthwiseCo (None, 10, 10, 576) 5184 block_11_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise_BN (BatchNor (None, 10, 10, 576) 2304 block_11_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise_relu (ReLU) (None, 10, 10, 576) 0 block_11_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_project (Conv2D) (None, 10, 10, 96) 55296 block_11_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_11_project_BN (BatchNorma (None, 10, 10, 96) 384 block_11_project[0][0] \n__________________________________________________________________________________________________\nblock_11_add (Add) (None, 10, 10, 96) 0 block_10_project_BN[0][0] \n block_11_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_expand (Conv2D) (None, 10, 10, 576) 55296 block_11_add[0][0] \n__________________________________________________________________________________________________\nblock_12_expand_BN (BatchNormal (None, 10, 10, 576) 2304 block_12_expand[0][0] \n__________________________________________________________________________________________________\nblock_12_expand_relu (ReLU) (None, 10, 10, 576) 0 block_12_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise (DepthwiseCo (None, 10, 10, 576) 5184 block_12_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise_BN (BatchNor (None, 10, 10, 576) 2304 block_12_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise_relu (ReLU) (None, 10, 10, 576) 0 block_12_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_project (Conv2D) (None, 10, 10, 96) 55296 block_12_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_12_project_BN (BatchNorma (None, 10, 10, 96) 384 block_12_project[0][0] \n__________________________________________________________________________________________________\nblock_12_add (Add) (None, 10, 10, 96) 0 block_11_add[0][0] \n block_12_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_expand (Conv2D) (None, 10, 10, 576) 55296 block_12_add[0][0] \n__________________________________________________________________________________________________\nblock_13_expand_BN (BatchNormal (None, 10, 10, 576) 2304 block_13_expand[0][0] \n__________________________________________________________________________________________________\nblock_13_expand_relu (ReLU) (None, 10, 10, 576) 0 block_13_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_pad (ZeroPadding2D) (None, 11, 11, 576) 0 block_13_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise (DepthwiseCo (None, 5, 5, 576) 5184 block_13_pad[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise_BN (BatchNor (None, 5, 5, 576) 2304 block_13_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise_relu (ReLU) (None, 5, 5, 576) 0 block_13_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_project (Conv2D) (None, 5, 5, 160) 92160 block_13_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_13_project_BN (BatchNorma (None, 5, 5, 160) 640 block_13_project[0][0] \n__________________________________________________________________________________________________\nblock_14_expand (Conv2D) (None, 5, 5, 960) 153600 block_13_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_expand_BN (BatchNormal (None, 5, 5, 960) 3840 block_14_expand[0][0] \n__________________________________________________________________________________________________\nblock_14_expand_relu (ReLU) (None, 5, 5, 960) 0 block_14_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise (DepthwiseCo (None, 5, 5, 960) 8640 block_14_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise_BN (BatchNor (None, 5, 5, 960) 3840 block_14_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise_relu (ReLU) (None, 5, 5, 960) 0 block_14_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_project (Conv2D) (None, 5, 5, 160) 153600 block_14_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_14_project_BN (BatchNorma (None, 5, 5, 160) 640 block_14_project[0][0] \n__________________________________________________________________________________________________\nblock_14_add (Add) (None, 5, 5, 160) 0 block_13_project_BN[0][0] \n block_14_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_expand (Conv2D) (None, 5, 5, 960) 153600 block_14_add[0][0] \n__________________________________________________________________________________________________\nblock_15_expand_BN (BatchNormal (None, 5, 5, 960) 3840 block_15_expand[0][0] \n__________________________________________________________________________________________________\nblock_15_expand_relu (ReLU) (None, 5, 5, 960) 0 block_15_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise (DepthwiseCo (None, 5, 5, 960) 8640 block_15_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise_BN (BatchNor (None, 5, 5, 960) 3840 block_15_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise_relu (ReLU) (None, 5, 5, 960) 0 block_15_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_project (Conv2D) (None, 5, 5, 160) 153600 block_15_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_15_project_BN (BatchNorma (None, 5, 5, 160) 640 block_15_project[0][0] \n__________________________________________________________________________________________________\nblock_15_add (Add) (None, 5, 5, 160) 0 block_14_add[0][0] \n block_15_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_expand (Conv2D) (None, 5, 5, 960) 153600 block_15_add[0][0] \n__________________________________________________________________________________________________\nblock_16_expand_BN (BatchNormal (None, 5, 5, 960) 3840 block_16_expand[0][0] \n__________________________________________________________________________________________________\nblock_16_expand_relu (ReLU) (None, 5, 5, 960) 0 block_16_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise (DepthwiseCo (None, 5, 5, 960) 8640 block_16_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise_BN (BatchNor (None, 5, 5, 960) 3840 block_16_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise_relu (ReLU) (None, 5, 5, 960) 0 block_16_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_project (Conv2D) (None, 5, 5, 320) 307200 block_16_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_16_project_BN (BatchNorma (None, 5, 5, 320) 1280 block_16_project[0][0] \n__________________________________________________________________________________________________\nConv_1 (Conv2D) (None, 5, 5, 1280) 409600 block_16_project_BN[0][0] \n__________________________________________________________________________________________________\nConv_1_bn (BatchNormalization) (None, 5, 5, 1280) 5120 Conv_1[0][0] \n__________________________________________________________________________________________________\nout_relu (ReLU) (None, 5, 5, 1280) 0 Conv_1_bn[0][0] \n==================================================================================================\nTotal params: 2,257,984\nTrainable params: 0\nNon-trainable params: 2,257,984\n__________________________________________________________________________________________________\n" ] ], [ [ "###Adding our Classifier\nNow that we have our base layer setup, we can add the classifier. Instead of flattening the feature map of the base layer we will use a global average pooling layer that will average the entire 5x5 area of each 2D feature map and return to us a single 1280 element vector per filter. \n\n", "_____no_output_____" ] ], [ [ "global_average_layer = tf.keras.layers.GlobalAveragePooling2D()", "_____no_output_____" ] ], [ [ "Finally, we will add the predicition layer that will be a single dense neuron. We can do this because we only have two classes to predict for.\n\n\n", "_____no_output_____" ] ], [ [ "prediction_layer = keras.layers.Dense(1)", "_____no_output_____" ] ], [ [ "Now we will combine these layers together in a model.", "_____no_output_____" ] ], [ [ "model = tf.keras.Sequential([\n base_model,\n global_average_layer,\n prediction_layer\n])", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nmobilenetv2_1.00_160 (Functi (None, 5, 5, 1280) 2257984 \n_________________________________________________________________\nglobal_average_pooling2d (Gl (None, 1280) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 1281 \n=================================================================\nTotal params: 2,259,265\nTrainable params: 1,281\nNon-trainable params: 2,257,984\n_________________________________________________________________\n" ] ], [ [ "###Train the Model\nWe will train and compile the model. We will use a very small learning rate to ensure that the model does not have any major changes made to it.", "_____no_output_____" ] ], [ [ "base_learning_rate = 0.0001\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n metrics=['accuracy'])", "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/optimizer_v2.py:356: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n \"The `lr` argument is deprecated, use `learning_rate` instead.\")\n" ], [ "# We can evaluate the model right now to see how it does before training it on our new images\ninitial_epochs = 3\nvalidation_steps=20\n\nloss0,accuracy0 = model.evaluate(validation_batches, steps = validation_steps)", "20/20 [==============================] - 11s 485ms/step - loss: 0.8757 - accuracy: 0.4062\n" ], [ "# Now we can train it on our images\nhistory = model.fit(train_batches,\n epochs=initial_epochs,\n validation_data=validation_batches)\n\nacc = history.history['accuracy']\nprint(acc)", "Epoch 1/3\n582/582 [==============================] - 319s 541ms/step - loss: 0.2412 - accuracy: 0.8893 - val_loss: 0.0903 - val_accuracy: 0.9678\nEpoch 2/3\n582/582 [==============================] - 319s 546ms/step - loss: 0.0742 - accuracy: 0.9742 - val_loss: 0.0640 - val_accuracy: 0.9759\nEpoch 3/3\n388/582 [===================>..........] - ETA: 1:37 - loss: 0.0615 - accuracy: 0.9777" ], [ "model.save(\"dogs_vs_cats.h5\") # we can save the model and reload it at anytime in the future\nnew_model = tf.keras.models.load_model('dogs_vs_cats.h5')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d03ad6b58abc91905c216549fdfad8926f8e5911
234,500
ipynb
Jupyter Notebook
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
d1d79527476f7c2bb74322f437e70d0dafe58543
[ "MIT" ]
null
null
null
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
d1d79527476f7c2bb74322f437e70d0dafe58543
[ "MIT" ]
null
null
null
PF-2/Notebooks/Train/D169 Last Block (Rand Init) (SGD0.9) (10CV).ipynb
pchandrasekaran1595/PetFinder.my---Pawpularity-Contest
d1d79527476f7c2bb74322f437e70d0dafe58543
[ "MIT" ]
null
null
null
143.865031
17,644
0.830345
[ [ [ "## Library Imports", "_____no_output_____" ] ], [ [ "from time import time\nnotebook_start_time = time()", "_____no_output_____" ], [ "import os\nimport re\nimport gc\nimport pickle\nimport random as r\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn, optim\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader as DL\nfrom torch.nn.utils import weight_norm as WN\nfrom torchvision import models, transforms\n\nfrom time import time\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ] ], [ [ "## Constants and Utilities", "_____no_output_____" ] ], [ [ "SEED = 49\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nNUM_FEATURES = 1664\nTRANSFORM = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225]),\n ])\n\nPATH = \"../input/petfinder-pawpularity-score\"\nIMAGE_PATH = \"../input/petfinder-pretrained-images-nocrop\"\n\nverbose = True\nDEBUG = False\n\nsc_y = StandardScaler()", "_____no_output_____" ], [ "def breaker(num=50, char=\"*\") -> None:\n print(\"\\n\" + num*char + \"\\n\")\n\n\ndef get_targets(path: str) -> np.ndarray:\n df = pd.read_csv(os.path.join(path, \"train.csv\"), engine=\"python\")\n targets = df[\"Pawpularity\"].copy().values\n return targets.reshape(-1, 1)\n\n\ndef show_graphs(L: list, title=None) -> None:\n TL, VL = [], []\n for i in range(len(L)):\n TL.append(L[i][\"train\"])\n VL.append(L[i][\"valid\"])\n x_Axis = np.arange(1, len(L) + 1)\n plt.figure()\n plt.plot(x_Axis, TL, \"r\", label=\"train\")\n plt.plot(x_Axis, VL, \"b\", label=\"valid\")\n plt.grid()\n plt.legend()\n if title:\n plt.title(\"{} Loss\".format(title))\n else:\n plt.title(\"Loss\")\n plt.show()", "_____no_output_____" ] ], [ [ "## Dataset Template and Build Dataloader", "_____no_output_____" ] ], [ [ "class DS(Dataset):\n def __init__(self, images=None, targets=None, transform=None):\n self.images = images\n self.targets = targets\n self.transform = transform\n \n def __len__(self):\n return self.images.shape[0]\n \n def __getitem__(self, idx):\n return self.transform(self.images[idx]), torch.FloatTensor(self.targets[idx])\n\n\ndef build_dataloaders(tr_images: np.ndarray, va_images: np.ndarray,\n tr_targets: np.ndarray, va_targets: np.ndarray,\n batch_size: int, seed: int, transform: transforms.transforms.Compose):\n\n if verbose:\n breaker()\n print(\"Building Train and Validation DataLoaders ...\")\n \n tr_data_setup = DS(images=tr_images, targets=tr_targets, transform=transform)\n va_data_setup = DS(images=va_images, targets=va_targets, transform=transform)\n \n dataloaders = {\n \"train\" : DL(tr_data_setup, batch_size=batch_size, shuffle=True, generator=torch.manual_seed(seed)),\n \"valid\" : DL(va_data_setup, batch_size=batch_size, shuffle=False)\n }\n \n return dataloaders", "_____no_output_____" ] ], [ [ "## Build Model", "_____no_output_____" ] ], [ [ "def build_model(IL: int, seed: int):\n class Model(nn.Module):\n def __init__(self, IL=None):\n super(Model, self).__init__()\n\n self.features = models.densenet169(pretrained=True, progress=False)\n self.features = nn.Sequential(*[*self.features.children()][:-1])\n self.freeze()\n self.features.add_module(\"Adaptive Average Pool\", nn.AdaptiveAvgPool2d(output_size=(1, 1)))\n self.features.add_module(\"Flatten\", nn.Flatten())\n\n self.predictor = nn.Sequential()\n self.predictor.add_module(\"BN\", nn.BatchNorm1d(num_features=IL, eps=1e-5))\n self.predictor.add_module(\"FC\", WN(nn.Linear(in_features=IL, out_features=1)))\n \n def freeze(self):\n for params in self.parameters():\n params.requires_grad = False\n \n for names, params in self.named_parameters():\n if re.match(r\"features.0.denseblock4\", names, re.IGNORECASE):\n params.requires_grad = True\n if re.match(r\"features.0.norm5\", names, re.IGNORECASE):\n params.requires_grad = True\n \n def get_optimizer(self, lr=1e-3, wd=0.0):\n params = [p for p in self.parameters() if p.requires_grad]\n return optim.SGD(params, lr=lr, momentum=0.9, weight_decay=wd)\n \n def forward(self, x1, x2=None):\n if x2 is not None:\n x1 = self.features(x1)\n x2 = self.features(x2)\n return self.predictor(x1), self.predictor(x2)\n else:\n x1 = self.features(x1)\n return self.predictor(x1)\n \n if verbose:\n breaker()\n print(\"Building Model ...\")\n\n torch.manual_seed(seed)\n model = Model(IL=IL)\n return model", "_____no_output_____" ] ], [ [ "## Fit and Predict", "_____no_output_____" ] ], [ [ "def fit(model=None, optimizer=None, scheduler=None, \n epochs=None, early_stopping_patience=None,\n dataloaders=None, fold=None, verbose=False) -> tuple:\n \n name = \"./Fold_{}_state.pt\".format(fold)\n \n if verbose:\n breaker()\n print(\"Training Fold {}...\".format(fold))\n breaker()\n else:\n print(\"Training Fold {}...\".format(fold))\n\n Losses = []\n bestLoss = {\"train\" : np.inf, \"valid\" : np.inf}\n\n start_time = time()\n for e in range(epochs):\n e_st = time()\n epochLoss = {\"train\" : np.inf, \"valid\" : np.inf}\n\n for phase in [\"train\", \"valid\"]:\n if phase == \"train\":\n model.train()\n else:\n model.eval()\n \n lossPerPass = []\n\n for X, y in dataloaders[phase]:\n X, y = X.to(DEVICE), y.to(DEVICE)\n\n optimizer.zero_grad()\n with torch.set_grad_enabled(phase == \"train\"):\n output = model(X)\n loss = torch.nn.MSELoss()(output, y)\n if phase == \"train\":\n loss.backward()\n optimizer.step()\n lossPerPass.append(loss.item())\n epochLoss[phase] = np.mean(np.array(lossPerPass))\n Losses.append(epochLoss)\n\n if early_stopping_patience:\n if epochLoss[\"valid\"] < bestLoss[\"valid\"]:\n bestLoss = epochLoss\n BLE = e + 1\n torch.save({\"model_state_dict\": model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict()},\n name)\n early_stopping_step = 0\n else:\n early_stopping_step += 1\n if early_stopping_step > early_stopping_patience:\n if verbose:\n print(\"\\nEarly Stopping at Epoch {}\".format(e))\n break\n \n if epochLoss[\"valid\"] < bestLoss[\"valid\"]:\n bestLoss = epochLoss\n BLE = e + 1\n torch.save({\"model_state_dict\": model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict()},\n name)\n \n if scheduler:\n scheduler.step(epochLoss[\"valid\"])\n \n if verbose:\n print(\"Epoch: {} | Train Loss: {:.5f} | Valid Loss: {:.5f} | Time: {:.2f} seconds\".format(e+1, epochLoss[\"train\"], epochLoss[\"valid\"], time()-e_st))\n \n if verbose:\n breaker()\n print(\"Best Validation Loss at Epoch {}\".format(BLE))\n breaker()\n print(\"Time Taken [{} Epochs] : {:.2f} minutes\".format(len(Losses), (time()-start_time)/60))\n breaker()\n print(\"Training Completed\")\n breaker()\n\n return Losses, BLE, name\n\n#####################################################################################################\n\ndef predict_batch(model=None, dataloader=None, mode=\"test\", path=None) -> np.ndarray: \n model.load_state_dict(torch.load(path, map_location=DEVICE)[\"model_state_dict\"])\n model.to(DEVICE)\n model.eval()\n\n y_pred = torch.zeros(1, 1).to(DEVICE)\n if re.match(r\"valid\", mode, re.IGNORECASE):\n for X, _ in dataloader:\n X = X.to(DEVICE)\n with torch.no_grad():\n output = model(X)\n y_pred = torch.cat((y_pred, output.view(-1, 1)), dim=0)\n elif re.match(r\"test\", mode, re.IGNORECASE):\n for X in dataloader:\n X = X.to(DEVICE)\n with torch.no_grad():\n output = model(X)\n y_pred = torch.cat((y_pred, output.view(-1, 1)), dim=0)\n \n return y_pred[1:].detach().cpu().numpy()", "_____no_output_____" ] ], [ [ "## Train", "_____no_output_____" ] ], [ [ "def train(images: np.ndarray, targets: np.ndarray, \n n_splits: int, batch_size: int, \n lr: float, wd: float, \n epochs: int, early_stopping: int,\n patience=None, eps=None) -> list: \n \n metrics = []\n \n KFold_start_time = time()\n breaker()\n print(\"Performing {} Fold CV ...\".format(n_splits))\n if verbose:\n pass\n else:\n breaker()\n fold = 1\n for tr_idx, va_idx in KFold(n_splits=n_splits, shuffle=True, random_state=SEED).split(images):\n tr_images, va_images = images[tr_idx], images[va_idx]\n tr_targets, va_targets = targets[tr_idx], targets[va_idx]\n\n tr_targets = sc_y.fit_transform(tr_targets)\n va_targets = sc_y.transform(va_targets)\n\n dataloaders = build_dataloaders(tr_images, va_images,\n tr_targets, va_targets, \n batch_size, SEED, TRANSFORM)\n model = build_model(IL=NUM_FEATURES, seed=SEED).to(DEVICE)\n optimizer = model.get_optimizer(lr=lr, wd=wd)\n scheduler = None\n if isinstance(patience, int) and isinstance(eps, float):\n scheduler = model.get_plateau_scheduler(optimizer, patience, eps)\n\n L, _, name = fit(model=model, optimizer=optimizer, scheduler=scheduler, \n epochs=epochs, early_stopping_patience=early_stopping,\n dataloaders=dataloaders, fold=fold, verbose=verbose)\n y_pred = predict_batch(model=model, dataloader=dataloaders[\"valid\"], mode=\"valid\", path=name)\n RMSE = np.sqrt(mean_squared_error(sc_y.inverse_transform(y_pred), sc_y.inverse_transform(va_targets)))\n if verbose:\n print(\"Validation RMSE [Fold {}]: {:.5f}\".format(fold, RMSE))\n breaker()\n show_graphs(L)\n \n metrics_dict = {\"Fold\" : fold, \"RMSE\" : RMSE}\n metrics.append(metrics_dict)\n\n fold += 1\n \n breaker()\n print(\"Total Time to {} Fold CV : {:.2f} minutes\".format(n_splits, (time() - KFold_start_time)/60))\n \n return metrics, (time() - KFold_start_time)/60", "_____no_output_____" ], [ "def main():\n \n breaker()\n print(\"Clean Memory, {} Objects Collected ...\".format(gc.collect()))\n\n ########### Params ###########\n \n if DEBUG:\n n_splits = 3\n patience, eps = 5, 1e-8\n epochs, early_stopping = 5, 5\n\n batch_size = 64\n lr = 1e-5\n wd = 1e-3\n else:\n n_splits = 10\n patience, eps = 5, 1e-8\n epochs, early_stopping = 25, 5\n\n batch_size = 64\n lr = 1e-5\n wd = 1e-3\n \n ##############################\n\n if verbose:\n breaker()\n print(\"Loading Data ...\")\n \n \n feature_start_time = time()\n images = np.load(os.path.join(IMAGE_PATH, \"Images_224x224.npy\"))\n targets = get_targets(PATH)\n\n # Without Scheduler\n metrics, _ = train(images, targets, n_splits, batch_size, lr, wd, epochs, early_stopping, patience=None, eps=None)\n\n # # With Plateau Scheduler\n # metrics, _ = train(images, targets, n_splits, batch_size, lr, wd, epochs, early_stopping, patience=patience, eps=eps)\n\n rmse = []\n breaker()\n for i in range(len(metrics)):\n print(\"Fold {}, RMSE: {:.5f}\".format(metrics[i][\"Fold\"], metrics[i][\"RMSE\"]))\n rmse.append(metrics[i][\"RMSE\"])\n \n best_index = rmse.index(min(rmse))\n breaker()\n print(\"Best RMSE : {:.5f}\".format(metrics[best_index][\"RMSE\"]))\n print(\"Avg RMSE : {:.5f}\".format(sum(rmse) / len(rmse)))\n breaker()\n\n with open(\"metrics.pkl\", \"wb\") as fp:\n pickle.dump(metrics, fp)", "_____no_output_____" ], [ "main()", "\n**************************************************\n\nClean Memory, 63 Objects Collected ...\n\n**************************************************\n\nLoading Data ...\n\n**************************************************\n\nPerforming 10 Fold CV ...\n\n**************************************************\n\nBuilding Train and Validation DataLoaders ...\n\n**************************************************\n\nBuilding Model ...\n" ] ], [ [ "## End", "_____no_output_____" ] ], [ [ "breaker()\nprint(\"Notebook Rumtime : {:.2f} minutes\".format((time() - notebook_start_time)/60))\nbreaker()", "\n**************************************************\n\nNotebook Rumtime : 149.44 minutes\n\n**************************************************\n\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d03adee2a0a537cc49de92a46d997b2b5d07242d
131,658
ipynb
Jupyter Notebook
Abusive_Comment_Detection/Inference_Related_Notebooks/inference-on-test-fasttext-dravidlangtech.ipynb
bp-high/BpHigh_at_Dravidian_Lang_Tech_ACL-2022
7252f824e7b59d66096bbd1b29a0e6e07664ee0f
[ "MIT" ]
null
null
null
Abusive_Comment_Detection/Inference_Related_Notebooks/inference-on-test-fasttext-dravidlangtech.ipynb
bp-high/BpHigh_at_Dravidian_Lang_Tech_ACL-2022
7252f824e7b59d66096bbd1b29a0e6e07664ee0f
[ "MIT" ]
null
null
null
Abusive_Comment_Detection/Inference_Related_Notebooks/inference-on-test-fasttext-dravidlangtech.ipynb
bp-high/BpHigh_at_Dravidian_Lang_Tech_ACL-2022
7252f824e7b59d66096bbd1b29a0e6e07664ee0f
[ "MIT" ]
null
null
null
131,658
131,658
0.902695
[ [ [ "from tqdm.auto import tqdm\nimport os\n\nimport numpy as np\nimport pandas as pd \n\nimport matplotlib.pyplot as plt\nimport seaborn as sns \n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split , StratifiedKFold\n\n\nimport tensorflow as tf \nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model, load_model, save_model\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.layers import Input,Dense, LSTM, RNN, Bidirectional, GlobalAveragePooling2D , Dropout, Conv1D, Flatten\n\nfrom transformers import TFAutoModel , AutoTokenizer\n# import ray\n# from ray import tune\n\n", "2022-04-07 23:18:46.329269: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /opt/conda/lib\n2022-04-07 23:18:46.329404: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.\n" ], [ "class config:\n #train_path = \"../input/dravidianlangtech2022-personal/Train_Data_Combined.csv\"\n #val_path = \"../input/dravidianlangtech2022-personal/Validation_Data_Combined.csv\"\n test_path = \"../input/test-for-dravid-lang-tech-new/ta-en-misogyny-test.csv\"\n save_dir = \"./result\"\n seed = 55\n try:\n AUTOTUNE = tf.data.AUTOTUNE \n except:\n AUTOTUNE = tf.data.experimental.AUTOTUNE \n epochs = 50\n max_len = 64\n batch_size = 32\n hf_path = \"google/muril-base-cased\"\n tokenizer_path = \"../input/with-n-augmentfasttext-abusive-comment-detection-t/result/muril_tokenizer\" \n model_weights = \"../input/with-n-augmentfasttext-abusive-comment-detection-t/result\"\ndef seed_everything(seed = config.seed):\n print(f\"seeded everything to seed {seed}\")\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n tf.random.set_seed(seed)\nif not os.path.exists(config.save_dir):\n os.makedirs(config.save_dir)\nseed_everything()\n", "seeded everything to seed 55\n" ], [ "col_names = ['text']\ndf_test = pd.read_csv(config.test_path,names=col_names,sep='\\t')", "_____no_output_____" ], [ "df_test.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1857 entries, 0 to 1856\nData columns (total 1 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 text 1857 non-null object\ndtypes: object(1)\nmemory usage: 14.6+ KB\n" ], [ "#Tokenization Process\ntokenizer = AutoTokenizer.from_pretrained(config.hf_path)\ntokenizer.save_pretrained(os.path.join(config.save_dir , \"muril_tokenizer\"))\n", "_____no_output_____" ], [ "def fast_encode(texts, tokenizer, chunk_size=512, maxlen=config.max_len):\n \n input_ids = []\n tt_ids = []\n at_ids = []\n \n for i in tqdm(range(0, len(texts), chunk_size)):\n text_chunk = texts[i:i+chunk_size]\n encs = tokenizer(\n text_chunk,\n max_length = config.max_len,\n padding='max_length',\n truncation=True\n )\n \n input_ids.extend(encs['input_ids'])\n tt_ids.extend(encs['token_type_ids'])\n at_ids.extend(encs['attention_mask'])\n \n return {'input_ids': input_ids, 'token_type_ids': tt_ids, 'attention_mask':at_ids}", "_____no_output_____" ], [ "test_token_data = fast_encode(list(df_test['text'].values), tokenizer)\n#train_token_data['label'] = list(df_train['label'].values)", "_____no_output_____" ], [ "df_tokenized_test = pd.DataFrame(test_token_data)\nlen(df_tokenized_test['input_ids'][0])", "_____no_output_____" ], [ "del test_token_data ", "_____no_output_____" ], [ "#preparing dataset\ndef test_prep_function(embeddings):\n input_ids = embeddings['input_ids']\n attention_mask = embeddings['attention_mask']\n token_type_ids = embeddings['token_type_ids']\n\n #target = tf.cast(target, tf.int32)\n \n return {'input_ids': input_ids ,'token_type_ids':token_type_ids,'attention_mask': attention_mask}", "_____no_output_____" ], [ "# Detect hardware, return appropriate distribution strategy\ntry:\n # TPU detection. No parameters necessary if TPU_NAME environment variable is\n # set: this is always the case on Kaggle.\n tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n print('Running on TPU ', tpu.master())\nexcept ValueError:\n tpu = None\n\nif tpu:\n tf.config.experimental_connect_to_cluster(tpu)\n tf.tpu.experimental.initialize_tpu_system(tpu)\n strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)", "Running on TPU grpc://10.0.0.2:8470\n" ], [ "def create_model(transformer_model):\n input_id_layer = Input(shape=(config.max_len,) ,dtype = tf.int32 , name = 'input_ids')\n attention_mask_layer = Input(shape=(config.max_len,) , dtype = tf.int32 , name = 'attention_mask')\n token_type_layer = Input(shape=(config.max_len,) , dtype = tf.int32 , name = 'token_type_ids')\n transformer = transformer_model(input_ids = input_id_layer ,token_type_ids=token_type_layer,attention_mask = attention_mask_layer)[0]\n \n\n x = Dropout(0.5)(transformer)\n x = Conv1D(1,1)(x)\n x = Flatten()(x) \n predictions = Dense(8, activation = \"softmax\")(x)\n\n model = Model(inputs=[input_id_layer ,token_type_layer, attention_mask_layer], outputs = predictions)\n model.compile(\n optimizer = Adam(learning_rate= 0.01),\n metrics = ['accuracy'],\n loss = 'sparse_categorical_crossentropy'\n )\n\n return model", "_____no_output_____" ], [ "with strategy.scope():\n transformer_model = TFAutoModel.from_pretrained(config.hf_path)\n transformer_model.bert.trainable = False \n model = create_model(transformer_model)\nmodel.summary()\ntf.keras.utils.plot_model(model, show_shapes=True,show_dtype=True)", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\ntest_embeddings = {'input_ids': df_tokenized_test['input_ids'].tolist() ,'token_type_ids': df_tokenized_test['token_type_ids'].tolist(),\"attention_mask\":df_tokenized_test['attention_mask'].tolist()}\n#y_train = df_tokenized_train['label']\n#y_test = df_tokenized_val['label']\n#train_dataset = tf.data.Dataset.from_tensor_slices((train_embeddings , y_train))\ntest_dataset = tf.data.Dataset.from_tensor_slices((test_embeddings))\ntest_dataset = (\n test_dataset\n .map(test_prep_function , num_parallel_calls = config.AUTOTUNE)\n .batch(config.batch_size)\n .prefetch(config.AUTOTUNE)\n )\ntest_steps = len(test_embeddings['input_ids'])//config.batch_size\nmodel.load_weights(f'{config.model_weights}/muril_fold_trained.h5')\ny_predict = model.predict(test_dataset , verbose = 1)\npredictions = y_predict\npreds_classes = np.argmax(predictions, axis=-1)\n", "59/59 [==============================] - 11s 121ms/step\n" ], [ "preds_classes", "_____no_output_____" ], [ "df_pred = pd.DataFrame(preds_classes,columns=['label'])", "_____no_output_____" ], [ "df_pred.replace({0:'Counter-speech',\n 1:'Homophobia', \n 2:'Hope-Speech', \n 3:'Misandry', \n 4:'Misogyny',\n 5:'None-of-the-above',\n 6:'Transphobic',\n 7:'Xenophobia'},inplace = True)", "_____no_output_____" ], [ "df_pred", "_____no_output_____" ], [ "df_test[list(df_pred.columns)] = df_pred", "_____no_output_____" ], [ "df_test", "_____no_output_____" ], [ "df_test.to_csv('BpHigh_tamil-english.tsv',sep=\"\\t\")", "_____no_output_____" ], [ "df_test.label.value_counts()", "_____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" ] ]
d03ae3ab69cde624d0b167f359a6a10c854a6e2b
14,241
ipynb
Jupyter Notebook
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
1211c6d97ba40fa304047d4e61aad7fa8e7d1fc8
[ "MIT" ]
null
null
null
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
1211c6d97ba40fa304047d4e61aad7fa8e7d1fc8
[ "MIT" ]
null
null
null
Linear_regression/Linear_regression.ipynb
xpgeng/exercises_of_machine_learning
1211c6d97ba40fa304047d4e61aad7fa8e7d1fc8
[ "MIT" ]
null
null
null
22.010819
183
0.423285
[ [ [ "# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfrom numpy.linalg import inv, qr, svd, solve, lstsq\nimport seaborn as sns\n%matplotlib inline", "/Users/xpgeng/anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')\n" ], [ "df = pd.read_csv('data.csv')", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ] ], [ [ "## linear regression\n### 解析式直接求解", "_____no_output_____" ] ], [ [ "df['x4'] = 1", "_____no_output_____" ], [ "X = df.iloc[:,(0,1,2,4)].values", "_____no_output_____" ], [ "y = df.y.values", "_____no_output_____" ] ], [ [ "$y = Xw$ \n$ w = (X^T*X)^[-1]*X^T*y$", "_____no_output_____" ] ], [ [ "inv_XX_T = inv(X.T.dot(X))", "_____no_output_____" ], [ "w = inv_XX_T.dot(X.T).dot(df.y.values)", "_____no_output_____" ], [ "w", "_____no_output_____" ] ], [ [ "## Results\nw1 = 2.97396653 \nw2 = -0.54139002 \nw3 = 0.97132913 \nb = 2.03076198", "_____no_output_____" ] ], [ [ "qr(inv_XX_T)", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ], [ "#solve(X,y)##只能解方阵", "_____no_output_____" ] ], [ [ "## 梯度下降法求解\n- 目标函数选取要合适一些, 前边乘以适当的系数.\n- 注意检验梯度的计算是否正确...", "_____no_output_____" ] ], [ [ "def f(w,X,y): \n return ((X.dot(w)-y)**2/(2*1000)).sum()", "_____no_output_____" ], [ "def grad_f(w,X,y):\n return (X.dot(w) - y).dot(X)/1000", "_____no_output_____" ], [ "w0 = np.array([100.0,100.0,100.0,100.0])", "_____no_output_____" ], [ "epsilon = 1e-10", "_____no_output_____" ], [ "alpha = 0.1", "_____no_output_____" ], [ "check_condition = 1", "_____no_output_____" ], [ "while check_condition > epsilon:\n w0 += -alpha*grad_f(w0,X,y)\n check_condition = abs(grad_f(w0,X,y)).sum()\nprint w0", "[ 2.97396671 -0.5414066 0.97132728 2.03076759]\n" ] ], [ [ "## 随机梯度下降法求解\n- Stochastic gradient descent\n- 使用了固定步长\n - 一开始用的0.1, 始终达不到给定的精度\n- 于是添加了判定条件用来更新步长.", "_____no_output_____" ] ], [ [ "def cost_function(w,X,y): \n return (X.dot(w)-y)**2/2", "_____no_output_____" ], [ "def grad_cost_f(w,X,y):\n return (np.dot(X, w) - y)*X", "_____no_output_____" ], [ "w0 = np.array([1.0, 1.0, 1.0, 1.0])", "_____no_output_____" ], [ "epsilon = 1e-3", "_____no_output_____" ], [ "alpha = 0.01", "_____no_output_____" ], [ "# 生成随机index,用来随机索引数据.\nrandom_index = np.arange(1000)\nnp.random.shuffle(random_index)", "_____no_output_____" ], [ "cost_value = np.inf #初始化目标函数值", "_____no_output_____" ], [ "while abs(grad_f(w0,X,y)).sum() > epsilon:\n for i in range(1000):\n w0 += -alpha*grad_cost_f(w0,X[random_index[i]],y[random_index[i]])\n \n #检查目标函数变化趋势, 如果趋势变化达到临界值, 更新更小的步长继续计算\n difference = cost_value - f(w0, X, y) \n if difference < 1e-10:\n alpha *= 0.9\n cost_value = f(w0, X, y)\nprint w0", "[ 2.97376767 -0.54075842 0.97217986 2.03067711]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03af1aa06d16349d478f07216d0384ed7ecdebd
7,773
ipynb
Jupyter Notebook
21_sesiones_remotas_y_transmision_de_datos.ipynb
jasant00/servidores
50f23b7a3e0d9b2e1e78ebe75d6137b7efb5f97a
[ "MIT" ]
11
2019-03-04T23:03:08.000Z
2021-10-14T23:08:41.000Z
21_sesiones_remotas_y_transmision_de_datos.ipynb
jasant00/servidores
50f23b7a3e0d9b2e1e78ebe75d6137b7efb5f97a
[ "MIT" ]
null
null
null
21_sesiones_remotas_y_transmision_de_datos.ipynb
jasant00/servidores
50f23b7a3e0d9b2e1e78ebe75d6137b7efb5f97a
[ "MIT" ]
7
2019-03-06T03:36:51.000Z
2021-07-08T14:55:10.000Z
23.698171
405
0.551267
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d03af298fa075ef655143d732fad6d324476ab22
28,419
ipynb
Jupyter Notebook
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
a76ffaacde8232c36854c45341104c6ef8fb17a5
[ "CC0-1.0" ]
null
null
null
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
a76ffaacde8232c36854c45341104c6ef8fb17a5
[ "CC0-1.0" ]
null
null
null
Workspace/.ipynb_checkpoints/EricCheng-checkpoint.ipynb
vleong1/modeling_earthquake_damage
a76ffaacde8232c36854c45341104c6ef8fb17a5
[ "CC0-1.0" ]
1
2021-06-02T15:53:56.000Z
2021-06-02T15:53:56.000Z
39.52573
1,473
0.617545
[ [ [ "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV, RepeatedStratifiedKFold\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom category_encoders import OneHotEncoder\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.metrics import f1_score, precision_score, recall_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, HistGradientBoostingClassifier, RandomForestClassifier, BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\n\nimport warnings\nwarnings.filterwarnings('ignore')\n", "_____no_output_____" ], [ "df = pd.read_csv('./data/train_10pct.csv')\ndf.head(5)", "_____no_output_____" ], [ "df.shape\n", "_____no_output_____" ], [ "df.mean().value_counts(normalize=True)", "_____no_output_____" ], [ "df_labels = pd.read_csv('./data/train_10pct_labels.csv')\ndf_labels.head(5)", "_____no_output_____" ], [ "df_labels.shape\n", "_____no_output_____" ], [ "# read in data\ntrain_values = pd.read_csv('../data/Proj5_train_values.csv')\ntrain_labels = pd.read_csv('./data/Proj5_train_labels.csv')\n# grab first 10% of rows\ntrain_values = train_values.head(int(len(train_values) * 0.1))\ntrain_labels = train_labels.head(int(len(train_labels) * 0.1))", "_____no_output_____" ], [ "print(f'Train value shape - {train_values.shape}')\nprint(f'Train labels shape - {train_labels.shape}')", "_____no_output_____" ], [ "train_values.describe().T", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "## Merge Datasets", "_____no_output_____" ] ], [ [ "combo = pd.merge(train_values, train_labels, on = 'building_id')\ncombo.head(5)", "_____no_output_____" ], [ "plt.figure (figsize=(5,10));\nsns.heatmap(df.corr()[['damage_grade']].sort_values(by='damage_grade', ascending = False),annot=True )", "_____no_output_____" ], [ "sns.scatterplot(data=combo, x='age', y='damage_grade', hue='age');", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ] ], [ [ "#Baseline\ntrain_labels['damage_grade'].value_counts(normalize=True)", "_____no_output_____" ], [ "le = LabelEncoder()\ntrain_enc = train_values.apply(le.fit_transform)\ntrain_enc", "_____no_output_____" ], [ "#From Chris\n\n#X = train_enc\n#y = trainlabel['damage_grade']\n#X_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123)\n#pipe_forest = make_pipeline(StandardScaler(), DecisionTreeClassifier())\n#params = {'decisiontreeclassifier__max_depth' : [2, 3, 4, 5]}\n#grid_forest = GridSearchCV(pipe_forest, param_grid = params)\n#grid_forest.fit(X_train,y_train)\n#grid_forest.score(X_test,y_test) # I got 0.646815042210284\n#grid_forest.best_estimator_", "_____no_output_____" ], [ "#TTS\nX = train_enc\ny = train_labels['damage_grade']\n#X_train, X_test, y_train, y_test = train_test_split(train_enc,train_labels, random_state=123 )\nX_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123)", "_____no_output_____" ] ], [ [ "## Model", "_____no_output_____" ] ], [ [ "#from Hackathon2 \n#Cvect and logreg\n#pipe = make_pipeline(CountVectorizer(stop_words = 'english'), LogisticRegression(n_jobs=-1))\n#\n#params = {'countvectorizer__max_features':[500, 1000, 15000, 2000, 2500]}\n#\n#grid=GridSearchCV(pipe, param_grid=params, n_jobs= -1)\n#grid.fit(X_train, y_train)\n#", "_____no_output_____" ] ], [ [ "### logreg", "_____no_output_____" ] ], [ [ "#Cvect and logreg\npipe = make_pipeline(StandardScaler(),LogisticRegression(n_jobs=-1))\n#\n#params = {'countvectorizer__max_features':[500, 1000, 15000, 2000, 2500]}\n#\n#grid=GridSearchCV(pipe, n_jobs= -1)\npipe.fit(X_train, y_train)\npipe.score(X_train, y_train)", "_____no_output_____" ], [ "pipe.fit(X_test, y_test)\npipe.score(X_test, y_test)", "_____no_output_____" ], [ "pipe.get_params().keys()\n", "_____no_output_____" ], [ "#LogisticRegression\npipe_lgr = make_pipeline(StandardScaler(), LogisticRegression(n_jobs = -1, max_iter = 1000))\nparams = {'logisticregression__C' : [0.1, 0.75, 1, 10],\n 'logisticregression__solver' : ['newton-cg', 'lbfgs', 'liblinear']}\ngrid_lgr = GridSearchCV(pipe_lgr, param_grid = params)\ngrid_lgr.fit(X_train, y_train)\nprint(f'Train Score: {grid_lgr.score(X_train, y_train)}')\nprint(f'Test Score: {grid_lgr.score(X_test, y_test)}')\ngrid_lgr.best_params_", "_____no_output_____" ] ], [ [ "## Modeling KNN", "_____no_output_____" ] ], [ [ "# define models and parameters\n# model = KNeighborsClassifier()\n# n_neighbors = range(1, 21, 2)\n# weights = ['uniform', 'distance']\n# #metric = ['euclidean', 'manhattan', 'minkowski']\n# metric = ['euclidean']\n# # define grid search\n# grid = dict(n_neighbors=n_neighbors,weights=weights,metric=metric)\n# #cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\n# #grid_search = GridSearchCV(estimator=model, param_grid=grid, n_jobs=-1, cv=cv, scoring='accuracy',error_score=0)\n# grid_search = GridSearchCV(estimator=model, param_grid=grid, n_jobs=-1, scoring='accuracy',error_score=0)\n# grid_result = grid_search.fit(X, y)\n# # summarize results\n# print(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))\n# means = grid_result.cv_results_['mean_test_score']\n# stds = grid_result.cv_results_['std_test_score']\n# params = grid_result.cv_results_['params']\n# for mean, stdev, param in zip(means, stds, params):\n# print(\"%f (%f) with: %r\" % (mean, stdev, param))", "_____no_output_____" ], [ "#Basic KNN\nX = train_enc\ny = train_labels['damage_grade']\nX_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123)\n\npipe_knn = make_pipeline(StandardScaler(),KNeighborsClassifier(n_jobs=-1))\npipe_knn.fit(X_train, y_train)\npipe_knn.score(X_train, y_train)\nprint(f'Train Score: {pipe_knn.score(X_train, y_train)}')\nprint(f'Test Score: {pipe_knn.score(X_test, y_test)}')", "_____no_output_____" ] ], [ [ "### Trying Veronica's code - KNN testing\n", "_____no_output_____" ] ], [ [ "pipe_knn = make_pipeline(StandardScaler(), KNeighborsClassifier(n_jobs = -1))\n\n# n_neighbors must be odd to avoid an even split\n#Note: tried leaf size and p, but it didn't give us any value\nparams = {'kneighborsclassifier__n_neighbors' : [5, 7, 9, 11]} \n\ngrid_knn = GridSearchCV(pipe_knn, param_grid = params)\ngrid_knn.fit(X_train, y_train)\nprint(f'Train Score: {grid_knn.score(X_train, y_train)}')\nprint(f'Test Score: {grid_knn.score(X_test, y_test)}')\ngrid_knn.best_params_", "_____no_output_____" ] ], [ [ "### 5/13 per Jacob, use OHE instead of LabelEncoding", "_____no_output_____" ], [ "#### LOG with OHE\n", "_____no_output_____" ] ], [ [ "X = train_values\ny = train_labels['damage_grade']\nX_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123)", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ] ], [ [ "#Cvect and logreg\n\n#define X and y\nX = train_values\ny = train_labels['damage_grade']\nX_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123)\n\n#Create pipeline\npipe = make_pipeline(OneHotEncoder(),StandardScaler(with_mean=False), LogisticRegression(n_jobs=-1))\n\nparams = {'logisticregression__C' : [0.1, 0.75, 1, 10],\n #'logisticregression__solver' : ['newton-cg', 'lbfgs', 'liblinear']\n }\ngrid_lgr = GridSearchCV(pipe, param_grid = params)\n\n\ngrid_lgr.fit(X_train, y_train)\ngrid_lgr.score(X_test, y_test)\nprint(f'Train Score: {grid_lgr.score(X_train, y_train)}')\nprint(f'Test Score: {grid_lgr.score(X_test, y_test)}')", "Train Score: 0.5925300588385777\nTest Score: 0.585111281657713\n" ] ], [ [ "#### KNN with OHE\n", "_____no_output_____" ] ], [ [ "#train_values = train_values.head(int(len(train_values) * 0.1))\n#train_labels = train_labels.head(int(len(train_labels) * 0.1))\nX = train_values\ny = train_labels['damage_grade']\nX_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=123)\n\npipe_knn = make_pipeline(OneHotEncoder(),StandardScaler(), KNeighborsClassifier(n_jobs = -1))\n\n# n_neighbors must be odd to avoid an even split\nparams = {'kneighborsclassifier__n_neighbors' : [5, 7, 9, 11]}\n #'kneighborsclassifier__leaf_size': [1,5,10,30]}\n\n\n#define parameters for hypertuning\n#params = {\n# 'n_neighbors': [5, 7, 9, 11],\n# 'leaf_size': (1,30),\n# 'p': (1,2)\n\ngrid_knn = GridSearchCV(pipe_knn, param_grid = params)\ngrid_knn.fit(X_train, y_train)\nprint(f'Train Score: {grid_knn.score(X_train, y_train)}')\nprint(f'Test Score: {grid_knn.score(X_test, y_test)}')\ngrid_knn.best_params_", "Train Score: 0.6720900486057815\nTest Score: 0.575287797390637\n" ] ], [ [ "---", "_____no_output_____" ] ], [ [ "#https://medium.datadriveninvestor.com/k-nearest-neighbors-in-python-hyperparameters-tuning-716734bc557f\n\n#List Hyperparameters that we want to tune.\nleaf_size = list(range(1,50))\nn_neighbors = list(range(1,30))\np=[1,2]\n#Convert to dictionary\nhyperparameters = dict(leaf_size=leaf_size, n_neighbors=n_neighbors, p=p)\n#Create new KNN object\nknn_2 = KNeighborsClassifier()\n#Use GridSearch\nclf = GridSearchCV(knn_2, hyperparameters, cv=10)", "_____no_output_____" ], [ "parameters_KNN = {\n 'n_neighbors': (1,10, 1),\n 'leaf_size': (20,40,1),\n 'p': (1,2),\n 'weights': ('uniform', 'distance'),\n 'metric': ('minkowski', 'chebyshev'),\n \n# with GridSearch\ngrid_search_KNN = GridSearchCV(\n estimator=estimator_KNN,\n param_grid=parameters_KNN,\n scoring = 'accuracy',\n n_jobs = -1,\n cv = 5", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d03b154bad4b3ff3bed6376cf1ef439154bb959a
332,039
ipynb
Jupyter Notebook
Understanding_the_LDA_Algorithm_20xx.ipynb
mistylight/Understanding_the_LDA_Algorithm
9d8f7a8a85ed16a1eb56e56ed5830c2fb2efce83
[ "MIT" ]
null
null
null
Understanding_the_LDA_Algorithm_20xx.ipynb
mistylight/Understanding_the_LDA_Algorithm
9d8f7a8a85ed16a1eb56e56ed5830c2fb2efce83
[ "MIT" ]
null
null
null
Understanding_the_LDA_Algorithm_20xx.ipynb
mistylight/Understanding_the_LDA_Algorithm
9d8f7a8a85ed16a1eb56e56ed5830c2fb2efce83
[ "MIT" ]
null
null
null
28.486531
1,621
0.388259
[ [ [ "# LDA Training\n<figure>\n<div>\n<img src=https://s2.loli.net/2022/02/28/X7vzOlDHJtP6UnM.png width=\"600\">\n</div>\n<figcaption>The LDA training algorithm from <a href=http://www.arbylon.net/publications/text-est.pdf>Parameter estimation for text analysis</a></figcaption>\n</figure>", "_____no_output_____" ] ], [ [ "import random\nimport numpy as np\nfrom collections import defaultdict, OrderedDict\nfrom types import SimpleNamespace\nfrom tqdm.notebook import tqdm\nfrom visualize import visualize_topic_word", "_____no_output_____" ], [ "# === corpus loading ===\nclass NeurIPSCorpus:\n def __init__(self, data_path, num_topics, mode, start_doc_idx=0, max_num_docs=100, max_num_words=10000, max_doc_length=1000, train_corpus=None):\n self.docs = []\n self.word2id = OrderedDict()\n self.max_doc_length = max_doc_length\n self.mode = mode\n\n # only keep the most frequent words\n if self.mode == \"train\":\n word2cnt = defaultdict(int)\n with open(data_path) as fin:\n for i, line in enumerate(list(fin)[::-1]): # use more recent papers\n if i >= max_num_docs: break\n for word in line.strip().split():\n word2cnt[word] += 1\n \n word2cnt = sorted(list(word2cnt.items()), key=lambda x: x[1], reverse=True)\n if len(word2cnt) > max_num_words:\n word2cnt = word2cnt[:max_num_words]\n word2cnt = dict(word2cnt)\n\n # read in the doc and convert words to integers\n with open(data_path) as fin:\n for i, line in enumerate(list(fin)[::-1]): # use more recent papers\n if i < start_doc_idx: continue\n if i - start_doc_idx >= max_num_docs: break\n doc = []\n for word in line.strip().split():\n if len(doc) >= self.max_doc_length: break\n if self.mode == \"train\":\n if word not in word2cnt: continue\n if word not in self.word2id: \n self.word2id[word] = len(self.word2id)\n doc.append(self.word2id[word])\n else:\n if word not in train_corpus.word2id: continue\n doc.append(train_corpus.word2id[word])\n self.docs.append(doc)\n\n self.num_docs = len(self.docs)\n self.num_topics = num_topics\n self.num_words = len(self.word2id)\n self.id2word = {v: k for k, v in self.word2id.items()}\n print(\n \"num_docs:\", self.num_docs, \n \"num_topics:\", self.num_topics, \n \"num_words:\", self.num_words\n )\n\ncorpus = NeurIPSCorpus(\n data_path=\"data/papers.txt\", \n mode=\"train\",\n num_topics=10,\n start_doc_idx=0,\n max_num_docs=1000,\n max_num_words=10000,\n max_doc_length=200,\n)\nhparams = SimpleNamespace(\n alpha=np.ones([corpus.num_topics], dtype=float) / corpus.num_topics,\n beta = np.ones([corpus.num_words], dtype=float) / corpus.num_topics,\n gibbs_sampling_max_iters=500,\n)", "num_docs: 1000 num_topics: 10 num_words: 7794\n" ], [ "# === initialization ===\nprint(\"Initializing...\", flush=True)\nn_doc_topic = np.zeros([corpus.num_docs, corpus.num_topics], dtype=float) # n_m^(k)\nn_topic_word = np.zeros([corpus.num_topics, corpus.num_words], dtype=float) # n_k^(t)\nz_doc_word = np.zeros([corpus.num_docs, corpus.max_doc_length], dtype=int)\n\nfor doc_i in range(corpus.num_docs):\n for j, word_j in enumerate(corpus.docs[doc_i]):\n topic_ij = random.randint(0, corpus.num_topics - 1)\n n_doc_topic[doc_i, topic_ij] += 1\n n_topic_word[topic_ij, word_j] += 1\n z_doc_word[doc_i, j] = topic_ij\n\n# === Gibbs sampling ===\nprint(\"Gibbs sampling...\", flush=True)\nfor iteration in tqdm(range(hparams.gibbs_sampling_max_iters)):\n for doc_i in range(corpus.num_docs):\n for j, word_j in enumerate(corpus.docs[doc_i]):\n # remove the old assignment\n topic_ij = z_doc_word[doc_i, j]\n n_doc_topic[doc_i, topic_ij] -= 1\n n_topic_word[topic_ij, word_j] -= 1\n # compute the new assignment\n p_doc_topic = (n_doc_topic[doc_i, :] + hparams.alpha) \\\n / np.sum(n_doc_topic[doc_i] + hparams.alpha)\n p_topic_word = (n_topic_word[:, word_j] + hparams.beta[word_j]) \\\n / np.sum(n_topic_word + hparams.beta, axis=1)\n p_topic = p_doc_topic * p_topic_word\n p_topic /= np.sum(p_topic)\n # record the new assignment\n new_topic_ij = np.random.choice(np.arange(corpus.num_topics), p=p_topic)\n n_doc_topic[doc_i, new_topic_ij] += 1\n n_topic_word[new_topic_ij, word_j] += 1\n z_doc_word[doc_i, j] = new_topic_ij\n\n if iteration % 50 == 0:\n print(f\"Iter [{iteration}]===\")\n # === Check convergence and read out parameters ===\n theta = (n_doc_topic + hparams.alpha) / np.sum(n_doc_topic + hparams.alpha, axis=1, keepdims=True)\n phi = (n_topic_word + hparams.beta) / np.sum(n_topic_word + hparams.beta, axis=1, keepdims=True)\n\n all_top_words = []\n all_top_probs = []\n for topic in range(corpus.num_topics):\n top_words = np.argsort(phi[topic])[::-1][:10]\n top_probs = phi[topic, top_words]\n top_words = [corpus.id2word[word] for word in top_words]\n all_top_words.append(top_words)\n all_top_probs.append(top_probs)\n print(f\"Topic {topic}:\", top_words)\n visualize_topic_word(all_top_words, all_top_probs)", "Initializing...\nGibbs sampling...\n" ] ], [ [ "# Inference on unseen documents", "_____no_output_____" ] ], [ [ "# === inference on unseen documents ===\ntest_corpus = NeurIPSCorpus(\n data_path=\"data/papers.txt\", \n mode=\"test\",\n num_topics=10,\n start_doc_idx=1000,\n max_num_docs=5,\n max_num_words=10000,\n max_doc_length=200,\n train_corpus=corpus,\n)\n# === inference via Gibbs sampling ===\nfor i, doc in enumerate(test_corpus.docs):\n print(f\"\\nTest Doc [{i}] ===\")\n doc_i = 0 # only infer 1 test doc at a time\n test_n_doc_topic = np.zeros([1, corpus.num_topics], dtype=float)\n test_n_topic_word = np.zeros([corpus.num_topics, corpus.num_words], dtype=float)\n test_z_doc_word = np.zeros([1, corpus.max_doc_length], dtype=int)\n\n print(\" \".join([corpus.id2word[x] for x in doc]))\n\n for j, word_j in enumerate(doc):\n topic_ij = random.randint(0, corpus.num_topics - 1)\n test_n_doc_topic[doc_i, topic_ij] += 1\n test_n_topic_word[topic_ij, word_j] += 1\n test_z_doc_word[doc_i, j] = topic_ij\n\n for iteration in tqdm(range(100)):\n for j, word_j in enumerate(doc):\n # remove the old assignment\n topic_ij = test_z_doc_word[doc_i, j]\n test_n_doc_topic[doc_i, topic_ij] -= 1\n test_n_topic_word[topic_ij, word_j] -= 1\n # compute the new assignment (new sampling formula!)\n p_doc_topic = (test_n_doc_topic[doc_i, :] + hparams.alpha) \\\n / np.sum(test_n_doc_topic[doc_i] + hparams.alpha)\n p_topic_word = (test_n_topic_word[:, word_j] + n_topic_word[:, word_j] + hparams.beta[word_j]) \\\n / np.sum(test_n_topic_word + n_topic_word + hparams.beta, axis=1)\n p_topic = p_doc_topic * p_topic_word\n p_topic /= np.sum(p_topic)\n # record the new assignment\n new_topic_ij = np.random.choice(np.arange(corpus.num_topics), p=p_topic)\n test_n_doc_topic[doc_i, new_topic_ij] += 1\n test_n_topic_word[new_topic_ij, word_j] += 1\n test_z_doc_word[doc_i, j] = new_topic_ij\n\n # === Check convergence and read out parameters ===\n test_theta = (test_n_doc_topic + hparams.alpha) / np.sum(test_n_doc_topic + hparams.alpha, axis=1, keepdims=True)\n test_phi = (test_n_topic_word + hparams.beta) / np.sum(test_n_topic_word + hparams.beta, axis=1, keepdims=True)\n print(\"Topic distribution:\", [float(f\"{x:.4f}\") for x in test_theta[0]])\n print(\"Top 3 topics:\", np.argsort(test_theta[0])[::-1][:3])", "num_docs: 5 num_topics: 10 num_words: 0\n\nTest Doc [0] ===\ninference graphical models semidefinite programming a microsoft research cs toronto edu mit microsoft research mit edu andrea montanari stanford university montanari stanford edu abstract maximum posteriori probability map inference graphical model amount solve graph structure combinatorial optimization problem popular inference algorithm belief propagation bp generalize belief propagation intimately related linear programming lp relaxation adams hierarchy despite popularity algorithm understand sum square hierarchy base semidefinite programming provide superior guarantee unfortunately relaxation graph n vertex require solve n d variable d degree hierarchy practice d approach scale ten variable paper propose binary relaxation map inference hierarchy innovation focus computational efficiency firstly analogy bp variant introduce decision variable correspond region graphical model secondly solve result non convex style method develop sequential procedure demonstrate result algorithm solve problem ten thousand variable minute outperform bp practical problem image denoising spin glass finally specific graph type establish sufficient condition tightness propose partial relaxation introduction graphical model provide powerful framework analyze system comprise large number interact variable inference graphical model crucial scientific methodology application variety field include causal inference computer vision statistical physics information theory genome research wj kf mm paper propose class inference algorithm pairwise graphical model model fully specify assign finite domain x variable ii\n" ] ], [ [ "Compare with the learned topics: \n\n<img src=https://raw.githubusercontent.com/mistylight/picbed/main/Hexo/Screen%20Shot%202022-02-28%20at%205.10.12%20PM.png style=\"width: 1200px\">", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d03b15a9f13970a83f6c4fdd8427502374e058e2
56,361
ipynb
Jupyter Notebook
190211_evolve_p3_p7_compute_best_conv_ts_from_err_and_p-val_info.ipynb
amwilson149/baby-andross
c1788cfa4d00130a1826044728667c51170d4870
[ "BSD-3-Clause" ]
null
null
null
190211_evolve_p3_p7_compute_best_conv_ts_from_err_and_p-val_info.ipynb
amwilson149/baby-andross
c1788cfa4d00130a1826044728667c51170d4870
[ "BSD-3-Clause" ]
4
2021-03-31T19:59:56.000Z
2022-03-12T00:47:26.000Z
190211_evolve_p3_p7_compute_best_conv_ts_from_err_and_p-val_info.ipynb
amwilson149/baby-andross
c1788cfa4d00130a1826044728667c51170d4870
[ "BSD-3-Clause" ]
null
null
null
230.987705
25,396
0.918454
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport scipy.stats as st", "_____no_output_____" ] ], [ [ "Set plot font size", "_____no_output_____" ] ], [ [ "FS = 18", "_____no_output_____" ] ], [ [ "Get dictionary with information about errors and p-values during convergent time steps", "_____no_output_____" ] ], [ [ "fname = './data/p3_p7_evolve_results/190211_errs_per_conv_ts_pr_0.005_g_1.1_niter_100.json'", "_____no_output_____" ], [ "with open(fname,'r') as f:\n c_err_results = json.loads(f.read())", "_____no_output_____" ], [ "# Inspect keys\nprint(c_err_results.keys())", "dict_keys(['err_ncfs', 'err_npcs', 'p_nsyns', 'p_nsynspcf', 'p_npcspcf', 'p_ncfsppc', 'time_step', 'iteration'])\n" ], [ "# Go through simulation iterations and compute the min, max, and best\n# (where errors are minimized and p-values are maximized) time step for each\nitercurr = []\nmin_c_ts = []\nmax_c_ts = []\nmean_c_ts = []\nbest_c_ts = []\n\niters = list(set(c_err_results['iteration']))\nfor ic in iters:\n rowscurr = [i for i,q in enumerate(c_err_results['iteration']) if q == ic]\n encfscurr = [c_err_results['err_ncfs'][q] for q in rowscurr]\n enpcscurr = [c_err_results['err_npcs'][q] for q in rowscurr]\n pnsynscurr = [c_err_results['p_nsyns'][q] for q in rowscurr]\n pnsynspcfcurr = [c_err_results['p_nsynspcf'][q] for q in rowscurr]\n pnpcspcfcurr = [c_err_results['p_npcspcf'][q] for q in rowscurr]\n pncfsppccurr = [c_err_results['p_ncfsppc'][q] for q in rowscurr]\n tscurr = [c_err_results['time_step'][q] for q in rowscurr]\n \n itercurr.append(ic)\n min_c_ts.append(np.min(tscurr))\n max_c_ts.append(np.max(tscurr))\n mean_c_ts.append(np.mean(tscurr))\n \n b_encfs = [i for i,q in enumerate(encfscurr) if q == np.min(encfscurr)]\n b_enpcs = [i for i,q in enumerate(enpcscurr) if q == np.min(enpcscurr)]\n b_pnsyns = [i for i,q in enumerate(pnsynscurr) if q == np.max(pnsynscurr)]\n b_pnsynspcf = [i for i,q in enumerate(pnsynspcfcurr) if q == np.max(pnsynspcfcurr)]\n b_pnpcspcf = [i for i,q in enumerate(pnpcspcfcurr) if q == np.max(pnpcspcfcurr)]\n b_pncfsppc = [i for i,q in enumerate(pncfsppccurr) if q == np.max(pncfsppccurr)]\n \n tben = [tscurr[q] for q in b_encfs]\n tbep = [tscurr[q] for q in b_enpcs]\n tpnsyns = [tscurr[q] for q in b_pnsyns]\n tpnspcf = [tscurr[q] for q in b_pnsynspcf]\n tpnpcpcf = [tscurr[q] for q in b_pnpcspcf]\n tpncfppc = [tscurr[q] for q in b_pncfsppc]\n \n # Find the time step where most of these conditions are true\n b_ts = st.mode(tben + tbep + tpnsyns + tpnspcf + tpnpcpcf + tpncfppc)[0][0]\n best_c_ts.append(b_ts)", "_____no_output_____" ], [ "plt.figure(figsize=(10,10))\nplt.hist(best_c_ts)\nplt.xlabel('time step of best convergence',fontsize=FS)\nplt.ylabel('number of occurrences',fontsize=FS)\nplt.title('Best convergence times for iterations of simulation with pr 0.005, g 1.1',fontsize=FS)\nplt.show()\nprint('mean best convergence time = {0} +/- {1} time steps'.format(np.mean(best_c_ts),st.sem(best_c_ts)))", "_____no_output_____" ], [ "plt.figure(figsize=(10,10))\nplt.hist(mean_c_ts)\nplt.xlabel('mean time step of convergence',fontsize=FS)\nplt.ylabel('number of occurrences',fontsize=FS)\nplt.title('Mean convergence times for iterations of simulation with pr 0.005, g 1.1',fontsize=FS)\nplt.show()\nprint('mean of mean convergent time steps = {0}'.format(np.mean(mean_c_ts)))", "_____no_output_____" ], [ "np.max(iters)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d03b37650373a173076fdfa5209cf4be6d7e3d05
43,026
ipynb
Jupyter Notebook
M11_A_DJ_NLP_Assignment.ipynb
schwaaweb/aimlds1_11-NLP
94fe4e5389ef22933c34849411ea7b7bf5509730
[ "Unlicense" ]
null
null
null
M11_A_DJ_NLP_Assignment.ipynb
schwaaweb/aimlds1_11-NLP
94fe4e5389ef22933c34849411ea7b7bf5509730
[ "Unlicense" ]
null
null
null
M11_A_DJ_NLP_Assignment.ipynb
schwaaweb/aimlds1_11-NLP
94fe4e5389ef22933c34849411ea7b7bf5509730
[ "Unlicense" ]
null
null
null
42.017578
667
0.531934
[ [ [ "[View in Colaboratory](https://colab.research.google.com/github/schwaaweb/aimlds1_11-NLP/blob/master/M11_A_DJ_NLP_Assignment.ipynb)", "_____no_output_____" ], [ "### Assignment: Natural Language Processing", "_____no_output_____" ], [ "In this assignment, you will work with a data set that contains restaurant reviews. You will use a Naive Bayes model to classify the reviews (positive or negative) based on the words in the review. The main objective of this assignment is gauge the performance of a Naive Bayes model by using a confusion matrix; however in order to ascertain the efficiacy of the model, you will have to first train the Naive Bayes model with a portion (i.e. 70%) of the underlying data set and then test it against the remainder of the data set . Before you can train the model, you will have to go through a sequence of steps to get the data ready for training the model.\n\nSteps you may need to perform:\n\n**1) **Read in the list of restaurant reviews\n\n**2)** Convert the reviews into a list of tokens\n\n**3) **You will most likely have to eliminate stop words\n\n**4)** You may have to utilize stemming or lemmatization to determine the base form of the words\n\n**5) **You will have to vectorize the data (i.e. construct a document term/word matix) wherein select words from the reviews will constitute the columns of the matrix and the individual reviews will be part of the rows of the matrix\n\n**6) ** Create 'Train' and 'Test' data sets (i.e. 70% of the underlying data set will constitute the training set and 30% of the underlying data set will constitute the test set)\n\n**7)** Train a Naive Bayes model on the Train data set and test it against the test data set\n\n**8) **Construct a confusion matirx to gauge the performance of the model\n\n**Dataset**: https://www.dropbox.com/s/yl5r7kx9nq15gmi/Restaurant_Reviews.tsv?raw=1\n\n\n", "_____no_output_____" ], [ "**1) **Read in the list of restaurant reviews", "_____no_output_____" ] ], [ [ "#%%time\n#!wget -c https://www.dropbox.com/s/yl5r7kx9nq15gmi/Restaurant_Reviews.tsv?raw=1 && mv Restaurant_Reviews.tsv?raw=1 Restaurant_Reviews.tsv\n!ls -lh *tsv", "-rw-r--r--@ 1 darwinm staff 60K Jun 13 17:43 Restaurant_Reviews.tsv\n" ], [ "%%time\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport re\nimport string\nimport nltk\nnltk.download('all')\n", "[nltk_data] Downloading collection 'all'\n[nltk_data] | \n[nltk_data] | Downloading package abc to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package abc is already up-to-date!\n[nltk_data] | Downloading package alpino to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package alpino is already up-to-date!\n[nltk_data] | Downloading package biocreative_ppi to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package biocreative_ppi is already up-to-date!\n[nltk_data] | Downloading package brown to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package brown is already up-to-date!\n[nltk_data] | Downloading package brown_tei to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package brown_tei is already up-to-date!\n[nltk_data] | Downloading package cess_cat to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package cess_cat is already up-to-date!\n[nltk_data] | Downloading package cess_esp to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package cess_esp is already up-to-date!\n[nltk_data] | Downloading package chat80 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package chat80 is already up-to-date!\n[nltk_data] | Downloading package city_database to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package city_database is already up-to-date!\n[nltk_data] | Downloading package cmudict to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package cmudict is already up-to-date!\n[nltk_data] | Downloading package comparative_sentences to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package comparative_sentences is already up-to-\n[nltk_data] | date!\n[nltk_data] | Downloading package comtrans to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package comtrans is already up-to-date!\n[nltk_data] | Downloading package conll2000 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package conll2000 is already up-to-date!\n[nltk_data] | Downloading package conll2002 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package conll2002 is already up-to-date!\n[nltk_data] | Downloading package conll2007 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package conll2007 is already up-to-date!\n[nltk_data] | Downloading package crubadan to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package crubadan is already up-to-date!\n[nltk_data] | Downloading package dependency_treebank to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package dependency_treebank is already up-to-date!\n[nltk_data] | Downloading package dolch to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package dolch is already up-to-date!\n[nltk_data] | Downloading package europarl_raw to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package europarl_raw is already up-to-date!\n[nltk_data] | Downloading package floresta to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package floresta is already up-to-date!\n[nltk_data] | Downloading package framenet_v15 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package framenet_v15 is already up-to-date!\n[nltk_data] | Downloading package framenet_v17 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package framenet_v17 is already up-to-date!\n[nltk_data] | Downloading package gazetteers to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package gazetteers is already up-to-date!\n[nltk_data] | Downloading package genesis to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package genesis is already up-to-date!\n[nltk_data] | Downloading package gutenberg to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package gutenberg is already up-to-date!\n[nltk_data] | Downloading package ieer to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package ieer is already up-to-date!\n[nltk_data] | Downloading package inaugural to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package inaugural is already up-to-date!\n[nltk_data] | Downloading package indian to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package indian is already up-to-date!\n[nltk_data] | Downloading package jeita to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package jeita is already up-to-date!\n[nltk_data] | Downloading package kimmo to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package kimmo is already up-to-date!\n[nltk_data] | Downloading package knbc to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package knbc is already up-to-date!\n[nltk_data] | Downloading package lin_thesaurus to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package lin_thesaurus is already up-to-date!\n[nltk_data] | Downloading package mac_morpho to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package mac_morpho is already up-to-date!\n[nltk_data] | Downloading package machado to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package machado is already up-to-date!\n[nltk_data] | Downloading package masc_tagged to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package masc_tagged is already up-to-date!\n[nltk_data] | Downloading package moses_sample to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package moses_sample is already up-to-date!\n[nltk_data] | Downloading package movie_reviews to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package movie_reviews is already up-to-date!\n[nltk_data] | Downloading package names to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package names is already up-to-date!\n[nltk_data] | Downloading package nombank.1.0 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package nombank.1.0 is already up-to-date!\n[nltk_data] | Downloading package nps_chat to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package nps_chat is already up-to-date!\n[nltk_data] | Downloading package omw to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package omw is already up-to-date!\n[nltk_data] | Downloading package opinion_lexicon to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package opinion_lexicon is already up-to-date!\n[nltk_data] | Downloading package paradigms to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package paradigms is already up-to-date!\n[nltk_data] | Downloading package pil to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package pil is already up-to-date!\n[nltk_data] | Downloading package pl196x to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package pl196x is already up-to-date!\n[nltk_data] | Downloading package ppattach to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package ppattach is already up-to-date!\n[nltk_data] | Downloading package problem_reports to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package problem_reports is already up-to-date!\n[nltk_data] | Downloading package propbank to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package propbank is already up-to-date!\n[nltk_data] | Downloading package ptb to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package ptb is already up-to-date!\n[nltk_data] | Downloading package product_reviews_1 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package product_reviews_1 is already up-to-date!\n[nltk_data] | Downloading package product_reviews_2 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package product_reviews_2 is already up-to-date!\n[nltk_data] | Downloading package pros_cons to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package pros_cons is already up-to-date!\n[nltk_data] | Downloading package qc to /Users/darwinm/nltk_data...\n[nltk_data] | Package qc is already up-to-date!\n[nltk_data] | Downloading package reuters to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package reuters is already up-to-date!\n[nltk_data] | Downloading package rte to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package rte is already up-to-date!\n[nltk_data] | Downloading package semcor to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package semcor is already up-to-date!\n[nltk_data] | Downloading package senseval to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package senseval is already up-to-date!\n[nltk_data] | Downloading package sentiwordnet to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package sentiwordnet is already up-to-date!\n[nltk_data] | Downloading package sentence_polarity to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package sentence_polarity is already up-to-date!\n[nltk_data] | Downloading package shakespeare to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package shakespeare is already up-to-date!\n[nltk_data] | Downloading package sinica_treebank to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package sinica_treebank is already up-to-date!\n[nltk_data] | Downloading package smultron to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package smultron is already up-to-date!\n[nltk_data] | Downloading package state_union to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package state_union is already up-to-date!\n[nltk_data] | Downloading package stopwords to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package stopwords is already up-to-date!\n[nltk_data] | Downloading package subjectivity to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package subjectivity is already up-to-date!\n[nltk_data] | Downloading package swadesh to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package swadesh is already up-to-date!\n[nltk_data] | Downloading package switchboard to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package switchboard is already up-to-date!\n[nltk_data] | Downloading package timit to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package timit is already up-to-date!\n[nltk_data] | Downloading package toolbox to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package toolbox is already up-to-date!\n[nltk_data] | Downloading package treebank to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package treebank is already up-to-date!\n[nltk_data] | Downloading package twitter_samples to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package twitter_samples is already up-to-date!\n[nltk_data] | Downloading package udhr to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package udhr is already up-to-date!\n[nltk_data] | Downloading package udhr2 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package udhr2 is already up-to-date!\n[nltk_data] | Downloading package unicode_samples to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package unicode_samples is already up-to-date!\n[nltk_data] | Downloading package universal_treebanks_v20 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package universal_treebanks_v20 is already up-to-\n[nltk_data] | date!\n[nltk_data] | Downloading package verbnet to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package verbnet is already up-to-date!\n[nltk_data] | Downloading package webtext to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package webtext is already up-to-date!\n[nltk_data] | Downloading package wordnet to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package wordnet is already up-to-date!\n[nltk_data] | Downloading package wordnet_ic to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package wordnet_ic is already up-to-date!\n[nltk_data] | Downloading package words to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package words is already up-to-date!\n[nltk_data] | Downloading package ycoe to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package ycoe is already up-to-date!\n[nltk_data] | Downloading package rslp to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package rslp is already up-to-date!\n[nltk_data] | Downloading package maxent_treebank_pos_tagger to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package maxent_treebank_pos_tagger is already up-\n[nltk_data] | to-date!\n[nltk_data] | Downloading package universal_tagset to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package universal_tagset is already up-to-date!\n[nltk_data] | Downloading package maxent_ne_chunker to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package maxent_ne_chunker is already up-to-date!\n[nltk_data] | Downloading package punkt to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package punkt is already up-to-date!\n[nltk_data] | Downloading package book_grammars to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package book_grammars is already up-to-date!\n[nltk_data] | Downloading package sample_grammars to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package sample_grammars is already up-to-date!\n[nltk_data] | Downloading package spanish_grammars to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package spanish_grammars is already up-to-date!\n[nltk_data] | Downloading package basque_grammars to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package basque_grammars is already up-to-date!\n[nltk_data] | Downloading package large_grammars to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package large_grammars is already up-to-date!\n[nltk_data] | Downloading package tagsets to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package tagsets is already up-to-date!\n[nltk_data] | Downloading package snowball_data to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package snowball_data is already up-to-date!\n[nltk_data] | Downloading package bllip_wsj_no_aux to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package bllip_wsj_no_aux is already up-to-date!\n[nltk_data] | Downloading package word2vec_sample to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package word2vec_sample is already up-to-date!\n[nltk_data] | Downloading package panlex_swadesh to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package panlex_swadesh is already up-to-date!\n[nltk_data] | Downloading package mte_teip5 to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package mte_teip5 is already up-to-date!\n[nltk_data] | Downloading package averaged_perceptron_tagger to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package averaged_perceptron_tagger is already up-\n[nltk_data] | to-date!\n[nltk_data] | Downloading package perluniprops to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package perluniprops is already up-to-date!\n[nltk_data] | Downloading package nonbreaking_prefixes to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package nonbreaking_prefixes is already up-to-date!\n[nltk_data] | Downloading package vader_lexicon to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package vader_lexicon is already up-to-date!\n[nltk_data] | Downloading package porter_test to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package porter_test is already up-to-date!\n[nltk_data] | Downloading package wmt15_eval to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package wmt15_eval is already up-to-date!\n[nltk_data] | Downloading package mwa_ppdb to\n[nltk_data] | /Users/darwinm/nltk_data...\n[nltk_data] | Package mwa_ppdb is already up-to-date!\n[nltk_data] | \n[nltk_data] Done downloading collection all\nCPU times: user 4.32 s, sys: 1.79 s, total: 6.1 s\nWall time: 50.3 s\n" ], [ "df = pd.read_csv('Restaurant_Reviews.tsv', sep='\\t')\ndf.head()", "_____no_output_____" ], [ "df.tail()", "_____no_output_____" ] ], [ [ "**2)** Convert the reviews into a list of tokens", "_____no_output_____" ] ], [ [ "review = df['Review'] # dropping the like here\nprint(review)\nlen(review)", "0 Wow... Loved this place.\n1 Crust is not good.\n2 Not tasty and the texture was just nasty.\n3 Stopped by during the late May bank holiday of...\n4 The selection on the menu was great and so wer...\n5 Now I am getting angry and I want my damn pho.\n6 Honeslty it didn't taste THAT fresh.)\n7 The potatoes were like rubber and you could te...\n8 The fries were great too.\n9 A great touch.\n10 Service was very prompt.\n11 Would not go back.\n12 The cashier had no care what so ever on what I...\n13 I tried the Cape Cod ravoli, chicken, with cra...\n14 I was disgusted because I was pretty sure that...\n15 I was shocked because no signs indicate cash o...\n16 Highly recommended.\n17 Waitress was a little slow in service.\n18 This place is not worth your time, let alone V...\n19 did not like at all.\n20 The Burrittos Blah!\n21 The food, amazing.\n22 Service is also cute.\n23 I could care less... The interior is just beau...\n24 So they performed.\n25 That's right....the red velvet cake.....ohhh t...\n26 - They never brought a salad we asked for.\n27 This hole in the wall has great Mexican street...\n28 Took an hour to get our food only 4 tables in ...\n29 The worst was the salmon sashimi.\n ... \n970 I immediately said I wanted to talk to the man...\n971 The ambiance isn't much better.\n972 Unfortunately, it only set us up for disapppoi...\n973 The food wasn't good.\n974 Your servers suck, wait, correction, our serve...\n975 What happened next was pretty....off putting.\n976 too bad cause I know it's family owned, I real...\n977 Overpriced for what you are getting.\n978 I vomited in the bathroom mid lunch.\n979 I kept looking at the time and it had soon bec...\n980 I have been to very few places to eat that und...\n981 We started with the tuna sashimi which was bro...\n982 Food was below average.\n983 It sure does beat the nachos at the movies but...\n984 All in all, Ha Long Bay was a bit of a flop.\n985 The problem I have is that they charge $11.99 ...\n986 Shrimp- When I unwrapped it (I live only 1/2 a...\n987 It lacked flavor, seemed undercooked, and dry.\n988 It really is impressive that the place hasn't ...\n989 I would avoid this place if you are staying in...\n990 The refried beans that came with my meal were ...\n991 Spend your money and time some place else.\n992 A lady at the table next to us found a live gr...\n993 the presentation of the food was awful.\n994 I can't tell you how disappointed I was.\n995 I think food should have flavor and texture an...\n996 Appetite instantly gone.\n997 Overall I was not impressed and would not go b...\n998 The whole experience was underwhelming, and I ...\n999 Then, as if I hadn't wasted enough of my life ...\nName: Review, Length: 1000, dtype: object\n" ] ], [ [ "**3) **You will most likely have to eliminate stop words", "_____no_output_____" ], [ "**4)** You may have to utilize stemming or lemmatization to determine the base form of the words", "_____no_output_____" ] ], [ [ "stopwords = nltk.corpus.stopwords.words('english')\nps = nltk.PorterStemmer()\n\n\n#Elmiminate punctations\n#Tokenize based on whitespace\n#Stem the text\n#Remove stopwords\ndef process_text(txt):\n eliminate_punct = \"\".join([word.lower() for word in txt if word not in string.punctuation])\n tokens = re.split('\\W+', txt)\n txt = [ps.stem(word) for word in tokens if word not in stopwords]\n return txt\n \ndf['clean_review'] = df['Review'].apply(lambda x: process_text(x))\n\ndf.head()", "_____no_output_____" ], [ "import gensim\n\n# Use the Gensim document to create a dictionary - a dictionary maps every word to a number\ndictionary = gensim.corpora.Dictionary(df['clean_review'])\n# Examine the length of the dictionary\nnum_of_words = len(dictionary)\nprint(\"# of words in dictionary: {}\".format(num_of_words))\n#for index,word in dictionary.items():\n# print(index,word)\nprint(dictionary)", "# of words in dictionary: 1668\nDictionary(1668 unique tokens: ['', 'love', 'place', 'wow', 'crust']...)\n" ], [ "#print(dictionary.token2id)", "_____no_output_____" ] ], [ [ "**5) **You will have to vectorize the data (i.e. construct a document term/word matix) wherein select words from the reviews will constitute the columns of the matrix and the individual reviews will be part of the rows of the matrix", "_____no_output_____" ] ], [ [ "from pprint import pprint", "_____no_output_____" ], [ "%%time\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\ndef cv(data):\n count_vectorizer = CountVectorizer()\n\n emb = count_vectorizer.fit_transform(data)\n\n return emb, count_vectorizer\n\nlist_corpus = df[\"clean_review\"].tolist()\nlist_labels = df[\"Liked\"].tolist()\n\nX_train, X_test, y_train, y_test = train_test_split(list_corpus, list_labels, test_size=0.3, random_state=42)\n\n#X_train_counts, count_vectorizer = cv(X_train)\n#X_test_counts = count_vectorizer.transform(X_test)\n#pprint(X_train)\n\n#from sklearn.feature_extraction.text import CountVectorizer\n\n#count_vect = CountVectorizer(analyzer=process_text, max_features=1668)\n#W_counts = count_vect.fit_transform(df['clean_review'])\n#print(W_counts.shape)\n#print(count_vect.get_feature_names())", "CPU times: user 2.39 ms, sys: 5.47 ms, total: 7.86 ms\nWall time: 25 ms\n" ], [ "%%time\ncorpus = [dictionary.doc2bow(text) for text in list_corpus]", "CPU times: user 18 ms, sys: 3.51 ms, total: 21.5 ms\nWall time: 26 ms\n" ], [ "tfidf = gensim.models.TfidfModel(corpus)\ncorpus_tfidf = tfidf[corpus]\nindex = gensim.similarities.MatrixSimilarity(tfidf[corpus])\nsims = index[corpus_tfidf]\n#for vector in corpus:\n# print(vector)\n\nprint(sims.shape)", "(1000, 1000)\n" ] ], [ [ "**6) ** Create 'Train' and 'Test' data sets (i.e. 70% of the underlying data set will constitute the training set and 30% of the underlying data set will constitute the test set)", "_____no_output_____" ], [ "**7)** Train a Naive Bayes model on the Train data set and test it against the test data set\n", "_____no_output_____" ], [ "**8) **Construct a confusion matirx to gauge the performance of the model", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
d03b3965fc1e9c085847aacd25e6a5c10b86c6b9
589,637
ipynb
Jupyter Notebook
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
476f28bba620b7568a95ce3f298e117557382cd9
[ "MIT" ]
null
null
null
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
476f28bba620b7568a95ce3f298e117557382cd9
[ "MIT" ]
null
null
null
projects/creating_customer_segments/customer_segments.ipynb
ankdesh/Udacity-MachineLearning-Nanodegree
476f28bba620b7568a95ce3f298e117557382cd9
[ "MIT" ]
null
null
null
278.261916
245,748
0.895134
[ [ [ "# Machine Learning Engineer Nanodegree\n## Unsupervised Learning\n## Project 3: Creating Customer Segments", "_____no_output_____" ], [ "Welcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!\n\nIn addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. \n\n>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.", "_____no_output_____" ], [ "## Getting Started\n\nIn this project, you will analyze a dataset containing data on various customers' annual spending amounts (reported in *monetary units*) of diverse product categories for internal structure. One goal of this project is to best describe the variation in the different types of customers that a wholesale distributor interacts with. Doing so would equip the distributor with insight into how to best structure their delivery service to meet the needs of each customer.\n\nThe dataset for this project can be found on the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Wholesale+customers). For the purposes of this project, the features `'Channel'` and `'Region'` will be excluded in the analysis — with focus instead on the six product categories recorded for customers.\n\nRun the code block below to load the wholesale customers dataset, along with a few of the necessary Python libraries required for this project. You will know the dataset loaded successfully if the size of the dataset is reported.", "_____no_output_____" ] ], [ [ "# Import libraries necessary for this project\nimport numpy as np\nimport pandas as pd\nimport renders as rs\nfrom IPython.display import display # Allows the use of display() for DataFrames\n\n# Show matplotlib plots inline (nicely formatted in the notebook)\n%matplotlib inline\n\n# Load the wholesale customers dataset\ntry:\n data = pd.read_csv(\"customers.csv\")\n data.drop(['Region', 'Channel'], axis = 1, inplace = True)\n print \"Wholesale customers dataset has {} samples with {} features each.\".format(*data.shape)\nexcept:\n print \"Dataset could not be loaded. Is the dataset missing?\"", "Wholesale customers dataset has 440 samples with 6 features each.\n" ] ], [ [ "## Data Exploration\nIn this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you will track through the course of this project.\n\nRun the code block below to observe a statistical description of the dataset. Note that the dataset is composed of six important product categories: **'Fresh'**, **'Milk'**, **'Grocery'**, **'Frozen'**, **'Detergents_Paper'**, and **'Delicatessen'**. Consider what each category represents in terms of products you could purchase.", "_____no_output_____" ] ], [ [ "# Display a description of the dataset\ndisplay(data.describe())", "_____no_output_____" ] ], [ [ "### Implementation: Selecting Samples\nTo get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add **three** indices of your choice to the `indices` list which will represent the customers to track. It is suggested to try different sets of samples until you obtain customers that vary significantly from one another.", "_____no_output_____" ] ], [ [ "# TODO: Select three indices of your choice you wish to sample from the dataset\nindices = [0, 15, 45]\n\n# Create a DataFrame of the chosen samples\nsamples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True)\nprint \"Chosen samples of wholesale customers dataset:\"\ndisplay(samples)", "Chosen samples of wholesale customers dataset:\n" ] ], [ [ "### Question 1\nConsider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers. \n*What kind of establishment (customer) could each of the three samples you've chosen represent?* \n**Hint:** Examples of establishments include places like markets, cafes, and retailers, among many others. Avoid using names for establishments, such as saying *\"McDonalds\"* when describing a sample customer as a restaurant.", "_____no_output_____" ], [ "**Answer:** \nCustomer 0 - Seems to be a cafe or restaurant given higher than average consumption of Milk and grocery and lower consumption for other products.\n\nCustomer 15 - Only product which is near the mean for this customer is \"Fresh\". In general there is low consumption for almost all other products (nearing 50 percentile). This customer is probably a small grocery shop.\n\nCustomer 45 - Very high comsumption of Milk, groceries and detergents above average points to this is probably a big restaurant or Bakery. ", "_____no_output_____" ], [ "### Implementation: Feature Relevance\nOne interesting thought to consider is if one (or more) of the six product categories is actually relevant for understanding customer purchasing. That is to say, is it possible to determine whether customers purchasing some amount of one category of products will necessarily purchase some proportional amount of another category of products? We can make this determination quite easily by training a supervised regression learner on a subset of the data with one feature removed, and then score how well that model can predict the removed feature.\n\nIn the code block below, you will need to implement the following:\n - Assign `new_data` a copy of the data by removing a feature of your choice using the `DataFrame.drop` function.\n - Use `sklearn.cross_validation.train_test_split` to split the dataset into training and testing sets.\n - Use the removed feature as your target label. Set a `test_size` of `0.25` and set a `random_state`.\n - Import a decision tree regressor, set a `random_state`, and fit the learner to the training data.\n - Report the prediction score of the testing set using the regressor's `score` function.", "_____no_output_____" ] ], [ [ "# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature\nnew_data = data.drop('Detergents_Paper',axis=1)\n\n# TODO: Split the data into training and testing sets using the given feature as the target\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(new_data, data['Detergents_Paper'], test_size = 0.25, random_state = 0)\n\n# TODO: Create a decision tree regressor and fit it to the training set\nfrom sklearn.tree import DecisionTreeRegressor\nregressor = DecisionTreeRegressor()\n\n# TODO: Report the score of the prediction using the testing set\nfrom sklearn.metrics import r2_score\nmodel = regressor.fit(X_train,y_train)\nscore = r2_score(y_test, model.predict(X_test))\n\nprint (score)", "0.671835598453\n" ] ], [ [ "### Question 2\n*Which feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits?* \n**Hint:** The coefficient of determination, `R^2`, is scored between 0 and 1, with 1 being a perfect fit. A negative `R^2` implies the model fails to fit the data.", "_____no_output_____" ], [ "**Answer:** \nI chose Deteregents_Paper for prediction. The R^2 score achieved was 0.67 which shows that this feature is dependent on some (non-linear) combination of other features. Since this feature is not independent of other features, this feature may not provide unique information about customer's spending habits. ", "_____no_output_____" ], [ "### Visualize Feature Distributions\nTo get a better understanding of the dataset, we can construct a scatter matrix of each of the six product features present in the data. If you found that the feature you attempted to predict above is relevant for identifying a specific customer, then the scatter matrix below may not show any correlation between that feature and the others. Conversely, if you believe that feature is not relevant for identifying a specific customer, the scatter matrix might show a correlation between that feature and another feature in the data. Run the code block below to produce a scatter matrix.", "_____no_output_____" ] ], [ [ "# Produce a scatter matrix for each pair of features in the data\npd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');", "_____no_output_____" ] ], [ [ "### Question 3\n*Are there any pairs of features which exhibit some degree of correlation? Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? How is the data for those features distributed?* \n**Hint:** Is the data normally distributed? Where do most of the data points lie? ", "_____no_output_____" ], [ "**Answer:** Above figure shows a strong correlation between Detergent_Paper and Grocery. Also, there is a weaker correlation between Milk and Detergent_Paper, Milk and Grocery. This infact confirms my suspicion of Detergent_Paper being dependent on other features. \n\nThe data is definetly not normally distirbuted and most of it is cluttered near the origin.", "_____no_output_____" ], [ "## Data Preprocessing\nIn this section, you will preprocess the data to create a better representation of customers by performing a scaling on the data and detecting (and optionally removing) outliers. Preprocessing data is often times a critical step in assuring that results you obtain from your analysis are significant and meaningful.", "_____no_output_____" ], [ "### Implementation: Feature Scaling\nIf data is not normally distributed, especially if the mean and median vary significantly (indicating a large skew), it is most [often appropriate](http://econbrowser.com/archives/2014/02/use-of-logarithms-in-economics) to apply a non-linear scaling — particularly for financial data. One way to achieve this scaling is by using a [Box-Cox test](http://scipy.github.io/devdocs/generated/scipy.stats.boxcox.html), which calculates the best power transformation of the data that reduces skewness. A simpler approach which can work in most cases would be applying the natural logarithm.\n\nIn the code block below, you will need to implement the following:\n - Assign a copy of the data to `log_data` after applying a logarithm scaling. Use the `np.log` function for this.\n - Assign a copy of the sample data to `log_samples` after applying a logrithm scaling. Again, use `np.log`.", "_____no_output_____" ] ], [ [ "# TODO: Scale the data using the natural logarithm\nlog_data = np.log(data)\n\n# TODO: Scale the sample data using the natural logarithm\nlog_samples = np.log(samples)\n\n# Produce a scatter matrix for each pair of newly-transformed features\npd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');", "_____no_output_____" ] ], [ [ "### Observation\nAfter applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before).\n\nRun the code below to see how the sample data has changed after having the natural logarithm applied to it.", "_____no_output_____" ] ], [ [ "# Display the log-transformed sample data\ndisplay(log_samples)", "_____no_output_____" ] ], [ [ "### Implementation: Outlier Detection\nDetecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many \"rules of thumb\" for what constitutes an outlier in a dataset. Here, we will use [Tukey's Method for identfying outliers](http://datapigtechnologies.com/blog/index.php/highlighting-outliers-in-your-data-with-the-tukey-method/): An *outlier step* is calculated as 1.5 times the interquartile range (IQR). A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal.\n\nIn the code block below, you will need to implement the following:\n - Assign the value of the 25th percentile for the given feature to `Q1`. Use `np.percentile` for this.\n - Assign the value of the 75th percentile for the given feature to `Q3`. Again, use `np.percentile`.\n - Assign the calculation of an outlier step for the given feature to `step`.\n - Optionally remove data points from the dataset by adding indices to the `outliers` list.\n\n**NOTE:** If you choose to remove any outliers, ensure that the sample data does not contain any of these points! \nOnce you have performed this implementation, the dataset will be stored in the variable `good_data`.", "_____no_output_____" ] ], [ [ "from sets import Set\noutliers_indices = {}\n\n# For each feature find the data points with extreme high or low values\nfor feature in log_data.keys():\n \n # TODO: Calculate Q1 (25th percentile of the data) for the given feature\n Q1 = np.percentile(log_data[feature], 25)\n \n # TODO: Calculate Q3 (75th percentile of the data) for the given feature\n Q3 = np.percentile(log_data[feature], 75)\n \n # TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)\n step = 1.5 * (Q3 - Q1)\n \n # Display the outliers\n print \"Data points considered outliers for the feature '{}':\".format(feature)\n outlier = log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))]\n outliers_indices[feature] = Set(outlier.index)\n display(outlier)\n\n# Find outlier in all the Feature \nconsistent_outliers = Set(outliers_indices['Fresh'])\nfor feature in outliers_indices.keys():\n consistent_outliers.intersection_update(feature)\n#print (\"Outlier in all of the features: \" + str(consistent_outliers))\n\n# Create histogram for outliers => map of customer index to num of outlier features\nhist_outliers = {}\nfor feature in outliers_indices.keys():\n for idx in outliers_indices[feature]:\n hist_outliers[idx] = hist_outliers[idx] + 1 if idx in hist_outliers.keys() else 1\n\n# Find out liers in more than one feature\ntwice_outliers = [key for key,item in hist_outliers.iteritems() if item > 1]\n# print twice_outliers\n\n# OPTIONAL: Select the indices for data points you wish to remove\noutliers = twice_outliers\n\n# Remove the outliers, if any were specified\ngood_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True)", "Data points considered outliers for the feature 'Fresh':\n" ] ], [ [ "### Question 4\n*Are there any data points considered outliers for more than one feature based on the definition above? Should these data points be removed from the dataset? If any data points were added to the `outliers` list to be removed, explain why.* ", "_____no_output_____" ], [ "**Answer:** Datapoints which were outliers in the more than one feature should be considered outliers. Such points have been assigned to outliers and hence have been removed from dataset. There is no datapoint which is outlier in all the features.", "_____no_output_____" ], [ "## Feature Transformation\nIn this section you will use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, we will find which compound combinations of features best describe customers.", "_____no_output_____" ], [ "### Implementation: PCA\n\nNow that the data has been scaled to a more normal distribution and has had any necessary outliers removed, we can now apply PCA to the `good_data` to discover which dimensions about the data best maximize the variance of features involved. In addition to finding these dimensions, PCA will also report the *explained variance ratio* of each dimension — how much variance within the data is explained by that dimension alone. Note that a component (dimension) from PCA can be considered a new \"feature\" of the space, however it is a composition of the original features present in the data.\n\nIn the code block below, you will need to implement the following:\n - Import `sklearn.decomposition.PCA` and assign the results of fitting PCA in six dimensions with `good_data` to `pca`.\n - Apply a PCA transformation of the sample log-data `log_samples` using `pca.transform`, and assign the results to `pca_samples`.", "_____no_output_____" ] ], [ [ "# TODO: Apply PCA by fitting the good data with the same number of dimensions as features\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=6)\npca.fit(good_data)\n\n# TODO: Transform the sample log-data using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Generate PCA results plot\npca_results = rs.pca_results(good_data, pca)\n\nprint pca.explained_variance_ratio_.cumsum()", "[ 0.44302505 0.70681723 0.82988103 0.93109011 0.97959207 1. ]\n" ] ], [ [ "### Question 5\n*How much variance in the data is explained* ***in total*** *by the first and second principal component? What about the first four principal components? Using the visualization provided above, discuss what the first four dimensions best represent in terms of customer spending.* \n**Hint:** A positive increase in a specific dimension corresponds with an *increase* of the *positive-weighted* features and a *decrease* of the *negative-weighted* features. The rate of increase or decrease is based on the indivdual feature weights.", "_____no_output_____" ], [ "**Answer:** As shown above, approx 44% and 70% resp. is explained by the first and second principle component. First four components together explains approx 93% of data. \n\nDim 1 - The prevalant components in this dim are Milk Grocery and Detergents_paper. This makes sense as the visualizations in the scatter matrix showed the strong pair-wise dependence in these three components.\n\nDim 2 - Fresh, Frozen, and delicatessen are most prominent components in this dim. which did not show the correlation with the components of first dim in scatter matrix.\n\nDim 3 - Fresh and Delicatessen seem to be major components here capturing the negative correlation.\n\nDim 4 - This dim shows negative correlation in frozen and Delicatessen components. ", "_____no_output_____" ], [ "### Observation\nRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points. Consider if this is consistent with your initial interpretation of the sample points.", "_____no_output_____" ] ], [ [ "# Display sample log-data after having a PCA transformation applied\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))", "_____no_output_____" ] ], [ [ "### Implementation: Dimensionality Reduction\nWhen using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being explained. Because of this, the *cumulative explained variance ratio* is extremely important for knowing how many dimensions are necessary for the problem. Additionally, if a signifiant amount of variance is explained by only two or three dimensions, the reduced data can be visualized afterwards.\n\nIn the code block below, you will need to implement the following:\n - Assign the results of fitting PCA in two dimensions with `good_data` to `pca`.\n - Apply a PCA transformation of `good_data` using `pca.transform`, and assign the reuslts to `reduced_data`.\n - Apply a PCA transformation of the sample log-data `log_samples` using `pca.transform`, and assign the results to `pca_samples`.", "_____no_output_____" ] ], [ [ "# TODO: Apply PCA by fitting the good data with only two dimensions\npca = PCA(n_components=2).fit(good_data)\n\n# TODO: Transform the good data using the PCA fit above\nreduced_data = pca.transform(good_data)\n\n# TODO: Transform the sample log-data using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Create a DataFrame for the reduced data\nreduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2'])", "_____no_output_____" ] ], [ [ "### Observation\nRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions.", "_____no_output_____" ] ], [ [ "# Display sample log-data after applying PCA transformation in two dimensions\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))", "_____no_output_____" ] ], [ [ "## Clustering\n\nIn this section, you will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. You will then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale. ", "_____no_output_____" ], [ "### Question 6\n*What are the advantages to using a K-Means clustering algorithm? What are the advantages to using a Gaussian Mixture Model clustering algorithm? Given your observations about the wholesale customer data so far, which of the two algorithms will you use and why?*", "_____no_output_____" ], [ "**Answer:** Major advantage of K-means clustering is that it is converges quite fast as compared to other clustering algorithms. However K means is ameneable to getting stuck in local minima. \n\nGaussian Mixture model is generalization of K-means clustering. It does not need to assign hard clusters to the data-points and hence can have a probablistic association of a data point to clusters.\n\nSince we need to find appropriate number of clusters here, we need to experiment multiple times with different number of clusters, I will use faster and clearer K-means clustering algo. ", "_____no_output_____" ], [ "### Implementation: Creating Clusters\nDepending on the problem, the number of clusters that you expect to be in the data may already be known. When the number of clusters is not known *a priori*, there is no guarantee that a given number of clusters best segments the data, since it is unclear what structure exists in the data — if any. However, we can quantify the \"goodness\" of a clustering by calculating each data point's *silhouette coefficient*. The [silhouette coefficient](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_score.html) for a data point measures how similar it is to its assigned cluster from -1 (dissimilar) to 1 (similar). Calculating the *mean* silhouette coefficient provides for a simple scoring method of a given clustering.\n\nIn the code block below, you will need to implement the following:\n - Fit a clustering algorithm to the `reduced_data` and assign it to `clusterer`.\n - Predict the cluster for each data point in `reduced_data` using `clusterer.predict` and assign them to `preds`.\n - Find the cluster centers using the algorithm's respective attribute and assign them to `centers`.\n - Predict the cluster for each sample data point in `pca_samples` and assign them `sample_preds`.\n - Import sklearn.metrics.silhouette_score and calculate the silhouette score of `reduced_data` against `preds`.\n - Assign the silhouette score to `score` and print the result.", "_____no_output_____" ] ], [ [ "scores = []\n# TODO: Apply your clustering algorithm of choice to the reduced data \nfor num_clusters in range(2,15):\n from sklearn.cluster import KMeans\n clusterer = KMeans(n_clusters=num_clusters).fit(reduced_data)\n\n # TODO: Predict the cluster for each data point\n preds = clusterer.predict(reduced_data)\n\n # TODO: Find the cluster centers\n centers = clusterer.cluster_centers_\n\n # TODO: Predict the cluster for each transformed sample data point\n sample_preds = clusterer.predict(pca_samples)\n\n # TODO: Calculate the mean silhouette coefficient for the number of clusters chosen\n from sklearn.metrics import silhouette_score\n score = silhouette_score(reduced_data, preds)\n scores.append(score)\nscores_series = pd.Series(scores, index = range(2,15))", "_____no_output_____" ], [ "print scores_series.argmax()", "2\n" ], [ "%matplotlib inline\n#import matplotlib.pyplot as plt\n#plt.bar(range(len(scores)),scores)\nscore_df = pd.DataFrame(np.array(scores), index=range(2,15), columns= {\"Scores\"})\nscore_df.plot(kind='bar')\nprint score_df", " Scores\n2 0.426281\n3 0.397423\n4 0.331246\n5 0.351346\n6 0.365422\n7 0.363828\n8 0.364055\n9 0.359186\n10 0.348973\n11 0.351340\n12 0.360199\n13 0.366984\n14 0.351710\n" ], [ "# Use K=2 \nfrom sklearn.cluster import KMeans\nclusterer = KMeans(n_clusters=2).fit(reduced_data)\npreds = clusterer.predict(reduced_data)\ncenters = clusterer.cluster_centers_\nsample_preds = clusterer.predict(pca_samples)", "_____no_output_____" ] ], [ [ "### Question 7\n*Report the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score?* ", "_____no_output_____" ], [ "**Answer:** I tried the cluster numbers from 2 to 14 as shown above. The best silhoutte score is reported from K=2.", "_____no_output_____" ], [ "### Cluster Visualization\nOnce you've chosen the optimal number of clusters for your clustering algorithm using the scoring metric above, you can now visualize the results by executing the code block below. Note that, for experimentation purposes, you are welcome to adjust the number of clusters for your clustering algorithm to see various visualizations. The final visualization provided should, however, correspond with the optimal number of clusters. ", "_____no_output_____" ] ], [ [ "# Display the results of the clustering from implementation\nrs.cluster_results(reduced_data, preds, centers, pca_samples)", "_____no_output_____" ] ], [ [ "### Implementation: Data Recovery\nEach cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the *averages* of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to *the average customer of that segment*. Since the data is currently reduced in dimension and scaled by a logarithm, we can recover the representative customer spending from these data points by applying the inverse transformations.\n\nIn the code block below, you will need to implement the following:\n - Apply the inverse transform to `centers` using `pca.inverse_transform` and assign the new centers to `log_centers`.\n - Apply the inverse function of `np.log` to `log_centers` using `np.exp` and assign the true centers to `true_centers`.\n", "_____no_output_____" ] ], [ [ "# TODO: Inverse transform the centers\nlog_centers = pca.inverse_transform(centers)\n\n# TODO: Exponentiate the centers\ntrue_centers = np.exp(log_centers)\n\n# Display the true centers\nsegments = ['Segment {}'.format(i) for i in range(0,len(centers))]\ntrue_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())\ntrue_centers.index = segments\ndisplay(true_centers)", "_____no_output_____" ] ], [ [ "### Question 8\nConsider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project. *What set of establishments could each of the customer segments represent?* \n**Hint:** A customer who is assigned to `'Cluster X'` should best identify with the establishments represented by the feature set of `'Segment X'`.", "_____no_output_____" ], [ "**Answer:** The Segment 0 cutomer seems to be showing high projection value on the second principal component in PCA analysis. It has relatively high values for Fresh and Frozen category. However, overall values are smaller than mean for each category. This data point would correspond to small ice-cream parlor. \n\nSegment 1 cutomer has high values on dominating categories for first principal component in PCA. This customer has a high on Milk, Grocery and Detergent_Paper category. This customer probably is a restaurant.", "_____no_output_____" ], [ "### Question 9\n*For each sample point, which customer segment from* ***Question 8*** *best represents it? Are the predictions for each sample point consistent with this?*\n\nRun the code block below to find which cluster each sample point is predicted to be.", "_____no_output_____" ] ], [ [ "# Display the predictions\nfor i, pred in enumerate(sample_preds):\n print \"Sample point\", i, \"predicted to be in Cluster\", pred", "Sample point 0 predicted to be in Cluster 1\nSample point 1 predicted to be in Cluster 0\nSample point 2 predicted to be in Cluster 1\n" ] ], [ [ "**Answer:** The predictions for Sample point 0 and 2 are assigned to cluster 1. This indeed matches the prediction at the start of this assignment where these customers were predicted to be restaurant or caffe.\n\nThe prediction for sample point 1 is cluster 0 which I predicted to be small ice-cream parlor. However, at the start I predicted it to be a small grocery shop given high consumption of Fresh. However, the profile do match for this cluster 0 and this sample data point with high fresh and frozen components.", "_____no_output_____" ], [ "## Conclusion", "_____no_output_____" ], [ "In this final section, you will investigate ways that you can make use of the clustered data. First, you will consider how the different groups of customers, the ***customer segments***, may be affected differently by a specific delivery scheme. Next, you will consider how giving a label to each customer (which *segment* that customer belongs to) can provide for additional features about the customer data. Finally, you will compare the ***customer segments*** to a hidden variable present in the data, to see whether the clustering identified certain relationships.", "_____no_output_____" ], [ "### Question 10\nCompanies will often run [A/B tests](https://en.wikipedia.org/wiki/A/B_testing) when making small changes to their products or services to determine whether making that change will affect its customers positively or negatively. The wholesale distributor is considering changing its delivery service from currently 5 days a week to 3 days a week. However, the distributor will only make this change in delivery service for customers that react positively. *How can the wholesale distributor use the customer segments to determine which customers, if any, would react positively to the change in delivery service?* \n**Hint:** Can we assume the change affects all customers equally? How can we determine which group of customers it affects the most?", "_____no_output_____" ], [ "**Answer:** Based on the profile of each segment the change in delivery serive of different groups should affect differently. We can use A/B tests for each cluster to determine the results of changes in delivery service. \n\nFirst we choose a random sample from each of the cluster (treatment group) and use the remaining points in the cluster as control group. Then apply the changes in delivery services to the treatment group and can find if the customer segment will affect positively or negatively for the cluster. ", "_____no_output_____" ], [ "### Question 11\nAdditional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a ***customer segment*** it best identifies with (depending on the clustering algorithm applied), we can consider *'customer segment'* as an **engineered feature** for the data. Assume the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor wants to classify each new customer to a ***customer segment*** to determine the most appropriate delivery service. \n*How can the wholesale distributor label the new customers using only their estimated product spending and the* ***customer segment*** *data?* \n**Hint:** A supervised learner could be used to train on the original customers. What would be the target variable?", "_____no_output_____" ], [ "**Answer:** To know the customer segment of a new customer any supervised learning algo can be used (preferably with non-linear hidden variables) with cluster id as the target variable. \n\nAlso, the model learned while cluster creation can be used for predicting the customer segment. E.g. if K-means was used, the new customer can be assined a customer id based on distance of the customer attributes to the center of K-clusters. ", "_____no_output_____" ], [ "### Visualizing Underlying Distributions\n\nAt the beginning of this project, it was discussed that the `'Channel'` and `'Region'` features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the `'Channel'` feature to the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset.\n\nRun the code block below to see how each data point is labeled either `'HoReCa'` (Hotel/Restaurant/Cafe) or `'Retail'` the reduced space. In addition, you will find the sample points are circled in the plot, which will identify their labeling.", "_____no_output_____" ] ], [ [ "# Display the clustering results based on 'Channel' data\nrs.channel_results(reduced_data, outliers, pca_samples)", "_____no_output_____" ] ], [ [ "### Question 12\n*How well does the clustering algorithm and number of clusters you've chosen compare to this underlying distribution of Hotel/Restaurant/Cafe customers to Retailer customers? Are there customer segments that would be classified as purely 'Retailers' or 'Hotels/Restaurants/Cafes' by this distribution? Would you consider these classifications as consistent with your previous definition of the customer segments?*", "_____no_output_____" ], [ "**Answer:** The above plot shows the clusters which matches quite well with the number of clusters identified earlier in the analysis. Also the distibution of clusters matches a lot.\n\nOne observation here is, near the virtual boundary of clusters in my earlier analysis, there are quite a few customers which were not classified consistent to the above plot. One of the reason being, the clustering algorithm used (K-means) assign hard cluster to each point. However, assigning a probablilty (e.g. using EM algo) would have done more justice to such points. ", "_____no_output_____" ], [ "> **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
d03b447ccc1838a87b1a98ad1fe002074a0f6819
1,837
ipynb
Jupyter Notebook
{{ cookiecutter.repo_name }}/notebooks/1.0-{{cookiecutter.author_name}}-dvc-pipeline.ipynb
vasinkd/cookiecutter-data-science
3b1be4b701198b73e9701af498381a2c55da9fe6
[ "MIT" ]
2
2020-03-26T22:06:11.000Z
2021-04-02T08:52:38.000Z
{{ cookiecutter.repo_name }}/notebooks/1.0-{{cookiecutter.author_name}}-dvc-pipeline.ipynb
vasinkd/cookiecutter-data-science
3b1be4b701198b73e9701af498381a2c55da9fe6
[ "MIT" ]
1
2019-10-19T13:36:33.000Z
2019-10-19T13:36:33.000Z
{{ cookiecutter.repo_name }}/notebooks/1.0-{{cookiecutter.author_name}}-dvc-pipeline.ipynb
vasinkd/cookiecutter-data-science
3b1be4b701198b73e9701af498381a2c55da9fe6
[ "MIT" ]
8
2019-10-17T20:32:07.000Z
2022-03-10T15:28:49.000Z
25.873239
90
0.483397
[ [ [ "import os\nimport subprocess\nfrom {{cookiecutter.repo_name}}.settings import cwd", "_____no_output_____" ], [ "PROJECT_NAME = os.path.basename(cwd)", "_____no_output_____" ], [ "def form_dvc_command(name, py_file, inps, outs=[],\n extra_deps=[], outs_persist=[]):\n res = (f\"dvc run --no-exec -w {cwd} -f {PROJECT_NAME}/pipelines/{name}.dvc\"\n f\" -d {py_file}\")\n res += \"\".join([\" -d \" + x for x in inps])\n res += \"\".join([\" -d \" + x for x in extra_deps])\n res += \"\".join([\" -o \" + x for x in outs])\n res += \"\".join([\" --outs-persist \" + x for x in outs_persist])\n res += f\" python {py_file}\"\n res += \" \" + \" \".join(inps)\n \n res += \" \" + \" \".join(outs_persist)\n res += \" \" + \" \".join(outs)\n return res.strip()\n \ndef execute_dvc_command(command_string):\n subprocess.check_output(f\"cd {cwd}; {command_string}\", shell=True)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
d03b5b82f039a2e19f726d795e1239c329d6aa0f
289,414
ipynb
Jupyter Notebook
Mydecolor.ipynb
gkgsd/Decolorization
815085f7635a0b2018be7f6ecc7bb663cc5e13ca
[ "Apache-2.0" ]
null
null
null
Mydecolor.ipynb
gkgsd/Decolorization
815085f7635a0b2018be7f6ecc7bb663cc5e13ca
[ "Apache-2.0" ]
null
null
null
Mydecolor.ipynb
gkgsd/Decolorization
815085f7635a0b2018be7f6ecc7bb663cc5e13ca
[ "Apache-2.0" ]
null
null
null
431.317437
258,634
0.912323
[ [ [ "from __future__ import division\nimport theano\nimport theano.tensor as T\nimport theano.tensor.signal.conv\nimport numpy as np\nimport cv2, scipy, time, os\nfrom tqdm import tqdm\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom my_utils import Progbar\nfrom skimage import measure\nimport matlab_wrapper", "_____no_output_____" ], [ "###################\n#### required functions\n###################\ndef floatX(X):\n return np.asarray(X, dtype=theano.config.floatX)\n\n## for computing loss of one step\ndef onepari(grayv_i, l_i, a_i, b_i, R_i, G_i, B_i, x_i, y_i, n_i, grayv, l, a, b, R, G, B, x, y, n, width, height, alpha, beta, gamma):\n ## non-linearity of the color contrast\n l_delta = alpha[0]*(l_i - l)\n a_delta = alpha[1]*(a_i - a)\n b_delta = alpha[2]*(b_i - b)\n# s_delta = (alpha[0] * T.abs_(l_delta) + alpha[1] * T.abs_(a_delta) + alpha[2]*T.abs_(b_delta))/(sum(alpha))\n s_delta = T.sqrt(T.sqr(l_delta) + T.sqr(a_delta) + T.sqr(b_delta)) # here can be nonlinearity, can separate l,a,b channels\n\n ## non-linearity of gray_delta \n# g_delta = 1 / np.log(1/beta + 1) / (grayv + beta) * (grayv_i - grayv)\n g_delta = beta / (grayv + beta) * (grayv_i - grayv) # beta controls the nonlinearity of grayv\n# g_delta = grayv_i - grayv\n\n ## assign sign flag to the g_delta\n R_delta = R_i - R\n G_delta = G_i - G\n B_delta = B_i - B \n flag = 1 * T.and_(T.and_(T.gt(R_delta, 0),T.gt(G_delta,0)),T.gt(B_delta,0)) + (-1)*T.and_(T.and_(T.lt(R_delta, 0),T.lt(G_delta,0)),T.lt(B_delta,0)) \n g_delta_flag = T.switch(T.eq(flag, 0), T.abs_(g_delta), flag*g_delta)\n\n ## non-linearity of the region importance weight\n w_i = n_i * n / T.sqr(0.01 * width * height)\n# w_i = T.log(n_i * n / T.sqr(0.01 * n_sum)) # nonlinear version of the weight\n# w_i = w_i * T.gt(w_i,0)\n \n ## the non-linear distance weight\n dist = gamma * (T.sqr(x_i - x) + T.sqr(y_i - y))\n diag = (T.sqr(width) + T.sqr(height))\n w_dist = T.exp(-dist/diag)\n \n ## final contrast loss\n# loss =T.sum(w_dist * w_i * T.sqr(g_delta_flag - s_delta)) \n loss =T.sum(w_dist * w_i * T.sqr(g_delta_flag - s_delta)) \n\n return loss\n\n## build up the loss function\ndef buildloss(alpha,beta,gamma):\n w = []\n for i in range(9):\n if i < 3:\n w.append(theano.shared(floatX(1/3)))\n else:\n w.append(theano.shared(floatX(0)))\n lr = theano.shared(floatX(0.01))\n \n R = T.fvector('R')\n G = T.fvector('G')\n B = T.fvector('B')\n l = T.fvector('l')\n a = T.fvector('a')\n b = T.fvector('b')\n x = T.fvector('x')\n y = T.fvector('y')\n n = T.fvector('n')\n width = T.fscalar('width')\n height = T.fscalar('height')\n \n grayv = w[0] * R + w[1] * G + w[2]*B + w[3] *R*G + w[4]*G*B + w[5]*B*R + w[6]*(T.sqr(R)) + w[7]*(T.sqr(G)) +w[8]*(T.sqr(B)) \n \n loss_c, updates = theano.scan(fn=onepari,\n outputs_info=None,\n sequences=[grayv, l, a, b, R, G, B, x, y, n],\n non_sequences=[grayv, l, a, b, R, G, B, x, y, n, width, height, alpha, beta, gamma])\n \n loss_contrast = T.sum(loss_c)/2\n loss_contrast = loss_contrast \n# loss_contrast = loss_contrast + T.sum(1e5 * T.gt(grayv,1)*(grayv-1) + 1e5 * T.lt(grayv,0)*(0 - grayv))\n \n w_update, m_previous, v_previous, t = Adam(loss_contrast,w,learning_rate=lr)\n outputs = []\n outputs.append(loss_contrast)\n \n func = theano.function([R,G,B,l,a,b,x,y,n,width,height],outputs=outputs,updates=w_update)\n return func,w,lr,m_previous,v_previous, t\n\ndef Adam(loss, all_params, learning_rate=0.001, b1=0.9, b2=0.999, e=1e-8,\n gamma=1-1e-8):\n \"\"\"\n ADAM update rules\n Default values are taken from [Kingma2014]\n References:\n [Kingma2014] Kingma, Diederik, and Jimmy Ba.\n \"Adam: A Method for Stochastic Optimization.\"\n arXiv preprint arXiv:1412.6980 (2014).\n http://arxiv.org/pdf/1412.6980v4.pdf\n \"\"\"\n updates = []\n all_grads = theano.grad(loss, all_params)\n alpha = learning_rate\n t = theano.shared(np.float32(1))\n b1_t = b1*gamma**(t-1) #(Decay the first moment running average coefficient)\n \n m_previous_v = []\n v_previous_v = []\n for theta_previous, g in zip(all_params, all_grads):\n m_previous = theano.shared(np.zeros(theta_previous.get_value().shape,\n dtype=theano.config.floatX))\n v_previous = theano.shared(np.zeros(theta_previous.get_value().shape,\n dtype=theano.config.floatX))\n\n m = b1_t*m_previous + (1 - b1_t)*g # (Update biased first moment estimate)\n v = b2*v_previous + (1 - b2)*g**2 # (Update biased second raw moment estimate)\n m_hat = m / (1-b1**t) # (Compute bias-corrected first moment estimate)\n v_hat = v / (1-b2**t) # (Compute bias-corrected second raw moment estimate)\n theta = theta_previous - (alpha * m_hat) / (T.sqrt(v_hat) + e) #(Update parameters)\n\n updates.append((m_previous, m))\n updates.append((v_previous, v))\n updates.append((theta_previous, theta) )\n \n m_previous_v.append(m_previous)\n v_previous_v.append(v_previous)\n updates.append((t, t + 1.))\n return updates, m_previous_v,v_previous_v,t\n ", "_____no_output_____" ], [ "def color2gray(path_images, img_name,lr_init=1,n_iter=1000):\n \n ## load the images\n img = cv2.imread(path_images + img_name)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n lab_img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)\n\n R_img = img[:,:,0].astype(np.float32) / 255\n G_img = img[:,:,1].astype(np.float32) / 255\n B_img = img[:,:,2].astype(np.float32) /255\n\n l_img = (lab_img[:,:,0]).astype(np.float32) / 255 \n a_img = (lab_img[:,:,1]).astype(np.float32) / 255\n b_img = (lab_img[:,:,2]).astype(np.float32) / 255\n\n sz = img.shape\n n_p = sz[0] * sz[1]\n# print sz, n_p\n \n ## automatically determine the numner of clusters\n matlab.put('filename', path_images + img_name)\n matlab.put('cdist', 30)\n matlab.put('minsize', 20)\n matlab.eval('findkmeans')\n numklabels = matlab.get('numklabels')\n klabels = matlab.get('klabels')\n numclabels = matlab.get('numclabels')\n clabels = matlab.get('clabels')\n# print 'number of k clusters: ', numklabels\n# print 'number of c clusters: ', numclabels\n# klabels = clabels\n# numklabels = numclabels\n \n ## build the statistics \n grid = np.indices((sz[0], sz[1]),dtype=np.float32)\n xgrid = grid[0]\n ygrid = grid[1]\n n_pixels = np.zeros((numklabels,)).astype(np.float32)\n R_ini = np.zeros((numklabels,)).astype(np.float32)\n G_ini = np.zeros((numklabels,)).astype(np.float32)\n B_ini = np.zeros((numklabels,)).astype(np.float32)\n l_ini = np.zeros((numklabels,)).astype(np.float32)\n a_ini = np.zeros((numklabels,)).astype(np.float32)\n b_ini = np.zeros((numklabels,)).astype(np.float32)\n x_ini = np.zeros((numklabels,)).astype(np.float32)\n y_ini = np.zeros((numklabels,)).astype(np.float32)\n\n for i in range(numklabels):\n n_pixels[i] = np.sum(klabels==i)\n R_ini[i] = np.sum(R_img * (klabels == i))/n_pixels[i]\n G_ini[i] = np.sum(G_img * (klabels == i))/n_pixels[i]\n B_ini[i] = np.sum(B_img * (klabels == i))/n_pixels[i]\n\n l_ini[i] = np.sum(l_img * (klabels == i))/n_pixels[i]\n a_ini[i] = np.sum(a_img * (klabels == i))/n_pixels[i]\n b_ini[i] = np.sum(b_img * (klabels == i))/n_pixels[i]\n \n x_ini[i] = np.sum(xgrid * (klabels == i))/n_pixels[i]\n y_ini[i] = np.sum(ygrid * (klabels == i))/n_pixels[i]\n # w_all = ((n_pixels.sum()**2 - n_pixels.dot(n_pixels)) / 2).astype(np.float32)\n\n ## compute the adjacency matrix between colors\n # w_ij = np.zeros((numklabels,numklabels)).astype(np.float32)\n # for i in range(sz[0]-1):\n # for j in range(sz[1]-1):\n # w_ij[klabels[i,j],klabels[i+1,j]] = w_ij[klabels[i,j],klabels[i+1,j]] + 1\n # w_ij[klabels[i,j],klabels[i,j+1]] = w_ij[klabels[i,j],klabels[i,j+1]] + 1\n # np.fill_diagonal(w_ij,0)\n # w_ij = w_ij + w_ij.T \n # w_ij = (w_ij.T / np.sum(w_ij,axis=1)).T\n \n ## draw the clustering results\n# fig = plt.figure(figsize=(20, 4))\n# ax = fig.add_subplot(141)\n# ax.imshow(img)\n# ax.set_title('ori')\n# ax.axis('off')\n\n# ax = fig.add_subplot(142)\n# ax.imshow(klabels,cmap='gray')\n# ax.set_title('clusters')\n# ax.axis('off')\n \n# g_ini = np.copy(l_ini)\n# imgg_ini = draw_gray(klabels,g_ini,mask)\n\n# ax = fig.add_subplot(143)\n# ax.imshow(imgg_ini,cmap='gray')\n# ax.set_title('initial')\n# ax.axis('off')\n\n# imgc_ini = draw_color(klabels,img,mask)\n# ax = fig.add_subplot(144)\n# ax.imshow(imgc_ini.astype(np.uint8),vmin=0,vmax=255)\n# ax.set_title('initial')\n# ax.axis('off')\n\n# plt.show()\n \n ## perform the decolorization optimization\n #### initialize the parameters, the learning rate and the shared variable for Adam\n for i in range(9):\n if i < 3:\n w[i].set_value(floatX(1/3))\n else:\n w[i].set_value(floatX(0))\n wv = [i.get_value() for i in w]\n# print wv\n\n lr.set_value(lr_init) \n# print lr.get_value()\n\n for i in range(9):\n m_previous[i].set_value(floatX(0))\n v_previous[i].set_value(floatX(0))\n t.set_value(floatX(1))\n m_previous_vtemp = [i.get_value() for i in m_previous]\n v_previous_vtemp = [i.get_value() for i in v_previous]\n# print m_previous_vtemp\n# print v_previous_vtemp\n# print t.get_value()\n \n ## perform the optimization\n# progbar = Progbar(n_iter,verbose=1)\n for i in range(n_iter):\n loss = func(R_ini,G_ini,B_ini,l_ini,a_ini,b_ini,x_ini,y_ini,n_pixels,sz[0],sz[1])\n# progbar.add(1., values=[(\"train loss\", loss[0]),])\n \n wv = [i.get_value() for i in w]\n# print wv\n\n ## draw the decolorization results\n img_g = wv[0] * R_img + wv[1] * G_img + wv[2]*B_img + wv[3] *R_img*G_img + wv[4]*G_img*B_img + wv[5]*B_img*R_img + wv[6]*(R_img**2) + wv[7]*(G_img**2) +wv[8]*(B_img**2)\n \n return img_g", "_____no_output_____" ], [ "def scan_parameters():\n for lr_init in [0.1,0.01,0.001,1]:\n for alpha in [[1,1,1],[2,1,1],[3,1,1],[1,2,2],[1,3,3]]:\n for beta in [2,1,0.5,0.1]:\n for gamma in [10,5,1,0.5,0.1]:\n yield (lr_init,alpha,beta,gamma)", "_____no_output_____" ], [ "###########\n## Build up the theano function and the matlab session\n###########\nfunc,w,lr,m_previous,v_previous, t = buildloss([2,1,1],2,0)\nmatlab = matlab_wrapper.MatlabSession()", "_____no_output_____" ], [ "## process all images in the folder\ntest_idx = '1'\n# path_base = '/data/bjin/MyDecolor/dataset/Cadik/'\npath_base = '/data/bjin/MyDecolor/dataset/CSDD_Dataset/'\npath_images = path_base + 'images/'\npath_results_CIEL = path_base + 'CIEL/'\npath_results_mine = path_base + 'mine/test' + test_idx + '/'\npath_results_2012Lu = path_base + '2012_Lu/'\npath_results_2013Song = path_base + '2013_Song/'\npath_results_2015Du = path_base + '2015_Du/'\npath_results_2015Liu = path_base + '2015_Liu/'\n\nlr_init = 0.0005\nn_iter = 1000\n\nif not os.path.isdir(path_results_mine):\n os.mkdir(path_results_mine)\nfiles = os.listdir(path_images)\nfiles.sort()\nn_files = len(files)\n\nfor i in tqdm(range(n_files)):\n img_name = files[i]\n if img_name[0] is '.':\n continue\n# print '************processing : ' + img_name + '************'\n \n try: \n img_g = color2gray(path_images, img_name,lr_init=lr_init,n_iter=n_iter)\n except:\n matlab = matlab_wrapper.MatlabSession()\n img_g = color2gray(path_images, img_name,lr_init=lr_init,n_iter=n_iter)\n img_g = (img_g - np.min(img_g))/(np.max(img_g) - np.min(img_g))\n \n ## plot the respective results\n# fig = plt.figure(figsize=(20, 4))\n \n# ax = fig.add_subplot(161)\n# img = cv2.imread(path_images + img_name)\n# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n# ax.imshow(img)\n# ax.set_title('ori')\n# ax.axis('off')\n\n# ax = fig.add_subplot(162)\n# img_2012Lu = cv2.imread(path_results_2012Lu + img_name)\n# ax.imshow(img_2012Lu,cmap='gray')\n# ax.set_title('2012 Lu')\n# ax.axis('off')\n\n# ax = fig.add_subplot(163)\n# img_2013Song = cv2.imread(path_results_2013Song + img_name)\n# ax.imshow(img_2013Song,cmap='gray')\n# ax.set_title('2013 Song')\n# ax.axis('off')\n\n# ax = fig.add_subplot(164)\n# img_2015Du = cv2.imread(path_results_2015Du + img_name)\n# ax.imshow(img_2015Du,cmap='gray')\n# ax.set_title('2015 Du')\n# ax.axis('off')\n \n# ax = fig.add_subplot(165)\n# # img_2015Liu = cv2.imread(path_results_2015Liu + img_name)\n# img_2015Liu = cv2.imread(path_results_CIEL + img_name)\n# ax.imshow(img_2015Liu,cmap='gray')\n# ax.set_title('CIEL')\n# ax.axis('off')\n \n# ax = fig.add_subplot(166)\n# ax.imshow(img_g,cmap='gray')\n# ax.set_title('mine')\n# ax.axis('off')\n# plt.show()\n \n cv2.imwrite(path_results_mine+img_name,(img_g*255).astype(np.uint8))\n", "100%|██████████| 22/22 [04:56<00:00, 11.81s/it]\n" ], [ "## evaluation \nmatlab = matlab_wrapper.MatlabSession()\n\nmatlab.put('thrNum', 15)\nmatlab.put('imNum', 24)\nmatlab.put('path_base', path_base)\nmatlab.put('path_results_mine', path_results_mine)\nmatlab.eval('Computemetrics')\nCCPR = matlab.get('CCPR')\nCCFR = matlab.get('CCFR')\nEscore = matlab.get('Escore')\nprint 'mine ' + '2012 Lu ' + '2013 Song ' + '2015 Du ' + '2015 Liu '\nprint CCPR", "mine 2012 Lu 2013 Song 2015 Du 2015 Liu \n[[ 0.96687234 0.94424905 0.92637764 0.90814634 0.8927261 0.87810178\n 0.86465649 0.85189774 0.84022119 0.82805622 0.81443342 0.79490558\n 0.77745956 0.76415904 0.75002881]\n [ 0.96647499 0.943362 0.92438165 0.90832196 0.89240099 0.87600867\n 0.86065135 0.84769524 0.83398591 0.82086553 0.80853186 0.79455791\n 0.7800474 0.7683703 0.75632736]\n [ 0.96468308 0.94235473 0.92392849 0.90772873 0.89127698 0.87273702\n 0.85701841 0.84313244 0.82787204 0.81122785 0.79577293 0.77901298\n 0.7646607 0.75282297 0.73944256]\n [ 0.96653885 0.94655042 0.92779111 0.91395931 0.90373507 0.88964025\n 0.87820621 0.86623599 0.85557556 0.84038493 0.82719286 0.81328721\n 0.80215019 0.7912512 0.78017817]\n [ 0.96346652 0.94335057 0.92761983 0.91280393 0.89997155 0.88499926\n 0.87381952 0.8636342 0.85289508 0.84064619 0.82995565 0.8191374\n 0.80884081 0.79928789 0.78834464]]\n" ], [ "path_base = '/data/bjin/MyDecolor/dataset/CSDD_Dataset/'\npath_images = path_base + 'images/'\nimg_name = '8.png'\nimg_g = color2gray(path_images, img_name,lr_init=0.0005,n_iter=2000)\n\n\nfig = plt.figure(figsize=(20, 4))\n \nax = fig.add_subplot(121)\nimg = cv2.imread(path_images + img_name)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nax.imshow(img)\nax.set_title('ori')\nax.axis('off')\n\nax = fig.add_subplot(122)\nax.imshow(img_g,cmap='gray')\nax.set_title('mine')\nax.axis('off')\n\nplt.show()", "_____no_output_____" ], [ "###########\n## Main functions \n###########\ntest_idx = '3'\npath_base = '/data/bjin/MyDecolor/dataset/Cadik/'\npath_images = path_base + 'images/'\npath_results_mine = path_base + 'mine/test' + test_idx + '/'\npath_results_2012Lu = path_base + '2012_Lu/'\npath_results_2013Song = path_base + '2013_Song/'\npath_results_2015Du = path_base + '2015_Du/'\npath_results_2015Liu = path_base + '2015_Liu/'\n\nlr_init = 0.1\nn_iter = 1000\n\nfptr = open(path_base + 'logs/Decolor_test' + test_idx + '.txt','w+')\nprint 'writing logs to ' + path_base + 'logs/Decolor_test' + test_idx\n\nif not os.path.isdir(path_results_mine):\n os.mkdir(path_results_mine)\nfiles = os.listdir(path_images)\nfiles.sort()\nn_files = len(files)\n\nfor (alpha,beta,gamma) in scan_parameters():\n print alpha, beta, gamma\n print >>fptr, '*'*20\n print >>fptr, alpha, beta\n\n func,w,lr,m_previous,v_previous,t = buildloss(alpha,beta,gamma)\n matlab = matlab_wrapper.MatlabSession()\n\n ## generate the gray scale images\n for img_name in files:\n if img_name[0] is '.':\n continue\n print '----------processing: ' + img_name + '---------'\n try: \n img_g = color2gray(path_images, img_name,lr_init=lr_init,n_iter=n_iter)\n except:\n matlab = matlab_wrapper.MatlabSession()\n img_g = color2gray(path_images, img_name,lr_init=lr_init,n_iter=n_iter)\n img_g = (img_g - np.min(img_g))/(np.max(img_g) - np.min(img_g))\n cv2.imwrite(path_results_mine+img_name,(img_g*255).astype(np.uint8))\n\n ## evaluation\n matlab = matlab_wrapper.MatlabSession()\n\n matlab.put('thrNum', 15)\n matlab.put('imNum', 24)\n matlab.put('path_base', path_base)\n matlab.put('path_results_mine', path_results_mine)\n matlab.eval('Computemetrics')\n CCPR = matlab.get('CCPR')\n CCFR = matlab.get('CCFR')\n Escore = matlab.get('Escore')\n print 'mine ' + '2012 Lu ' + '2013 Song ' + '2015 Du ' + '2015 Liu '\n print CCPR\n print >>fptr, 'CCPR'\n print >>fptr, CCPR\n print >>fptr, 'CCFR'\n print >>fptr, CCFR\n print >>fptr, 'Escore'\n print >>fptr, Escore\n print >>fptr, '*'*20\n fptr.flush()\n os.fsync(fptr.fileno())\n\nfptr.close()", "writing logs to /data/bjin/MyDecolor/dataset/Cadik/logs/Decolor_test3\n[0.5, 0.5, 0.5] 1 1\n----------processing: 1.png---------\n(293, 390, 3) 114270\nnumber of k clusters: 17\nnumber of c clusters: 182\n1000/1000 [==============================] - 25s - train loss: 11.0473 \n----------processing: 10.png---------\n(390, 390, 3) 152100\nnumber of k clusters: 12\nnumber of c clusters: 198\n 546/1000 [===============>..............] - ETA: 12s - train loss: 4.6586" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03b744ea56a679e7e7efdef77fd9477e8cf5b78
71,513
ipynb
Jupyter Notebook
Code/001-make-training-data.ipynb
Aglinskas/BC-MRI-ADHD
fc4b81d7fc43af6617cf0f68fc0c99089693e22c
[ "MIT" ]
null
null
null
Code/001-make-training-data.ipynb
Aglinskas/BC-MRI-ADHD
fc4b81d7fc43af6617cf0f68fc0c99089693e22c
[ "MIT" ]
null
null
null
Code/001-make-training-data.ipynb
Aglinskas/BC-MRI-ADHD
fc4b81d7fc43af6617cf0f68fc0c99089693e22c
[ "MIT" ]
null
null
null
61.70233
36,544
0.646302
[ [ [ "pwd", "_____no_output_____" ], [ "import ants\nimport os \nimport pandas as pd\nimport numpy as np\n\nfrom matplotlib import pyplot as plt", "_____no_output_____" ], [ "df = pd.read_csv('../Data/df_all2.csv')\ndf", "_____no_output_____" ], [ "brain_dir = '../../Extracted_Brains/'\nfiles = [f for f in os.listdir(brain_dir) if f.endswith('.nii.gz')]\nfiles.sort()\nprint(len(files))\nfiles[0:5]", "596\n" ], [ "fn_temp = '../../Extracted_Brains/{sub}_Extracted_Brain.nii.gz'", "_____no_output_____" ], [ "df['has_brain'] = [os.path.exists(fn_temp.format(sub=val)) for val in df['subID'].values]", "_____no_output_____" ], [ "#df.iloc[np.isnan(pd.to_numeric(brain_df['DX'],errors='coerce').values)]", "_____no_output_____" ], [ "brain_df = df.iloc[df['has_brain'].values]\nbrain_df = brain_df.iloc[brain_df['DX'].values!='pending']\nbrain_df['DX'] = pd.to_numeric(brain_df['DX'])\nbrain_df.to_csv('../Data/brain_df_S466.csv')\nbrain_df", "_____no_output_____" ], [ "def norm(mat):\n return (mat - mat.min()) / (mat.max()-mat.min())", "_____no_output_____" ], [ "%%time\nim_arr = [ants.image_read(fn_temp.format(sub=val)).numpy() for val in brain_df['subID'].values]\nim_arr = np.array(im_arr)\nim_arr = np.array([norm(im_arr[i,:,:,:]) for i in range(im_arr.shape[0])])\nim_arr.shape", "CPU times: user 2.96 s, sys: 1.06 s, total: 4.03 s\nWall time: 6.42 s\n" ], [ "#im_arr = im_arr.astype('float16')\nplt.figure(figsize=(15,5))\nplt.subplot(1,3,1)\nplt.imshow(im_arr[0,:,:,32])\n\nplt.subplot(1,3,2)\nplt.imshow(im_arr[233,:,:,32])\n\nplt.subplot(1,3,3)\nplt.imshow(im_arr[-1,:,:,32])", "_____no_output_____" ], [ "controls = brain_df['DX'].values==0\npatients = brain_df['DX'].values!=0", "_____no_output_____" ], [ "np.savez_compressed(file='../Assets/brain_array-440.npz',data=im_arr,controls=controls,patients=patients)", "_____no_output_____" ], [ "list(np.load('../Assets/brain_array-440.npz').keys())", "_____no_output_____" ], [ "# def pad_subID(val):\n# if np.isnan(val):\n# val_str = val\n# else:\n# val_str = str(int(val))\n# if len(val_str)==5:\n# val_str = 'sub-00'+val_str\n \n# if len(val_str)==7:\n# val_str = 'sub-'+val_str\n\n# return val_str\n\n# df['subID'] = [pad_subID(val) for val in df['ScanDir ID'].values]\n# df.to_csv('../Data/df_all2.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03b89683fb696eae64f6b18ffcd17e722bdff54
137,003
ipynb
Jupyter Notebook
ipython_examples/Simple Oscillator.ipynb
tinosulzer/odes
858df720cc13c3ce59a358659626cfe8a9937286
[ "BSD-3-Clause" ]
95
2015-02-12T15:33:24.000Z
2022-03-07T12:57:46.000Z
ipython_examples/Simple Oscillator.ipynb
tinosulzer/odes
858df720cc13c3ce59a358659626cfe8a9937286
[ "BSD-3-Clause" ]
89
2015-01-22T12:42:26.000Z
2022-01-09T17:02:49.000Z
ipython_examples/Simple Oscillator.ipynb
tinosulzer/odes
858df720cc13c3ce59a358659626cfe8a9937286
[ "BSD-3-Clause" ]
29
2015-01-30T09:20:56.000Z
2022-02-23T03:50:15.000Z
264.484556
40,418
0.89998
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "# Simple Oscillator Example\n\nThis example shows the most simple way of using a solver.\nWe solve free vibration of a simple oscillator:\n$$m \\ddot{u} + k u = 0,\\quad u(0) = u_0,\\quad \\dot{u}(0) = \\dot{u}_0$$\nusing the CVODE solver. An analytical solution exists, given by\n$$u(t) = u_0 \\cos\\left(\\sqrt{\\frac{k}{m}} t\\right)+\\frac{\\dot{u}_0}{\\sqrt{\\frac{k}{m}}} \\sin\\left(\\sqrt{\\frac{k}{m}} t\\right)$$", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scikits.odes import ode", "_____no_output_____" ], [ "#data of the oscillator\nk = 4.0\nm = 1.0\n#initial position and speed data on t=0, x[0] = u, x[1] = \\dot{u}, xp = \\dot{x}\ninitx = [1, 0.1]", "_____no_output_____" ] ], [ [ "We need a first order system, so convert the second order system \n$$m \\ddot{u} + k u = 0,\\quad u(0) = u_0,\\quad \\dot{u}(0) = \\dot{u}_0$$\ninto \n$$\\left\\{ \\begin{array}{l}\n \\dot u = v\\\\\n \\dot v = \\ddot u = -\\frac{ku}{m}\n\\end{array} \\right.$$\nYou need to define a function that computes the right hand side of above equation:", "_____no_output_____" ] ], [ [ "def rhseqn(t, x, xdot):\n \"\"\" we create rhs equations for the problem\"\"\"\n xdot[0] = x[1]\n xdot[1] = - k/m * x[0]", "_____no_output_____" ] ], [ [ "To solve the ODE you define an ode object, specify the solver to use, here cvode, and pass the right hand side function. You request the solution at specific timepoints by passing an array of times to the solve member.", "_____no_output_____" ] ], [ [ "solver = ode('cvode', rhseqn, old_api=False)\nsolution = solver.solve([0., 1., 2.], initx)", "_____no_output_____" ], [ "print('\\n t Solution Exact')\nprint('------------------------------------')\nfor t, u in zip(solution.values.t, solution.values.y):\n print('{0:>4.0f} {1:15.6g} {2:15.6g}'.format(t, u[0], \n initx[0]*np.cos(np.sqrt(k/m)*t)+initx[1]*np.sin(np.sqrt(k/m)*t)/np.sqrt(k/m)))\n", "\n t Solution Exact\n------------------------------------\n 0 1 1\n 1 -0.370694 -0.370682\n 2 -0.691508 -0.691484\n" ] ], [ [ "You can continue the solver by passing further times. Calling the solve routine reinits the solver, so you can restart at whatever time. To continue from the last computed solution, pass the last obtained time and solution. \n\n**Note:** The solver performes better if it can take into account history information, so avoid calling solve to continue computation!\n\nIn general, you must check for errors using the errors output of solve.", "_____no_output_____" ] ], [ [ "#Solve over the next hour by continuation\ntimes = np.linspace(0, 3600, 61)\ntimes[0] = solution.values.t[-1]\nsolution = solver.solve(times, solution.values.y[-1])\nif solution.errors.t:\n print ('Error: ', solution.message, 'Error at time', solution.errors.t)\nprint ('Computed Solutions:')\nprint('\\n t Solution Exact')\nprint('------------------------------------')\nfor t, u in zip(solution.values.t, solution.values.y):\n print('{0:>4.0f} {1:15.6g} {2:15.6g}'.format(t, u[0], \n initx[0]*np.cos(np.sqrt(k/m)*t)+initx[1]*np.sin(np.sqrt(k/m)*t)/np.sqrt(k/m)))\n", "Error: Could not reach endpoint Error at time 24.5780834078\nComputed Solutions:\n\n t Solution Exact\n------------------------------------\n 2 -0.691508 -0.691484\n" ] ], [ [ "The solution fails at a time around 24 seconds. Erros can be due to many things. Here however the reason is simple: we try to make too large jumps in time output. Increasing the allowed steps the solver can take will fix this. This is the **max_steps** option of cvode:", "_____no_output_____" ] ], [ [ "solver = ode('cvode', rhseqn, old_api=False, max_steps=5000)\nsolution = solver.solve(times, solution.values.y[-1])\nif solution.errors.t:\n print ('Error: ', solution.message, 'Error at time', solution.errors.t)\nprint ('Computed Solutions:')\nprint('\\n t Solution Exact')\nprint('------------------------------------')\nfor t, u in zip(solution.values.t, solution.values.y):\n print('{0:>4.0f} {1:15.6g} {2:15.6g}'.format(t, u[0], \n initx[0]*np.cos(np.sqrt(k/m)*t)+initx[1]*np.sin(np.sqrt(k/m)*t)/np.sqrt(k/m)))\n", "Computed Solutions:\n\n t Solution Exact\n------------------------------------\n 2 -0.691508 -0.691484\n 60 0.843074 0.843212\n 120 0.372884 0.373054\n 180 -0.235749 -0.235745\n 240 -0.756553 -0.756932\n 300 -0.996027 -0.996814\n 360 -0.865262 -0.866242\n 420 -0.412897 -0.413742\n 480 0.192583 0.192521\n 540 0.726263 0.727236\n 600 0.989879 0.991682\n 660 0.885441 0.887581\n 720 0.452113 0.453622\n 780 -0.149122 -0.148921\n 840 -0.694753 -0.696119\n 900 -0.981996 -0.984613\n 960 -0.904317 -0.907187\n1020 -0.490547 -0.492616\n1080 0.105433 0.10503\n1140 0.661996 0.663643\n1200 0.972376 0.97562\n1260 0.921229 0.925021\n1320 0.527762 0.530648\n1380 -0.0616772 -0.0609338\n1440 -0.627855 -0.62987\n1500 -0.960354 -0.964723\n1560 -0.935939 -0.941048\n1620 -0.563703 -0.567643\n1680 0.0179025 0.0167187\n1740 0.592593 0.594867\n1800 0.946886 0.951941\n1860 0.949087 0.955237\n1920 0.59865 0.60353\n1980 0.025868 0.0275291\n2040 -0.556352 -0.558703\n2100 -0.931643 -0.9373\n2160 -0.960605 -0.96756\n2220 -0.632579 -0.638239\n2280 -0.0695761 -0.0717232\n2340 0.51911 0.521447\n2400 0.914706 0.920828\n2460 0.97026 0.977994\n2520 0.66523 0.6717\n2580 0.113083 0.115777\n2640 -0.48092 -0.483173\n2700 -0.896022 -0.902558\n2760 -0.978027 -0.986518\n2820 -0.69649 -0.70385\n2880 -0.156248 -0.159605\n2940 0.441822 0.443956\n3000 0.875509 0.882526\n3060 0.983777 0.993115\n3120 0.72638 0.734626\n3180 0.199071 0.203121\n3240 -0.401994 -0.403871\n3300 -0.853534 -0.860769\n3360 -0.987807 -0.997773\n3420 -0.75483 -0.763966\n3480 -0.241495 -0.246241\n3540 0.361435 0.362997\n3600 0.82981 0.837332\n" ] ], [ [ "To plot the simple oscillator, we show a (t,x) plot of the solution. Doing this over 60 seconds can be done as follows:", "_____no_output_____" ] ], [ [ "#plot of the oscilator\nsolver = ode('cvode', rhseqn, old_api=False)\ntimes = np.linspace(0,60,600)\nsolution = solver.solve(times, initx)\nplt.plot(solution.values.t,[x[0] for x in solution.values.y])\nplt.xlabel('Time [s]')\nplt.ylabel('Position [m]')\nplt.show()", "_____no_output_____" ] ], [ [ "You can refine the tolerances from their defaults to obtain more accurate solutions", "_____no_output_____" ] ], [ [ "options1= {'rtol': 1e-6, 'atol': 1e-12, 'max_steps': 50000} # default rtol and atol\noptions2= {'rtol': 1e-15, 'atol': 1e-25, 'max_steps': 50000}\nsolver1 = ode('cvode', rhseqn, old_api=False, **options1)\nsolver2 = ode('cvode', rhseqn, old_api=False, **options2)\nsolution1 = solver1.solve([0., 1., 60], initx)\nsolution2 = solver2.solve([0., 1., 60], initx)\n\nprint('\\n t Solution1 Solution2 Exact')\nprint('-----------------------------------------------------')\nfor t, u1, u2 in zip(solution1.values.t, solution1.values.y, solution2.values.y):\n print('{0:>4.0f} {1:15.8g} {2:15.8g} {3:15.8g}'.format(t, u1[0], u2[0], \n initx[0]*np.cos(np.sqrt(k/m)*t)+initx[1]*np.sin(np.sqrt(k/m)*t)/np.sqrt(k/m)))", "\n t Solution1 Solution2 Exact\n-----------------------------------------------------\n 0 1 1 1\n 1 -0.37069371 -0.37068197 -0.37068197\n 60 0.8430298 0.84321153 0.84321153\n" ] ], [ [ "# Simple Oscillator Example: Stepwise running\nWhen using the *solve* method, you solve over a period of time you decided before. In some problems you might want to solve and decide on the output when to stop. Then you use the *step* method. The same example as above using the step method can be solved as follows. \n\nYou define the ode object selecting the cvode solver. You initialize the solver with the begin time and initial conditions using *init_step*. You compute solutions going forward with the *step* method.", "_____no_output_____" ] ], [ [ "solver = ode('cvode', rhseqn, old_api=False)\ntime = 0.\nsolver.init_step(time, initx)\nplott = []\nplotx = []\nwhile True:\n time += 0.1\n # fix roundoff error at end\n if time > 60: time = 60\n solution = solver.step(time)\n if solution.errors.t:\n print ('Error: ', solution.message, 'Error at time', solution.errors.t)\n break\n #we store output for plotting\n plott.append(solution.values.t)\n plotx.append(solution.values.y[0])\n if time >= 60:\n break\nplt.plot(plott,plotx)\nplt.xlabel('Time [s]')\nplt.ylabel('Position [m]')\nplt.show()", "_____no_output_____" ] ], [ [ "The solver interpolates solutions to return the solution at the required output times:", "_____no_output_____" ] ], [ [ "print ('plott length:', len(plott), ', last computation times:', plott[-15:]);", "plott length: 600 , last computation times: [58.60000000000056, 58.700000000000564, 58.800000000000566, 58.90000000000057, 59.00000000000057, 59.10000000000057, 59.20000000000057, 59.30000000000057, 59.400000000000574, 59.500000000000576, 59.60000000000058, 59.70000000000058, 59.80000000000058, 59.90000000000058, 60.0]\n" ] ], [ [ "# Simple Oscillator Example: Internal Solver Stepwise running\nWhen using the *solve* method, you solve over a period of time you decided before. With the *step* method you solve by default towards a desired output time after which you can continue solving the problem. \n\nFor full control, you can also compute problems using the solver internal steps. This is not advised, as the number of return steps can be very large, **slowing down** the computation enormously. If you want this nevertheless, you can achieve it with the *one_step_compute* option. Like this:", "_____no_output_____" ] ], [ [ "solver = ode('cvode', rhseqn, old_api=False, one_step_compute=True)\ntime = 0.\nsolver.init_step(time, initx)\nplott = []\nplotx = []\nwhile True:\n solution = solver.step(60)\n if solution.errors.t:\n print ('Error: ', solution.message, 'Error at time', solution.errors.t)\n break\n #we store output for plotting\n plott.append(solution.values.t)\n plotx.append(solution.values.y[0]) \n if solution.values.t >= 60:\n #back up to 60\n solver.set_options(one_step_compute=False)\n solution = solver.step(60)\n plott[-1] = solution.values.t\n plotx[-1] = solution.values.y[0]\n break\nplt.plot(plott,plotx)\nplt.xlabel('Time [s]')\nplt.ylabel('Position [m]')\nplt.show()", "_____no_output_____" ] ], [ [ "By inspection of the returned times you can see how efficient the solver can solve this problem:", "_____no_output_____" ] ], [ [ "print ('plott length:', len(plott), ', last computation times:', plott[-15:]);", "plott length: 1328 , last computation times: [59.2297953049153, 59.28543421477497, 59.34107312463465, 59.39671203449432, 59.452350944353995, 59.50798985421367, 59.56362876407334, 59.61926767393302, 59.67490658379269, 59.730545493652365, 59.78618440351204, 59.84182331337171, 59.897462223231386, 59.95310113309106, 60.0]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d03b9477ca31e288c3e5a05865cf0835172a9f14
7,234
ipynb
Jupyter Notebook
ML_Simplilearn/handwritten_datasets_NN/.ipynb_checkpoints/VisualizeDataAndRunMLP-checkpoint.ipynb
tanuja333/ML_Training
238f75829952ee2d107e927f5ff32a8f5ef4d4ef
[ "Apache-2.0" ]
1
2020-03-17T12:46:15.000Z
2020-03-17T12:46:15.000Z
ML_Simplilearn/handwritten_datasets_NN/.ipynb_checkpoints/VisualizeDataAndRunMLP-checkpoint.ipynb
tanuja333/ML_Training
238f75829952ee2d107e927f5ff32a8f5ef4d4ef
[ "Apache-2.0" ]
null
null
null
ML_Simplilearn/handwritten_datasets_NN/.ipynb_checkpoints/VisualizeDataAndRunMLP-checkpoint.ipynb
tanuja333/ML_Training
238f75829952ee2d107e927f5ff32a8f5ef4d4ef
[ "Apache-2.0" ]
null
null
null
26.021583
98
0.479403
[ [ [ "import classifierMLP as cmlp\n\nimport os\nimport struct\nimport numpy as np\n \ndef load_mnist(path, kind='train'):\n \"\"\"Load MNIST data from `path`\"\"\"\n labels_path = os.path.join(path, \n '%s-labels-idx1-ubyte' % kind)\n images_path = os.path.join(path, \n '%s-images-idx3-ubyte' % kind)\n print(labels_path)\n print(images_path)\n \n with open(labels_path, 'rb') as lbpath:\n magic, n = struct.unpack('>II', \n lbpath.read(8))\n labels = np.fromfile(lbpath, \n dtype=np.uint8)\n\n with open(images_path, 'rb') as imgpath:\n magic, num, rows, cols = struct.unpack(\">IIII\", \n imgpath.read(16))\n images = np.fromfile(imgpath, \n dtype=np.uint8).reshape(len(labels), 784)\n images = ((images / 255.) - .5) * 2\n \n return images, labels\n", "_____no_output_____" ], [ "# unzips mnist\n%matplotlib inline\nimport sys\nimport gzip\nimport shutil\n\nif (sys.version_info > (3, 0)):\n writemode = 'wb'\nelse:\n writemode = 'w'\n\nzipped_mnist = [f for f in os.listdir('./') if f.endswith('ubyte.gz')]\nfor z in zipped_mnist:\n with gzip.GzipFile(z, mode='rb') as decompressed, open(z[:-3], writemode) as outfile:\n outfile.write(decompressed.read()) \n \nX_train, y_train = load_mnist('', kind='train')\nprint('Rows: %d, columns: %d' % (X_train.shape[0], X_train.shape[1]))\n\nX_test, y_test = load_mnist('', kind='t10k')\nprint('Rows: %d, columns: %d' % (X_test.shape[0], X_test.shape[1]))", "train-labels-idx1-ubyte\ntrain-images-idx3-ubyte\nRows: 60000, columns: 784\nt10k-labels-idx1-ubyte\nt10k-images-idx3-ubyte\nRows: 10000, columns: 784\n" ], [ "X_train.shape", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True,)\nax = ax.flatten()\nfor i in range(10):\n img = X_train[y_train == i][0].reshape(28, 28)\n ax[i].imshow(img, cmap='Greys')\n\nax[0].set_xticks([])\nax[0].set_yticks([])\nplt.tight_layout()\n# plt.savefig('images/12_5.png', dpi=300)\nplt.show()\n\n", "_____no_output_____" ], [ "fig, ax = plt.subplots(nrows=7, ncols=12, sharex=True, sharey=True,)\nax = ax.flatten()\nfor i in range(84):\n img = X_train[y_train == 4][i].reshape(28, 28)\n ax[i].imshow(img, cmap='Greys')\n\nax[0].set_xticks([])\nax[0].set_yticks([])\nplt.tight_layout()\n# plt.savefig('images/12_6.png', dpi=300)\nplt.show()", "_____no_output_____" ], [ "import seaborn as sns\nsns.countplot(y_train)", "_____no_output_____" ], [ "n_epochs = 100\n\nnn = cmlp.SimpleMLP(n_hidden_units=100, \n l2=0.01, \n epochs=n_epochs, \n eta=0.0005,\n minibatch_size=100, \n shuffle=True,\n seed=1)\n\nnn.fit(X_train=X_train[:55000], \n y_train=y_train[:55000],\n X_valid=X_train[55000:],\n y_valid=y_train[55000:])\n\n", "_____no_output_____" ], [ "#playing with the traiued model\nfig, ax = plt.subplots(nrows=5, ncols=4, sharex=True, sharey=True,)\nax = ax.flatten()\nfor i in range(20):\n img = X_test[i].reshape(28, 28)\n ax[i].imshow(img, cmap='Greys')\n\nax[0].set_xticks([])\nax[0].set_yticks([])\nplt.tight_layout()\n# plt.savefig('images/12_6.png', dpi=300)\nplt.show()", "_____no_output_____" ], [ "#Lets test for X_test - 1 to 20\nfor i in range(20):\n print (\"Prediction for {}th image is {}\".format(i,\n nn.predict(X_test[i:i+1])))", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nplt.plot(range(nn.epochs), nn.eval_['cost'],color='green' ,\n label='training Error')\nplt.ylabel('Error')\nplt.xlabel('Epochs')\nplt.legend()", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nplt.plot(range(nn.epochs), nn.eval_['train_acc'],color='green' ,\n label='training')\nplt.plot(range(nn.epochs), nn.eval_['valid_acc'], color='red',\n label='validation', linestyle='--')\nplt.ylabel('Accuracy')\nplt.xlabel('Epochs')\nplt.legend()\n#plt.savefig('images/12_08.png', dpi=300)\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03ba4615c034bea086b21083ef855737eec7dc7
10,129
ipynb
Jupyter Notebook
Chapter10/siamese.ipynb
arifmudi/Advanced-Deep-Learning-with-Python
180cae0ec62857670bfc2a4d566857030adc4905
[ "MIT" ]
107
2019-12-09T13:49:33.000Z
2021-08-31T03:23:39.000Z
Chapter10/siamese.ipynb
bwantan/Advanced-Deep-Learning-with-Python
083f63dfc0c5f404143552ea20d560b06ec303f5
[ "MIT" ]
null
null
null
Chapter10/siamese.ipynb
bwantan/Advanced-Deep-Learning-with-Python
083f63dfc0c5f404143552ea20d560b06ec303f5
[ "MIT" ]
48
2019-12-05T05:30:51.000Z
2022-03-22T02:03:00.000Z
38.367424
195
0.539737
[ [ [ "# Siamese networks with TensorFlow 2.0/Keras\n\nIn this example, we'll implement a simple siamese network system, which verifyies whether a pair of MNIST images is of the same class (true) or not (false). \n\n_This example is partially based on_ [https://github.com/keras-team/keras/blob/master/examples/mnist_siamese.py](https://github.com/keras-team/keras/blob/master/examples/mnist_siamese.py)\n", "_____no_output_____" ], [ "Let's start with the imports", "_____no_output_____" ] ], [ [ "import random\n\nimport numpy as np\nimport tensorflow as tf", "_____no_output_____" ] ], [ [ "We'll continue with the `create_pairs` function, which creates a training dataset of equal number of true/false pairs of each MNIST class.", "_____no_output_____" ] ], [ [ "def create_pairs(inputs: np.ndarray, labels: np.ndarray):\n \"\"\"Create equal number of true/false pairs of samples\"\"\"\n\n num_classes = 10\n\n digit_indices = [np.where(labels == i)[0] for i in range(num_classes)]\n pairs = list()\n labels = list()\n n = min([len(digit_indices[d]) for d in range(num_classes)]) - 1\n for d in range(num_classes):\n for i in range(n):\n z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]\n pairs += [[inputs[z1], inputs[z2]]]\n inc = random.randrange(1, num_classes)\n dn = (d + inc) % num_classes\n z1, z2 = digit_indices[d][i], digit_indices[dn][i]\n pairs += [[inputs[z1], inputs[z2]]]\n labels += [1, 0]\n return np.array(pairs), np.array(labels, dtype=np.float32)", "_____no_output_____" ] ], [ [ "Next, we'll define the base network of the siamese system:", "_____no_output_____" ] ], [ [ "def create_base_network():\n \"\"\"The shared encoding part of the siamese network\"\"\"\n\n return tf.keras.models.Sequential([\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.1),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.1),\n tf.keras.layers.Dense(64, activation='relu'),\n ])", "_____no_output_____" ] ], [ [ "Next, let's load the regular MNIST training and validation sets and create true/false pairs out of them:", "_____no_output_____" ] ], [ [ "# Load the train and test MNIST datasets\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\nx_train = x_train.astype(np.float32)\nx_test = x_test.astype(np.float32)\nx_train /= 255\nx_test /= 255\ninput_shape = x_train.shape[1:]\n\n# Create true/false training and testing pairs\ntrain_pairs, tr_labels = create_pairs(x_train, y_train)\ntest_pairs, test_labels = create_pairs(x_test, y_test)", "_____no_output_____" ] ], [ [ "Then, we'll build the siamese system, which includes the `base_network`, the 2 siamese paths `encoder_a` and `encoder_b`, the `l1_dist` measure, and the combined `model`:", "_____no_output_____" ] ], [ [ "# Create the siamese network\n# Start from the shared layers\nbase_network = create_base_network()\n\n# Create first half of the siamese system\ninput_a = tf.keras.layers.Input(shape=input_shape)\n\n# Note how we reuse the base_network in both halfs\nencoder_a = base_network(input_a)\n\n# Create the second half of the siamese system\ninput_b = tf.keras.layers.Input(shape=input_shape)\nencoder_b = base_network(input_b)\n\n# Create the the distance measure\nl1_dist = tf.keras.layers.Lambda(\n lambda embeddings: tf.keras.backend.abs(embeddings[0] - embeddings[1])) \\\n ([encoder_a, encoder_b])\n\n# Final fc layer with a single logistic output for the binary classification\nflattened_weighted_distance = tf.keras.layers.Dense(1, activation='sigmoid') \\\n (l1_dist)\n\n# Build the model\nmodel = tf.keras.models.Model([input_a, input_b], flattened_weighted_distance)", "_____no_output_____" ] ], [ [ "Finally, we can train the model and check the validation accuracy, which reaches 99.37%:", "_____no_output_____" ] ], [ [ "# Train\nmodel.compile(loss='binary_crossentropy',\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['accuracy'])\n\nmodel.fit([train_pairs[:, 0], train_pairs[:, 1]], tr_labels,\n batch_size=128,\n epochs=20,\n validation_data=([test_pairs[:, 0], test_pairs[:, 1]], test_labels))", "Train on 108400 samples, validate on 17820 samples\nEpoch 1/20\n108400/108400 [==============================] - 5s 44us/sample - loss: 0.3328 - accuracy: 0.8540 - val_loss: 0.2435 - val_accuracy: 0.9184\nEpoch 2/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.1612 - accuracy: 0.9409 - val_loss: 0.1672 - val_accuracy: 0.9465\nEpoch 3/20\n108400/108400 [==============================] - 4s 38us/sample - loss: 0.1096 - accuracy: 0.9611 - val_loss: 0.1221 - val_accuracy: 0.9625\nEpoch 4/20\n108400/108400 [==============================] - 4s 38us/sample - loss: 0.0824 - accuracy: 0.9712 - val_loss: 0.1052 - val_accuracy: 0.9667\nEpoch 5/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0673 - accuracy: 0.9760 - val_loss: 0.0958 - val_accuracy: 0.9706\nEpoch 6/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0542 - accuracy: 0.9808 - val_loss: 0.1054 - val_accuracy: 0.9689\nEpoch 7/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0471 - accuracy: 0.9832 - val_loss: 0.0823 - val_accuracy: 0.9764\nEpoch 8/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0410 - accuracy: 0.9853 - val_loss: 0.0769 - val_accuracy: 0.9769\nEpoch 9/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0377 - accuracy: 0.9868 - val_loss: 0.0921 - val_accuracy: 0.9731\nEpoch 10/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0326 - accuracy: 0.9887 - val_loss: 0.0920 - val_accuracy: 0.9744\nEpoch 11/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0309 - accuracy: 0.9887 - val_loss: 0.0846 - val_accuracy: 0.9753\nEpoch 12/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0283 - accuracy: 0.9898 - val_loss: 0.0902 - val_accuracy: 0.9742\nEpoch 13/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0262 - accuracy: 0.9908 - val_loss: 0.0956 - val_accuracy: 0.9753\nEpoch 14/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0228 - accuracy: 0.9918 - val_loss: 0.0820 - val_accuracy: 0.9781\nEpoch 15/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0240 - accuracy: 0.9914 - val_loss: 0.0869 - val_accuracy: 0.9759\nEpoch 16/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0225 - accuracy: 0.9921 - val_loss: 0.0754 - val_accuracy: 0.9794\nEpoch 17/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0209 - accuracy: 0.9928 - val_loss: 0.0786 - val_accuracy: 0.9778\nEpoch 18/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0207 - accuracy: 0.9929 - val_loss: 0.0797 - val_accuracy: 0.9787\nEpoch 19/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0178 - accuracy: 0.9937 - val_loss: 0.0884 - val_accuracy: 0.9785\nEpoch 20/20\n108400/108400 [==============================] - 4s 37us/sample - loss: 0.0189 - accuracy: 0.9935 - val_loss: 0.0754 - val_accuracy: 0.9799\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d03bbd6a28dc6afe3a3a8d84c9ce288545946480
4,263
ipynb
Jupyter Notebook
01_introduction/06_write_a_function.ipynb
juanhenao21/hack_rank
da5cfbab9c4adfdf505745fe321a849efad44d2c
[ "MIT" ]
null
null
null
01_introduction/06_write_a_function.ipynb
juanhenao21/hack_rank
da5cfbab9c4adfdf505745fe321a849efad44d2c
[ "MIT" ]
null
null
null
01_introduction/06_write_a_function.ipynb
juanhenao21/hack_rank
da5cfbab9c4adfdf505745fe321a849efad44d2c
[ "MIT" ]
null
null
null
24.36
205
0.518883
[ [ [ "# Introduction\n\nJuan Camilo Henao Londono\n\nExercise from [Hacker rank](https://www.hackerrank.com/challenges/write-a-function/problem)", "_____no_output_____" ], [ "# Write a function\n\nWe add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February.\nIn the Gregorian calendar three criteria must be taken into account to identify leap years:\n\n* The year can be evenly divided by 4, is a leap year, unless:\n * The year can be evenly divided by 100, it is NOT a leap year, unless:\n * The year is also evenly divisible by 400. Then it is a leap year.\n\nThis means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.\n\n**Task**\n\nYou are given the year, and you have to write a function to check if the year is leap or not.\n\nNote that you have to complete the function and remaining code is given as template. \n\n**Input Format**\n\nRead y, the year that needs to be checked. \n\n**Constraints**\n\n* $1900 \\le y \\le 10^{5}$\n\n**Output Format**\n\nOutput is taken care of by the template. Your function must return a boolean value (```True```/```False```)\n\n**Sample Input 0**\n\n```\n1990\n```\n\n**Sample Output 0**\n\n```\nFalse\n```\n\n**Explanation 0**\n\n1990 is not a multiple of 4 hence it's not a leap year. ", "_____no_output_____" ], [ "## My implementation", "_____no_output_____" ], [ "If one of the conditions to be a leap year is achieved, the function return `True`. If not return `False`. This implementation was used as the exercise give a \"template\" to complete with the code.", "_____no_output_____" ] ], [ [ "def is_leap(year):\n \n if (year%400 == 0 and year%100 == 0):\n return True\n elif (year%4 == 0 and year%100 != 0):\n return True\n \n return False\n\nyear = int(input())\nprint(is_leap(year))", "2019\nFalse\n" ] ], [ [ "## Best implementation in the discussion", "_____no_output_____" ], [ "From the discussion:\n\n> you should know that doing something like the setup for this challenge inclines you to do is a bad practice. Never do the following:\n\n```Python\ndef f():\n\tif condition:\n \treturn True\n else:\n \treturn False\n```", "_____no_output_____" ] ], [ [ "def is_leap(year):\n return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)\n\nyear = int(input())\nprint(is_leap(year)) ", "2019\nFalse\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
d03bd3a24998a314e6e2cca1b9e0e60ed2edc8b5
540,952
ipynb
Jupyter Notebook
BBOX_GRADCAM_demo_example.ipynb
zalkikar/BBOX_GradCAM
85feb617d40e8261301abe35aa3cc36a4b89340a
[ "MIT" ]
12
2019-10-18T03:45:22.000Z
2021-06-23T22:40:24.000Z
BBOX_GRADCAM_demo_example.ipynb
zalkikar/BBOX_GradCAM
85feb617d40e8261301abe35aa3cc36a4b89340a
[ "MIT" ]
null
null
null
BBOX_GRADCAM_demo_example.ipynb
zalkikar/BBOX_GradCAM
85feb617d40e8261301abe35aa3cc36a4b89340a
[ "MIT" ]
1
2020-09-09T08:30:30.000Z
2020-09-09T08:30:30.000Z
500.418131
178,722
0.916037
[ [ [ "# BBoxerwGradCAM\n\n### This class forms boundary boxes (rectangle and polygon) using GradCAM outputs for a given image.\n\nThe purpose of this class is to develop Rectangle and Polygon coordinates that define an object based on an image classification model. The 'automatic' creation of these coordinates, which are often included in COCO JSONs used to train object detection models, is valuable because data preparation and labeling can be a time consuming task.\n\n### This class takes 5 user inputs:\n* **Pretrained Learner** (image classification model)\n* **GradCAM Heatmap** (heatmap of GradCAM object - formed by a pretrained image classification learner)\n* **Source Image**\n* **Image Resizing Scale** (also applied to corresponding GradCAM heatmap)\n* **BBOX Rectangle Resizing Scale**\n\n\n*Class is compatible with google colab and other Python 3 enivronments*\n", "_____no_output_____" ] ], [ [ "# Imports for loading learner and the GradCAM class\nfrom fastai import *\nfrom fastai.vision import *\nfrom fastai.callbacks.hooks import *\nimport scipy.ndimage", "_____no_output_____" ] ], [ [ "The following cell contains the widely used GradCAM class for pretrained image classification models (unedited).", "_____no_output_____" ] ], [ [ "#@title GradCAM Class\n\nclass GradCam():\n @classmethod\n def from_interp(cls,learn,interp,img_idx,ds_type=DatasetType.Valid,include_label=False):\n # produce heatmap and xb_grad for pred label (and actual label if include_label is True)\n if ds_type == DatasetType.Valid:\n ds = interp.data.valid_ds\n elif ds_type == DatasetType.Test:\n ds = interp.data.test_ds\n include_label=False\n else:\n return None\n \n x_img = ds.x[img_idx]\n xb,_ = interp.data.one_item(x_img)\n xb_img = Image(interp.data.denorm(xb)[0])\n probs = interp.preds[img_idx].numpy()\n\n pred_idx = interp.pred_class[img_idx].item() # get class idx of img prediction label\n hmap_pred,xb_grad_pred = get_grad_heatmap(learn,xb,pred_idx,size=xb_img.shape[-1])\n prob_pred = probs[pred_idx]\n \n actual_args=None\n if include_label:\n actual_idx = ds.y.items[img_idx] # get class idx of img actual label\n if actual_idx!=pred_idx:\n hmap_actual,xb_grad_actual = get_grad_heatmap(learn,xb,actual_idx,size=xb_img.shape[-1])\n prob_actual = probs[actual_idx]\n actual_args=[interp.data.classes[actual_idx],prob_actual,hmap_actual,xb_grad_actual]\n \n return cls(xb_img,interp.data.classes[pred_idx],prob_pred,hmap_pred,xb_grad_pred,actual_args)\n \n @classmethod\n def from_one_img(cls,learn,x_img,label1=None,label2=None):\n '''\n learn: fastai's Learner\n x_img: fastai.vision.image.Image\n label1: generate heatmap according to this label. If None, this wil be the label with highest probability from the model\n label2: generate additional heatmap according to this label\n '''\n pred_class,pred_idx,probs = learn.predict(x_img)\n label1= str(pred_class) if not label1 else label1\n \n xb,_ = learn.data.one_item(x_img)\n xb_img = Image(learn.data.denorm(xb)[0])\n probs = probs.numpy()\n \n label1_idx = learn.data.classes.index(label1)\n hmap1,xb_grad1 = get_grad_heatmap(learn,xb,label1_idx,size=xb_img.shape[-1])\n prob1 = probs[label1_idx]\n \n label2_args = None\n if label2:\n label2_idx = learn.data.classes.index(label2)\n hmap2,xb_grad2 = get_grad_heatmap(learn,xb,label2_idx,size=xb_img.shape[-1])\n prob2 = probs[label2_idx]\n label2_args = [label2,prob2,hmap2,xb_grad2]\n \n return cls(xb_img,label1,prob1,hmap1,xb_grad1,label2_args)\n \n def __init__(self,xb_img,label1,prob1,hmap1,xb_grad1,label2_args=None):\n self.xb_img=xb_img\n self.label1,self.prob1,self.hmap1,self.xb_grad1 = label1,prob1,hmap1,xb_grad1\n if label2_args:\n self.label2,self.prob2,self.hmap2,self.xb_grad2 = label2_args\n \n def plot(self,plot_hm=True,plot_gbp=True):\n if not plot_hm and not plot_gbp:\n plot_hm=True\n cols = 5 if hasattr(self, 'label2') else 3\n if not plot_gbp or not plot_hm:\n cols-= 2 if hasattr(self, 'label2') else 1\n\n fig,row_axes = plt.subplots(1,cols,figsize=(cols*5,5)) \n col=0\n size=self.xb_img.shape[-1]\n self.xb_img.show(row_axes[col]);col+=1\n \n label1_title = f'1.{self.label1} {self.prob1:.3f}'\n if plot_hm:\n show_heatmap(self.hmap1,self.xb_img,size,row_axes[col])\n row_axes[col].set_title(label1_title);col+=1\n if plot_gbp:\n row_axes[col].imshow(self.xb_grad1)\n row_axes[col].set_axis_off()\n row_axes[col].set_title(label1_title);col+=1\n \n if hasattr(self, 'label2'):\n label2_title = f'2.{self.label2} {self.prob2:.3f}'\n if plot_hm:\n show_heatmap(self.hmap2,self.xb_img,size,row_axes[col])\n row_axes[col].set_title(label2_title);col+=1\n if plot_gbp:\n row_axes[col].imshow(self.xb_grad2)\n row_axes[col].set_axis_off()\n row_axes[col].set_title(label2_title)\n # plt.tight_layout()\n fig.subplots_adjust(wspace=0, hspace=0)\n # fig.savefig('data_draw/both/gradcam.png')\n\ndef minmax_norm(x):\n return (x - np.min(x))/(np.max(x) - np.min(x))\ndef scaleup(x,size):\n scale_mult=size/x.shape[0]\n upsampled = scipy.ndimage.zoom(x, scale_mult)\n return upsampled\n\n# hook for Gradcam\ndef hooked_backward(m,xb,target_layer,clas):\n with hook_output(target_layer) as hook_a: #hook at last layer of group 0's output (after bn, size 512x7x7 if resnet34)\n with hook_output(target_layer, grad=True) as hook_g: # gradient w.r.t to the target_layer\n preds = m(xb)\n preds[0,int(clas)].backward() # same as onehot backprop\n return hook_a,hook_g\n\ndef clamp_gradients_hook(module, grad_in, grad_out):\n for grad in grad_in:\n torch.clamp_(grad, min=0.0)\n \n# hook for guided backprop\ndef hooked_ReLU(m,xb,clas):\n relu_modules = [module[1] for module in m.named_modules() if str(module[1]) == \"ReLU(inplace)\"]\n with callbacks.Hooks(relu_modules, clamp_gradients_hook, is_forward=False) as _:\n preds = m(xb)\n preds[0,int(clas)].backward()\n \ndef guided_backprop(learn,xb,y):\n xb = xb.cuda()\n m = learn.model.eval();\n xb.requires_grad_();\n if not xb.grad is None:\n xb.grad.zero_(); \n hooked_ReLU(m,xb,y);\n return xb.grad[0].cpu().numpy()\n\ndef show_heatmap(hm,xb_im,size,ax=None):\n if ax is None:\n _,ax = plt.subplots()\n xb_im.show(ax)\n ax.imshow(hm, alpha=0.8, extent=(0,size,size,0),\n interpolation='bilinear',cmap='magma');\n\ndef get_grad_heatmap(learn,xb,y,size):\n '''\n Main function to get hmap for heatmap and xb_grad for guided backprop\n '''\n xb = xb.cuda()\n m = learn.model.eval();\n target_layer = m[0][-1][-1] # last layer of group 0\n hook_a,hook_g = hooked_backward(m,xb,target_layer,y)\n \n target_act= hook_a.stored[0].cpu().numpy()\n target_grad = hook_g.stored[0][0].cpu().numpy()\n \n mean_grad = target_grad.mean(1).mean(1)\n# hmap = (target_act*mean_grad[...,None,None]).mean(0)\n hmap = (target_act*mean_grad[...,None,None]).sum(0)\n hmap = np.where(hmap >= 0, hmap, 0)\n \n xb_grad = guided_backprop(learn,xb,y) # (3,224,224) \n #minmax norm the grad\n xb_grad = minmax_norm(xb_grad)\n hmap_scaleup = minmax_norm(scaleup(hmap,size)) # (224,224)\n \n # multiply xb_grad and hmap_scaleup and switch axis\n xb_grad = np.einsum('ijk, jk->jki',xb_grad, hmap_scaleup) #(224,224,3)\n \n return hmap,xb_grad", "_____no_output_____" ] ], [ [ "I connect to google drive (this notebook was made on google colab for GPU usage) and load my pretrained learner.", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], [ "base_dir = '/content/drive/My Drive/fellowshipai-data/final_3_class_data_train_test_split'\n\ndef get_data(sz): # This function returns an ImageDataBunch with a given image size\n return ImageDataBunch.from_folder(base_dir+'/', train='train', valid='valid', # 0% validation because we already formed our testing set\n ds_tfms=get_transforms(), size=sz, num_workers=4).normalize(imagenet_stats) # Normalized, 4 workers (multiprocessing) - 64 batch size (default)", "_____no_output_____" ], [ "arch = models.resnet34\ndata = get_data(224)\nlearn = cnn_learner(data,arch,metrics=[error_rate,Precision(average='micro'),Recall(average='micro')],train_bn=True,pretrained=True).mixup()\nlearn.load('model-224sz-basicaugments-oversampling-mixup-dLRs')", "/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n" ], [ "example_image = '/content/drive/My Drive/fellowshipai-data/final_3_class_data_train_test_split/train/raw/00000015.jpg'\n\nimg = open_image(example_image)\n\ngcam = GradCam.from_one_img(learn,img) # using the GradCAM class\n\ngcam.plot(plot_gbp = False) # We care about the heatmap (which is overlayed on top of the original image inherently)\n\ngcam_heatmap = gcam.hmap1 # This is a 2d array", "/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:2854: UserWarning: The default behavior for interpolate/upsample with float scale_factor will change in 1.6.0 to align with other frameworks/libraries, and use scale_factor directly, instead of relying on the computed output size. If you wish to keep the old behavior, please set recompute_scale_factor=True. See the documentation of nn.Upsample for details. \n warnings.warn(\"The default behavior for interpolate/upsample with float scale_factor will change \"\n" ] ], [ [ "My pretrained learner correctly classified the image as raw with probability 0.996.\n\nNote that images with very low noise and accurate feature importances (as with the example image) are \n\nThe learner is focusing on the steak in center view (heatmap pixels indicate feature importance).", "_____no_output_____" ] ], [ [ "from BBOXES_from_GRADCAM import BBoxerwGradCAM # load class from .py file", "_____no_output_____" ], [ "image_resizing_scale = [400,300]\nbbox_scaling = [1,1,1,1] \n\nbbox = BBoxerwGradCAM(learn,\n gcam_heatmap,\n example_image,\n image_resizing_scale,\n bbox_scaling)", "_____no_output_____" ], [ "for function in dir(bbox)[-18:]: print(function)", "bbox_coords\ncontours\nform_bboxes\nget_bboxes\ngrey_img\nheatmap\nheatmap_smoothing\nimage_path\nlearner\nog_img\npoly_coords\nresize_list\nscale_list\nshow_bboxpolygon\nshow_bboxrectangle\nshow_contouredheatmap\nshow_smoothheatmap\nsmooth_heatmap\n" ], [ "bbox.show_smoothheatmap()\nbbox.show_contouredheatmap()\n#bbox.show_bboxrectangle()\nbbox.show_bboxpolygon()", "_____no_output_____" ], [ "bbox.show_bboxrectangle()", "_____no_output_____" ], [ "rect_coords, polygon_coords = bbox.get_bboxes()", "_____no_output_____" ], [ "rect_coords # x,y,w,h", "_____no_output_____" ], [ "polygon_coords", "_____no_output_____" ], [ "# IoU for object detection\ndef get_IoU(truth_coords, pred_coords):\n pred_area = pred_coords[2]*pred_coords[3]\n truth_area = truth_coords[2]*truth_coords[3]\n # coords of intersection rectangle\n x1 = max(truth_coords[0], pred_coords[0])\n y1 = max(truth_coords[1], pred_coords[1])\n x2 = min(truth_coords[2], pred_coords[2])\n y2 = min(truth_coords[3], pred_coords[3])\n # area of intersection rectangle\n interArea = max(0, x2 - x1 + 1) * max(0, y2 - y1 + 1)\n # area of prediction and truth rectangles\n boxTruthArea = (truth_coords[2] - truth_coords[0] + 1) * (truth_coords[3] - truth_coords[1] + 1)\n boxPredArea = (pred_coords[2] - pred_coords[0] + 1) * (pred_coords[3] - pred_coords[1] + 1)\n # intersection over union \n iou = interArea / float(boxTruthArea + boxPredArea - interArea)\n return iou", "_____no_output_____" ], [ "get_IoU([80,40,240,180],rect_coords)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d03bd88740021c2ca1ea43e688b9c582b64ddf04
48,978
ipynb
Jupyter Notebook
Playground/Untitled.ipynb
dustykat/engr-1330-psuedo-course
3e7e31a32a1896fcb1fd82b573daa5248e465a36
[ "CC0-1.0" ]
null
null
null
Playground/Untitled.ipynb
dustykat/engr-1330-psuedo-course
3e7e31a32a1896fcb1fd82b573daa5248e465a36
[ "CC0-1.0" ]
null
null
null
Playground/Untitled.ipynb
dustykat/engr-1330-psuedo-course
3e7e31a32a1896fcb1fd82b573daa5248e465a36
[ "CC0-1.0" ]
null
null
null
60.616337
12,368
0.682592
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "import requests # Module to process http/https requests\n\nremote_url=\"http://54.243.252.9/engr-1330-webroot/9-MyJupyterNotebooks/41A-HypothesisTests/precon.csv\" # set the url\nrget = requests.get(remote_url, allow_redirects=True) # get the remote resource, follow imbedded links\nopen('precon.csv','wb').write(rget.content) # extract from the remote the contents, assign to a local file same name\n\nremote_url=\"http://54.243.252.9/engr-1330-webroot/9-MyJupyterNotebooks/41A-HypothesisTests/durcon.csv\" # set the url\nrget = requests.get(remote_url, allow_redirects=True) # get the remote resource, follow imbedded links\nopen('durcon.csv','wb').write(rget.content) # extract from the remote the contents, assign to a local file same name", "_____no_output_____" ], [ "precon = pd.read_csv(\"precon.csv\")\ndurcon = pd.read_csv(\"durcon.csv\") ", "_____no_output_____" ], [ "precon.head(24)", "_____no_output_____" ], [ "durcon.head(24)", "_____no_output_____" ], [ "precon.describe()", "_____no_output_____" ], [ "durcon.describe()", "_____no_output_____" ], [ "precon['RAIN.PRE'].hist(alpha=0.4,color='red',density=\"True\")\ndurcon['RAIN.DUR'].hist(alpha=0.4,color='blue',density=\"True\")", "_____no_output_____" ], [ "precon['TS.PRE'].hist(alpha=0.4,color='red',density=\"True\",bins=20)\ndurcon['TS.DUR'].hist(alpha=0.4,color='blue',density=\"True\",bins=20)", "_____no_output_____" ], [ "pre_s = np.random.normal(np.array(precon['TS.PRE']).mean(), np.array(precon['TS.PRE']).std(), 100000) # random sample from a normal distribution function\ndur_s = np.random.normal(np.array(precon['TS.PRE']).mean(), 10*np.array(precon['TS.PRE']).std(), 100000) # random sample from a normal distribution function", "_____no_output_____" ], [ "myfakedata_d = pd.DataFrame({'PreSim':pre_s,'DurSim':dur_s}) # make into a dataframe _d == derived", "_____no_output_____" ], [ "\n\nfig, ax = plt.subplots()\nmyfakedata_d.plot.hist(density=True, ax=ax, title='Histogram: Pre samples vs. Dur samples', bins=60)\nax.set_ylabel('Count')\nax.grid(axis='y')\n\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]