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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e787b7952d075f1e0c4fd1f0209d3eadd39bfdd5 | 385,083 | ipynb | Jupyter Notebook | EDA_techniques.ipynb | capitallatera/Stat-and-ML | 924c7497db3b41f592ecd1d8f51bd4007f6791cc | [
"MIT"
] | null | null | null | EDA_techniques.ipynb | capitallatera/Stat-and-ML | 924c7497db3b41f592ecd1d8f51bd4007f6791cc | [
"MIT"
] | null | null | null | EDA_techniques.ipynb | capitallatera/Stat-and-ML | 924c7497db3b41f592ecd1d8f51bd4007f6791cc | [
"MIT"
] | null | null | null | 516.197051 | 118,886 | 0.93342 | [
[
[
"<a href=\"https://colab.research.google.com/github/capitallatera/Stat-and-ML/blob/main/EDA_techniques.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline",
"_____no_output_____"
],
[
"df=pd.read_csv('/content/drive/MyDrive/DataSet_Main/HouseData.csv')",
"_____no_output_____"
],
[
"df.columns ",
"_____no_output_____"
]
],
[
[
"Analysis Sales Price",
"_____no_output_____"
]
],
[
[
"# Descriptive statistics summary\ndf['SalePrice'].describe() ",
"_____no_output_____"
]
],
[
[
"- If mean and median are same in the dataset means\nthere is no outliers",
"_____no_output_____"
]
],
[
[
"# Histogram \nsns.distplot(df['SalePrice'])",
"_____no_output_____"
]
],
[
[
"- Normarl Distribution\n",
"_____no_output_____"
]
],
[
[
"# Skewness an d kurtosis\nprint('Skewness: %f' % df['SalePrice'].skew())\nprint('Kurtosis: %f' % df['SalePrice'].skew())",
"Skewness: 1.882876\nKurtosis: 1.882876\n"
]
],
[
[
"- If skewness is zero means dataset has no skewed point\n- It ranges from 0 to 10",
"_____no_output_____"
],
[
"Relationships",
"_____no_output_____"
]
],
[
[
"# Scatter plot grlivarea/saleprice\nvar='GrLivArea'\ndata=pd.concat([df['SalePrice'],df[var]],axis=1) #another way of making dataframe\ndata.plot.scatter(x=var,y='SalePrice',ylim=(0,800000))",
"_____no_output_____"
]
],
[
[
"- For removing Outliers\n - If value is greater than 4000 then remove row",
"_____no_output_____"
]
],
[
[
"# Scatter plot totalbsmtsf/saleprice\nvar='TotalBsmtSF'\ndata=pd.concat([df['SalePrice'],df[var]],axis=1)\ndata.plot.scatter(x=var,y='SalePrice',ylim=(0,800000))",
"_____no_output_____"
]
],
[
[
"Relationship with categorical variables",
"_____no_output_____"
]
],
[
[
"# Box plot overallqual/saleprice\nvar='OverallQual'\ndata=pd.concat([df['SalePrice'],df[var]],axis=1)\nf,ax=plt.subplots(figsize=(10,6))\nfig=sns.boxplot(x=var,y='SalePrice',data=data)\nfig.axis(ymin=0,ymax=800000);",
"_____no_output_____"
],
[
"var='YearBuilt'\ndata=pd.concat([df['SalePrice'],df[var]],axis=1)\nf,ax=plt.subplots(figsize=(16,8))\nfig=sns.boxplot(x=var,y='SalePrice',data=data)\nfig.axis(ymin=0,ymax=800000)\nplt.xticks(rotation=90);",
"_____no_output_____"
]
],
[
[
"- The Dataset which is not able to visualize correctly alternate method is use tableau and powerBI for better and clear illustration",
"_____no_output_____"
],
[
"Correlation",
"_____no_output_____"
]
],
[
[
"# Correlation Matrix\ncorrmat=df.corr()\nf,ax=plt.subplots(figsize=(12,9))\nsns.heatmap(corrmat,vmax=.8,square=True); ",
"_____no_output_____"
],
[
"# SalePrice correlation matrix\nk=10 # number of variables for heatmap\ncols=corrmat.nlargest(k,'SalePrice')['SalePrice'].index\ncm=np.corrcoef(df[cols].values.T)\nsns.set(font_scale=0.6)\nhm=sns.heatmap(cm,cbar=True,annot=True,square=True,fmt='.2f',annot_kws={'size':7},yticklabels=cols.values,xticklabels=cols.values)\nplt.show()",
"_____no_output_____"
],
[
"# Scatterplot\nsns.set()\ncols=['SalePrice','OverallQual','GrLivArea','GarageCars']\nsns.pairplot(df[cols],size=2.5)\nplt.show();",
"_____no_output_____"
]
],
[
[
"Missing Value",
"_____no_output_____"
]
],
[
[
"# missing data\ntotal=df.isnull().sum().sort_values(ascending=False)\npercent=(df.isnull().sum()/df.isnull().count()).sort_values(ascending=False)\nmissing_data=pd.concat([total,percent],axis=1,keys=['Total','Percent'])\nmissing_data.head(20)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e787ba099403d67f3b3a7b97157b4737a479722e | 225,882 | ipynb | Jupyter Notebook | ind.ipynb | djamaludinn/cp4 | 4634097edc3a1cb3e6e6f9295cfac453778a9f1d | [
"MIT"
] | null | null | null | ind.ipynb | djamaludinn/cp4 | 4634097edc3a1cb3e6e6f9295cfac453778a9f1d | [
"MIT"
] | null | null | null | ind.ipynb | djamaludinn/cp4 | 4634097edc3a1cb3e6e6f9295cfac453778a9f1d | [
"MIT"
] | null | null | null | 858.86692 | 97,232 | 0.95035 | [
[
[
"import matplotlib\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"\nx = [1, 5, 10, 15, 20]\ny1 = [1, 7, 3, 5, 11]\ny2 = [i*1.2 + 1 for i in y1]\ny3 = [i*1.2 + 1 for i in y2]\ny4 = [i*1.2 + 1 for i in y3]\n\nplt.figure(figsize=(12, 7))\n\nplt.subplot(2, 2, 1)\nplt.plot(x, y1, '-')\nplt.subplot(2, 2, 2)\nplt.plot(x, y2, '--')\nplt.subplot(2, 2, 3)\nplt.plot(x, y3, '-.')\nplt.subplot(2, 2, 4)\nplt.plot(x, y4, ':')",
"_____no_output_____"
],
[
"# Вывод графиков\nplt.subplot(221)\nplt.plot(x, y1, '-')\nplt.subplot(222)\nplt.plot(x, y2, '--')\nplt.subplot(223)\nplt.plot(x, y3, '-.')\nplt.subplot(224)\nplt.plot(x, y4, ':')",
"_____no_output_____"
],
[
"fig, axs = plt.subplots(2, 2, figsize=(12, 7))\naxs[0, 0].plot(x, y1, '-')\naxs[0, 1].plot(x, y2, '--')\naxs[1, 0].plot(x, y3, '-.')\naxs[1, 1].plot(x, y4, ':')",
"_____no_output_____"
],
[
"plt.plot([10,9,7,6,4,0])\nplt.title(\"График снижения уровня заработных плат\") \nplt.xlabel(\"Продолжительность 5 лет\") \nplt.ylabel(\"Уровень зароботных плат\") \nplt.scatter()\nplt.grid() \nplt.plot() ",
"_____no_output_____"
]
],
[
[
"# Индивидуальное задание",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter,\n\nAutoMinorLocator)\n\nimport numpy as np\n\nx = np.linspace(0, 5, 50)\ny1 = 3*x\ny2 = [i/0.10 for i in x]\nfig, ax = plt.subplots(figsize=(15, 9))\nax.set_title(\"График вероятности получения зачета по кроссплатформенному программированию\", fontsize=16)\nax.set_xlabel(\"Оценки\", fontsize=14)\nax.set_ylabel(\"Вероятность получения зачета\", fontsize=14)\nax.grid(which=\"major\", linewidth=1, color=\"black\")\nax.grid(which=\"minor\", linestyle=\"--\", color=\"grey\", linewidth=0.6)\nax.scatter(x, y1, c=\"red\", label=\"Вероятность получения зачета\")\nax.plot(x, y2, label=\"График вероятности \")\nax.legend()\n#Деления основной сетки\nax.xaxis.set_minor_locator(AutoMinorLocator())\nax.yaxis.set_minor_locator(AutoMinorLocator())\nplt.show()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e787bfb6e794bab067719d99255bb2c62cbdb244 | 64,452 | ipynb | Jupyter Notebook | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge | f90515658914a6f42841c14fe2e95a9b39037dd7 | [
"MIT"
] | null | null | null | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge | f90515658914a6f42841c14fe2e95a9b39037dd7 | [
"MIT"
] | null | null | null | sentiment-rnn/Sentiment_RNN.ipynb | hsneto/pytorch-challenge | f90515658914a6f42841c14fe2e95a9b39037dd7 | [
"MIT"
] | null | null | null | 45.905983 | 7,349 | 0.558617 | [
[
[
"# Sentiment Analysis with an RNN\n\nIn this notebook, you'll implement a recurrent neural network that performs sentiment analysis. \n>Using an RNN rather than a strictly feedforward network is more accurate since we can include information about the *sequence* of words. \n\nHere we'll use a dataset of movie reviews, accompanied by sentiment labels: positive or negative.\n\n<img src=\"assets/reviews_ex.png\" width=40%>\n\n### Network Architecture\n\nThe architecture for this network is shown below.\n\n<img src=\"assets/network_diagram.png\" width=40%>\n\n>**First, we'll pass in words to an embedding layer.** We need an embedding layer because we have tens of thousands of words, so we'll need a more efficient representation for our input data than one-hot encoded vectors. You should have seen this before from the Word2Vec lesson. You can actually train an embedding with the Skip-gram Word2Vec model and use those embeddings as input, here. However, it's good enough to just have an embedding layer and let the network learn a different embedding table on its own. *In this case, the embedding layer is for dimensionality reduction, rather than for learning semantic representations.*\n\n>**After input words are passed to an embedding layer, the new embeddings will be passed to LSTM cells.** The LSTM cells will add *recurrent* connections to the network and give us the ability to include information about the *sequence* of words in the movie review data. \n\n>**Finally, the LSTM outputs will go to a sigmoid output layer.** We're using a sigmoid function because positive and negative = 1 and 0, respectively, and a sigmoid will output predicted, sentiment values between 0-1. \n\nWe don't care about the sigmoid outputs except for the **very last one**; we can ignore the rest. We'll calculate the loss by comparing the output at the last time step and the training label (pos or neg).",
"_____no_output_____"
],
[
"---\n### Load in and visualize the data",
"_____no_output_____"
]
],
[
[
"from google.colab import files\n\n# Upload reviews.txt and labels.txt to google colab\nuploaded = files.upload()",
"_____no_output_____"
],
[
"import numpy as np\n\n# read data from text files\nwith open('reviews.txt', 'r') as f:\n reviews = f.read()\nwith open('labels.txt', 'r') as f:\n labels = f.read()",
"_____no_output_____"
],
[
"print(reviews[:2000])\nprint()\nprint(labels[:20])",
"bromwell high is a cartoon comedy . it ran at the same time as some other programs about school life such as teachers . my years in the teaching profession lead me to believe that bromwell high s satire is much closer to reality than is teachers . the scramble to survive financially the insightful students who can see right through their pathetic teachers pomp the pettiness of the whole situation all remind me of the schools i knew and their students . when i saw the episode in which a student repeatedly tried to burn down the school i immediately recalled . . . . . . . . . at . . . . . . . . . . high . a classic line inspector i m here to sack one of your teachers . student welcome to bromwell high . i expect that many adults of my age think that bromwell high is far fetched . what a pity that it isn t \nstory of a man who has unnatural feelings for a pig . starts out with a opening scene that is a terrific example of absurd comedy . a formal orchestra audience is turned into an insane violent mob by the crazy chantings of it s singers . unfortunately it stays absurd the whole time with no general narrative eventually making it just too off putting . even those from the era should be turned off . the cryptic dialogue would make shakespeare seem easy to a third grader . on a technical level it s better than you might think with some good cinematography by future great vilmos zsigmond . future stars sally kirkland and frederic forrest can be seen briefly . \nhomelessness or houselessness as george carlin stated has been an issue for years but never a plan to help those on the street that were once considered human who did everything from going to school work or vote for the matter . most people think of the homeless as just a lost cause while worrying about things such as racism the war on iraq pressuring kids to succeed technology the elections inflation or worrying if they ll be next to end up on the streets . br br but what if y\n\npositive\nnegative\npo\n"
]
],
[
[
"## Data pre-processing\n\nThe first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit.\n\nYou can see an example of the reviews data above. Here are the processing steps, we'll want to take:\n>* We'll want to get rid of periods and extraneous punctuation.\n* Also, you might notice that the reviews are delimited with newline characters `\\n`. To deal with those, I'm going to split the text into each review using `\\n` as the delimiter. \n* Then I can combined all the reviews back together into one big string.\n\nFirst, let's remove all punctuation. Then get all the text without the newlines and split it into individual words.",
"_____no_output_____"
]
],
[
[
"from string import punctuation\n\nprint(punctuation)\n\n# get rid of punctuation\nreviews = reviews.lower() # lowercase, standardize\nall_text = ''.join([c for c in reviews if c not in punctuation])",
"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n"
],
[
"# split by new lines and spaces\nreviews_split = all_text.split('\\n')\nall_text = ' '.join(reviews_split)\n\n# create a list of words\nwords = all_text.split()",
"_____no_output_____"
],
[
"words[:30]",
"_____no_output_____"
]
],
[
[
"### Encoding the words\n\nThe embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network.\n\n> **Exercise:** Now you're going to encode the words with integers. Build a dictionary that maps words to integers. Later we're going to pad our input vectors with zeros, so make sure the integers **start at 1, not 0**.\n> Also, convert the reviews to integers and store the reviews in a new list called `reviews_ints`. ",
"_____no_output_____"
]
],
[
[
"# feel free to use this import \nfrom collections import Counter\n\n## Build a dictionary that maps words to integers\nwords_counts = Counter(words)\nvocab = sorted(words_counts, key=words_counts.get, reverse=True)\nvocab_to_int = {word:ii for ii, word in enumerate(vocab, 1)}\n\n## use the dict to tokenize each review in reviews_split\n## store the tokenized reviews in reviews_ints\nreviews_ints = []\nfor review in reviews_split:\n reviews_ints.append([vocab_to_int[word] for word in review.split()])",
"_____no_output_____"
]
],
[
[
"**Test your code**\n\nAs a text that you've implemented the dictionary correctly, print out the number of unique words in your vocabulary and the contents of the first, tokenized review.",
"_____no_output_____"
]
],
[
[
"# stats about vocabulary\nprint('Unique words: ', len((vocab_to_int))) # should ~ 74000+\nprint()\n\n# print tokens in first review\nprint('Tokenized review: \\n', reviews_ints[:1])",
"Unique words: 74072\n\nTokenized review: \n [[21025, 308, 6, 3, 1050, 207, 8, 2138, 32, 1, 171, 57, 15, 49, 81, 5785, 44, 382, 110, 140, 15, 5194, 60, 154, 9, 1, 4975, 5852, 475, 71, 5, 260, 12, 21025, 308, 13, 1978, 6, 74, 2395, 5, 613, 73, 6, 5194, 1, 24103, 5, 1983, 10166, 1, 5786, 1499, 36, 51, 66, 204, 145, 67, 1199, 5194, 19869, 1, 37442, 4, 1, 221, 883, 31, 2988, 71, 4, 1, 5787, 10, 686, 2, 67, 1499, 54, 10, 216, 1, 383, 9, 62, 3, 1406, 3686, 783, 5, 3483, 180, 1, 382, 10, 1212, 13583, 32, 308, 3, 349, 341, 2913, 10, 143, 127, 5, 7690, 30, 4, 129, 5194, 1406, 2326, 5, 21025, 308, 10, 528, 12, 109, 1448, 4, 60, 543, 102, 12, 21025, 308, 6, 227, 4146, 48, 3, 2211, 12, 8, 215, 23]]\n"
]
],
[
[
"### Encoding the labels\n\nOur labels are \"positive\" or \"negative\". To use these labels in our network, we need to convert them to 0 and 1.\n\n> **Exercise:** Convert labels from `positive` and `negative` to 1 and 0, respectively, and place those in a new list, `encoded_labels`.",
"_____no_output_____"
]
],
[
[
"# 1=positive, 0=negative label conversion\nencoded_labels = np.array([1 if label==\"positive\" else 0 for label in labels.split('\\n')])",
"_____no_output_____"
]
],
[
[
"### Removing Outliers\n\nAs an additional pre-processing step, we want to make sure that our reviews are in good shape for standard processing. That is, our network will expect a standard input text size, and so, we'll want to shape our reviews into a specific length. We'll approach this task in two main steps:\n\n1. Getting rid of extremely long or short reviews; the outliers\n2. Padding/truncating the remaining data so that we have reviews of the same length.\n\n<img src=\"assets/outliers_padding_ex.png\" width=40%>\n\nBefore we pad our review text, we should check for reviews of extremely short or long lengths; outliers that may mess with our training.",
"_____no_output_____"
]
],
[
[
"# outlier review stats\nreview_lens = Counter([len(x) for x in reviews_ints])\nprint(\"Zero-length reviews: {}\".format(review_lens[0]))\nprint(\"Maximum review length: {}\".format(max(review_lens)))",
"Zero-length reviews: 1\nMaximum review length: 2514\n"
]
],
[
[
"Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. We'll have to remove any super short reviews and truncate super long reviews. This removes outliers and should allow our model to train more efficiently.\n\n> **Exercise:** First, remove *any* reviews with zero length from the `reviews_ints` list and their corresponding label in `encoded_labels`.",
"_____no_output_____"
]
],
[
[
"print('Number of reviews before removing outliers: ', len(reviews_ints))\n\n## remove any reviews/labels with zero length from the reviews_ints list.\n\nreview_zero_lenght = [ii for ii in range(len(reviews_ints)) if len(reviews_ints[ii]) <= 1]\nreviews_ints = [reviews_ints[ii] for ii in range(len(reviews_ints)) if ii not in review_zero_lenght]\nencoded_labels = [encoded_labels[ii] for ii in range(len(encoded_labels)) if ii not in review_zero_lenght]\n\nprint('Number of reviews after removing outliers: ', len(reviews_ints))",
"Number of reviews before removing outliers: 25001\nNumber of reviews after removing outliers: 25000\n"
]
],
[
[
"---\n## Padding sequences\n\nTo deal with both short and very long reviews, we'll pad or truncate all our reviews to a specific length. For reviews shorter than some `seq_length`, we'll pad with 0s. For reviews longer than `seq_length`, we can truncate them to the first `seq_length` words. A good `seq_length`, in this case, is 200.\n\n> **Exercise:** Define a function that returns an array `features` that contains the padded data, of a standard size, that we'll pass to the network. \n* The data should come from `review_ints`, since we want to feed integers to the network. \n* Each row should be `seq_length` elements long. \n* For reviews shorter than `seq_length` words, **left pad** with 0s. That is, if the review is `['best', 'movie', 'ever']`, `[117, 18, 128]` as integers, the row will look like `[0, 0, 0, ..., 0, 117, 18, 128]`. \n* For reviews longer than `seq_length`, use only the first `seq_length` words as the feature vector.\n\nAs a small example, if the `seq_length=10` and an input review is: \n```\n[117, 18, 128]\n```\nThe resultant, padded sequence should be: \n\n```\n[0, 0, 0, 0, 0, 0, 0, 117, 18, 128]\n```\n\n**Your final `features` array should be a 2D array, with as many rows as there are reviews, and as many columns as the specified `seq_length`.**\n\nThis isn't trivial and there are a bunch of ways to do this. But, if you're going to be building your own deep learning networks, you're going to have to get used to preparing your data.",
"_____no_output_____"
]
],
[
[
"def pad_features(reviews_ints, seq_length):\n ''' Return features of review_ints, where each review is padded with 0's \n or truncated to the input seq_length.\n '''\n ## implement function\n \n features = np.zeros((len(reviews_ints), seq_length), dtype=int)\n \n for ii, review in enumerate(reviews_ints):\n features[ii, -len(review):] = np.array(review)[:seq_length]\n \n return features",
"_____no_output_____"
],
[
"# Test your implementation!\n\nseq_length = 200\n\nfeatures = pad_features(reviews_ints, seq_length=seq_length)\n\n## test statements - do not change - ##\nassert len(features)==len(reviews_ints), \"Your features should have as many rows as reviews.\"\nassert len(features[0])==seq_length, \"Each feature row should contain seq_length values.\"\n\n# print first 10 values of the first 30 batches \nprint(features[:30,:10])",
"[[ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [22382 42 46418 15 706 17139 3389 47 77 35]\n [ 4505 505 15 3 3342 162 8312 1652 6 4819]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 54 10 14 116 60 798 552 71 364 5]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 1 330 578 34 3 162 748 2731 9 325]\n [ 9 11 10171 5305 1946 689 444 22 280 673]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 1 307 10399 2069 1565 6202 6528 3288 17946 10628]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 21 122 2069 1565 515 8181 88 6 1325 1182]\n [ 1 20 6 76 40 6 58 81 95 5]\n [ 54 10 84 329 26230 46427 63 10 14 614]\n [ 11 20 6 30 1436 32317 3769 690 15100 6]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 40 26 109 17952 1422 9 1 327 4 125]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 10 499 1 307 10399 55 74 8 13 30]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0]]\n"
]
],
[
[
"## Training, Validation, Test\n\nWith our data in nice shape, we'll split it into training, validation, and test sets.\n\n> **Exercise:** Create the training, validation, and test sets. \n* You'll need to create sets for the features and the labels, `train_x` and `train_y`, for example. \n* Define a split fraction, `split_frac` as the fraction of data to **keep** in the training set. Usually this is set to 0.8 or 0.9. \n* Whatever data is left will be split in half to create the validation and *testing* data.",
"_____no_output_____"
]
],
[
[
"split_frac = 0.8\n\nencoded_labels = np.array(encoded_labels)\n\n## split data into training, validation, and test data (features and labels, x and y)\nsplit_idx = int(len(features)*0.8)\ntrain_x, remaining_x = features[:split_idx], features[split_idx:]\ntrain_y, remaining_y = encoded_labels[:split_idx], encoded_labels[split_idx:]\n\ntest_idx = int(len(remaining_x)*0.5)\nval_x, test_x = remaining_x[:test_idx], remaining_x[test_idx:]\nval_y, test_y = remaining_y[:test_idx], remaining_y[test_idx:]\n\n## print out the shapes of your resultant feature data\nprint(\"\\t\\t\\tFeature Shapes: \\tLabels Shapes:\")\nprint(\"Train set: \\t\\t{} \\t\\t{}\".format(train_x.shape, train_y.shape), \n \"\\nValidation set: \\t{} \\t\\t{}\".format(val_x.shape, val_y.shape),\n \"\\nTest set: \\t\\t{} \\t\\t{}\".format(test_x.shape, test_y.shape))",
"\t\t\tFeature Shapes: \tLabels Shapes:\nTrain set: \t\t(20000, 200) \t\t(20000,) \nValidation set: \t(2500, 200) \t\t(2500,) \nTest set: \t\t(2500, 200) \t\t(2500,)\n"
]
],
[
[
"**Check your work**\n\nWith train, validation, and test fractions equal to 0.8, 0.1, 0.1, respectively, the final, feature data shapes should look like:\n```\n Feature Shapes:\nTrain set: \t\t (20000, 200) \nValidation set: \t(2500, 200) \nTest set: \t\t (2500, 200)\n```",
"_____no_output_____"
],
[
"---\n## DataLoaders and Batching\n\nAfter creating training, test, and validation data, we can create DataLoaders for this data by following two steps:\n1. Create a known format for accessing our data, using [TensorDataset](https://pytorch.org/docs/stable/data.html#) which takes in an input set of data and a target set of data with the same first dimension, and creates a dataset.\n2. Create DataLoaders and batch our training, validation, and test Tensor datasets.\n\n```\ntrain_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))\ntrain_loader = DataLoader(train_data, batch_size=batch_size)\n```\n\nThis is an alternative to creating a generator function for batching our data into full batches.",
"_____no_output_____"
]
],
[
[
"import torch\nfrom torch.utils.data import TensorDataset, DataLoader\n\n# create Tensor datasets\ntrain_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))\nvalid_data = TensorDataset(torch.from_numpy(val_x), torch.from_numpy(val_y))\ntest_data = TensorDataset(torch.from_numpy(test_x), torch.from_numpy(test_y))\n\n# dataloaders\nbatch_size = 50\n\n# make sure to SHUFFLE your data\ntrain_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)\nvalid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size)\ntest_loader = DataLoader(test_data, shuffle=True, batch_size=batch_size)",
"_____no_output_____"
],
[
"# obtain one batch of training data\ndataiter = iter(train_loader)\nsample_x, sample_y = dataiter.next()\n\nprint('Sample input size: ', sample_x.size()) # batch_size, seq_length\nprint('Sample input: \\n', sample_x)\nprint()\nprint('Sample label size: ', sample_y.size()) # batch_size\nprint('Sample label: \\n', sample_y)",
"Sample input size: torch.Size([50, 200])\nSample input: \n tensor([[ 1, 224, 2, ..., 8522, 10, 1514],\n [ 32, 48, 210, ..., 174, 57, 1],\n [ 0, 0, 0, ..., 11, 233, 580],\n ...,\n [ 0, 0, 0, ..., 5, 41, 798],\n [ 1, 78, 36, ..., 59, 9260, 32],\n [ 11, 20, 14, ..., 2, 841, 4]])\n\nSample label size: torch.Size([50])\nSample label: \n tensor([1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1,\n 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1,\n 0, 1])\n"
]
],
[
[
"---\n# Sentiment Network with PyTorch\n\nBelow is where you'll define the network.\n\n<img src=\"assets/network_diagram.png\" width=40%>\n\nThe layers are as follows:\n1. An [embedding layer](https://pytorch.org/docs/stable/nn.html#embedding) that converts our word tokens (integers) into embeddings of a specific size.\n2. An [LSTM layer](https://pytorch.org/docs/stable/nn.html#lstm) defined by a hidden_state size and number of layers\n3. A fully-connected output layer that maps the LSTM layer outputs to a desired output_size\n4. A sigmoid activation layer which turns all outputs into a value 0-1; return **only the last sigmoid output** as the output of this network.\n\n### The Embedding Layer\n\nWe need to add an [embedding layer](https://pytorch.org/docs/stable/nn.html#embedding) because there are 74000+ words in our vocabulary. It is massively inefficient to one-hot encode that many classes. So, instead of one-hot encoding, we can have an embedding layer and use that layer as a lookup table. You could train an embedding layer using Word2Vec, then load it here. But, it's fine to just make a new layer, using it for only dimensionality reduction, and let the network learn the weights.\n\n\n### The LSTM Layer(s)\n\nWe'll create an [LSTM](https://pytorch.org/docs/stable/nn.html#lstm) to use in our recurrent network, which takes in an input_size, a hidden_dim, a number of layers, a dropout probability (for dropout between multiple layers), and a batch_first parameter.\n\nMost of the time, you're network will have better performance with more layers; between 2-3. Adding more layers allows the network to learn really complex relationships. \n\n> **Exercise:** Complete the `__init__`, `forward`, and `init_hidden` functions for the SentimentRNN model class.\n\nNote: `init_hidden` should initialize the hidden and cell state of an lstm layer to all zeros, and move those state to GPU, if available.",
"_____no_output_____"
]
],
[
[
"# First checking if GPU is available\ntrain_on_gpu=torch.cuda.is_available()\n\nif(train_on_gpu):\n print('Training on GPU.')\nelse:\n print('No GPU available, training on CPU.')",
"Training on GPU.\n"
],
[
"import torch.nn as nn\n\nclass SentimentRNN(nn.Module):\n \"\"\"\n The RNN model that will be used to perform Sentiment analysis.\n \"\"\"\n\n def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):\n \"\"\"\n Initialize the model by setting up the layers.\n \"\"\"\n super(SentimentRNN, self).__init__()\n\n self.output_size = output_size\n self.n_layers = n_layers\n self.hidden_dim = hidden_dim\n \n # define all layers\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, \n dropout=drop_prob, batch_first=True)\n self.dropout = nn.Dropout(drop_prob)\n self.fc = nn.Linear(hidden_dim, output_size)\n self.sigmoid = nn.Sigmoid()\n \n\n def forward(self, x, hidden):\n \"\"\"\n Perform a forward pass of our model on some input and hidden state.\n \"\"\"\n \n batch_size = x.size(0)\n \n # embeddings and lstm_out\n embeds = self.embedding(x)\n lstm_out, hidden = self.lstm(embeds, hidden)\n \n # stack up lstm outputs\n lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)\n \n # dropout and fully-connected layer\n out = self.dropout(lstm_out)\n out = self.fc(out)\n # sigmoid function\n sig_out = self.sigmoid(out)\n \n # reshape to be batch_size first\n sig_out = sig_out.view(batch_size, -1)\n sig_out = sig_out[:, -1] # get last batch of labels\n \n \n # return last sigmoid output and hidden state\n return sig_out, hidden\n \n \n def init_hidden(self, batch_size):\n ''' Initializes hidden state '''\n # Create two new tensors with sizes n_layers x batch_size x hidden_dim,\n # initialized to zero, for hidden state and cell state of LSTM\n weight = next(self.parameters()).data\n \n if (train_on_gpu):\n hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(),\n weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda())\n else:\n hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(),\n weight.new(self.n_layers, batch_size, self.hidden_dim).zero_())\n \n return hidden",
"_____no_output_____"
]
],
[
[
"## Instantiate the network\n\nHere, we'll instantiate the network. First up, defining the hyperparameters.\n\n* `vocab_size`: Size of our vocabulary or the range of values for our input, word tokens.\n* `output_size`: Size of our desired output; the number of class scores we want to output (pos/neg).\n* `embedding_dim`: Number of columns in the embedding lookup table; size of our embeddings.\n* `hidden_dim`: Number of units in the hidden layers of our LSTM cells. Usually larger is better performance wise. Common values are 128, 256, 512, etc.\n* `n_layers`: Number of LSTM layers in the network. Typically between 1-3\n\n> **Exercise:** Define the model hyperparameters.\n",
"_____no_output_____"
]
],
[
[
"# Instantiate the model w/ hyperparams\nvocab_size = len(vocab_to_int)+1 # +1 for the 0 padding + our word tokens\noutput_size = 1\nembedding_dim = 400\nhidden_dim = 256\nn_layers = 2\n\nnet = SentimentRNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers)\n\nprint(net)",
"SentimentRNN(\n (embedding): Embedding(74073, 400)\n (lstm): LSTM(400, 256, num_layers=2, batch_first=True, dropout=0.5)\n (dropout): Dropout(p=0.5)\n (fc): Linear(in_features=256, out_features=1, bias=True)\n (sigmoid): Sigmoid()\n)\n"
]
],
[
[
"---\n## Training\n\nBelow is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. You can also add code to save a model by name.\n\n>We'll also be using a new kind of cross entropy loss, which is designed to work with a single Sigmoid output. [BCELoss](https://pytorch.org/docs/stable/nn.html#bceloss), or **Binary Cross Entropy Loss**, applies cross entropy loss to a single value between 0 and 1.\n\nWe also have some data and training hyparameters:\n\n* `lr`: Learning rate for our optimizer.\n* `epochs`: Number of times to iterate through the training dataset.\n* `clip`: The maximum gradient value to clip at (to prevent exploding gradients).",
"_____no_output_____"
]
],
[
[
"# loss and optimization functions\nlr=0.001\n\ncriterion = nn.BCELoss()\noptimizer = torch.optim.Adam(net.parameters(), lr=lr)",
"_____no_output_____"
],
[
"# training params\n\nepochs = 4 # 3-4 is approx where I noticed the validation loss stop decreasing\n\ncounter = 0\nprint_every = 100\nclip=5 # gradient clipping\n\n# move model to GPU, if available\nif(train_on_gpu):\n net.cuda()\n\nnet.train()\n# train for some number of epochs\nfor e in range(epochs):\n # initialize hidden state\n h = net.init_hidden(batch_size)\n\n # batch loop\n for inputs, labels in train_loader:\n counter += 1\n\n if(train_on_gpu):\n inputs, labels = inputs.cuda(), labels.cuda()\n\n # Creating new variables for the hidden state, otherwise\n # we'd backprop through the entire training history\n h = tuple([each.data for each in h])\n\n # zero accumulated gradients\n net.zero_grad()\n\n # get the output from the model\n output, h = net(inputs, h)\n\n # calculate the loss and perform backprop\n loss = criterion(output.squeeze(), labels.float())\n loss.backward()\n # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.\n nn.utils.clip_grad_norm_(net.parameters(), clip)\n optimizer.step()\n\n # loss stats\n if counter % print_every == 0:\n # Get validation loss\n val_h = net.init_hidden(batch_size)\n val_losses = []\n net.eval()\n for inputs, labels in valid_loader:\n\n # Creating new variables for the hidden state, otherwise\n # we'd backprop through the entire training history\n val_h = tuple([each.data for each in val_h])\n\n if(train_on_gpu):\n inputs, labels = inputs.cuda(), labels.cuda()\n\n output, val_h = net(inputs, val_h)\n val_loss = criterion(output.squeeze(), labels.float())\n\n val_losses.append(val_loss.item())\n\n net.train()\n print(\"Epoch: {}/{}...\".format(e+1, epochs),\n \"Step: {}...\".format(counter),\n \"Loss: {:.6f}...\".format(loss.item()),\n \"Val Loss: {:.6f}\".format(np.mean(val_losses)))",
"Epoch: 1/4... Step: 100... Loss: 0.635234... Val Loss: 0.656715\nEpoch: 1/4... Step: 200... Loss: 0.666213... Val Loss: 0.640142\nEpoch: 1/4... Step: 300... Loss: 0.506314... Val Loss: 0.556882\nEpoch: 1/4... Step: 400... Loss: 0.515226... Val Loss: 0.541775\nEpoch: 2/4... Step: 500... Loss: 0.481418... Val Loss: 0.488891\nEpoch: 2/4... Step: 600... Loss: 0.529370... Val Loss: 0.465098\nEpoch: 2/4... Step: 700... Loss: 0.426508... Val Loss: 0.489485\nEpoch: 2/4... Step: 800... Loss: 0.314929... Val Loss: 0.505303\nEpoch: 3/4... Step: 900... Loss: 0.238121... Val Loss: 0.503732\nEpoch: 3/4... Step: 1000... Loss: 0.269352... Val Loss: 0.478062\nEpoch: 3/4... Step: 1100... Loss: 0.303809... Val Loss: 0.424000\nEpoch: 3/4... Step: 1200... Loss: 0.222771... Val Loss: 0.430880\nEpoch: 4/4... Step: 1300... Loss: 0.201906... Val Loss: 0.511853\nEpoch: 4/4... Step: 1400... Loss: 0.172416... Val Loss: 0.484791\nEpoch: 4/4... Step: 1500... Loss: 0.249004... Val Loss: 0.512710\nEpoch: 4/4... Step: 1600... Loss: 0.220029... Val Loss: 0.538146\n"
]
],
[
[
"---\n## Testing\n\nThere are a few ways to test your network.\n\n* **Test data performance:** First, we'll see how our trained model performs on all of our defined test_data, above. We'll calculate the average loss and accuracy over the test data.\n\n* **Inference on user-generated data:** Second, we'll see if we can input just one example review at a time (without a label), and see what the trained model predicts. Looking at new, user input data like this, and predicting an output label, is called **inference**.",
"_____no_output_____"
]
],
[
[
"# Get test data loss and accuracy\n\ntest_losses = [] # track loss\nnum_correct = 0\n\n# init hidden state\nh = net.init_hidden(batch_size)\n\nnet.eval()\n# iterate over test data\nfor inputs, labels in test_loader:\n\n # Creating new variables for the hidden state, otherwise\n # we'd backprop through the entire training history\n h = tuple([each.data for each in h])\n\n if(train_on_gpu):\n inputs, labels = inputs.cuda(), labels.cuda()\n \n # get predicted outputs\n output, h = net(inputs, h)\n \n # calculate loss\n test_loss = criterion(output.squeeze(), labels.float())\n test_losses.append(test_loss.item())\n \n # convert output probabilities to predicted class (0 or 1)\n pred = torch.round(output.squeeze()) # rounds to the nearest integer\n \n # compare predictions to true label\n correct_tensor = pred.eq(labels.float().view_as(pred))\n correct = np.squeeze(correct_tensor.numpy()) if not train_on_gpu else np.squeeze(correct_tensor.cpu().numpy())\n num_correct += np.sum(correct)\n\n\n# -- stats! -- ##\n# avg test loss\nprint(\"Test loss: {:.3f}\".format(np.mean(test_losses)))\n\n# accuracy over all test data\ntest_acc = num_correct/len(test_loader.dataset)\nprint(\"Test accuracy: {:.3f}\".format(test_acc))",
"Test loss: 0.525\nTest accuracy: 0.811\n"
]
],
[
[
"### Inference on a test review\n\nYou can change this test_review to any text that you want. Read it and think: is it pos or neg? Then see if your model predicts correctly!\n \n> **Exercise:** Write a `predict` function that takes in a trained net, a plain text_review, and a sequence length, and prints out a custom statement for a positive or negative review!\n* You can use any functions that you've already defined or define any helper functions you want to complete `predict`, but it should just take in a trained net, a text review, and a sequence length.\n",
"_____no_output_____"
]
],
[
[
"def predict(net, test_review, seq_length=200):\n ''' Prints out whether a give review is predicted to be \n positive or negative in sentiment, using a trained model.\n \n params:\n net - A trained net \n test_review - a review made of normal text and punctuation\n seq_length - the padded length of a review\n '''\n \n # tokenize review\n test_review = test_review.lower() # lowercase, standardize\n review = ''.join([c for c in test_review if c not in punctuation])\n words = review.split()\n review_ints = []\n review_ints.append([vocab_to_int[word] for word in words])\n \n # pad review \n features = pad_features(review_ints, seq_length)\n \n # convert to tensor\n feature_tensor = torch.from_numpy(features)\n \n # set model to eval\n net.eval()\n \n # initialize hidden state\n batch_size = feature_tensor.size(0)\n h = net.init_hidden(batch_size)\n \n if(train_on_gpu):\n feature_tensor = feature_tensor.cuda()\n \n # get the output from the model\n output, h = net(feature_tensor, h) \n \n # convert output probabilities to predicted class (0 or 1)\n pred = torch.round(output.squeeze()) \n # printing output value, before rounding\n print('Prediction value, pre-rounding: {:.6f}'.format(output.item())) \n \n # print custom response\n if(pred.item()==1):\n print(\"Positive review detected!\")\n else:\n print(\"Negative review detected.\")",
"_____no_output_____"
],
[
"# negative test review\ntest_review_neg = 'The worst movie I have seen; acting was terrible and I want my money back. This movie had bad acting and the dialogue was slow.'\n",
"_____no_output_____"
],
[
"# positive test review\ntest_review_pos = 'This movie had the best acting and the dialogue was so good. I loved it.'\n",
"_____no_output_____"
],
[
"# call function\n# try negative and positive reviews!\nseq_length=200\npredict(net, test_review_pos, seq_length)\npredict(net, test_review_neg, seq_length)",
"Prediction value, pre-rounding: 0.993000\nPositive review detected!\nPrediction value, pre-rounding: 0.005079\nNegative review detected.\n"
]
],
[
[
"### Try out test_reviews of your own!\n\nNow that you have a trained model and a predict function, you can pass in _any_ kind of text and this model will predict whether the text has a positive or negative sentiment. Push this model to its limits and try to find what words it associates with positive or negative.\n\nLater, you'll learn how to deploy a model like this to a production environment so that it can respond to any kind of user data put into a web app!",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e787c7e4be8c7a776e35865c6213e0d3476a5506 | 259,583 | ipynb | Jupyter Notebook | Census_Data.ipynb | ertomz/h4bl-superfund-website | a98d0e48fbd31d6ff334beeec9468e7657f61908 | [
"CC-BY-3.0"
] | 1 | 2021-02-22T01:05:23.000Z | 2021-02-22T01:05:23.000Z | Census_Data.ipynb | ertomz/h4bl-superfund-website | a98d0e48fbd31d6ff334beeec9468e7657f61908 | [
"CC-BY-3.0"
] | null | null | null | Census_Data.ipynb | ertomz/h4bl-superfund-website | a98d0e48fbd31d6ff334beeec9468e7657f61908 | [
"CC-BY-3.0"
] | 2 | 2021-02-22T01:05:39.000Z | 2021-04-28T20:49:41.000Z | 50.102876 | 34,526 | 0.419931 | [
[
[
"<a href=\"https://colab.research.google.com/github/ertomz/h4bl-superfund-website/blob/main/Census_Data.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"from google.colab import files\nuploaded_files = files.upload()",
"_____no_output_____"
],
[
"#reading the file\ncensus = pd.read_excel('2county2019.xlsx')\ncensus.head(5)",
"_____no_output_____"
],
[
"#fixing the names\ncensus['CTYNAME']=census['CTYNAME'].str.replace('County', '')\ncensus['CTYNAME']=census['CTYNAME'].str.replace('Parish', '')\ncensus['CTYNAME']=census['CTYNAME'].str.replace('Census Area', '')\ncensus['CTYNAME']=census['CTYNAME'].str.replace('Burough', '')\ncensus['CTYNAME']=census['CTYNAME'].str.replace('Municipality', '')\ncensus['CTYNAME']=census['CTYNAME'].str.replace('City and Burough', '')\ncensus['CTYNAME']=census['CTYNAME'].str.replace('city', '')\n\n#census['CTYNAME']=census['CTYNAME'].str.split(' ',expand=True)[0:-1].str[:-1]\n\ncensus['CTYNAME']=census['CTYNAME'].str.strip(' ')\ncensus.head(5)",
"_____no_output_____"
],
[
"census['CountyState']= census['CTYNAME'].str.cat(census['STNAME'], sep =\", \") \ncensus",
"_____no_output_____"
],
[
"#percentage of counties with >50% male or >50% female\nfem_census = census['BFEM?'].value_counts(\"FEM\")\nfem_census",
"_____no_output_____"
],
[
"from google.colab import files\nuploaded_files = files.upload()",
"_____no_output_____"
],
[
"#superfund data\nsuperfunds = pd.read_csv(\"superfunds.csv\")\nsuperfunds.head(5)",
"_____no_output_____"
],
[
"active = superfunds[superfunds[\"Status\"] == \"NPL Site\"].shape\nproposed = superfunds[superfunds[\"Status\"] == \"Deleted NPL Site\"].shape\ndeleted = superfunds[superfunds[\"Status\"] == \"Proposed NPL Site\"].shape\n\n(active, proposed, deleted)",
"_____no_output_____"
],
[
"superfunds['CountyState']= superfunds['County'].str.cat(superfunds['State'], sep =\", \") \nsuperfunds.head(5)",
"_____no_output_____"
],
[
"superfunds_series = superfunds.set_index('CountyState').squeeze()\nsuperfunds_series.head(5) ",
"_____no_output_____"
],
[
"census_nodrop = census",
"_____no_output_____"
],
[
"#counties with >13% black population\nblack_census = census[census[\"BAC_PER\"] > 13]\nblack_census",
"_____no_output_____"
],
[
"#number of counties with >50% male or >50% female given >13% black population\nblack_fem_census1 = black_census['BFEM?'].value_counts()\nblack_fem_census1",
"_____no_output_____"
],
[
"#percentage of counties with >50% male or >50% female given >13% black population\nblack_fem_census2 = black_census['BFEM?'].value_counts(\"FEM\")\nblack_fem_census2",
"_____no_output_____"
],
[
"black_census_series = black_census.set_index('CountyState').squeeze()\nblack_census_series",
"_____no_output_____"
],
[
"nodrop_series = census_nodrop.set_index('CountyState').squeeze()\nnodrop_series",
"_____no_output_____"
],
[
"superfund_and_blackcensus = black_census_series.join(superfunds_series)\n\n#remove any counties that aren't in the superfund dataset\nsuperfund_and_blackcensus = superfund_and_blackcensus[superfund_and_blackcensus['Site Score'].notna()]\nsuperfund_and_blackcensus.head(5)",
"_____no_output_____"
],
[
"superfund_and_nodrop = nodrop_series.join(superfunds_series)\n\n#remove any counties that aren't in the superfund dataset\nsuperfund_and_nodrop = superfund_and_nodrop[superfund_and_nodrop['Site Score'].notna()]\nsuperfund_and_nodrop.head(200)",
"_____no_output_____"
],
[
"#number of counties with >50% male or >50% female given >13% black population and superfund site\nsex1 = superfund_and_blackcensus['BFEM?'].value_counts()\nsex1",
"_____no_output_____"
],
[
"#number of counties with >50% male or >50% female given >13% black population and superfund site\nsex1 = superfund_and_blackcensus['BFEM?'].value_counts()\nsex1",
"_____no_output_____"
],
[
"#percentage of counties with >50% male or >50% female given >13% black population and superfund site\nsex2 = superfund_and_blackcensus['BFEM?'].value_counts('FEM')\nsex2",
"_____no_output_____"
],
[
"superfund_and_nodrop['nonBI'] = superfund_and_nodrop['BAC_PER'] + superfund_and_nodrop['IAC_PER']\nsuperfund_and_nodrop",
"_____no_output_____"
],
[
"plt.scatter(superfund_and_nodrop['nonBI'], superfund_and_nodrop['Site Score'], c='green', s=2, label=\"non Black or Indigenious\")\nplt.scatter(superfund_and_nodrop['BAC_PER'], superfund_and_nodrop['Site Score'], c='black', s=2, label=\"Black\")\nplt.scatter(superfund_and_nodrop['IAC_PER'], superfund_and_nodrop['Site Score'], c='brown', s=2, label=\"Indigenious\")\nplt.xlabel(\"% of residents\")\nplt.ylabel(\"superfund site score\")\nplt.figure()\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e787cd215425cccc50785a691d99358d95ee7ce9 | 18,872 | ipynb | Jupyter Notebook | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh | fd6d2d749f40fee46bee749ff868212bf117a747 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh | fd6d2d749f40fee46bee749ff868212bf117a747 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | notebooks/twitter-import.ipynb | jacob-heglund/socialsensing-jh | fd6d2d749f40fee46bee749ff868212bf117a747 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | 55.020408 | 1,693 | 0.646566 | [
[
[
"# Notebook for importing twitter data for hurricane sandy.\n\nThe twitter dataset is from mdredze.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport sys\nimport os\nsys.path.append(os.path.abspath('../'))\n\nimport pandas as pd\nimport pymongo\nimport twitterinfrastructure.twitter_sandy as ts\nimport importlib\nimportlib.reload(ts)\n\n#os.chdir('../')\nprint(os.getcwd())",
"C:\\dev\\research\\socialsensing\\notebooks\n"
]
],
[
[
"## Hydrate tweet IDs into tweets using Hydrator.\n1. Run the following cell to convert the raw mdredze sandy tweet ids file into an interim file of tweet ids in the format necessary to hydrate using Hydrator.\n1. Use [Hydrator](https://github.com/DocNow/hydrator) to hydrate the \"data/interim/sandy-tweetids.txt\" file. Hydrating on 03-14-2018 created a 13.3 GB json file with ??? tweets.",
"_____no_output_____"
]
],
[
[
"# create interim file with only tweet ids for hydration using Hydrator \n# (6,554,744 tweet ids, 124.5 MB)\n# takes ~1 min (3.1 GHz Intel Core i7, 16 GB 1867 MHz DDR3)\npath = \"data/raw/release-mdredze.txt\"\nwrite_path = \"data/interim/sandy-tweetids.txt\"\nnum_tweets = ts.create_hydrator_tweetids(path=path, write_path=write_path, \n filter_sandy=False, progressbar=False, verbose=1)",
"2019-05-02 13:30:54 : Started converting tweet ids from data/raw/release-mdredze.txt to Hydrator format.\n\n"
]
],
[
[
"## Import hydrated tweets into mongodb database.",
"_____no_output_____"
]
],
[
[
"# import tweets (4799665 tweets out of 4799665 lines, 12.2 GB total doc size)\n# takes ~ 40 mins (3.1 GHz Intel Core i7, 16 GB 1867 MHz DDR3)\n# path = 'data/processed/sandy-tweets-20180314.json'\npath = 'E:/Work/projects/twitterinfrastructure/data/processed/sandy-tweets-20180314.json'\ncollection = 'tweets'\ndb_name = 'sandy'\ndb_instance = 'mongodb://localhost:27017/'\n\ninsert_num = ts.insert_tweets(path, collection=collection, db_name=db_name, \n db_instance=db_instance, progressbar=True,\n overwrite=True, verbose=1)\n",
"2019-05-02 13:18:14 : Started inserting tweets from \"E:/Work/projects/twitterinfrastructure/data/processed/sandy-tweets-20180314.json\" to tweets collection in sandy database.\n\n2019-05-02 13:18:14 : Dropped tweets collection (if exists).\n\n"
]
],
[
[
"## Import taxi_zones GeoJSON into mongodb database.\n\n1. Open terminal.\n1. Change to the twitterinfrastructure project home directory. For example, run the following (based on my directory structure):\n\n\t$ cd Documents/projects/twitterinfrastructure\n\n1. Use mongoimport to import the taxi_zones_crs4326_mod.geojson into the database by running the following in terminal (not mongodb shell). Be aware of double dash lines in front of db, collection, file, and jsonArray arguments).\n\n\t$ mongoimport --db sandy --collection taxi_zones --file \"data/processed/taxi_zones_crs4326_mod.geojson\" --jsonArray\n\n1. Run the following cell to create a geosphere index in the taxi_zones collection.",
"_____no_output_____"
]
],
[
[
"# create geosphere index in taxi_zones collection\ndb_instance = 'mongodb://localhost:27017/'\ndb_name = 'sandy'\nzones_collection = 'taxi_zones'\n#db_name = 'sandy_test'\n#zones_collection = 'taxi_zones_test'\nclient = pymongo.MongoClient(db_instance)\ndb = client[db_name]\ndb[zones_collection].create_index([(\"geometry\", pymongo.GEOSPHERE)])\n\nzones = db[zones_collection].find()\nprint('{count} taxi zones found in imported taxi_zones GeoJSON file.'.format(\n count=zones.count()))",
"263 taxi zones found in imported taxi_zones GeoJSON file.\n"
]
],
[
[
"## Import nyiso_zones GeoJSON into mongodb database.\n\n1. Open terminal.\n1. Change to the twitterinfrastructure project home directory. For example, run the following (based on my directory structure):\n\n\t$ cd Documents/projects/twitterinfrastructure\n\n1. Use mongoimport to import the 'nyiso-zones-crs4326-mod.geojson' file into the database by running the following in terminal (not mongodb shell). Be aware of double dash lines in front of db, collection, file, and jsonArray arguments. Make sure you delete any existing nyiso_zones collection in the database (the command will append, not overwrite).\n\n\tThis geojson was created by manually querying and copying nyiso zone geojsons from [here](https://services1.arcgis.com/Lsfphzk53dXVltQC/arcgis/rest/services/NYISO_Zones/FeatureServer/0/query?outFields=*&where=1%3D1) (linked from [here](https://hub.arcgis.com/items/3a510da542c74537b268657f63dc2ce4)) to the 'data/raw/nyiso/' directory. Those individual zone geojsons were then combined into the 'nyiso.geojson' file and loaded into qgis3 (version 3.2, using the 'Add Vector Layer' option, individual zones were visualized by adjusting symbology of the layer properties to be categorized). The layer was then exported to a geojson file using qgis3 (with the EPSG:4326 crs).\n\n\t$ mongoimport --db sandy --collection nyiso_zones --file \"data/processed/nyiso-zones-crs4326-mod.geojson\" --jsonArray\n\n1. Run the following cell to create a geosphere index in the nyiso_zones collection and add the properties.zone_id field to each zone in the collection.",
"_____no_output_____"
]
],
[
[
"# create geosphere index in nyiso_zones collection\ndb_instance = 'mongodb://localhost:27017/'\ndb_name = 'sandy'\nzones_collection = 'nyiso_zones'\nclient = pymongo.MongoClient(db_instance)\ndb = client[db_name]\ndb[zones_collection].create_index([(\"geometry\", pymongo.GEOSPHERE)])\nzones = db[zones_collection].find()\nprint('{count} nyiso zones found in imported nyiso_zones GeoJSON file.'.format(\n count=zones.count()))\n\n# add zone_id to nyiso_zones collection\nzones_path = 'data/raw/nyiso/nyiso-zones.csv'\ndf = pd.read_csv(zones_path)\nfor abbrev, zone_id in zip(df['abbrev'], df['zone_id']):\n db[zones_collection].update_one(\n {\"properties.Zone\": abbrev},\n {\"$set\": {\"properties.zone_id\": zone_id}}\n )",
"11 nyiso zones found in imported nyiso_zones GeoJSON file.\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e787d42d0f34f25b921312e5ac7277d13427243b | 59,117 | ipynb | Jupyter Notebook | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn | c482b1e84496279935b5bb2cfc1e6d78e2868c63 | [
"Apache-2.0"
] | null | null | null | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn | c482b1e84496279935b5bb2cfc1e6d78e2868c63 | [
"Apache-2.0"
] | null | null | null | DeepLearning/pytorch/cifar10_tutorial.ipynb | MikoyChinese/learn | c482b1e84496279935b5bb2cfc1e6d78e2868c63 | [
"Apache-2.0"
] | null | null | null | 117.063366 | 23,088 | 0.862375 | [
[
[
"import torch\nimport torchvision\nimport torchvision.transforms as transforms",
"_____no_output_____"
],
[
"data_dir = '/home/commaai-03/Data/dataset/torch/'",
"_____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.CIFAR10(root=data_dir, train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root=data_dir, train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')",
"Using downloaded and verified file: /home/commaai-03/Data/dataset/torch/cifar-10-python.tar.gz\nExtracting /home/commaai-03/Data/dataset/torch/cifar-10-python.tar.gz to /home/commaai-03/Data/dataset/torch/\nFiles already downloaded and verified\n"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\n\n# Function to show an image.\n\ndef imshow(img):\n img = img /2 + 0.5\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n \n\n# get some random training images\ndataiter = iter(trainloader)\nimages, labels = dataiter.next()\n\nimshow(torchvision.utils.make_grid(images))\nprint(' '.join('%5s' % classes[labels[j]] for j in range(4)))",
"_____no_output_____"
]
],
[
[
"#### Define a Convolutional Neural Network\n\nCopy the neural network from the Neural Networks section before and modify it to take 3-channel images (instead of 1-channel images as it was defined).",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n \n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n \n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5) # reshape\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n \nnet = Net()",
"_____no_output_____"
]
],
[
[
"#### Define a Loss function and optimizer\n\nLet's use a Classification Cross-Entropy loss and SGD with momentum.",
"_____no_output_____"
]
],
[
[
"import torch.optim as optim\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=1e-3, momentum=0.9)",
"_____no_output_____"
]
],
[
[
"#### Train the network\n\nThis is when things start to get interesting. We simply have to loop over our data iterator, and feed the inputs to the network and optimize.",
"_____no_output_____"
]
],
[
[
"for epoch in range(2): # loop over the dataset multiple times\n \n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n # get the inputs; data is list of [inputs, labels]\n inputs, labels = data\n \n # zero the parameters gradients\n optimizer.zero_grad()\n \n # Forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n \n # print statistics\n running_loss += loss.item()\n if i % 2000 == 1999:\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n \nprint('Finished Training.')",
"[1, 2000] loss: 2.172\n[1, 4000] loss: 1.828\n[1, 6000] loss: 1.685\n[1, 8000] loss: 1.598\n[1, 10000] loss: 1.541\n[1, 12000] loss: 1.503\n[2, 2000] loss: 1.445\n[2, 4000] loss: 1.384\n[2, 6000] loss: 1.343\n[2, 8000] loss: 1.326\n[2, 10000] loss: 1.305\n[2, 12000] loss: 1.273\nFinished Training.\n"
],
[
"# save trained model:\nPATH = data_dir + 'cifar_net.pth'\ntorch.save(net.state_dict(), PATH)",
"_____no_output_____"
]
],
[
[
"#### Test the network on the test data\n\nWe have trained the network for 2 passes over the training dataset. But we need to check if the network has learnt anything at all.\n\nWe will check this by predicting the class label that the neural network outputs, and checking it against the ground-truth. If the prediction is correct, we add the sample to the list of correct predictions.\n\nOkay, first step. Let us display an image from the test set to get familiar.",
"_____no_output_____"
]
],
[
[
"dataiter = iter(testloader)\nimages, labels = dataiter.next()\n\n# print images\nimshow(torchvision.utils.make_grid(images))\nprint('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))",
"_____no_output_____"
],
[
"# Load pre-train model\nnet = Net()\nnet.load_state_dict(torch.load(PATH))\n\noutputs = net(images)\n\n_, predicted = torch.max(outputs, 1)\n\nprint('Predicted: ', ' '.join('%5s' % classes[predicted[j]]\n for j in range(4)))",
"Predicted: cat ship car plane\n"
],
[
"correct = 0\ntotal = 0\nwith torch.no_grad():\n for data in testloader:\n images, labels = data\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Accuracy of the network on the 10000 test images: %d %%' % (\n 100 * correct / total))",
"Accuracy of the network on the 10000 test images: 53 %\n"
],
[
"# show the predict accuracy of each class\n\nclass_correct = list(0. for i in range(10))\nclass_total = list(0. for i in range(10))\nwith torch.no_grad():\n for data in testloader:\n images, labels = data\n outputs = net(images)\n _, predicted = torch.max(outputs, 1)\n c = (predicted == labels).squeeze()\n for i in range(4):\n label = labels[i]\n class_correct[label] += c[i].item()\n class_total[label] += 1\n\n\nfor i in range(10):\n print('Accuracy of %5s : %2d %%' % (\n classes[i], 100 * class_correct[i] / class_total[i]))",
"Accuracy of plane : 56 %\nAccuracy of car : 57 %\nAccuracy of bird : 40 %\nAccuracy of cat : 55 %\nAccuracy of deer : 45 %\nAccuracy of dog : 24 %\nAccuracy of frog : 51 %\nAccuracy of horse : 60 %\nAccuracy of ship : 73 %\nAccuracy of truck : 69 %\n"
]
],
[
[
"#### Training on GPU\n\nJust like how you transfer a Tensor onto the GPU, you transfer the neural net onto the GPU.\n\nLet’s first define our device as the first visible cuda device if we have CUDA available:",
"_____no_output_____"
]
],
[
[
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# Assuming that we are on a CUDA machine, this should print a CUDA device:\n\nprint(device)",
"cuda:0\n"
],
[
"correct = 0\ntotal = 0\n\nnet.to(device)\n\nwith torch.no_grad():\n for data in testloader:\n images, labels = data[0].to(device), data[1].to(device)\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Accuracy of the network on the 10000 test images: %d %%' % (\n 100 * correct / total))",
"Accuracy of the network on the 10000 test images: 53 %\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e787d7213f6e2a187383cceab9075978848c65c2 | 13,934 | ipynb | Jupyter Notebook | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n | 8b24263ca37dbf5cb4b0c15070a3d32c7284729d | [
"Apache-2.0"
] | 1 | 2020-08-05T05:52:57.000Z | 2020-08-05T05:52:57.000Z | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n | 8b24263ca37dbf5cb4b0c15070a3d32c7284729d | [
"Apache-2.0"
] | null | null | null | site/ko/tutorials/generative/adversarial_fgsm.ipynb | gmb-ftcont/docs-l10n | 8b24263ca37dbf5cb4b0c15070a3d32c7284729d | [
"Apache-2.0"
] | null | null | null | 35.545918 | 418 | 0.529999 | [
[
[
"##### Copyright 2019 The TensorFlow Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");",
"_____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_____"
]
],
[
[
"# FGSM을 이용한 적대적 샘플 생성\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/generative/adversarial_fgsm\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />TensorFlow.org에서 보기</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/tutorials/generative/adversarial_fgsm.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />구글 코랩(Colab)에서 실행하기</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/ko/tutorials/generative/adversarial_fgsm.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />깃허브(GitHub) 소스 보기</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/tutorials/generative/adversarial_fgsm.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도\n불구하고 [공식 영문 문서](https://www.tensorflow.org/?hl=en)의 내용과 일치하지 않을 수 있습니다.\n이 번역에 개선할 부분이 있다면\n[tensorflow/docs-l10n](https://github.com/tensorflow/docs-l10n/) 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다.\n문서 번역이나 리뷰에 참여하려면\n[[email protected]](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)로\n메일을 보내주시기 바랍니다.",
"_____no_output_____"
],
[
"이 튜토리얼에서는 Ian Goodfellow *et al*의 [Explaining and Harnessing Adversarial Examples](https://arxiv.org/abs/1412.6572)에 기술된 FGSM(Fast Gradient Signed Method)을 이용해 적대적 샘플(adversarial example)을 생성하는 방법에 대해 소개합니다. FGSM은 신경망 공격 기술들 중 초기에 발견된 방법이자 가장 유명한 방식 중 하나입니다.\n\n## 적대적 샘플이란?\n\n적대적 샘플이란 신경망을 혼란시킬 목적으로 만들어진 특수한 입력으로, 신경망으로 하여금 샘플을 잘못 분류하도록 합니다. 비록 인간에게 적대적 샘플은 일반 샘플과 큰 차이가 없어보이지만, 신경망은 적대적 샘플을 올바르게 식별하지 못합니다. 이와 같은 신경망 공격에는 여러 종류가 있는데, 본 튜토리얼에서는 화이트 박스(white box) 공격 기술에 속하는 FGSM을 소개합니다. 화이트 박스 공격이란 공격자가 대상 모델의 모든 파라미터값에 접근할 수 있다는 가정 하에 이루어지는 공격을 일컫습니다. 아래 이미지는 Goodfellow et al에 소개된 가장 유명한 적대적 샘플인 판다의 사진입니다.\n\n\n\n원본 이미지에 특정한 작은 왜곡을 추가하면 신경망으로 하여금 판다를 높은 신뢰도로 긴팔 원숭이로 잘못 인식하도록 만들 수 있습니다. 이하 섹션에서는 이 왜곡 추가 과정에 대해 살펴보도록 하겠습니다.\n\n## FGSM\nFGSM은 신경망의 그래디언트(gradient)를 이용해 적대적 샘플을 생성하는 기법입니다. 만약 모델의 입력이 이미지라면, 입력 이미지에 대한 손실 함수의 그래디언트를 계산하여 그 손실을 최대화하는 이미지를 생성합니다. 이처럼 새롭게 생성된 이미지를 적대적 이미지(adversarial image)라고 합니다. 이 과정은 다음과 같은 수식으로 정리할 수 있습니다:\n\n$$adv\\_x = x + \\epsilon*\\text{sign}(\\nabla_xJ(\\theta, x, y))$$\n\n각 기호에 대한 설명은 다음과 같습니다.\n\n* adv_x : 적대적 이미지.\n* x : 원본 입력 이미지.\n* y : 원본 입력 레이블(label).\n* $\\epsilon$ : 왜곡의 양을 적게 만들기 위해 곱하는 수.\n* $\\theta$ : 모델의 파라미터.\n* $J$ : 손실 함수.\n\n여기서 흥미로운 사실은 입력 이미지에 대한 그래디언트가 사용된다는 점입니다. 이는 손실을 최대화하는 이미지를 생성하는 것이 FGSM의 목적이기 때문입니다. 요약하자면, 적대적 샘플은 각 픽셀의 손실에 대한 기여도를 그래디언트를 통해 계산한 후, 그 기여도에 따라 픽셀값에 왜곡을 추가함으로써 생성할 수 있습니다. 각 픽셀의 기여도는 연쇄 법칙(chain rule)을 이용해 그래디언트를 계산하는 것으로 빠르게 파악할 수 있습니다. 이것이 입력 이미지에 대한 그래디언트가 쓰이는 이유입니다. 또한, 대상 모델은 더 이상 학습하고 있지 않기 때문에 (따라서 신경망의 가중치에 대한 그래디언트는 필요하지 않습니다) 모델의 가중치값은 변하지 않습니다. FGSM의 궁극적인 목표는 이미 학습을 마친 상태의 모델을 혼란시키는 것입니다.\n\n이제 사전 훈련된 모델을 공격해보도록 하겠습니다. 이 튜토리얼에서 사용될 모델은 [ImageNet](http://www.image-net.org/)에서 사전 훈련된 [MobileNetV2](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/applications/MobileNetV2) 모델입니다.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nmpl.rcParams['figure.figsize'] = (8, 8)\nmpl.rcParams['axes.grid'] = False",
"_____no_output_____"
]
],
[
[
"사전 훈련된 MobileNetV2 모델과 ImageNet의 클래스(class) 이름들을 불러옵니다.",
"_____no_output_____"
]
],
[
[
"pretrained_model = tf.keras.applications.MobileNetV2(include_top=True,\n weights='imagenet')\npretrained_model.trainable = False\n\n# ImageNet 클래스 레이블\ndecode_predictions = tf.keras.applications.mobilenet_v2.decode_predictions",
"_____no_output_____"
],
[
"# 이미지가 MobileNetV2에 전달될 수 있도록 전처리해주는 헬퍼 메서드(helper function)\ndef preprocess(image):\n image = tf.cast(image, tf.float32)\n image = image/255\n image = tf.image.resize(image, (224, 224))\n image = image[None, ...]\n return image\n\n# 확률 벡터에서 레이블을 추출해주는 헬퍼 메서드\ndef get_imagenet_label(probs):\n return decode_predictions(probs, top=1)[0][0]",
"_____no_output_____"
]
],
[
[
"## 원본 이미지\nMirko [CC-BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/)의 [래브라도 리트리버](https://commons.wikimedia.org/wiki/File:YellowLabradorLooking_new.jpg) 샘플 이미지를 이용해 적대적 샘플을 생성합니다. 첫 단계로, 원본 이미지를 전처리하여 MobileNetV2 모델에 입력으로 제공합니다.",
"_____no_output_____"
]
],
[
[
"image_path = tf.keras.utils.get_file('YellowLabradorLooking_new.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg')\nimage_raw = tf.io.read_file(image_path)\nimage = tf.image.decode_image(image_raw)\n\nimage = preprocess(image)\nimage_probs = pretrained_model.predict(image)",
"_____no_output_____"
]
],
[
[
"이미지를 살펴봅시다.",
"_____no_output_____"
]
],
[
[
"plt.figure()\nplt.imshow(image[0])\n_, image_class, class_confidence = get_imagenet_label(image_probs)\nplt.title('{} : {:.2f}% Confidence'.format(image_class, class_confidence*100))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 적대적 이미지 생성하기\n\n### FGSM 실행하기\n첫번째 단계는 샘플 생성을 위해 원본 이미지에 가하게 될 왜곡을 생성하는 것입니다. 앞서 살펴보았듯이, 왜곡을 생성할 때에는 입력 이미지에 대한 그래디언트를 사용합니다.",
"_____no_output_____"
]
],
[
[
"loss_object = tf.keras.losses.CategoricalCrossentropy()\n\ndef create_adversarial_pattern(input_image, input_label):\n with tf.GradientTape() as tape:\n tape.watch(input_image)\n prediction = pretrained_model(input_image)\n loss = loss_object(input_label, prediction)\n\n # 입력 이미지에 대한 손실 함수의 기울기를 구합니다.\n gradient = tape.gradient(loss, input_image)\n # 왜곡을 생성하기 위해 그래디언트의 부호를 구합니다.\n signed_grad = tf.sign(gradient)\n return signed_grad",
"_____no_output_____"
]
],
[
[
"생성한 왜곡을 시각화해 볼 수 있습니다.",
"_____no_output_____"
]
],
[
[
"# 이미지의 레이블을 원-핫 인코딩 처리합니다.\nlabrador_retriever_index = 208\nlabel = tf.one_hot(labrador_retriever_index, image_probs.shape[-1])\nlabel = tf.reshape(label, (1, image_probs.shape[-1]))\n\nperturbations = create_adversarial_pattern(image, label)\nplt.imshow(perturbations[0])",
"_____no_output_____"
]
],
[
[
"왜곡 승수 엡실론(epsilon)을 바꿔가며 다양한 값들을 시도해봅시다. 위의 간단한 실험을 통해 엡실론의 값이 커질수록 네트워크를 혼란시키는 것이 쉬워짐을 알 수 있습니다. 하지만 이는 이미지의 왜곡이 점점 더 뚜렷해진다는 단점을 동반합니다.",
"_____no_output_____"
]
],
[
[
"def display_images(image, description):\n _, label, confidence = get_imagenet_label(pretrained_model.predict(image))\n plt.figure()\n plt.imshow(image[0])\n plt.title('{} \\n {} : {:.2f}% Confidence'.format(description,\n label, confidence*100))\n plt.show()",
"_____no_output_____"
],
[
"epsilons = [0, 0.01, 0.1, 0.15]\ndescriptions = [('Epsilon = {:0.3f}'.format(eps) if eps else 'Input')\n for eps in epsilons]\n\nfor i, eps in enumerate(epsilons):\n adv_x = image + eps*perturbations\n adv_x = tf.clip_by_value(adv_x, 0, 1)\n display_images(adv_x, descriptions[i])",
"_____no_output_____"
]
],
[
[
"## 다음 단계\n\n이 튜토리얼에서 적대적 공격에 대해서 알아보았으니, 이제는 이 기법을 다양한 데이터넷과 신경망 구조에 시험해볼 차례입니다. 새로 만든 모델에 FGSM을 시도해보는 것도 가능할 것입니다. 엡실론 값을 바꿔가며 신경망의 샘플 신뢰도가 어떻게 변하는지 살펴볼 수도 있습니다.\n\nFGSM은 그 자체로도 강력한 기법이지만 이후 다른 연구들에서 발견된 보다 더 효과적인 적대적 공격 기술들의 시작점에 불과합니다. 또한, FGSM의 발견은 적대적 공격 뿐만 아니라 더 견고한 기계 학습 모델을 만들기 위한 방어 기술에 대한 연구도 촉진시켰습니다. 적대적 공격과 방어 기술에 대한 전반적인 조망은 이 [문헌](https://arxiv.org/abs/1810.00069)에서 볼 수 있습니다.\n\n다양한 적대적 공격과 방어 기술의 구현 방법이 궁금하다면, 적대적 샘플 라이브러리 [CleverHans](https://github.com/tensorflow/cleverhans)를 참고합니다.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e787d78eff770a45e01cfc46e21c9032983f0078 | 72,935 | ipynb | Jupyter Notebook | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron | da07a6c780c59ca3e6e785cb9e742ce4a9953965 | [
"MIT"
] | null | null | null | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron | da07a6c780c59ca3e6e785cb9e742ce4a9953965 | [
"MIT"
] | null | null | null | HG-GAN-Geometry.ipynb | RoozbehFarhoodi/McNeuron | da07a6c780c59ca3e6e785cb9e742ce4a9953965 | [
"MIT"
] | 1 | 2020-11-02T18:11:45.000Z | 2020-11-02T18:11:45.000Z | 72.935 | 32,582 | 0.741276 | [
[
[
"## plotting a neuron",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport McNeuron\nimport data_transforms\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Reshape\nfrom keras.layers.recurrent import LSTM\n\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nimport os\n\nfrom numpy import linalg as LA\n\n%matplotlib inline",
"_____no_output_____"
],
[
"import scipy.io\nmat = scipy.io.loadmat(\"/Volumes/Arch/Dropbox/HG-GAN/03-Data/Matlab format/part 1.mat\")\n#mat = scipy.io.loadmat(\"/Volumes/Arch/Dropbox/HG-GAN/03-Data/Matlab format/sample.mat\")\nmat.keys()",
"_____no_output_____"
],
[
"tmp = mat['neuron_data'][186][3]\n#tmp = mat['N']\nneuron = data_transforms.swc_to_neuron(tmp)",
"_____no_output_____"
],
[
"tmp = mat['neuron_data'][186][3]\n#tmp = mat['N']\nneuron = data_transforms.swc_to_neuron(tmp)\nneuron2 = data_transforms.downsample_neuron(neuron, number = 20)\nMcNeuron.visualize.plot_2D(neuron2 ,size = 4)",
"_____no_output_____"
],
[
"McNeuron.visualize.plot_2D(neuron ,size = 4)",
"_____no_output_____"
],
[
"L = []\nfor i in range(185):\n tmp = mat['neuron_data'][i][3]\n#tmp = mat['N']\n neuron = data_transforms.swc_to_neuron(tmp)\n neuron2 = data_transforms.downsample_neuron(neuron, number = 20)\n print i\n L.append(neuron2)",
"_____no_output_____"
],
[
"L",
"_____no_output_____"
],
[
"n = neuron.mesoscale_subsample(150)\n#n = neuron.subsample_main_nodes()\nMcNeuron.visualize.plot_2D(n ,size = 4)\nprint n.n_node",
"_____no_output_____"
],
[
"McNeuron.visualize.plot_2D(neuron ,size = 4)",
"_____no_output_____"
]
],
[
[
"#### Subsampling methods",
"_____no_output_____"
]
],
[
[
"# self is neuron!\ndef get_main_points(self):\n \"\"\"\n gets the index of branching points and end points.\n \"\"\"\n (branch_index,) = np.where(self.branch_order[self.n_soma:]==2)\n (endpoint_index,) = np.where(self.branch_order[self.n_soma:]==0)\n selected_index = np.union1d(branch_index + self.n_soma, endpoint_index + self.n_soma)\n selected_index = np.append(range(self.n_soma), selected_index)\n return selected_index\n\ndef parent_id(self, selected_index):\n \"\"\"\n Gives back the parent id of all the selected_index of the neuron. \n Parameters\n ----------\n selected_index: numpy array\n the index of nodes\n Returns\n -------\n parent_id: the index of parent of each element in selected_index in this array.\n \"\"\"\n parent_id = np.array([],dtype = int)\n for i in selected_index:\n p = self.parent_index[i]\n while(~np.any(selected_index == p)):\n p = self.parent_index[p]\n (ind,) = np.where(selected_index==p)\n parent_id = np.append(parent_id , ind) \n return parent_id\n\ndef neuron_with_selected_nodes(self, selected_index):\n \"\"\"\n Gives back a new neuron made up with the selected_index nodes of self.\n if node A is parent (or grand parent) of node B in the original neuron, it is the same for the new neuron.\n Parameters\n ----------\n selected_index: numpy array\n the index of nodes from original neuron for making new neuron\n Returns\n -------\n Neuron: the subsampled neuron\n \"\"\"\n parent = parent_id(self, selected_index)\n # making the list of nodes\n n_list = []\n for i in range(selected_index.shape[0]):\n n = McNeuron.Node()\n n.xyz = self.nodes_list[selected_index[i]].xyz\n n.r = self.nodes_list[selected_index[i]].r\n n.type = self.nodes_list[selected_index[i]].type\n n_list.append(n)\n # adjusting the childern and parents for the nodes.\n for i in np.arange(1,selected_index.shape[0]):\n j = parent[i]\n n_list[i].parent = n_list[j]\n n_list[j].add_child(n_list[i])\n return McNeuron.Neuron(file_format = 'only list of nodes', input_file = n_list)\n\ndef find_sharpest_fork(self, Nodes):\n \"\"\"\n Looks at the all branching point in the Nodes list, selects those which both its children are end points and finds\n the closest pair of childern (the distance between children).\n Parameters\n ----------\n Nodes: list\n the list of Node\n \n Returns\n -------\n sharpest_pair: array\n the index of the pair of closest pair of childern\n distance: float\n Distance of the pair of children\n \"\"\"\n pair_list = []\n Dis = np.array([])\n for n in Nodes: \n if n.parent is not None:\n if n.parent.parent is not None:\n a = n.parent.children\n if(isinstance(a, list)):\n if(len(a)==2):\n n1 = a[0]\n n2 = a[1]\n if(len(n1.children) == 0 and len(n2.children) == 0):\n pair_list.append([n1 , n2])\n dis = LA.norm(a[0].xyz - a[1].xyz,2)\n Dis = np.append(Dis,dis)\n if(len(Dis)!= 0):\n (b,) = np.where(Dis == Dis.min())\n sharpest_pair = pair_list[b[0]]\n distance = Dis.min()\n else:\n sharpest_pair = [0,0]\n distance = 0.\n return sharpest_pair, distance\n\ndef find_sharpest_fork_general(self, Nodes):\n \"\"\"\n Looks at the all branching point in the Nodes list, selects those which both its children are end points and finds\n the closest pair of childern (the distance between children).\n Parameters\n ----------\n Nodes: list\n the list of Node\n \n Returns\n -------\n sharpest_pair: array\n the index of the pair of closest pair of childern\n distance: float\n Distance of the pair of children\n \"\"\"\n pair_list = []\n Dis = np.array([])\n for n in Nodes: \n if n.parent is not None:\n if n.parent.parent is not None:\n a = n.parent.children\n if(isinstance(a, list)):\n if(len(a)==2):\n n1 = a[0]\n n2 = a[1]\n pair_list.append([n1 , n2])\n dis = LA.norm(a[0].xyz - a[1].xyz,2)\n Dis = np.append(Dis,dis)\n if(len(Dis)!= 0):\n (b,) = np.where(Dis == Dis.min())\n sharpest_pair = pair_list[b[0]]\n distance = Dis.min()\n else:\n sharpest_pair = [0,0]\n distance = 0.\n return sharpest_pair, distance\n\ndef remove_pair_replace_node(self, Nodes, pair):\n \"\"\"\n Removes the pair of nodes and replace it with a new node. the parent of new node is the parent of the pair of node,\n and its location and its radius are the mean of removed nodes.\n Parameters\n ----------\n Nodes: list\n the list of Nodes\n \n pair: array\n The index of pair of nodes. the nodes should be end points and have the same parent.\n \n Returns\n -------\n The new list of Nodes which the pair are removed and a mean node is replaced.\n \"\"\"\n \n par = pair[0].parent\n loc = pair[0].xyz + pair[1].xyz\n loc = loc/2\n r = pair[0].r + pair[1].r\n r = r/2\n Nodes.remove(pair[1])\n Nodes.remove(pair[0])\n n = McNeuron.Node()\n n.xyz = loc\n n.r = r\n par.children = []\n par.add_child(n)\n n.parent = par\n Nodes.append(n)\n \ndef remove_pair_adjust_parent(self, Nodes, pair):\n \"\"\"\n Removes the pair of nodes and adjust its parent. the location of the parent is the mean of the locaton of two nodes.\n \n Parameters\n ----------\n Nodes: list\n the list of Nodes\n \n pair: array\n The index of pair of nodes. the nodes should be end points and have the same parent.\n \n Returns\n -------\n The new list of Nodes which the pair are removed their parent is adjusted.\n \"\"\"\n \n par = pair[0].parent\n loc = pair[0].xyz + pair[1].xyz\n loc = loc/2\n Nodes.remove(pair[1])\n Nodes.remove(pair[0])\n par.xyz = loc\n par.children = []\n \ndef prune_shortest_seg(self):\n (endpoint_index,) = np.where(self.branch_order[self.n_soma:]==0)\n #for i in endpoint_index:\n \n \n \ndef random_subsample(self, num):\n \"\"\"\n randomly selects a few nodes from neuron and builds a new neuron with them. The location of these node in the new neuron \n is the same as the original neuron and the morphology of them is such that if node A is parent (or grand parent) of node B\n in the original neuron, it is the same for the new neuron.\n \n Parameters\n ---------- \n num: int\n number of nodes to be selected randomly.\n\n Returns\n -------\n Neuron: the subsampled neuron\n \"\"\"\n \n # select the index of num nodes randomly.\n I = np.arange(self.n_soma, self.n_node)\n np.random.shuffle(I)\n selected_index = I[0:num]\n selected_index = np.union1d(np.arange(self.n_soma), selected_index)\n selected_index = selected_index.astype(int)\n selected_index = np.unique(np.sort(selected_index))\n \n # making a list of node from the selected nodes\n neuron = neuron_with_selected_nodes(self, selected_index)\n \n return neuron\n\ndef subsample_main_nodes(self):\n \"\"\"\n subsamples a neuron with its main node only; i.e endpoints and branching nodes.\n\n Returns\n -------\n Neuron: the subsampled neuron\n \"\"\"\n # select all the main points\n selected_index = get_main_points(self)\n\n # Computing the parent id of the selected nodes \n neuron = neuron_with_selected_nodes(self, selected_index)\n return neuron\n\ndef regular_subsample(self, distance):\n \"\"\"\n subsamples a neuron from original neuron. It has all the main points of the original neuron, \n i.e endpoints or branching nodes, are not changed and meanwhile the distance of two consecutive nodes \n of subsample neuron is around the 'distance'. \n for each segment between two consecuative main points, a few nodes from the segment will be added to the selected node;\n it starts from the far main point, and goes on the segment toward the near main point. Then the first node which is \n going to add has the property that it is the farest node from begining on the segment such that its distance from begining is\n less than 'distance'. The next nodes will be selected similarly. this procesure repeat for all the segments.\n \n Parameters\n ---------- \n distance: float\n the mean distance between pairs of consecuative nodes.\n\n Returns\n -------\n Neuron: the subsampled neuron\n \"\"\"\n \n # Selecting the main points: branching nodes and end nodes\n selected_index = get_main_points(self)\n \n # for each segment between two consecuative main points, a few nodes from the segment will be added to the selected node.\n # These new nodes will be selected base on the fact that neural distance of two consecuative nodes is around 'distance'. \n # Specifically, it starts from the far main point, and goes on the segment toward the near main point. Then the first node which is \n # going to add has the property that it is the farest node from begining on the segment such that its distance from begining is\n # less than 'distance'. The next nodes will be selected similarly.\n \n for i in selected_index:\n upList = np.array([i],dtype = int)\n index = self.parent_index[i]\n dist = self.distance_from_parent[i]\n while(~np.any(selected_index == index)):\n upList = np.append(upList,index)\n index = self.parent_index[index]\n dist = np.append(dist, sum(self.distance_from_parent[upList]))\n dist = np.append(0,dist)\n (I,) = np.where(np.diff(np.floor(dist/distance))>0)\n I = upList[I]\n selected_index = np.append(selected_index,I)\n selected_index = np.unique(selected_index)\n \n neuron = neuron_with_selected_nodes(self, selected_index)\n\n return neuron\n\ndef regular_subsample_with_fixed_number(self, num):\n \"\"\"\n gives back a regular subsample neuron (regular means that the distance between consecuative nodes is approximately fixed) \n such that the number of nodes is 'num'.\n \n Parameters\n ---------- \n num: int\n number of nodes on the subsampled neuron\n\n Returns\n -------\n Neuron: the subsampled neuron \n \n \"\"\"\n l = sum(self.distance_from_parent)\n branch_number = len(np.where(self.branch_order[self.n_soma:] == 2))\n distance = l/(num - branch_number)\n return regular_subsample(self, distance)\n\ndef mesoscale_subsample(self, number):\n main_point = self.subsample_main_nodes()\n Nodes = main_point.nodes_list\n rm = (main_point.n_node - number)/2.\n for remove in range(int(rm)):\n b, m = find_sharpest_fork(self, Nodes)\n remove_pair_adjust_parent(self, Nodes, b)\n \n return McNeuron.Neuron(file_format = 'only list of nodes', input_file = Nodes)\n\ndef regular_mesoscale_subsample(self, number):\n thresh = 1.\n# n = neuron.subsample(thresh)\n# while(len(n.nodes_list)>number):\n# thresh += 1 \n# n = neuron.subsample(thresh)\n# if(sum(n.branch_order[n.n_soma:]==1)==0):\n# break\n# neuron = n\n Nodes = self.nodes_list\n while(len(Nodes)>number):\n b, m = find_sharpest_fork_general(self, Nodes)\n print m\n if(m>0. and m < thresh):\n remove_pair_replace_node(self, Nodes, b)\n else:\n self = McNeuron.Neuron(file_format = 'only list of nodes', input_file = Nodes)\n thresh = thresh + 1\n self = self.subsample(thresh)\n Nodes = self.nodes_list\n print thresh\n \n return McNeuron.Neuron(file_format = 'only list of nodes', input_file = Nodes)\n",
"_____no_output_____"
],
[
"self= neuron\n(endpoint_index,) = np.where(self.branch_order[self.n_soma:]==0)\nfor i in endpoint_index:\n a = self.nodes_list[i]\n b = a.parent\n while(len(b.children) ==1):\n b = b.parent\n print LA.norm(b.xyz - a.xyz,2)",
"_____no_output_____"
]
],
[
[
"#### Testing subsamples",
"_____no_output_____"
]
],
[
[
"neuron_list = McNeuron.visualize.get_all_path(os.getcwd()+\"/Data/Pyramidal/chen\")\nneuron = McNeuron.Neuron(file_format = 'swc', input_file=neuron_list[19])\n# McNeuron.visualize.plot_2D(neuron,size = 4)\n# McNeuron.visualize.plot_2D(random_subsample(neuron, 200) ,size = 4)\n# McNeuron.visualize.plot_2D(subsample_main_nodes(neuron) ,size = 4)\n# McNeuron.visualize.plot_2D(regular_subsample(neuron, distance = 60) ,size = 4)\n# McNeuron.visualize.plot_2D(regular_subsample_with_fixed_number(neuron, num = 200) ,size = 4)\n#McNeuron.visualize.plot_2D(mesoscale_subsample(neuron, number = 40) ,size = 4)\nMcNeuron.visualize.plot_2D(regular_mesoscale_subsample(neuron, number = 40) ,size = 4)",
"_____no_output_____"
],
[
"neuron.location",
"_____no_output_____"
]
],
[
[
"#### Models",
"_____no_output_____"
]
],
[
[
"def reducing_data(swc_df, pruning_number=10):\n \"\"\"\n Parameters\n ----------\n swc_df: dataframe\n the original swc file\n pruning_number: int\n number of nodes remaining at the end of pruning\n \n Returns\n -------\n pruned_df: dataframe\n pruned dataframe\n \n \"\"\"\n L = []\n for i in range(len(swc_df)):\n L.append(mesoscale_subsample(McNeuron.Neuron(file_format = 'swc', input_file = swc_df[i]), pruning_number))\n \n return L\n \ndef separate(list_of_neurons):\n \"\"\"\n Parameters\n ----------\n list_of_neurons: List of Neurons\n \n \n Returns\n -------\n geometry: array of shape (n-1, 3)\n (x, y, z) coordinates of each shape assuming that soma is at (0, 0, 0)\n \n morphology : array of shape (n-1,)\n index of node - index of parent\n \"\"\"\n Geo = list()\n Morph = list()\n for n in range(len(list_of_neurons)):\n neuron = list_of_neurons[n]\n Geo.append(neuron.location)\n Morph.append(neuron.parent_index)\n \n return Geo, Morph\n \ndef geometry_generator(n_nodes=10):\n \"\"\"\n Generator network: fully connected 2-layer network to generate locations\n \n Parameters\n ----------\n n_nodes: int\n number of nodes\n \n Returns\n -------\n model: keras object\n number of models\n \"\"\"\n \n model = Sequential()\n \n model.add(Dense(input_dim=100, output_dim=512))\n model.add(Activation('tanh'))\n\n model.add(Dense(input_dim=512, output_dim=512))\n model.add(Activation('tanh'))\n\n model.add(Dense(input_dim=512, output_dim=n_nodes * 3))\n model.add(Reshape((n_nodes, 3)))\n \n return model\n\ndef morphology_generator(n_nodes=10):\n \"\"\"\n Generator network: fully connected 2-layer network to generate locations\n \n Parameters\n ----------\n n_nodes: int\n number of nodes\n \n Returns\n -------\n model: keras object\n number of models\n \"\"\"\n \n model = Sequential()\n \n # A keras seq to seq model, with the following characteristics:\n # input length: 1\n # input dimensionality: 100\n # some hidden layers for encoding\n # some hidden layers for decoding\n # output length: n_nodes - 1\n # output dimensionality: n_nodes - 1 (there will finally be a softmax on each output node)\n \n return model",
"_____no_output_____"
],
[
"for i in range(5):\n n_nodes = 10 + 10 * i\n subsampled_neuron = mesoscale_subsample(deepcopy(neuron), n_nodes)\n print 'Number of nodes: %d' % (n_nodes)\n McNeuron.visualize.plot_2D(subsampled_neuron, size = 4)\n #McNeuron.visualize.plot_dedrite_tree(subsampled_neuron)\n \n #plt.show()",
"_____no_output_____"
],
[
"for i in range(20):\n n_nodes = 10 + 10 * i\n subsampled_neuron = mesoscale_subsample_2d(deepcopy(neuron), n_nodes)\n print subsampled_neuron.n_node\n McNeuron.visualize.plot_2D(subsampled_neuron, size = 4, save = str(40+i)+\".eps\")",
"_____no_output_____"
],
[
"subsampled_neuron.n_node",
"_____no_output_____"
]
],
[
[
"#### Showing the geometrical data",
"_____no_output_____"
]
],
[
[
"tmp = reducing_data(neuron_list[0:20], pruning_number=10)\ngeo, morph = separate(tmp)",
"_____no_output_____"
],
[
"McNeuron.visualize.plot_2D(tmp[0])",
"_____no_output_____"
],
[
"plt.scatter(tmp[0].location[0,:],tmp[0].location[1,:])",
"_____no_output_____"
],
[
"for n in range(10):\n plt.scatter(geo[n][0,:],geo[n][1,:])\n plt.show()",
"_____no_output_____"
],
[
"McNeuron.visualize.plot_2D(tmp[1])",
"_____no_output_____"
]
],
[
[
"#### Testing function: separate [works]",
"_____no_output_____"
]
],
[
[
"geo, morph = separate(tmp)",
"_____no_output_____"
],
[
"print morph[0]\nprint morph[1]\nprint morph[2]",
"_____no_output_____"
],
[
"print geo[6].shape\nn = 1\nplt.scatter(geo[n][0,:],geo[n][1,:])",
"_____no_output_____"
]
],
[
[
"#### Testing geometry_generator( ) [works]",
"_____no_output_____"
]
],
[
[
"neuron = McNeuron.Neuron(file_format = 'swc', input_file=neuron_list[0])\nMcNeuron.visualize.plot_2D(neuron)",
"_____no_output_____"
],
[
"n1 = neuron.subsample(100)\nMcNeuron.visualize.plot_2D(n1)",
"_____no_output_____"
],
[
"McNeuron.visualize.plot_dedrite_tree(n1)",
"_____no_output_____"
],
[
"neuron.n_node",
"_____no_output_____"
],
[
"n1.n_node",
"_____no_output_____"
],
[
"plt.hist(n1.distance_from_parent)",
"_____no_output_____"
],
[
"plt.scatter(n1.location[0,:],n1.location[1,:],s = 7)",
"_____no_output_____"
],
[
"tmp = mat['N'][2500][3]\ntmp[0:3,:]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e787dbbc99f0598d7e8f799115653b2d2314e04e | 206,008 | ipynb | Jupyter Notebook | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort | 160afbb02270ca96f3613d50eb56eeafaca1c991 | [
"MIT"
] | null | null | null | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort | 160afbb02270ca96f3613d50eb56eeafaca1c991 | [
"MIT"
] | null | null | null | models/GuidedCapstone_final_documentationStep6HL.ipynb | reetibhagat/big_mountain_resort | 160afbb02270ca96f3613d50eb56eeafaca1c991 | [
"MIT"
] | null | null | null | 176.225834 | 51,248 | 0.885572 | [
[
[
"# Guided Capstone Step 6. Documentation",
"_____no_output_____"
],
[
"**The Data Science Method** \n\n\n1. Problem Identification \n\n2. Data Wrangling \n \n3. Exploratory Data Analysis \n \n4. Pre-processing and Training Data Development\n\n5. Modeling\n\n6. **Documentation**\n * Review the Results\n * Finalize Code \n * Finalize Documentation\n * Create a Project Report \n * Create a Slide Deck for the Executive Audience",
"_____no_output_____"
],
[
"In this guided capstone we are going to revisit many of the actions we took in the previous guided capstone steps. This gives you the opportunity to practice the code you wrote to solve the questions in step 4 and 5. ",
"_____no_output_____"
],
[
"**<font color='teal'> Start by loading the necessary packages and printing out our current working directory just to confirm we are in the correct project directory. </font>**",
"_____no_output_____"
]
],
[
[
"import os\nimport pandas as pd\nimport datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline",
"_____no_output_____"
],
[
"os.getcwd()",
"_____no_output_____"
]
],
[
[
"## Fit Models with Training Dataset",
"_____no_output_____"
],
[
"**<font color='teal'> Using sklearn fit the model you chose in Guided Capstone 5 on your training dataset. This includes: creating dummy features for states if you need them, scaling the data,and creating train and test splits before fitting the chosen model.Also, remember to generate a model performance score(MAE, or explained variance) based on the testing hold-out data set.</font>**",
"_____no_output_____"
],
[
"#### Best Model ",
"_____no_output_____"
]
],
[
[
"##model4 is best model as accuracy is 93% and it is generalized model.",
"_____no_output_____"
],
[
"df_1=pd.read_csv(r'/Users/ajesh_mahto/Desktop/capstone_project/data/step_try.csv')",
"_____no_output_____"
],
[
"df_1.head()\n",
"_____no_output_____"
],
[
"df_1=df_1.drop('Unnamed: 0',axis=1)\n",
"_____no_output_____"
],
[
"df=pd.get_dummies(df_1, columns=['state'],drop_first=True)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler\nX=df.drop(['Name','AdultWeekend'], axis=1)\ny=df['AdultWeekend']\nscaler=StandardScaler()\nX_scaled=scaler.fit_transform(X)\ny=y.ravel()",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nX_train,X_test,y_train,y_test = train_test_split(X, y, test_size=0.25, random_state=1)\n\nmodel4=LinearRegression()\nmodel4.fit(X_train,y_train)",
"_____no_output_____"
],
[
"ypred=model4.predict(X_test)",
"_____no_output_____"
],
[
"actual_weekened = pd.DataFrame({'Actual': y_test, 'Predicted': ypred})\nactual_weekened",
"_____no_output_____"
],
[
"model4.score(X_train,y_train)",
"_____no_output_____"
],
[
"model4.score(X_test,y_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nimport math",
"_____no_output_____"
],
[
"print('Mean Absolute Error:', mean_absolute_error(y_test, ypred))\nprint('Root Mean Squared Error:', np.sqrt(mean_squared_error(y_test, ypred)))\nprint('Mean Squared Error:', mean_squared_error(y_test, ypred))\n\n\n",
"Mean Absolute Error: 5.162174619564856\nRoot Mean Squared Error: 6.874864639122517\nMean Squared Error: 47.263763806257174\n"
]
],
[
[
"## Review the results ",
"_____no_output_____"
],
[
"**<font color='teal'> Now, let's predict the Big Mountain Weekend price with our model in order to provide a recommendation to our managers on how to price the `AdultWeekend` lift ticket. First we need to find the row for Big Mountain resort in our data using string contains or string matching.</font>**",
"_____no_output_____"
]
],
[
[
"#df[df['Name'].str.contains('Big Mountain')]\ndf3=df[df['Name'].str.contains('Big Mountain')]\ndf3",
"_____no_output_____"
]
],
[
[
"**<font color='teal'> Prepare the Big Mountain resort data row as you did in the model fitting stage.</font>**",
"_____no_output_____"
]
],
[
[
"\nfeatures=df3.drop(['Name','AdultWeekend'], axis=1)\n",
"_____no_output_____"
]
],
[
[
"**<font color='teal'> Predict the Big Mountain resort `Adult Weekend` price and print it out.</font>** This is our expected price to present to management. Based on our model given the characteristics of the resort in comparison to other ski resorts and their unique characteristics.",
"_____no_output_____"
]
],
[
[
"price=model4.predict(features)\nprice",
"_____no_output_____"
]
],
[
[
"**<font color='teal'> Print the Big Mountain resort actual `Adult Weekend` price.</font>**",
"_____no_output_____"
]
],
[
[
"ac=df[df['Name'].str.contains('Big Mountain')]\nprint (\"The actual Big Mountain Resort adult weekend price is $%s \" % ' '.join(map(str, ac.AdultWeekend)))",
"The actual Big Mountain Resort adult weekend price is $81.0 \n"
]
],
[
[
"**<font color='teal'> As part of reviewing the results it is an important step to generate figures to visualize the data story. We can use the clusters we added to our data frame to create scatter plots for visualizing the Adult Weekend values compared to other characteristics. Run the example below to get you started and build two or three more figures to include in your data story telling.</font>**",
"_____no_output_____"
]
],
[
[
"plt.scatter(df['summit_elev'], df['vertical_drop'], c=df['clusters'], s=50, cmap='viridis', label ='clusters',edgecolors='white')\nplt.scatter(ac['summit_elev'], ac['vertical_drop'], c='white', s=200,edgecolors='black')\nsns.despine()\nplt.xlabel('Summit Elevation (feet)')\nplt.ylabel('Vertical Elevation Drop (feet)')\n#plt.title('summit_elev by vertical_drop by cluster')\nplt.savefig('figures/fig1.png',bbox_inches='tight')",
"_____no_output_____"
],
[
"sns.regplot(x=\"AdultWeekend\", y=\"SkiableTerrain_ac\", data=df[(df['SkiableTerrain_ac']<25000)], color =\"#440154FF\",scatter_kws={\"s\": 25})\nplt.scatter(x=\"AdultWeekend\", y=\"SkiableTerrain_ac\", data=ac, c='white',s=200,edgecolors='black')\nsns.despine()\nplt.xlabel('Lift Ticket Price ($)')\nplt.ylabel('Skiable Area (acres)')\nplt.savefig('figures/fig2.png',bbox_inches='tight')",
"_____no_output_____"
],
[
"sns.regplot(x=\"AdultWeekend\", y=\"daysOpenLastYear\", data=df,color =\"#21908CFF\",scatter_kws={\"s\": 25})\nsns.despine()\nplt.scatter(x=\"AdultWeekend\", y=\"daysOpenLastYear\", data=ac, c='white',s=200,edgecolors='black')\nplt.xlabel('Lift Ticket Price ($)')\nplt.ylabel('Days Open Last Year')\nplt.savefig('figures/fig3.png',bbox_inches='tight')",
"_____no_output_____"
],
[
"sns.set(style=\"ticks\")\nsns.jointplot(x=df['AdultWeekend'], y=df['daysOpenLastYear'], kind=\"hex\", color=\"#FDE725FF\")\nsns.despine()\nplt.xlabel('Lift Ticket Price ($)')\nplt.ylabel('Days Open Last Year')\nplt.savefig('figures/fig4.png',bbox_inches='tight')",
"_____no_output_____"
],
[
"\nplt.scatter(x=\"AdultWeekend\", y=\"averageSnowfall\", data=df_1, c='blue',s=200,edgecolors='black')\nplt.xlabel('Lift Ticket Price ($)')\nplt.ylabel('Average Snowfall')\nplt.savefig('figures/fig3.png',bbox_inches='tight')",
"_____no_output_____"
]
],
[
[
"## Finalize Code",
"_____no_output_____"
],
[
" Making sure our code is well organized and easy to follow is an important step. This is the time where you need to review the notebooks and Python scripts you've created and clean them up so they are easy to follow and succinct in nature. Addtionally, we will also save our final model as a callable object using Pickle for future use in a data pipeline. Pickle is a module that serializes (and de-serializes) Python objects so that they can become executable objects like functions. It's used extensively in production environments where machine learning models are deployed on an industrial scale!**<font color='teal'> Run the example code below to save out your callable model. Notice that we save it in the models folder we created in our previous guided capstone step.</font>** ",
"_____no_output_____"
]
],
[
[
"import pickle\ns = pickle.dumps(model4)\nfrom joblib import dump, load\ndump(model4, 'models/regression_model_adultweekend.joblib') ",
"_____no_output_____"
]
],
[
[
"## Finalize Documentation",
"_____no_output_____"
],
[
"For model documentation, we want to save the model performance metrics as well as the features included in the final model. You could also save the model perfomance metrics and coefficients fo the other models you tried in case you want to refer to them later. **<font color='teal'> Create a dataframe containing the coefficients and the model performance metrics and save it out as a csv file, then upload it to your github repository.</font>** ",
"_____no_output_____"
]
],
[
[
"performance_metrics=pd.DataFrame(abs(model4.coef_), X.columns, columns=['Coefficient'])\nperformance_metrics['Mean Absolute Error']= mean_absolute_error(y_test, ypred)\nperformance_metrics['Root Mean Squared Error']=np.sqrt(mean_squared_error(y_test, ypred))\nperformance_metrics['r2-testscore']=model4.score(X_test,y_test)\nperformance_metrics['r2-trainscore']=model4.score(X_train,y_train)",
"_____no_output_____"
],
[
"performance_metrics.to_csv(r'/Users/ajesh_mahto/Desktop/capstone_project/data/performance_metrics_model4.csv')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
e787e89c88936c26c092dcb7d30548ea7f47a447 | 6,415 | ipynb | Jupyter Notebook | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- | bc8e5ee5b55c0408b7436d0f866b3b7e79164daf | [
"Apache-2.0"
] | 58 | 2019-05-16T00:12:11.000Z | 2022-03-14T06:12:12.000Z | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- | bc8e5ee5b55c0408b7436d0f866b3b7e79164daf | [
"Apache-2.0"
] | 1 | 2021-03-26T00:38:05.000Z | 2021-03-26T00:38:05.000Z | courses/machine_learning/tensorflow/d_experiment.ipynb | AmirQureshi/code-to-run- | bc8e5ee5b55c0408b7436d0f866b3b7e79164daf | [
"Apache-2.0"
] | 46 | 2018-03-03T17:17:27.000Z | 2022-03-24T14:56:46.000Z | 29.562212 | 553 | 0.595635 | [
[
[
"<h1> 2d. Distributed training and monitoring </h1>\n\nIn this notebook, we refactor to use the Experimenter class instead of hand-coding our ML pipeline. This allows us to carry out evaluation as part of our training loop instead of as a separate step. It also adds in failure-handling that is necessary for distributed training capabilities.\n\nWe also use TensorBoard to monitor the training.",
"_____no_output_____"
]
],
[
[
"import google.datalab.ml as ml\nimport tensorflow as tf\nfrom tensorflow.contrib import layers\nprint tf.__version__\n# print ml.sdk_location",
"_____no_output_____"
],
[
"import datalab.bigquery as bq\nimport tensorflow as tf\nimport numpy as np\nimport shutil",
"_____no_output_____"
]
],
[
[
"<h2> Input </h2>\n\nRead data created in Lab1a, but this time make it more general, so that we are reading in batches. Instead of using Pandas, we will use add a filename queue to the TensorFlow graph.",
"_____no_output_____"
]
],
[
[
"CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']\nLABEL_COLUMN = 'fare_amount'\nDEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']]\n\ndef read_dataset(filename, num_epochs=None, batch_size=512, mode=tf.contrib.learn.ModeKeys.TRAIN):\n def _input_fn():\n filename_queue = tf.train.string_input_producer(\n [filename], num_epochs=num_epochs, shuffle=True)\n reader = tf.TextLineReader()\n _, value = reader.read_up_to(filename_queue, num_records=batch_size)\n\n value_column = tf.expand_dims(value, -1)\n columns = tf.decode_csv(value_column, record_defaults=DEFAULTS)\n features = dict(zip(CSV_COLUMNS, columns))\n label = features.pop(LABEL_COLUMN)\n return features, label\n\n return _input_fn\n\ndef get_train():\n return read_dataset('./taxi-train.csv', num_epochs=100, mode=tf.contrib.learn.ModeKeys.TRAIN)\n\ndef get_valid():\n return read_dataset('./taxi-valid.csv', num_epochs=1, mode=tf.contrib.learn.ModeKeys.EVAL)\n\ndef get_test():\n return read_dataset('./taxi-test.csv', num_epochs=1, mode=tf.contrib.learn.ModeKeys.EVAL)",
"_____no_output_____"
]
],
[
[
"<h2> Create features out of input data </h2>\n\nFor now, pass these through. (same as previous lab)",
"_____no_output_____"
]
],
[
[
"INPUT_COLUMNS = [\n layers.real_valued_column('pickuplon'),\n layers.real_valued_column('pickuplat'),\n layers.real_valued_column('dropofflat'),\n layers.real_valued_column('dropofflon'),\n layers.real_valued_column('passengers'),\n]\n\nfeature_cols = INPUT_COLUMNS",
"_____no_output_____"
]
],
[
[
"<h2> Experiment framework </h2>",
"_____no_output_____"
]
],
[
[
"import tensorflow.contrib.learn as tflearn\nfrom tensorflow.contrib.learn.python.learn import learn_runner\nimport tensorflow.contrib.metrics as metrics\n\ndef experiment_fn(output_dir):\n return tflearn.Experiment(\n tflearn.LinearRegressor(feature_columns=feature_cols, model_dir=output_dir),\n train_input_fn=get_train(),\n eval_input_fn=get_valid(),\n eval_metrics={\n 'rmse': tflearn.MetricSpec(\n metric_fn=metrics.streaming_root_mean_squared_error\n )\n }\n )\n\n\nshutil.rmtree('taxi_trained', ignore_errors=True) # start fresh each time\nlearn_runner.run(experiment_fn, 'taxi_trained')",
"_____no_output_____"
]
],
[
[
"<h2> Monitoring with TensorBoard </h2>",
"_____no_output_____"
]
],
[
[
"from google.datalab.ml import TensorBoard\nTensorBoard().start('./taxi_trained')\nTensorBoard().list()",
"_____no_output_____"
],
[
"# to stop TensorBoard\nTensorBoard().stop(23002)\nprint 'stopped TensorBoard'\nTensorBoard().list()",
"_____no_output_____"
]
],
[
[
"Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e787e9c6a4013d3ecc2ca6b08311510766e3fc89 | 325,371 | ipynb | Jupyter Notebook | Dataworks/Fremont_Bridge_Bicycle_Counter_work/Fremont_Bridge_Bicycle_Counter.ipynb | ozkanuysal/Un-vers-tySecondClass | 0330fe3576e5febb517f1a3e6b7ec90be0ff759f | [
"Unlicense"
] | 2 | 2020-12-10T16:05:32.000Z | 2020-12-14T22:20:58.000Z | Dataworks/Fremont_Bridge_Bicycle_Counter_work/Fremont_Bridge_Bicycle_Counter.ipynb | ozkanuysal/UniversitySecondClass | 0330fe3576e5febb517f1a3e6b7ec90be0ff759f | [
"Unlicense"
] | null | null | null | Dataworks/Fremont_Bridge_Bicycle_Counter_work/Fremont_Bridge_Bicycle_Counter.ipynb | ozkanuysal/UniversitySecondClass | 0330fe3576e5febb517f1a3e6b7ec90be0ff759f | [
"Unlicense"
] | null | null | null | 869.975936 | 96,176 | 0.946357 | [
[
[
"import pandas as pd\ndata = pd.read_csv(\"Fremont_Bridge_Bicycle_Counter.csv\", index_col= 'Date', parse_dates=True)\ndata.head()",
"_____no_output_____"
],
[
"data.dropna().describe()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport seaborn\nseaborn.set()\ndata.plot()\nplt.ylabel(\"Hourly Bicycle count\")\nplt.show()",
"_____no_output_____"
],
[
"weekly = data.resample(\"W\").sum()\nweekly.plot(style=[':', '--', '-'])\nplt.ylabel('Weekly bicycle count')\nplt.show()",
"_____no_output_____"
],
[
"daily = data.resample('D').sum()\ndaily.rolling(30, center=True).sum().plot(style=[':', '--', '-'])\nplt.ylabel('mean hourly count')\nplt.show()",
"_____no_output_____"
],
[
"daily.rolling(50, center=True,\n win_type='gaussian').sum(std=10).plot(style=[':','--', '-'])\nplt.show()",
"_____no_output_____"
],
[
"import numpy as np\nby_time = data.groupby(data.index.time).mean()\nhourly_ticks = 4 * 60 * 60 * np.arange(6)\nby_time.plot(xticks= hourly_ticks, style=[':', '--', '-'])\nplt.ylabel(\"Traffic according to time\")\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7881a599f00938602c0c049f29a678241f1706b | 74,613 | ipynb | Jupyter Notebook | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja | f90af32f94881d547961ed379654bb91cb9efcc2 | [
"Apache-2.0"
] | null | null | null | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja | f90af32f94881d547961ed379654bb91cb9efcc2 | [
"Apache-2.0"
] | null | null | null | exercise/day_3/actor_and_critic_method.ipynb | masatoomori/baby-steps-of-rl-ja | f90af32f94881d547961ed379654bb91cb9efcc2 | [
"Apache-2.0"
] | null | null | null | 74,613 | 74,613 | 0.926179 | [
[
[
"# Actor and Critic Method",
"_____no_output_____"
],
[
"## パッケージの準備",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2\n%matplotlib inline",
"_____no_output_____"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
],
[
"import sys\nimport os\n\nHOME_PATH = '/content/drive/MyDrive/Colab Notebooks/baby-steps-of-rl-ja/exercise/day_3'\nsys.path.append(HOME_PATH)",
"_____no_output_____"
],
[
"import numpy as np\nimport gym\nfrom el_agent import ELAgent\nfrom frozen_lake_util import show_q_value",
"_____no_output_____"
]
],
[
[
"## Actor の定義",
"_____no_output_____"
]
],
[
[
"class Actor(ELAgent):\n def __init__(self, env):\n super().__init__(epsilon=-1)\n n_row = env.observation_space.n\n n_col = env.action_space.n\n self.actions = list(range(env.action_space.n))\n self.Q = np.random.uniform(0, 1, n_row * n_col).reshape((n_row, n_col))\n \n def softmax(self, x):\n return np.exp(x) / np.sum(np.exp(x), axis=0)\n\n def policy(self, s):\n a = np.random.choice(self.actions, 1, p=self.softmax(self.Q[s]))\n return a[0]",
"_____no_output_____"
]
],
[
[
"## Critic の定義",
"_____no_output_____"
]
],
[
[
"class Critic():\n def __init__(self, env):\n n_state = env.observation_space.n\n self.V = np.zeros(n_state)",
"_____no_output_____"
]
],
[
[
"## Actor & Critic 学習プロセスの定義",
"_____no_output_____"
]
],
[
[
"class ActorCritic():\n def __init__(self, actor_class, critic_class):\n self.actor_class = actor_class\n self.critic_class = critic_class\n \n def train(self, env, episode_count=1000, gamma=0.9, learning_rate=0.1, render=False, report_interval=50):\n actor = self.actor_class(env)\n critic = self.critic_class(env)\n \n actor.init_log()\n for e in range(episode_count):\n s = env.reset()\n is_done = False\n while not is_done:\n if render:\n env.render()\n a = actor.policy(s)\n state, reward, is_done, info = env.step(a)\n\n gain = reward + gamma * critic.V[state]\n estimated = critic.V[s]\n td = gain - estimated\n actor.Q[s][a] += learning_rate * td\n critic.V[s] += learning_rate * td\n s = state\n else:\n actor.log(reward)\n \n if e != 0 and e % report_interval == 0:\n actor.show_reward_log(episode=e)\n \n return actor, critic",
"_____no_output_____"
]
],
[
[
"## Agent を学習させる",
"_____no_output_____"
]
],
[
[
"def train():\n trainer = ActorCritic(Actor, Critic)\n env = gym.make(\"FrozenLakeEasy-v0\")\n actor, critic = trainer.train(env, episode_count=3000)\n show_q_value(actor.Q)\n actor.show_reward_log()",
"_____no_output_____"
],
[
"agent = train()",
"At Episode 50 average reward is 0.02 (+/-0.14).\nAt Episode 100 average reward is 0.0 (+/-0.0).\nAt Episode 150 average reward is 0.0 (+/-0.0).\nAt Episode 200 average reward is 0.06 (+/-0.237).\nAt Episode 250 average reward is 0.04 (+/-0.196).\nAt Episode 300 average reward is 0.02 (+/-0.14).\nAt Episode 350 average reward is 0.0 (+/-0.0).\nAt Episode 400 average reward is 0.02 (+/-0.14).\nAt Episode 450 average reward is 0.02 (+/-0.14).\nAt Episode 500 average reward is 0.0 (+/-0.0).\nAt Episode 550 average reward is 0.06 (+/-0.237).\nAt Episode 600 average reward is 0.08 (+/-0.271).\nAt Episode 650 average reward is 0.04 (+/-0.196).\nAt Episode 700 average reward is 0.06 (+/-0.237).\nAt Episode 750 average reward is 0.04 (+/-0.196).\nAt Episode 800 average reward is 0.1 (+/-0.3).\nAt Episode 850 average reward is 0.08 (+/-0.271).\nAt Episode 900 average reward is 0.14 (+/-0.347).\nAt Episode 950 average reward is 0.12 (+/-0.325).\nAt Episode 1000 average reward is 0.3 (+/-0.458).\nAt Episode 1050 average reward is 0.44 (+/-0.496).\nAt Episode 1100 average reward is 0.46 (+/-0.498).\nAt Episode 1150 average reward is 0.72 (+/-0.449).\nAt Episode 1200 average reward is 0.84 (+/-0.367).\nAt Episode 1250 average reward is 0.84 (+/-0.367).\nAt Episode 1300 average reward is 0.88 (+/-0.325).\nAt Episode 1350 average reward is 0.88 (+/-0.325).\nAt Episode 1400 average reward is 0.94 (+/-0.237).\nAt Episode 1450 average reward is 0.9 (+/-0.3).\nAt Episode 1500 average reward is 0.9 (+/-0.3).\nAt Episode 1550 average reward is 0.94 (+/-0.237).\nAt Episode 1600 average reward is 0.92 (+/-0.271).\nAt Episode 1650 average reward is 0.98 (+/-0.14).\nAt Episode 1700 average reward is 0.92 (+/-0.271).\nAt Episode 1750 average reward is 0.96 (+/-0.196).\nAt Episode 1800 average reward is 0.94 (+/-0.237).\nAt Episode 1850 average reward is 0.98 (+/-0.14).\nAt Episode 1900 average reward is 0.98 (+/-0.14).\nAt Episode 1950 average reward is 0.98 (+/-0.14).\nAt Episode 2000 average reward is 1.0 (+/-0.0).\nAt Episode 2050 average reward is 0.98 (+/-0.14).\nAt Episode 2100 average reward is 0.98 (+/-0.14).\nAt Episode 2150 average reward is 0.96 (+/-0.196).\nAt Episode 2200 average reward is 1.0 (+/-0.0).\nAt Episode 2250 average reward is 1.0 (+/-0.0).\nAt Episode 2300 average reward is 1.0 (+/-0.0).\nAt Episode 2350 average reward is 0.98 (+/-0.14).\nAt Episode 2400 average reward is 0.98 (+/-0.14).\nAt Episode 2450 average reward is 0.98 (+/-0.14).\nAt Episode 2500 average reward is 0.96 (+/-0.196).\nAt Episode 2550 average reward is 1.0 (+/-0.0).\nAt Episode 2600 average reward is 0.98 (+/-0.14).\nAt Episode 2650 average reward is 1.0 (+/-0.0).\nAt Episode 2700 average reward is 0.98 (+/-0.14).\nAt Episode 2750 average reward is 1.0 (+/-0.0).\nAt Episode 2800 average reward is 1.0 (+/-0.0).\nAt Episode 2850 average reward is 0.98 (+/-0.14).\nAt Episode 2900 average reward is 0.98 (+/-0.14).\nAt Episode 2950 average reward is 0.98 (+/-0.14).\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7881b6e71a2d5e7e40bf75138e58fb1621ed175 | 17,642 | ipynb | Jupyter Notebook | GrapheneWithQrays.ipynb | 4dsolutions/Python5 | 8d80753e823441a571b827d24d21577446409b52 | [
"MIT"
] | 11 | 2016-08-17T00:15:26.000Z | 2020-07-17T21:31:10.000Z | GrapheneWithQrays.ipynb | 4dsolutions/Python5 | 8d80753e823441a571b827d24d21577446409b52 | [
"MIT"
] | null | null | null | GrapheneWithQrays.ipynb | 4dsolutions/Python5 | 8d80753e823441a571b827d24d21577446409b52 | [
"MIT"
] | 5 | 2017-02-22T05:15:52.000Z | 2019-11-08T06:17:34.000Z | 38.352174 | 692 | 0.553792 | [
[
[
"[Oregon Curriculum Network](http://www.4dsolutions.net/ocn) <br />\n[Discovering Math with Python](Introduction.ipynb)\n\n# Quadrays and Graphene\n\n<p><a href=\"https://commons.wikimedia.org/wiki/File:Graphen.jpg#/media/File:Graphen.jpg\"><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Graphen.jpg/1200px-Graphen.jpg\" alt=\"Graphen.jpg\"></a><br>By <a href=\"//commons.wikimedia.org/w/index.php?title=User:AlexanderAlUS&action=edit&redlink=1\" class=\"new\" title=\"User:AlexanderAlUS (page does not exist)\">AlexanderAlUS</a> - <span class=\"int-own-work\" lang=\"en\">Own work</span>, <a href=\"https://creativecommons.org/licenses/by-sa/3.0\" title=\"Creative Commons Attribution-Share Alike 3.0\">CC BY-SA 3.0</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=11294534\">Link</a></p>\n\n\"Graphene\" refers to an hexagonal grid of cells, the vertexes being carbon atoms. However any hexagonal mesh, such as for game boards, might be referred to as a \"graphene pattern\".\n\nQuadrays are explained [in other Notebooks](QuadraysJN.ipynb). Four basis vectors emanate to the corners of a volume 1 tetrahedron of edges 2R or 1D, in the canonical version, where R and D refer respectively to the Radius and Diameter of imaginary spheres packed together, giving this home base tetrahedron.\n\n\n\n<a data-flickr-embed=\"true\" href=\"https://farm5.staticflickr.com/4143/4949799682_327b33e8d5.jpg\" title=\"Tetrahedron\"><img src=\"https://farm5.staticflickr.com/4143/4949799682_327b33e8d5.jpg\" width=\"375\" height=\"500\" alt=\"Tetrahedron\"></a><script async src=\"//embedr.flickr.com/assets/client-code.js\" charset=\"utf-8\"></script>\n\nThe Quadrays {2, 1, 1, 0}, meaning all 12 permutations of those numbers, fan out from (0,0,0,0) to the corners of a cuboctahedron. ",
"_____no_output_____"
]
],
[
[
"from itertools import permutations\ng = permutations((2,1,1,0))\nunique = {p for p in g} # set comprehension\nprint(unique)",
"{(0, 1, 1, 2), (1, 0, 1, 2), (2, 0, 1, 1), (0, 2, 1, 1), (0, 1, 2, 1), (1, 2, 1, 0), (1, 1, 2, 0), (2, 1, 1, 0), (1, 0, 2, 1), (1, 2, 0, 1), (2, 1, 0, 1), (1, 1, 0, 2)}\n"
]
],
[
[
"I have [elsewhere](Generating%20the%20FCC.ipynb) used this fact to algorithmically generate consecutive shells of 12, 42, 92, 162... spheres (balls) respectively; a growing cuboctahedron of $10 S^{2} + 2$ balls per shell S = 1,2,3... (1 when S=0).\n\n\n\nHowever suppose we don't want to grow the grid omni-directionally, but only in a plane. Each ball will be surrounded by six neighbors meaning at the center of a hexagon.\n\nThe cuboctahedron supplies four such hexagons i.e. its 24 edges comprise four hexagons orbiting the center. We may use any one of them.\n\n## The Algorithm\nThe algorithm begins with a planar subset of the vectors {2, 1, 1, 0} used to compute the six vertexes surrounding (0,0,0,0). We may call these six vertexes \"carbons\".\n\nThen hop to neighboring hexagon centers (where no carbon is located) using an additional set of vectors. \n\nFrom these new centers, compute the six surrounding carbons again, some of which will have already been found, as neighbors share fences, with three faces (centers) sharing each fence post (carbon). \n\nUsing the Python set object, the algorithm filters to keep only unique carbons. \n\nKeep track of hexagon centers, a dual mesh, in a separate set. \n\n(0,0,0,0) will be the first center (ring0).\n\nIf qrays r, s are 60 degrees apart on the same hexagon, pointing to neighboring carbons, then r + s will be the \"hop\" vector over the fence (edge) to the neighboring \"yard\" (face), or center. \n\nOnce we have six vertex vectors from a center, computing the six hop vectors (for jumping over the fences) will be a matter of summing pairs of adjacent (60 degree separated) vectors. We only keep new centers i.e. those of the next ring (see below).\n\nWhat about edges?\n\nAs we go around a hexagon in 60 degree increments, say in a clockwise direction, we will be finding edges in terms of adjacent ball pairs. \n\nTo avoid redundancy, (ball_a, ball_b) -- any edge -- [will be sorted](https://github.com/4dsolutions/SAISOFT/blob/master/OrderingPolys.ipynb). Any two quadrays may be ordered as 4-tuples e.g. (2, 1, 1, 0) is \"greater than\" (2, 1, 0, 1). \n\nWith unique representations of any edge, in the form of sorted tuples of qray namedtuples, we will be able to employ the same general technique employed with vertexes (carbons) and face centers: check the existing database for uniqueness and throw away (filter) anything already in the database. Sets will not allow duplicates.\n\nThe first step is to isolate six of the twelve from {2, 1, 1, 0} that define a hexagon.",
"_____no_output_____"
],
[
"\n<table class=\"multicol\" role=\"presentation\" style=\"border-collapse: collapse; padding: 0; border: 0; background:transparent; width:100%;\"><tbody><tr>\n<td style=\"text-align: left; vertical-align: top;\">\n<table class=\"wikitable\">\n\n<tbody><tr>\n<th>Shape\n</th>\n<th>Volume\n</th>\n<th>Vertex Inventory (sum of Quadrays)\n</th></tr>\n<tr>\n<td>Tetrahedron\n</td>\n<td>1\n</td>\n<td>A,B,C,D\n</td></tr>\n<tr>\n<td>Inverse Tetrahedron\n</td>\n<td>1\n</td>\n<td>E,F,G,H = B+C+D, A+C+D, A+B+D, A+B+C\n</td></tr>\n<tr>\n<td>Duo-Tet Cube\n</td>\n<td>3\n</td>\n<td>A through H\n</td></tr>\n<tr>\n<td>Octahedron\n</td>\n<td>4\n</td>\n<td>I,J,K,L,M,N = A+B, A+C, A+D, B+C, B+D, C+D\n</td></tr>\n<tr>\n<td>Rhombic Dodecahedron\n</td>\n<td>6\n</td>\n<td>A through N\n</td></tr>\n<tr>\n<td>Cuboctahedron\n</td>\n<td>20\n</td>\n<td>O,P,Q,R,S,T = I+J, I+K, I+L, I+M, N+J, N+K; U,V,W,X,Y,Z = N+L, N+M, J+L, L+M, M+K, K+J\n</td></tr></tbody></table>\n<p> \n</p>\n</td>\n<td style=\"text-align: left; vertical-align: top;\">\n<p><a href=\"https://upload.wikimedia.org/wikipedia/commons/d/dc/Povlabels.gif\" class=\"image\" title=\"Points A-Z\"><img alt=\"Points A-Z\" src=\"https://upload.wikimedia.org/wikipedia/commons/d/dc/Povlabels.gif\" width=\"320\" height=\"240\" data-file-width=\"320\" data-file-height=\"240\" /></a>\n \n</p>\n</td></tr></tbody></table>",
"_____no_output_____"
],
[
"One of the hexagons is TZOQXV. Do you see it in the above graphic? Another one is TYRQWS. If we regenerate all of the vectors A-Z mentioned above, we'll have a vocabulary suitable for graphene grid development, and then some.",
"_____no_output_____"
]
],
[
[
"from qrays import Qvector, IVM\n\nA, B, C, D = Qvector((1,0,0,0)), Qvector((0,1,0,0)), Qvector((0,0,1,0)), Qvector((0,0,0,1))\nE,F,G,H = B+C+D, A+C+D, A+B+D, A+B+C\nI,J,K,L,M,N = A+B, A+C, A+D, B+C, B+D, C+D\nO,P,Q,R,S,T = I+J, I+K, I+L, I+M, N+J, N+K; U,V,W,X,Y,Z = N+L, N+M, J+L, L+M, M+K, K+J",
"_____no_output_____"
],
[
"# two \"beacons\" of six spokes\nhexrays = [T, Z, O, Q, X, V] # to surrounding carbon atoms\nhoprays = [T+Z, Z+O, O+Q, Q+X, X+V, V+T] # to neighboring (vacant) hex centers",
"_____no_output_____"
],
[
"(T.angle(Z), Z.angle(O), O.angle(Q), Q.angle(X), X.angle(V), V.angle(T))",
"_____no_output_____"
]
],
[
[
"Lets verify that, going around the hexagon, each pair of consecutive hexrays is 60 degree apart. And ditto for hoprays, the vectors we'll use to jump over the fence to neighboring hexagon centers.",
"_____no_output_____"
]
],
[
[
"(hoprays[0].angle(hoprays[1]),\n hoprays[1].angle(hoprays[2]),\n hoprays[2].angle(hoprays[3]),\n hoprays[3].angle(hoprays[4]),\n hoprays[4].angle(hoprays[5]),\n hoprays[5].angle(hoprays[0]))",
"_____no_output_____"
]
],
[
[
"Looks like we're in business!\n\nAs with the growing cuboctahedron and the CCP packing, it makes sense to think in terms of consecutive rings.\n\nThe [hexagonal coordination sequence](https://oeis.org/A008458) is generated by:",
"_____no_output_____"
]
],
[
[
"def A008458(n):\n # OEIS number\n if n == 0:\n return 1\n return 6 * n\n \n[A008458(x) for x in range(10)]",
"_____no_output_____"
]
],
[
[
"I will use this as a check as the algorithm generates multiple rings.",
"_____no_output_____"
]
],
[
[
"centers = {IVM(0,0,0,0)} # center face\nedges = set() # no duplicates permitted\ncarbons = set()\n\nring0 = [Qvector((0,0,0,0))]\n\ndef next_ring(ring):\n \"\"\"\n Use only the most recently added hexagonal ring \n of face centers to compute the next ring, moving \n outward: 1, 6, 12, 18, 24...\n \"\"\"\n new_faces = []\n for face in ring:\n verts = []\n \n # CARBONS\n for spoke in hexrays:\n v = face + spoke\n carbons.add(v.coords) # just the namedtuple is added to the set\n verts.append(v)\n \n # EDGES\n for bond in zip(verts, verts[1:] + [verts[0]]):\n # adding carbon-to-carbon bonds if not already in the set\n edge = tuple(sorted([bond[0].coords, bond[1].coords]))\n edges.add(edge)\n \n # CENTERS\n for jump in hoprays:\n neighbor = face + jump\n previous = len(centers)\n centers.add(neighbor.coords)\n if len(centers) > previous: # if True, face is new\n new_faces.append(neighbor)\n \n return new_faces",
"_____no_output_____"
],
[
"def rings(n):\n prev = ring0\n for ring in range(n):\n print(\"Ring: {:3} Number: {:4}\".format(ring, len(prev)))\n nxt = next_ring(prev)\n prev = nxt\n\n \nrings(12)",
"Ring: 0 Number: 1\nRing: 1 Number: 6\nRing: 2 Number: 12\nRing: 3 Number: 18\nRing: 4 Number: 24\nRing: 5 Number: 30\nRing: 6 Number: 36\nRing: 7 Number: 42\nRing: 8 Number: 48\nRing: 9 Number: 54\nRing: 10 Number: 60\nRing: 11 Number: 66\n"
]
],
[
[
"<a data-flickr-embed=\"true\" href=\"https://www.flickr.com/photos/kirbyurner/2949087863/in/album-72157612943105800/\" title=\"Global Matrix\"><img src=\"https://farm4.staticflickr.com/3249/2949087863_aea4cecb7f.jpg\" width=\"500\" height=\"375\" alt=\"Global Matrix\"></a><script async src=\"//embedr.flickr.com/assets/client-code.js\" charset=\"utf-8\"></script>\n\nNote these are the expected numbers for consecutive rings.\n\nNow that we have our database, it's time to generate some graphical output. As with the FCC, I'll use [POV-Ray's scene description language](http://www.4dsolutions.net/ocn/numeracy0.html) and then render in [POV-Ray](http://www.povray.org). We just want to look at the edges and carbon atom vertexes.",
"_____no_output_____"
]
],
[
[
"sph = \"\"\"sphere { %s 0.1 texture { pigment { color rgb <1,0,0> } } }\"\"\"\ncyl = \"\"\"cylinder { %s %s 0.05 texture { pigment { color rgb <1.0, 0.65, 0.0> } } }\"\"\"\n\ndef make_graphene(fname=\"../c6xty/graphene.pov\", append=True):\n \"\"\"\n Scan through carbons, edges, converting to XYZ and embedding\n in POV-Ray Scene Description Language\n \"\"\"\n if append:\n pov = open(fname, \"a\")\n else:\n pov = open(fname, \"w\")\n\n # graphene will be included as a single object in the \n # parent povray script, where lighting, camera position,\n # and background are defined\n \n print(\"#declare graphene = union{\", file=pov)\n for atom in carbons:\n v = Qvector(atom).xyz()\n s = sph % \"<{0.x}, {0.y}, {0.z}>\".format(v)\n print(s, file=pov)\n for bond in edges:\n v0, v1 = bond\n v0 = Qvector(v0).xyz()\n v1 = Qvector(v1).xyz()\n c = cyl % (\"<{0.x}, {0.y}, {0.z}>\".format(v0), \"<{0.x}, {0.y}, {0.z}>\".format(v1))\n print(c, file=pov)\n print(\"}\\n\", file=pov)\n \nmake_graphene(append=False)",
"_____no_output_____"
]
],
[
[
"Success!\n\n<a data-flickr-embed=\"true\" href=\"https://www.flickr.com/photos/kirbyurner/44743063302/in/dateposted-public/\" title=\"Another Test\"><img src=\"https://farm2.staticflickr.com/1877/44743063302_e7db33cdea_b.jpg\" width=\"1024\" height=\"768\" alt=\"Another Test\"></a><script async src=\"//embedr.flickr.com/assets/client-code.js\" charset=\"utf-8\"></script>\n\n## ADDENDUM\n\nThe graphrene grid needs twelve of its hexagons to become pentagons in order to lose the 720 degrees necessary to turn it into a concave / convex \"global matrix\" or \"hexapent\" grid. \n\nThis 720 degrees is characteristic of polyhedrons more generally and is sometimes referred to as \"Descartes' Deficit\". We may visualize the subtration of 720 degrees as the removal of one tetrahedron, thereby likewise begetting a tetrahedron (something with an inside and outside, not flat).\n\n<a data-flickr-embed=\"true\" href=\"https://www.flickr.com/photos/kirbyurner/44174173534/in/dateposted-public/\" title=\"Better Sunlight\"><img src=\"https://farm2.staticflickr.com/1958/44174173534_2773c5f9cf_z.jpg\" width=\"640\" height=\"480\" alt=\"Better Sunlight\"></a><script async src=\"//embedr.flickr.com/assets/client-code.js\" charset=\"utf-8\"></script>",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7883faa4703d0aaf58dbbd6c55b2d910264b754 | 35,378 | ipynb | Jupyter Notebook | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks | 1f5384a1a27f4cf0ffe8197311f1300a9c4da6d2 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 12 | 2022-01-23T16:05:26.000Z | 2022-03-18T08:00:25.000Z | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks | 1f5384a1a27f4cf0ffe8197311f1300a9c4da6d2 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 6 | 2022-01-26T18:11:32.000Z | 2022-03-28T14:03:04.000Z | docs/20_image_segmentation/15_sequential_labeling.ipynb | rayanirban/BioImageAnalysisNotebooks | 1f5384a1a27f4cf0ffe8197311f1300a9c4da6d2 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | 4 | 2022-01-23T16:05:31.000Z | 2022-03-07T17:18:40.000Z | 91.65285 | 4,488 | 0.864746 | [
[
[
"(image-segmentation:relabel-sequential)=\n# Sequential object (re-)labeling\n\nAs mentioned above, depending on the use-case it might be important to label objects in an image subsequently. It could for example be that a post-processing algorithm for label images crashes in case we pass a label image with missing labels. Hence, we should know how to relabel an image sequentially.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom skimage.io import imread\nfrom skimage.segmentation import relabel_sequential\nimport pyclesperanto_prototype as cle",
"_____no_output_____"
]
],
[
[
"Our starting point is a label image with labels 1-8, where some labels are not present:",
"_____no_output_____"
]
],
[
[
"label_image = imread(\"../../data/label_map_with_index_gaps.tif\")\ncle.imshow(label_image, labels=True)",
"_____no_output_____"
]
],
[
[
"When measuring the maximum intensity in the image, we can see that this label image containing 4 labels is obviously not sequentially labeled.",
"_____no_output_____"
]
],
[
[
"np.max(label_image)",
"_____no_output_____"
]
],
[
[
"We can use the `unique` function to figure out which labels are present:",
"_____no_output_____"
]
],
[
[
"np.unique(label_image)",
"_____no_output_____"
]
],
[
[
"## Sequential labeling\nWe can now relabel this image and remove these gaps using [scikit-image's `relabel_sequential()` function](https://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.relabel_sequential). We're entering the `_` as additional return variables as we're not interested in them. This is necessary because the `relabel_sequential` function returns three things, but we only need the first.",
"_____no_output_____"
]
],
[
[
"relabeled, _, _ = relabel_sequential(label_image)\n\ncle.imshow(relabeled, labels=True)",
"_____no_output_____"
]
],
[
[
"Afterwards, the unique labels should be sequential:",
"_____no_output_____"
]
],
[
[
"np.unique(relabeled)",
"_____no_output_____"
]
],
[
[
"Also pyclesperanto has a function for relabeling label images sequentially. The result is supposed identical to the result in scikit-image. It just doesn't return the additional values.",
"_____no_output_____"
]
],
[
[
"relabeled1 = cle.relabel_sequential(label_image)\n\ncle.imshow(relabeled1, labels=True)",
"_____no_output_____"
]
],
[
[
"## Reverting sequential labeling\nIn some cases we apply an operation to a label image that returns a new label image with less labels that are sequentially labeled but the label-identity is lost. This happens for example when excluding labels from the label image that are too small.",
"_____no_output_____"
]
],
[
[
"large_labels = cle.exclude_small_labels(relabeled, maximum_size=260)\n\ncle.imshow(large_labels, labels=True, max_display_intensity=4)",
"_____no_output_____"
],
[
"np.unique(large_labels)",
"_____no_output_____"
]
],
[
[
"To restore the original label identities, we need to multiply a binary image representing the remaining labels with the original label image.",
"_____no_output_____"
]
],
[
[
"binary_remaining_labels = large_labels > 0\n\ncle.imshow(binary_remaining_labels)",
"_____no_output_____"
],
[
"large_labels_with_original_identity = binary_remaining_labels * relabeled\n\ncle.imshow(large_labels_with_original_identity, labels=True, max_display_intensity=4)",
"_____no_output_____"
],
[
"np.unique(large_labels_with_original_identity)",
"_____no_output_____"
]
],
[
[
"We can now conclude that labels with identities 2 and 4 were too small and thus, excluded.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e78842c699fc4738978b6e8b2948a871036d59d3 | 173,860 | ipynb | Jupyter Notebook | multimodel-1obs-1step.ipynb | righthandabacus/market_notebooks | e32c6a5a5b897c562b0a2793f9fe2e848e01ef07 | [
"MIT"
] | null | null | null | multimodel-1obs-1step.ipynb | righthandabacus/market_notebooks | e32c6a5a5b897c562b0a2793f9fe2e848e01ef07 | [
"MIT"
] | null | null | null | multimodel-1obs-1step.ipynb | righthandabacus/market_notebooks | e32c6a5a5b897c562b0a2793f9fe2e848e01ef07 | [
"MIT"
] | null | null | null | 431.414392 | 38,388 | 0.933067 | [
[
[
"# Multiple single-step forecast models",
"_____no_output_____"
],
[
"models studied in Zoumpekas et al (2020)",
"_____no_output_____"
]
],
[
[
"import random\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import Callback\nfrom tensorflow.keras.layers import Dense, Input, Conv1D, LSTM, GRU, Bidirectional, Dropout, Flatten\nfrom tensorflow.keras import Model, Sequential\nfrom tensorflow.keras.initializers import RandomNormal\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\n\nl2reg = l2(l2=0.0001)\n\ncnn2 = Sequential([\n Input(shape=(6,2), name=\"conv1d_1_input\"),\n Conv1D(80, kernel_size=3, strides=1, activation=\"relu\", kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"conv1d_1\"),\n Dropout(0.20, name=\"dropout_1\"),\n Conv1D(2, kernel_size=3, strides=2, activation=\"linear\", kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"conv1d_2\"),\n Flatten(),\n Dense(1, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"dense_1\")\n])\n\ncnn3 = Sequential([\n Input(shape=(6,2), name=\"conv1d_1_input\"),\n Conv1D(80, kernel_size=3, strides=1, activation=\"relu\", kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"conv1d_1\"),\n Dropout(0.20, name=\"dropout_1\"),\n Conv1D(40, kernel_size=2, strides=1, activation=\"relu\", kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"conv1d_2\"),\n Dropout(0.20, name=\"dropout_2\"),\n Conv1D(2, kernel_size=2, strides=2, activation=\"linear\", kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"conv1d_3\"),\n Flatten(),\n Dense(1, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"dense_1\")\n])\n\nlstm = Sequential([\n Input(shape=(6,2), name=\"lstm_1_input\"),\n LSTM(50, activation=\"tanh\", recurrent_dropout=0.2, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"lstm_1\"),\n Dropout(0.20, name=\"dropout_1\"),\n Dense(1, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"dense_1\")\n])\n\nslstm = Sequential([\n Input(shape=(6,2), name=\"lstm_1_input\"),\n LSTM(50, activation=\"tanh\", return_sequences=True, recurrent_dropout=0.2, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"lstm_1\"),\n Dropout(0.20, name=\"dropout_1\"),\n LSTM(50, activation=\"tanh\", recurrent_dropout=0.2, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"lstm_2\"),\n Dropout(0.20, name=\"dropout_2\"),\n Dense(1, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"dense_1\")\n])\n\nbilstm = Sequential([\n Input(shape=(6,2), name=\"lstm_1_input\"),\n Bidirectional(LSTM(50, activation=\"tanh\", recurrent_dropout=0.2, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"lstm_1\")),\n Dropout(0.20, name=\"dropout_1\"),\n Dense(1, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"dense_1\")\n])\n\ngru = Sequential([\n Input(shape=(6,2), name=\"gru_1_input\"),\n GRU(50, activation=\"tanh\", recurrent_dropout=0.2, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"gru_1\"),\n Dropout(0.20, name=\"dropout_1\"),\n Dense(1, kernel_regularizer=l2reg, bias_regularizer=l2reg, name=\"dense_1\")\n])",
"2021-12-14 00:35:32.549592: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_UNKNOWN: unknown error\n2021-12-14 00:35:32.549617: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: acer\n2021-12-14 00:35:32.549623: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: acer\n2021-12-14 00:35:32.549713: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:200] libcuda reported version is: 495.29.5\n2021-12-14 00:35:32.549734: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:204] kernel reported version is: 495.29.5\n2021-12-14 00:35:32.549740: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:310] kernel version seems to match DSO: 495.29.5\n2021-12-14 00:35:32.549981: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA\nTo enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
],
[
"from tensorflow.keras.utils import plot_model\nplot_model(cnn2, show_shapes=True, show_layer_names=True, dpi=64)",
"_____no_output_____"
],
[
"plot_model(cnn3, show_shapes=True, show_layer_names=True, dpi=64)",
"_____no_output_____"
],
[
"plot_model(lstm, show_shapes=True, show_layer_names=True, dpi=64)",
"_____no_output_____"
],
[
"plot_model(slstm, show_shapes=True, show_layer_names=True, dpi=64)",
"_____no_output_____"
],
[
"plot_model(bilstm, show_shapes=True, show_layer_names=True, dpi=64)",
"_____no_output_____"
],
[
"plot_model(gru, show_shapes=True, show_layer_names=True, dpi=64)",
"_____no_output_____"
],
[
"# Build data generator\ndef datagen(data, seq_len, batch_size, targetcol):\n \"As a generator to produce samples for Keras model\"\n # Learn about the data's features and time axis\n input_cols = [c for c in data.columns if c != targetcol]\n # Infinite loop to generate a batch\n batch = []\n while True:\n # Pick one position, then clip a sequence length\n while True:\n t = random.choice(data.index)\n n = (data.index == t).argmax()\n if n-seq_len+1 < 0:\n continue # this sample is not enough for one sequence length\n frame = data.iloc[n-seq_len+1:n+1][input_cols].T\n target = data.iloc[n+1][targetcol]\n # extract 2D array\n batch.append([frame, data.iloc[n+1][targetcol]])\n break\n # if we get enough for a batch, dispatch\n if len(batch) == batch_size:\n X, y = zip(*batch)\n yield np.array(X, dtype=\"float32\"), np.array(y, dtype=\"float32\")\n batch = []\n \ndef read_data(filename):\n # Read data into pandas DataFrames\n X = pd.read_csv(filename, index_col=\"Timestamp\")\n X.index = pd.to_datetime(X.index, unit=\"s\")\n # target is next day closing price\n cols = X.columns\n X[\"Target\"] = X[\"Close\"].shift(-1)\n X.dropna(inplace=True)\n return X",
"_____no_output_____"
],
[
"# Read data\nTRAINFILE = \"dataset/Ethereum_price_data_train.csv\"\nVALIDFILE = \"dataset/EThereum_price_data_test_29_May_2018-30_December_2018.csv\"\n\ndf_train = read_data(TRAINFILE)\ndf_valid = read_data(VALIDFILE)",
"_____no_output_____"
],
[
"# Training in SGD with batch size 128 and 50 epochs\nseq_len = 2\nbatch_size = 128\nn_epochs = 50\nn_steps = 400\n\ncheckpoint_path = \"cnn2-{epoch}-{val_loss:.0f}.h5\"\ncallbacks = [\n ModelCheckpoint(checkpoint_path,\n monitor='val_loss', mode=\"max\",\n verbose=0, save_best_only=True, save_weights_only=False, save_freq=\"epoch\"),\n EarlyStopping(monitor=\"val_loss\", patience=3, restore_best_weights=True)\n]\ncnn2.compile(optimizer=\"adam\", loss=\"mse\")\ncnn2.fit(datagen(df_train, seq_len, batch_size, \"Target\"),\n validation_data=datagen(df_valid, seq_len, batch_size, \"Target\"),\n epochs=n_epochs, steps_per_epoch=n_steps, validation_steps=10, verbose=1, callbacks=callbacks)",
"Epoch 1/50\n400/400 [==============================] - 52s 129ms/step - loss: 5134155.0000 - val_loss: 36836.4336\nEpoch 2/50\n400/400 [==============================] - 51s 128ms/step - loss: 784477.2500 - val_loss: 21840.3535\nEpoch 3/50\n400/400 [==============================] - 51s 129ms/step - loss: 224073.4531 - val_loss: 6584.0576\nEpoch 4/50\n400/400 [==============================] - 51s 129ms/step - loss: 84045.1719 - val_loss: 5507.8584\nEpoch 5/50\n400/400 [==============================] - 52s 129ms/step - loss: 38750.0430 - val_loss: 1258.1412\nEpoch 6/50\n400/400 [==============================] - 52s 130ms/step - loss: 20047.4297 - val_loss: 407.4286\nEpoch 7/50\n400/400 [==============================] - 51s 129ms/step - loss: 14825.2490 - val_loss: 1907.7725\nEpoch 8/50\n400/400 [==============================] - 51s 129ms/step - loss: 7697.8579 - val_loss: 310.8632\nEpoch 9/50\n400/400 [==============================] - 52s 129ms/step - loss: 3882.0569 - val_loss: 84.9826\nEpoch 10/50\n400/400 [==============================] - 51s 129ms/step - loss: 4043.2842 - val_loss: 1336.3011\nEpoch 11/50\n400/400 [==============================] - 51s 129ms/step - loss: 2533.0771 - val_loss: 73.1278\nEpoch 12/50\n400/400 [==============================] - 52s 129ms/step - loss: 1831.2122 - val_loss: 44.2584\nEpoch 13/50\n400/400 [==============================] - 51s 129ms/step - loss: 1814.2236 - val_loss: 39.1109\nEpoch 14/50\n400/400 [==============================] - 52s 129ms/step - loss: 1474.9673 - val_loss: 124.2770\nEpoch 15/50\n400/400 [==============================] - 51s 129ms/step - loss: 1204.8274 - val_loss: 39.5159\nEpoch 16/50\n400/400 [==============================] - 51s 129ms/step - loss: 3227.2451 - val_loss: 2031.0986\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7886b62a7be184528ab0e0422ba9e13196db598 | 32,957 | ipynb | Jupyter Notebook | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular | efb93340653c4a69b1c3a60c88a82116d7906148 | [
"Apache-2.0"
] | 124 | 2021-10-08T19:59:52.000Z | 2022-03-27T22:13:26.000Z | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | NVIDIA-Merlin/NVTabular | 650f6923f0533dcfa18f6e181116ada706a41f6a | [
"Apache-2.0"
] | 325 | 2021-10-08T19:58:49.000Z | 2022-03-31T21:27:39.000Z | examples/scaling-criteo/04-Triton-Inference-with-HugeCTR.ipynb | mikemckiernan/NVTabular | efb93340653c4a69b1c3a60c88a82116d7906148 | [
"Apache-2.0"
] | 26 | 2021-10-13T21:43:22.000Z | 2022-03-29T14:33:58.000Z | 42.580103 | 5,838 | 0.560822 | [
[
[
"# Copyright 2021 NVIDIA Corporation. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================",
"_____no_output_____"
]
],
[
[
"# Scaling Criteo: Triton Inference with HugeCTR\n\n## Overview\n\nThe last step is to deploy the ETL workflow and saved model to production. In the production setting, we want to transform the input data as during training (ETL). We need to apply the same mean/std for continuous features and use the same categorical mapping to convert the categories to continuous integer before we use the deep learning model for a prediction. Therefore, we deploy the NVTabular workflow with the HugeCTR model as an ensemble model to Triton Inference. The ensemble model guarantees that the same transformation are applied to the raw inputs.\n\n<img src='./imgs/triton-hugectr.png' width=\"25%\">\n\n### Learning objectives\n\nIn this notebook, we learn how to deploy our models to production:\n\n- Use **NVTabular** to generate config and model files for Triton Inference Server\n- Deploy an ensemble of NVTabular workflow and HugeCTR model\n- Send example request to Triton Inference Server",
"_____no_output_____"
],
[
"## Inference with Triton and HugeCTR\n\nFirst, we need to generate the Triton Inference Server configurations and save the models in the correct format. In the previous notebooks [02-ETL-with-NVTabular](./02-ETL-with-NVTabular.ipynb) and [03-Training-with-HugeCTR](./03-Training-with-HugeCTR.ipynb) we saved the NVTabular workflow and HugeCTR model to disk. We will load them.",
"_____no_output_____"
],
[
"### Saving Ensemble Model for Triton Inference Server",
"_____no_output_____"
],
[
"After training terminates, we can see that two `.model` files are generated. We need to move them inside a temporary folder, like `criteo_hugectr/1`. Let's create these folders.",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"Now we move our saved `.model` files inside 1 folder. We use only the last snapshot after `9600` iterations.",
"_____no_output_____"
]
],
[
[
"os.system(\"mv *9600.model ./criteo_hugectr/1/\")",
"_____no_output_____"
]
],
[
[
"Now we can save our models to be deployed at the inference stage. To do so we will use export_hugectr_ensemble method below. With this method, we can generate the config.pbtxt files automatically for each model. In doing so, we should also create a hugectr_params dictionary, and define the parameters like where the amazonreview.json file will be read, slots which corresponds to number of categorical features, `embedding_vector_size`, `max_nnz`, and `n_outputs` which is number of outputs.<br><br>\nThe script below creates an ensemble triton server model where\n- workflow is the the nvtabular workflow used in preprocessing,\n- hugectr_model_path is the HugeCTR model that should be served. \n- This path includes the .model files.name is the base name of the various triton models\n- output_path is the path where is model will be saved to.\n- cats are the categorical column names\n- conts are the continuous column names",
"_____no_output_____"
],
[
"We need to load the NVTabular workflow first",
"_____no_output_____"
]
],
[
[
"import nvtabular as nvt\n\nBASE_DIR = os.environ.get(\"BASE_DIR\", \"/raid/data/criteo\")\ninput_path = os.path.join(BASE_DIR, \"test_dask/output\")\nworkflow = nvt.Workflow.load(os.path.join(input_path, \"workflow\"))",
"_____no_output_____"
]
],
[
[
"Let's clear the directory",
"_____no_output_____"
]
],
[
[
"os.system(\"rm -rf /model/*\")",
"_____no_output_____"
],
[
"from nvtabular.inference.triton import export_hugectr_ensemble\n\nhugectr_params = dict()\nhugectr_params[\"config\"] = \"/model/criteo/1/criteo.json\"\nhugectr_params[\"slots\"] = 26\nhugectr_params[\"max_nnz\"] = 1\nhugectr_params[\"embedding_vector_size\"] = 128\nhugectr_params[\"n_outputs\"] = 1\nexport_hugectr_ensemble(\n workflow=workflow,\n hugectr_model_path=\"./criteo_hugectr/1/\",\n hugectr_params=hugectr_params,\n name=\"criteo\",\n output_path=\"/model/\",\n label_columns=[\"label\"],\n cats=[\"C\" + str(x) for x in range(1, 27)],\n conts=[\"I\" + str(x) for x in range(1, 14)],\n max_batch_size=64,\n)",
"_____no_output_____"
]
],
[
[
"We can take a look at the generated files.",
"_____no_output_____"
]
],
[
[
"!tree /model",
"\u001b[01;34m/model\u001b[00m\n├── \u001b[01;34mcriteo\u001b[00m\n│ ├── \u001b[01;34m1\u001b[00m\n│ │ ├── 0_opt_sparse_9600.model\n│ │ ├── \u001b[01;34m0_sparse_9600.model\u001b[00m\n│ │ │ ├── emb_vector\n│ │ │ ├── key\n│ │ │ └── slot_id\n│ │ ├── _dense_9600.model\n│ │ ├── _opt_dense_9600.model\n│ │ └── criteo.json\n│ └── config.pbtxt\n├── \u001b[01;34mcriteo_ens\u001b[00m\n│ ├── \u001b[01;34m1\u001b[00m\n│ └── config.pbtxt\n└── \u001b[01;34mcriteo_nvt\u001b[00m\n ├── \u001b[01;34m1\u001b[00m\n │ ├── model.py\n │ └── \u001b[01;34mworkflow\u001b[00m\n │ ├── \u001b[01;34mcategories\u001b[00m\n │ │ ├── unique.C1.parquet\n │ │ ├── unique.C10.parquet\n │ │ ├── unique.C11.parquet\n │ │ ├── unique.C12.parquet\n │ │ ├── unique.C13.parquet\n │ │ ├── unique.C14.parquet\n │ │ ├── unique.C15.parquet\n │ │ ├── unique.C16.parquet\n │ │ ├── unique.C17.parquet\n │ │ ├── unique.C18.parquet\n │ │ ├── unique.C19.parquet\n │ │ ├── unique.C2.parquet\n │ │ ├── unique.C20.parquet\n │ │ ├── unique.C21.parquet\n │ │ ├── unique.C22.parquet\n │ │ ├── unique.C23.parquet\n │ │ ├── unique.C24.parquet\n │ │ ├── unique.C25.parquet\n │ │ ├── unique.C26.parquet\n │ │ ├── unique.C3.parquet\n │ │ ├── unique.C4.parquet\n │ │ ├── unique.C5.parquet\n │ │ ├── unique.C6.parquet\n │ │ ├── unique.C7.parquet\n │ │ ├── unique.C8.parquet\n │ │ └── unique.C9.parquet\n │ ├── column_types.json\n │ ├── metadata.json\n │ └── workflow.pkl\n └── config.pbtxt\n\n9 directories, 40 files\n"
]
],
[
[
"We need to write a configuration file with the stored model weights and model configuration.",
"_____no_output_____"
]
],
[
[
"%%writefile '/model/ps.json'\n\n{\n \"supportlonglong\": true,\n \"models\": [\n {\n \"model\": \"criteo\",\n \"sparse_files\": [\"/model/criteo/1/0_sparse_9600.model\"],\n \"dense_file\": \"/model/criteo/1/_dense_9600.model\",\n \"network_file\": \"/model/criteo/1/criteo.json\",\n \"max_batch_size\": \"64\",\n \"gpucache\": \"true\",\n \"hit_rate_threshold\": \"0.9\",\n \"gpucacheper\": \"0.5\",\n \"num_of_worker_buffer_in_pool\": \"4\",\n \"num_of_refresher_buffer_in_pool\": \"1\",\n \"cache_refresh_percentage_per_iteration\": 0.2,\n \"deployed_device_list\": [\"0\"],\n \"default_value_for_each_table\": [\"0.0\", \"0.0\"],\n }\n ],\n}",
"Overwriting /model/ps.json\n"
]
],
[
[
"### Loading Ensemble Model with Triton Inference Server\n\nWe have only saved the models for Triton Inference Server. We started Triton Inference Server in explicit mode, meaning that we need to send a request that Triton will load the ensemble model.",
"_____no_output_____"
],
[
"We connect to the Triton Inference Server.",
"_____no_output_____"
]
],
[
[
"import tritonhttpclient\n\ntry:\n triton_client = tritonhttpclient.InferenceServerClient(url=\"localhost:8000\", verbose=True)\n print(\"client created.\")\nexcept Exception as e:\n print(\"channel creation failed: \" + str(e))",
"client created.\n"
]
],
[
[
"We deactivate warnings.",
"_____no_output_____"
]
],
[
[
"import warnings\n\nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
]
],
[
[
"We check if the server is alive.",
"_____no_output_____"
]
],
[
[
"triton_client.is_server_live()",
"GET /v2/health/live, headers None\n<HTTPSocketPoolResponse status=200 headers={'content-length': '0', 'content-type': 'text/plain'}>\n"
]
],
[
[
"We check the available models in the repositories:\n- criteo_ens: Ensemble \n- criteo_nvt: NVTabular \n- criteo: HugeCTR model",
"_____no_output_____"
]
],
[
[
"triton_client.get_model_repository_index()",
"POST /v2/repository/index, headers None\n\n<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '93'}>\nbytearray(b'[{\"name\":\".ipynb_checkpoints\"},{\"name\":\"criteo\"},{\"name\":\"criteo_ens\"},{\"name\":\"criteo_nvt\"}]')\n"
]
],
[
[
"We load the models individually.",
"_____no_output_____"
]
],
[
[
"%%time\n\ntriton_client.load_model(model_name=\"criteo_nvt\")",
"POST /v2/repository/models/criteo_nvt/load, headers None\n\n<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>\nLoaded model 'criteo_nvt'\nCPU times: user 4.21 ms, sys: 258 µs, total: 4.47 ms\nWall time: 20.6 s\n"
],
[
"%%time\n\ntriton_client.load_model(model_name=\"criteo\")",
"POST /v2/repository/models/criteo/load, headers None\n\n<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>\nLoaded model 'criteo'\nCPU times: user 1.8 ms, sys: 3.01 ms, total: 4.81 ms\nWall time: 32.4 s\n"
],
[
"%%time\n\ntriton_client.load_model(model_name=\"criteo_ens\")",
"POST /v2/repository/models/criteo_ens/load, headers None\n\n<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>\nLoaded model 'criteo_ens'\nCPU times: user 4.7 ms, sys: 0 ns, total: 4.7 ms\nWall time: 20.2 s\n"
]
],
[
[
"### Example Request to Triton Inference Server\n\nNow, the models are loaded and we can create a sample request. We read an example **raw batch** for inference.",
"_____no_output_____"
]
],
[
[
"# Get dataframe library - cudf or pandas\nfrom merlin.core.dispatch import get_lib\n\ndf_lib = get_lib()\n\n# read in the workflow (to get input/output schema to call triton with)\nbatch_path = os.path.join(BASE_DIR, \"converted/criteo\")\nbatch = df_lib.read_parquet(os.path.join(batch_path, \"*.parquet\"), num_rows=3)\nbatch = batch[[x for x in batch.columns if x != \"label\"]]\nprint(batch)",
" I1 I2 I3 I4 I5 I6 I7 I8 I9 I10 ... C17 \\\n0 5 110 <NA> 16 <NA> 1 0 14 7 1 ... -771205462 \n1 32 3 5 <NA> 1 0 0 61 5 0 ... -771205462 \n2 <NA> 233 1 146 1 0 0 99 7 0 ... -771205462 \n\n C18 C19 C20 C21 C22 C23 \\\n0 -1206449222 -1793932789 -1014091992 351689309 632402057 -675152885 \n1 -1578429167 -1793932789 -20981661 -1556988767 -924717482 391309800 \n2 1653545869 -1793932789 -1014091992 351689309 632402057 -675152885 \n\n C24 C25 C26 \n0 2091868316 809724924 -317696227 \n1 1966410890 -1726799382 -1218975401 \n2 883538181 -10139646 -317696227 \n\n[3 rows x 39 columns]\n"
]
],
[
[
"We prepare the batch for inference by using correct column names and data types. We use the same datatypes as defined in our dataframe.",
"_____no_output_____"
]
],
[
[
"batch.dtypes",
"_____no_output_____"
],
[
"import tritonclient.http as httpclient\nfrom tritonclient.utils import np_to_triton_dtype\n\ninputs = []\n\ncol_names = list(batch.columns)\ncol_dtypes = [np.int32] * len(col_names)\n\nfor i, col in enumerate(batch.columns):\n d = batch[col].fillna(0).values_host.astype(col_dtypes[i])\n d = d.reshape(len(d), 1)\n inputs.append(httpclient.InferInput(col_names[i], d.shape, np_to_triton_dtype(col_dtypes[i])))\n inputs[i].set_data_from_numpy(d)",
"_____no_output_____"
]
],
[
[
"We send the request to the triton server and collect the last output.",
"_____no_output_____"
]
],
[
[
"# placeholder variables for the output\noutputs = [httpclient.InferRequestedOutput(\"OUTPUT0\")]\n\n# build a client to connect to our server.\n# This InferenceServerClient object is what we'll be using to talk to Triton.\n# make the request with tritonclient.http.InferInput object\nresponse = triton_client.infer(\"criteo_ens\", inputs, request_id=\"1\", outputs=outputs)\n\nprint(\"predicted sigmoid result:\\n\", response.as_numpy(\"OUTPUT0\"))",
"POST /v2/models/criteo_ens/infer, headers {'Inference-Header-Content-Length': 3383}\nb'{\"id\":\"1\",\"inputs\":[{\"name\":\"I1\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I2\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I3\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I4\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I5\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I6\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I7\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I8\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I9\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I10\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I11\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I12\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"I13\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C1\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C2\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C3\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C4\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C5\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C6\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C7\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C8\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C9\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C10\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C11\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C12\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C13\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C14\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C15\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C16\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C17\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C18\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C19\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C20\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C21\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C22\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C23\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C24\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C25\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}},{\"name\":\"C26\",\"shape\":[3,1],\"datatype\":\"INT32\",\"parameters\":{\"binary_data_size\":12}}],\"outputs\":[{\"name\":\"OUTPUT0\",\"parameters\":{\"binary_data\":true}}]}\\x05\\x00\\x00\\x00 \\x00\\x00\\x00\\x00\\x00\\x00\\x00n\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\xe9\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x92\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0e\\x00\\x00\\x00=\\x00\\x00\\x00c\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x07\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x002\\x01\\x00\\x00U\\x0c\\x00\\x00\\x1d\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x01\\x00\\x00\\x00y\\rwb\\x8d\\xfd\\xf3\\xe5y\\rwbX]\\x1f\\xe2\\xa6\\xff\\xaa\\xa0\\x03B\\x98\\xad/D\\xea\\xaf\\xd5\\x15\\xaao\\r\\xc6\\xbeb\\xcf\\x7f\\\\\\x94!4\\x8a\\xda\\xeeIl8H\\'\\xb08#\\x9f\\xd6<M\\x06U\\xe7\\xcbm\\xcdo\\xcbm\\xcdo\\xcbm\\xcdo!\\xaa\\x805\\x81\\xed\\x16\\xabb\\xeb\\xf5\\xb5\\x03\\x89\\x80()lBC\\x8b\\xcc\\xf2\\xd1\\xa6\\xdf\\xdeFT\\xe1\\xf5\\x1d\\x1f\\x82N.\\xc1}\\x02.\\xa9\\xc0\\xe9}\\xc1}\\x02.1B|\\x0cd\\xdcRf1B|\\x0c\\x1f\\x1d\\x98\\x95\\'N\\xeb\\x99\\x84aq\\x12\\xb7\\xff\\xc5\\x00\\xb7\\xff\\xc5\\x00\\xb7\\xff\\xc5\\x007\\xe5N\\xbe7\\xe5N\\xbe7\\xe5N\\xbe\\xcct\\x0b\\x8a\\x99\\xfe\\xbb\\xf3\\x0b\\r\\x0f\\xf7\\xfa>\\xdcL\\xfa>\\xdcL\\xfa>\\xdcL\\xaaV\\x08\\xd2\\xaaV\\x08\\xd2\\xaaV\\x08\\xd2\\xba\\x0b\\x17\\xb8\\x11\\x15\\xeb\\xa1\\x8d\\x1b\\x8fb\\x0b\\xc2\\x12\\x95\\x0b\\xc2\\x12\\x95\\x0b\\xc2\\x12\\x95(/\\x8e\\xc3c\\xd8\\xbf\\xfe(/\\x8e\\xc3]Z\\xf6\\x14\\xa1<2\\xa3]Z\\xf6\\x14\\x89\\xb0\\xb1%V\\xee\\xe1\\xc8\\x89\\xb0\\xb1%\\x0b\\xfc\\xc1\\xd7\\xe8\\xe9R\\x17\\x0b\\xfc\\xc1\\xd7\\x9c`\\xaf|\\x8a\\x0c5u\\x05\\xb9\\xa94\\xfckC0\\xea!\\x13\\x99\\x02He\\xff\\x1dW\\x10\\xedW\\xe9W\\xb7\\x1dW\\x10\\xed'\n<HTTPSocketPoolResponse status=400 headers={'content-length': '122', 'content-type': 'text/plain'}>\n"
]
],
[
[
"Let's unload the model. We need to unload each model.",
"_____no_output_____"
]
],
[
[
"triton_client.unload_model(model_name=\"criteo_ens\")\ntriton_client.unload_model(model_name=\"criteo_nvt\")\ntriton_client.unload_model(model_name=\"criteo\")",
"POST /v2/repository/models/criteo_ens/unload, headers None\n{\"parameters\":{\"unload_dependents\":false}}\n<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>\nLoaded model 'criteo_ens'\nPOST /v2/repository/models/criteo_nvt/unload, headers None\n{\"parameters\":{\"unload_dependents\":false}}\n<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>\nLoaded model 'criteo_nvt'\nPOST /v2/repository/models/criteo/unload, headers None\n{\"parameters\":{\"unload_dependents\":false}}\n<HTTPSocketPoolResponse status=200 headers={'content-type': 'application/json', 'content-length': '0'}>\nLoaded model 'criteo'\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"
] | [
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7886f26fbae6a2d95e7dbc3d1887c54a5084795 | 7,560 | ipynb | Jupyter Notebook | docs/source/user_guide/clean/clean_headers.ipynb | jwa345/dataprep | cb386934b0e151ef538c3873ae8fa37bb8bd1513 | [
"MIT"
] | 1,229 | 2019-12-21T02:58:59.000Z | 2022-03-30T08:12:33.000Z | docs/source/user_guide/clean/clean_headers.ipynb | jwa345/dataprep | cb386934b0e151ef538c3873ae8fa37bb8bd1513 | [
"MIT"
] | 680 | 2019-12-19T06:09:23.000Z | 2022-03-31T04:15:25.000Z | docs/source/user_guide/clean/clean_headers.ipynb | jwa345/dataprep | cb386934b0e151ef538c3873ae8fa37bb8bd1513 | [
"MIT"
] | 170 | 2020-01-08T03:27:26.000Z | 2022-03-20T20:42:55.000Z | 22.567164 | 240 | 0.519048 | [
[
[
".. _clean_headers_user_guide:\n\nColumn Headers\n==============",
"_____no_output_____"
],
[
"Introduction\n------------\n\nThe function :func:`clean_headers() <dataprep.clean.clean_headers.clean_headers>` cleans column headers in a DataFrame, and standardizes them in a desired format.",
"_____no_output_____"
]
],
[
[
"Column names can be converted to the following case styles via the `case` parameter:\n\n* snake: \"column_name\"\n* kebab: \"column-name\"\n* camel: \"columnName\"\n* pascal: \"ColumnName\"\n* const: \"COLUMN_NAME\"\n* sentence: \"Column name\"\n* title: \"Column Name\"\n* lower: \"column name\"\n* upper: \"COLUMN NAME\"\n\nAfter cleaning, a **report** is printed that provides the number and percentage of values that were cleaned (the value must be transformed).\n\nThe following sections demonstrate the functionality of `clean_headers()`.",
"_____no_output_____"
],
[
"### An example dirty dataset",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\ndf = pd.DataFrame(\n {\n \"ISBN\": [9781455582341],\n \"isbn\": [1455582328],\n \"bookTitle\": [\"How Google Works\"],\n \"__Author\": [\"Eric Schmidt, Jonathan Rosenberg\"],\n \"Publication (year)\": [2014],\n \"éditeur\": [\"Grand Central Publishing\"],\n \"Number_Of_Pages\": [305],\n \"★ Rating\": [4.06],\n }\n )\ndf",
"_____no_output_____"
]
],
[
[
"## 1. Default `clean_headers()`",
"_____no_output_____"
],
[
"By default, the `case` parameter is set to \"snake\" and the `remove_accents` parameter is set to True (strip accents and symbols from the column name).",
"_____no_output_____"
]
],
[
[
"from dataprep.clean import clean_headers\nclean_headers(df)",
"_____no_output_____"
]
],
[
[
"Note that \"_1\" is appended to the second instance of the column name \"isbn\" to distinguish it from the first instance after the transformation. Consequently, all column names are considered to have been cleaned in this example.\n\nColumn names that are duplicated as a result of calling `clean_headers()` are automatically renamed to append a number to the end. The suffix used to append the number is inferred from the `case` parameter.",
"_____no_output_____"
],
[
"## 2. `case` parameter\n\nThis section demonstrates the supported case styles.\n\n### kebab",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"kebab\")",
"_____no_output_____"
]
],
[
[
"### camel",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"camel\")",
"_____no_output_____"
]
],
[
[
"### pascal",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"pascal\")",
"_____no_output_____"
]
],
[
[
"### const",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"const\")",
"_____no_output_____"
]
],
[
[
"### sentence",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"sentence\")",
"_____no_output_____"
]
],
[
[
"### title",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"title\")",
"_____no_output_____"
]
],
[
[
"### lower",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"lower\")",
"_____no_output_____"
]
],
[
[
"### upper",
"_____no_output_____"
]
],
[
[
"clean_headers(df, case=\"upper\")",
"_____no_output_____"
]
],
[
[
"## 3. `replace` parameter\n\nThe `replace` parameter takes in a dictionary of values in the column names to be replaced by new values.",
"_____no_output_____"
]
],
[
[
"clean_headers(df, replace={\"éditeur\": \"publisher\", \"★\": \"star\"})",
"_____no_output_____"
]
],
[
[
"## 4. `remove_accents` parameter\n\nBy default, the `remove_accents` parameter is set to True (strip accents and symbols from the column names). If set to False, any accents or symbols are kept in.",
"_____no_output_____"
]
],
[
[
"clean_headers(df, remove_accents=False)",
"_____no_output_____"
]
],
[
[
"## 5. Null headers\n\nNull column headers in the DataFrame are replaced with the default value \"header\". As with other column names, duplicated values are renamed with appended numbers. Null header values include `np.nan`, `None` and the empty string.",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({\"\": [9781455582341],\n np.nan: [\"How Google Works\"],\n None: [\"Eric Schmidt, Jonathan Rosenberg\"],\n \"N/A\": [2014],\n })\ndf",
"_____no_output_____"
],
[
"clean_headers(df)",
"_____no_output_____"
]
]
] | [
"raw",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"raw",
"raw"
],
[
"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"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e78887f06bb6e1d0ea39d80f4dca784e34f79f57 | 6,414 | ipynb | Jupyter Notebook | combined_models_output.ipynb | joshsia/monkey-neural-decoder | 665e109a9d8b25c30fe75ce13aee3da9a6a85de6 | [
"MIT"
] | null | null | null | combined_models_output.ipynb | joshsia/monkey-neural-decoder | 665e109a9d8b25c30fe75ce13aee3da9a6a85de6 | [
"MIT"
] | null | null | null | combined_models_output.ipynb | joshsia/monkey-neural-decoder | 665e109a9d8b25c30fe75ce13aee3da9a6a85de6 | [
"MIT"
] | null | null | null | 24.957198 | 78 | 0.522451 | [
[
[
"import numpy as np\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn, optim\nfrom torchvision import transforms, utils\nfrom torch.utils.data import TensorDataset, DataLoader\nimport time\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import (\n train_test_split,\n cross_validate,\n RandomizedSearchCV\n)\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.multiclass import OneVsOneClassifier\nfrom sklearn.ensemble import RandomForestRegressor\nfrom scipy.stats import loguniform, randint\n\n%matplotlib inline",
"_____no_output_____"
],
[
"with open(\"data/processed/training_data.pickle\", \"rb\") as f:\n training_data = pickle.load(f)\n\nwith open(\"data/processed/training_arm.pickle\", \"rb\") as f:\n training_arm = pickle.load(f)\n\nwith open(\"data/processed/mean_trajectory.pickle\", \"rb\") as f:\n mean_trajectory = pickle.load(f)\n\nwith open(\"trained_models/lr.pickle\", \"rb\") as f:\n lr = pickle.load(f)",
"_____no_output_____"
],
[
"class NeuralDecoder(nn.Module):\n def __init__(self, input_size, output_size):\n super().__init__()\n self.main = nn.Sequential(\n nn.Linear(input_size, 500),\n nn.ReLU(),\n nn.Linear(500, 1_000),\n nn.ReLU(),\n nn.Linear(1_000, 5_000),\n nn.ReLU(),\n nn.Linear(5_000, 10_000),\n nn.ReLU(),\n nn.Linear(10_000, 15_000),\n nn.ReLU(),\n nn.Linear(15_000, 10_000),\n nn.ReLU(),\n nn.Linear(10_000, 5_000),\n nn.ReLU(),\n nn.Linear(5_000, output_size)\n )\n\n def forward(self, x):\n out = self.main(x)\n return out\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nnn = NeuralDecoder(input_size=297, output_size=3_000)\nnn.load_state_dict(torch.load(\"trained_models/trained_nn.pt\",\n map_location=device))",
"_____no_output_____"
],
[
"data = np.concatenate((training_data, training_arm), axis=1)\ndata.shape",
"_____no_output_____"
],
[
"output_model1 = lr.predict(data[:, :297])\noutput_model1.shape",
"_____no_output_____"
],
[
"output_model2 = np.array(\n [mean_trajectory[f\"dir_{int(i)}\"] for i in output_model1])\noutput_model2.shape",
"_____no_output_____"
],
[
"output_model3 = nn(torch.Tensor(data[:, :297])).detach().numpy()\noutput_model3.shape",
"_____no_output_____"
],
[
"output_model1 = np.reshape(output_model1, (40_000, 1))\nprint(output_model1.shape)\nprint(output_model2.shape)\nprint(output_model3.shape)\n\noutput_models = np.concatenate(\n (output_model1, output_model2, output_model3), axis=1\n)",
"(40000, 1)\n(40000, 3000)\n(40000, 3000)\n"
],
[
"out_file = \"data/processed/output_models.pickle\"\nwith open(out_file, \"wb\") as f:\n pickle.dump(output_models, f)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e788881051f8660ca485d2d641179d5f40a4155c | 239,874 | ipynb | Jupyter Notebook | Pytorch/NNCLR.ipynb | ashishpatel26/Self-Supervisedd-Learning | 973129b34fcf8a05ad15871e16b717294005c854 | [
"MIT"
] | 2 | 2022-01-24T12:38:30.000Z | 2022-01-25T05:33:46.000Z | Pytorch/NNCLR.ipynb | ashishpatel26/Self-Supervisedd-Learning | 973129b34fcf8a05ad15871e16b717294005c854 | [
"MIT"
] | null | null | null | Pytorch/NNCLR.ipynb | ashishpatel26/Self-Supervisedd-Learning | 973129b34fcf8a05ad15871e16b717294005c854 | [
"MIT"
] | null | null | null | 605.742424 | 223,626 | 0.933473 | [
[
[
"### NNCLR\n* Nearest- Neighbor Contrastive Learning of visual Representations (NNCLR), samples the nearest neighbors from the dataset in the latent space, and treats them as positives. This provides more semantic variations than pre-defined transformations.\n* NNCLR Formulated by Google Research and DeepMind\n\n",
"_____no_output_____"
]
],
[
[
"# !pip install lightly av torch-summary",
"_____no_output_____"
],
[
"import torch\nfrom torch import nn\nimport torchvision\n\nfrom lightly.data import LightlyDataset\nfrom lightly.data import SimCLRCollateFunction\nfrom lightly.loss import NTXentLoss\nfrom lightly.models.modules import NNCLRProjectionHead\nfrom lightly.models.modules import NNCLRPredictionHead\nfrom lightly.models.modules import NNMemoryBankModule",
"_____no_output_____"
],
[
"class NNCLR(nn.Module):\n def __init__(self, backbone):\n super().__init__()\n\n self.backbone = backbone\n self.projection_head = NNCLRProjectionHead(512, 512, 128)\n self.prediction_head = NNCLRPredictionHead(128, 512, 128)\n\n def forward(self, x):\n y = self.backbone(x).flatten(start_dim=1)\n z = self.projection_head(y)\n p = self.prediction_head(z)\n z = z.detach()\n return z, p",
"_____no_output_____"
],
[
"resnet = torchvision.models.resnet18()\nbackbone = nn.Sequential(*list(resnet.children())[:-1])\nmodel = NNCLR(backbone)",
"_____no_output_____"
],
[
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel.to(device)",
"_____no_output_____"
],
[
"memory_bank = NNMemoryBankModule(size=4096)\nmemory_bank.to(device)",
"_____no_output_____"
],
[
"cifar10 = torchvision.datasets.CIFAR10(\"datasets/cifar10\", download=True)\ndataset = LightlyDataset.from_torch_dataset(cifar10)",
"Files already downloaded and verified\n"
],
[
"collate_fn = SimCLRCollateFunction(input_size=32)",
"_____no_output_____"
],
[
"dataloader = torch.utils.data.DataLoader(\n dataset,\n batch_size=256,\n collate_fn=collate_fn,\n shuffle=True,\n drop_last=True,\n num_workers=8,\n)",
"/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 8 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n cpuset_checked))\n"
],
[
"criterion = NTXentLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.06)",
"_____no_output_____"
],
[
"print(\"Starting Training\")\nfor epoch in range(5):\n total_loss = 0\n for (x0, x1), _, _ in dataloader:\n x0 = x0.to(device)\n x1 = x1.to(device)\n z0, p0 = model(x0)\n z1, p1 = model(x1)\n z0 = memory_bank(z0, update=False)\n z1 = memory_bank(z1, update=True)\n loss = 0.5 * (criterion(z0, p1) + criterion(z1, p0))\n total_loss += loss.detach()\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n avg_loss = total_loss / len(dataloader)\n print(f\"epoch: {epoch:>02}, loss: {avg_loss:.5f}\")",
"Starting Training\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e78889d70eb8c7285520110d2f603d56876b9af0 | 253,174 | ipynb | Jupyter Notebook | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf | fcb561eff35a0c57020868549181b2ac8a5e789b | [
"MIT"
] | 3 | 2020-11-17T18:21:48.000Z | 2021-05-30T04:03:51.000Z | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf | fcb561eff35a0c57020868549181b2ac8a5e789b | [
"MIT"
] | 2 | 2021-04-30T21:04:04.000Z | 2021-12-13T20:28:58.000Z | notebooks/06e_Predictive_Modeling-XGBoost-Copy1.ipynb | robindoering86/capstone_nf | fcb561eff35a0c57020868549181b2ac8a5e789b | [
"MIT"
] | 3 | 2020-11-17T18:21:50.000Z | 2021-09-06T02:32:51.000Z | 57.802283 | 11,284 | 0.634398 | [
[
[
"# Predictive Modelling: XGBoost",
"_____no_output_____"
],
[
"# Imports",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2\n\n# Pandas and numpy\nimport pandas as pd\nimport numpy as np\n\n# \nfrom IPython.display import display, clear_output\nimport sys\nimport time\n\n# Libraries for Visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom src.visualization.visualize import plot_corr_matrix, plot_multi, plot_norm_dist, plot_feature_importances\n\n# Some custom tools\nfrom src.data.tools import check_for_missing_vals\n\n# \nfrom src.models.predict_model import avg_model, run_combinations\n#from src.models.train_model import run_combinations \n\n# Alpaca API\nimport alpaca_trade_api as tradeapi\n\n# Pickle\nimport pickle\nimport os\nfrom pathlib import Path\n\n# To load variables from .env file into system environment\nfrom dotenv import find_dotenv, load_dotenv\n\nfrom atomm.Indicators import MomentumIndicators\nfrom atomm.DataManager.main import MSDataManager\nfrom atomm.Tools import calc_open_position, calc_returns\nfrom src.visualization.visualize import plot_confusion_matrix\nfrom atomm.Methods import BlockingTimeSeriesSplit, PurgedKFold \n\n\nimport time\n\n# scikit-learn\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import cross_val_score, TimeSeriesSplit\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix, plot_confusion_matrix\nfrom sklearn.metrics import accuracy_score, recall_score, f1_score, precision_score\nfrom sklearn.model_selection import train_test_split, TimeSeriesSplit\nfrom xgboost import XGBClassifier\n\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\n\n# For BayesianHyperparameter Optimization\nfrom atomm.Models.Tuning import search_space, BayesianSearch\nfrom hyperopt import space_eval\n\n# Visualization libraries\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.gridspec as gridspec\n#import matplotlib.style as style\nfrom scipy import stats",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
],
[
"# Load environment variables\nload_dotenv(find_dotenv())",
"_____no_output_____"
]
],
[
[
"## Loading the data",
"_____no_output_____"
]
],
[
[
"data_base_dir = os.environ.get('DATA_DIR_BASE_PATH')\ndata_base_dir",
"_____no_output_____"
],
[
"!pwd",
"/Users/robin/Documents/projects/python/capstone_nf/notebooks\n"
],
[
"fname = os.path.join(data_base_dir, 'processed', 'index.h5')\nfname = Path(fname)\n#fname = '../data/processed/index.h5'",
"_____no_output_____"
],
[
"# Load dataset from HDF storage\nwith pd.HDFStore(fname) as storage:\n djia = storage.get('nyse/cleaned/rand_symbols')\n y_2c = storage.get('nyse/engineered/target_two_class')\n y_3c = storage.get('nyse/engineered/target_three_class')\n df_moments = storage.get('nyse/engineered/features')\n #print(storage.info())\n \n# Create copies of the pristine data\nX = df_moments.copy()\ny = y_3c.copy()\ny2 = y_2c.copy()\nprices = djia.copy()",
"_____no_output_____"
],
[
"forecast_horizon = [1, 3, 5, 7, 10, 15, 20, 25, 30]\ninput_window_size = [3, 5, 7, 10, 15, 20, 25, 30]\nti_list = ['macd', 'rsi', 'stoc', 'roc', 'bbu', 'bbl', 'ema', 'atr', 'adx', 'cci', 'williamsr', 'stocd']\nsymbol_list = df_moments.columns.get_level_values(0).unique()",
"_____no_output_____"
],
[
"df_moments.columns.get_level_values(1).unique()",
"_____no_output_____"
]
],
[
[
"## Imputing missing values",
"_____no_output_____"
]
],
[
[
"X.shape",
"_____no_output_____"
],
[
"check_for_missing_vals(X)",
"No missing values found in dataframe\n"
]
],
[
[
"Prices values",
"_____no_output_____"
]
],
[
[
"prices.shape",
"_____no_output_____"
],
[
"check_for_missing_vals(prices)",
"No missing values found in dataframe\n"
],
[
"y_3c.shape",
"_____no_output_____"
],
[
"check_for_missing_vals(y_3c)",
"No missing values found in dataframe\n"
],
[
"y2.shape",
"_____no_output_____"
],
[
"check_for_missing_vals(y2)",
"No missing values found in dataframe\n"
]
],
[
[
"No missing values, and sizes of ```y.shape[0]``` and```X.shape[0]``` match.",
"_____no_output_____"
],
[
"# Scaling the features",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import MinMaxScaler, StandardScaler",
"_____no_output_____"
],
[
"#scale = MinMaxScaler()\nscale = StandardScaler()",
"_____no_output_____"
],
[
"scaled = scale.fit_transform(X)",
"_____no_output_____"
],
[
"scaled.shape",
"_____no_output_____"
],
[
"#X_scaled = pd.DataFrame(data=scaled, columns=X.columns)\nX_scaled = X",
"_____no_output_____"
]
],
[
[
"# Train-Test Split",
"_____no_output_____"
]
],
[
[
"# Use 70/30 train/test splits\ntest_p = .3",
"_____no_output_____"
],
[
"# Scaled, three-class\ntest_size = int((1 - test_p) * X_scaled.shape[0])\nX_train, X_test, y_train, y_test = X_scaled[:test_size], X_scaled[test_size:], y_3c[:test_size], y_3c[test_size:]\nprices_train, prices_test = djia[:test_size], djia[test_size:]",
"_____no_output_____"
],
[
"# Unscaled, two-class\ntest_size = int((1 - test_p) * X.shape[0])\nX_train, X_test, y_train, y_test = X[:test_size], X[test_size:], y2[:test_size], y2[test_size:]\nprices_train, prices_test = djia[:test_size], djia[test_size:]",
"_____no_output_____"
],
[
"# Scaled, two-class\ntest_size = int((1 - test_p) * X.shape[0])\nX_train, X_test, y_train, y_test = X_scaled[:test_size], X_scaled[test_size:], y2[:test_size], y2[test_size:]\nprices_train, prices_test = djia[:test_size], djia[test_size:]",
"_____no_output_____"
],
[
"#test_size = test_p\n#X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_3c, test_size=test_size, random_state=101)",
"_____no_output_____"
]
],
[
[
"# Model",
"_____no_output_____"
]
],
[
[
"symbol_list",
"_____no_output_____"
],
[
"symbol = 'T'\nn1 = 15\nn2 = 15\nn_estimators = 10\n# set up cross validation splits\ntscv = TimeSeriesSplit(n_splits=5)\nbtscv = BlockingTimeSeriesSplit(n_splits=5)\n#ppcv = PurgedKFold(n_splits=5)",
"_____no_output_____"
],
[
"# Creates a list of features for a given lookback window (n1)\nfeatures = [f'{x}_{n1}' for x in ti_list]\n# Creates a list of all features\nall_features = [f'{x}_{n}' for x in ti_list for n in input_window_size]",
"_____no_output_____"
]
],
[
[
"## Single lookback/lookahead combination",
"_____no_output_____"
]
],
[
[
"clf_svc1 = OneVsRestClassifier(\n BaggingClassifier(\n SVC(\n kernel='rbf',\n class_weight='balanced'\n ),\n max_samples=.4, \n n_estimators=n_estimators,\n n_jobs=-1)\n)\n\n\nclf_svc1.fit(X_train[symbol][[f'{x}_{n}' for x in ti_list]], y_train[symbol][f'signal_{n}'])",
"_____no_output_____"
],
[
"y_pred_svc1 = clf_svc1.predict(X_test[symbol][[f'{x}_{n}' for x in ti_list]])\nprint('Accuracy Score: ', accuracy_score(y_pred_svc1, y_test[symbol][f'signal_{n}']))\nprint(classification_report(y_pred_svc1, y_test[symbol][f'signal_{n}']))\nplot_confusion_matrix(\n clf_svc1,\n X_test[symbol][[f'{x}_{n}' for x in ti_list]],\n y_test[symbol][f'signal_{n}'],\n normalize='all'\n)",
"Accuracy Score: 0.5400340715502555\n precision recall f1-score support\n\n 0 0.91 0.52 0.66 505\n 1 0.19 0.68 0.29 82\n\n accuracy 0.54 587\n macro avg 0.55 0.60 0.48 587\nweighted avg 0.81 0.54 0.61 587\n\n"
]
],
[
[
"## All combinations",
"_____no_output_____"
],
[
"## Averaging across all 50 randomly selected stocks",
"_____no_output_____"
]
],
[
[
"avg_results, scores_dict, preds_dict, params_dict, returns_dict = avg_model(\n symbol_list,\n forecast_horizon, \n input_window_size, \n X_train, \n X_test, \n y_train, \n y_test, \n prices_test,\n model=clf_svc1,\n silent = False\n)",
"_____no_output_____"
]
],
[
[
"## Hyperparamter Optimization: GridSearch",
"_____no_output_____"
]
],
[
[
"gsearch_xgb.best_score_",
"_____no_output_____"
]
],
[
[
"## Hyperparamter Optimization: Bayesian Optimization",
"_____no_output_____"
],
[
"### XGBoost",
"_____no_output_____"
]
],
[
[
"n1=15\nn2=15\nsymbol='T'",
"_____no_output_____"
],
[
"y_train[symbol][f'signal_{n2}'].value_counts()",
"_____no_output_____"
],
[
"symbol_list",
"_____no_output_____"
],
[
"# Optimizing for accuracy_score",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgba, clf_bsearch_xgba, params_bsearch_xgba = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='accuracy_score'\n)",
"100%|██████████| 100/100 [06:56<00:00, 4.17s/it, best loss: -0.6690909090909091] \n##### Results #####\nScore best parameters: -0.6690909090909091\nBest parameters: {'booster': 'gblinear', 'colsample_bytree': 0.36129690778665075, 'cv': 'btscv', 'gamma': 0, 'learning_rate': 73.01990167419177, 'max_depth': 103, 'model': <class 'xgboost.sklearn.XGBClassifier'>, 'n_estimators': 904, 'n_jobs': -1, 'subsample': 1}\nTest Score (accuracy): 0.4565587734241908\nParameter combinations evaluated: 100\nTime elapsed: 417.04670810699463\n"
],
[
"y_pred_bsearch_xgba = clf_bsearch_xgba.predict(X_test[symbol][features])\nprint('Recall Score: ', recall_score(y_pred_bsearch_xgba, y_test[symbol][f'signal_{n2}']))\nprint(classification_report(y_pred_bsearch_xgba, y_test[symbol][f'signal_{n2}']))\nplot_confusion_matrix(\n clf_bsearch_xgba,\n X_test[symbol][features], y_test[symbol][f'signal_{n2}'],\n)\n\n",
"Recall Score: 0.0\n precision recall f1-score support\n\n 0 1.00 0.46 0.63 587\n 1 0.00 0.00 0.00 0\n\n accuracy 0.46 587\n macro avg 0.50 0.23 0.31 587\nweighted avg 1.00 0.46 0.63 587\n\n"
],
[
"calc_returns(y_pred_bsearch_xgba, djia[symbol][test_size:])",
"_____no_output_____"
],
[
"# Optimizing for recall_score",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgbb, clf_bsearch_xgbb, params_bsearch_xgbb = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='recall_score'\n)",
"100%|██████████| 100/100 [04:07<00:00, 2.47s/it, best loss: -0.911648686934728]\n##### Results #####\nScore best parameters: -0.911648686934728\nBest parameters: {'booster': 'gbtree', 'colsample_bytree': 0.5072711376222986, 'cv': 'tscv', 'gamma': 5, 'learning_rate': 30.882542347484573, 'max_depth': 2, 'model': <class 'xgboost.sklearn.XGBClassifier'>, 'n_estimators': 775, 'n_jobs': -1, 'subsample': 1}\nTest Score (accuracy): 0.5434412265758092\nParameter combinations evaluated: 100\nTime elapsed: 247.46733975410461\n"
],
[
"y_pred_bsearch_xgbb = clf_bsearch_xgbb.predict(X_test[symbol][features])\nprint('Recall Score: ', recall_score(y_pred_bsearch_xgbb, y_test[symbol][f'signal_{n2}']))\nprint(classification_report(y_pred_bsearch_xgbb, y_test[symbol][f'signal_{n2}']))\nplot_confusion_matrix(\n clf_bsearch_xgbb,\n X_test[symbol][features], y_test[symbol][f'signal_{n2}'],\n)",
"Recall Score: 0.5434412265758092\n precision recall f1-score support\n\n 0 0.00 0.00 0.00 0\n 1 1.00 0.54 0.70 587\n\n accuracy 0.54 587\n macro avg 0.50 0.27 0.35 587\nweighted avg 1.00 0.54 0.70 587\n\n"
],
[
"calc_returns(y_pred_bsearch_xgbb, djia[symbol][test_size:])",
"_____no_output_____"
],
[
"# f1_score as scoring metric",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgbc, clf_bsearch_xgbc, params_bsearch_xgbc = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='f1_score'\n)",
"100%|██████████| 100/100 [01:24<00:00, 1.18it/s, best loss: -1.0] \n##### Results #####\nScore best parameters: -1.0\nBest parameters: {'C': 1.2684596435401332, 'cv': 'tscv', 'gamma': 4.423721243560753e-07, 'max_samples': 0.6601903887287633, 'model': <class 'sklearn.svm._classes.SVC'>, 'normalize': 0, 'scale': 1}\nTest Score (accuracy): 0.5434412265758092\nParameter combinations evaluated: 100\nTime elapsed: 84.97224712371826\n"
],
[
"y_pred_bsearch_xgbc = clf_bsearch_xgbc.predict(X_test[symbol][features])\nprint('Recall Score: ', recall_score(y_pred_bsearch_xgbb, y_test[symbol][f'signal_{n2}']))\nprint(classification_report(y_pred_bsearch_xgbc, y_test[symbol][f'signal_{n2}']))\nplot_confusion_matrix(\n clf_bsearch_xgbc,\n X_test[symbol][features], y_test[symbol][f'signal_{n2}'],\n)",
"_____no_output_____"
],
[
"calc_returns(y_pred_bsearch_xgbc, djia[symbol][test_size:])",
"_____no_output_____"
],
[
"# Precision as scoring metric",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgbd, clf_bsearch_xgbd, params_bsearch_xgbd = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='precision_score'\n)",
"100%|██████████| 100/100 [01:14<00:00, 1.33it/s, best loss: -0.8559006211180125]\n##### Results #####\nScore best parameters: -0.8559006211180125\nBest parameters: {'C': 33.70248519605152, 'cv': 'btscv', 'gamma': 0.0013222898903965097, 'max_samples': 0.8926533257844226, 'model': <class 'sklearn.svm._classes.SVC'>, 'normalize': 1, 'scale': 1}\nTest Score (accuracy): 0.5366269165247018\nParameter combinations evaluated: 100\nTime elapsed: 75.24364185333252\n"
],
[
"y_pred_bsearch_xgbd = clf_bsearch_xgbd.predict(X_test[symbol][features])\nprint('Recall Score: ', recall_score(y_pred_bsearch_xgbd, y_test[symbol][f'signal_{n2}']))\nprint(classification_report(y_pred_bsearch_xgbd, y_test[symbol][f'signal_{n2}']))\nplot_confusion_matrix(\n clf_bsearch_xgbd,\n X_test[symbol][features], y_test[symbol][f'signal_{n2}'],\n)",
"Recall Score: 0.5685131195335277\n precision recall f1-score support\n\n 0 0.45 0.49 0.47 244\n 1 0.61 0.57 0.59 343\n\n accuracy 0.54 587\n macro avg 0.53 0.53 0.53 587\nweighted avg 0.54 0.54 0.54 587\n\n"
],
[
"calc_returns(y_pred_bsearch_xgbd, djia[symbol][test_size:])",
"_____no_output_____"
]
],
[
[
"### XGBoost with all features",
"_____no_output_____"
]
],
[
[
"# Accuracy as scoring metric",
"_____no_output_____"
],
[
"n1=15\nn2=15\nsymbol='T'",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgb1, clf_bsearch_xgb1, params_bsearch_xgb1 = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][all_features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][all_features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='accuracy_score'\n)",
" 1%| | 1/100 [00:06<11:13, 6.80s/it, best loss: -0.49378091494879806]"
],
[
"y_pred_xgb1 = clf_bsearch_xgb1.predict(X_test[symbol][all_features])\nprint('Accuracy Score: ', accuracy_score(y_pred_xgb1, y_test[symbol][f'signal_{n1}']))\nprint(classification_report(y_pred_xgb1, y_test[symbol][f'signal_{n1}']))\nplot_confusion_matrix(\n clf_bsearch_xgb1,\n X_test[symbol][all_features],\n y_test[symbol][f'signal_{n1}'],\n)\n\n",
"Accuracy Score: 0.5161839863713799\n precision recall f1-score support\n\n 0 0.37 0.46 0.41 212\n 1 0.64 0.55 0.59 375\n\n accuracy 0.52 587\n macro avg 0.50 0.50 0.50 587\nweighted avg 0.54 0.52 0.52 587\n\n"
],
[
"calc_returns(y_pred_xgb1, djia[symbol][test_size:])",
"_____no_output_____"
],
[
"# Recall as scoring metric",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgb2, clf_bsearch_xgb2, params_bsearch_xgb2 = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][all_features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][all_features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='recall_score'\n)",
"100%|██████████| 100/100 [00:57<00:00, 1.75it/s, best loss: -0.6399999999999999]\n##### Results #####\nScore best parameters: -0.6399999999999999\nBest parameters: {'C': 35.094482053713115, 'cv': 'btscv', 'gamma': 0.00033006568854120804, 'max_samples': 0.6965204658380075, 'model': <class 'sklearn.svm._classes.SVC'>, 'normalize': 0, 'scale': 0}\nTest Score (accuracy): 0.5485519591141397\nParameter combinations evaluated: 100\nTime elapsed: 57.48174428939819\n"
],
[
"y_pred_xgb2 = clf_bsearch_xgb2.predict(X_test[symbol][all_features])\nprint('Recall Score: ', recall_score(y_pred_xgb2, y_test[symbol][f'signal_{n1}']))\nprint(classification_report(y_pred_xgb2, y_test[symbol][f'signal_{n1}']))\nplot_confusion_matrix(\n clf_bsearch_xgb2, \n X_test[symbol][all_features], y_test[symbol][f'signal_{n1}']\n)\n",
"_____no_output_____"
],
[
"calc_returns(y_pred_xgb2, djia[symbol][test_size:])",
"_____no_output_____"
],
[
"# f1_score as scoring metric",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgb3, clf_bsearch_xgb3, params_bsearch_xgb3 = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][all_features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][all_features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='f1_score'\n)",
"100%|██████████| 100/100 [01:39<00:00, 1.00it/s, best loss: -0.6290909090909091]\n##### Results #####\nScore best parameters: -0.6290909090909091\nBest parameters: {'C': 4.347303095840981, 'cv': 'btscv', 'gamma': 5.3535089549065505e-08, 'max_samples': 0.6171437284292799, 'model': <class 'sklearn.svm._classes.SVC'>, 'normalize': 0, 'scale': 0}\nTest Score (accuracy): 0.5434412265758092\nParameter combinations evaluated: 100\nTime elapsed: 100.35282611846924\n"
],
[
"y_pred_xgb3 = clf_bsearch_xgb3.predict(X_test[symbol][all_features])\nprint('F1 Score: ', f1_score(y_pred_xgb3, y_test[symbol][f'signal_{n1}']))\nprint(classification_report(y_pred_xgb3, y_test[symbol][f'signal_{n1}']))\nplot_confusion_matrix(\n clf_bsearch_xgb3,\n X_test[symbol][all_features],\n y_test[symbol][f'signal_{n1}']\n)\n\n",
"F1 Score: 0.7041942604856511\n precision recall f1-score support\n\n 0 0.00 0.00 0.00 0\n 1 1.00 0.54 0.70 587\n\n accuracy 0.54 587\n macro avg 0.50 0.27 0.35 587\nweighted avg 1.00 0.54 0.70 587\n\n"
],
[
"calc_returns(y_pred_xgb3, djia[symbol][test_size:])",
"_____no_output_____"
],
[
"# precision_score as scoring metric",
"_____no_output_____"
],
[
"model = XGBClassifier\nbsearch_xgb4, clf_bsearch_xgb4, params_bsearch_xgb4 = BayesianSearch(\n search_space(model),\n model,\n X_train[symbol][all_features], \n y_train[symbol][f'signal_{n2}'], \n X_test[symbol][all_features],\n y_test[symbol][f'signal_{n2}'],\n num_eval=100,\n scoring_metric='precision_score'\n)",
" 1%| | 1/100 [00:00<00:20, 4.87it/s, best loss: -0.24727272727272726]"
],
[
"y_pred_xgb4 = clf_bsearch_xgb4.predict(X_test[symbol][all_features])\nprint('Precision Score: ', precision_score(y_pred_xgb4, y_test[symbol][f'signal_{n1}'], average='weighted'))\nprint(classification_report(y_pred_xgb4, y_test[symbol][f'signal_{n1}']))\nplot_confusion_matrix(\n clf_bsearch_xgb4,\n X_test[symbol][all_features],\n y_test[symbol][f'signal_{n1}']\n)\n",
"Precision Score: 0.5424982530220307\n precision recall f1-score support\n\n 0 0.45 0.49 0.47 246\n 1 0.61 0.57 0.59 341\n\n accuracy 0.54 587\n macro avg 0.53 0.53 0.53 587\nweighted avg 0.54 0.54 0.54 587\n\n"
],
[
"calc_returns(y_pred_xgb4, djia[symbol][test_size:])",
"_____no_output_____"
]
],
[
[
"## Running on all 50 stocks on best model",
"_____no_output_____"
]
],
[
[
"#best_params = {'bootstrap': False, 'criterion': 'gini', 'max_depth': 218, 'max_features': 1, 'min_samples_leaf': 19, 'n_estimators': 423}\n#model_2a = (n_jobs=-1, **params_rf4)\navg_results, scores_dict, preds_dict, params_dict, returns_dict = avg_model( \n symbol_list,\n forecast_horizon, \n input_window_size,\n ti_list,\n X_train, \n X_test, \n y_train, \n y_test, \n prices_test,\n model=clf_rf4,\n silent = False\n)",
"_____no_output_____"
],
[
"#best_params = {'bootstrap': False, 'criterion': 'gini', 'max_depth': 218, 'max_features': 1, 'min_samples_leaf': 19, 'n_estimators': 423}\n#model_2a = (n_jobs=-1, **params_rf4)\navg_results, scores_dict, preds_dict, params_dict, returns_dict = avg_model(\n symbol_list,\n forecast_horizon, \n input_window_size,\n ti_list,\n X_train, \n X_test, \n y_train, \n y_test, \n prices_test,\n model=RandomForestClassifier,\n silent = False,\n hyper_optimize=True,\n n_eval=10,\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",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7889122b26683c9a997d04ee0b1be1269237905 | 19,135 | ipynb | Jupyter Notebook | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models | 2c700da53210a16f75c468ba521061106afa6982 | [
"MIT"
] | null | null | null | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models | 2c700da53210a16f75c468ba521061106afa6982 | [
"MIT"
] | null | null | null | notebooks/pokemon/basic/convolutional/AE/pokemonAE_Convolutional_reconst_1ellwlb_01psnr.ipynb | Fidan13/Generative_Models | 2c700da53210a16f75c468ba521061106afa6982 | [
"MIT"
] | null | null | null | 22.25 | 185 | 0.559446 | [
[
[
"# Settings",
"_____no_output_____"
]
],
[
[
"%env TF_KERAS = 1\nimport os\nsep_local = os.path.sep\n\nimport sys\nsys.path.append('..'+sep_local+'..')\nprint(sep_local)",
"_____no_output_____"
],
[
"os.chdir('..'+sep_local+'..'+sep_local+'..'+sep_local+'..'+sep_local+'..')\nprint(os.getcwd())",
"_____no_output_____"
],
[
"import tensorflow as tf\nprint(tf.__version__)",
"_____no_output_____"
]
],
[
[
"# Dataset loading",
"_____no_output_____"
]
],
[
[
"dataset_name='pokemon'",
"_____no_output_____"
],
[
"images_dir = 'C:\\\\Users\\\\Khalid\\\\Documents\\projects\\\\pokemon\\DS06\\\\'\nvalidation_percentage = 20\nvalid_format = 'png'",
"_____no_output_____"
],
[
"from training.generators.file_image_generator import create_image_lists, get_generators",
"_____no_output_____"
],
[
"imgs_list = create_image_lists(\n image_dir=images_dir, \n validation_pct=validation_percentage, \n valid_imgae_formats=valid_format\n)",
"_____no_output_____"
],
[
"inputs_shape= image_size=(200, 200, 3)\nbatch_size = 32\nlatents_dim = 32\nintermediate_dim = 50",
"_____no_output_____"
],
[
"training_generator, testing_generator = get_generators(\n images_list=imgs_list, \n image_dir=images_dir, \n image_size=image_size, \n batch_size=batch_size, \n class_mode=None\n)",
"_____no_output_____"
],
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"train_ds = tf.data.Dataset.from_generator(\n lambda: training_generator, \n output_types=tf.float32 ,\n output_shapes=tf.TensorShape((batch_size, ) + image_size)\n)\n\ntest_ds = tf.data.Dataset.from_generator(\n lambda: testing_generator, \n output_types=tf.float32 ,\n output_shapes=tf.TensorShape((batch_size, ) + image_size)\n)",
"_____no_output_____"
],
[
"_instance_scale=1.0\nfor data in train_ds:\n _instance_scale = float(data[0].numpy().max())\n break",
"_____no_output_____"
],
[
"_instance_scale",
"_____no_output_____"
],
[
"import numpy as np\nfrom collections.abc import Iterable",
"_____no_output_____"
],
[
"if isinstance(inputs_shape, Iterable):\n _outputs_shape = np.prod(inputs_shape)",
"_____no_output_____"
],
[
"_outputs_shape",
"_____no_output_____"
]
],
[
[
"# Model's Layers definition",
"_____no_output_____"
]
],
[
[
"units=20\nc=50\nenc_lays = [\n tf.keras.layers.Conv2D(filters=units, kernel_size=3, strides=(2, 2), activation='relu'),\n tf.keras.layers.Conv2D(filters=units*9, kernel_size=3, strides=(2, 2), activation='relu'),\n tf.keras.layers.Flatten(),\n # No activation\n tf.keras.layers.Dense(latents_dim)\n]\n\ndec_lays = [\n tf.keras.layers.Dense(units=c*c*units, activation=tf.nn.relu),\n tf.keras.layers.Reshape(target_shape=(c , c, units)),\n tf.keras.layers.Conv2DTranspose(filters=units, kernel_size=3, strides=(2, 2), padding=\"SAME\", activation='relu'),\n tf.keras.layers.Conv2DTranspose(filters=units*3, kernel_size=3, strides=(2, 2), padding=\"SAME\", activation='relu'),\n \n # No activation\n tf.keras.layers.Conv2DTranspose(filters=3, kernel_size=3, strides=(1, 1), padding=\"SAME\")\n]",
"_____no_output_____"
]
],
[
[
"# Model definition",
"_____no_output_____"
]
],
[
[
"model_name = dataset_name+'AE_Convolutional_reconst_1ell_01psnr'\nexperiments_dir='experiments'+sep_local+model_name",
"_____no_output_____"
],
[
"from training.autoencoding_basic.autoencoders.autoencoder import autoencoder as AE",
"_____no_output_____"
],
[
"inputs_shape=image_size",
"_____no_output_____"
],
[
"variables_params = \\\n[\n {\n 'name': 'inference', \n 'inputs_shape':inputs_shape,\n 'outputs_shape':latents_dim,\n 'layers': enc_lays\n }\n\n ,\n \n {\n 'name': 'generative', \n 'inputs_shape':latents_dim,\n 'outputs_shape':inputs_shape,\n 'layers':dec_lays\n }\n]",
"_____no_output_____"
],
[
"from utils.data_and_files.file_utils import create_if_not_exist",
"_____no_output_____"
],
[
"_restore = os.path.join(experiments_dir, 'var_save_dir')",
"_____no_output_____"
],
[
"create_if_not_exist(_restore)\n_restore",
"_____no_output_____"
],
[
"#to restore trained model, set filepath=_restore",
"_____no_output_____"
],
[
"ae = AE( \n name=model_name,\n latents_dim=latents_dim,\n batch_size=batch_size,\n variables_params=variables_params, \n filepath=None\n )",
"_____no_output_____"
],
[
"from evaluation.quantitive_metrics.peak_signal_to_noise_ratio import prepare_psnr\nfrom statistical.losses_utilities import similarty_to_distance\nfrom statistical.ae_losses import expected_loglikelihood_with_lower_bound as ellwlb",
"_____no_output_____"
],
[
"ae.compile(loss={'x_logits': lambda x_true, x_logits: ellwlb(x_true, x_logits)+ 0.1*similarity_to_distance(prepare_psnr([ae.batch_size]+ae.get_inputs_shape()))(x_true, x_logits)})",
"_____no_output_____"
]
],
[
[
"# Callbacks",
"_____no_output_____"
]
],
[
[
"\nfrom training.callbacks.sample_generation import SampleGeneration\nfrom training.callbacks.save_model import ModelSaver",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"es = tf.keras.callbacks.EarlyStopping(\n monitor='loss', \n min_delta=1e-12, \n patience=12, \n verbose=1, \n restore_best_weights=False\n)",
"_____no_output_____"
],
[
"ms = ModelSaver(filepath=_restore)",
"_____no_output_____"
],
[
"csv_dir = os.path.join(experiments_dir, 'csv_dir')\ncreate_if_not_exist(csv_dir)\ncsv_dir = os.path.join(csv_dir, ae.name+'.csv')\ncsv_log = tf.keras.callbacks.CSVLogger(csv_dir, append=True)\ncsv_dir",
"_____no_output_____"
],
[
"image_gen_dir = os.path.join(experiments_dir, 'image_gen_dir')\ncreate_if_not_exist(image_gen_dir)",
"_____no_output_____"
],
[
"sg = SampleGeneration(latents_shape=latents_dim, filepath=image_gen_dir, gen_freq=5, save_img=True, gray_plot=False)",
"_____no_output_____"
]
],
[
[
"# Model Training",
"_____no_output_____"
]
],
[
[
"ae.fit(\n x=train_ds,\n input_kw=None,\n steps_per_epoch=int(1e4),\n epochs=int(1e6), \n verbose=2,\n callbacks=[ es, ms, csv_log, sg],\n workers=-1,\n use_multiprocessing=True,\n validation_data=test_ds,\n validation_steps=int(1e4)\n)",
"_____no_output_____"
]
],
[
[
"# Model Evaluation",
"_____no_output_____"
],
[
"## inception_score",
"_____no_output_____"
]
],
[
[
"from evaluation.generativity_metrics.inception_metrics import inception_score",
"_____no_output_____"
],
[
"is_mean, is_sigma = inception_score(ae, tolerance_threshold=1e-6, max_iteration=200)\nprint(f'inception_score mean: {is_mean}, sigma: {is_sigma}')",
"_____no_output_____"
]
],
[
[
"## Frechet_inception_distance",
"_____no_output_____"
]
],
[
[
"from evaluation.generativity_metrics.inception_metrics import frechet_inception_distance",
"_____no_output_____"
],
[
"fis_score = frechet_inception_distance(ae, training_generator, tolerance_threshold=1e-6, max_iteration=10, batch_size=32)\nprint(f'frechet inception distance: {fis_score}')",
"_____no_output_____"
]
],
[
[
"## perceptual_path_length_score",
"_____no_output_____"
]
],
[
[
"from evaluation.generativity_metrics.perceptual_path_length import perceptual_path_length_score",
"_____no_output_____"
],
[
"ppl_mean_score = perceptual_path_length_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200, batch_size=32)\nprint(f'perceptual path length score: {ppl_mean_score}')",
"_____no_output_____"
]
],
[
[
"## precision score",
"_____no_output_____"
]
],
[
[
"from evaluation.generativity_metrics.precision_recall import precision_score",
"_____no_output_____"
],
[
"_precision_score = precision_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)\nprint(f'precision score: {_precision_score}')",
"_____no_output_____"
]
],
[
[
"## recall score",
"_____no_output_____"
]
],
[
[
"from evaluation.generativity_metrics.precision_recall import recall_score",
"_____no_output_____"
],
[
"_recall_score = recall_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)\nprint(f'recall score: {_recall_score}')",
"_____no_output_____"
]
],
[
[
"# Image Generation",
"_____no_output_____"
],
[
"## image reconstruction",
"_____no_output_____"
],
[
"### Training dataset",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"from training.generators.image_generation_testing import reconstruct_from_a_batch",
"_____no_output_____"
],
[
"from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'reconstruct_training_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\nreconstruct_from_a_batch(ae, training_generator, save_dir)",
"_____no_output_____"
],
[
"from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'reconstruct_testing_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\nreconstruct_from_a_batch(ae, testing_generator, save_dir)",
"_____no_output_____"
]
],
[
[
"## with Randomness",
"_____no_output_____"
]
],
[
[
"from training.generators.image_generation_testing import generate_images_like_a_batch",
"_____no_output_____"
],
[
"from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'generate_training_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\ngenerate_images_like_a_batch(ae, training_generator, save_dir)",
"_____no_output_____"
],
[
"from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'generate_testing_images_like_a_batch_dir')\ncreate_if_not_exist(save_dir)\n\ngenerate_images_like_a_batch(ae, testing_generator, save_dir)",
"_____no_output_____"
]
],
[
[
"### Complete Randomness",
"_____no_output_____"
]
],
[
[
"from training.generators.image_generation_testing import generate_images_randomly",
"_____no_output_____"
],
[
"from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'random_synthetic_dir')\ncreate_if_not_exist(save_dir)\n\ngenerate_images_randomly(ae, save_dir)",
"_____no_output_____"
],
[
"from training.generators.image_generation_testing import interpolate_a_batch",
"_____no_output_____"
],
[
"from utils.data_and_files.file_utils import create_if_not_exist\nsave_dir = os.path.join(experiments_dir, 'interpolate_dir')\ncreate_if_not_exist(save_dir)\n\ninterpolate_a_batch(ae, testing_generator, save_dir)",
"100%|██████████| 15/15 [00:00<00:00, 19.90it/s]\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7889db7acc35b8590f3d5806dc36bb668b6ae28 | 6,915 | ipynb | Jupyter Notebook | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 0.16/_downloads/plot_ica_from_raw.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 48.020833 | 995 | 0.613883 | [
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\n\nCompute ICA on MEG data and remove artifacts\n============================================\n\nICA is fit to MEG raw data.\nThe sources matching the ECG and EOG are automatically found and displayed.\nSubsequently, artifact detection and rejection quality are assessed.\n\n",
"_____no_output_____"
]
],
[
[
"# Authors: Denis Engemann <[email protected]>\n# Alexandre Gramfort <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\n\nimport mne\nfrom mne.preprocessing import ICA\nfrom mne.preprocessing import create_ecg_epochs, create_eog_epochs\nfrom mne.datasets import sample",
"_____no_output_____"
]
],
[
[
"Setup paths and prepare raw data.\n\n",
"_____no_output_____"
]
],
[
[
"data_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\n\nraw = mne.io.read_raw_fif(raw_fname, preload=True)\nraw.filter(1, None, fir_design='firwin') # already lowpassed @ 40\nraw.annotations = mne.Annotations([1], [10], 'BAD')\nraw.plot(block=True)\n\n# For the sake of example we annotate first 10 seconds of the recording as\n# 'BAD'. This part of data is excluded from the ICA decomposition by default.\n# To turn this behavior off, pass ``reject_by_annotation=False`` to\n# :meth:`mne.preprocessing.ICA.fit`.\nraw.annotations = mne.Annotations([0], [10], 'BAD')",
"_____no_output_____"
]
],
[
[
"1) Fit ICA model using the FastICA algorithm.\nOther available choices are ``picard``, ``infomax`` or ``extended-infomax``.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>The default method in MNE is FastICA, which along with Infomax is\n one of the most widely used ICA algorithm. Picard is a\n new algorithm that is expected to converge faster than FastICA and\n Infomax, especially when the aim is to recover accurate maps with\n a low tolerance parameter, see [1]_ for more information.</p></div>\n\nWe pass a float value between 0 and 1 to select n_components based on the\npercentage of variance explained by the PCA components.\n\n",
"_____no_output_____"
]
],
[
[
"ica = ICA(n_components=0.95, method='fastica', random_state=0, max_iter=100)\n\npicks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False,\n stim=False, exclude='bads')\n\nica.fit(raw, picks=picks, decim=3, reject=dict(mag=4e-12, grad=4000e-13),\n verbose='warning') # low iterations -> does not fully converge\n\n# maximum number of components to reject\nn_max_ecg, n_max_eog = 3, 1 # here we don't expect horizontal EOG components",
"_____no_output_____"
]
],
[
[
"2) identify bad components by analyzing latent sources.\n\n",
"_____no_output_____"
]
],
[
[
"title = 'Sources related to %s artifacts (red)'\n\n# generate ECG epochs use detection via phase statistics\n\necg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5, picks=picks)\n\necg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')\nica.plot_scores(scores, exclude=ecg_inds, title=title % 'ecg', labels='ecg')\n\nshow_picks = np.abs(scores).argsort()[::-1][:5]\n\nica.plot_sources(raw, show_picks, exclude=ecg_inds, title=title % 'ecg')\nica.plot_components(ecg_inds, title=title % 'ecg', colorbar=True)\n\necg_inds = ecg_inds[:n_max_ecg]\nica.exclude += ecg_inds\n\n# detect EOG by correlation\n\neog_inds, scores = ica.find_bads_eog(raw)\nica.plot_scores(scores, exclude=eog_inds, title=title % 'eog', labels='eog')\n\nshow_picks = np.abs(scores).argsort()[::-1][:5]\n\nica.plot_sources(raw, show_picks, exclude=eog_inds, title=title % 'eog')\nica.plot_components(eog_inds, title=title % 'eog', colorbar=True)\n\neog_inds = eog_inds[:n_max_eog]\nica.exclude += eog_inds",
"_____no_output_____"
]
],
[
[
"3) Assess component selection and unmixing quality.\n\n",
"_____no_output_____"
]
],
[
[
"# estimate average artifact\necg_evoked = ecg_epochs.average()\nica.plot_sources(ecg_evoked, exclude=ecg_inds) # plot ECG sources + selection\nica.plot_overlay(ecg_evoked, exclude=ecg_inds) # plot ECG cleaning\n\neog_evoked = create_eog_epochs(raw, tmin=-.5, tmax=.5, picks=picks).average()\nica.plot_sources(eog_evoked, exclude=eog_inds) # plot EOG sources + selection\nica.plot_overlay(eog_evoked, exclude=eog_inds) # plot EOG cleaning\n\n# check the amplitudes do not change\nica.plot_overlay(raw) # EOG artifacts remain",
"_____no_output_____"
],
[
"# To save an ICA solution you can say:\n# ica.save('my_ica.fif')\n\n# You can later load the solution by saying:\n# from mne.preprocessing import read_ica\n# read_ica('my_ica.fif')\n\n# Apply the solution to Raw, Epochs or Evoked like this:\n# ica.apply(epochs)",
"_____no_output_____"
]
],
[
[
"References\n----------\n.. [1] Ablin, P., Cardoso, J.F., Gramfort, A., 2017. Faster Independent\n Component Analysis by preconditioning with Hessian approximations.\n arXiv:1706.08171\n\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e788a5240a6312f14c5a3e2cd8218bc04a90c92a | 12,782 | ipynb | Jupyter Notebook | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo | 9ee08f3112b5ad007a431cccc26598a1f28cf5b4 | [
"Apache-2.0"
] | null | null | null | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo | 9ee08f3112b5ad007a431cccc26598a1f28cf5b4 | [
"Apache-2.0"
] | null | null | null | tutorials/torchhub_inference_tutorial.ipynb | Spencer551/pytorchvideo | 9ee08f3112b5ad007a431cccc26598a1f28cf5b4 | [
"Apache-2.0"
] | null | null | null | 34.733696 | 821 | 0.546159 | [
[
[
"# Torch Hub Inference Tutorial\n\nIn this tutorial you'll learn:\n- how to load a pretrained model using Torch Hub \n- run inference to classify the action in a demo video",
"_____no_output_____"
],
[
"### Install and Import modules",
"_____no_output_____"
],
[
"If `torch`, `torchvision` and `pytorchvideo` are not installed, run the following cell:",
"_____no_output_____"
]
],
[
[
"try:\n import torch\nexcept ModuleNotFoundError:\n !pip install torch torchvision\n import os\n import sys\n import torch\n \nif torch.__version__=='1.6.0+cu101' and sys.platform.startswith('linux'):\n !pip install pytorchvideo\nelse:\n need_pytorchvideo=False\n try:\n # Running notebook locally\n import pytorchvideo\n except ModuleNotFoundError:\n need_pytorchvideo=True\n if need_pytorchvideo:\n # Install from GitHub\n !pip install \"git+https://github.com/facebookresearch/pytorchvideo.git\"",
"_____no_output_____"
],
[
"import json \nfrom torchvision.transforms import Compose, Lambda\nfrom torchvision.transforms._transforms_video import (\n CenterCropVideo,\n NormalizeVideo,\n)\nfrom pytorchvideo.data.encoded_video import EncodedVideo\nfrom pytorchvideo.transforms import (\n ApplyTransformToKey,\n ShortSideScale,\n UniformTemporalSubsample,\n UniformCropVideo\n) \nfrom typing import Dict",
"_____no_output_____"
]
],
[
[
"### Setup \n\nDownload the id to label mapping for the Kinetics 400 dataset on which the Torch Hub models were trained. \nThis will be used to get the category label names from the predicted class ids.",
"_____no_output_____"
]
],
[
[
"!wget https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json ",
"_____no_output_____"
],
[
"with open(\"kinetics_classnames.json\", \"r\") as f:\n kinetics_classnames = json.load(f)\n\n# Create an id to label name mapping\nkinetics_id_to_classname = {}\nfor k, v in kinetics_classnames.items():\n kinetics_id_to_classname[v] = str(k).replace('\"', \"\")",
"_____no_output_____"
]
],
[
[
"### Load Model using Torch Hub API\n\nPyTorchVideo provides several pretrained models through Torch Hub. Available models are described in [model zoo documentation](https://github.com/facebookresearch/pytorchvideo/blob/main/docs/source/model_zoo.md#kinetics-400). \n\nHere we are selecting the `slowfast_r50` model which was trained using a 8x8 setting on the Kinetics 400 dataset. \n\n\nNOTE: to run on GPU in Google Colab, in the menu bar selet: Runtime -> Change runtime type -> Harware Accelerator -> GPU\n",
"_____no_output_____"
]
],
[
[
"# Device on which to run the model\n# Set to cuda to load on GPU\ndevice = \"cpu\"\n\n# Pick a pretrained model \nmodel_name = \"slowfast_r50\"\nmodel = torch.hub.load(\"facebookresearch/pytorchvideo:main\", model=model_name, pretrained=True)\n\n# Set to eval mode and move to desired device\nmodel = model.to(device)\nmodel = model.eval()",
"_____no_output_____"
]
],
[
[
"### Define the transformations for the input required by the model\n\nBefore passing the video into the model we need to apply some input transforms and sample a clip of the correct duration.\n\nNOTE: The input transforms are specific to the model. If you choose a different model than the example in this tutorial, please refer to the code provided in the Torch Hub documentation and copy over the relevant transforms:\n- [SlowFast](https://pytorch.org/hub/facebookresearch_pytorchvideo_slowfast/)\n- [X3D](https://pytorch.org/hub/facebookresearch_pytorchvideo_x3d/)\n- [Slow](https://pytorch.org/hub/facebookresearch_pytorchvideo_resnet/)",
"_____no_output_____"
]
],
[
[
"####################\n# SlowFast transform\n####################\n\nside_size = 256\nmean = [0.45, 0.45, 0.45]\nstd = [0.225, 0.225, 0.225]\ncrop_size = 256\nnum_frames = 32\nsampling_rate = 2\nframes_per_second = 30\nalpha = 4\n\nclass PackPathway(torch.nn.Module):\n \"\"\"\n Transform for converting video frames as a list of tensors. \n \"\"\"\n def __init__(self):\n super().__init__()\n \n def forward(self, frames: torch.Tensor):\n fast_pathway = frames\n # Perform temporal sampling from the fast pathway.\n slow_pathway = torch.index_select(\n frames,\n 1,\n torch.linspace(\n 0, frames.shape[1] - 1, frames.shape[1] // alpha\n ).long(),\n )\n frame_list = [slow_pathway, fast_pathway]\n return frame_list\n\ntransform = ApplyTransformToKey(\n key=\"video\",\n transform=Compose(\n [\n UniformTemporalSubsample(num_frames),\n Lambda(lambda x: x/255.0),\n NormalizeVideo(mean, std),\n ShortSideScale(\n size=side_size\n ),\n CenterCropVideo(crop_size),\n PackPathway()\n ]\n ),\n)\n\n# The duration of the input clip is also specific to the model.\nclip_duration = (num_frames * sampling_rate)/frames_per_second",
"_____no_output_____"
]
],
[
[
"### Load an example video\nWe can test the classification of an example video from the kinetics validation set such as this [archery video](https://www.youtube.com/watch?v=3and4vWkW4s).",
"_____no_output_____"
]
],
[
[
"# Download the example video file\n!wget https://dl.fbaipublicfiles.com/pytorchvideo/projects/archery.mp4 ",
"--2022-03-06 12:01:29-- https://dl.fbaipublicfiles.com/pytorchvideo/projects/archery.mp4\nResolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.75.142, 172.67.9.4, 104.22.74.142, ...\nConnecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.75.142|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 549197 (536K) [video/mp4]\nSaving to: 'archery.mp4'\n\n 0K .......... .......... .......... .......... .......... 9% 289K 2s\n 50K .......... .......... .......... .......... .......... 18% 700K 1s\n 100K .......... .......... .......... .......... .......... 27% 405K 1s\n 150K .......... .......... .......... .......... .......... 37% 880K 1s\n 200K .......... .......... .......... .......... .......... 46% 678K 1s\n 250K .......... .......... .......... .......... .......... 55% 816K 0s\n 300K .......... .......... .......... .......... .......... 65% 1.00M 0s\n 350K .......... .......... .......... .......... .......... 74% 535K 0s\n 400K .......... .......... .......... .......... .......... 83% 1.19M 0s\n 450K .......... .......... .......... .......... .......... 93% 2.25M 0s\n 500K .......... .......... .......... ...... 100% 2.69M=0.8s\n\n2022-03-06 12:01:31 (689 KB/s) - 'archery.mp4' saved [549197/549197]\n\n"
],
[
"# Load the example video\nvideo_path = \"archery.mp4\" \n\n# Select the duration of the clip to load by specifying the start and end duration\n# The start_sec should correspond to where the action occurs in the video\nstart_sec = 0\nend_sec = start_sec + clip_duration \n\n# Initialize an EncodedVideo helper class\nvideo = EncodedVideo.from_path(video_path)\n\n# Load the desired clip\nvideo_data = video.get_clip(start_sec=start_sec, end_sec=end_sec)\n\n# Apply a transform to normalize the video input\nvideo_data = transform(video_data)\n\n# Move the inputs to the desired device\ninputs = video_data[\"video\"]\ninputs = [i.to(device)[None, ...] for i in inputs]",
"_____no_output_____"
]
],
[
[
"### Get model predictions",
"_____no_output_____"
]
],
[
[
"# Pass the input clip through the model \npreds = model(inputs)",
"_____no_output_____"
],
[
"# Get the predicted classes \npost_act = torch.nn.Softmax(dim=1)\npreds = post_act(preds)\npred_classes = preds.topk(k=5).indices\n\n# Map the predicted classes to the label names\npred_class_names = [kinetics_id_to_classname[int(i)] for i in pred_classes[0]]\nprint(\"Predicted labels: %s\" % \", \".join(pred_class_names))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e788a893e27e399036021a4ef11b0ee34c8d84b5 | 76,924 | ipynb | Jupyter Notebook | TS Analysis for each book/#97.Memoirs of a Geisha.ipynb | shef4793/Online-Book-Price-Aggregator | 9e829564cee2f5069839eba75f730e099841b8ad | [
"MIT"
] | null | null | null | TS Analysis for each book/#97.Memoirs of a Geisha.ipynb | shef4793/Online-Book-Price-Aggregator | 9e829564cee2f5069839eba75f730e099841b8ad | [
"MIT"
] | null | null | null | TS Analysis for each book/#97.Memoirs of a Geisha.ipynb | shef4793/Online-Book-Price-Aggregator | 9e829564cee2f5069839eba75f730e099841b8ad | [
"MIT"
] | null | null | null | 43.264342 | 24,140 | 0.628451 | [
[
[
"from plotly import __version__\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n\nimport plotly.graph_objs as go",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\ndf = pd.read_excel('books_variation.xlsx')\ndf.head()",
"_____no_output_____"
],
[
"book1 = df.loc[df['title'] == 'Memoirs of a Geisha']\nbook1 = book1.drop(columns='title')\nbook1",
"_____no_output_____"
],
[
"book1['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)\nindexed_book1 = book1.set_index(['date'])\nindexed_book1.index",
"_____no_output_____"
],
[
"data = [go.Scatter(x= indexed_book1.index, y= indexed_book1.price)]\nplot(data, filename='basic-line')",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `basic-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"#Determining rolling statistics\nrollmean = indexed_book1.rolling(window='14d').mean() #monthly basis\nrollstd = indexed_book1.rolling(window='14d').std()\nrollmean, rollstd",
"_____no_output_____"
],
[
"#Plotting Rolling Statistics\n\ntrace1 = go.Scatter(x= indexed_book1.index, y= indexed_book1.price, name='Original')\ntrace2 = go.Scatter(x= rollmean.index , y= rollmean.price, name= 'Rolling Mean')\ntrace3 = go.Scatter(x= rollstd.index , y= rollstd.price, name= 'Rolling Std')\ndata = [trace1, trace2, trace3]\n # Edit the layout\nlayout = dict(title = 'Rolling Mean and Standard Deviation',\n xaxis = dict(title = 'Date'),\n yaxis = dict(title = 'Price')\n )\nfig = dict(data=data, layout=layout)\nplot(fig, filename='styled-line')",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `styled-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"#Dickey-Fuller test\nfrom statsmodels.tsa.stattools import adfuller\n\ndftest = adfuller(indexed_book1['price'], autolag='AIC')\ndfout = pd.Series(dftest[0:4], index= ['Test statistic','p-value','lags used','number of observations used'])\nfor key,value in dftest[4].items():\n dfout['Critical value (%s)'%key] = value\nprint(dfout)\n",
"Test statistic -0.000000\np-value 0.958532\nlags used 7.000000\nnumber of observations used 6.000000\nCritical value (1%) -5.354256\nCritical value (5%) -3.646238\nCritical value (10%) -2.901198\ndtype: float64\n"
],
[
"#The test statistic is positive, meaning we are much less likely to reject the null hypothesis (it looks non-stationary).\n#Comparing the test statistic to the critical values, it looks like we would have to fail to reject the null hypothesis \n#that the time series is non-stationary and does have time-dependent structure.",
"_____no_output_____"
],
[
"#log transform the dataset to make the distribution of values more linear and better meet the expectations of this statistical test\nimport numpy as np\nindexed_book1_logscale = np.log(indexed_book1)\n\ndata = [go.Scatter(x= indexed_book1_logscale.index, y= indexed_book1_logscale.price)]\nplot(data, filename='line-mode')",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `line-mode` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"# Moving Average with log timeseries\n\nmoving_avg = indexed_book1_logscale.rolling(window='14d').mean()\nmoving_std = indexed_book1_logscale.rolling(window='14d').std()\nmoving_avg, moving_std",
"_____no_output_____"
],
[
"trace1 = go.Scatter(x= indexed_book1_logscale.index, y= indexed_book1_logscale.price)\ntrace2 = go.Scatter(x= moving_avg.index , y= moving_avg.price)\ndata = [trace1, trace2]\nplot(data, filename='basic-line')\n",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `basic-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"#Difference between log timeseries and moving average\n\nlogminusMA = indexed_book1_logscale - moving_avg\nlogminusMA",
"_____no_output_____"
],
[
"#Determining the Stationarity of data\n\nmoving_avg = logminusMA.rolling(window='14d').mean()\nmoving_std = logminusMA.rolling(window='14d').std()\n \ntrace1 = go.Scatter(x= logminusMA.index, y= logminusMA.price, name='Original')\ntrace2 = go.Scatter(x= moving_avg.index , y= moving_avg.price, name= 'Rolling Mean')\ntrace3 = go.Scatter(x= moving_std.index , y= moving_std.price, name= 'Rolling Std')\ndata = [trace1, trace2, trace3]\n # Edit the layout\nlayout = dict(title = 'Rolling Mean and Standard Deviation',\n xaxis = dict(title = 'Date'),\n yaxis = dict(title = 'Price'))\nfig = dict(data=data, layout=layout)\nplot(fig, filename='styled-line')",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `styled-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"print(\"Results of Dickey-Fuller test: \")\ndftest = adfuller(logminusMA['price'], autolag='AIC')\ndfout = pd.Series(dftest[0:4], index= ['Test statistic','p-value','lags used','number of observations used'])\nfor key,value in dftest[4].items():\n dfout['Critical value (%s)'%key] = value\nprint(dfout)",
"Results of Dickey-Fuller test: \nTest statistic -0.000000\np-value 0.958532\nlags used 7.000000\nnumber of observations used 6.000000\nCritical value (1%) -5.354256\nCritical value (5%) -3.646238\nCritical value (10%) -2.901198\ndtype: float64\n"
],
[
"#Calculate the weighted average to see the trend\n#DataFrame.ewm : Provides exponential weighted functions\n\nweighted_avg = indexed_book1_logscale.ewm(com=0.5).mean()\nweighted_avg",
"_____no_output_____"
],
[
"trace1 = go.Scatter(x= indexed_book1_logscale.index, y= indexed_book1_logscale.price)\ntrace2 = go.Scatter(x= weighted_avg.index , y= weighted_avg.price)\ndata = [trace1, trace2]\nplot(data, filename='basic-line')\n\n#As you can see, the trend is moving with the logged data with respect to time",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `basic-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"#Difference between log timeseries and weighted average\n\nlogminusWA = indexed_book1_logscale - weighted_avg\nprint(logminusWA)\n\n#Determining the Stationarity of data\n\nmoving_avg = logminusWA.rolling(window='14d').mean()\nmoving_std = logminusWA.rolling(window='14d').std()\n \ntrace1 = go.Scatter(x= logminusWA.index, y= logminusWA.price, name='Original')\ntrace2 = go.Scatter(x= moving_avg.index , y= moving_avg.price, name= 'Rolling Mean')\ntrace3 = go.Scatter(x= moving_std.index , y= moving_std.price, name= 'Rolling Std')\ndata = [trace1, trace2, trace3]\n # Edit the layout\nlayout = dict(title = 'Rolling Mean and Standard Deviation',\n xaxis = dict(title = 'Date'),\n yaxis = dict(title = 'Price'))\nfig = dict(data=data, layout=layout)\nplot(fig, filename='styled-line')",
" price\ndate \n2019-01-24 0.000000\n2019-01-25 0.000000\n2019-01-26 0.000000\n2019-01-27 0.000000\n2019-01-28 0.000000\n2019-01-29 -0.031683\n2019-01-30 0.021190\n2019-01-31 -0.049748\n2019-02-01 -0.016581\n2019-02-02 -0.005527\n2019-02-03 -0.001842\n2019-02-04 -0.000614\n2019-02-05 -0.010268\n2019-02-06 -0.042684\n"
],
[
"print(\"Results of Dickey-Fuller test: \")\ndftest = adfuller(logminusWA['price'], autolag='AIC')\ndfout = pd.Series(dftest[0:4], index= ['Test statistic','p-value','lags used','number of observations used'])\nfor key,value in dftest[4].items():\n dfout['Critical value (%s)'%key] = value\nprint(dfout)",
"Results of Dickey-Fuller test: \nTest statistic -0.000000\np-value 0.958532\nlags used 6.000000\nnumber of observations used 7.000000\nCritical value (1%) -4.938690\nCritical value (5%) -3.477583\nCritical value (10%) -2.843868\ndtype: float64\n"
],
[
"# No difference in the p-value from original data and weighted average data\n# Here timeseries is not stationary",
"_____no_output_____"
],
[
"#Shifting the values\n\nindexed_book1_logscale_diffshift = indexed_book1_logscale - indexed_book1_logscale.shift()\n\ndata = [go.Scatter(x= indexed_book1_logscale_diffshift.index, y= indexed_book1_logscale_diffshift.price)]\nplot(data, filename='basic-line')",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `basic-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"indexed_book1_logscale_diffshift.dropna(inplace=True)\n\n#Determining the Stationarity of data\n\nmoving_avg = indexed_book1_logscale_diffshift.rolling(window='14d').mean()\nmoving_std = indexed_book1_logscale_diffshift.rolling(window='14d').std()\n \ntrace1 = go.Scatter(x= indexed_book1_logscale_diffshift.index, y= indexed_book1_logscale_diffshift.price, name='Original')\ntrace2 = go.Scatter(x= moving_avg.index , y= moving_avg.price, name= 'Rolling Mean')\ntrace3 = go.Scatter(x= moving_std.index , y= moving_std.price, name= 'Rolling Std')\ndata = [trace1, trace2, trace3]\n # Edit the layout\nlayout = dict(title = 'Rolling Mean and Standard Deviation',\n xaxis = dict(title = 'Date'),\n yaxis = dict(title = 'Price'))\nfig = dict(data=data, layout=layout)\nplot(fig, filename='styled-line')",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `styled-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"print(\"Results of Dickey-Fuller test: \")\ndftest = adfuller(indexed_book1_logscale_diffshift['price'], autolag='AIC')\ndfout = pd.Series(dftest[0:4], index= ['Test statistic','p-value','lags used','number of observations used'])\nfor key,value in dftest[4].items():\n dfout['Critical value (%s)'%key] = value\nprint(dfout)\n\n# Here timeseries is stationary and null-hypothesis is rejected",
"Results of Dickey-Fuller test: \nTest statistic -0.000000\np-value 0.958532\nlags used 5.000000\nnumber of observations used 7.000000\nCritical value (1%) -4.938690\nCritical value (5%) -3.477583\nCritical value (10%) -2.843868\ndtype: float64\n"
],
[
"from statsmodels.tsa.seasonal import seasonal_decompose\n\ndecomposition = seasonal_decompose(indexed_book1_logscale)\n\ntrend = decomposition.trend\nseasonal = decomposition.seasonal\nresidual = decomposition.resid\n\nfrom plotly import tools\n\ntrace1 = go.Scatter(x= indexed_book1_logscale.index, y= indexed_book1_logscale.price, name='Original')\ntrace2 = go.Scatter(x= trend.index, y= trend.price, name='Trend')\ntrace3 = go.Scatter(x= seasonal.index, y= seasonal.price, name='Seasonality')\ntrace4 = go.Scatter(x= residual.index, y= residual.price, name='Residual')\n\nfig = tools.make_subplots(rows=4, cols=1)\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 2, 1)\nfig.append_trace(trace3, 3, 1)\nfig.append_trace(trace4, 4, 1)\n\n\nfig['layout'].update(title='Stacked subplots')\nplot(fig, filename='stacked-subplots')",
"This is the format of your plot grid:\n[ (1,1) x1,y1 ]\n[ (2,1) x2,y2 ]\n[ (3,1) x3,y3 ]\n[ (4,1) x4,y4 ]\n\n"
],
[
"#Residuals are irregualr in nature\n#So checking noise stationarity\n\ndecomposed_logdata = residual\ndecomposed_logdata.dropna(inplace=True)\n\n#Determining the Stationarity of data\n\nmoving_avg = decomposed_logdata.rolling(window='14d').mean()\nmoving_std = decomposed_logdata.rolling(window='14d').std()\n \ntrace1 = go.Scatter(x= decomposed_logdata.index, y= decomposed_logdata.price, name='Original')\ntrace2 = go.Scatter(x= moving_avg.index , y= moving_avg.price, name= 'Rolling Mean')\ntrace3 = go.Scatter(x= moving_std.index , y= moving_std.price, name= 'Rolling Std')\ndata = [trace1, trace2, trace3]\n # Edit the layout\nlayout = dict(title = 'Rolling Mean and Standard Deviation',\n xaxis = dict(title = 'Date'),\n yaxis = dict(title = 'Price'))\nfig = dict(data=data, layout=layout)\nplot(fig, filename='styled-line')",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\plotly\\offline\\offline.py:635: UserWarning:\n\nYour filename `styled-line` didn't end with .html. Adding .html to the end of your file.\n\n"
],
[
"#ACF and PACF plots\n\nfrom statsmodels.tsa.stattools import acf, pacf\n\nlag_acf = acf(indexed_book1_logscale_diffshift)\nlag_pacf = pacf(indexed_book1_logscale_diffshift)\n#lag_acf,lag_pacf\n\n#ACF\n#trace1 = go.Scatter(y= lag_acf, name='Autocorrelation Function', type='bar')\ntrace1 = {\"y\": lag_acf, \"name\": \"Autocorrelation Function\", \"type\": \"bar\"}\ntrace2 = {\"y\": lag_pacf, \"name\": \"Partial Autocorrelation Function\", \"type\": \"bar\"}\n#trace2 = go.Scatter(y= lag_pacf, name='Partial Autocorrelation Function', type='bar')\n\ndata = [trace1, trace2]\nlayout = dict(title = 'ACF and PACF Plots')\nfig = dict(data=data, layout=layout)\nplot(fig)",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\statsmodels\\regression\\linear_model.py:1283: RuntimeWarning:\n\ninvalid value encountered in sqrt\n\nC:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\statsmodels\\regression\\linear_model.py:1275: RuntimeWarning:\n\ninvalid value encountered in double_scalars\n\n"
],
[
"#AR Model\nfrom statsmodels.tsa.arima_model import ARIMA\n\nmodel = ARIMA(indexed_book1_logscale, order= (3,1,0))\nresults_AR = model.fit(disp=-1)\n\nprint(\"Plotting AR Model...\")\ntrace1 = go.Scatter(x= indexed_book1_logscale_diffshift.index, y= indexed_book1_logscale_diffshift.price, name='Original')\ntrace2 = go.Scatter(y=results_AR.fittedvalues, name='AR fitted values')\n\ndata = [trace1, trace2]\nlayout = dict(title = 'RSS: %.4f'%sum((results_AR.fittedvalues-indexed_book1_logscale_diffshift.price)**2))\nfig = dict(data=data, layout=layout)\nplot(fig)",
"Plotting AR Model...\n"
],
[
"#MA Model\nfrom statsmodels.tsa.arima_model import ARIMA\n\nmodel = ARIMA(indexed_book1_logscale, order= (0,1,0))\nresults_MA = model.fit(disp=-1)\n\nprint(\"Plotting MA Model...\")\ntrace1 = go.Scatter(x= indexed_book1_logscale_diffshift.index, y= indexed_book1_logscale_diffshift.price, name='Original')\ntrace2 = go.Scatter(y=results_MA.fittedvalues, name='MA fitted values')\n\ndata = [trace1, trace2]\nlayout = dict(title = 'RSS: %.4f'%sum((results_MA.fittedvalues-indexed_book1_logscale_diffshift.price)**2))\nfig = dict(data=data, layout=layout)\nplot(fig)",
"Plotting MA Model...\n"
],
[
"#AR Model is better as it has less RSS value than MA Model",
"_____no_output_____"
],
[
"prediction = pd.Series(results_AR.fittedvalues, copy=True)\nprint(prediction)\n\nprediction_cumsum = prediction.cumsum()\nprint(prediction_cumsum)",
"date\n2019-01-25 -0.021804\n2019-01-26 -0.034429\n2019-01-27 -0.042358\n2019-01-28 -0.047576\n2019-01-29 -0.047576\n2019-01-30 0.023028\n2019-01-31 -0.087865\n2019-02-01 0.060137\n2019-02-02 -0.005092\n2019-02-03 -0.026577\n2019-02-04 -0.047576\n2019-02-05 -0.047576\n2019-02-06 -0.025211\ndtype: float64\ndate\n2019-01-25 -0.021804\n2019-01-26 -0.056233\n2019-01-27 -0.098591\n2019-01-28 -0.146167\n2019-01-29 -0.193743\n2019-01-30 -0.170715\n2019-01-31 -0.258580\n2019-02-01 -0.198442\n2019-02-02 -0.203535\n2019-02-03 -0.230112\n2019-02-04 -0.277687\n2019-02-05 -0.325263\n2019-02-06 -0.350474\ndtype: float64\n"
],
[
"prediction_log = pd.Series(indexed_book1_logscale.price.ix[0], index = indexed_book1_logscale.index)\nprediction_log = prediction_log.add(prediction_cumsum, fill_value=0)\nprediction_log",
"C:\\Users\\Shefali\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:1: DeprecationWarning:\n\n\n.ix is deprecated. Please use\n.loc for label based indexing or\n.iloc for positional indexing\n\nSee the documentation here:\nhttp://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated\n\n"
],
[
"prediction_ARIMA = np.exp(prediction_log)\n\ntrace1 = go.Scatter(x= indexed_book1.index, y= indexed_book1.price, name='Original data')\ntrace2 = go.Scatter(y=prediction_ARIMA, name='prdiction')\n\ndata = [trace1, trace2]\nlayout = dict(title = \"Predictions\")\nfig = dict(data=data, layout=layout)\nplot(fig)",
"_____no_output_____"
],
[
"indexed_book1_logscale",
"_____no_output_____"
],
[
"forecast = results_AR.forecast(steps=7)\n#print(results_AR.forecast(steps=7))\n\nresults_AR.plot_predict(1,21)\nresults_AR.forecast(steps=7)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e788bc096fd9ab07e844a2534a2e38da04dcf4d4 | 199,567 | ipynb | Jupyter Notebook | demo.ipynb | namjiwon1023/Code_With_RL | 37beec975b1685e9f6cf991abed491b854b78173 | [
"MIT"
] | 3 | 2021-08-12T15:11:28.000Z | 2021-09-27T16:04:16.000Z | demo.ipynb | namjiwon1023/Code_With_RL | 37beec975b1685e9f6cf991abed491b854b78173 | [
"MIT"
] | null | null | null | demo.ipynb | namjiwon1023/Code_With_RL | 37beec975b1685e9f6cf991abed491b854b78173 | [
"MIT"
] | 1 | 2021-08-05T07:20:57.000Z | 2021-08-05T07:20:57.000Z | 376.541509 | 68,703 | 0.797076 | [
[
[
"import torch as T\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.distributions import Normal, Categorical\nimport numpy as np\nimport os\nimport copy\nimport gym\nfrom gym.wrappers import RescaleAction\nimport random\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom icsl_rl.utils import _read_yaml\n\nfrom icsl_rl.agent import DQNAgent, DoubleDQNAgent, DuelingDQNAgent, D3QNAgent, NoisyDQNAgent\nfrom icsl_rl.agent import DDPGAgent, TD3Agent, SACAgent, PPOAgent, A2CAgent, BC_SACAgent\nfrom icsl_rl.runner import Runner",
"_____no_output_____"
],
[
"parameter_patgh = './icsl_rl/Hyperparameter/dqn.yaml' # Algorithms can be chosen by themselves\nconfig = _read_yaml(parameter_patgh)\nprint(config)",
"{'algorithm': 'DQN', 'critic_lr': 0.001, 'gamma': 0.99, 'tau': 0.01, 'hidden_size': 128, 'update_rate': 100, 'buffer_size': 1000, 'batch_size': 32, 'epsilon': 1.0, 'min_epsilon': 0.1, 'epsilon_decay': 0.0005, 'use_epsilon': True, 'is_discrete': True, 'use_noisy_layer': False, 'is_off_policy': True}\n"
],
[
"import argparse\ndevice = T.device('cuda:0' if T.cuda.is_available() else 'cpu')\n# In the jupyter book, the argparse library is not easy to use, so use the following form instead\nargs = argparse.Namespace(algorithm='DQN', device=device, evaluate=False)\nprint(args)\n\nargs.__dict__ = config\nprint(args)\n\nargs.device = device # GPU or CPU\nargs.seed = 123 # random seed setting\nargs.render = False # Visualization during training.\nargs.time_steps = 3000000 # total training step\nargs.episode = 1000000 # total episode\nargs.save_dir = \"./model\" # Where to store the trained model\nargs.save_rate = 2000 # store rate\nargs.model_dir = \"\" # Where to store the trained model\nargs.evaluate_episodes = 10 # Parameters for Model Prediction\nargs.evaluate = False # Parameters for Model Prediction\nargs.evaluate_rate = 1000 # Parameters for Model Prediction\nargs.is_store_transition = False # Store expert data\nargs.env_name = 'CartPole-v0' # discrete env\nprint(args)",
"Namespace(algorithm='DQN', device=device(type='cuda', index=0), evaluate=False)\nNamespace(algorithm='DQN', batch_size=32, buffer_size=1000, critic_lr=0.001, epsilon=1.0, epsilon_decay=0.0005, gamma=0.99, hidden_size=128, is_discrete=True, is_off_policy=True, min_epsilon=0.1, tau=0.01, update_rate=100, use_epsilon=True, use_noisy_layer=False)\nNamespace(algorithm='DQN', batch_size=32, buffer_size=1000, critic_lr=0.001, device=device(type='cuda', index=0), env_name='CartPole-v0', episode=1000000, epsilon=1.0, epsilon_decay=0.0005, evaluate=False, evaluate_episodes=10, evaluate_rate=1000, gamma=0.99, hidden_size=128, is_discrete=True, is_off_policy=True, is_store_transition=False, min_epsilon=0.1, model_dir='', render=False, save_dir='./model', save_rate=2000, seed=123, tau=0.01, time_steps=3000000, update_rate=100, use_epsilon=True, use_noisy_layer=False)\n"
],
[
"def _random_seed(seed): # random seed setting\n if T.backends.cudnn.enabled:\n T.backends.cudnn.benchmark = False\n T.backends.cudnn.deterministic = True\n\n T.manual_seed(seed)\n T.cuda.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n print('Using GPU : ', T.cuda.is_available() , ' | Seed : ', seed)",
"_____no_output_____"
],
[
"_random_seed(args.seed)",
"Using GPU : True | Seed : 123\n"
],
[
"writer = SummaryWriter('./logs/' + args.algorithm) # Tensorboard",
"_____no_output_____"
],
[
"agent = DQNAgent(args) # agent setting\nrunner = Runner(agent, args, agent.env, writer)",
"_____no_output_____"
],
[
"runner.run() # Training",
" : 38 | Score : 136.0 | Avg score : 130.6 | Time_Step : 2137 | update number : 2106 |\n------ Save model ------\nEpisode : 39 | Score : 163.0 | Avg score : 140.5 | Time_Step : 2300 | update number : 2269 |\n------ Save model ------\nEpisode : 40 | Score : 170.0 | Avg score : 146.8 | Time_Step : 2470 | update number : 2439 |\n------ Save model ------\nEpisode : 41 | Score : 190.0 | Avg score : 148.2 | Time_Step : 2660 | update number : 2629 |\n------ Save model ------\nEpisode : 42 | Score : 200.0 | Avg score : 154.8 | Time_Step : 2860 | update number : 2829 |\n| Episode : 43 | Score : 140.0 | Predict Score : 197.5 | Avg score : 154.8 |\n------ Save model ------\nEpisode : 43 | Score : 141.0 | Avg score : 157.4 | Time_Step : 3001 | update number : 2970 |\n------ Save model ------\nEpisode : 44 | Score : 200.0 | Avg score : 163.2 | Time_Step : 3201 | update number : 3170 |\nEpisode : 45 | Score : 187.0 | Avg score : 163.2 | Time_Step : 3388 | update number : 3357 |\n------ Save model ------\nEpisode : 46 | Score : 200.0 | Avg score : 165.3 | Time_Step : 3588 | update number : 3557 |\n------ Save model ------\nEpisode : 47 | Score : 200.0 | Avg score : 178.7 | Time_Step : 3788 | update number : 3757 |\n------ Save model ------\nEpisode : 48 | Score : 200.0 | Avg score : 185.1 | Time_Step : 3988 | update number : 3957 |\n| Episode : 49 | Score : 12.0 | Predict Score : 200.0 | Avg score : 185.1 |\nEpisode : 49 | Score : 13.0 | Avg score : 170.1 | Time_Step : 4001 | update number : 3970 |\nEpisode : 50 | Score : 17.0 | Avg score : 154.8 | Time_Step : 4018 | update number : 3987 |\nEpisode : 51 | Score : 161.0 | Avg score : 151.9 | Time_Step : 4179 | update number : 4148 |\nEpisode : 52 | Score : 136.0 | Avg score : 145.5 | Time_Step : 4315 | update number : 4284 |\nEpisode : 53 | Score : 200.0 | Avg score : 151.4 | Time_Step : 4515 | update number : 4484 |\nEpisode : 54 | Score : 176.0 | Avg score : 149.0 | Time_Step : 4691 | update number : 4660 |\nEpisode : 55 | Score : 200.0 | Avg score : 150.3 | Time_Step : 4891 | update number : 4860 |\n| Episode : 56 | Score : 109.0 | Predict Score : 197.8 | Avg score : 150.3 |\nEpisode : 56 | Score : 110.0 | Avg score : 141.3 | Time_Step : 5001 | update number : 4970 |\nEpisode : 57 | Score : 137.0 | Avg score : 135.0 | Time_Step : 5138 | update number : 5107 |\nEpisode : 58 | Score : 83.0 | Avg score : 123.3 | Time_Step : 5221 | update number : 5190 |\nEpisode : 59 | Score : 105.0 | Avg score : 132.5 | Time_Step : 5326 | update number : 5295 |\nEpisode : 60 | Score : 116.0 | Avg score : 142.4 | Time_Step : 5442 | update number : 5411 |\nEpisode : 61 | Score : 103.0 | Avg score : 136.6 | Time_Step : 5545 | update number : 5514 |\nEpisode : 62 | Score : 124.0 | Avg score : 135.4 | Time_Step : 5669 | update number : 5638 |\nEpisode : 63 | Score : 119.0 | Avg score : 127.3 | Time_Step : 5788 | update number : 5757 |\nEpisode : 64 | Score : 142.0 | Avg score : 123.9 | Time_Step : 5930 | update number : 5899 |\n| Episode : 65 | Score : 70.0 | Predict Score : 181.3 | Avg score : 123.9 |\nEpisode : 65 | Score : 70.0 | Avg score : 110.9 | Time_Step : 6001 | update number : 5970 |\nEpisode : 66 | Score : 168.0 | Avg score : 116.7 | Time_Step : 6169 | update number : 6138 |\nEpisode : 67 | Score : 135.0 | Avg score : 116.5 | Time_Step : 6304 | update number : 6273 |\nEpisode : 68 | Score : 142.0 | Avg score : 122.4 | Time_Step : 6446 | update number : 6415 |\nEpisode : 69 | Score : 125.0 | Avg score : 124.4 | Time_Step : 6571 | update number : 6540 |\nEpisode : 70 | Score : 127.0 | Avg score : 125.5 | Time_Step : 6698 | update number : 6667 |\nEpisode : 71 | Score : 131.0 | Avg score : 128.3 | Time_Step : 6829 | update number : 6798 |\nEpisode : 72 | Score : 128.0 | Avg score : 128.7 | Time_Step : 6957 | update number : 6926 |\n| Episode : 73 | Score : 43.0 | Predict Score : 124.3 | Avg score : 128.7 |\nEpisode : 73 | Score : 43.0 | Avg score : 121.1 | Time_Step : 7001 | update number : 6970 |\nEpisode : 74 | Score : 20.0 | Avg score : 108.9 | Time_Step : 7021 | update number : 6990 |\nEpisode : 75 | Score : 21.0 | Avg score : 104.0 | Time_Step : 7042 | update number : 7011 |\nEpisode : 76 | Score : 21.0 | Avg score : 89.3 | Time_Step : 7063 | update number : 7032 |\nEpisode : 77 | Score : 16.0 | Avg score : 77.4 | Time_Step : 7079 | update number : 7048 |\nEpisode : 78 | Score : 19.0 | Avg score : 65.1 | Time_Step : 7098 | update number : 7067 |\nEpisode : 79 | Score : 126.0 | Avg score : 65.2 | Time_Step : 7224 | update number : 7193 |\nEpisode : 80 | Score : 124.0 | Avg score : 64.9 | Time_Step : 7348 | update number : 7317 |\nEpisode : 81 | Score : 154.0 | Avg score : 67.2 | Time_Step : 7502 | update number : 7471 |\nEpisode : 82 | Score : 185.0 | Avg score : 72.9 | Time_Step : 7687 | update number : 7656 |\nEpisode : 83 | Score : 200.0 | Avg score : 88.6 | Time_Step : 7887 | update number : 7856 |\n| Episode : 84 | Score : 113.0 | Predict Score : 197.5 | Avg score : 88.6 |\nEpisode : 84 | Score : 114.0 | Avg score : 98.0 | Time_Step : 8001 | update number : 7970 |\nEpisode : 85 | Score : 179.0 | Avg score : 113.8 | Time_Step : 8180 | update number : 8149 |\nEpisode : 86 | Score : 84.0 | Avg score : 120.1 | Time_Step : 8264 | update number : 8233 |\nEpisode : 87 | Score : 99.0 | Avg score : 128.4 | Time_Step : 8363 | update number : 8332 |\nEpisode : 88 | Score : 107.0 | Avg score : 137.2 | Time_Step : 8470 | update number : 8439 |\nEpisode : 89 | Score : 97.0 | Avg score : 134.3 | Time_Step : 8567 | update number : 8536 |\nEpisode : 90 | Score : 150.0 | Avg score : 136.9 | Time_Step : 8717 | update number : 8686 |\nEpisode : 91 | Score : 126.0 | Avg score : 134.1 | Time_Step : 8843 | update number : 8812 |\nEpisode : 92 | Score : 130.0 | Avg score : 128.6 | Time_Step : 8973 | update number : 8942 |\n| Episode : 93 | Score : 27.0 | Predict Score : 121.5 | Avg score : 128.6 |\nEpisode : 93 | Score : 27.0 | Avg score : 111.3 | Time_Step : 9001 | update number : 8970 |\nEpisode : 94 | Score : 162.0 | Avg score : 116.1 | Time_Step : 9163 | update number : 9132 |\nEpisode : 95 | Score : 136.0 | Avg score : 111.8 | Time_Step : 9299 | update number : 9268 |\nEpisode : 96 | Score : 136.0 | Avg score : 117.0 | Time_Step : 9435 | update number : 9404 |\nEpisode : 97 | Score : 200.0 | Avg score : 127.1 | Time_Step : 9635 | update number : 9604 |\nEpisode : 98 | Score : 155.0 | Avg score : 131.9 | Time_Step : 9790 | update number : 9759 |\nEpisode : 99 | Score : 155.0 | Avg score : 137.7 | Time_Step : 9945 | update number : 9914 |\n| Episode : 100 | Score : 55.0 | Predict Score : 196.3 | Avg score : 137.7 |\nEpisode : 100 | Score : 56.0 | Avg score : 128.3 | Time_Step : 10001 | update number : 9970 |\nEpisode : 101 | Score : 149.0 | Avg score : 130.6 | Time_Step : 10150 | update number : 10119 |\nEpisode : 102 | Score : 129.0 | Avg score : 130.5 | Time_Step : 10279 | update number : 10248 |\nEpisode : 103 | Score : 133.0 | Avg score : 141.1 | Time_Step : 10412 | update number : 10381 |\nEpisode : 104 | Score : 159.0 | Avg score : 140.8 | Time_Step : 10571 | update number : 10540 |\nEpisode : 105 | Score : 143.0 | Avg score : 141.5 | Time_Step : 10714 | update number : 10683 |\nEpisode : 106 | Score : 145.0 | Avg score : 142.4 | Time_Step : 10859 | update number : 10828 |\n| Episode : 107 | Score : 141.0 | Predict Score : 133.5 | Avg score : 142.4 |\nEpisode : 107 | Score : 141.0 | Avg score : 136.5 | Time_Step : 11001 | update number : 10970 |\nEpisode : 108 | Score : 128.0 | Avg score : 133.8 | Time_Step : 11129 | update number : 11098 |\nEpisode : 109 | Score : 137.0 | Avg score : 132.0 | Time_Step : 11266 | update number : 11235 |\nEpisode : 110 | Score : 134.0 | Avg score : 139.8 | Time_Step : 11400 | update number : 11369 |\nEpisode : 111 | Score : 135.0 | Avg score : 138.4 | Time_Step : 11535 | update number : 11504 |\nEpisode : 112 | Score : 152.0 | Avg score : 140.7 | Time_Step : 11687 | update number : 11656 |\nEpisode : 113 | Score : 180.0 | Avg score : 145.4 | Time_Step : 11867 | update number : 11836 |\n| Episode : 114 | Score : 133.0 | Predict Score : 153.0 | Avg score : 145.4 |\nEpisode : 114 | Score : 133.0 | Avg score : 142.8 | Time_Step : 12001 | update number : 11970 |\nEpisode : 115 | Score : 122.0 | Avg score : 140.7 | Time_Step : 12123 | update number : 12092 |\nEpisode : 116 | Score : 166.0 | Avg score : 142.8 | Time_Step : 12289 | update number : 12258 |\nEpisode : 117 | Score : 162.0 | Avg score : 144.9 | Time_Step : 12451 | update number : 12420 |\nEpisode : 118 | Score : 190.0 | Avg score : 151.1 | Time_Step : 12641 | update number : 12610 |\nEpisode : 119 | Score : 157.0 | Avg score : 153.1 | Time_Step : 12798 | update number : 12767 |\nEpisode : 120 | Score : 155.0 | Avg score : 155.2 | Time_Step : 12953 | update number : 12922 |\n| Episode : 121 | Score : 47.0 | Predict Score : 157.3 | Avg score : 155.2 |\nEpisode : 121 | Score : 47.0 | Avg score : 146.4 | Time_Step : 13001 | update number : 12970 |\nEpisode : 122 | Score : 162.0 | Avg score : 147.4 | Time_Step : 13163 | update number : 13132 |\nEpisode : 123 | Score : 144.0 | Avg score : 143.8 | Time_Step : 13307 | update number : 13276 |\nEpisode : 124 | Score : 176.0 | Avg score : 148.1 | Time_Step : 13483 | update number : 13452 |\nEpisode : 125 | Score : 200.0 | Avg score : 155.9 | Time_Step : 13683 | update number : 13652 |\nEpisode : 126 | Score : 166.0 | Avg score : 155.9 | Time_Step : 13849 | update number : 13818 |\n| Episode : 127 | Score : 151.0 | Predict Score : 163.7 | Avg score : 155.9 |\nEpisode : 127 | Score : 151.0 | Avg score : 154.8 | Time_Step : 14001 | update number : 13970 |\nEpisode : 128 | Score : 165.0 | Avg score : 152.3 | Time_Step : 14166 | update number : 14135 |\nEpisode : 129 | Score : 194.0 | Avg score : 156.0 | Time_Step : 14360 | update number : 14329 |\nEpisode : 130 | Score : 111.0 | Avg score : 151.6 | Time_Step : 14471 | update number : 14440 |\nEpisode : 131 | Score : 154.0 | Avg score : 162.3 | Time_Step : 14625 | update number : 14594 |\nEpisode : 132 | Score : 150.0 | Avg score : 161.1 | Time_Step : 14775 | update number : 14744 |\nEpisode : 133 | Score : 200.0 | Avg score : 166.7 | Time_Step : 14975 | update number : 14944 |\n| Episode : 134 | Score : 25.0 | Predict Score : 184.9 | Avg score : 166.7 |\nEpisode : 134 | Score : 25.0 | Avg score : 151.6 | Time_Step : 15001 | update number : 14970 |\nEpisode : 135 | Score : 200.0 | Avg score : 151.6 | Time_Step : 15201 | update number : 15170 |\nEpisode : 136 | Score : 166.0 | Avg score : 151.6 | Time_Step : 15367 | update number : 15336 |\nEpisode : 137 | Score : 156.0 | Avg score : 152.1 | Time_Step : 15523 | update number : 15492 |\nEpisode : 138 | Score : 134.0 | Avg score : 149.0 | Time_Step : 15657 | update number : 15626 |\nEpisode : 139 | Score : 134.0 | Avg score : 143.0 | Time_Step : 15791 | update number : 15760 |\nEpisode : 140 | Score : 110.0 | Avg score : 142.9 | Time_Step : 15901 | update number : 15870 |\n| Episode : 141 | Score : 99.0 | Predict Score : 118.8 | Avg score : 142.9 |\nEpisode : 141 | Score : 99.0 | Avg score : 137.4 | Time_Step : 16001 | update number : 15970 |\nEpisode : 142 | Score : 114.0 | Avg score : 133.8 | Time_Step : 16115 | update number : 16084 |\nEpisode : 143 | Score : 122.0 | Avg score : 126.0 | Time_Step : 16237 | update number : 16206 |\nEpisode : 144 | Score : 113.0 | Avg score : 134.8 | Time_Step : 16350 | update number : 16319 |\nEpisode : 145 | Score : 134.0 | Avg score : 128.2 | Time_Step : 16484 | update number : 16453 |\nEpisode : 146 | Score : 130.0 | Avg score : 124.6 | Time_Step : 16614 | update number : 16583 |\nEpisode : 147 | Score : 118.0 | Avg score : 120.8 | Time_Step : 16732 | update number : 16701 |\nEpisode : 148 | Score : 122.0 | Avg score : 119.6 | Time_Step : 16854 | update number : 16823 |\nEpisode : 149 | Score : 120.0 | Avg score : 118.2 | Time_Step : 16974 | update number : 16943 |\n| Episode : 150 | Score : 26.0 | Predict Score : 128.2 | Avg score : 118.2 |\nEpisode : 150 | Score : 26.0 | Avg score : 109.8 | Time_Step : 17001 | update number : 16970 |\nEpisode : 151 | Score : 139.0 | Avg score : 113.8 | Time_Step : 17140 | update number : 17109 |\nEpisode : 152 | Score : 120.0 | Avg score : 114.4 | Time_Step : 17260 | update number : 17229 |\nEpisode : 153 | Score : 112.0 | Avg score : 113.4 | Time_Step : 17372 | update number : 17341 |\nEpisode : 154 | Score : 132.0 | Avg score : 115.3 | Time_Step : 17504 | update number : 17473 |\nEpisode : 155 | Score : 116.0 | Avg score : 113.5 | Time_Step : 17620 | update number : 17589 |\nEpisode : 156 | Score : 102.0 | Avg score : 110.7 | Time_Step : 17722 | update number : 17691 |\nEpisode : 157 | Score : 18.0 | Avg score : 100.7 | Time_Step : 17740 | update number : 17709 |\nEpisode : 158 | Score : 121.0 | Avg score : 100.6 | Time_Step : 17861 | update number : 17830 |\n| Episode : 159 | Score : 139.0 | Predict Score : 138.5 | Avg score : 100.6 |\nEpisode : 159 | Score : 139.0 | Avg score : 102.5 | Time_Step : 18001 | update number : 17970 |\nEpisode : 160 | Score : 136.0 | Avg score : 113.5 | Time_Step : 18137 | update number : 18106 |\nEpisode : 161 | Score : 129.0 | Avg score : 112.5 | Time_Step : 18266 | update number : 18235 |\nEpisode : 162 | Score : 137.0 | Avg score : 114.2 | Time_Step : 18403 | update number : 18372 |\nEpisode : 163 | Score : 125.0 | Avg score : 115.5 | Time_Step : 18528 | update number : 18497 |\nEpisode : 164 | Score : 147.0 | Avg score : 117.0 | Time_Step : 18675 | update number : 18644 |\nEpisode : 165 | Score : 178.0 | Avg score : 123.2 | Time_Step : 18853 | update number : 18822 |\n| Episode : 166 | Score : 147.0 | Predict Score : 157.9 | Avg score : 123.2 |\nEpisode : 166 | Score : 147.0 | Avg score : 127.7 | Time_Step : 19001 | update number : 18970 |\nEpisode : 167 | Score : 200.0 | Avg score : 145.9 | Time_Step : 19201 | update number : 19170 |\nEpisode : 168 | Score : 181.0 | Avg score : 151.9 | Time_Step : 19382 | update number : 19351 |\nEpisode : 169 | Score : 181.0 | Avg score : 156.1 | Time_Step : 19563 | update number : 19532 |\nEpisode : 170 | Score : 199.0 | Avg score : 162.4 | Time_Step : 19762 | update number : 19731 |\nEpisode : 171 | Score : 200.0 | Avg score : 169.5 | Time_Step : 19962 | update number : 19931 |\n| Episode : 172 | Score : 38.0 | Predict Score : 199.4 | Avg score : 169.5 |\nEpisode : 172 | Score : 38.0 | Avg score : 159.6 | Time_Step : 20001 | update number : 19970 |\nEpisode : 173 | Score : 112.0 | Avg score : 158.3 | Time_Step : 20113 | update number : 20082 |\nEpisode : 174 | Score : 75.0 | Avg score : 151.1 | Time_Step : 20188 | update number : 20157 |\nEpisode : 175 | Score : 39.0 | Avg score : 137.2 | Time_Step : 20227 | update number : 20196 |\nEpisode : 176 | Score : 60.0 | Avg score : 128.5 | Time_Step : 20287 | update number : 20256 |\nEpisode : 177 | Score : 28.0 | Avg score : 111.3 | Time_Step : 20315 | update number : 20284 |\nEpisode : 178 | Score : 135.0 | Avg score : 106.7 | Time_Step : 20450 | update number : 20419 |\nEpisode : 179 | Score : 15.0 | Avg score : 90.1 | Time_Step : 20465 | update number : 20434 |\nEpisode : 180 | Score : 18.0 | Avg score : 72.0 | Time_Step : 20483 | update number : 20452 |\nEpisode : 181 | Score : 120.0 | Avg score : 64.0 | Time_Step : 20603 | update number : 20572 |\nEpisode : 182 | Score : 161.0 | Avg score : 76.3 | Time_Step : 20764 | update number : 20733 |\nEpisode : 183 | Score : 117.0 | Avg score : 76.8 | Time_Step : 20881 | update number : 20850 |\n| Episode : 184 | Score : 119.0 | Predict Score : 133.1 | Avg score : 76.8 |\nEpisode : 184 | Score : 119.0 | Avg score : 81.2 | Time_Step : 21001 | update number : 20970 |\nEpisode : 185 | Score : 157.0 | Avg score : 93.0 | Time_Step : 21158 | update number : 21127 |\nEpisode : 186 | Score : 200.0 | Avg score : 107.0 | Time_Step : 21358 | update number : 21327 |\nEpisode : 187 | Score : 200.0 | Avg score : 124.2 | Time_Step : 21558 | update number : 21527 |\nEpisode : 188 | Score : 200.0 | Avg score : 130.7 | Time_Step : 21758 | update number : 21727 |\nEpisode : 189 | Score : 200.0 | Avg score : 149.2 | Time_Step : 21958 | update number : 21927 |\n| Episode : 190 | Score : 42.0 | Predict Score : 200.0 | Avg score : 149.2 |\nEpisode : 190 | Score : 43.0 | Avg score : 151.7 | Time_Step : 22001 | update number : 21970 |\nEpisode : 191 | Score : 200.0 | Avg score : 159.7 | Time_Step : 22201 | update number : 22170 |\nEpisode : 192 | Score : 200.0 | Avg score : 163.6 | Time_Step : 22401 | update number : 22370 |\nEpisode : 193 | Score : 200.0 | Avg score : 171.9 | Time_Step : 22601 | update number : 22570 |\nEpisode : 194 | Score : 200.0 | Avg score : 180.0 | Time_Step : 22801 | update number : 22770 |\n| Episode : 195 | Score : 199.0 | Predict Score : 199.7 | Avg score : 180.0 |\nEpisode : 195 | Score : 200.0 | Avg score : 184.3 | Time_Step : 23001 | update number : 22970 |\nEpisode : 196 | Score : 200.0 | Avg score : 184.3 | Time_Step : 23201 | update number : 23170 |\nEpisode : 197 | Score : 200.0 | Avg score : 184.3 | Time_Step : 23401 | update number : 23370 |\nEpisode : 198 | Score : 176.0 | Avg score : 181.9 | Time_Step : 23577 | update number : 23546 |\nEpisode : 199 | Score : 200.0 | Avg score : 181.9 | Time_Step : 23777 | update number : 23746 |\n------ Save model ------\nEpisode : 200 | Score : 174.0 | Avg score : 195.0 | Time_Step : 23951 | update number : 23920 |\n| Episode : 201 | Score : 49.0 | Predict Score : 168.4 | Avg score : 195.0 |\nEpisode : 201 | Score : 49.0 | Avg score : 179.9 | Time_Step : 24001 | update number : 23970 |\nEpisode : 202 | Score : 150.0 | Avg score : 174.9 | Time_Step : 24151 | update number : 24120 |\nEpisode : 203 | Score : 166.0 | Avg score : 171.5 | Time_Step : 24317 | update number : 24286 |\nEpisode : 204 | Score : 175.0 | Avg score : 169.0 | Time_Step : 24492 | update number : 24461 |\nEpisode : 205 | Score : 200.0 | Avg score : 169.0 | Time_Step : 24692 | update number : 24661 |\nEpisode : 206 | Score : 200.0 | Avg score : 169.0 | Time_Step : 24892 | update number : 24861 |\n| Episode : 207 | Score : 108.0 | Predict Score : 186.2 | Avg score : 169.0 |\nEpisode : 207 | Score : 108.0 | Avg score : 159.8 | Time_Step : 25001 | update number : 24970 |\nEpisode : 208 | Score : 160.0 | Avg score : 158.2 | Time_Step : 25161 | update number : 25130 |\nEpisode : 209 | Score : 200.0 | Avg score : 158.2 | Time_Step : 25361 | update number : 25330 |\nEpisode : 210 | Score : 200.0 | Avg score : 160.8 | Time_Step : 25561 | update number : 25530 |\nEpisode : 211 | Score : 200.0 | Avg score : 175.9 | Time_Step : 25761 | update number : 25730 |\nEpisode : 212 | Score : 200.0 | Avg score : 180.9 | Time_Step : 25961 | update number : 25930 |\n| Episode : 213 | Score : 39.0 | Predict Score : 198.7 | Avg score : 180.9 |\nEpisode : 213 | Score : 40.0 | Avg score : 168.3 | Time_Step : 26001 | update number : 25970 |\nEpisode : 214 | Score : 200.0 | Avg score : 170.8 | Time_Step : 26201 | update number : 26170 |\nEpisode : 215 | Score : 200.0 | Avg score : 170.8 | Time_Step : 26401 | update number : 26370 |\nEpisode : 216 | Score : 200.0 | Avg score : 170.8 | Time_Step : 26601 | update number : 26570 |\nEpisode : 217 | Score : 200.0 | Avg score : 180.0 | Time_Step : 26801 | update number : 26770 |\n| Episode : 218 | Score : 199.0 | Predict Score : 187.7 | Avg score : 180.0 |\nEpisode : 218 | Score : 200.0 | Avg score : 184.0 | Time_Step : 27001 | update number : 26970 |\nEpisode : 219 | Score : 200.0 | Avg score : 184.0 | Time_Step : 27201 | update number : 27170 |\nEpisode : 220 | Score : 200.0 | Avg score : 184.0 | Time_Step : 27401 | update number : 27370 |\nEpisode : 221 | Score : 200.0 | Avg score : 184.0 | Time_Step : 27601 | update number : 27570 |\nEpisode : 222 | Score : 200.0 | Avg score : 184.0 | Time_Step : 27801 | update number : 27770 |\n| Episode : 223 | Score : 199.0 | Predict Score : 200.0 | Avg score : 184.0 |\n------ Save model ------\nStop Training\n"
],
[
"returns = runner.evaluate() # Test\nprint(returns)",
"200.0\n"
],
[
"dqn_total_path = './model/DQN/CartPole-v0/episode_return.txt'\ndqn_step_path = './model/DQN/CartPole-v0/step_return.txt'\ndqn_total = np.loadtxt(dqn_total_path, delimiter=',')\ndqn_step = np.loadtxt(dqn_step_path, delimiter=',')",
"_____no_output_____"
],
[
"def var_name(var,all_var=locals()):\n return [var_name for var_name in all_var if all_var[var_name] is var][0]",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport os\nimport numpy as np\ndef _step_plot(scores):\n plt.figure(figsize=(10,5))\n plt.title(\"Step Reward\")\n plt.grid(True)\n\n name = var_name(scores).replace('_step', '')\n\n plt.xlabel(\"step * 1000\")\n plt.ylabel(\"Average Reward\")\n plt.plot(scores, \"r-\", linewidth=1.5, label= name + \"_reward\")\n plt.legend(loc=\"best\", shadow=True)\n plt.show()\n\ndef _avg_plot(scores):\n plt.figure(figsize=(10,5))\n plt.title(\"Reward\")\n plt.grid(True)\n\n name = var_name(scores).replace('_total', '')\n\n z = [c+1 for c in range(len(scores))]\n running_avg = np.zeros(len(scores))\n for e in range(len(running_avg)):\n running_avg[e] = np.mean(scores[max(0, e-10):(e+1)])\n\n plt.xlabel(\"Episode\")\n plt.ylabel(\"Total Reward\")\n plt.plot(scores, \"r-\", linewidth=1.5, label= name + \"_reward\")\n plt.plot(z, running_avg, \"b-\", linewidth=1.5, label= name + \"_avg_reward\")\n plt.legend(loc=\"best\", shadow=True)\n plt.show()",
"_____no_output_____"
],
[
"_step_plot(dqn_step)\n_avg_plot(dqn_total)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e788bdc091ee21a3ffb4ba59b9198079c9371f69 | 110,803 | ipynb | Jupyter Notebook | Boda/ensemble/NN.ipynb | UVA-DSI-2019-Capstones/UVACyber | 9ab75501b5fbb91d86162c657ba50dfc7b07a711 | [
"MIT"
] | null | null | null | Boda/ensemble/NN.ipynb | UVA-DSI-2019-Capstones/UVACyber | 9ab75501b5fbb91d86162c657ba50dfc7b07a711 | [
"MIT"
] | null | null | null | Boda/ensemble/NN.ipynb | UVA-DSI-2019-Capstones/UVACyber | 9ab75501b5fbb91d86162c657ba50dfc7b07a711 | [
"MIT"
] | 2 | 2018-09-27T22:47:12.000Z | 2019-02-05T00:06:54.000Z | 34.876613 | 251 | 0.324874 | [
[
[
"from keras.utils import to_categorical\nfrom keras.layers import Dropout\nfrom keras.layers import Dense\nfrom keras import models\nfrom keras import optimizers\nfrom keras import backend as K\nimport pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn.preprocessing import StandardScaler\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport math\nimport gensim\nfrom gensim.models import Word2Vec \nimport time",
"/opt/conda/lib/python3.6/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\nUsing TensorFlow backend.\n"
]
],
[
[
"# ANN Metrics",
"_____no_output_____"
]
],
[
[
"def recall(y_true, y_pred):\n \n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n \ndef precision(y_true, y_pred):\n \n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\ndef f1(y_true, y_pred):\n \n myPrecision = precision(y_true, y_pred)\n myRecall = recall(y_true, y_pred)\n return 2*((myPrecision*myRecall)/(myPrecision+myRecall+K.epsilon()))",
"_____no_output_____"
]
],
[
[
"# ANN Model",
"_____no_output_____"
]
],
[
[
"tests[tests.label == 1]",
"_____no_output_____"
],
[
"df = pd.read_csv('/scratch/by8jj/stratified samples/ensemble model/file.csv')",
"_____no_output_____"
],
[
"len(df)",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\n\nX_train, X_test, y_train, y_test = train_test_split(df.drop('label', axis = 1), df.label, test_size=0.2)",
"_____no_output_____"
],
[
"X_train['label'] = y_train",
"_____no_output_____"
],
[
"X_train",
"_____no_output_____"
],
[
"df_mal = X_train[X_train['label'] == 1]\ndf_ben = X_train[X_train['label'] == 0].sample(frac = 1)[:len(df_mal)]\ndf_bal = pd.concat([df_mal, df_ben]).sample(frac = 1)",
"_____no_output_____"
],
[
"df_bal",
"_____no_output_____"
],
[
"y = df_bal.label.tolist()\nX = np.matrix(df_bal.drop(labels = ['label'], axis = 1)).astype(np.float)\nprint(X.shape)",
"(1484072, 4)\n"
],
[
"model = models.Sequential()\nmodel.add(Dense(2, input_dim=4, kernel_initializer='uniform', activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))\nadam = optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0000002, amsgrad=False)\nmodel.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy',f1,recall,precision])",
"_____no_output_____"
],
[
"result = model.fit(X, y, epochs=20, batch_size=256, verbose=1, validation_split=0.3)",
"Train on 1038850 samples, validate on 445222 samples\nEpoch 1/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.6352 - acc: 0.6991 - f1: 0.6422 - recall: 0.5718 - precision: 0.7399 - val_loss: 0.5338 - val_acc: 0.9138 - val_f1: 0.9204 - val_recall: 0.9991 - val_precision: 0.8537\nEpoch 2/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.5221 - acc: 0.7494 - f1: 0.7040 - recall: 0.5991 - precision: 0.8567 - val_loss: 0.3794 - val_acc: 0.9434 - val_f1: 0.9462 - val_recall: 0.9961 - val_precision: 0.9014\nEpoch 3/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.4429 - acc: 0.7662 - f1: 0.7178 - recall: 0.5980 - precision: 0.9008 - val_loss: 0.2859 - val_acc: 0.9480 - val_f1: 0.9501 - val_recall: 0.9908 - val_precision: 0.9129\nEpoch 4/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3951 - acc: 0.7680 - f1: 0.7187 - recall: 0.5961 - precision: 0.9079 - val_loss: 0.2345 - val_acc: 0.9500 - val_f1: 0.9515 - val_recall: 0.9827 - val_precision: 0.9226\nEpoch 5/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3720 - acc: 0.7682 - f1: 0.7176 - recall: 0.5920 - precision: 0.9138 - val_loss: 0.2016 - val_acc: 0.9510 - val_f1: 0.9521 - val_recall: 0.9771 - val_precision: 0.9287\nEpoch 6/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3634 - acc: 0.7687 - f1: 0.7172 - recall: 0.5899 - precision: 0.9178 - val_loss: 0.1863 - val_acc: 0.9511 - val_f1: 0.9521 - val_recall: 0.9734 - val_precision: 0.9321\nEpoch 7/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3600 - acc: 0.7693 - f1: 0.7506 - recall: 0.7287 - precision: 0.8366 - val_loss: 0.1796 - val_acc: 0.9511 - val_f1: 0.9520 - val_recall: 0.9720 - val_precision: 0.9331\nEpoch 8/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3580 - acc: 0.7697 - f1: 0.8071 - recall: 0.9670 - precision: 0.6933 - val_loss: 0.1767 - val_acc: 0.9510 - val_f1: 0.9518 - val_recall: 0.9708 - val_precision: 0.9339\nEpoch 9/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3566 - acc: 0.7693 - f1: 0.8070 - recall: 0.9681 - precision: 0.6926 - val_loss: 0.1744 - val_acc: 0.9510 - val_f1: 0.9519 - val_recall: 0.9704 - val_precision: 0.9344\nEpoch 10/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3540 - acc: 0.7705 - f1: 0.8083 - recall: 0.9711 - precision: 0.6929 - val_loss: 0.1712 - val_acc: 0.9509 - val_f1: 0.9517 - val_recall: 0.9697 - val_precision: 0.9347\nEpoch 11/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3517 - acc: 0.7707 - f1: 0.7653 - recall: 0.7888 - precision: 0.8062 - val_loss: 0.1685 - val_acc: 0.9512 - val_f1: 0.9523 - val_recall: 0.9770 - val_precision: 0.9292\nEpoch 12/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3483 - acc: 0.7711 - f1: 0.7174 - recall: 0.5843 - precision: 0.9323 - val_loss: 0.1603 - val_acc: 0.9512 - val_f1: 0.9520 - val_recall: 0.9711 - val_precision: 0.9340\nEpoch 13/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3459 - acc: 0.7712 - f1: 0.7168 - recall: 0.5823 - precision: 0.9356 - val_loss: 0.1548 - val_acc: 0.9505 - val_f1: 0.9512 - val_recall: 0.9661 - val_precision: 0.9370\nEpoch 14/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3449 - acc: 0.7700 - f1: 0.7141 - recall: 0.5779 - precision: 0.9380 - val_loss: 0.1520 - val_acc: 0.9498 - val_f1: 0.9502 - val_recall: 0.9602 - val_precision: 0.9407\nEpoch 15/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3428 - acc: 0.7697 - f1: 0.7130 - recall: 0.5752 - precision: 0.9413 - val_loss: 0.1485 - val_acc: 0.9490 - val_f1: 0.9492 - val_recall: 0.9554 - val_precision: 0.9434\nEpoch 16/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3416 - acc: 0.7703 - f1: 0.7957 - recall: 0.9254 - precision: 0.7276 - val_loss: 0.1447 - val_acc: 0.9486 - val_f1: 0.9486 - val_recall: 0.9522 - val_precision: 0.9454\nEpoch 17/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3406 - acc: 0.7696 - f1: 0.7644 - recall: 0.7956 - precision: 0.8076 - val_loss: 0.1408 - val_acc: 0.9482 - val_f1: 0.9481 - val_recall: 0.9480 - val_precision: 0.9486\nEpoch 18/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3398 - acc: 0.7699 - f1: 0.7565 - recall: 0.7617 - precision: 0.8308 - val_loss: 0.1369 - val_acc: 0.9500 - val_f1: 0.9497 - val_recall: 0.9460 - val_precision: 0.9537\nEpoch 19/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3390 - acc: 0.7716 - f1: 0.7122 - recall: 0.5682 - precision: 0.9576 - val_loss: 0.1350 - val_acc: 0.9514 - val_f1: 0.9509 - val_recall: 0.9435 - val_precision: 0.9587\nEpoch 20/20\n1038850/1038850 [==============================] - 5s 5us/step - loss: 0.3384 - acc: 0.7722 - f1: 0.7125 - recall: 0.5676 - precision: 0.9604 - val_loss: 0.1327 - val_acc: 0.9518 - val_f1: 0.9512 - val_recall: 0.9421 - val_precision: 0.9608\n"
],
[
"y_pred = model.predict(np.matrix(X_test).astype(np.float))",
"_____no_output_____"
],
[
"y_pred = [x[0] for x in y_pred]",
"_____no_output_____"
],
[
"temp = [x if x>0.5 else 0 for x in y_pred]",
"_____no_output_____"
],
[
"pred = pd.DataFrame({'test':y_test, 'pred': y_pred})",
"_____no_output_____"
],
[
"pred",
"_____no_output_____"
],
[
"temp = [1 if x>0.8 else 0 for x in y_pred]\ncm= confusion_matrix(y_test, temp)\ntn, fp, fn, tp = cm.ravel()\nprecision=tp/(tp+fp)\nrecall=tp/(tp+fn)\nfpr = fp/(fp+ tn)\naccuracy = (tp + tn)/(tn + tp + fn + fp)\nF1 = 2 * (precision * recall) / (precision + recall)\nprint(\"precision:\", precision*100)\nprint(\"recall:\", recall*100)\nprint(\"false positive rate:\", fpr*100)\nprint(\"accuracy\", accuracy*100)\nprint(\"F1-score\", F1)",
"precision: 81.6491971891807\nrecall: 89.35790853042899\nfalse positive rate: 1.0073213698881054\naccuracy 98.5325078797032\nF1-score 0.8532980501964162\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e788bf04d3e0e0f3c50b0032eed4b380b3788e44 | 28,690 | ipynb | Jupyter Notebook | 10x-3-to-13-submission.ipynb | detrout/encode4-curation | c4d7904a8013a276c2771afaeb28db94b73ff020 | [
"BSD-3-Clause"
] | null | null | null | 10x-3-to-13-submission.ipynb | detrout/encode4-curation | c4d7904a8013a276c2771afaeb28db94b73ff020 | [
"BSD-3-Clause"
] | null | null | null | 10x-3-to-13-submission.ipynb | detrout/encode4-curation | c4d7904a8013a276c2771afaeb28db94b73ff020 | [
"BSD-3-Clause"
] | null | null | null | 77.331536 | 1,844 | 0.636738 | [
[
[
"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/pandasodf')\nif PANDAS_ODF not in sys.path:\n sys.path.append(PANDAS_ODF)\n from pandasodf import ODFReader",
"_____no_output_____"
],
[
"from htsworkflow.submission.encoded import Document\nfrom htsworkflow.submission.aws_submission import run_aws_cp",
"_____no_output_____"
],
[
"# live server & control file\nserver = ENCODED('www.encodeproject.org')\nspreadsheet_name = os.path.expanduser('~diane/woldlab/ENCODE/10x_mouse_limb_20181219.ods')\n\n# test server & datafile\n#server = ENCODED('test.encodedcc.org')\n#spreadsheet_name = os.path.expanduser('~diane/woldlab/ENCODE/10x_mouse_limb_20181219-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 = ODFReader(spreadsheet_name)\nbiosample = book.parse('Biosample', header=0)\ncreated = server.post_sheet('/biosamples/', biosample, \n verbose=True, \n dry_run=True, \n validator=validator)\nprint(len(created))",
"11\n"
],
[
"if created:\n biosample.to_excel('/dev/shm/biosamples.xlsx', index=False)",
"_____no_output_____"
]
],
[
[
"# Register Libraries",
"_____no_output_____"
]
],
[
[
"print(spreadsheet_name)\nbook = ODFReader(spreadsheet_name)\nlibraries = book.parse('Library', header=0)\ncreated = server.post_sheet('/libraries/', \n libraries, \n verbose=True, \n dry_run=True, \n validator=validator)\nprint(len(created))",
"/home/diane/woldlab/ENCODE/10x_mouse_limb_20181219.ods\n11\n"
],
[
"if created:\n libraries.to_excel('/dev/shm/libraries.xlsx', index=False)",
"_____no_output_____"
]
],
[
[
"# Register Experiments",
"_____no_output_____"
]
],
[
[
"book = ODFReader(spreadsheet_name)\nexperiments = book.parse('Experiment', header=0)\ncreated = server.post_sheet('/experiments/', \n experiments, \n verbose=True, \n dry_run=False, \n validator=validator)\nprint(len(created))",
"Reponse {'@type': ['result'], 'status': 'success', '@graph': [{'@id': '/experiments/ENCSR642XVO/', 'revoked_files': [], 'original_files': [], 'objective_slims': [], 'accession': 'ENCSR642XVO', 'dbxrefs': [], 'system_slims': [], 'references': [], 'lab': '/labs/barbara-wold/', 'uuid': 'e51d1d30-754e-450a-bbe4-d7b0f241f1af', 'biosample_synonyms': ['free part of upper limb', 'upper limb', 'free upper limb', 'foreleg', 'Entire upper limb', 'anteriormost limb', 'pectoral flipper', 'pectoral limb', 'fore limb', 'membrum superius', 'forelimb', 'superior member', 'upper extremity'], 'possible_controls': [], 'description': \"10X Genomics Chromium 3' single-cell RNA-Seq (v2 kit) of C57Bl6 wild-type 11.0 day embryonic mouse forelimb\", 'submitted_by': '/users/bc5b62f7-ce28-4a1e-b6b3-81c9c5a86d7a/', '@type': ['Experiment', 'Dataset', 'Item'], 'internal_status': 'unreviewed', 'aliases': [], 'assembly': [], 'biosample_term_name': 'forelimb', 'assay_title': 'single cell RNA-seq', 'date_created': '2019-01-04T21:14:14.247268+00:00', 'status': 'in progress', 'internal_tags': [], 'supersedes': [], 'organ_slims': ['limb'], 'type_slims': [], 'assay_term_id': 'NTR:0003082', 'developmental_slims': [], 'related_series': [], 'alternate_accessions': [], 'assay_term_name': 'single cell isolation followed by RNA-seq', 'award': '/awards/UM1HG009443/', 'biosample_type': 'tissue', 'schema_version': '22', 'replication_type': 'unreplicated', 'assay_slims': ['Transcription'], 'related_files': [], 'replicates': [], 'superseded_by': [], 'files': [], 'cell_slims': [], 'experiment_classification': ['functional genomics assay'], 'documents': ['/documents/515a990c-50c4-459a-8036-502feaf5a18c/', '/documents/ecb1c489-905b-4afb-8389-ed7fb2e36ff2/'], 'biosample_term_id': 'UBERON:0002102', 'category_slims': [], 'contributing_files': []}]}\nrow 1 created: e51d1d30-754e-450a-bbe4-d7b0f241f1af\nReponse {'status': 'success', '@graph': [{'supersedes': [], 'internal_tags': [], '@id': '/experiments/ENCSR745DNK/', 'category_slims': [], 'system_slims': [], 'biosample_term_name': 'forelimb', 'dbxrefs': [], 'status': 'in progress', 'accession': 'ENCSR745DNK', 'objective_slims': [], 'cell_slims': [], 'alternate_accessions': [], 'organ_slims': ['limb'], 'contributing_files': [], 'related_series': [], '@type': ['Experiment', 'Dataset', 'Item'], 'files': [], 'related_files': [], 'references': [], 'biosample_synonyms': ['Entire upper limb', 'pectoral flipper', 'free part of upper limb', 'anteriormost limb', 'upper extremity', 'pectoral limb', 'foreleg', 'free upper limb', 'membrum superius', 'fore limb', 'superior member', 'upper limb', 'forelimb'], 'original_files': [], 'biosample_type': 'tissue', 'assay_term_id': 'NTR:0003082', 'revoked_files': [], 'submitted_by': '/users/bc5b62f7-ce28-4a1e-b6b3-81c9c5a86d7a/', 'biosample_term_id': 'UBERON:0002102', 'possible_controls': [], 'experiment_classification': ['functional genomics assay'], 'description': \"10X Genomics Chromium 3' single-cell RNA-Seq (v2 kit) of C57Bl6 wild-type 12.0 day embryonic mouse forelimb\", 'internal_status': 'unreviewed', 'assay_term_name': 'single cell isolation followed by RNA-seq', 'lab': '/labs/barbara-wold/', 'type_slims': [], 'assembly': [], 'developmental_slims': [], 'date_created': '2019-01-04T21:14:14.416498+00:00', 'replicates': [], 'assay_title': 'single cell RNA-seq', 'schema_version': '22', 'aliases': [], 'superseded_by': [], 'award': '/awards/UM1HG009443/', 'uuid': '8c1a2220-2c99-4796-9b1e-00dd31db3368', 'documents': ['/documents/515a990c-50c4-459a-8036-502feaf5a18c/', '/documents/ecb1c489-905b-4afb-8389-ed7fb2e36ff2/'], 'assay_slims': ['Transcription'], 'replication_type': 'unreplicated'}], '@type': ['result']}\nrow 2 created: 8c1a2220-2c99-4796-9b1e-00dd31db3368\nReponse {'@type': ['result'], 'status': 'success', '@graph': [{'@id': '/experiments/ENCSR476JWN/', 'revoked_files': [], 'original_files': [], 'objective_slims': [], 'accession': 'ENCSR476JWN', 'dbxrefs': [], 'system_slims': [], 'references': [], 'lab': '/labs/barbara-wold/', 'uuid': '5ca81662-d3e3-43c5-8227-2961fdb43d5d', 'biosample_synonyms': ['free part of upper limb', 'upper limb', 'free upper limb', 'foreleg', 'Entire upper limb', 'anteriormost limb', 'pectoral flipper', 'pectoral limb', 'fore limb', 'membrum superius', 'forelimb', 'superior member', 'upper extremity'], 'possible_controls': [], 'description': \"10X Genomics Chromium 3' single-cell RNA-Seq (v2 kit) of C57Bl6 wild-type 13.0 day embryonic mouse forelimb\", 'submitted_by': '/users/bc5b62f7-ce28-4a1e-b6b3-81c9c5a86d7a/', '@type': ['Experiment', 'Dataset', 'Item'], 'internal_status': 'unreviewed', 'aliases': [], 'assembly': [], 'biosample_term_name': 'forelimb', 'assay_title': 'single cell RNA-seq', 'date_created': '2019-01-04T21:14:14.554987+00:00', 'status': 'in progress', 'internal_tags': [], 'supersedes': [], 'organ_slims': ['limb'], 'type_slims': [], 'assay_term_id': 'NTR:0003082', 'developmental_slims': [], 'related_series': [], 'alternate_accessions': [], 'assay_term_name': 'single cell isolation followed by RNA-seq', 'award': '/awards/UM1HG009443/', 'biosample_type': 'tissue', 'schema_version': '22', 'replication_type': 'unreplicated', 'assay_slims': ['Transcription'], 'related_files': [], 'replicates': [], 'superseded_by': [], 'files': [], 'cell_slims': [], 'experiment_classification': ['functional genomics assay'], 'documents': ['/documents/515a990c-50c4-459a-8036-502feaf5a18c/', '/documents/ecb1c489-905b-4afb-8389-ed7fb2e36ff2/'], 'biosample_term_id': 'UBERON:0002102', 'category_slims': [], 'contributing_files': []}]}\nrow 3 created: 5ca81662-d3e3-43c5-8227-2961fdb43d5d\nReponse {'status': 'success', '@graph': [{'original_files': [], 'related_files': [], 'assay_title': 'single cell RNA-seq', 'biosample_term_name': 'forelimb', 'superseded_by': [], 'biosample_term_id': 'UBERON:0002102', 'replication_type': 'unreplicated', 'contributing_files': [], 'submitted_by': '/users/bc5b62f7-ce28-4a1e-b6b3-81c9c5a86d7a/', 'internal_status': 'unreviewed', 'description': \"10X Genomics Chromium 3' single-cell RNA-Seq (v2 kit) of C57Bl6 wild-type 15.0 day embryonic mouse forelimb\", 'experiment_classification': ['functional genomics assay'], '@type': ['Experiment', 'Dataset', 'Item'], 'category_slims': [], 'files': [], 'possible_controls': [], 'dbxrefs': [], 'schema_version': '22', 'organ_slims': ['limb'], 'status': 'in progress', 'award': '/awards/UM1HG009443/', 'date_created': '2019-01-04T21:14:14.692088+00:00', 'assembly': [], 'uuid': '406171c2-7689-4c0d-ac26-ee333fa75df2', 'lab': '/labs/barbara-wold/', 'type_slims': [], '@id': '/experiments/ENCSR337QTQ/', 'assay_slims': ['Transcription'], 'system_slims': [], 'assay_term_name': 'single cell isolation followed by RNA-seq', 'objective_slims': [], 'assay_term_id': 'NTR:0003082', 'alternate_accessions': [], 'developmental_slims': [], 'aliases': [], 'accession': 'ENCSR337QTQ', 'references': [], 'internal_tags': [], 'related_series': [], 'replicates': [], 'cell_slims': [], 'biosample_type': 'tissue', 'documents': ['/documents/515a990c-50c4-459a-8036-502feaf5a18c/', '/documents/ecb1c489-905b-4afb-8389-ed7fb2e36ff2/'], 'supersedes': [], 'revoked_files': [], 'biosample_synonyms': ['forelimb', 'anteriormost limb', 'membrum superius', 'pectoral limb', 'upper extremity', 'free part of upper limb', 'upper limb', 'foreleg', 'free upper limb', 'fore limb', 'Entire upper limb', 'pectoral flipper', 'superior member']}], '@type': ['result']}\nrow 4 created: 406171c2-7689-4c0d-ac26-ee333fa75df2\nReponse {'status': 'success', '@graph': [{'supersedes': [], 'internal_tags': [], '@id': '/experiments/ENCSR874BOF/', 'category_slims': [], 'system_slims': [], 'biosample_term_name': 'forelimb', 'dbxrefs': [], 'status': 'in progress', 'accession': 'ENCSR874BOF', 'objective_slims': [], 'cell_slims': [], 'alternate_accessions': [], 'organ_slims': ['limb'], 'contributing_files': [], 'related_series': [], '@type': ['Experiment', 'Dataset', 'Item'], 'files': [], 'related_files': [], 'references': [], 'biosample_synonyms': ['Entire upper limb', 'pectoral flipper', 'free part of upper limb', 'anteriormost limb', 'upper extremity', 'pectoral limb', 'foreleg', 'free upper limb', 'membrum superius', 'fore limb', 'superior member', 'upper limb', 'forelimb'], 'original_files': [], 'biosample_type': 'tissue', 'assay_term_id': 'NTR:0003082', 'revoked_files': [], 'submitted_by': '/users/bc5b62f7-ce28-4a1e-b6b3-81c9c5a86d7a/', 'biosample_term_id': 'UBERON:0002102', 'possible_controls': [], 'experiment_classification': ['functional genomics assay'], 'description': \"10X Genomics Chromium 3' single-cell RNA-Seq (v2 kit) of C57Bl6 wild-type 10.5 day embryonic mouse forelimb\", 'internal_status': 'unreviewed', 'assay_term_name': 'single cell isolation followed by RNA-seq', 'lab': '/labs/barbara-wold/', 'type_slims': [], 'assembly': [], 'developmental_slims': [], 'date_created': '2019-01-04T21:14:14.838123+00:00', 'replicates': [], 'assay_title': 'single cell RNA-seq', 'schema_version': '22', 'aliases': [], 'superseded_by': [], 'award': '/awards/UM1HG009443/', 'uuid': '44ffd920-f48d-4e35-84de-02b229787cb1', 'documents': ['/documents/515a990c-50c4-459a-8036-502feaf5a18c/', '/documents/ecb1c489-905b-4afb-8389-ed7fb2e36ff2/'], 'assay_slims': ['Transcription'], 'replication_type': 'unreplicated'}], '@type': ['result']}\nrow 5 created: 44ffd920-f48d-4e35-84de-02b229787cb1\nReponse {'@graph': [{'lab': '/labs/barbara-wold/', 'revoked_files': [], 'possible_controls': [], 'assembly': [], 'schema_version': '22', 'organ_slims': ['limb'], 'developmental_slims': [], 'dbxrefs': [], '@id': '/experiments/ENCSR306UHC/', 'files': [], 'internal_status': 'unreviewed', 'biosample_term_name': 'forelimb', 'biosample_term_id': 'UBERON:0002102', 'accession': 'ENCSR306UHC', 'alternate_accessions': [], 'biosample_synonyms': ['upper limb', 'forelimb', 'Entire upper limb', 'pectoral limb', 'upper extremity', 'superior member', 'fore limb', 'anteriormost limb', 'membrum superius', 'free upper limb', 'foreleg', 'pectoral flipper', 'free part of upper limb'], 'uuid': '9b34b90b-3d7b-461d-99b7-6b85c8836e52', 'cell_slims': [], 'assay_term_name': 'single cell isolation followed by RNA-seq', 'status': 'in progress', '@type': ['Experiment', 'Dataset', 'Item'], 'assay_title': 'single cell RNA-seq', 'date_created': '2019-01-04T21:14:14.951234+00:00', 'type_slims': [], 'replicates': [], 'original_files': [], 'award': '/awards/UM1HG009443/', 'internal_tags': [], 'assay_term_id': 'NTR:0003082', 'aliases': [], 'objective_slims': [], 'related_files': [], 'category_slims': [], 'submitted_by': '/users/bc5b62f7-ce28-4a1e-b6b3-81c9c5a86d7a/', 'description': \"10X Genomics Chromium 3' single-cell RNA-Seq (v2 kit) of C57Bl6 wild-type 15.0 day embryonic mouse forelimb\", 'contributing_files': [], 'related_series': [], 'system_slims': [], 'references': [], 'documents': ['/documents/515a990c-50c4-459a-8036-502feaf5a18c/', '/documents/ecb1c489-905b-4afb-8389-ed7fb2e36ff2/'], 'assay_slims': ['Transcription'], 'experiment_classification': ['functional genomics assay'], 'biosample_type': 'tissue', 'superseded_by': [], 'supersedes': [], 'replication_type': 'unreplicated'}], 'status': 'success', '@type': ['result']}\nrow 6 created: 9b34b90b-3d7b-461d-99b7-6b85c8836e52\n"
],
[
"if created:\n experiments.to_excel('/dev/shm/experiments.xlsx', index=False)",
"_____no_output_____"
]
],
[
[
"# Register Replicates",
"_____no_output_____"
]
],
[
[
"book = ODFReader(spreadsheet_name)\nreplicates = book.parse('Replicate', header=0)\ncreated = server.post_sheet('/replicates/', \n replicates, \n verbose=True, \n dry_run=True, \n validator=validator)\nprint(len(created))",
"0\n"
],
[
"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"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e788cdbb412d7c37ec6fb80313374ec8a0347f99 | 618,141 | ipynb | Jupyter Notebook | Part2.ipynb | ismailfaruk/ECSE415-Final-Project | de72843dbdac03760efb75239d4503ac5601887b | [
"MIT"
] | null | null | null | Part2.ipynb | ismailfaruk/ECSE415-Final-Project | de72843dbdac03760efb75239d4503ac5601887b | [
"MIT"
] | null | null | null | Part2.ipynb | ismailfaruk/ECSE415-Final-Project | de72843dbdac03760efb75239d4503ac5601887b | [
"MIT"
] | null | null | null | 210.538488 | 541,434 | 0.88298 | [
[
[
"from google.colab import drive\ndrive.mount('/content/drive')\n\n# path for google drive\npath = '/content/drive/My Drive/ECSE415/FinalProject/'\nframe_path = '/content/drive/My Drive/ECSE415/FinalProject/frames/'\npositive_path = '/content/drive/My Drive/ECSE415/FinalProject/positive/'\nnegative_path = '/content/drive/My Drive/ECSE415/FinalProject/negative/'\nperson_path = '/content/drive/My Drive/ECSE415/FinalProject/person/'\npositive_test = '/content/drive/My Drive/ECSE415/FinalProject/positive_test/'\nnegative_test = '/content/drive/My Drive/ECSE415/FinalProject/negative_test/'",
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
],
[
"# install dependencies: \n!pip install pyyaml==5.1\nimport torch, torchvision\nprint(torch.__version__, torch.cuda.is_available())\n!gcc --version\n!pip install --upgrade imutils\n# opencv is pre-installed on colab",
"Requirement already satisfied: pyyaml==5.1 in /usr/local/lib/python3.6/dist-packages (5.1)\n1.7.0+cu101 True\ngcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0\nCopyright (C) 2017 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\nRequirement already up-to-date: imutils in /usr/local/lib/python3.6/dist-packages (0.5.3)\n"
],
[
"# install detectron2: (Colab has CUDA 10.1 + torch 1.7)\n# See https://detectron2.readthedocs.io/tutorials/install.html for instructions\nimport torch\nassert torch.__version__.startswith(\"1.7\")\n!pip install detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.7/index.html\n# exit(0) # After installation, you need to \"restart runtime\" in Colab. This line can also restart runtime",
"Looking in links: https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.7/index.html\nRequirement already satisfied: detectron2 in /usr/local/lib/python3.6/dist-packages (0.3+cu101)\nRequirement already satisfied: tensorboard in /usr/local/lib/python3.6/dist-packages (from detectron2) (2.3.0)\nRequirement already satisfied: Pillow>=7.1 in /usr/local/lib/python3.6/dist-packages (from detectron2) (8.0.1)\nRequirement already satisfied: pycocotools>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from detectron2) (2.0.2)\nRequirement already satisfied: termcolor>=1.1 in /usr/local/lib/python3.6/dist-packages (from detectron2) (1.1.0)\nRequirement already satisfied: pydot in /usr/local/lib/python3.6/dist-packages (from detectron2) (1.3.0)\nRequirement already satisfied: tqdm>4.29.0 in /usr/local/lib/python3.6/dist-packages (from detectron2) (4.41.1)\nRequirement already satisfied: fvcore>=0.1.2 in /usr/local/lib/python3.6/dist-packages (from detectron2) (0.1.2.post20201216)\nRequirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from detectron2) (0.16.0)\nRequirement already satisfied: yacs>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from detectron2) (0.1.8)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from detectron2) (3.2.2)\nRequirement already satisfied: cloudpickle in /usr/local/lib/python3.6/dist-packages (from detectron2) (1.3.0)\nRequirement already satisfied: tabulate in /usr/local/lib/python3.6/dist-packages (from detectron2) (0.8.7)\nRequirement already satisfied: numpy>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (1.18.5)\nRequirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (3.12.4)\nRequirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (0.36.1)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (1.7.0)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (0.4.2)\nRequirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (2.23.0)\nRequirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (50.3.2)\nRequirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (1.17.2)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (1.15.0)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (3.3.3)\nRequirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (0.10.0)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (1.0.1)\nRequirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard->detectron2) (1.34.0)\nRequirement already satisfied: cython>=0.27.3 in /usr/local/lib/python3.6/dist-packages (from pycocotools>=2.0.2->detectron2) (0.29.21)\nRequirement already satisfied: pyparsing>=2.1.4 in /usr/local/lib/python3.6/dist-packages (from pydot->detectron2) (2.4.7)\nRequirement already satisfied: iopath>=0.1.2 in /usr/local/lib/python3.6/dist-packages (from fvcore>=0.1.2->detectron2) (0.1.2)\nRequirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.6/dist-packages (from fvcore>=0.1.2->detectron2) (5.1)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->detectron2) (2.8.1)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->detectron2) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->detectron2) (1.3.1)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard->detectron2) (1.3.0)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (2020.12.5)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (3.0.4)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (1.24.3)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard->detectron2) (4.1.1)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard->detectron2) (0.2.8)\nRequirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard->detectron2) (4.6)\nRequirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard->detectron2) (3.1.1)\nRequirement already satisfied: portalocker in /usr/local/lib/python3.6/dist-packages (from iopath>=0.1.2->fvcore>=0.1.2->detectron2) (2.0.0)\nRequirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard->detectron2) (3.1.0)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard->detectron2) (0.4.8)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard->detectron2) (3.4.0)\n"
],
[
"# Some basic setup:\n# Setup detectron2 logger\nimport detectron2\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\n\n# import some common libraries\nimport numpy as np\nimport os, json, cv2, random\nfrom google.colab.patches import cv2_imshow\nimport matplotlib.pyplot as plt\n\n# import some common detectron2 utilities\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import MetadataCatalog, DatasetCatalog\nfrom skimage.feature import hog\n\nimport time\nimport random as rg\nimport math\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold\nimport csv",
"_____no_output_____"
]
],
[
[
"# Image extraction from folders and creating image set",
"_____no_output_____"
]
],
[
[
"def CreateTrainSet(positive_path, negative_path, IMAGE_WIDTH, IMAGE_HEIGHT, Positive_Images=1200):\r\n # getting all file names from positive path\r\n positives = os.listdir(positive_path)\r\n positive_files = [os.path.join(positive_path, file_name) for file_name in positives if file_name.endswith('.jpg')]\r\n positive_files.sort()\r\n\r\n # getting all file names from negative path\r\n negatives = os.listdir(negative_path) \r\n negative_files = [os.path.join(negative_path, file_name) for file_name in negatives if file_name.endswith('.jpg')]\r\n negative_files.sort()\r\n\r\n # creating train label np array for pos=0 and neg=1\r\n pos_labels = np.zeros(Positive_Images)\r\n neg_labels = np.ones(len(negative_files))\r\n train_labels = np.concatenate((pos_labels, neg_labels), axis=0).astype(int)\r\n \r\n # add positive images to train_image np array\r\n pos_images = np.zeros((Positive_Images, IMAGE_HEIGHT, IMAGE_WIDTH))\r\n for filename in positive_files[0: Positive_Images]:\r\n img = cv2.imread(filename, 0)\r\n img = cv2.resize(img, (IMAGE_WIDTH, IMAGE_HEIGHT))\r\n pos_images[positive_files.index(filename)] = img\r\n \r\n # add negative images to train_image np array\r\n neg_images = np.zeros((len(negative_files), IMAGE_HEIGHT, IMAGE_WIDTH))\r\n for filename in negative_files:\r\n img = cv2.imread(filename, 0)\r\n img = cv2.resize(img, (IMAGE_WIDTH, IMAGE_HEIGHT))\r\n neg_images[negative_files.index(filename)] = img\r\n \r\n train_images = np.zeros((len(positive_files)+len(negative_files), IMAGE_HEIGHT, IMAGE_WIDTH))\r\n train_images = np.concatenate((pos_images, neg_images), axis=0).astype(int)\r\n return train_images, train_labels",
"_____no_output_____"
],
[
"Positive_Images = 1200\r\nprint(f\"Path exists: {os.path.isdir(positive_path) and os.path.isdir(negative_path)}\")\r\nIMAGE_WIDTH = 64\r\nIMAGE_HEIGHT = 128\r\nR_train_images, train_labels = CreateTrainSet(positive_path, negative_path, IMAGE_WIDTH, IMAGE_HEIGHT, Positive_Images)\r\n\r\nprint(\"train_images: \", R_train_images.shape)\r\nprint(\"train_labels: \", train_labels.shape)\r\nprint(R_train_images[0])\r\nprint(train_labels[0])\r\nprint(R_train_images[-1])\r\nprint(train_labels[-1])",
"Path exists: True\ntrain_images: (1480, 128, 64)\ntrain_labels: (1480,)\n[[196 197 201 ... 124 119 117]\n [195 197 200 ... 125 118 115]\n [195 196 200 ... 126 116 111]\n ...\n [181 181 181 ... 182 181 181]\n [178 178 177 ... 184 184 184]\n [176 176 175 ... 186 186 186]]\n0\n[[198 198 197 ... 123 113 106]\n [196 196 196 ... 121 115 113]\n [194 194 194 ... 121 123 128]\n ...\n [247 247 246 ... 246 245 245]\n [250 250 248 ... 244 244 244]\n [247 247 246 ... 246 247 247]]\n1\n"
]
],
[
[
"# Getting Hog features and creating training feature set",
"_____no_output_____"
]
],
[
[
"# returns HoG features, and orderd features\r\ndef HoG_features(images):\r\n cell_size = (8,8)\r\n block_size = (4,4)\r\n nbins = 4\r\n\r\n # all images have same shape\r\n img_size = images[0].shape\r\n\r\n # creating HoG object\r\n hog = cv2.HOGDescriptor(_winSize=(img_size[1] // cell_size[1] * cell_size[1],\r\n img_size[0] // cell_size[0] * cell_size[0]),\r\n _blockSize=(block_size[1] * cell_size[1],\r\n block_size[0] * cell_size[0]),\r\n _blockStride=(cell_size[1], cell_size[0]),\r\n _cellSize=(cell_size[1], cell_size[0]),\r\n _nbins=nbins)\r\n\r\n features = []\r\n for i in range(images.shape[0]):\r\n \r\n # Compute HoG features\r\n features.append(hog.compute((images[i]).astype(np.uint8)).reshape(1, -1))\r\n \r\n # Stack arrays in sequence vertically \r\n features = np.vstack(features)\r\n \r\n return features",
"_____no_output_____"
],
[
"# getting HoG features\r\ntrain_features = HoG_features(R_train_images)\r\nprint(\"trained_features_reshaped: \", train_features.shape)\r\nprint(\"trained_features_reshaped[0]: \", train_features[0])",
"trained_features_reshaped: (1480, 4160)\ntrained_features_reshaped[0]: [0.03915166 0.0065741 0.00676362 ... 0.0232183 0.02239115 0.00087363]\n"
]
],
[
[
"# Non-linear SVM Classifier",
"_____no_output_____"
]
],
[
[
"def NonLinear_SVM(train_features, train_labels, gamma, C, random_state=None):\r\n # creating non-linear svc object, RBF kernel is default\r\n clf = svm.SVC(C=C, gamma=gamma, random_state=random_state)\r\n\r\n # fit and predict\r\n clf.fit(train_features, train_labels)\r\n return clf\r\n\r\ndef predict(clf, test_features, test_labels):\r\n predict = clf.predict(test_features)\r\n \r\n # using accruacy score from metrics lib and multiply 100 to get precentage\r\n accuracy = accuracy_score(test_labels, predict)*100\r\n return accuracy",
"_____no_output_____"
]
],
[
[
"# 1 Fold Validation",
"_____no_output_____"
]
],
[
[
"k_fold = 5\r\npos_count = Positive_Images\r\nneg_count = 280\r\npos_train_split = int(pos_count*4/k_fold)\r\nneg_train_split = int(pos_count+neg_count*4/k_fold)\r\n\r\nprint(f\"train_size: {pos_train_split+neg_train_split-pos_count}\")\r\nprint(f\"test_size: {pos_count-pos_train_split+neg_count-neg_train_split+pos_count}\")\r\n\r\n# splitting all pos and neg into 4/5 for train and 1/5 split for test\r\ntrain_features_split = np.concatenate((train_features[: pos_train_split], train_features[pos_count: neg_train_split]), axis=0)\r\ntrain_labels_split = np.concatenate((train_labels[: pos_train_split], train_labels[pos_count: neg_train_split]), axis=0)\r\n\r\nval_features_split = np.concatenate((train_features[pos_train_split:pos_count], train_features[neg_train_split:]), axis=0)\r\nval_labels_split = np.concatenate((train_labels[pos_train_split:pos_count], train_labels[neg_train_split:]), axis=0)\r\n\r\nprint(f\"train_split: {train_features_split.shape} and {train_labels_split.shape}\")\r\nprint(f\"val_split: {val_features_split.shape} and {val_labels_split.shape}\")",
"train_size: 1184\ntest_size: 296\ntrain_split: (1184, 4160) and (1184,)\nval_split: (296, 4160) and (296,)\n"
],
[
"MIN_ACCURACY = 50\r\nGammaList = ['auto', 'scale']\r\nC_List = [0.01, 0.1, 1, 10, 100, 1000]\r\nBest_SVM = {\"gamma\":None, \"C\":None, \"accuracy\":0}\r\nfor gamma in GammaList:\r\n for C in C_List:\r\n clf = NonLinear_SVM(train_features_split, train_labels_split, gamma, C)\r\n accuracy = predict(clf, val_features_split, val_labels_split)\r\n if round(accuracy, 2) > MIN_ACCURACY:\r\n print(f\"Gamma: {gamma}, C: {C}, Accuracy: {round(accuracy, 2)}%\")\r\n if round(accuracy, 2) > Best_SVM[\"accuracy\"]:\r\n Best_SVM[\"gamma\"] = gamma\r\n Best_SVM[\"C\"] = C\r\n Best_SVM[\"accuracy\"] = round(accuracy, 2)\r\nprint(\"Best parameters: \", Best_SVM)",
"_____no_output_____"
]
],
[
[
"# 5 Fold Cross Validation",
"_____no_output_____"
]
],
[
[
"def k_fold_SVC(train_features, train_labels, train_index, val_index, k_folds):\r\n total_accuracy = 0\r\n for i in range(k_folds):\r\n x_train, x_val = train_features[train_index], train_features[val_index]\r\n y_train, y_val = train_labels[train_index], train_labels[val_index]\r\n clf = NonLinear_SVM(x_train, y_train, gamma, C)\r\n total_accuracy += predict(clf, x_val, y_val)\r\n avg_accuracy = total_accuracy/k_folds\r\n return avg_accuracy",
"_____no_output_____"
],
[
"# 5 fold cross validation dataset\r\nk_folds = 5\r\nkf = KFold(n_splits=k_folds, shuffle=True)\r\nkf.get_n_splits(train_features)\r\n\r\nMIN_ACCURACY = 50\r\nGammaList = ['auto', 'scale']\r\nC_List = [0.01, 0.1, 1, 10, 100, 1000]\r\nBest_SVM = {\"gamma\":None, \"C\":None, \"accuracy\":0}\r\nfor gamma in GammaList:\r\n for C in C_List:\r\n start_time = time.time()\r\n for train_index, val_index in kf.split(train_features):\r\n accuracy = k_fold_SVC(train_features, train_labels, train_index, val_index, 5)\r\n time_taken = (time.time() - (start_time))/k_folds\r\n if round(accuracy, 2) > MIN_ACCURACY:\r\n print(f\"Gamma: {gamma}, C: {C}, Accuracy: {round(accuracy, 2)}%, time taken to train/test: {round(time_taken, 2)}\")\r\n if round(accuracy, 2) > Best_SVM[\"accuracy\"]:\r\n Best_SVM[\"gamma\"] = gamma\r\n Best_SVM[\"C\"] = C\r\n Best_SVM[\"accuracy\"] = round(accuracy, 2)\r\nprint(\"Best parameters: \", Best_SVM)",
"_____no_output_____"
]
],
[
[
"# Using Optimal Paramaeters for SVM Classifier",
"_____no_output_____"
]
],
[
[
"# Optimal SVM Classifer\ngamma = \"scale\"\nC = 10\nOptimal_Clf = NonLinear_SVM(train_features_split, train_labels_split, gamma, C)\naccuracy = predict(clf, val_features_split, val_labels_split)\nprint(f\"Gamma: {gamma}, C: {C}, Accuracy: {round(accuracy, 2)}%\")",
"Gamma: scale, C: 10, Accuracy: 96.62%\n"
]
],
[
[
"# Comparison with detectron",
"_____no_output_____"
]
],
[
[
"def load_images(image_path):\r\n files = os.listdir(frame_path) \r\n files_name = [file_name for file_name in files if file_name.endswith('.jpg')]\r\n files_name.sort()\r\n frames = []\r\n\r\n #read the first 100 images\r\n for i, file_name in enumerate(files_name):\r\n frame = cv2.imread(image_path + file_name)\r\n frames.append(frame)\r\n\r\n frames = np.array(frames)\r\n return frames\r\nseq_images = load_images(frame_path)",
"_____no_output_____"
],
[
"cfg = get_cfg()\r\n# add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library\r\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml\"))\r\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\r\n# Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well\r\ncfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml\")\r\npredictor = DefaultPredictor(cfg)",
"model_final_280758.pkl: 167MB [00:02, 67.8MB/s] \n"
],
[
"# crop positive samples\r\ndef crop_objects(img, outputs, image_index, writer):\r\n classes = outputs[\"instances\"].pred_classes\r\n boxes = outputs[\"instances\"].pred_boxes.tensor.cpu().numpy()\r\n #create dictionary to hold count of objects for image name\r\n index = -1\r\n count = 0\r\n print()\r\n test_images = []\r\n test_labels = []\r\n for class_index in classes:\r\n # get count of class for part of image name\r\n # class_index = int(classes[i])\r\n if class_index == 0:\r\n # get box coords\r\n box = boxes[index]\r\n # print(box)\r\n xmin, ymin, xmax, ymax = box\r\n # crop detection from image (take an additional 5 pixels around all edges)\r\n cropped_img = img[int(ymin):int(ymax), int(xmin):int(xmax)]\r\n\r\n test_images.append(cropped_img)\r\n test_labels.append(0)\r\n count+=1\r\n writer.writerow([image_index+1, count])\r\n return writer, test_images, test_labels",
"_____no_output_____"
],
[
"# returns an array of resized images and converts to grayscale\r\ndef ResizeImages(images, IMAGE_WIDTH, IMAGE_HEIGHT):\r\n ResizedImages = np.zeros((len(images), IMAGE_HEIGHT, IMAGE_WIDTH))\r\n for i in range(len(images)):\r\n img = cv2.cvtColor(images[i], cv2.COLOR_BGR2GRAY)\r\n ResizedImages[i] = cv2.resize(img, (IMAGE_WIDTH, IMAGE_HEIGHT))\r\n return ResizedImages",
"_____no_output_____"
],
[
"def comparative_acc(Optimal_Clf, test_images, test_labels):\r\n # resize and grayscale for HoG\r\n R_test_images = ResizeImages(test_images, IMAGE_WIDTH, IMAGE_HEIGHT)\r\n # print(\"R_train_images: \", R_train_images.shape)\r\n\r\n # create HoG test features\r\n test_features = HoG_features(R_test_images)\r\n # print(\"trained_features_reshaped: \", test_features.shape)\r\n # print(\"trained_features_reshaped[0]: \", test_features[0])\r\n\r\n # accuracy\r\n accuracy = predict(Optimal_Clf, test_features, test_labels)\r\n # print(f\"Gamma: {gamma}, C: {C}, Accuracy: {round(accuracy, 2)}%\")\r\n return accuracy",
"_____no_output_____"
],
[
"cfile = open(path + 'detectron_count.csv', 'w+', newline='')\r\naccfile = open(path + 'accuracy_comparison.csv', 'w+', newline='')\r\nwriter = csv.writer(cfile)\r\nwriter.writerow([\"id\", \"Count\"])\r\nacc_writer = csv.writer(accfile)\r\nacc_writer.writerow([\"id\", \"accuracy\"])\r\n\r\n# getting HoG features\r\nIMAGE_WIDTH = 64 # same as train image\r\nIMAGE_HEIGHT = 128\r\n\r\n# use optimal parameter for model\r\ngamma = \"scale\"\r\nC = 10\r\n\r\ntest_img_set = []\r\nfor image_index in range(len(seq_images)):\r\n try:\r\n outputs = predictor(seq_images[image_index])\r\n writer, test_images, test_labels = crop_objects(seq_images[image_index], outputs, image_index, writer)\r\n accuracy = comparative_acc(Optimal_Clf, test_images, test_labels)\r\n acc_writer.writerow([image_index+1, accuracy])\r\n except Exception as e:\r\n print(str(e))\r\n\r\ncfile.close\r\naccfile.close\r\n\r\nv = Visualizer(seq_images[0][:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.0)\r\nout = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\"))\r\ncv2_imshow(out.get_image()[:, :, ::-1])",
"1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
],
[
"import imutils\r\ndef pyramid(image, scale=1.5, minSize=(30, 30)):\r\n\t# yield the original image\r\n\tyield image\r\n\t# keep looping over the pyramid\r\n\twhile True:\r\n\t\t# compute the new dimensions of the image and resize it\r\n\t\tw = int(image.shape[1] / scale)\r\n\t\timage = imutils.resize(image, width=w)\r\n\t\t# if the resized image does not meet the supplied minimum\r\n\t\t# size, then stop constructing the pyramid\r\n\t\tif image.shape[0] < minSize[1] or image.shape[1] < minSize[0]:\r\n\t\t\tbreak\r\n\t\t# yield the next image in the pyramid\r\n\t\tyield image\r\n\r\ndef sliding_window(image, stepSize, windowSize):\r\n\t# slide a window across the image\r\n\tfor y in range(0, image.shape[0], stepSize):\r\n\t\tfor x in range(0, image.shape[1], stepSize):\r\n\t\t\t# yield the current window\r\n\t\t\tyield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])\r\n\r\ndef detectron_detect(img):\r\n frame = np.array(img)\r\n outputs = predictor(frame)\r\n v = Visualizer(frame[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.0)\r\n out = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\"))\r\n cv2_imshow(out.get_image()[:, :, ::-1])\r\n classes = outputs[\"instances\"].pred_classes\r\n boxes = outputs[\"instances\"].pred_boxes.tensor.cpu().numpy()\r\n #create dictionary to hold count of objects for image name\r\n index = -1\r\n count = 0\r\n for class_index in classes:\r\n index+=1\r\n if class_index == 0:\r\n # get box coords\r\n box = boxes[index]\r\n return class_index, box\r\n\r\n(winW, winH) = (64, 128)\r\ndef window_predict(clf, image):\r\n person_count = 0\r\n # loop over the image pyramid\r\n for resized in pyramid(image, scale=1.5):\r\n # loop over the sliding window for each layer of the pyramid\r\n for (x, y, window) in sliding_window(resized, stepSize=32, windowSize=(winW, winH)):\r\n # if the window does not meet our desired window size, ignore it\r\n if window.shape[0] != winH or window.shape[1] != winW:\r\n # detectron predict\r\n det_label, det_box = detectron_detect(window))\r\n \r\n # svm prediction\r\n # test feature: window\r\n SVM_prediction = clf.predict(window)\r\n # both predict true\r\n if SVM_prediction == 1 and det_label == 0:\r\n person_count += 1\r\n SumIOU += bb_intersection_over_union(window, det_box)\r\n # SVM predicts true || False Positive\r\n elif SVM_prediction == 1:\r\n SumIOU += 0\r\n person_count += 1\r\n # detectron predicts true || False Negative\r\n elif det_label == 0:\r\n SumIOU += 0\r\n person_count += 1\r\n\r\n # since we do not have a classifier, we'll just draw the window\r\n clone = resized.copy()\r\n cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2)\r\n # cv2_imshow(\"Window\", clone)\r\n # cv2.waitKey(1)\r\n # time.sleep(0.025)\r\n AvgIOU = SumIOU / person_count \r\n return AvgIOU",
"_____no_output_____"
],
[
"def bb_intersection_over_union(BoxA, BoxB):\r\n A_xmin, A_ymin, A_xmax, A_ymax = BoxA\r\n B_xmin, B_ymin, B_xmax, B_ymax = BoxB\r\n\r\n # determine the (x, y)-coordinates of the intersection rectangle\r\n xA = max(A_xmin, B_xmin)\r\n yA = max(A_ymin, B_ymin)\r\n xB = min(A_xmax, B_xmax)\r\n yB = min(A_ymax, B_ymax)\r\n # compute the area of intersection rectangle\r\n interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\r\n # compute the area of both the prediction and ground-truth\r\n # rectangles\r\n boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\r\n boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\r\n # compute the intersection over union by taking the intersection\r\n # area and dividing it by the sum of prediction + ground-truth\r\n # areas - the interesection area\r\n iou = interArea / float(boxAArea + boxBArea - interArea)\r\n # return the intersection over union value\r\n return iou",
"_____no_output_____"
],
[
"def LBP(images, radius):\n P = 8 * radius\n R = radius\n features = []\n eps = 1e-7\n for img in images:\n lbp = feature.local_binary_pattern(img, P, R)\n (hist, _) = np.histogram(lbp.ravel(),bins=np.arange(0, P + 3),range=(0, P + 2))\n # normalize the histogram\n hist = hist.astype(\"float\")\n hist /= (hist.sum() + eps)\n if np.isnan(hist.any()):\n print(\"nan\")\n \n features.append(hist)\n features=np.array(features)\n return features",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e788cf673a787785d26534d226208b1d70cbc129 | 243,090 | ipynb | Jupyter Notebook | scikit-learn/learn/02随机森林/Record.ipynb | openjw/penter | 0200f40c9d01a84c758ddcb6a9c84871d6f628c0 | [
"MIT"
] | 13 | 2020-01-04T07:37:38.000Z | 2021-08-31T05:19:58.000Z | scikit-learn/learn/02随机森林/Record.ipynb | openjw/penter | 0200f40c9d01a84c758ddcb6a9c84871d6f628c0 | [
"MIT"
] | 3 | 2020-06-05T22:42:53.000Z | 2020-08-24T07:18:54.000Z | scikit-learn/learn/02随机森林/Record.ipynb | openjw/penter | 0200f40c9d01a84c758ddcb6a9c84871d6f628c0 | [
"MIT"
] | 9 | 2020-10-19T04:53:06.000Z | 2021-08-31T05:20:01.000Z | 170.949367 | 46,728 | 0.883924 | [
[
[
"%matplotlib inline\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.datasets import load_wine",
"_____no_output_____"
],
[
"wine = load_wine()\n \nwine.data\nwine.target",
"_____no_output_____"
],
[
"#实例化\n#训练集带入实例化的模型去进行训练,使用的接口是fit\n#使用其他接口将测试集导入我们训练好的模型,去获取我们希望过去的结果(score.Y_test)\nfrom sklearn.model_selection import train_test_split\nXtrain, Xtest, Ytrain, Ytest = train_test_split(wine.data,wine.target,test_size=0.3)\n \nclf = DecisionTreeClassifier(random_state=0)\nrfc = RandomForestClassifier(random_state=0)\nclf = clf.fit(Xtrain,Ytrain)\nrfc = rfc.fit(Xtrain,Ytrain)\nscore_c = clf.score(Xtest,Ytest)\nscore_r = rfc.score(Xtest,Ytest)\n \nprint(\"Single Tree:{}\".format(score_c)\n ,\"Random Forest:{}\".format(score_r)\n )\n",
"Single Tree:0.7962962962962963 Random Forest:0.9444444444444444\n"
],
[
"#目的是带大家复习一下交叉验证\n#交叉验证:是数据集划分为n分,依次取每一份做测试集,每n-1份做训练集,多次训练模型以观测模型稳定性的方法\n \nfrom sklearn.model_selection import cross_val_score\nimport matplotlib.pyplot as plt\n \nrfc = RandomForestClassifier(n_estimators=25)\nrfc_s = cross_val_score(rfc,wine.data,wine.target,cv=10)\n \nclf = DecisionTreeClassifier()\nclf_s = cross_val_score(clf,wine.data,wine.target,cv=10)\n \nplt.plot(range(1,11),rfc_s,label = \"RandomForest\")\nplt.plot(range(1,11),clf_s,label = \"Decision Tree\")\nplt.legend()\nplt.show()\n \n#====================一种更加有趣也更简单的写法===================#\n \n\"\"\"\nlabel = \"RandomForest\"\nfor model in [RandomForestClassifier(n_estimators=25),DecisionTreeClassifier()]:\n score = cross_val_score(model,wine.data,wine.target,cv=10)\n print(\"{}:\".format(label)),print(score.mean())\n plt.plot(range(1,11),score,label = label)\n plt.legend()\n label = \"DecisionTree\"\n \n\"\"\"",
"_____no_output_____"
],
[
"rfc_l = []\nclf_l = []\n \nfor i in range(10):\n rfc = RandomForestClassifier(n_estimators=25)\n rfc_s = cross_val_score(rfc,wine.data,wine.target,cv=10).mean()\n rfc_l.append(rfc_s)\n clf = DecisionTreeClassifier()\n clf_s = cross_val_score(clf,wine.data,wine.target,cv=10).mean()\n clf_l.append(clf_s)\n \nplt.plot(range(1,11),rfc_l,label = \"Random Forest\")\nplt.plot(range(1,11),clf_l,label = \"Decision Tree\")\nplt.legend()\nplt.show()\n \n#是否有注意到,单个决策树的波动轨迹和随机森林一致?\n#再次验证了我们之前提到的,单个决策树的准确率越高,随机森林的准确率也会越高\n\n ",
"_____no_output_____"
],
[
"#####【TIME WARNING: 2mins 30 seconds】#####\n \nsuperpa = []\nfor i in range(200):\n rfc = RandomForestClassifier(n_estimators=i+1,n_jobs=-1)\n rfc_s = cross_val_score(rfc,wine.data,wine.target,cv=10).mean()\n superpa.append(rfc_s)\nprint(max(superpa),superpa.index(max(superpa))+1)#打印出:最高精确度取值,max(superpa))+1指的是森林数目的数量n_estimators\nplt.figure(figsize=[20,5])\nplt.plot(range(1,201),superpa)\nplt.show()",
"0.9888888888888889 32\n"
],
[
"import numpy as np\nfrom scipy.special import comb\n \nnp.array([comb(25,i)*(0.2**i)*((1-0.2)**(25-i)) for i in range(13,26)]).sum()\n",
"_____no_output_____"
],
[
"rfc = RandomForestClassifier(n_estimators=20,random_state=2)\nrfc = rfc.fit(Xtrain, Ytrain)\n \n#随机森林的重要属性之一:estimators,查看森林中树的状况\nrfc.estimators_[0].random_state\n \nfor i in range(len(rfc.estimators_)):\n print(rfc.estimators_[i].random_state)\n",
"1872583848\n794921487\n111352301\n1853453896\n213298710\n1922988331\n1869695442\n2081981515\n1805465960\n1376693511\n1418777250\n663257521\n878959199\n854108747\n512264917\n515183663\n1287007039\n2083814687\n1146014426\n570104212\n"
],
[
"#无需划分训练集和测试集\n \nrfc = RandomForestClassifier(n_estimators=25,oob_score=True)#默认为False\nrfc = rfc.fit(wine.data,wine.target)\n \n#重要属性oob_score_\nrfc.oob_score_#0.9719101123595506\n",
"_____no_output_____"
],
[
"#大家可以分别取尝试一下这些属性和接口\n \nrfc = RandomForestClassifier(n_estimators=25)\nrfc = rfc.fit(Xtrain, Ytrain)\nrfc.score(Xtest,Ytest)\n \nrfc.feature_importances_#结合zip可以对照特征名字查看特征重要性,参见上节决策树\nrfc.apply(Xtest)#apply返回每个测试样本所在的叶子节点的索引\nrfc.predict(Xtest)#predict返回每个测试样本的分类/回归结果\nrfc.predict_proba(Xtest)",
"_____no_output_____"
],
[
"import numpy as np\n \nx = np.linspace(0,1,20)\n \ny = []\nfor epsilon in np.linspace(0,1,20):\n E = np.array([comb(25,i)*(epsilon**i)*((1-epsilon)**(25-i)) for i in range(13,26)]).sum() \n y.append(E)\nplt.plot(x,y,\"o-\",label=\"when estimators are different\")\nplt.plot(x,x,\"--\",color=\"red\",label=\"if all estimators are same\")\nplt.xlabel(\"individual estimator's error\")\nplt.ylabel(\"RandomForest's error\")\nplt.legend()\nplt.show()\n",
"_____no_output_____"
],
[
"import numpy as np\n \nx = np.linspace(0,1,20)\n \ny = []\nfor epsilon in np.linspace(0,1,20):\n E = np.array([comb(25,i)*(epsilon**i)*((1-epsilon)**(25-i)) \n for i in range(13,26)]).sum()\n y.append(E)\nplt.plot(x,y,\"o-\",label=\"when estimators are different\")\nplt.plot(x,x,\"--\",color=\"red\",label=\"if all estimators are same\")\nplt.xlabel(\"individual estimator's error\")\nplt.ylabel(\"RandomForest's error\")\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"from sklearn.datasets import load_boston#一个标签是连续西变量的数据集\nfrom sklearn.model_selection import cross_val_score#导入交叉验证模块\nfrom sklearn.ensemble import RandomForestRegressor#导入随机森林回归系\n \nboston = load_boston()\nregressor = RandomForestRegressor(n_estimators=100,random_state=0)#实例化\ncross_val_score(regressor, boston.data, boston.target, cv=10\n ,scoring = \"neg_mean_squared_error\"#如果不写scoring,回归评估默认是R平方\n )\n",
"_____no_output_____"
],
[
"#sklearn当中的模型评估指标(打分)列表\nimport sklearn\nsorted(sklearn.metrics.SCORERS.keys())#这些指标是scoring可选择的参数",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_boston\nfrom sklearn.impute import SimpleImputer#填补缺失值的类\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import cross_val_score",
"_____no_output_____"
],
[
"dataset = load_boston()\ndataset#是一个字典\ndataset.target#查看数据标签\ndataset.data#数据的特征矩阵\ndataset.data.shape#数据的结构\n#总共506*13=6578个数据\n \nX_full, y_full = dataset.data, dataset.target\nn_samples = X_full.shape[0]#506\nn_features = X_full.shape[1]#13\n",
"_____no_output_____"
],
[
"#首先确定我们希望放入的缺失数据的比例,在这里我们假设是50%,那总共就要有3289个数据缺失\n \nrng = np.random.RandomState(0)#设置一个随机种子,方便观察\nmissing_rate = 0.5\nn_missing_samples = int(np.floor(n_samples * n_features * missing_rate))#3289\n#np.floor向下取整,返回.0格式的浮点数\n \n#所有数据要随机遍布在数据集的各行各列当中,而一个缺失的数据会需要一个行索引和一个列索引\n#如果能够创造一个数组,包含3289个分布在0~506中间的行索引,和3289个分布在0~13之间的列索引,那我们就可以利用索引来为数据中的任意3289个位置赋空值\n#然后我们用0,均值和随机森林来填写这些缺失值,然后查看回归的结果如何\n \nmissing_features = rng.randint(0,n_features,n_missing_samples)#randint(下限,上限,n)指在下限和上限之间取出n个整数\nlen(missing_features)#3289\nmissing_samples = rng.randint(0,n_samples,n_missing_samples)\nlen(missing_samples)#3289\n \n#missing_samples = rng.choice(n_samples,n_missing_samples,replace=False)\n#我们现在采样了3289个数据,远远超过我们的样本量506,所以我们使用随机抽取的函数randint。\n# 但如果我们需要的数据量小于我们的样本量506,那我们可以采用np.random.choice来抽样,choice会随机抽取不重复的随机数,\n# 因此可以帮助我们让数据更加分散,确保数据不会集中在一些行中!\n#这里我们不采用np.random.choice,因为我们现在采样了3289个数据,远远超过我们的样本量506,使用np.random.choice会报错\n \nX_missing = X_full.copy()\ny_missing = y_full.copy()\n \nX_missing[missing_samples,missing_features] = np.nan\n \nX_missing = pd.DataFrame(X_missing)\n#转换成DataFrame是为了后续方便各种操作,numpy对矩阵的运算速度快到拯救人生,但是在索引等功能上却不如pandas来得好用\nX_missing.head()\n\n#并没有对y_missing进行缺失值填补,原因是有监督学习,不能缺标签啊\n\n",
"_____no_output_____"
],
[
"#使用均值进行填补\nfrom sklearn.impute import SimpleImputer\nimp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')#实例化\nX_missing_mean = imp_mean.fit_transform(X_missing)#特殊的接口fit_transform = 训练fit + 导出predict\n#pd.DataFrame(X_missing_mean).isnull()#但是数据量大的时候还是看不全\n#布尔值False = 0, True = 1 \n# pd.DataFrame(X_missing_mean).isnull().sum()#如果求和为0可以彻底确认是否有NaN\n\n#使用0进行填补\nimp_0 = SimpleImputer(missing_values=np.nan, strategy=\"constant\",fill_value=0)#constant指的是常数\nX_missing_0 = imp_0.fit_transform(X_missing)",
"_____no_output_____"
],
[
"X_missing_reg = X_missing.copy()\n\n#找出数据集中,缺失值从小到大排列的特征们的顺序,并且有了这些的索引\nsortindex = np.argsort(X_missing_reg.isnull().sum(axis=0)).values#np.argsort()返回的是从小到大排序的顺序所对应的索引\n \nfor i in sortindex:\n \n #构建我们的新特征矩阵(没有被选中去填充的特征 + 原始的标签)和新标签(被选中去填充的特征)\n df = X_missing_reg\n fillc = df.iloc[:,i]#新标签\n df = pd.concat([df.iloc[:,df.columns != i],pd.DataFrame(y_full)],axis=1)#新特征矩阵\n \n #在新特征矩阵中,对含有缺失值的列,进行0的填补\n df_0 =SimpleImputer(missing_values=np.nan,strategy='constant',fill_value=0).fit_transform(df)\n \n #找出我们的训练集和测试集\n Ytrain = fillc[fillc.notnull()]# Ytrain是被选中要填充的特征中(现在是我们的标签),存在的那些值:非空值\n Ytest = fillc[fillc.isnull()]#Ytest 是被选中要填充的特征中(现在是我们的标签),不存在的那些值:空值。注意我们需要的不是Ytest的值,需要的是Ytest所带的索引\n Xtrain = df_0[Ytrain.index,:]#在新特征矩阵上,被选出来的要填充的特征的非空值所对应的记录\n Xtest = df_0[Ytest.index,:]#在新特征矩阵上,被选出来的要填充的特征的空值所对应的记录\n \n #用随机森林回归来填补缺失值\n rfc = RandomForestRegressor(n_estimators=100)#实例化\n rfc = rfc.fit(Xtrain, Ytrain)#导入训练集进行训练\n Ypredict = rfc.predict(Xtest)#用predict接口将Xtest导入,得到我们的预测结果(回归结果),就是我们要用来填补空值的这些值\n \n #将填补好的特征返回到我们的原始的特征矩阵中\n X_missing_reg.loc[X_missing_reg.iloc[:,i].isnull(),i] = Ypredict\n\n#检验是否有空值\nX_missing_reg.isnull().sum()",
"_____no_output_____"
],
[
"#对所有数据进行建模,取得MSE结果\n \nX = [X_full,X_missing_mean,X_missing_0,X_missing_reg]\n \nmse = []\nstd = []\nfor x in X:\n estimator = RandomForestRegressor(random_state=0, n_estimators=100)#实例化\n scores = cross_val_score(estimator,x,y_full,scoring='neg_mean_squared_error', cv=5).mean()\n mse.append(scores * -1)",
"_____no_output_____"
],
[
"[*zip(['Full data','Zero Imputation','Mean Imputation','Regressor Imputation'],mse)]",
"_____no_output_____"
],
[
"x_labels = ['Full data',\n 'Zero Imputation',\n 'Mean Imputation',\n 'Regressor Imputation']\ncolors = ['r', 'g', 'b', 'orange']\n \nplt.figure(figsize=(12, 6))#画出画布\nax = plt.subplot(111)#添加子图\nfor i in np.arange(len(mse)):\n ax.barh(i, mse[i],color=colors[i], alpha=0.6, align='center')#bar为条形图,barh为横向条形图,alpha表示条的粗度\nax.set_title('Imputation Techniques with Boston Data')\nax.set_xlim(left=np.min(mse) * 0.9,\n right=np.max(mse) * 1.1)#设置x轴取值范围\nax.set_yticks(np.arange(len(mse)))\nax.set_xlabel('MSE')\nax.set_yticklabels(x_labels)\nplt.show()",
"_____no_output_____"
],
[
"from sklearn.datasets import load_breast_cancer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"data = load_breast_cancer()\n \ndata\n \ndata.data.shape\n \ndata.target\n \n#可以看到,乳腺癌数据集有569条记录,30个特征,单看维度虽然不算太高,但是样本量非常少。过拟合的情况可能存在。",
"_____no_output_____"
],
[
"rfc = RandomForestClassifier(n_estimators=100,random_state=90)\nscore_pre = cross_val_score(rfc,data.data,data.target,cv=10).mean()#交叉验证的分类默认scoring='accuracy'\n \nscore_pre\n \n#这里可以看到,随机森林在乳腺癌数据上的表现本就还不错,在现实数据集上,基本上不可能什么都不调就看到95%以上的准确率\n\n",
"_____no_output_____"
],
[
"\"\"\"\n在这里我们选择学习曲线,可以使用网格搜索吗?可以,但是只有学习曲线,才能看见趋势\n我个人的倾向是,要看见n_estimators在什么取值开始变得平稳,是否一直推动模型整体准确率的上升等信息\n第一次的学习曲线,可以先用来帮助我们划定范围,我们取每十个数作为一个阶段,来观察n_estimators的变化如何\n引起模型整体准确率的变化\n\"\"\"\n \n#####【TIME WARNING: 30 seconds】#####\n \nscorel = []\nfor i in range(0,200,10):\n rfc = RandomForestClassifier(n_estimators=i+1,\n n_jobs=-1,\n random_state=90)\n score = cross_val_score(rfc,data.data,data.target,cv=10).mean()\n scorel.append(score)\nprint(max(scorel),(scorel.index(max(scorel))*10)+1)\nplt.figure(figsize=[20,5])\nplt.plot(range(1,201,10),scorel)\nplt.show()\n \n#list.index([object])\n#返回这个object在列表list中的索引\n",
"0.9684480598046841 41\n"
],
[
"scorel = []\nfor i in range(35,45):\n rfc = RandomForestClassifier(n_estimators=i,\n n_jobs=-1,\n random_state=90)\n score = cross_val_score(rfc,data.data,data.target,cv=10).mean()\n scorel.append(score)\nprint(max(scorel),([*range(35,45)][scorel.index(max(scorel))]))\nplt.figure(figsize=[20,5])\nplt.plot(range(35,45),scorel)\nplt.show()",
"0.9719568317345088 39\n"
],
[
"\"\"\"\n有一些参数是没有参照的,很难说清一个范围,这种情况下我们使用学习曲线,看趋势\n从曲线跑出的结果中选取一个更小的区间,再跑曲线\nparam_grid = {'n_estimators':np.arange(0, 200, 10)}\n \nparam_grid = {'max_depth':np.arange(1, 20, 1)}\n \nparam_grid = {'max_leaf_nodes':np.arange(25,50,1)}\n 对于大型数据集,可以尝试从1000来构建,先输入1000,每100个叶子一个区间,再逐渐缩小范围\n \n有一些参数是可以找到一个范围的,或者说我们知道他们的取值和随着他们的取值,模型的整体准确率会如何变化,这\n样的参数我们就可以直接跑网格搜索\nparam_grid = {'criterion':['gini', 'entropy']}\n \nparam_grid = {'min_samples_split':np.arange(2, 2+20, 1)}\n \nparam_grid = {'min_samples_leaf':np.arange(1, 1+10, 1)}\n \nparam_grid = {'max_features':np.arange(5,30,1)} \n \n\"\"\"",
"_____no_output_____"
],
[
"#调整max_depth\n \nparam_grid = {'max_depth':np.arange(1, 20, 1)}\n \n# 一般根据数据的大小来进行一个试探,乳腺癌数据很小,所以可以采用1~10,或者1~20这样的试探\n# 但对于像digit recognition那样的大型数据来说,我们应该尝试30~50层深度(或许还不足够\n# 更应该画出学习曲线,来观察深度对模型的影响\n \nrfc = RandomForestClassifier(n_estimators=39\n ,random_state=90\n )\nGS = GridSearchCV(rfc,param_grid,cv=10)#网格搜索\nGS.fit(data.data,data.target)\n \nGS.best_params_#显示调整出来的最佳参数\n \nGS.best_score_#返回调整好的最佳参数对应的准确率",
"f:\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_search.py:841: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.\n DeprecationWarning)\n"
],
[
"#调整max_features\n \nparam_grid = {'max_features':np.arange(5,30,1)} \n \n\"\"\"\n \nmax_features是唯一一个即能够将模型往左(低方差高偏差)推,也能够将模型往右(高方差低偏差)推的参数。我\n们需要根据调参前,模型所在的位置(在泛化误差最低点的左边还是右边)来决定我们要将max_features往哪边调。\n现在模型位于图像左侧,我们需要的是更高的复杂度,因此我们应该把max_features往更大的方向调整,可用的特征\n越多,模型才会越复杂。max_features的默认最小值是sqrt(n_features),因此我们使用这个值作为调参范围的\n最小值。\n \n\"\"\"\n \nrfc = RandomForestClassifier(n_estimators=39\n ,random_state=90\n )\nGS = GridSearchCV(rfc,param_grid,cv=10)\nGS.fit(data.data,data.target)\n \nGS.best_params_\n \nGS.best_score_",
"f:\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_search.py:841: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.\n DeprecationWarning)\n"
],
[
"#调整min_samples_leaf\n \nparam_grid={'min_samples_leaf':np.arange(1, 1+10, 1)}\n \n#对于min_samples_split和min_samples_leaf,一般是从他们的最小值开始向上增加10或20\n#面对高维度高样本量数据,如果不放心,也可以直接+50,对于大型数据,可能需要200~300的范围\n#如果调整的时候发现准确率无论如何都上不来,那可以放心大胆调一个很大的数据,大力限制模型的复杂度\n \nrfc = RandomForestClassifier(n_estimators=39\n ,random_state=90\n )\nGS = GridSearchCV(rfc,param_grid,cv=10)\nGS.fit(data.data,data.target)\n \nGS.best_params_\n \nGS.best_score_\n",
"f:\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_search.py:841: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.\n DeprecationWarning)\n"
],
[
"#调整min_samples_split\n \nparam_grid={'min_samples_split':np.arange(2, 2+20, 1)}\n \nrfc = RandomForestClassifier(n_estimators=39\n ,random_state=90\n )\nGS = GridSearchCV(rfc,param_grid,cv=10)\nGS.fit(data.data,data.target)\n \nGS.best_params_\n \nGS.best_score_\n",
"f:\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_search.py:841: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.\n DeprecationWarning)\n"
],
[
"#调整Criterion\n \nparam_grid = {'criterion':['gini', 'entropy']}\n \nrfc = RandomForestClassifier(n_estimators=39\n ,random_state=90\n )\nGS = GridSearchCV(rfc,param_grid,cv=10)\nGS.fit(data.data,data.target)\n \nGS.best_params_\n \nGS.best_score_\n",
"_____no_output_____"
],
[
"rfc = RandomForestClassifier(n_estimators=39,random_state=90)\nscore = cross_val_score(rfc,data.data,data.target,cv=10).mean()\nscore\n \nscore - score_pre\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e788e280aac43f65491828e4c4baa94235573e9a | 17,022 | ipynb | Jupyter Notebook | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage | 06c15faeae00716dda6cb7865d72d448618b50ce | [
"MIT"
] | null | null | null | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage | 06c15faeae00716dda6cb7865d72d448618b50ce | [
"MIT"
] | 8 | 2020-01-09T17:00:05.000Z | 2020-06-29T18:01:24.000Z | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage | 06c15faeae00716dda6cb7865d72d448618b50ce | [
"MIT"
] | 1 | 2020-08-01T17:13:31.000Z | 2020-08-01T17:13:31.000Z | 31.175824 | 508 | 0.498531 | [
[
[
"# Understanding Cross-Entropy Loss\n\n**Recall:** a loss function compares the predictions of a model with the correct labels to tell us how well the model is doing, and to help find out how we can update the model's parameters to improve its performance (using gradient descent).\n\n**Cross-entropy** is a loss function we can use to train a model when the output is one of several classes. For example, we have 10 classes to choose from when trying to predict which number an image of a single digit represents.\n\n\n\n*In this image, the number we are trying to predict belongs to the class representing the digit 8.*\n\nTo use the cross-entropy loss, we need to have as many outputs from our model as the number of possible classes. The cross-entropy loss then enables us to train the model such that the value of the output corresponding to the correct prediction is high, and for the other outputs it is low.\n\nThe first step of using the cross-entropy loss function is passing the raw outputs of the model through a **softmax layer**. A softmax layer squishes all the outputs of the model between 0 and 1. It also ensures that all these values combined add up to 1.\n\n",
"_____no_output_____"
]
],
[
[
"import torch\n\nt = torch.tensor([[-9, 5, 10]], dtype=torch.double)\ntorch.softmax(t, dim=1)",
"_____no_output_____"
]
],
[
[
"Mathematically, each of the values above is calculated as follows:\n\n\n\nWe can create a function to calculate the softmax on our own as follows:\n",
"_____no_output_____"
]
],
[
[
"def softmax(x):\n return torch.exp(x) / torch.exp(x).sum()\n\nsoftmax(t)",
"_____no_output_____"
]
],
[
[
"Each value can be interpreted as the confidence with which the model predicts the corresponding output as the correct class.\n\nSince the exponential function is used in the softmax layer, any raw output from the model that is slightly higher than another will be amplified by the softmax layer.\n\n\n\n*The exponential function amplifies even small differences in input values*\n\nThis goes to show that the softmax layer tries its best to pick one single value as the correct model output. As a result, this layer works really well when trying to train a classifier that has to pick one correct category.\n\nOn the other hand, if you want a model not to pick a class just because it has just a slightly higher output value, it is advisable to use the sigmoid function with each individual output.\n\nAfter the softmax layer, the second part of the cross-entropy loss is the **log likelihood**.\n\nBy using the softmax layer, we have condensed the value of each output between 0 and 1. This greatly reduces the sensitivity of the model confidence. For example, a prediction of 0.999 can be interpreted as being 10 times more confident than a prediction of 0.99. However, on a softmax scale, the difference between the two values is minuscule - a mere 0.009!\n\nBy taking the log of the values, we can amplify even such small differences.\n\nFor example,\n\n$$\n\\frac{0.999}{0.99} \\times 100\\% = \\text{approx. 0.9\\% difference in confidence}\n$$\n\nHowever,\n\n$$\n\\frac{\\log{0.999}}{\\log{0.99}} \\times 100\\% = \\text{approx. 10\\% difference in confidence}\n$$\n\nOn a log scale, number close to 0 are pushed towards negative infinity and numbers close to 1 are pushed towards 0.\n\n\n\nLet us now consider the model output value corresponding to the correct class. If we maximize this value, then all the other values will be automatically minimized (since all values have to add up to 1 because of the softmax layer).\n\nIf the output of the model corresponding to the correct class is close to 1, its log value will be close to 0. However, if the model output is close to 0, its log value will be highly negative (close to negative infinity).\n\nWe need the value of the loss function to be high when the prediction is incorrect, and low when the prediction is correct. We can have this with the log values if we drop the negative sign (or equivalently, multiply the value by -1). Then, when the model output is close to 0 for the correct class (incorrect prediction), the negative log value will be extremely high and when the model output is close to 1 for the correct class (correct prediction), the negative log value will be close to 0.\n\n\n\nWe can then use this as a loss function to maximize the output of the model corresponding to the correct class. Like we saw before, this will automatically minimize the outputs of the other classes because of the softmax function.\n\nThis combination of softmax and log-likelihood is the cross-entropy loss.",
"_____no_output_____"
],
[
"To see how this all works with PyTorch, let us assume we have 3 data points that can belong to one of 5 classes.\n\nAssume our model produces the following output for these 3 data points:",
"_____no_output_____"
]
],
[
[
"model_output = torch.randn((3, 5))\nmodel_output",
"_____no_output_____"
]
],
[
[
"Let us also assume that the correct classes for these data points are as follows:",
"_____no_output_____"
]
],
[
[
"targets = torch.tensor([3, 0, 1])\ntargets",
"_____no_output_____"
]
],
[
[
"We first pass these outputs through a softmax layer:",
"_____no_output_____"
]
],
[
[
"sm = torch.softmax(model_output, dim = 1)\nsm",
"_____no_output_____"
]
],
[
[
"As expected, all values have been squished between 0 and 1.\n\nWe can also confirm that for each data point, the values sum up to 1:",
"_____no_output_____"
]
],
[
[
"sm.sum(dim=1)",
"_____no_output_____"
]
],
[
[
"Next, we take the log of these values:",
"_____no_output_____"
]
],
[
[
"lg = torch.log(sm)\nlg",
"_____no_output_____"
]
],
[
[
"We can then use `nll_loss` (i.e. Negative Log Likelihood) that will find the mean of the values corresponding to the correct class. This function will also multiply the values by -1 for us before doing so.",
"_____no_output_____"
]
],
[
[
"import torch.nn.functional as F\n\nloss = F.nll_loss(lg, targets)\nloss",
"_____no_output_____"
]
],
[
[
"We can manually verify this for the 3 data points:",
"_____no_output_____"
]
],
[
[
"-1 * (lg[0][targets[0]] + lg[1][targets[1]] + lg[2][targets[2]]) / 3",
"_____no_output_____"
]
],
[
[
"Note that the `nll_loss` function assumes that the log has been taken before the values are passed to the function.\n\nPyTorch has a `log_softmax` function that combines softmax with log in one step. We can use that function to achieve the same result as follows:",
"_____no_output_____"
]
],
[
[
"lsm = F.log_softmax(model_output, dim = 1)\nloss = F.nll_loss(lsm, targets)\nloss",
"_____no_output_____"
]
],
[
[
"PyTorch also has a cross-entropy loss that can be used directly on raw model outputs:",
"_____no_output_____"
]
],
[
[
"F.cross_entropy(model_output, targets)",
"_____no_output_____"
]
],
[
[
"The relationship between these three approaches can be summarized as follows:\n\n\n\n## References\n\n- [Deep Learning for Coders with Fastai and Pytorch: AI Applications Without a PhD (Fastbook) - Ch. 5](https://github.com/fastai/fastbook/blob/master/05_pet_breeds.ipynb)\n- [Understanding softmax and the negative log-likelihood](https://ljvmiranda921.github.io/notebook/2017/08/13/softmax-and-the-negative-log-likelihood/)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e788e6d8eca04b08f8129325987d88b4c3a432f0 | 4,016 | ipynb | Jupyter Notebook | LaTeX_Assignment.ipynb | UWashington-Astro300/Astro300-Wtr19 | 0d61faf057ea926d6b5d6c55677d70d2b4ab2261 | [
"MIT"
] | 2 | 2020-02-06T03:05:59.000Z | 2021-06-03T22:55:57.000Z | LaTeX_Assignment.ipynb | UWashington-Astro300/Astro300-Wtr19 | 0d61faf057ea926d6b5d6c55677d70d2b4ab2261 | [
"MIT"
] | null | null | null | LaTeX_Assignment.ipynb | UWashington-Astro300/Astro300-Wtr19 | 0d61faf057ea926d6b5d6c55677d70d2b4ab2261 | [
"MIT"
] | 3 | 2019-01-15T01:03:17.000Z | 2021-04-09T23:11:58.000Z | 22.818182 | 98 | 0.464392 | [
[
[
"---\n\n## Some websites to open up for class:",
"_____no_output_____"
],
[
"- ## [Overleaf](https://v2.overleaf.com/)\n\n- ## [Overleaf Docs and Help](https://v2.overleaf.com/learn)\n\n- ## [Latex Symbols](https://en.wikipedia.org/wiki/Wikipedia:LaTeX_symbols)\n\n- ## [Latex draw symbols](http://detexify.kirelabs.org/classify.html)\n\n- ## [The SAO/NASA Astrophysics Data System](https://ui.adsabs.harvard.edu/#classic-form)\n\n---\n\n- ## [Latex wikibook](https://en.wikibooks.org/wiki/LaTeX)",
"_____no_output_____"
],
[
"---\n\n# $\\LaTeX$ Assignment",
"_____no_output_____"
]
],
[
[
"-----------------------------------------------------------------------------\nLaTeX homework - Create a LaTeX document with references.\n-----------------------------------------------------------------------------\n\nStart with the file: FirstLast.tex\n\nMinimum required elements:\n\n* Between 2 and 4 pages in length (pages > 4 will be ignored).\n\n* At least two paragraphs of text (the text should be coherent).\n\n* At least 5 references from ADS.\n\n * http://adsabs.harvard.edu/abstract_service.html\n * Make sure to \\citep{} or \\citet{} the references in your paper\n\n* The equation on the blackboard.\n\n* One (or more) equation(s) of your choice.\n\n* Include the plot you generated last class (MyCoolPlot.png)\n\n* One other plot/image (do not reuse and old one!)\n\n* One table of at least 4 columns and 4 rows.\n\n* Bonus points given for interesting content!\n\n-----------------------------------------------------------------------------\n\nCreate a PDF file:\n\nSave the file as FirstLast.pdf (i.e. TobySmith.pdf)\n\nUpload the PDF to the class canvas site\n\n-----------------------------------------------------------------------------\nDeadline: Monday Mar 11 - 10pm\n-----------------------------------------------------------------------------",
"_____no_output_____"
]
],
[
[
"## `pandas` can output $\\LaTeX$ tables",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"my_table = pd.read_csv('./Data/Zodiac.csv')",
"_____no_output_____"
],
[
"my_table[0:3]",
"_____no_output_____"
],
[
"print(my_table.to_latex(index=False))",
"_____no_output_____"
]
]
] | [
"markdown",
"raw",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"raw"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e788ef2c35738c8f8933def465ef35c5b23da107 | 21,986 | ipynb | Jupyter Notebook | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge | 3ca16437092911a23c2a3a388c7c2ca1cc7f1622 | [
"ADSL"
] | null | null | null | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge | 3ca16437092911a23c2a3a388c7c2ca1cc7f1622 | [
"ADSL"
] | null | null | null | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge | 3ca16437092911a23c2a3a388c7c2ca1cc7f1622 | [
"ADSL"
] | null | null | null | 33.515244 | 1,441 | 0.486082 | [
[
[
"# Update sklearn to prevent version mismatches\n!pip install sklearn --upgrade",
"Requirement already up-to-date: sklearn in c:\\users\\megam\\anaconda3\\envs\\pythondata\\lib\\site-packages (0.0)\nRequirement already satisfied, skipping upgrade: scikit-learn in c:\\users\\megam\\anaconda3\\envs\\pythondata\\lib\\site-packages (from sklearn) (0.21.2)\nRequirement already satisfied, skipping upgrade: numpy>=1.11.0 in c:\\users\\megam\\anaconda3\\envs\\pythondata\\lib\\site-packages (from scikit-learn->sklearn) (1.16.4)\nRequirement already satisfied, skipping upgrade: joblib>=0.11 in c:\\users\\megam\\anaconda3\\envs\\pythondata\\lib\\site-packages (from scikit-learn->sklearn) (0.13.2)\nRequirement already satisfied, skipping upgrade: scipy>=0.17.0 in c:\\users\\megam\\anaconda3\\envs\\pythondata\\lib\\site-packages (from scikit-learn->sklearn) (1.3.1)\n"
],
[
"# install joblib. This will be used to save your model. \n# Restart your kernel after installing \n!pip install joblib",
"Requirement already satisfied: joblib in c:\\users\\megam\\anaconda3\\envs\\pythondata\\lib\\site-packages (0.13.2)\n"
],
[
"import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt ",
"_____no_output_____"
]
],
[
[
"# Read the CSV and Perform Basic Data Cleaning",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"exoplanet_data.csv\")\n# Drop the null columns where all values are null\ndf = df.dropna(axis='columns', how='all')\n# Drop the null rows\ndf = df.dropna()\ndf.head()",
"_____no_output_____"
],
[
"df = df[df[\"koi_disposition\"] != 'CANDIDATE']\ndf[\"koi_disposition\"].value_counts()",
"_____no_output_____"
]
],
[
[
"# Select your features (columns)",
"_____no_output_____"
]
],
[
[
"# Set features. This will also be used as your x values.\nselected_features = df[['koi_period', 'koi_impact', 'koi_duration', 'koi_depth', 'koi_prad', 'koi_teq', 'koi_insol', 'koi_steff', 'koi_slogg', 'koi_srad']]\nselected_features.koi_period.astype(float)",
"_____no_output_____"
]
],
[
[
"# Create a Train Test Split\n\nUse `koi_disposition` for the y values",
"_____no_output_____"
]
],
[
[
"selected_features['koi_disposition_dummy'] = selected_features.koi_disposition.map({'FALSE POSITIVE':0, 'CONFIRMED':1})\ny = selected_features['koi_disposition_dummy']",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(selected_features, y, random_state=0)",
"_____no_output_____"
],
[
"y_train.head()",
"_____no_output_____"
]
],
[
[
"# Pre-processing\n\nScale the data using the MinMaxScaler and perform some feature selection",
"_____no_output_____"
]
],
[
[
"# Scale your data\nfrom sklearn.preprocessing import MinMaxScaler\nminmax = MinMaxScaler()\nminmax_fitted = minmax.fit(X_train)\nX_trains = minmax_fitted.transform(X_train)\nX_tests = minmax_fitted.transform(X_test)\n# y_trains = minmax.fit_transform(y_train)\n# y_tests = minmax.fit_transform(y_test)",
"_____no_output_____"
]
],
[
[
"# Train the Model\n\n",
"_____no_output_____"
],
[
"## Not using scaled",
"_____no_output_____"
]
],
[
[
"from sklearn.cluster import KMeans\nfrom sklearn import metrics\nmodel1 = KMeans(n_clusters=3)",
"_____no_output_____"
],
[
"model1.fit(X_train)",
"_____no_output_____"
],
[
"# Predict the clusters\npred = model1.predict(X_test)\npred_train = model1.predict(X_train)",
"_____no_output_____"
],
[
"# testing score\nscore = metrics.f1_score(y_test, pred, pos_label=list(set(y_test)), average=None)\n# training score\nscore_train = metrics.f1_score(y_train, pred_train, pos_label=list(set(y_train)), average=None)\n\nprint(f\"Training Data Score: {score_train[0]}\")\nprint(\"-----------------------------------------------------\")\nprint(f\"Testing Data Score: {score[0]}\")",
"Training Data Score: 0.7941800545619885\n-----------------------------------------------------\nTesting Data Score: 0.7972789115646258\n"
]
],
[
[
"## Using scaled",
"_____no_output_____"
]
],
[
[
"kmeansS = KMeans(n_clusters=3)\nkmeansS.fit(X_trains)\n\n# Predict the clusters\npreds = kmeansS.predict(X_tests)\npred_trains = kmeansS.predict(X_trains)\n\n# testing score\nscores = metrics.f1_score(y_test, preds, pos_label=list(set(y_test)), average=None)\n# training score\nscore_trains = metrics.f1_score(y_train, pred_trains, pos_label=list(set(y_train)), average=None)\n\nprint(f\"Testing score: {kmeansS.score(X_tests, y_test)}\")\nprint(f\"Training score: {kmeansS.score(X_trains, y_train)}\")\n\nprint(scores)\nprint(score_trains)",
"Testing score: -29.14663974446135\nTraining score: -87.19826994353079\n[0.21327968 0.5829904 0. ]\n[0.23431242 0.59401416 0. ]\n"
]
],
[
[
"# Save the Model",
"_____no_output_____"
]
],
[
[
"# save your model by updating \"your_name\" with your name\n# and \"your_model\" with your model variable\n# be sure to turn this in to BCS\n# if joblib fails to import, try running the command to install in terminal/git-bash\nimport joblib\nfilename = 'megan_okerlund_model1.sav'\njoblib.dump(model1, filename)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e78909bd1ef57f305229cded235c6f2e33ac1bfc | 75,633 | ipynb | Jupyter Notebook | basic-statistical-description.ipynb | Shawn-Ng/statistics | 712c08673614360d3a1c27d5b14c14d9e70d80de | [
"BSD-2-Clause"
] | null | null | null | basic-statistical-description.ipynb | Shawn-Ng/statistics | 712c08673614360d3a1c27d5b14c14d9e70d80de | [
"BSD-2-Clause"
] | null | null | null | basic-statistical-description.ipynb | Shawn-Ng/statistics | 712c08673614360d3a1c27d5b14c14d9e70d80de | [
"BSD-2-Clause"
] | null | null | null | 210.091667 | 16,828 | 0.925284 | [
[
[
"import numpy as np\nfrom scipy import stats\nimport seaborn as sns\n\n%matplotlib inline",
"_____no_output_____"
],
[
"data = [30,36,47,50,52,52,56,60,63,70,70,110]",
"_____no_output_____"
],
[
"# mean\nnp.mean(data)",
"_____no_output_____"
],
[
"# median\nnp.median(data)",
"_____no_output_____"
],
[
"# mode\nstats.mode(data)",
"_____no_output_____"
],
[
"# variance\nnp.var(data)",
"_____no_output_____"
],
[
"# 25 percentile\nnp.percentile(data, 25)",
"_____no_output_____"
],
[
"# 75 percentile\nnp.percentile(data, 75)",
"_____no_output_____"
],
[
"# interquantile range\nstats.iqr(data)",
"_____no_output_____"
],
[
"sns.boxplot(data)",
"_____no_output_____"
],
[
"sns.violinplot(data)",
"_____no_output_____"
],
[
"sns.distplot(data)",
"/home/anonymous/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.\n warnings.warn(\"The 'normed' kwarg is deprecated, and has been \"\n"
],
[
"sns.distplot(data, hist=False, rug=True)",
"_____no_output_____"
],
[
"sns.kdeplot(data, shade=True)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7890e7f5dd28c769be3ccc44cb0cb02d2ed6fc8 | 432,213 | ipynb | Jupyter Notebook | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch | 558ddd3592a127cc4316c1054c640a8de49091c7 | [
"MIT"
] | 1 | 2022-03-26T17:44:06.000Z | 2022-03-26T17:44:06.000Z | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch | 558ddd3592a127cc4316c1054c640a8de49091c7 | [
"MIT"
] | null | null | null | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch | 558ddd3592a127cc4316c1054c640a8de49091c7 | [
"MIT"
] | null | null | null | 71.440165 | 666 | 0.58945 | [
[
[
"# Transfer Learning\n\nIn this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html). \n\nImageNet is a massive dataset with over 1 million labeled images in 1000 categories. It's used to train deep neural networks using an architecture called convolutional layers. I'm not going to get into the details of convolutional networks here, but if you want to learn more about them, please [watch this](https://www.youtube.com/watch?v=2-Ol7ZB0MmU).\n\nOnce trained, these models work astonishingly well as feature detectors for images they weren't trained on. Using a pre-trained network on images not in the training set is called transfer learning. Here we'll use transfer learning to train a network that can classify our cat and dog photos with near perfect accuracy.\n\nWith `torchvision.models` you can download these pre-trained networks and use them in your applications. We'll include `models` in our imports now.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models",
"_____no_output_____"
]
],
[
[
"Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trained. Each color channel was normalized separately, the means are `[0.485, 0.456, 0.406]` and the standard deviations are `[0.229, 0.224, 0.225]`.",
"_____no_output_____"
]
],
[
[
"! curl -O \"https://s3.amazonaws.com/content.udacity-data.com/nd089/Cat_Dog_data.zip\"",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 553M 100 553M 0 0 44.8M 0 0:00:12 0:00:12 --:--:-- 48.2M\n"
],
[
"! unzip Cat_Dog_data.zip",
"\u001b[1;30;43mStreaming output truncated to the last 5000 lines.\u001b[0m\n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8636.jpg \n inflating: Cat_Dog_data/train/dog/dog.7505.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7505.jpg \n inflating: Cat_Dog_data/train/dog/dog.1174.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1174.jpg \n inflating: Cat_Dog_data/train/dog/dog.9528.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9528.jpg \n inflating: Cat_Dog_data/train/dog/dog.1612.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1612.jpg \n inflating: Cat_Dog_data/train/dog/dog.8150.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8150.jpg \n inflating: Cat_Dog_data/train/dog/dog.7263.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7263.jpg \n inflating: Cat_Dog_data/train/dog/dog.11043.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11043.jpg \n inflating: Cat_Dog_data/train/dog/dog.634.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.634.jpg \n inflating: Cat_Dog_data/train/dog/dog.3005.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3005.jpg \n inflating: Cat_Dog_data/train/dog/dog.5474.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5474.jpg \n inflating: Cat_Dog_data/train/dog/dog.6155.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6155.jpg \n inflating: Cat_Dog_data/train/dog/dog.9266.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9266.jpg \n inflating: Cat_Dog_data/train/dog/dog.8178.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8178.jpg \n inflating: Cat_Dog_data/train/dog/dog.4742.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4742.jpg \n inflating: Cat_Dog_data/train/dog/dog.2333.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2333.jpg \n inflating: Cat_Dog_data/train/dog/dog.10375.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10375.jpg \n inflating: Cat_Dog_data/train/dog/dog.3993.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3993.jpg \n inflating: Cat_Dog_data/train/dog/dog.10413.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10413.jpg \n inflating: Cat_Dog_data/train/dog/dog.2455.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2455.jpg \n inflating: Cat_Dog_data/train/dog/dog.4024.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4024.jpg \n inflating: Cat_Dog_data/train/dog/dog.12204.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12204.jpg \n inflating: Cat_Dog_data/train/dog/dog.6633.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6633.jpg \n inflating: Cat_Dog_data/train/dog/dog.9500.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9500.jpg \n inflating: Cat_Dog_data/train/dog/dog.12210.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12210.jpg \n inflating: Cat_Dog_data/train/dog/dog.7539.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7539.jpg \n inflating: Cat_Dog_data/train/dog/dog.1148.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1148.jpg \n inflating: Cat_Dog_data/train/dog/dog.6627.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6627.jpg \n inflating: Cat_Dog_data/train/dog/dog.9514.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9514.jpg \n inflating: Cat_Dog_data/train/dog/dog.3987.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3987.jpg \n inflating: Cat_Dog_data/train/dog/dog.10407.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10407.jpg \n inflating: Cat_Dog_data/train/dog/dog.2441.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2441.jpg \n inflating: Cat_Dog_data/train/dog/dog.4030.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4030.jpg \n inflating: Cat_Dog_data/train/dog/dog.11719.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11719.jpg \n inflating: Cat_Dog_data/train/dog/dog.4756.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4756.jpg \n inflating: Cat_Dog_data/train/dog/dog.608.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.608.jpg \n inflating: Cat_Dog_data/train/dog/dog.3039.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3039.jpg \n inflating: Cat_Dog_data/train/dog/dog.5448.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5448.jpg \n inflating: Cat_Dog_data/train/dog/dog.10361.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10361.jpg \n inflating: Cat_Dog_data/train/dog/dog.6141.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6141.jpg \n inflating: Cat_Dog_data/train/dog/dog.9272.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9272.jpg \n inflating: Cat_Dog_data/train/dog/dog.8187.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8187.jpg \n inflating: Cat_Dog_data/train/dog/dog.9299.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9299.jpg \n inflating: Cat_Dog_data/train/dog/dog.4965.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4965.jpg \n inflating: Cat_Dog_data/train/dog/dog.11094.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11094.jpg \n inflating: Cat_Dog_data/train/dog/dog.185.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.185.jpg \n inflating: Cat_Dog_data/train/dog/dog.6814.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6814.jpg \n inflating: Cat_Dog_data/train/dog/dog.191.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.191.jpg \n inflating: Cat_Dog_data/train/dog/dog.3978.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3978.jpg \n inflating: Cat_Dog_data/train/dog/dog.4971.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4971.jpg \n inflating: Cat_Dog_data/train/dog/dog.11080.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11080.jpg \n inflating: Cat_Dog_data/train/dog/dog.8193.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8193.jpg \n inflating: Cat_Dog_data/train/dog/dog.1809.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1809.jpg \n inflating: Cat_Dog_data/train/dog/dog.4959.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4959.jpg \n inflating: Cat_Dog_data/train/dog/dog.807.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.807.jpg \n inflating: Cat_Dog_data/train/dog/dog.4781.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4781.jpg \n inflating: Cat_Dog_data/train/dog/dog.7288.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7288.jpg \n inflating: Cat_Dog_data/train/dog/dog.1821.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1821.jpg \n inflating: Cat_Dog_data/train/dog/dog.6196.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6196.jpg \n inflating: Cat_Dog_data/train/dog/dog.8805.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8805.jpg \n inflating: Cat_Dog_data/train/dog/dog.3788.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3788.jpg \n inflating: Cat_Dog_data/train/dog/dog.2496.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2496.jpg \n inflating: Cat_Dog_data/train/dog/dog.3944.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3944.jpg \n inflating: Cat_Dog_data/train/dog/dog.2482.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2482.jpg \n inflating: Cat_Dog_data/train/dog/dog.11902.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11902.jpg \n inflating: Cat_Dog_data/train/dog/dog.8811.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8811.jpg \n inflating: Cat_Dog_data/train/dog/dog.1835.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1835.jpg \n inflating: Cat_Dog_data/train/dog/dog.6182.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6182.jpg \n inflating: Cat_Dog_data/train/dog/dog.813.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.813.jpg \n inflating: Cat_Dog_data/train/dog/dog.4795.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4795.jpg \n inflating: Cat_Dog_data/train/dog/dog.8810.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8810.jpg \n inflating: Cat_Dog_data/train/dog/dog.11903.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11903.jpg \n inflating: Cat_Dog_data/train/dog/dog.2483.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2483.jpg \n inflating: Cat_Dog_data/train/dog/dog.3945.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3945.jpg \n inflating: Cat_Dog_data/train/dog/dog.4794.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4794.jpg \n inflating: Cat_Dog_data/train/dog/dog.812.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.812.jpg \n inflating: Cat_Dog_data/train/dog/dog.6183.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6183.jpg \n inflating: Cat_Dog_data/train/dog/dog.1834.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1834.jpg \n inflating: Cat_Dog_data/train/dog/dog.6197.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6197.jpg \n inflating: Cat_Dog_data/train/dog/dog.1820.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1820.jpg \n inflating: Cat_Dog_data/train/dog/dog.7289.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7289.jpg \n inflating: Cat_Dog_data/train/dog/dog.4780.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4780.jpg \n inflating: Cat_Dog_data/train/dog/dog.806.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.806.jpg \n inflating: Cat_Dog_data/train/dog/dog.4958.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4958.jpg \n inflating: Cat_Dog_data/train/dog/dog.2497.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2497.jpg \n inflating: Cat_Dog_data/train/dog/dog.3951.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3951.jpg \n inflating: Cat_Dog_data/train/dog/dog.3789.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3789.jpg \n inflating: Cat_Dog_data/train/dog/dog.6829.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6829.jpg \n inflating: Cat_Dog_data/train/dog/dog.8804.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8804.jpg \n inflating: Cat_Dog_data/train/dog/dog.3979.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3979.jpg \n inflating: Cat_Dog_data/train/dog/dog.190.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.190.jpg \n inflating: Cat_Dog_data/train/dog/dog.6801.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6801.jpg \n inflating: Cat_Dog_data/train/dog/dog.8192.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8192.jpg \n inflating: Cat_Dog_data/train/dog/dog.11081.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11081.jpg \n inflating: Cat_Dog_data/train/dog/dog.4970.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4970.jpg \n inflating: Cat_Dog_data/train/dog/dog.4964.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4964.jpg \n inflating: Cat_Dog_data/train/dog/dog.8186.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8186.jpg \n inflating: Cat_Dog_data/train/dog/dog.6815.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6815.jpg \n inflating: Cat_Dog_data/train/dog/dog.184.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.184.jpg \n inflating: Cat_Dog_data/train/dog/dog.11718.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11718.jpg \n inflating: Cat_Dog_data/train/dog/dog.4031.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4031.jpg \n inflating: Cat_Dog_data/train/dog/dog.2440.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2440.jpg \n inflating: Cat_Dog_data/train/dog/dog.10406.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10406.jpg \n inflating: Cat_Dog_data/train/dog/dog.3986.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3986.jpg \n inflating: Cat_Dog_data/train/dog/dog.9515.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9515.jpg \n inflating: Cat_Dog_data/train/dog/dog.6626.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6626.jpg \n inflating: Cat_Dog_data/train/dog/dog.7538.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7538.jpg \n inflating: Cat_Dog_data/train/dog/dog.12211.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12211.jpg \n inflating: Cat_Dog_data/train/dog/dog.9273.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9273.jpg \n inflating: Cat_Dog_data/train/dog/dog.10360.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10360.jpg \n inflating: Cat_Dog_data/train/dog/dog.5449.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5449.jpg \n inflating: Cat_Dog_data/train/dog/dog.2326.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2326.jpg \n inflating: Cat_Dog_data/train/dog/dog.3038.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3038.jpg \n inflating: Cat_Dog_data/train/dog/dog.609.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.609.jpg \n inflating: Cat_Dog_data/train/dog/dog.4757.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4757.jpg \n inflating: Cat_Dog_data/train/dog/dog.10374.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10374.jpg \n inflating: Cat_Dog_data/train/dog/dog.2332.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2332.jpg \n inflating: Cat_Dog_data/train/dog/dog.4743.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4743.jpg \n inflating: Cat_Dog_data/train/dog/dog.8179.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8179.jpg \n inflating: Cat_Dog_data/train/dog/dog.16.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.16.jpg \n inflating: Cat_Dog_data/train/dog/dog.9267.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9267.jpg \n inflating: Cat_Dog_data/train/dog/dog.6154.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6154.jpg \n inflating: Cat_Dog_data/train/dog/dog.9501.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9501.jpg \n inflating: Cat_Dog_data/train/dog/dog.12205.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12205.jpg \n inflating: Cat_Dog_data/train/dog/dog.4025.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4025.jpg \n inflating: Cat_Dog_data/train/dog/dog.2454.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2454.jpg \n inflating: Cat_Dog_data/train/dog/dog.10412.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10412.jpg \n inflating: Cat_Dog_data/train/dog/dog.3992.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3992.jpg \n inflating: Cat_Dog_data/train/dog/dog.9529.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9529.jpg \n inflating: Cat_Dog_data/train/dog/dog.1175.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1175.jpg \n inflating: Cat_Dog_data/train/dog/dog.7504.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7504.jpg \n inflating: Cat_Dog_data/train/dog/dog.8637.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8637.jpg \n inflating: Cat_Dog_data/train/dog/dog.11724.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11724.jpg \n inflating: Cat_Dog_data/train/dog/dog.153.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.153.jpg \n inflating: Cat_Dog_data/train/dog/dog.5313.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5313.jpg \n inflating: Cat_Dog_data/train/dog/dog.5475.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5475.jpg \n inflating: Cat_Dog_data/train/dog/dog.3004.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3004.jpg \n inflating: Cat_Dog_data/train/dog/dog.635.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.635.jpg \n inflating: Cat_Dog_data/train/dog/dog.11042.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11042.jpg \n inflating: Cat_Dog_data/train/dog/dog.1613.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1613.jpg \n inflating: Cat_Dog_data/train/dog/dog.7276.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7276.jpg \n inflating: Cat_Dog_data/train/dog/dog.8145.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8145.jpg \n inflating: Cat_Dog_data/train/dog/dog.1607.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1607.jpg \n inflating: Cat_Dog_data/train/dog/dog.6168.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6168.jpg \n inflating: Cat_Dog_data/train/dog/dog.5461.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5461.jpg \n inflating: Cat_Dog_data/train/dog/dog.621.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.621.jpg \n inflating: Cat_Dog_data/train/dog/dog.3010.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3010.jpg \n inflating: Cat_Dog_data/train/dog/dog.11056.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11056.jpg \n inflating: Cat_Dog_data/train/dog/dog.4019.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4019.jpg \n inflating: Cat_Dog_data/train/dog/dog.11730.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11730.jpg \n inflating: Cat_Dog_data/train/dog/dog.147.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.147.jpg \n inflating: Cat_Dog_data/train/dog/dog.3776.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3776.jpg \n inflating: Cat_Dog_data/train/dog/dog.2468.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2468.jpg \n inflating: Cat_Dog_data/train/dog/dog.5307.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5307.jpg \n inflating: Cat_Dog_data/train/dog/dog.1161.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1161.jpg \n inflating: Cat_Dog_data/train/dog/dog.12239.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12239.jpg \n inflating: Cat_Dog_data/train/dog/dog.7510.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7510.jpg \n inflating: Cat_Dog_data/train/dog/dog.8623.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8623.jpg \n inflating: Cat_Dog_data/train/dog/dog.6381.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6381.jpg \n inflating: Cat_Dog_data/train/dog/dog.5688.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5688.jpg \n inflating: Cat_Dog_data/train/dog/dog.4596.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4596.jpg \n inflating: Cat_Dog_data/train/dog/dog.5850.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5850.jpg \n inflating: Cat_Dog_data/train/dog/dog.2859.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2859.jpg \n inflating: Cat_Dog_data/train/dog/dog.2681.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2681.jpg \n inflating: Cat_Dog_data/train/dog/dog.7921.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7921.jpg \n inflating: Cat_Dog_data/train/dog/dog.1388.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1388.jpg \n inflating: Cat_Dog_data/train/dog/dog.7935.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7935.jpg \n inflating: Cat_Dog_data/train/dog/dog.9918.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9918.jpg \n inflating: Cat_Dog_data/train/dog/dog.2695.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2695.jpg \n inflating: Cat_Dog_data/train/dog/dog.4582.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4582.jpg \n inflating: Cat_Dog_data/train/dog/dog.5844.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5844.jpg \n inflating: Cat_Dog_data/train/dog/dog.6395.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6395.jpg \n inflating: Cat_Dog_data/train/dog/dog.11283.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11283.jpg \n inflating: Cat_Dog_data/train/dog/dog.8390.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8390.jpg \n inflating: Cat_Dog_data/train/dog/dog.9930.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9930.jpg \n inflating: Cat_Dog_data/train/dog/dog.10823.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10823.jpg \n inflating: Cat_Dog_data/train/dog/dog.2865.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2865.jpg \n inflating: Cat_Dog_data/train/dog/dog.10837.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10837.jpg \n inflating: Cat_Dog_data/train/dog/dog.386.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.386.jpg \n inflating: Cat_Dog_data/train/dog/dog.7909.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7909.jpg \n inflating: Cat_Dog_data/train/dog/dog.9924.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9924.jpg \n inflating: Cat_Dog_data/train/dog/dog.8384.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8384.jpg \n inflating: Cat_Dog_data/train/dog/dog.10189.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10189.jpg \n inflating: Cat_Dog_data/train/dog/dog.11297.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11297.jpg \n inflating: Cat_Dog_data/train/dog/dog.5878.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5878.jpg \n inflating: Cat_Dog_data/train/dog/dog.4555.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4555.jpg \n inflating: Cat_Dog_data/train/dog/dog.5893.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5893.jpg \n inflating: Cat_Dog_data/train/dog/dog.2124.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2124.jpg \n inflating: Cat_Dog_data/train/dog/dog.10162.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10162.jpg \n inflating: Cat_Dog_data/train/dog/dog.6342.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6342.jpg \n inflating: Cat_Dog_data/train/dog/dog.9071.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9071.jpg \n inflating: Cat_Dog_data/train/dog/dog.12013.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12013.jpg \n inflating: Cat_Dog_data/train/dog/dog.8409.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8409.jpg \n inflating: Cat_Dog_data/train/dog/dog.6424.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6424.jpg \n inflating: Cat_Dog_data/train/dog/dog.9717.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9717.jpg \n inflating: Cat_Dog_data/train/dog/dog.2642.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2642.jpg \n inflating: Cat_Dog_data/train/dog/dog.5139.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5139.jpg \n inflating: Cat_Dog_data/train/dog/dog.10610.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10610.jpg \n inflating: Cat_Dog_data/train/dog/dog.2656.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2656.jpg \n inflating: Cat_Dog_data/train/dog/dog.379.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.379.jpg \n inflating: Cat_Dog_data/train/dog/dog.4227.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4227.jpg \n inflating: Cat_Dog_data/train/dog/dog.12007.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12007.jpg \n inflating: Cat_Dog_data/train/dog/dog.9703.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9703.jpg \n inflating: Cat_Dog_data/train/dog/dog.6356.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6356.jpg \n inflating: Cat_Dog_data/train/dog/dog.9065.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9065.jpg \n inflating: Cat_Dog_data/train/dog/dog.1439.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1439.jpg \n inflating: Cat_Dog_data/train/dog/dog.7048.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7048.jpg \n inflating: Cat_Dog_data/train/dog/dog.4541.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4541.jpg \n inflating: Cat_Dog_data/train/dog/dog.11268.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11268.jpg \n inflating: Cat_Dog_data/train/dog/dog.2130.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2130.jpg \n inflating: Cat_Dog_data/train/dog/dog.10176.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10176.jpg \n inflating: Cat_Dog_data/train/dog/dog.1411.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1411.jpg \n inflating: Cat_Dog_data/train/dog/dog.8353.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8353.jpg \n inflating: Cat_Dog_data/train/dog/dog.7060.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7060.jpg \n inflating: Cat_Dog_data/train/dog/dog.11240.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11240.jpg \n inflating: Cat_Dog_data/train/dog/dog.4569.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4569.jpg \n inflating: Cat_Dog_data/train/dog/dog.3206.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3206.jpg \n inflating: Cat_Dog_data/train/dog/dog.437.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.437.jpg \n inflating: Cat_Dog_data/train/dog/dog.2118.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2118.jpg \n inflating: Cat_Dog_data/train/dog/dog.5677.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5677.jpg \n inflating: Cat_Dog_data/train/dog/dog.10638.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10638.jpg \n inflating: Cat_Dog_data/train/dog/dog.5111.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5111.jpg \n inflating: Cat_Dog_data/train/dog/dog.351.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.351.jpg \n inflating: Cat_Dog_data/train/dog/dog.11526.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11526.jpg \n inflating: Cat_Dog_data/train/dog/dog.8435.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8435.jpg \n inflating: Cat_Dog_data/train/dog/dog.7706.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7706.jpg \n inflating: Cat_Dog_data/train/dog/dog.1377.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1377.jpg \n inflating: Cat_Dog_data/train/dog/dog.6418.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6418.jpg \n inflating: Cat_Dog_data/train/dog/dog.8421.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8421.jpg \n inflating: Cat_Dog_data/train/dog/dog.7712.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7712.jpg \n inflating: Cat_Dog_data/train/dog/dog.1363.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1363.jpg \n inflating: Cat_Dog_data/train/dog/dog.5105.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5105.jpg \n inflating: Cat_Dog_data/train/dog/dog.345.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.345.jpg \n inflating: Cat_Dog_data/train/dog/dog.3574.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3574.jpg \n inflating: Cat_Dog_data/train/dog/dog.11532.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11532.jpg \n inflating: Cat_Dog_data/train/dog/dog.11254.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11254.jpg \n inflating: Cat_Dog_data/train/dog/dog.423.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.423.jpg \n inflating: Cat_Dog_data/train/dog/dog.5663.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5663.jpg \n inflating: Cat_Dog_data/train/dog/dog.1405.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1405.jpg \n inflating: Cat_Dog_data/train/dog/dog.8347.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8347.jpg \n inflating: Cat_Dog_data/train/dog/dog.7074.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7074.jpg \n inflating: Cat_Dog_data/train/dog/dog.5924.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5924.jpg \n inflating: Cat_Dog_data/train/dog/dog.2093.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2093.jpg \n inflating: Cat_Dog_data/train/dog/dog.9878.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9878.jpg \n inflating: Cat_Dog_data/train/dog/dog.6593.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6593.jpg \n inflating: Cat_Dog_data/train/dog/dog.7855.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7855.jpg \n inflating: Cat_Dog_data/train/dog/dog.7699.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7699.jpg \n inflating: Cat_Dog_data/train/dog/dog.7841.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7841.jpg \n inflating: Cat_Dog_data/train/dog/dog.2939.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2939.jpg \n inflating: Cat_Dog_data/train/dog/dog.4390.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4390.jpg \n inflating: Cat_Dog_data/train/dog/dog.3399.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3399.jpg \n inflating: Cat_Dog_data/train/dog/dog.5930.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5930.jpg \n inflating: Cat_Dog_data/train/dog/dog.2087.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2087.jpg \n inflating: Cat_Dog_data/train/dog/dog.5918.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5918.jpg \n inflating: Cat_Dog_data/train/dog/dog.580.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.580.jpg \n inflating: Cat_Dog_data/train/dog/dog.9844.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9844.jpg \n inflating: Cat_Dog_data/train/dog/dog.12198.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12198.jpg \n inflating: Cat_Dog_data/train/dog/dog.7869.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7869.jpg \n inflating: Cat_Dog_data/train/dog/dog.11491.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11491.jpg \n inflating: Cat_Dog_data/train/dog/dog.2911.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2911.jpg \n inflating: Cat_Dog_data/train/dog/dog.10957.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10957.jpg \n inflating: Cat_Dog_data/train/dog/dog.11485.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11485.jpg \n inflating: Cat_Dog_data/train/dog/dog.2905.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2905.jpg \n inflating: Cat_Dog_data/train/dog/dog.10943.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10943.jpg \n inflating: Cat_Dog_data/train/dog/dog.9850.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9850.jpg \n inflating: Cat_Dog_data/train/dog/dog.8596.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8596.jpg \n inflating: Cat_Dog_data/train/dog/dog.9688.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9688.jpg \n inflating: Cat_Dog_data/train/dog/dog.594.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.594.jpg \n inflating: Cat_Dog_data/train/dog/dog.10016.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10016.jpg \n inflating: Cat_Dog_data/train/dog/dog.2050.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2050.jpg \n inflating: Cat_Dog_data/train/dog/dog.4421.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4421.jpg \n inflating: Cat_Dog_data/train/dog/dog.11308.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11308.jpg \n inflating: Cat_Dog_data/train/dog/dog.7128.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7128.jpg \n inflating: Cat_Dog_data/train/dog/dog.1559.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1559.jpg \n inflating: Cat_Dog_data/train/dog/dog.6236.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6236.jpg \n inflating: Cat_Dog_data/train/dog/dog.6550.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6550.jpg \n inflating: Cat_Dog_data/train/dog/dog.9663.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9663.jpg \n inflating: Cat_Dog_data/train/dog/dog.7896.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7896.jpg \n inflating: Cat_Dog_data/train/dog/dog.12167.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12167.jpg \n inflating: Cat_Dog_data/train/dog/dog.4347.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4347.jpg \n inflating: Cat_Dog_data/train/dog/dog.219.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.219.jpg \n inflating: Cat_Dog_data/train/dog/dog.3428.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3428.jpg \n inflating: Cat_Dog_data/train/dog/dog.2736.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2736.jpg \n inflating: Cat_Dog_data/train/dog/dog.5059.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5059.jpg \n inflating: Cat_Dog_data/train/dog/dog.4353.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4353.jpg \n inflating: Cat_Dog_data/train/dog/dog.10764.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10764.jpg \n inflating: Cat_Dog_data/train/dog/dog.6544.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6544.jpg \n inflating: Cat_Dog_data/train/dog/dog.9677.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9677.jpg \n inflating: Cat_Dog_data/train/dog/dog.7882.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7882.jpg \n inflating: Cat_Dog_data/train/dog/dog.12173.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12173.jpg \n inflating: Cat_Dog_data/train/dog/dog.8569.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8569.jpg \n inflating: Cat_Dog_data/train/dog/dog.6222.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6222.jpg \n inflating: Cat_Dog_data/train/dog/dog.2044.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2044.jpg \n inflating: Cat_Dog_data/train/dog/dog.4435.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4435.jpg \n inflating: Cat_Dog_data/train/dog/dog.8227.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8227.jpg \n inflating: Cat_Dog_data/train/dog/dog.7114.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7114.jpg \n inflating: Cat_Dog_data/train/dog/dog.1565.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1565.jpg \n inflating: Cat_Dog_data/train/dog/dog.9139.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9139.jpg \n inflating: Cat_Dog_data/train/dog/dog.5703.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5703.jpg \n inflating: Cat_Dog_data/train/dog/dog.543.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.543.jpg \n inflating: Cat_Dog_data/train/dog/dog.3372.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3372.jpg \n inflating: Cat_Dog_data/train/dog/dog.11334.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11334.jpg \n inflating: Cat_Dog_data/train/dog/dog.10994.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10994.jpg \n inflating: Cat_Dog_data/train/dog/dog.3414.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3414.jpg \n inflating: Cat_Dog_data/train/dog/dog.5065.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5065.jpg \n inflating: Cat_Dog_data/train/dog/dog.1203.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1203.jpg \n inflating: Cat_Dog_data/train/dog/dog.9887.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9887.jpg \n inflating: Cat_Dog_data/train/dog/dog.8541.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8541.jpg \n inflating: Cat_Dog_data/train/dog/dog.6578.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6578.jpg \n inflating: Cat_Dog_data/train/dog/dog.1217.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1217.jpg \n inflating: Cat_Dog_data/train/dog/dog.8555.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8555.jpg \n inflating: Cat_Dog_data/train/dog/dog.7666.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7666.jpg \n inflating: Cat_Dog_data/train/dog/dog.11446.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11446.jpg \n inflating: Cat_Dog_data/train/dog/dog.10980.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10980.jpg \n inflating: Cat_Dog_data/train/dog/dog.3400.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3400.jpg \n inflating: Cat_Dog_data/train/dog/dog.10758.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10758.jpg \n inflating: Cat_Dog_data/train/dog/dog.5717.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5717.jpg \n inflating: Cat_Dog_data/train/dog/dog.2078.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2078.jpg \n inflating: Cat_Dog_data/train/dog/dog.3366.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3366.jpg \n inflating: Cat_Dog_data/train/dog/dog.557.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.557.jpg \n inflating: Cat_Dog_data/train/dog/dog.4409.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4409.jpg \n inflating: Cat_Dog_data/train/dog/dog.8233.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8233.jpg \n inflating: Cat_Dog_data/train/dog/dog.7100.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7100.jpg \n inflating: Cat_Dog_data/train/dog/dog.1571.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1571.jpg \n inflating: Cat_Dog_data/train/dog/dog.8964.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8964.jpg \n inflating: Cat_Dog_data/train/dog/dog.6791.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6791.jpg \n inflating: Cat_Dog_data/train/dog/dog.6949.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6949.jpg \n inflating: Cat_Dog_data/train/dog/dog.4186.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4186.jpg \n inflating: Cat_Dog_data/train/dog/dog.3831.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3831.jpg \n inflating: Cat_Dog_data/train/dog/dog.11877.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11877.jpg \n inflating: Cat_Dog_data/train/dog/dog.4838.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4838.jpg \n inflating: Cat_Dog_data/train/dog/dog.2291.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2291.jpg \n inflating: Cat_Dog_data/train/dog/dog.966.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.966.jpg \n inflating: Cat_Dog_data/train/dog/dog.1940.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1940.jpg \n inflating: Cat_Dog_data/train/dog/dog.1798.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1798.jpg \n inflating: Cat_Dog_data/train/dog/dog.1954.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1954.jpg \n inflating: Cat_Dog_data/train/dog/dog.2285.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2285.jpg \n inflating: Cat_Dog_data/train/dog/dog.972.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.972.jpg \n inflating: Cat_Dog_data/train/dog/dog.4192.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4192.jpg \n inflating: Cat_Dog_data/train/dog/dog.3825.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3825.jpg \n inflating: Cat_Dog_data/train/dog/dog.11863.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11863.jpg \n inflating: Cat_Dog_data/train/dog/dog.8970.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8970.jpg \n inflating: Cat_Dog_data/train/dog/dog.6785.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6785.jpg \n inflating: Cat_Dog_data/train/dog/dog.11693.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11693.jpg \n inflating: Cat_Dog_data/train/dog/dog.8780.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8780.jpg \n inflating: Cat_Dog_data/train/dog/dog.6975.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6975.jpg \n inflating: Cat_Dog_data/train/dog/dog.4804.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4804.jpg \n inflating: Cat_Dog_data/train/dog/dog.782.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.782.jpg \n inflating: Cat_Dog_data/train/dog/dog.4810.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4810.jpg \n inflating: Cat_Dog_data/train/dog/dog.796.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.796.jpg \n inflating: Cat_Dog_data/train/dog/dog.1968.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1968.jpg \n inflating: Cat_Dog_data/train/dog/dog.11687.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11687.jpg \n inflating: Cat_Dog_data/train/dog/dog.3819.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3819.jpg \n inflating: Cat_Dog_data/train/dog/dog.10599.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10599.jpg \n inflating: Cat_Dog_data/train/dog/dog.10572.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10572.jpg \n inflating: Cat_Dog_data/train/dog/dog.2534.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2534.jpg \n inflating: Cat_Dog_data/train/dog/dog.4145.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4145.jpg \n inflating: Cat_Dog_data/train/dog/dog.12365.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12365.jpg \n inflating: Cat_Dog_data/train/dog/dog.9461.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9461.jpg \n inflating: Cat_Dog_data/train/dog/dog.6752.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6752.jpg \n inflating: Cat_Dog_data/train/dog/dog.6034.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6034.jpg \n inflating: Cat_Dog_data/train/dog/dog.8019.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8019.jpg \n inflating: Cat_Dog_data/train/dog/dog.1983.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1983.jpg \n inflating: Cat_Dog_data/train/dog/dog.12403.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12403.jpg \n inflating: Cat_Dog_data/train/dog/dog.4623.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4623.jpg \n inflating: Cat_Dog_data/train/dog/dog.2252.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2252.jpg \n inflating: Cat_Dog_data/train/dog/dog.10214.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10214.jpg \n inflating: Cat_Dog_data/train/dog/dog.4637.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4637.jpg \n inflating: Cat_Dog_data/train/dog/dog.3158.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3158.jpg \n inflating: Cat_Dog_data/train/dog/dog.769.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.769.jpg \n inflating: Cat_Dog_data/train/dog/dog.2246.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2246.jpg \n inflating: Cat_Dog_data/train/dog/dog.10200.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10200.jpg \n inflating: Cat_Dog_data/train/dog/dog.5529.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5529.jpg \n inflating: Cat_Dog_data/train/dog/dog.6020.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6020.jpg \n inflating: Cat_Dog_data/train/dog/dog.1997.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1997.jpg \n inflating: Cat_Dog_data/train/dog/dog.12417.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12417.jpg \n inflating: Cat_Dog_data/train/dog/dog.12371.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12371.jpg \n inflating: Cat_Dog_data/train/dog/dog.1029.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1029.jpg \n inflating: Cat_Dog_data/train/dog/dog.6746.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6746.jpg \n inflating: Cat_Dog_data/train/dog/dog.10566.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10566.jpg \n inflating: Cat_Dog_data/train/dog/dog.2520.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2520.jpg \n inflating: Cat_Dog_data/train/dog/dog.11678.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11678.jpg \n inflating: Cat_Dog_data/train/dog/dog.4151.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4151.jpg \n inflating: Cat_Dog_data/train/dog/dog.12359.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12359.jpg \n inflating: Cat_Dog_data/train/dog/dog.7470.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7470.jpg \n inflating: Cat_Dog_data/train/dog/dog.5267.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5267.jpg \n inflating: Cat_Dog_data/train/dog/dog.2508.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2508.jpg \n inflating: Cat_Dog_data/train/dog/dog.11888.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11888.jpg \n inflating: Cat_Dog_data/train/dog/dog.3616.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3616.jpg \n inflating: Cat_Dog_data/train/dog/dog.4179.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4179.jpg \n inflating: Cat_Dog_data/train/dog/dog.11650.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11650.jpg \n inflating: Cat_Dog_data/train/dog/dog.11136.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11136.jpg \n inflating: Cat_Dog_data/train/dog/dog.741.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.741.jpg \n inflating: Cat_Dog_data/train/dog/dog.3170.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3170.jpg \n inflating: Cat_Dog_data/train/dog/dog.999.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.999.jpg \n inflating: Cat_Dog_data/train/dog/dog.10228.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10228.jpg \n inflating: Cat_Dog_data/train/dog/dog.6008.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6008.jpg \n inflating: Cat_Dog_data/train/dog/dog.1767.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1767.jpg \n inflating: Cat_Dog_data/train/dog/dog.8025.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8025.jpg \n inflating: Cat_Dog_data/train/dog/dog.7302.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7302.jpg \n inflating: Cat_Dog_data/train/dog/dog.8031.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8031.jpg \n inflating: Cat_Dog_data/train/dog/dog.11122.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11122.jpg \n inflating: Cat_Dog_data/train/dog/dog.3164.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3164.jpg \n inflating: Cat_Dog_data/train/dog/dog.755.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.755.jpg \n inflating: Cat_Dog_data/train/dog/dog.5515.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5515.jpg \n inflating: Cat_Dog_data/train/dog/dog.5273.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5273.jpg \n inflating: Cat_Dog_data/train/dog/dog.7464.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7464.jpg \n inflating: Cat_Dog_data/train/dog/dog.8757.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8757.jpg \n inflating: Cat_Dog_data/train/dog/dog.1015.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1015.jpg \n inflating: Cat_Dog_data/train/dog/dog.9449.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9449.jpg \n inflating: Cat_Dog_data/train/dog/dog.7314.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7314.jpg \n inflating: Cat_Dog_data/train/dog/dog.8027.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8027.jpg \n inflating: Cat_Dog_data/train/dog/dog.1765.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1765.jpg \n inflating: Cat_Dog_data/train/dog/dog.9339.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9339.jpg \n inflating: Cat_Dog_data/train/dog/dog.5503.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5503.jpg \n inflating: Cat_Dog_data/train/dog/dog.3172.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3172.jpg \n inflating: Cat_Dog_data/train/dog/dog.743.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.743.jpg \n inflating: Cat_Dog_data/train/dog/dog.11134.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11134.jpg \n inflating: Cat_Dog_data/train/dog/dog.11652.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11652.jpg \n inflating: Cat_Dog_data/train/dog/dog.3614.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3614.jpg \n inflating: Cat_Dog_data/train/dog/dog.5265.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5265.jpg \n inflating: Cat_Dog_data/train/dog/dog.1003.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1003.jpg \n inflating: Cat_Dog_data/train/dog/dog.8999.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8999.jpg \n inflating: Cat_Dog_data/train/dog/dog.7472.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7472.jpg \n inflating: Cat_Dog_data/train/dog/dog.8741.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8741.jpg \n inflating: Cat_Dog_data/train/dog/dog.6778.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6778.jpg \n inflating: Cat_Dog_data/train/dog/dog.7466.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7466.jpg \n inflating: Cat_Dog_data/train/dog/dog.8755.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8755.jpg \n inflating: Cat_Dog_data/train/dog/dog.10558.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10558.jpg \n inflating: Cat_Dog_data/train/dog/dog.5271.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5271.jpg \n inflating: Cat_Dog_data/train/dog/dog.5517.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5517.jpg \n inflating: Cat_Dog_data/train/dog/dog.2278.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2278.jpg \n inflating: Cat_Dog_data/train/dog/dog.757.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.757.jpg \n inflating: Cat_Dog_data/train/dog/dog.3166.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3166.jpg \n inflating: Cat_Dog_data/train/dog/dog.11120.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11120.jpg \n inflating: Cat_Dog_data/train/dog/dog.4609.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4609.jpg \n inflating: Cat_Dog_data/train/dog/dog.7300.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7300.jpg \n inflating: Cat_Dog_data/train/dog/dog.12429.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12429.jpg \n inflating: Cat_Dog_data/train/dog/dog.8033.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8033.jpg \n inflating: Cat_Dog_data/train/dog/dog.1771.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1771.jpg \n inflating: Cat_Dog_data/train/dog/dog.2250.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2250.jpg \n inflating: Cat_Dog_data/train/dog/dog.4621.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4621.jpg \n inflating: Cat_Dog_data/train/dog/dog.11108.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11108.jpg \n inflating: Cat_Dog_data/train/dog/dog.1981.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1981.jpg \n inflating: Cat_Dog_data/train/dog/dog.12401.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12401.jpg \n inflating: Cat_Dog_data/train/dog/dog.7328.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7328.jpg \n inflating: Cat_Dog_data/train/dog/dog.1759.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1759.jpg \n inflating: Cat_Dog_data/train/dog/dog.9305.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9305.jpg \n inflating: Cat_Dog_data/train/dog/dog.6036.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6036.jpg \n inflating: Cat_Dog_data/train/dog/dog.9463.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9463.jpg \n inflating: Cat_Dog_data/train/dog/dog.6750.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6750.jpg \n inflating: Cat_Dog_data/train/dog/dog.6988.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6988.jpg \n inflating: Cat_Dog_data/train/dog/dog.12367.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12367.jpg \n inflating: Cat_Dog_data/train/dog/dog.4147.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4147.jpg \n inflating: Cat_Dog_data/train/dog/dog.3628.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3628.jpg \n inflating: Cat_Dog_data/train/dog/dog.2536.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2536.jpg \n inflating: Cat_Dog_data/train/dog/dog.5259.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5259.jpg \n inflating: Cat_Dog_data/train/dog/dog.10570.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10570.jpg \n inflating: Cat_Dog_data/train/dog/dog.4153.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4153.jpg \n inflating: Cat_Dog_data/train/dog/dog.2522.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2522.jpg \n inflating: Cat_Dog_data/train/dog/dog.10564.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10564.jpg \n inflating: Cat_Dog_data/train/dog/dog.9477.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9477.jpg \n inflating: Cat_Dog_data/train/dog/dog.6744.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6744.jpg \n inflating: Cat_Dog_data/train/dog/dog.8769.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8769.jpg \n inflating: Cat_Dog_data/train/dog/dog.12373.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12373.jpg \n inflating: Cat_Dog_data/train/dog/dog.12415.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12415.jpg \n inflating: Cat_Dog_data/train/dog/dog.9311.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9311.jpg \n inflating: Cat_Dog_data/train/dog/dog.6022.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6022.jpg \n inflating: Cat_Dog_data/train/dog/dog.10202.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10202.jpg \n inflating: Cat_Dog_data/train/dog/dog.2244.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2244.jpg \n inflating: Cat_Dog_data/train/dog/dog.4635.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4635.jpg \n inflating: Cat_Dog_data/train/dog/dog.780.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.780.jpg \n inflating: Cat_Dog_data/train/dog/dog.958.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.958.jpg \n inflating: Cat_Dog_data/train/dog/dog.4806.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4806.jpg \n inflating: Cat_Dog_data/train/dog/dog.6977.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6977.jpg \n inflating: Cat_Dog_data/train/dog/dog.12398.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12398.jpg \n inflating: Cat_Dog_data/train/dog/dog.8782.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8782.jpg \n inflating: Cat_Dog_data/train/dog/dog.11849.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11849.jpg \n inflating: Cat_Dog_data/train/dog/dog.11691.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11691.jpg \n inflating: Cat_Dog_data/train/dog/dog.11685.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11685.jpg \n inflating: Cat_Dog_data/train/dog/dog.6963.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6963.jpg \n inflating: Cat_Dog_data/train/dog/dog.8796.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8796.jpg \n inflating: Cat_Dog_data/train/dog/dog.9488.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9488.jpg \n inflating: Cat_Dog_data/train/dog/dog.4812.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4812.jpg \n inflating: Cat_Dog_data/train/dog/dog.2293.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2293.jpg \n inflating: Cat_Dog_data/train/dog/dog.11875.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11875.jpg \n inflating: Cat_Dog_data/train/dog/dog.3833.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3833.jpg \n inflating: Cat_Dog_data/train/dog/dog.4184.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4184.jpg \n inflating: Cat_Dog_data/train/dog/dog.6793.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6793.jpg \n inflating: Cat_Dog_data/train/dog/dog.8966.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8966.jpg \n inflating: Cat_Dog_data/train/dog/dog.7499.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7499.jpg \n inflating: Cat_Dog_data/train/dog/dog.6787.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6787.jpg \n inflating: Cat_Dog_data/train/dog/dog.8972.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8972.jpg \n inflating: Cat_Dog_data/train/dog/dog.3827.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3827.jpg \n inflating: Cat_Dog_data/train/dog/dog.3199.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3199.jpg \n inflating: Cat_Dog_data/train/dog/dog.970.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.970.jpg \n inflating: Cat_Dog_data/train/dog/dog.2287.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2287.jpg \n inflating: Cat_Dog_data/train/dog/dog.1956.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1956.jpg \n inflating: Cat_Dog_data/train/dog/dog.8543.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8543.jpg \n inflating: Cat_Dog_data/train/dog/dog.12159.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12159.jpg \n inflating: Cat_Dog_data/train/dog/dog.7670.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7670.jpg \n inflating: Cat_Dog_data/train/dog/dog.9885.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9885.jpg \n inflating: Cat_Dog_data/train/dog/dog.1201.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1201.jpg \n inflating: Cat_Dog_data/train/dog/dog.5067.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5067.jpg \n inflating: Cat_Dog_data/train/dog/dog.2708.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2708.jpg \n inflating: Cat_Dog_data/train/dog/dog.10996.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10996.jpg \n inflating: Cat_Dog_data/train/dog/dog.227.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.227.jpg \n inflating: Cat_Dog_data/train/dog/dog.4379.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4379.jpg \n inflating: Cat_Dog_data/train/dog/dog.11336.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11336.jpg \n inflating: Cat_Dog_data/train/dog/dog.3370.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3370.jpg \n inflating: Cat_Dog_data/train/dog/dog.541.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.541.jpg \n inflating: Cat_Dog_data/train/dog/dog.5701.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5701.jpg \n inflating: Cat_Dog_data/train/dog/dog.10028.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10028.jpg \n inflating: Cat_Dog_data/train/dog/dog.6208.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6208.jpg \n inflating: Cat_Dog_data/train/dog/dog.1567.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1567.jpg \n inflating: Cat_Dog_data/train/dog/dog.8225.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8225.jpg \n inflating: Cat_Dog_data/train/dog/dog.7116.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7116.jpg \n inflating: Cat_Dog_data/train/dog/dog.7102.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7102.jpg \n inflating: Cat_Dog_data/train/dog/dog.11322.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11322.jpg \n inflating: Cat_Dog_data/train/dog/dog.3364.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3364.jpg \n inflating: Cat_Dog_data/train/dog/dog.5715.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5715.jpg \n inflating: Cat_Dog_data/train/dog/dog.5073.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5073.jpg \n inflating: Cat_Dog_data/train/dog/dog.10982.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10982.jpg \n inflating: Cat_Dog_data/train/dog/dog.233.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.233.jpg \n inflating: Cat_Dog_data/train/dog/dog.3402.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3402.jpg \n inflating: Cat_Dog_data/train/dog/dog.11444.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11444.jpg \n inflating: Cat_Dog_data/train/dog/dog.8557.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8557.jpg \n inflating: Cat_Dog_data/train/dog/dog.7664.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7664.jpg \n inflating: Cat_Dog_data/train/dog/dog.9891.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9891.jpg \n inflating: Cat_Dog_data/train/dog/dog.9649.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9649.jpg \n inflating: Cat_Dog_data/train/dog/dog.10772.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10772.jpg \n inflating: Cat_Dog_data/train/dog/dog.2734.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2734.jpg \n inflating: Cat_Dog_data/train/dog/dog.4345.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4345.jpg \n inflating: Cat_Dog_data/train/dog/dog.12165.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12165.jpg \n inflating: Cat_Dog_data/train/dog/dog.7894.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7894.jpg \n inflating: Cat_Dog_data/train/dog/dog.6552.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6552.jpg \n inflating: Cat_Dog_data/train/dog/dog.9661.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9661.jpg \n inflating: Cat_Dog_data/train/dog/dog.6234.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6234.jpg \n inflating: Cat_Dog_data/train/dog/dog.9107.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9107.jpg \n inflating: Cat_Dog_data/train/dog/dog.8219.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8219.jpg \n inflating: Cat_Dog_data/train/dog/dog.4423.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4423.jpg \n inflating: Cat_Dog_data/train/dog/dog.2052.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2052.jpg \n inflating: Cat_Dog_data/train/dog/dog.10014.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10014.jpg \n inflating: Cat_Dog_data/train/dog/dog.4437.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4437.jpg \n inflating: Cat_Dog_data/train/dog/dog.2046.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2046.jpg \n inflating: Cat_Dog_data/train/dog/dog.10000.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10000.jpg \n inflating: Cat_Dog_data/train/dog/dog.5729.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5729.jpg \n inflating: Cat_Dog_data/train/dog/dog.6220.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6220.jpg \n inflating: Cat_Dog_data/train/dog/dog.9113.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9113.jpg \n inflating: Cat_Dog_data/train/dog/dog.7658.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7658.jpg \n inflating: Cat_Dog_data/train/dog/dog.12171.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12171.jpg \n inflating: Cat_Dog_data/train/dog/dog.7880.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7880.jpg \n inflating: Cat_Dog_data/train/dog/dog.6546.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6546.jpg \n inflating: Cat_Dog_data/train/dog/dog.9675.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9675.jpg \n inflating: Cat_Dog_data/train/dog/dog.10766.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10766.jpg \n inflating: Cat_Dog_data/train/dog/dog.2720.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2720.jpg \n inflating: Cat_Dog_data/train/dog/dog.11478.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11478.jpg \n inflating: Cat_Dog_data/train/dog/dog.10955.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10955.jpg \n inflating: Cat_Dog_data/train/dog/dog.2913.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2913.jpg \n inflating: Cat_Dog_data/train/dog/dog.8580.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8580.jpg \n inflating: Cat_Dog_data/train/dog/dog.9846.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9846.jpg \n inflating: Cat_Dog_data/train/dog/dog.582.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.582.jpg \n inflating: Cat_Dog_data/train/dog/dog.596.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.596.jpg \n inflating: Cat_Dog_data/train/dog/dog.8594.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8594.jpg \n inflating: Cat_Dog_data/train/dog/dog.9852.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9852.jpg \n inflating: Cat_Dog_data/train/dog/dog.10941.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10941.jpg \n inflating: Cat_Dog_data/train/dog/dog.11487.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11487.jpg \n inflating: Cat_Dog_data/train/dog/dog.10799.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10799.jpg \n inflating: Cat_Dog_data/train/dog/dog.7857.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7857.jpg \n inflating: Cat_Dog_data/train/dog/dog.6591.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6591.jpg \n inflating: Cat_Dog_data/train/dog/dog.10969.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10969.jpg \n inflating: Cat_Dog_data/train/dog/dog.4386.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4386.jpg \n inflating: Cat_Dog_data/train/dog/dog.5098.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5098.jpg \n inflating: Cat_Dog_data/train/dog/dog.2091.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2091.jpg \n inflating: Cat_Dog_data/train/dog/dog.5926.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5926.jpg \n inflating: Cat_Dog_data/train/dog/dog.1598.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1598.jpg \n inflating: Cat_Dog_data/train/dog/dog.2085.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2085.jpg \n inflating: Cat_Dog_data/train/dog/dog.5932.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5932.jpg \n inflating: Cat_Dog_data/train/dog/dog.4392.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4392.jpg \n inflating: Cat_Dog_data/train/dog/dog.7843.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7843.jpg \n inflating: Cat_Dog_data/train/dog/dog.9729.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9729.jpg \n inflating: Cat_Dog_data/train/dog/dog.1375.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1375.jpg \n inflating: Cat_Dog_data/train/dog/dog.8437.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8437.jpg \n inflating: Cat_Dog_data/train/dog/dog.7704.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7704.jpg \n inflating: Cat_Dog_data/train/dog/dog.11524.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11524.jpg \n inflating: Cat_Dog_data/train/dog/dog.353.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.353.jpg \n inflating: Cat_Dog_data/train/dog/dog.3562.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3562.jpg \n inflating: Cat_Dog_data/train/dog/dog.5113.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5113.jpg \n inflating: Cat_Dog_data/train/dog/dog.5675.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5675.jpg \n inflating: Cat_Dog_data/train/dog/dog.435.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.435.jpg \n inflating: Cat_Dog_data/train/dog/dog.3204.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3204.jpg \n inflating: Cat_Dog_data/train/dog/dog.11242.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11242.jpg \n inflating: Cat_Dog_data/train/dog/dog.7062.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7062.jpg \n inflating: Cat_Dog_data/train/dog/dog.1413.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1413.jpg \n inflating: Cat_Dog_data/train/dog/dog.8345.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8345.jpg \n inflating: Cat_Dog_data/train/dog/dog.7076.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7076.jpg \n inflating: Cat_Dog_data/train/dog/dog.1407.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1407.jpg \n inflating: Cat_Dog_data/train/dog/dog.6368.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6368.jpg \n inflating: Cat_Dog_data/train/dog/dog.10148.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10148.jpg \n inflating: Cat_Dog_data/train/dog/dog.3210.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3210.jpg \n inflating: Cat_Dog_data/train/dog/dog.421.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.421.jpg \n inflating: Cat_Dog_data/train/dog/dog.11256.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11256.jpg \n inflating: Cat_Dog_data/train/dog/dog.4219.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4219.jpg \n inflating: Cat_Dog_data/train/dog/dog.11530.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11530.jpg \n inflating: Cat_Dog_data/train/dog/dog.3576.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3576.jpg \n inflating: Cat_Dog_data/train/dog/dog.347.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.347.jpg \n inflating: Cat_Dog_data/train/dog/dog.2668.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2668.jpg \n inflating: Cat_Dog_data/train/dog/dog.5107.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5107.jpg \n inflating: Cat_Dog_data/train/dog/dog.1361.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1361.jpg \n inflating: Cat_Dog_data/train/dog/dog.8423.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8423.jpg \n inflating: Cat_Dog_data/train/dog/dog.12039.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12039.jpg \n inflating: Cat_Dog_data/train/dog/dog.7710.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7710.jpg \n inflating: Cat_Dog_data/train/dog/dog.2898.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2898.jpg \n inflating: Cat_Dog_data/train/dog/dog.11518.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11518.jpg \n inflating: Cat_Dog_data/train/dog/dog.4231.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4231.jpg \n inflating: Cat_Dog_data/train/dog/dog.2640.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2640.jpg \n inflating: Cat_Dog_data/train/dog/dog.10606.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10606.jpg \n inflating: Cat_Dog_data/train/dog/dog.6426.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6426.jpg \n inflating: Cat_Dog_data/train/dog/dog.1349.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1349.jpg \n inflating: Cat_Dog_data/train/dog/dog.7738.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7738.jpg \n inflating: Cat_Dog_data/train/dog/dog.12011.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12011.jpg \n inflating: Cat_Dog_data/train/dog/dog.6340.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6340.jpg \n inflating: Cat_Dog_data/train/dog/dog.9073.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9073.jpg \n inflating: Cat_Dog_data/train/dog/dog.10160.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10160.jpg \n inflating: Cat_Dog_data/train/dog/dog.5649.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5649.jpg \n inflating: Cat_Dog_data/train/dog/dog.2126.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2126.jpg \n inflating: Cat_Dog_data/train/dog/dog.409.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.409.jpg \n inflating: Cat_Dog_data/train/dog/dog.5891.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5891.jpg \n inflating: Cat_Dog_data/train/dog/dog.10174.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10174.jpg \n inflating: Cat_Dog_data/train/dog/dog.2132.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2132.jpg \n inflating: Cat_Dog_data/train/dog/dog.5885.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5885.jpg \n inflating: Cat_Dog_data/train/dog/dog.4543.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4543.jpg \n inflating: Cat_Dog_data/train/dog/dog.8379.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8379.jpg \n inflating: Cat_Dog_data/train/dog/dog.6354.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6354.jpg \n inflating: Cat_Dog_data/train/dog/dog.9701.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9701.jpg \n inflating: Cat_Dog_data/train/dog/dog.12005.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12005.jpg \n inflating: Cat_Dog_data/train/dog/dog.4225.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4225.jpg \n inflating: Cat_Dog_data/train/dog/dog.2654.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2654.jpg \n inflating: Cat_Dog_data/train/dog/dog.2867.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2867.jpg \n inflating: Cat_Dog_data/train/dog/dog.10821.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10821.jpg \n inflating: Cat_Dog_data/train/dog/dog.390.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.390.jpg \n inflating: Cat_Dog_data/train/dog/dog.9932.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9932.jpg \n inflating: Cat_Dog_data/train/dog/dog.8392.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8392.jpg \n inflating: Cat_Dog_data/train/dog/dog.11281.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11281.jpg \n inflating: Cat_Dog_data/train/dog/dog.11295.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11295.jpg \n inflating: Cat_Dog_data/train/dog/dog.9098.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9098.jpg \n inflating: Cat_Dog_data/train/dog/dog.8386.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8386.jpg \n inflating: Cat_Dog_data/train/dog/dog.9926.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9926.jpg \n inflating: Cat_Dog_data/train/dog/dog.2873.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2873.jpg \n inflating: Cat_Dog_data/train/dog/dog.10835.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10835.jpg \n inflating: Cat_Dog_data/train/dog/dog.384.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.384.jpg \n inflating: Cat_Dog_data/train/dog/dog.7923.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7923.jpg \n inflating: Cat_Dog_data/train/dog/dog.2683.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2683.jpg \n inflating: Cat_Dog_data/train/dog/dog.5852.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5852.jpg \n inflating: Cat_Dog_data/train/dog/dog.4594.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4594.jpg \n inflating: Cat_Dog_data/train/dog/dog.6383.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6383.jpg \n inflating: Cat_Dog_data/train/dog/dog.6397.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6397.jpg \n inflating: Cat_Dog_data/train/dog/dog.7089.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7089.jpg \n inflating: Cat_Dog_data/train/dog/dog.5846.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5846.jpg \n inflating: Cat_Dog_data/train/dog/dog.2697.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2697.jpg \n inflating: Cat_Dog_data/train/dog/dog.3589.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3589.jpg \n inflating: Cat_Dog_data/train/dog/dog.10809.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10809.jpg \n inflating: Cat_Dog_data/train/dog/dog.7937.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7937.jpg \n inflating: Cat_Dog_data/train/dog/dog.1611.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1611.jpg \n inflating: Cat_Dog_data/train/dog/dog.7260.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7260.jpg \n inflating: Cat_Dog_data/train/dog/dog.8153.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8153.jpg \n inflating: Cat_Dog_data/train/dog/dog.11040.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11040.jpg \n inflating: Cat_Dog_data/train/dog/dog.4769.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4769.jpg \n inflating: Cat_Dog_data/train/dog/dog.637.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.637.jpg \n inflating: Cat_Dog_data/train/dog/dog.3006.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3006.jpg \n inflating: Cat_Dog_data/train/dog/dog.2318.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2318.jpg \n inflating: Cat_Dog_data/train/dog/dog.5477.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5477.jpg \n inflating: Cat_Dog_data/train/dog/dog.5311.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5311.jpg \n inflating: Cat_Dog_data/train/dog/dog.151.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.151.jpg \n inflating: Cat_Dog_data/train/dog/dog.3760.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3760.jpg \n inflating: Cat_Dog_data/train/dog/dog.11726.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11726.jpg \n inflating: Cat_Dog_data/train/dog/dog.7506.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7506.jpg \n inflating: Cat_Dog_data/train/dog/dog.8635.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8635.jpg \n inflating: Cat_Dog_data/train/dog/dog.1177.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1177.jpg \n inflating: Cat_Dog_data/train/dog/dog.6618.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6618.jpg \n inflating: Cat_Dog_data/train/dog/dog.7512.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7512.jpg \n inflating: Cat_Dog_data/train/dog/dog.8621.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8621.jpg \n inflating: Cat_Dog_data/train/dog/dog.5305.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5305.jpg \n inflating: Cat_Dog_data/train/dog/dog.3774.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3774.jpg \n inflating: Cat_Dog_data/train/dog/dog.145.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.145.jpg \n inflating: Cat_Dog_data/train/dog/dog.11732.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11732.jpg \n inflating: Cat_Dog_data/train/dog/dog.11054.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11054.jpg \n inflating: Cat_Dog_data/train/dog/dog.3012.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3012.jpg \n inflating: Cat_Dog_data/train/dog/dog.623.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.623.jpg \n inflating: Cat_Dog_data/train/dog/dog.5463.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5463.jpg \n inflating: Cat_Dog_data/train/dog/dog.9259.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9259.jpg \n inflating: Cat_Dog_data/train/dog/dog.1605.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1605.jpg \n inflating: Cat_Dog_data/train/dog/dog.7274.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7274.jpg \n inflating: Cat_Dog_data/train/dog/dog.28.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.28.jpg \n inflating: Cat_Dog_data/train/dog/dog.8147.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8147.jpg \n inflating: Cat_Dog_data/train/dog/dog.4755.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4755.jpg \n inflating: Cat_Dog_data/train/dog/dog.2324.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2324.jpg \n inflating: Cat_Dog_data/train/dog/dog.10362.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10362.jpg \n inflating: Cat_Dog_data/train/dog/dog.9271.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9271.jpg \n inflating: Cat_Dog_data/train/dog/dog.6142.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6142.jpg \n inflating: Cat_Dog_data/train/dog/dog.8609.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8609.jpg \n inflating: Cat_Dog_data/train/dog/dog.12213.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12213.jpg \n inflating: Cat_Dog_data/train/dog/dog.9517.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9517.jpg \n inflating: Cat_Dog_data/train/dog/dog.6624.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6624.jpg \n inflating: Cat_Dog_data/train/dog/dog.10404.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10404.jpg \n inflating: Cat_Dog_data/train/dog/dog.3984.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3984.jpg \n inflating: Cat_Dog_data/train/dog/dog.2442.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2442.jpg \n inflating: Cat_Dog_data/train/dog/dog.4033.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4033.jpg \n inflating: Cat_Dog_data/train/dog/dog.5339.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5339.jpg \n inflating: Cat_Dog_data/train/dog/dog.10410.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10410.jpg \n inflating: Cat_Dog_data/train/dog/dog.3990.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3990.jpg \n inflating: Cat_Dog_data/train/dog/dog.2456.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2456.jpg \n inflating: Cat_Dog_data/train/dog/dog.3748.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3748.jpg \n inflating: Cat_Dog_data/train/dog/dog.179.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.179.jpg \n inflating: Cat_Dog_data/train/dog/dog.4027.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4027.jpg \n inflating: Cat_Dog_data/train/dog/dog.12207.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12207.jpg \n inflating: Cat_Dog_data/train/dog/dog.9503.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9503.jpg \n inflating: Cat_Dog_data/train/dog/dog.6630.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6630.jpg \n inflating: Cat_Dog_data/train/dog/dog.9265.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9265.jpg \n inflating: Cat_Dog_data/train/dog/dog.6156.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6156.jpg \n inflating: Cat_Dog_data/train/dog/dog.1639.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1639.jpg \n inflating: Cat_Dog_data/train/dog/dog.7248.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7248.jpg \n inflating: Cat_Dog_data/train/dog/dog.14.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.14.jpg \n inflating: Cat_Dog_data/train/dog/dog.4741.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4741.jpg \n inflating: Cat_Dog_data/train/dog/dog.11068.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11068.jpg \n inflating: Cat_Dog_data/train/dog/dog.2330.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2330.jpg \n inflating: Cat_Dog_data/train/dog/dog.10376.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10376.jpg \n inflating: Cat_Dog_data/train/dog/dog.4972.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4972.jpg \n inflating: Cat_Dog_data/train/dog/dog.11083.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11083.jpg \n inflating: Cat_Dog_data/train/dog/dog.8190.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8190.jpg \n inflating: Cat_Dog_data/train/dog/dog.6803.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6803.jpg \n inflating: Cat_Dog_data/train/dog/dog.192.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.192.jpg \n inflating: Cat_Dog_data/train/dog/dog.186.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.186.jpg \n inflating: Cat_Dog_data/train/dog/dog.11929.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11929.jpg \n inflating: Cat_Dog_data/train/dog/dog.8184.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8184.jpg \n inflating: Cat_Dog_data/train/dog/dog.4966.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4966.jpg \n inflating: Cat_Dog_data/train/dog/dog.838.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.838.jpg \n inflating: Cat_Dog_data/train/dog/dog.10389.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10389.jpg \n inflating: Cat_Dog_data/train/dog/dog.11097.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11097.jpg \n inflating: Cat_Dog_data/train/dog/dog.1836.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1836.jpg \n inflating: Cat_Dog_data/train/dog/dog.6181.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6181.jpg \n inflating: Cat_Dog_data/train/dog/dog.5488.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5488.jpg \n inflating: Cat_Dog_data/train/dog/dog.810.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.810.jpg \n inflating: Cat_Dog_data/train/dog/dog.4796.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4796.jpg \n inflating: Cat_Dog_data/train/dog/dog.3947.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3947.jpg \n inflating: Cat_Dog_data/train/dog/dog.11901.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11901.jpg \n inflating: Cat_Dog_data/train/dog/dog.2481.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2481.jpg \n inflating: Cat_Dog_data/train/dog/dog.1188.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1188.jpg \n inflating: Cat_Dog_data/train/dog/dog.8812.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8812.jpg \n inflating: Cat_Dog_data/train/dog/dog.8806.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8806.jpg \n inflating: Cat_Dog_data/train/dog/dog.3953.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3953.jpg \n inflating: Cat_Dog_data/train/dog/dog.11915.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11915.jpg \n inflating: Cat_Dog_data/train/dog/dog.2495.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2495.jpg \n inflating: Cat_Dog_data/train/dog/dog.4782.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4782.jpg \n inflating: Cat_Dog_data/train/dog/dog.1822.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1822.jpg \n inflating: Cat_Dog_data/train/dog/dog.6195.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6195.jpg \n inflating: Cat_Dog_data/train/dog/dog.2494.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2494.jpg \n inflating: Cat_Dog_data/train/dog/dog.3952.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3952.jpg \n inflating: Cat_Dog_data/train/dog/dog.8807.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8807.jpg \n inflating: Cat_Dog_data/train/dog/dog.6194.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6194.jpg \n inflating: Cat_Dog_data/train/dog/dog.4783.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4783.jpg \n inflating: Cat_Dog_data/train/dog/dog.805.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.805.jpg \n inflating: Cat_Dog_data/train/dog/dog.4797.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4797.jpg \n inflating: Cat_Dog_data/train/dog/dog.811.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.811.jpg \n inflating: Cat_Dog_data/train/dog/dog.5489.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5489.jpg \n inflating: Cat_Dog_data/train/dog/dog.6180.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6180.jpg \n inflating: Cat_Dog_data/train/dog/dog.1837.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1837.jpg \n inflating: Cat_Dog_data/train/dog/dog.1189.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1189.jpg \n inflating: Cat_Dog_data/train/dog/dog.8813.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8813.jpg \n inflating: Cat_Dog_data/train/dog/dog.2480.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2480.jpg \n inflating: Cat_Dog_data/train/dog/dog.11900.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11900.jpg \n inflating: Cat_Dog_data/train/dog/dog.3946.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3946.jpg \n inflating: Cat_Dog_data/train/dog/dog.6816.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6816.jpg \n inflating: Cat_Dog_data/train/dog/dog.11928.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11928.jpg \n inflating: Cat_Dog_data/train/dog/dog.187.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.187.jpg \n inflating: Cat_Dog_data/train/dog/dog.11096.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11096.jpg \n inflating: Cat_Dog_data/train/dog/dog.839.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.839.jpg \n inflating: Cat_Dog_data/train/dog/dog.4967.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4967.jpg \n inflating: Cat_Dog_data/train/dog/dog.8185.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8185.jpg \n inflating: Cat_Dog_data/train/dog/dog.8191.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8191.jpg \n inflating: Cat_Dog_data/train/dog/dog.11082.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11082.jpg \n inflating: Cat_Dog_data/train/dog/dog.4973.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4973.jpg \n inflating: Cat_Dog_data/train/dog/dog.193.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.193.jpg \n inflating: Cat_Dog_data/train/dog/dog.6802.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6802.jpg \n inflating: Cat_Dog_data/train/dog/dog.6631.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6631.jpg \n inflating: Cat_Dog_data/train/dog/dog.9502.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9502.jpg \n inflating: Cat_Dog_data/train/dog/dog.12206.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12206.jpg \n inflating: Cat_Dog_data/train/dog/dog.178.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.178.jpg \n inflating: Cat_Dog_data/train/dog/dog.3749.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3749.jpg \n inflating: Cat_Dog_data/train/dog/dog.2457.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2457.jpg \n inflating: Cat_Dog_data/train/dog/dog.3991.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3991.jpg \n inflating: Cat_Dog_data/train/dog/dog.10411.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10411.jpg \n inflating: Cat_Dog_data/train/dog/dog.10377.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10377.jpg \n inflating: Cat_Dog_data/train/dog/dog.2331.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2331.jpg \n inflating: Cat_Dog_data/train/dog/dog.4998.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4998.jpg \n inflating: Cat_Dog_data/train/dog/dog.11069.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11069.jpg \n inflating: Cat_Dog_data/train/dog/dog.4740.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4740.jpg \n inflating: Cat_Dog_data/train/dog/dog.15.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.15.jpg \n inflating: Cat_Dog_data/train/dog/dog.7249.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7249.jpg \n inflating: Cat_Dog_data/train/dog/dog.6157.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6157.jpg \n inflating: Cat_Dog_data/train/dog/dog.9264.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9264.jpg \n inflating: Cat_Dog_data/train/dog/dog.6143.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6143.jpg \n inflating: Cat_Dog_data/train/dog/dog.9270.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9270.jpg \n inflating: Cat_Dog_data/train/dog/dog.10363.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10363.jpg \n inflating: Cat_Dog_data/train/dog/dog.2325.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2325.jpg \n inflating: Cat_Dog_data/train/dog/dog.4754.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4754.jpg \n inflating: Cat_Dog_data/train/dog/dog.4032.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4032.jpg \n inflating: Cat_Dog_data/train/dog/dog.2443.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2443.jpg \n inflating: Cat_Dog_data/train/dog/dog.3985.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3985.jpg \n inflating: Cat_Dog_data/train/dog/dog.10405.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10405.jpg \n inflating: Cat_Dog_data/train/dog/dog.9516.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9516.jpg \n inflating: Cat_Dog_data/train/dog/dog.12212.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12212.jpg \n inflating: Cat_Dog_data/train/dog/dog.8608.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8608.jpg \n inflating: Cat_Dog_data/train/dog/dog.11733.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11733.jpg \n inflating: Cat_Dog_data/train/dog/dog.144.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.144.jpg \n inflating: Cat_Dog_data/train/dog/dog.5304.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5304.jpg \n inflating: Cat_Dog_data/train/dog/dog.1162.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1162.jpg \n inflating: Cat_Dog_data/train/dog/dog.8620.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8620.jpg \n inflating: Cat_Dog_data/train/dog/dog.7513.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7513.jpg \n inflating: Cat_Dog_data/train/dog/dog.29.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.29.jpg \n inflating: Cat_Dog_data/train/dog/dog.7275.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7275.jpg \n inflating: Cat_Dog_data/train/dog/dog.1604.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1604.jpg \n inflating: Cat_Dog_data/train/dog/dog.9258.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9258.jpg \n inflating: Cat_Dog_data/train/dog/dog.5462.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5462.jpg \n inflating: Cat_Dog_data/train/dog/dog.622.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.622.jpg \n inflating: Cat_Dog_data/train/dog/dog.3013.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3013.jpg \n inflating: Cat_Dog_data/train/dog/dog.11055.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11055.jpg \n inflating: Cat_Dog_data/train/dog/dog.2319.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2319.jpg \n inflating: Cat_Dog_data/train/dog/dog.3007.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3007.jpg \n inflating: Cat_Dog_data/train/dog/dog.636.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.636.jpg \n inflating: Cat_Dog_data/train/dog/dog.4768.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4768.jpg \n inflating: Cat_Dog_data/train/dog/dog.11041.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11041.jpg \n inflating: Cat_Dog_data/train/dog/dog.8152.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8152.jpg \n inflating: Cat_Dog_data/train/dog/dog.7261.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7261.jpg \n inflating: Cat_Dog_data/train/dog/dog.1610.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1610.jpg \n inflating: Cat_Dog_data/train/dog/dog.1176.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1176.jpg \n inflating: Cat_Dog_data/train/dog/dog.8634.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8634.jpg \n inflating: Cat_Dog_data/train/dog/dog.7507.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7507.jpg \n inflating: Cat_Dog_data/train/dog/dog.11727.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11727.jpg \n inflating: Cat_Dog_data/train/dog/dog.3761.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3761.jpg \n inflating: Cat_Dog_data/train/dog/dog.5310.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5310.jpg \n inflating: Cat_Dog_data/train/dog/dog.10439.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10439.jpg \n inflating: Cat_Dog_data/train/dog/dog.4581.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4581.jpg \n inflating: Cat_Dog_data/train/dog/dog.5847.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5847.jpg \n inflating: Cat_Dog_data/train/dog/dog.7088.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7088.jpg \n inflating: Cat_Dog_data/train/dog/dog.6396.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6396.jpg \n inflating: Cat_Dog_data/train/dog/dog.7936.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7936.jpg \n inflating: Cat_Dog_data/train/dog/dog.10808.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10808.jpg \n inflating: Cat_Dog_data/train/dog/dog.3588.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3588.jpg \n inflating: Cat_Dog_data/train/dog/dog.2682.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2682.jpg \n inflating: Cat_Dog_data/train/dog/dog.7922.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7922.jpg \n inflating: Cat_Dog_data/train/dog/dog.6382.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6382.jpg \n inflating: Cat_Dog_data/train/dog/dog.4595.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4595.jpg \n inflating: Cat_Dog_data/train/dog/dog.5853.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5853.jpg \n inflating: Cat_Dog_data/train/dog/dog.8387.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8387.jpg \n inflating: Cat_Dog_data/train/dog/dog.9099.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9099.jpg \n inflating: Cat_Dog_data/train/dog/dog.11294.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11294.jpg \n inflating: Cat_Dog_data/train/dog/dog.385.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.385.jpg \n inflating: Cat_Dog_data/train/dog/dog.10834.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10834.jpg \n inflating: Cat_Dog_data/train/dog/dog.2872.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2872.jpg \n inflating: Cat_Dog_data/train/dog/dog.9927.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9927.jpg \n inflating: Cat_Dog_data/train/dog/dog.9933.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9933.jpg \n inflating: Cat_Dog_data/train/dog/dog.391.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.391.jpg \n inflating: Cat_Dog_data/train/dog/dog.10820.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10820.jpg \n inflating: Cat_Dog_data/train/dog/dog.2866.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2866.jpg \n inflating: Cat_Dog_data/train/dog/dog.11280.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11280.jpg \n inflating: Cat_Dog_data/train/dog/dog.8393.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8393.jpg \n inflating: Cat_Dog_data/train/dog/dog.9066.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9066.jpg \n inflating: Cat_Dog_data/train/dog/dog.6355.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6355.jpg \n inflating: Cat_Dog_data/train/dog/dog.8378.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8378.jpg \n inflating: Cat_Dog_data/train/dog/dog.4542.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4542.jpg \n inflating: Cat_Dog_data/train/dog/dog.5884.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5884.jpg \n inflating: Cat_Dog_data/train/dog/dog.2133.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2133.jpg \n inflating: Cat_Dog_data/train/dog/dog.10175.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10175.jpg \n inflating: Cat_Dog_data/train/dog/dog.10613.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10613.jpg \n inflating: Cat_Dog_data/train/dog/dog.2655.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2655.jpg \n inflating: Cat_Dog_data/train/dog/dog.4224.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4224.jpg \n inflating: Cat_Dog_data/train/dog/dog.12004.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12004.jpg \n inflating: Cat_Dog_data/train/dog/dog.9700.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9700.jpg \n inflating: Cat_Dog_data/train/dog/dog.6433.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6433.jpg \n inflating: Cat_Dog_data/train/dog/dog.12010.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12010.jpg \n inflating: Cat_Dog_data/train/dog/dog.7739.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7739.jpg \n inflating: Cat_Dog_data/train/dog/dog.9714.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9714.jpg \n inflating: Cat_Dog_data/train/dog/dog.6427.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6427.jpg \n inflating: Cat_Dog_data/train/dog/dog.10607.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10607.jpg \n inflating: Cat_Dog_data/train/dog/dog.2641.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2641.jpg \n inflating: Cat_Dog_data/train/dog/dog.4230.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4230.jpg \n inflating: Cat_Dog_data/train/dog/dog.11519.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11519.jpg \n inflating: Cat_Dog_data/train/dog/dog.2899.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2899.jpg \n inflating: Cat_Dog_data/train/dog/dog.4556.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4556.jpg \n inflating: Cat_Dog_data/train/dog/dog.3239.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3239.jpg \n inflating: Cat_Dog_data/train/dog/dog.408.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.408.jpg \n inflating: Cat_Dog_data/train/dog/dog.2127.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2127.jpg \n inflating: Cat_Dog_data/train/dog/dog.5648.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5648.jpg \n inflating: Cat_Dog_data/train/dog/dog.10161.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10161.jpg \n inflating: Cat_Dog_data/train/dog/dog.9072.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9072.jpg \n inflating: Cat_Dog_data/train/dog/dog.6341.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6341.jpg \n inflating: Cat_Dog_data/train/dog/dog.11257.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11257.jpg \n inflating: Cat_Dog_data/train/dog/dog.420.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.420.jpg \n inflating: Cat_Dog_data/train/dog/dog.3211.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3211.jpg \n inflating: Cat_Dog_data/train/dog/dog.10149.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10149.jpg \n inflating: Cat_Dog_data/train/dog/dog.5660.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5660.jpg \n inflating: Cat_Dog_data/train/dog/dog.6369.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6369.jpg \n inflating: Cat_Dog_data/train/dog/dog.1406.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1406.jpg \n inflating: Cat_Dog_data/train/dog/dog.7077.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7077.jpg \n inflating: Cat_Dog_data/train/dog/dog.8344.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8344.jpg \n inflating: Cat_Dog_data/train/dog/dog.7711.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7711.jpg \n inflating: Cat_Dog_data/train/dog/dog.12038.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12038.jpg \n inflating: Cat_Dog_data/train/dog/dog.8422.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8422.jpg \n inflating: Cat_Dog_data/train/dog/dog.1360.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1360.jpg \n inflating: Cat_Dog_data/train/dog/dog.5106.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5106.jpg \n inflating: Cat_Dog_data/train/dog/dog.2669.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2669.jpg \n inflating: Cat_Dog_data/train/dog/dog.346.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.346.jpg \n inflating: Cat_Dog_data/train/dog/dog.3577.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3577.jpg \n inflating: Cat_Dog_data/train/dog/dog.11531.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11531.jpg \n inflating: Cat_Dog_data/train/dog/dog.4218.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4218.jpg \n inflating: Cat_Dog_data/train/dog/dog.5112.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5112.jpg \n inflating: Cat_Dog_data/train/dog/dog.352.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.352.jpg \n inflating: Cat_Dog_data/train/dog/dog.11525.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11525.jpg \n inflating: Cat_Dog_data/train/dog/dog.7705.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7705.jpg \n inflating: Cat_Dog_data/train/dog/dog.8436.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8436.jpg \n inflating: Cat_Dog_data/train/dog/dog.1374.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1374.jpg \n inflating: Cat_Dog_data/train/dog/dog.9728.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9728.jpg \n inflating: Cat_Dog_data/train/dog/dog.1412.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1412.jpg \n inflating: Cat_Dog_data/train/dog/dog.7063.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7063.jpg \n inflating: Cat_Dog_data/train/dog/dog.8350.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8350.jpg \n inflating: Cat_Dog_data/train/dog/dog.11243.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11243.jpg \n inflating: Cat_Dog_data/train/dog/dog.3205.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3205.jpg \n inflating: Cat_Dog_data/train/dog/dog.434.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.434.jpg \n inflating: Cat_Dog_data/train/dog/dog.5674.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5674.jpg \n inflating: Cat_Dog_data/train/dog/dog.5933.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5933.jpg \n inflating: Cat_Dog_data/train/dog/dog.2084.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2084.jpg \n inflating: Cat_Dog_data/train/dog/dog.6584.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6584.jpg \n inflating: Cat_Dog_data/train/dog/dog.7842.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7842.jpg \n inflating: Cat_Dog_data/train/dog/dog.4393.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4393.jpg \n inflating: Cat_Dog_data/train/dog/dog.4387.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4387.jpg \n inflating: Cat_Dog_data/train/dog/dog.10968.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10968.jpg \n inflating: Cat_Dog_data/train/dog/dog.6590.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6590.jpg \n inflating: Cat_Dog_data/train/dog/dog.7856.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7856.jpg \n inflating: Cat_Dog_data/train/dog/dog.1599.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1599.jpg \n inflating: Cat_Dog_data/train/dog/dog.5927.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5927.jpg \n inflating: Cat_Dog_data/train/dog/dog.2090.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2090.jpg \n inflating: Cat_Dog_data/train/dog/dog.10798.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10798.jpg \n inflating: Cat_Dog_data/train/dog/dog.2906.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2906.jpg \n inflating: Cat_Dog_data/train/dog/dog.11486.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11486.jpg \n inflating: Cat_Dog_data/train/dog/dog.10940.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10940.jpg \n inflating: Cat_Dog_data/train/dog/dog.9853.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9853.jpg \n inflating: Cat_Dog_data/train/dog/dog.8595.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8595.jpg \n inflating: Cat_Dog_data/train/dog/dog.9847.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9847.jpg \n inflating: Cat_Dog_data/train/dog/dog.8581.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8581.jpg \n inflating: Cat_Dog_data/train/dog/dog.2912.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2912.jpg \n inflating: Cat_Dog_data/train/dog/dog.11492.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11492.jpg \n inflating: Cat_Dog_data/train/dog/dog.10954.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10954.jpg \n inflating: Cat_Dog_data/train/dog/dog.583.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.583.jpg \n inflating: Cat_Dog_data/train/dog/dog.9112.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9112.jpg \n inflating: Cat_Dog_data/train/dog/dog.6221.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6221.jpg \n inflating: Cat_Dog_data/train/dog/dog.5728.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5728.jpg \n inflating: Cat_Dog_data/train/dog/dog.10001.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10001.jpg \n inflating: Cat_Dog_data/train/dog/dog.2047.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2047.jpg \n inflating: Cat_Dog_data/train/dog/dog.3359.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3359.jpg \n inflating: Cat_Dog_data/train/dog/dog.568.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.568.jpg \n inflating: Cat_Dog_data/train/dog/dog.4436.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4436.jpg \n inflating: Cat_Dog_data/train/dog/dog.4350.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4350.jpg \n inflating: Cat_Dog_data/train/dog/dog.2721.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2721.jpg \n inflating: Cat_Dog_data/train/dog/dog.10767.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10767.jpg \n inflating: Cat_Dog_data/train/dog/dog.9674.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9674.jpg \n inflating: Cat_Dog_data/train/dog/dog.6547.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6547.jpg \n inflating: Cat_Dog_data/train/dog/dog.1228.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1228.jpg \n inflating: Cat_Dog_data/train/dog/dog.7881.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7881.jpg \n inflating: Cat_Dog_data/train/dog/dog.12170.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12170.jpg \n inflating: Cat_Dog_data/train/dog/dog.7659.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7659.jpg \n inflating: Cat_Dog_data/train/dog/dog.9660.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9660.jpg \n inflating: Cat_Dog_data/train/dog/dog.6553.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6553.jpg \n inflating: Cat_Dog_data/train/dog/dog.7895.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7895.jpg \n inflating: Cat_Dog_data/train/dog/dog.12164.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12164.jpg \n inflating: Cat_Dog_data/train/dog/dog.4344.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4344.jpg \n inflating: Cat_Dog_data/train/dog/dog.2735.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2735.jpg \n inflating: Cat_Dog_data/train/dog/dog.10773.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10773.jpg \n inflating: Cat_Dog_data/train/dog/dog.10015.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10015.jpg \n inflating: Cat_Dog_data/train/dog/dog.4422.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4422.jpg \n inflating: Cat_Dog_data/train/dog/dog.8218.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8218.jpg \n inflating: Cat_Dog_data/train/dog/dog.9106.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9106.jpg \n inflating: Cat_Dog_data/train/dog/dog.6235.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6235.jpg \n inflating: Cat_Dog_data/train/dog/dog.5714.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5714.jpg \n inflating: Cat_Dog_data/train/dog/dog.3365.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3365.jpg \n inflating: Cat_Dog_data/train/dog/dog.554.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.554.jpg \n inflating: Cat_Dog_data/train/dog/dog.11323.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11323.jpg \n inflating: Cat_Dog_data/train/dog/dog.7103.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7103.jpg \n inflating: Cat_Dog_data/train/dog/dog.8230.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8230.jpg \n inflating: Cat_Dog_data/train/dog/dog.1572.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1572.jpg \n inflating: Cat_Dog_data/train/dog/dog.9648.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9648.jpg \n inflating: Cat_Dog_data/train/dog/dog.1214.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1214.jpg \n inflating: Cat_Dog_data/train/dog/dog.9890.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9890.jpg \n inflating: Cat_Dog_data/train/dog/dog.7665.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7665.jpg \n inflating: Cat_Dog_data/train/dog/dog.8556.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8556.jpg \n inflating: Cat_Dog_data/train/dog/dog.11445.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11445.jpg \n inflating: Cat_Dog_data/train/dog/dog.3403.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3403.jpg \n inflating: Cat_Dog_data/train/dog/dog.232.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.232.jpg \n inflating: Cat_Dog_data/train/dog/dog.10983.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10983.jpg \n inflating: Cat_Dog_data/train/dog/dog.5072.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5072.jpg \n inflating: Cat_Dog_data/train/dog/dog.11451.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11451.jpg \n inflating: Cat_Dog_data/train/dog/dog.4378.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4378.jpg \n inflating: Cat_Dog_data/train/dog/dog.10997.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10997.jpg \n inflating: Cat_Dog_data/train/dog/dog.2709.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2709.jpg \n inflating: Cat_Dog_data/train/dog/dog.5066.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5066.jpg \n inflating: Cat_Dog_data/train/dog/dog.1200.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1200.jpg \n inflating: Cat_Dog_data/train/dog/dog.9884.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9884.jpg \n inflating: Cat_Dog_data/train/dog/dog.7671.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7671.jpg \n inflating: Cat_Dog_data/train/dog/dog.12158.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12158.jpg \n inflating: Cat_Dog_data/train/dog/dog.8542.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8542.jpg \n inflating: Cat_Dog_data/train/dog/dog.7117.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7117.jpg \n inflating: Cat_Dog_data/train/dog/dog.1566.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1566.jpg \n inflating: Cat_Dog_data/train/dog/dog.6209.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6209.jpg \n inflating: Cat_Dog_data/train/dog/dog.5700.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5700.jpg \n inflating: Cat_Dog_data/train/dog/dog.540.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.540.jpg \n inflating: Cat_Dog_data/train/dog/dog.3371.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3371.jpg \n inflating: Cat_Dog_data/train/dog/dog.11337.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11337.jpg \n inflating: Cat_Dog_data/train/dog/dog.4191.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4191.jpg \n inflating: Cat_Dog_data/train/dog/dog.3826.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3826.jpg \n inflating: Cat_Dog_data/train/dog/dog.11860.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11860.jpg \n inflating: Cat_Dog_data/train/dog/dog.8973.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8973.jpg \n inflating: Cat_Dog_data/train/dog/dog.6786.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6786.jpg \n inflating: Cat_Dog_data/train/dog/dog.7498.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7498.jpg \n inflating: Cat_Dog_data/train/dog/dog.1957.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1957.jpg \n inflating: Cat_Dog_data/train/dog/dog.2286.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2286.jpg \n inflating: Cat_Dog_data/train/dog/dog.971.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.971.jpg \n inflating: Cat_Dog_data/train/dog/dog.3198.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3198.jpg \n inflating: Cat_Dog_data/train/dog/dog.2292.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2292.jpg \n inflating: Cat_Dog_data/train/dog/dog.965.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.965.jpg \n inflating: Cat_Dog_data/train/dog/dog.1943.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1943.jpg \n inflating: Cat_Dog_data/train/dog/dog.8967.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8967.jpg \n inflating: Cat_Dog_data/train/dog/dog.4185.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4185.jpg \n inflating: Cat_Dog_data/train/dog/dog.3832.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3832.jpg \n inflating: Cat_Dog_data/train/dog/dog.11874.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11874.jpg \n inflating: Cat_Dog_data/train/dog/dog.8797.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8797.jpg \n inflating: Cat_Dog_data/train/dog/dog.6962.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6962.jpg \n inflating: Cat_Dog_data/train/dog/dog.4813.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4813.jpg \n inflating: Cat_Dog_data/train/dog/dog.795.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.795.jpg \n inflating: Cat_Dog_data/train/dog/dog.4807.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4807.jpg \n inflating: Cat_Dog_data/train/dog/dog.781.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.781.jpg \n inflating: Cat_Dog_data/train/dog/dog.11690.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11690.jpg \n inflating: Cat_Dog_data/train/dog/dog.8783.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8783.jpg \n inflating: Cat_Dog_data/train/dog/dog.12399.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12399.jpg \n inflating: Cat_Dog_data/train/dog/dog.6976.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6976.jpg \n inflating: Cat_Dog_data/train/dog/dog.12372.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12372.jpg \n inflating: Cat_Dog_data/train/dog/dog.8768.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8768.jpg \n inflating: Cat_Dog_data/train/dog/dog.10565.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10565.jpg \n inflating: Cat_Dog_data/train/dog/dog.2523.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2523.jpg \n inflating: Cat_Dog_data/train/dog/dog.4152.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4152.jpg \n inflating: Cat_Dog_data/train/dog/dog.4634.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4634.jpg \n inflating: Cat_Dog_data/train/dog/dog.2245.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2245.jpg \n inflating: Cat_Dog_data/train/dog/dog.6023.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6023.jpg \n inflating: Cat_Dog_data/train/dog/dog.9310.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9310.jpg \n inflating: Cat_Dog_data/train/dog/dog.12414.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12414.jpg \n inflating: Cat_Dog_data/train/dog/dog.6037.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6037.jpg \n inflating: Cat_Dog_data/train/dog/dog.9304.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9304.jpg \n inflating: Cat_Dog_data/train/dog/dog.1758.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1758.jpg \n inflating: Cat_Dog_data/train/dog/dog.7329.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7329.jpg \n inflating: Cat_Dog_data/train/dog/dog.12400.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12400.jpg \n inflating: Cat_Dog_data/train/dog/dog.1980.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1980.jpg \n inflating: Cat_Dog_data/train/dog/dog.11109.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11109.jpg \n inflating: Cat_Dog_data/train/dog/dog.4620.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4620.jpg \n inflating: Cat_Dog_data/train/dog/dog.2251.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2251.jpg \n inflating: Cat_Dog_data/train/dog/dog.10217.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10217.jpg \n inflating: Cat_Dog_data/train/dog/dog.10571.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10571.jpg \n inflating: Cat_Dog_data/train/dog/dog.5258.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5258.jpg \n inflating: Cat_Dog_data/train/dog/dog.2537.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2537.jpg \n inflating: Cat_Dog_data/train/dog/dog.3629.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3629.jpg \n inflating: Cat_Dog_data/train/dog/dog.4146.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4146.jpg \n inflating: Cat_Dog_data/train/dog/dog.12366.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12366.jpg \n inflating: Cat_Dog_data/train/dog/dog.6989.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6989.jpg \n inflating: Cat_Dog_data/train/dog/dog.6751.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6751.jpg \n inflating: Cat_Dog_data/train/dog/dog.9462.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9462.jpg \n inflating: Cat_Dog_data/train/dog/dog.5270.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5270.jpg \n inflating: Cat_Dog_data/train/dog/dog.10559.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10559.jpg \n inflating: Cat_Dog_data/train/dog/dog.11647.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11647.jpg \n inflating: Cat_Dog_data/train/dog/dog.8754.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8754.jpg \n inflating: Cat_Dog_data/train/dog/dog.7467.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7467.jpg \n inflating: Cat_Dog_data/train/dog/dog.1016.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1016.jpg \n inflating: Cat_Dog_data/train/dog/dog.6779.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6779.jpg \n inflating: Cat_Dog_data/train/dog/dog.1770.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1770.jpg \n inflating: Cat_Dog_data/train/dog/dog.8032.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8032.jpg \n inflating: Cat_Dog_data/train/dog/dog.7301.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7301.jpg \n inflating: Cat_Dog_data/train/dog/dog.4608.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4608.jpg \n inflating: Cat_Dog_data/train/dog/dog.11121.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11121.jpg \n inflating: Cat_Dog_data/train/dog/dog.3167.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3167.jpg \n inflating: Cat_Dog_data/train/dog/dog.756.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.756.jpg \n inflating: Cat_Dog_data/train/dog/dog.2279.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2279.jpg \n inflating: Cat_Dog_data/train/dog/dog.5516.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5516.jpg \n inflating: Cat_Dog_data/train/dog/dog.11135.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11135.jpg \n inflating: Cat_Dog_data/train/dog/dog.742.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.742.jpg \n inflating: Cat_Dog_data/train/dog/dog.3173.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3173.jpg \n inflating: Cat_Dog_data/train/dog/dog.5502.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5502.jpg \n inflating: Cat_Dog_data/train/dog/dog.9338.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9338.jpg \n inflating: Cat_Dog_data/train/dog/dog.1764.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1764.jpg \n inflating: Cat_Dog_data/train/dog/dog.8026.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8026.jpg \n inflating: Cat_Dog_data/train/dog/dog.7315.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7315.jpg \n inflating: Cat_Dog_data/train/dog/dog.8740.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8740.jpg \n inflating: Cat_Dog_data/train/dog/dog.7473.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7473.jpg \n inflating: Cat_Dog_data/train/dog/dog.1002.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1002.jpg \n inflating: Cat_Dog_data/train/dog/dog.8998.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8998.jpg \n inflating: Cat_Dog_data/train/dog/dog.3615.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3615.jpg \n inflating: Cat_Dog_data/train/dog/dog.11653.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11653.jpg \n inflating: Cat_Dog_data/train/dog/dog.9466.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9466.jpg \n inflating: Cat_Dog_data/train/dog/dog.6755.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6755.jpg \n inflating: Cat_Dog_data/train/dog/dog.8778.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8778.jpg \n inflating: Cat_Dog_data/train/dog/dog.12362.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12362.jpg \n inflating: Cat_Dog_data/train/dog/dog.4142.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4142.jpg \n inflating: Cat_Dog_data/train/dog/dog.2533.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2533.jpg \n inflating: Cat_Dog_data/train/dog/dog.10213.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10213.jpg \n inflating: Cat_Dog_data/train/dog/dog.4624.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4624.jpg \n inflating: Cat_Dog_data/train/dog/dog.1984.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1984.jpg \n inflating: Cat_Dog_data/train/dog/dog.12404.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12404.jpg \n inflating: Cat_Dog_data/train/dog/dog.9300.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9300.jpg \n inflating: Cat_Dog_data/train/dog/dog.6033.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6033.jpg \n inflating: Cat_Dog_data/train/dog/dog.1990.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1990.jpg \n inflating: Cat_Dog_data/train/dog/dog.12410.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12410.jpg \n inflating: Cat_Dog_data/train/dog/dog.7339.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7339.jpg \n inflating: Cat_Dog_data/train/dog/dog.9314.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9314.jpg \n inflating: Cat_Dog_data/train/dog/dog.6027.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6027.jpg \n inflating: Cat_Dog_data/train/dog/dog.1748.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1748.jpg \n inflating: Cat_Dog_data/train/dog/dog.2241.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2241.jpg \n inflating: Cat_Dog_data/train/dog/dog.10207.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10207.jpg \n inflating: Cat_Dog_data/train/dog/dog.11119.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11119.jpg \n inflating: Cat_Dog_data/train/dog/dog.3639.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3639.jpg \n inflating: Cat_Dog_data/train/dog/dog.4156.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4156.jpg \n inflating: Cat_Dog_data/train/dog/dog.5248.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5248.jpg \n inflating: Cat_Dog_data/train/dog/dog.2527.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2527.jpg \n inflating: Cat_Dog_data/train/dog/dog.6741.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6741.jpg \n inflating: Cat_Dog_data/train/dog/dog.6999.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6999.jpg \n inflating: Cat_Dog_data/train/dog/dog.3611.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3611.jpg \n inflating: Cat_Dog_data/train/dog/dog.10549.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10549.jpg \n inflating: Cat_Dog_data/train/dog/dog.5260.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5260.jpg \n inflating: Cat_Dog_data/train/dog/dog.1006.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1006.jpg \n inflating: Cat_Dog_data/train/dog/dog.6769.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6769.jpg \n inflating: Cat_Dog_data/train/dog/dog.7477.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7477.jpg \n inflating: Cat_Dog_data/train/dog/dog.8744.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8744.jpg \n inflating: Cat_Dog_data/train/dog/dog.7311.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7311.jpg \n inflating: Cat_Dog_data/train/dog/dog.12438.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12438.jpg \n inflating: Cat_Dog_data/train/dog/dog.8022.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8022.jpg \n inflating: Cat_Dog_data/train/dog/dog.1760.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1760.jpg \n inflating: Cat_Dog_data/train/dog/dog.2269.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2269.jpg \n inflating: Cat_Dog_data/train/dog/dog.5506.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5506.jpg \n inflating: Cat_Dog_data/train/dog/dog.4618.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4618.jpg \n inflating: Cat_Dog_data/train/dog/dog.3177.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3177.jpg \n inflating: Cat_Dog_data/train/dog/dog.746.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.746.jpg \n inflating: Cat_Dog_data/train/dog/dog.5512.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5512.jpg \n inflating: Cat_Dog_data/train/dog/dog.11125.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11125.jpg \n inflating: Cat_Dog_data/train/dog/dog.3163.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3163.jpg \n inflating: Cat_Dog_data/train/dog/dog.7305.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7305.jpg \n inflating: Cat_Dog_data/train/dog/dog.8036.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8036.jpg \n inflating: Cat_Dog_data/train/dog/dog.1774.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1774.jpg \n inflating: Cat_Dog_data/train/dog/dog.8988.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8988.jpg \n inflating: Cat_Dog_data/train/dog/dog.7463.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7463.jpg \n inflating: Cat_Dog_data/train/dog/dog.8750.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8750.jpg \n inflating: Cat_Dog_data/train/dog/dog.3605.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3605.jpg \n inflating: Cat_Dog_data/train/dog/dog.5274.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5274.jpg \n inflating: Cat_Dog_data/train/dog/dog.3836.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3836.jpg \n inflating: Cat_Dog_data/train/dog/dog.11870.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11870.jpg \n inflating: Cat_Dog_data/train/dog/dog.4181.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4181.jpg \n inflating: Cat_Dog_data/train/dog/dog.8963.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8963.jpg \n inflating: Cat_Dog_data/train/dog/dog.6796.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6796.jpg \n inflating: Cat_Dog_data/train/dog/dog.1947.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1947.jpg \n inflating: Cat_Dog_data/train/dog/dog.3188.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3188.jpg \n inflating: Cat_Dog_data/train/dog/dog.961.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.961.jpg \n inflating: Cat_Dog_data/train/dog/dog.2282.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2282.jpg \n inflating: Cat_Dog_data/train/dog/dog.975.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.975.jpg \n inflating: Cat_Dog_data/train/dog/dog.1953.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1953.jpg \n inflating: Cat_Dog_data/train/dog/dog.8977.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8977.jpg \n inflating: Cat_Dog_data/train/dog/dog.6782.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6782.jpg \n inflating: Cat_Dog_data/train/dog/dog.3822.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3822.jpg \n inflating: Cat_Dog_data/train/dog/dog.11864.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11864.jpg \n inflating: Cat_Dog_data/train/dog/dog.4195.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4195.jpg \n inflating: Cat_Dog_data/train/dog/dog.8787.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8787.jpg \n inflating: Cat_Dog_data/train/dog/dog.9499.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9499.jpg \n inflating: Cat_Dog_data/train/dog/dog.11694.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11694.jpg \n inflating: Cat_Dog_data/train/dog/dog.785.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.785.jpg \n inflating: Cat_Dog_data/train/dog/dog.4803.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4803.jpg \n inflating: Cat_Dog_data/train/dog/dog.791.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.791.jpg \n inflating: Cat_Dog_data/train/dog/dog.4817.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4817.jpg \n inflating: Cat_Dog_data/train/dog/dog.949.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.949.jpg \n inflating: Cat_Dog_data/train/dog/dog.11858.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11858.jpg \n inflating: Cat_Dog_data/train/dog/dog.11680.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11680.jpg \n inflating: Cat_Dog_data/train/dog/dog.12389.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12389.jpg \n inflating: Cat_Dog_data/train/dog/dog.8793.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8793.jpg \n inflating: Cat_Dog_data/train/dog/dog.6966.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6966.jpg \n inflating: Cat_Dog_data/train/dog/dog.6231.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6231.jpg \n inflating: Cat_Dog_data/train/dog/dog.9102.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9102.jpg \n inflating: Cat_Dog_data/train/dog/dog.3349.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3349.jpg \n inflating: Cat_Dog_data/train/dog/dog.578.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.578.jpg \n inflating: Cat_Dog_data/train/dog/dog.4426.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4426.jpg \n inflating: Cat_Dog_data/train/dog/dog.10011.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10011.jpg \n inflating: Cat_Dog_data/train/dog/dog.5738.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5738.jpg \n inflating: Cat_Dog_data/train/dog/dog.2057.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2057.jpg \n inflating: Cat_Dog_data/train/dog/dog.2731.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2731.jpg \n inflating: Cat_Dog_data/train/dog/dog.10777.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10777.jpg \n inflating: Cat_Dog_data/train/dog/dog.11469.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11469.jpg \n inflating: Cat_Dog_data/train/dog/dog.4340.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4340.jpg \n inflating: Cat_Dog_data/train/dog/dog.7649.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7649.jpg \n inflating: Cat_Dog_data/train/dog/dog.12160.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12160.jpg \n inflating: Cat_Dog_data/train/dog/dog.6557.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6557.jpg \n inflating: Cat_Dog_data/train/dog/dog.9664.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9664.jpg \n inflating: Cat_Dog_data/train/dog/dog.7891.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7891.jpg \n inflating: Cat_Dog_data/train/dog/dog.12174.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12174.jpg \n inflating: Cat_Dog_data/train/dog/dog.6543.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6543.jpg \n inflating: Cat_Dog_data/train/dog/dog.9670.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9670.jpg \n inflating: Cat_Dog_data/train/dog/dog.2725.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2725.jpg \n inflating: Cat_Dog_data/train/dog/dog.10763.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10763.jpg \n inflating: Cat_Dog_data/train/dog/dog.4354.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4354.jpg \n inflating: Cat_Dog_data/train/dog/dog.10005.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10005.jpg \n inflating: Cat_Dog_data/train/dog/dog.2043.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2043.jpg \n inflating: Cat_Dog_data/train/dog/dog.6225.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6225.jpg \n inflating: Cat_Dog_data/train/dog/dog.9116.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9116.jpg \n inflating: Cat_Dog_data/train/dog/dog.8208.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8208.jpg \n inflating: Cat_Dog_data/train/dog/dog.3375.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3375.jpg \n inflating: Cat_Dog_data/train/dog/dog.544.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.544.jpg \n inflating: Cat_Dog_data/train/dog/dog.11333.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11333.jpg \n inflating: Cat_Dog_data/train/dog/dog.5704.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5704.jpg \n inflating: Cat_Dog_data/train/dog/dog.1562.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1562.jpg \n inflating: Cat_Dog_data/train/dog/dog.8220.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8220.jpg \n inflating: Cat_Dog_data/train/dog/dog.7113.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7113.jpg \n inflating: Cat_Dog_data/train/dog/dog.9880.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9880.jpg \n inflating: Cat_Dog_data/train/dog/dog.8546.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8546.jpg \n inflating: Cat_Dog_data/train/dog/dog.9658.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9658.jpg \n inflating: Cat_Dog_data/train/dog/dog.1204.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1204.jpg \n inflating: Cat_Dog_data/train/dog/dog.5062.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5062.jpg \n inflating: Cat_Dog_data/train/dog/dog.10993.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10993.jpg \n inflating: Cat_Dog_data/train/dog/dog.3413.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3413.jpg \n inflating: Cat_Dog_data/train/dog/dog.222.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.222.jpg \n inflating: Cat_Dog_data/train/dog/dog.2719.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2719.jpg \n inflating: Cat_Dog_data/train/dog/dog.5076.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5076.jpg \n inflating: Cat_Dog_data/train/dog/dog.4368.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4368.jpg \n inflating: Cat_Dog_data/train/dog/dog.11441.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11441.jpg \n inflating: Cat_Dog_data/train/dog/dog.10987.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10987.jpg \n inflating: Cat_Dog_data/train/dog/dog.236.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.236.jpg \n inflating: Cat_Dog_data/train/dog/dog.3407.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3407.jpg \n inflating: Cat_Dog_data/train/dog/dog.9894.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9894.jpg \n inflating: Cat_Dog_data/train/dog/dog.8552.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8552.jpg \n inflating: Cat_Dog_data/train/dog/dog.12148.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12148.jpg \n inflating: Cat_Dog_data/train/dog/dog.7661.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7661.jpg \n inflating: Cat_Dog_data/train/dog/dog.1210.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1210.jpg \n inflating: Cat_Dog_data/train/dog/dog.1576.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1576.jpg \n inflating: Cat_Dog_data/train/dog/dog.6219.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6219.jpg \n inflating: Cat_Dog_data/train/dog/dog.8234.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8234.jpg \n inflating: Cat_Dog_data/train/dog/dog.7107.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7107.jpg \n inflating: Cat_Dog_data/train/dog/dog.550.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.550.jpg \n inflating: Cat_Dog_data/train/dog/dog.3361.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3361.jpg \n inflating: Cat_Dog_data/train/dog/dog.11327.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11327.jpg \n inflating: Cat_Dog_data/train/dog/dog.5710.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5710.jpg \n inflating: Cat_Dog_data/train/dog/dog.10039.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10039.jpg \n inflating: Cat_Dog_data/train/dog/dog.2094.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2094.jpg \n inflating: Cat_Dog_data/train/dog/dog.6594.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6594.jpg \n inflating: Cat_Dog_data/train/dog/dog.7852.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7852.jpg \n inflating: Cat_Dog_data/train/dog/dog.4383.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4383.jpg \n inflating: Cat_Dog_data/train/dog/dog.4397.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4397.jpg \n inflating: Cat_Dog_data/train/dog/dog.10978.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10978.jpg \n inflating: Cat_Dog_data/train/dog/dog.5089.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5089.jpg \n inflating: Cat_Dog_data/train/dog/dog.7846.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7846.jpg \n inflating: Cat_Dog_data/train/dog/dog.1589.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1589.jpg \n inflating: Cat_Dog_data/train/dog/dog.2080.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2080.jpg \n inflating: Cat_Dog_data/train/dog/dog.5937.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5937.jpg \n inflating: Cat_Dog_data/train/dog/dog.587.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.587.jpg \n inflating: Cat_Dog_data/train/dog/dog.11496.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11496.jpg \n inflating: Cat_Dog_data/train/dog/dog.2916.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2916.jpg \n inflating: Cat_Dog_data/train/dog/dog.10950.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10950.jpg \n inflating: Cat_Dog_data/train/dog/dog.10788.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10788.jpg \n inflating: Cat_Dog_data/train/dog/dog.9843.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9843.jpg \n inflating: Cat_Dog_data/train/dog/dog.8585.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8585.jpg \n inflating: Cat_Dog_data/train/dog/dog.9857.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9857.jpg \n inflating: Cat_Dog_data/train/dog/dog.8591.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8591.jpg \n inflating: Cat_Dog_data/train/dog/dog.11482.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11482.jpg \n inflating: Cat_Dog_data/train/dog/dog.2902.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2902.jpg \n inflating: Cat_Dog_data/train/dog/dog.10944.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10944.jpg \n inflating: Cat_Dog_data/train/dog/dog.593.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.593.jpg \n inflating: Cat_Dog_data/train/dog/dog.8368.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8368.jpg \n inflating: Cat_Dog_data/train/dog/dog.6345.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6345.jpg \n inflating: Cat_Dog_data/train/dog/dog.9076.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9076.jpg \n inflating: Cat_Dog_data/train/dog/dog.2123.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2123.jpg \n inflating: Cat_Dog_data/train/dog/dog.4552.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4552.jpg \n inflating: Cat_Dog_data/train/dog/dog.5894.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5894.jpg \n inflating: Cat_Dog_data/train/dog/dog.4234.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4234.jpg \n inflating: Cat_Dog_data/train/dog/dog.10603.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10603.jpg \n inflating: Cat_Dog_data/train/dog/dog.2645.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2645.jpg \n inflating: Cat_Dog_data/train/dog/dog.6423.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6423.jpg \n inflating: Cat_Dog_data/train/dog/dog.9710.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9710.jpg \n inflating: Cat_Dog_data/train/dog/dog.12014.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12014.jpg \n inflating: Cat_Dog_data/train/dog/dog.1358.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1358.jpg \n inflating: Cat_Dog_data/train/dog/dog.6437.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6437.jpg \n inflating: Cat_Dog_data/train/dog/dog.9704.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9704.jpg \n inflating: Cat_Dog_data/train/dog/dog.12000.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12000.jpg \n inflating: Cat_Dog_data/train/dog/dog.2889.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2889.jpg \n inflating: Cat_Dog_data/train/dog/dog.11509.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11509.jpg \n inflating: Cat_Dog_data/train/dog/dog.4220.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4220.jpg \n inflating: Cat_Dog_data/train/dog/dog.10617.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10617.jpg \n inflating: Cat_Dog_data/train/dog/dog.2651.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2651.jpg \n inflating: Cat_Dog_data/train/dog/dog.2137.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2137.jpg \n inflating: Cat_Dog_data/train/dog/dog.10171.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10171.jpg \n inflating: Cat_Dog_data/train/dog/dog.5658.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5658.jpg \n inflating: Cat_Dog_data/train/dog/dog.4546.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4546.jpg \n inflating: Cat_Dog_data/train/dog/dog.3229.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3229.jpg \n inflating: Cat_Dog_data/train/dog/dog.418.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.418.jpg \n inflating: Cat_Dog_data/train/dog/dog.5880.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5880.jpg \n inflating: Cat_Dog_data/train/dog/dog.6351.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6351.jpg \n inflating: Cat_Dog_data/train/dog/dog.9062.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9062.jpg \n inflating: Cat_Dog_data/train/dog/dog.5670.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5670.jpg \n inflating: Cat_Dog_data/train/dog/dog.10159.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10159.jpg \n inflating: Cat_Dog_data/train/dog/dog.11247.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11247.jpg \n inflating: Cat_Dog_data/train/dog/dog.430.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.430.jpg \n inflating: Cat_Dog_data/train/dog/dog.3201.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3201.jpg \n inflating: Cat_Dog_data/train/dog/dog.8354.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8354.jpg \n inflating: Cat_Dog_data/train/dog/dog.7067.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7067.jpg \n inflating: Cat_Dog_data/train/dog/dog.1370.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1370.jpg \n inflating: Cat_Dog_data/train/dog/dog.8432.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8432.jpg \n inflating: Cat_Dog_data/train/dog/dog.12028.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12028.jpg \n inflating: Cat_Dog_data/train/dog/dog.7701.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7701.jpg \n inflating: Cat_Dog_data/train/dog/dog.356.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.356.jpg \n inflating: Cat_Dog_data/train/dog/dog.3567.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3567.jpg \n inflating: Cat_Dog_data/train/dog/dog.4208.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4208.jpg \n inflating: Cat_Dog_data/train/dog/dog.11521.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11521.jpg \n inflating: Cat_Dog_data/train/dog/dog.5116.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5116.jpg \n inflating: Cat_Dog_data/train/dog/dog.2679.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2679.jpg \n inflating: Cat_Dog_data/train/dog/dog.3573.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3573.jpg \n inflating: Cat_Dog_data/train/dog/dog.342.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.342.jpg \n inflating: Cat_Dog_data/train/dog/dog.11535.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11535.jpg \n inflating: Cat_Dog_data/train/dog/dog.5102.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5102.jpg \n inflating: Cat_Dog_data/train/dog/dog.1364.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1364.jpg \n inflating: Cat_Dog_data/train/dog/dog.9738.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9738.jpg \n inflating: Cat_Dog_data/train/dog/dog.7715.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7715.jpg \n inflating: Cat_Dog_data/train/dog/dog.8340.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8340.jpg \n inflating: Cat_Dog_data/train/dog/dog.7073.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7073.jpg \n inflating: Cat_Dog_data/train/dog/dog.1402.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1402.jpg \n inflating: Cat_Dog_data/train/dog/dog.5664.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5664.jpg \n inflating: Cat_Dog_data/train/dog/dog.11253.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11253.jpg \n inflating: Cat_Dog_data/train/dog/dog.3215.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3215.jpg \n inflating: Cat_Dog_data/train/dog/dog.5857.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5857.jpg \n inflating: Cat_Dog_data/train/dog/dog.6386.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6386.jpg \n inflating: Cat_Dog_data/train/dog/dog.7098.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7098.jpg \n inflating: Cat_Dog_data/train/dog/dog.7926.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7926.jpg \n inflating: Cat_Dog_data/train/dog/dog.2686.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2686.jpg \n inflating: Cat_Dog_data/train/dog/dog.10818.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10818.jpg \n inflating: Cat_Dog_data/train/dog/dog.2692.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2692.jpg \n inflating: Cat_Dog_data/train/dog/dog.7932.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7932.jpg \n inflating: Cat_Dog_data/train/dog/dog.6392.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6392.jpg \n inflating: Cat_Dog_data/train/dog/dog.4585.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4585.jpg \n inflating: Cat_Dog_data/train/dog/dog.5843.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5843.jpg \n inflating: Cat_Dog_data/train/dog/dog.9089.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9089.jpg \n inflating: Cat_Dog_data/train/dog/dog.8397.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8397.jpg \n inflating: Cat_Dog_data/train/dog/dog.11284.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11284.jpg \n inflating: Cat_Dog_data/train/dog/dog.10824.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10824.jpg \n inflating: Cat_Dog_data/train/dog/dog.395.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.395.jpg \n inflating: Cat_Dog_data/train/dog/dog.9937.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9937.jpg \n inflating: Cat_Dog_data/train/dog/dog.9923.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9923.jpg \n inflating: Cat_Dog_data/train/dog/dog.10830.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10830.jpg \n inflating: Cat_Dog_data/train/dog/dog.381.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.381.jpg \n inflating: Cat_Dog_data/train/dog/dog.2876.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2876.jpg \n inflating: Cat_Dog_data/train/dog/dog.11290.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11290.jpg \n inflating: Cat_Dog_data/train/dog/dog.8383.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8383.jpg \n inflating: Cat_Dog_data/train/dog/dog.12216.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12216.jpg \n inflating: Cat_Dog_data/train/dog/dog.9512.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9512.jpg \n inflating: Cat_Dog_data/train/dog/dog.6621.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6621.jpg \n inflating: Cat_Dog_data/train/dog/dog.2447.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2447.jpg \n inflating: Cat_Dog_data/train/dog/dog.5328.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5328.jpg \n inflating: Cat_Dog_data/train/dog/dog.3981.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3981.jpg \n inflating: Cat_Dog_data/train/dog/dog.4036.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4036.jpg \n inflating: Cat_Dog_data/train/dog/dog.3759.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3759.jpg \n inflating: Cat_Dog_data/train/dog/dog.4750.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4750.jpg \n inflating: Cat_Dog_data/train/dog/dog.11079.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11079.jpg \n inflating: Cat_Dog_data/train/dog/dog.10367.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10367.jpg \n inflating: Cat_Dog_data/train/dog/dog.2321.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2321.jpg \n inflating: Cat_Dog_data/train/dog/dog.1628.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1628.jpg \n inflating: Cat_Dog_data/train/dog/dog.9274.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9274.jpg \n inflating: Cat_Dog_data/train/dog/dog.6147.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6147.jpg \n inflating: Cat_Dog_data/train/dog/dog.7259.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7259.jpg \n inflating: Cat_Dog_data/train/dog/dog.6153.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6153.jpg \n inflating: Cat_Dog_data/train/dog/dog.11.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11.jpg \n inflating: Cat_Dog_data/train/dog/dog.4744.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4744.jpg \n inflating: Cat_Dog_data/train/dog/dog.10373.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10373.jpg \n inflating: Cat_Dog_data/train/dog/dog.2335.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2335.jpg \n inflating: Cat_Dog_data/train/dog/dog.2453.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2453.jpg \n inflating: Cat_Dog_data/train/dog/dog.10415.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10415.jpg \n inflating: Cat_Dog_data/train/dog/dog.3995.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3995.jpg \n inflating: Cat_Dog_data/train/dog/dog.4022.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4022.jpg \n inflating: Cat_Dog_data/train/dog/dog.8618.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8618.jpg \n inflating: Cat_Dog_data/train/dog/dog.12202.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12202.jpg \n inflating: Cat_Dog_data/train/dog/dog.9506.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9506.jpg \n inflating: Cat_Dog_data/train/dog/dog.6635.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6635.jpg \n inflating: Cat_Dog_data/train/dog/dog.5314.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5314.jpg \n inflating: Cat_Dog_data/train/dog/dog.11723.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11723.jpg \n inflating: Cat_Dog_data/train/dog/dog.154.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.154.jpg \n inflating: Cat_Dog_data/train/dog/dog.3765.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3765.jpg \n inflating: Cat_Dog_data/train/dog/dog.7503.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7503.jpg \n inflating: Cat_Dog_data/train/dog/dog.8630.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8630.jpg \n inflating: Cat_Dog_data/train/dog/dog.1172.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1172.jpg \n inflating: Cat_Dog_data/train/dog/dog.1614.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1614.jpg \n inflating: Cat_Dog_data/train/dog/dog.9248.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9248.jpg \n inflating: Cat_Dog_data/train/dog/dog.39.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.39.jpg \n inflating: Cat_Dog_data/train/dog/dog.7265.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7265.jpg \n inflating: Cat_Dog_data/train/dog/dog.8156.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8156.jpg \n inflating: Cat_Dog_data/train/dog/dog.632.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.632.jpg \n inflating: Cat_Dog_data/train/dog/dog.3003.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3003.jpg \n inflating: Cat_Dog_data/train/dog/dog.11045.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11045.jpg \n inflating: Cat_Dog_data/train/dog/dog.626.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.626.jpg \n inflating: Cat_Dog_data/train/dog/dog.4778.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4778.jpg \n inflating: Cat_Dog_data/train/dog/dog.5466.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5466.jpg \n inflating: Cat_Dog_data/train/dog/dog.2309.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2309.jpg \n inflating: Cat_Dog_data/train/dog/dog.1600.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1600.jpg \n inflating: Cat_Dog_data/train/dog/dog.7271.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7271.jpg \n inflating: Cat_Dog_data/train/dog/dog.8142.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8142.jpg \n inflating: Cat_Dog_data/train/dog/dog.7517.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7517.jpg \n inflating: Cat_Dog_data/train/dog/dog.8624.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8624.jpg \n inflating: Cat_Dog_data/train/dog/dog.6609.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6609.jpg \n inflating: Cat_Dog_data/train/dog/dog.1166.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1166.jpg \n inflating: Cat_Dog_data/train/dog/dog.10429.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10429.jpg \n inflating: Cat_Dog_data/train/dog/dog.5300.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5300.jpg \n inflating: Cat_Dog_data/train/dog/dog.11737.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11737.jpg \n inflating: Cat_Dog_data/train/dog/dog.3771.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3771.jpg \n inflating: Cat_Dog_data/train/dog/dog.140.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.140.jpg \n inflating: Cat_Dog_data/train/dog/dog.11904.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11904.jpg \n inflating: Cat_Dog_data/train/dog/dog.2484.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2484.jpg \n inflating: Cat_Dog_data/train/dog/dog.3942.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3942.jpg \n inflating: Cat_Dog_data/train/dog/dog.8817.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8817.jpg \n inflating: Cat_Dog_data/train/dog/dog.1833.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1833.jpg \n inflating: Cat_Dog_data/train/dog/dog.6184.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6184.jpg \n inflating: Cat_Dog_data/train/dog/dog.815.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.815.jpg \n inflating: Cat_Dog_data/train/dog/dog.4793.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4793.jpg \n inflating: Cat_Dog_data/train/dog/dog.5499.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5499.jpg \n inflating: Cat_Dog_data/train/dog/dog.801.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.801.jpg \n inflating: Cat_Dog_data/train/dog/dog.4787.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4787.jpg \n inflating: Cat_Dog_data/train/dog/dog.1827.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1827.jpg \n inflating: Cat_Dog_data/train/dog/dog.6190.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6190.jpg \n inflating: Cat_Dog_data/train/dog/dog.1199.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1199.jpg \n inflating: Cat_Dog_data/train/dog/dog.8803.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8803.jpg \n inflating: Cat_Dog_data/train/dog/dog.11910.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11910.jpg \n inflating: Cat_Dog_data/train/dog/dog.2490.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2490.jpg \n inflating: Cat_Dog_data/train/dog/dog.3956.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3956.jpg \n inflating: Cat_Dog_data/train/dog/dog.6806.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6806.jpg \n inflating: Cat_Dog_data/train/dog/dog.11938.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11938.jpg \n inflating: Cat_Dog_data/train/dog/dog.829.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.829.jpg \n inflating: Cat_Dog_data/train/dog/dog.10398.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10398.jpg \n inflating: Cat_Dog_data/train/dog/dog.11086.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11086.jpg \n inflating: Cat_Dog_data/train/dog/dog.8195.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8195.jpg \n inflating: Cat_Dog_data/train/dog/dog.8181.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8181.jpg \n inflating: Cat_Dog_data/train/dog/dog.4963.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4963.jpg \n inflating: Cat_Dog_data/train/dog/dog.11092.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11092.jpg \n inflating: Cat_Dog_data/train/dog/dog.183.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.183.jpg \n inflating: Cat_Dog_data/train/dog/dog.6812.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6812.jpg \n inflating: Cat_Dog_data/train/dog/dog.11093.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11093.jpg \n inflating: Cat_Dog_data/train/dog/dog.4962.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4962.jpg \n inflating: Cat_Dog_data/train/dog/dog.8180.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8180.jpg \n inflating: Cat_Dog_data/train/dog/dog.6813.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6813.jpg \n inflating: Cat_Dog_data/train/dog/dog.182.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.182.jpg \n inflating: Cat_Dog_data/train/dog/dog.11939.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11939.jpg \n inflating: Cat_Dog_data/train/dog/dog.196.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.196.jpg \n inflating: Cat_Dog_data/train/dog/dog.6807.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6807.jpg \n inflating: Cat_Dog_data/train/dog/dog.8194.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8194.jpg \n inflating: Cat_Dog_data/train/dog/dog.11087.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11087.jpg \n inflating: Cat_Dog_data/train/dog/dog.4976.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4976.jpg \n inflating: Cat_Dog_data/train/dog/dog.10399.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10399.jpg \n inflating: Cat_Dog_data/train/dog/dog.828.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.828.jpg \n inflating: Cat_Dog_data/train/dog/dog.6191.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6191.jpg \n inflating: Cat_Dog_data/train/dog/dog.1826.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1826.jpg \n inflating: Cat_Dog_data/train/dog/dog.800.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.800.jpg \n inflating: Cat_Dog_data/train/dog/dog.5498.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5498.jpg \n inflating: Cat_Dog_data/train/dog/dog.3957.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3957.jpg \n inflating: Cat_Dog_data/train/dog/dog.2491.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2491.jpg \n inflating: Cat_Dog_data/train/dog/dog.11911.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11911.jpg \n inflating: Cat_Dog_data/train/dog/dog.1198.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1198.jpg \n inflating: Cat_Dog_data/train/dog/dog.8816.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8816.jpg \n inflating: Cat_Dog_data/train/dog/dog.3943.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3943.jpg \n inflating: Cat_Dog_data/train/dog/dog.2485.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2485.jpg \n inflating: Cat_Dog_data/train/dog/dog.11905.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11905.jpg \n inflating: Cat_Dog_data/train/dog/dog.4792.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4792.jpg \n inflating: Cat_Dog_data/train/dog/dog.814.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.814.jpg \n inflating: Cat_Dog_data/train/dog/dog.6185.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6185.jpg \n inflating: Cat_Dog_data/train/dog/dog.1832.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1832.jpg \n inflating: Cat_Dog_data/train/dog/dog.8143.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8143.jpg \n inflating: Cat_Dog_data/train/dog/dog.7270.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7270.jpg \n inflating: Cat_Dog_data/train/dog/dog.1601.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1601.jpg \n inflating: Cat_Dog_data/train/dog/dog.2308.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2308.jpg \n inflating: Cat_Dog_data/train/dog/dog.5467.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5467.jpg \n inflating: Cat_Dog_data/train/dog/dog.4779.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4779.jpg \n inflating: Cat_Dog_data/train/dog/dog.11050.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11050.jpg \n inflating: Cat_Dog_data/train/dog/dog.627.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.627.jpg \n inflating: Cat_Dog_data/train/dog/dog.3016.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3016.jpg \n inflating: Cat_Dog_data/train/dog/dog.141.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.141.jpg \n inflating: Cat_Dog_data/train/dog/dog.3770.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3770.jpg \n inflating: Cat_Dog_data/train/dog/dog.11736.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11736.jpg \n inflating: Cat_Dog_data/train/dog/dog.5301.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5301.jpg \n inflating: Cat_Dog_data/train/dog/dog.6608.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6608.jpg \n inflating: Cat_Dog_data/train/dog/dog.8625.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8625.jpg \n inflating: Cat_Dog_data/train/dog/dog.7516.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7516.jpg \n inflating: Cat_Dog_data/train/dog/dog.1173.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1173.jpg \n inflating: Cat_Dog_data/train/dog/dog.7502.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7502.jpg \n inflating: Cat_Dog_data/train/dog/dog.3764.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3764.jpg \n inflating: Cat_Dog_data/train/dog/dog.155.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.155.jpg \n inflating: Cat_Dog_data/train/dog/dog.11722.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11722.jpg \n inflating: Cat_Dog_data/train/dog/dog.5315.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5315.jpg \n inflating: Cat_Dog_data/train/dog/dog.5473.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5473.jpg \n inflating: Cat_Dog_data/train/dog/dog.11044.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11044.jpg \n inflating: Cat_Dog_data/train/dog/dog.3002.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3002.jpg \n inflating: Cat_Dog_data/train/dog/dog.633.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.633.jpg \n inflating: Cat_Dog_data/train/dog/dog.8157.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8157.jpg \n inflating: Cat_Dog_data/train/dog/dog.7264.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7264.jpg \n inflating: Cat_Dog_data/train/dog/dog.38.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.38.jpg \n inflating: Cat_Dog_data/train/dog/dog.9249.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9249.jpg \n inflating: Cat_Dog_data/train/dog/dog.1615.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1615.jpg \n inflating: Cat_Dog_data/train/dog/dog.2334.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2334.jpg \n inflating: Cat_Dog_data/train/dog/dog.10372.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10372.jpg \n inflating: Cat_Dog_data/train/dog/dog.4745.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4745.jpg \n inflating: Cat_Dog_data/train/dog/dog.10.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10.jpg \n inflating: Cat_Dog_data/train/dog/dog.6152.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6152.jpg \n inflating: Cat_Dog_data/train/dog/dog.9261.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9261.jpg \n inflating: Cat_Dog_data/train/dog/dog.6634.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6634.jpg \n inflating: Cat_Dog_data/train/dog/dog.9507.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9507.jpg \n inflating: Cat_Dog_data/train/dog/dog.12203.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12203.jpg \n inflating: Cat_Dog_data/train/dog/dog.8619.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8619.jpg \n inflating: Cat_Dog_data/train/dog/dog.4023.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4023.jpg \n inflating: Cat_Dog_data/train/dog/dog.3994.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3994.jpg \n inflating: Cat_Dog_data/train/dog/dog.10414.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10414.jpg \n inflating: Cat_Dog_data/train/dog/dog.2452.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2452.jpg \n inflating: Cat_Dog_data/train/dog/dog.3758.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3758.jpg \n inflating: Cat_Dog_data/train/dog/dog.169.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.169.jpg \n inflating: Cat_Dog_data/train/dog/dog.4037.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4037.jpg \n inflating: Cat_Dog_data/train/dog/dog.3980.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3980.jpg \n inflating: Cat_Dog_data/train/dog/dog.10400.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10400.jpg \n inflating: Cat_Dog_data/train/dog/dog.5329.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5329.jpg \n inflating: Cat_Dog_data/train/dog/dog.2446.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2446.jpg \n inflating: Cat_Dog_data/train/dog/dog.6620.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6620.jpg \n inflating: Cat_Dog_data/train/dog/dog.9513.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9513.jpg \n inflating: Cat_Dog_data/train/dog/dog.12217.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12217.jpg \n inflating: Cat_Dog_data/train/dog/dog.7258.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7258.jpg \n inflating: Cat_Dog_data/train/dog/dog.6146.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6146.jpg \n inflating: Cat_Dog_data/train/dog/dog.9275.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9275.jpg \n inflating: Cat_Dog_data/train/dog/dog.1629.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1629.jpg \n inflating: Cat_Dog_data/train/dog/dog.2320.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2320.jpg \n inflating: Cat_Dog_data/train/dog/dog.4989.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4989.jpg \n inflating: Cat_Dog_data/train/dog/dog.10366.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10366.jpg \n inflating: Cat_Dog_data/train/dog/dog.11078.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11078.jpg \n inflating: Cat_Dog_data/train/dog/dog.4751.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4751.jpg \n inflating: Cat_Dog_data/train/dog/dog.2877.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2877.jpg \n inflating: Cat_Dog_data/train/dog/dog.380.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.380.jpg \n inflating: Cat_Dog_data/train/dog/dog.10831.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10831.jpg \n inflating: Cat_Dog_data/train/dog/dog.9922.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9922.jpg \n inflating: Cat_Dog_data/train/dog/dog.8382.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8382.jpg \n inflating: Cat_Dog_data/train/dog/dog.11291.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11291.jpg \n inflating: Cat_Dog_data/train/dog/dog.11285.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11285.jpg \n inflating: Cat_Dog_data/train/dog/dog.8396.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8396.jpg \n inflating: Cat_Dog_data/train/dog/dog.9088.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9088.jpg \n inflating: Cat_Dog_data/train/dog/dog.9936.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9936.jpg \n inflating: Cat_Dog_data/train/dog/dog.2863.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2863.jpg \n inflating: Cat_Dog_data/train/dog/dog.394.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.394.jpg \n inflating: Cat_Dog_data/train/dog/dog.10825.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10825.jpg \n inflating: Cat_Dog_data/train/dog/dog.7933.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7933.jpg \n inflating: Cat_Dog_data/train/dog/dog.2693.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2693.jpg \n inflating: Cat_Dog_data/train/dog/dog.5842.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5842.jpg \n inflating: Cat_Dog_data/train/dog/dog.6393.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6393.jpg \n inflating: Cat_Dog_data/train/dog/dog.7099.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7099.jpg \n inflating: Cat_Dog_data/train/dog/dog.6387.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6387.jpg \n inflating: Cat_Dog_data/train/dog/dog.5856.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5856.jpg \n inflating: Cat_Dog_data/train/dog/dog.4590.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4590.jpg \n inflating: Cat_Dog_data/train/dog/dog.10819.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10819.jpg \n inflating: Cat_Dog_data/train/dog/dog.2687.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2687.jpg \n inflating: Cat_Dog_data/train/dog/dog.7927.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7927.jpg \n inflating: Cat_Dog_data/train/dog/dog.7714.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7714.jpg \n inflating: Cat_Dog_data/train/dog/dog.8427.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8427.jpg \n inflating: Cat_Dog_data/train/dog/dog.9739.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9739.jpg \n inflating: Cat_Dog_data/train/dog/dog.1365.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1365.jpg \n inflating: Cat_Dog_data/train/dog/dog.5103.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5103.jpg \n inflating: Cat_Dog_data/train/dog/dog.11534.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11534.jpg \n inflating: Cat_Dog_data/train/dog/dog.3572.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3572.jpg \n inflating: Cat_Dog_data/train/dog/dog.425.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.425.jpg \n inflating: Cat_Dog_data/train/dog/dog.3214.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3214.jpg \n inflating: Cat_Dog_data/train/dog/dog.11252.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11252.jpg \n inflating: Cat_Dog_data/train/dog/dog.5665.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5665.jpg \n inflating: Cat_Dog_data/train/dog/dog.1403.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1403.jpg \n inflating: Cat_Dog_data/train/dog/dog.7072.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7072.jpg \n inflating: Cat_Dog_data/train/dog/dog.8341.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8341.jpg \n inflating: Cat_Dog_data/train/dog/dog.1417.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1417.jpg \n inflating: Cat_Dog_data/train/dog/dog.7066.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7066.jpg \n inflating: Cat_Dog_data/train/dog/dog.8355.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8355.jpg \n inflating: Cat_Dog_data/train/dog/dog.431.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.431.jpg \n inflating: Cat_Dog_data/train/dog/dog.11246.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11246.jpg \n inflating: Cat_Dog_data/train/dog/dog.10158.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10158.jpg \n inflating: Cat_Dog_data/train/dog/dog.5671.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5671.jpg \n inflating: Cat_Dog_data/train/dog/dog.2678.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2678.jpg \n inflating: Cat_Dog_data/train/dog/dog.5117.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5117.jpg \n inflating: Cat_Dog_data/train/dog/dog.11520.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11520.jpg \n inflating: Cat_Dog_data/train/dog/dog.4209.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4209.jpg \n inflating: Cat_Dog_data/train/dog/dog.3566.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3566.jpg \n inflating: Cat_Dog_data/train/dog/dog.357.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.357.jpg \n inflating: Cat_Dog_data/train/dog/dog.7700.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7700.jpg \n inflating: Cat_Dog_data/train/dog/dog.12029.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12029.jpg \n inflating: Cat_Dog_data/train/dog/dog.8433.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8433.jpg \n inflating: Cat_Dog_data/train/dog/dog.2650.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2650.jpg \n inflating: Cat_Dog_data/train/dog/dog.10616.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10616.jpg \n inflating: Cat_Dog_data/train/dog/dog.4221.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4221.jpg \n inflating: Cat_Dog_data/train/dog/dog.11508.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11508.jpg \n inflating: Cat_Dog_data/train/dog/dog.2888.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2888.jpg \n inflating: Cat_Dog_data/train/dog/dog.12001.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12001.jpg \n inflating: Cat_Dog_data/train/dog/dog.7728.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7728.jpg \n inflating: Cat_Dog_data/train/dog/dog.9705.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9705.jpg \n inflating: Cat_Dog_data/train/dog/dog.6436.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6436.jpg \n inflating: Cat_Dog_data/train/dog/dog.1359.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1359.jpg \n inflating: Cat_Dog_data/train/dog/dog.9063.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9063.jpg \n inflating: Cat_Dog_data/train/dog/dog.6350.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6350.jpg \n inflating: Cat_Dog_data/train/dog/dog.419.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.419.jpg \n inflating: Cat_Dog_data/train/dog/dog.3228.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3228.jpg \n inflating: Cat_Dog_data/train/dog/dog.4547.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4547.jpg \n inflating: Cat_Dog_data/train/dog/dog.5659.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5659.jpg \n inflating: Cat_Dog_data/train/dog/dog.2136.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2136.jpg \n inflating: Cat_Dog_data/train/dog/dog.5895.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5895.jpg \n inflating: Cat_Dog_data/train/dog/dog.10164.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10164.jpg \n inflating: Cat_Dog_data/train/dog/dog.2122.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2122.jpg \n inflating: Cat_Dog_data/train/dog/dog.9077.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9077.jpg \n inflating: Cat_Dog_data/train/dog/dog.6344.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6344.jpg \n inflating: Cat_Dog_data/train/dog/dog.8369.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8369.jpg \n inflating: Cat_Dog_data/train/dog/dog.12015.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12015.jpg \n inflating: Cat_Dog_data/train/dog/dog.9711.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9711.jpg \n inflating: Cat_Dog_data/train/dog/dog.6422.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6422.jpg \n inflating: Cat_Dog_data/train/dog/dog.2644.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2644.jpg \n inflating: Cat_Dog_data/train/dog/dog.10602.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10602.jpg \n inflating: Cat_Dog_data/train/dog/dog.4235.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4235.jpg \n inflating: Cat_Dog_data/train/dog/dog.10945.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10945.jpg \n inflating: Cat_Dog_data/train/dog/dog.11483.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11483.jpg \n inflating: Cat_Dog_data/train/dog/dog.8590.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8590.jpg \n inflating: Cat_Dog_data/train/dog/dog.9856.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9856.jpg \n inflating: Cat_Dog_data/train/dog/dog.592.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.592.jpg \n inflating: Cat_Dog_data/train/dog/dog.586.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.586.jpg \n inflating: Cat_Dog_data/train/dog/dog.8584.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8584.jpg \n inflating: Cat_Dog_data/train/dog/dog.9842.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9842.jpg \n inflating: Cat_Dog_data/train/dog/dog.10951.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10951.jpg \n inflating: Cat_Dog_data/train/dog/dog.2917.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2917.jpg \n inflating: Cat_Dog_data/train/dog/dog.11497.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11497.jpg \n inflating: Cat_Dog_data/train/dog/dog.7847.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7847.jpg \n inflating: Cat_Dog_data/train/dog/dog.6581.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6581.jpg \n inflating: Cat_Dog_data/train/dog/dog.5088.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5088.jpg \n inflating: Cat_Dog_data/train/dog/dog.10979.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10979.jpg \n inflating: Cat_Dog_data/train/dog/dog.4396.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4396.jpg \n inflating: Cat_Dog_data/train/dog/dog.5936.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5936.jpg \n inflating: Cat_Dog_data/train/dog/dog.2081.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2081.jpg \n inflating: Cat_Dog_data/train/dog/dog.1588.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1588.jpg \n inflating: Cat_Dog_data/train/dog/dog.2095.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2095.jpg \n inflating: Cat_Dog_data/train/dog/dog.4382.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4382.jpg \n inflating: Cat_Dog_data/train/dog/dog.7853.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7853.jpg \n inflating: Cat_Dog_data/train/dog/dog.6595.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6595.jpg \n inflating: Cat_Dog_data/train/dog/dog.1211.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1211.jpg \n inflating: Cat_Dog_data/train/dog/dog.12149.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12149.jpg \n inflating: Cat_Dog_data/train/dog/dog.8553.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8553.jpg \n inflating: Cat_Dog_data/train/dog/dog.9895.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9895.jpg \n inflating: Cat_Dog_data/train/dog/dog.3406.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3406.jpg \n inflating: Cat_Dog_data/train/dog/dog.237.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.237.jpg \n inflating: Cat_Dog_data/train/dog/dog.10986.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10986.jpg \n inflating: Cat_Dog_data/train/dog/dog.11440.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11440.jpg \n inflating: Cat_Dog_data/train/dog/dog.4369.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4369.jpg \n inflating: Cat_Dog_data/train/dog/dog.5077.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5077.jpg \n inflating: Cat_Dog_data/train/dog/dog.2718.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2718.jpg \n inflating: Cat_Dog_data/train/dog/dog.10038.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10038.jpg \n inflating: Cat_Dog_data/train/dog/dog.5711.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5711.jpg \n inflating: Cat_Dog_data/train/dog/dog.11326.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11326.jpg \n inflating: Cat_Dog_data/train/dog/dog.3360.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3360.jpg \n inflating: Cat_Dog_data/train/dog/dog.551.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.551.jpg \n inflating: Cat_Dog_data/train/dog/dog.7106.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7106.jpg \n inflating: Cat_Dog_data/train/dog/dog.8235.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8235.jpg \n inflating: Cat_Dog_data/train/dog/dog.6218.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6218.jpg \n inflating: Cat_Dog_data/train/dog/dog.1577.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1577.jpg \n inflating: Cat_Dog_data/train/dog/dog.7112.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7112.jpg \n inflating: Cat_Dog_data/train/dog/dog.8221.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8221.jpg \n inflating: Cat_Dog_data/train/dog/dog.1563.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1563.jpg \n inflating: Cat_Dog_data/train/dog/dog.5705.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5705.jpg \n inflating: Cat_Dog_data/train/dog/dog.3374.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3374.jpg \n inflating: Cat_Dog_data/train/dog/dog.223.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.223.jpg \n inflating: Cat_Dog_data/train/dog/dog.3412.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3412.jpg \n inflating: Cat_Dog_data/train/dog/dog.10992.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10992.jpg \n inflating: Cat_Dog_data/train/dog/dog.11454.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11454.jpg \n inflating: Cat_Dog_data/train/dog/dog.5063.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5063.jpg \n inflating: Cat_Dog_data/train/dog/dog.1205.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1205.jpg \n inflating: Cat_Dog_data/train/dog/dog.9659.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9659.jpg \n inflating: Cat_Dog_data/train/dog/dog.7674.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7674.jpg \n inflating: Cat_Dog_data/train/dog/dog.8547.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8547.jpg \n inflating: Cat_Dog_data/train/dog/dog.4355.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4355.jpg \n inflating: Cat_Dog_data/train/dog/dog.10762.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10762.jpg \n inflating: Cat_Dog_data/train/dog/dog.2724.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2724.jpg \n inflating: Cat_Dog_data/train/dog/dog.7884.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7884.jpg \n inflating: Cat_Dog_data/train/dog/dog.9671.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9671.jpg \n inflating: Cat_Dog_data/train/dog/dog.6542.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6542.jpg \n inflating: Cat_Dog_data/train/dog/dog.12175.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12175.jpg \n inflating: Cat_Dog_data/train/dog/dog.8209.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8209.jpg \n inflating: Cat_Dog_data/train/dog/dog.9117.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9117.jpg \n inflating: Cat_Dog_data/train/dog/dog.6224.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6224.jpg \n inflating: Cat_Dog_data/train/dog/dog.2042.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2042.jpg \n inflating: Cat_Dog_data/train/dog/dog.10004.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10004.jpg \n inflating: Cat_Dog_data/train/dog/dog.4433.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4433.jpg \n inflating: Cat_Dog_data/train/dog/dog.5739.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5739.jpg \n inflating: Cat_Dog_data/train/dog/dog.4427.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4427.jpg \n inflating: Cat_Dog_data/train/dog/dog.579.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.579.jpg \n inflating: Cat_Dog_data/train/dog/dog.3348.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3348.jpg \n inflating: Cat_Dog_data/train/dog/dog.9103.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9103.jpg \n inflating: Cat_Dog_data/train/dog/dog.6230.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6230.jpg \n inflating: Cat_Dog_data/train/dog/dog.1239.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1239.jpg \n inflating: Cat_Dog_data/train/dog/dog.7890.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7890.jpg \n inflating: Cat_Dog_data/train/dog/dog.9665.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9665.jpg \n inflating: Cat_Dog_data/train/dog/dog.6556.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6556.jpg \n inflating: Cat_Dog_data/train/dog/dog.12161.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12161.jpg \n inflating: Cat_Dog_data/train/dog/dog.7648.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7648.jpg \n inflating: Cat_Dog_data/train/dog/dog.4341.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4341.jpg \n inflating: Cat_Dog_data/train/dog/dog.11468.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11468.jpg \n inflating: Cat_Dog_data/train/dog/dog.10776.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10776.jpg \n inflating: Cat_Dog_data/train/dog/dog.2730.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2730.jpg \n inflating: Cat_Dog_data/train/dog/dog.948.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.948.jpg \n inflating: Cat_Dog_data/train/dog/dog.4816.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4816.jpg \n inflating: Cat_Dog_data/train/dog/dog.790.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.790.jpg \n inflating: Cat_Dog_data/train/dog/dog.8792.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8792.jpg \n inflating: Cat_Dog_data/train/dog/dog.12388.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12388.jpg \n inflating: Cat_Dog_data/train/dog/dog.11681.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11681.jpg \n inflating: Cat_Dog_data/train/dog/dog.11859.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11859.jpg \n inflating: Cat_Dog_data/train/dog/dog.11695.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11695.jpg \n inflating: Cat_Dog_data/train/dog/dog.9498.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9498.jpg \n inflating: Cat_Dog_data/train/dog/dog.6973.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6973.jpg \n inflating: Cat_Dog_data/train/dog/dog.8786.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8786.jpg \n inflating: Cat_Dog_data/train/dog/dog.4802.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4802.jpg \n inflating: Cat_Dog_data/train/dog/dog.784.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.784.jpg \n inflating: Cat_Dog_data/train/dog/dog.974.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.974.jpg \n inflating: Cat_Dog_data/train/dog/dog.4194.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4194.jpg \n inflating: Cat_Dog_data/train/dog/dog.11865.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11865.jpg \n inflating: Cat_Dog_data/train/dog/dog.3823.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3823.jpg \n inflating: Cat_Dog_data/train/dog/dog.6783.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6783.jpg \n inflating: Cat_Dog_data/train/dog/dog.8976.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8976.jpg \n inflating: Cat_Dog_data/train/dog/dog.6797.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6797.jpg \n inflating: Cat_Dog_data/train/dog/dog.8962.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8962.jpg \n inflating: Cat_Dog_data/train/dog/dog.7489.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7489.jpg \n inflating: Cat_Dog_data/train/dog/dog.4180.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4180.jpg \n inflating: Cat_Dog_data/train/dog/dog.11871.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11871.jpg \n inflating: Cat_Dog_data/train/dog/dog.3837.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3837.jpg \n inflating: Cat_Dog_data/train/dog/dog.960.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.960.jpg \n inflating: Cat_Dog_data/train/dog/dog.2297.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2297.jpg \n inflating: Cat_Dog_data/train/dog/dog.3189.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3189.jpg \n inflating: Cat_Dog_data/train/dog/dog.1946.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1946.jpg \n inflating: Cat_Dog_data/train/dog/dog.1775.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1775.jpg \n inflating: Cat_Dog_data/train/dog/dog.9329.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9329.jpg \n inflating: Cat_Dog_data/train/dog/dog.8037.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8037.jpg \n inflating: Cat_Dog_data/train/dog/dog.7304.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7304.jpg \n inflating: Cat_Dog_data/train/dog/dog.3162.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3162.jpg \n inflating: Cat_Dog_data/train/dog/dog.753.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.753.jpg \n inflating: Cat_Dog_data/train/dog/dog.11124.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11124.jpg \n inflating: Cat_Dog_data/train/dog/dog.5513.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5513.jpg \n inflating: Cat_Dog_data/train/dog/dog.5275.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5275.jpg \n inflating: Cat_Dog_data/train/dog/dog.11642.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11642.jpg \n inflating: Cat_Dog_data/train/dog/dog.3604.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3604.jpg \n inflating: Cat_Dog_data/train/dog/dog.8751.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8751.jpg \n inflating: Cat_Dog_data/train/dog/dog.1013.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1013.jpg \n inflating: Cat_Dog_data/train/dog/dog.8989.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8989.jpg \n inflating: Cat_Dog_data/train/dog/dog.8745.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8745.jpg \n inflating: Cat_Dog_data/train/dog/dog.7476.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7476.jpg \n inflating: Cat_Dog_data/train/dog/dog.6768.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6768.jpg \n inflating: Cat_Dog_data/train/dog/dog.1007.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1007.jpg \n inflating: Cat_Dog_data/train/dog/dog.5261.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5261.jpg \n inflating: Cat_Dog_data/train/dog/dog.10548.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10548.jpg \n inflating: Cat_Dog_data/train/dog/dog.11656.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11656.jpg \n inflating: Cat_Dog_data/train/dog/dog.3610.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3610.jpg \n inflating: Cat_Dog_data/train/dog/dog.3176.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3176.jpg \n inflating: Cat_Dog_data/train/dog/dog.4619.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4619.jpg \n inflating: Cat_Dog_data/train/dog/dog.11130.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11130.jpg \n inflating: Cat_Dog_data/train/dog/dog.5507.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5507.jpg \n inflating: Cat_Dog_data/train/dog/dog.1761.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1761.jpg \n inflating: Cat_Dog_data/train/dog/dog.8023.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8023.jpg \n inflating: Cat_Dog_data/train/dog/dog.7310.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7310.jpg \n inflating: Cat_Dog_data/train/dog/dog.4631.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4631.jpg \n inflating: Cat_Dog_data/train/dog/dog.10206.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10206.jpg \n inflating: Cat_Dog_data/train/dog/dog.2240.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2240.jpg \n inflating: Cat_Dog_data/train/dog/dog.1749.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1749.jpg \n inflating: Cat_Dog_data/train/dog/dog.6026.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6026.jpg \n inflating: Cat_Dog_data/train/dog/dog.9315.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9315.jpg \n inflating: Cat_Dog_data/train/dog/dog.12411.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12411.jpg \n inflating: Cat_Dog_data/train/dog/dog.1991.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1991.jpg \n inflating: Cat_Dog_data/train/dog/dog.6998.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6998.jpg \n inflating: Cat_Dog_data/train/dog/dog.12377.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12377.jpg \n inflating: Cat_Dog_data/train/dog/dog.6740.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6740.jpg \n inflating: Cat_Dog_data/train/dog/dog.9473.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9473.jpg \n inflating: Cat_Dog_data/train/dog/dog.2526.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2526.jpg \n inflating: Cat_Dog_data/train/dog/dog.10560.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10560.jpg \n inflating: Cat_Dog_data/train/dog/dog.5249.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5249.jpg \n inflating: Cat_Dog_data/train/dog/dog.3638.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3638.jpg \n inflating: Cat_Dog_data/train/dog/dog.10574.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10574.jpg \n inflating: Cat_Dog_data/train/dog/dog.4143.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4143.jpg \n inflating: Cat_Dog_data/train/dog/dog.12363.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12363.jpg \n inflating: Cat_Dog_data/train/dog/dog.8779.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8779.jpg \n inflating: Cat_Dog_data/train/dog/dog.6754.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6754.jpg \n inflating: Cat_Dog_data/train/dog/dog.9467.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9467.jpg \n inflating: Cat_Dog_data/train/dog/dog.6032.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6032.jpg \n inflating: Cat_Dog_data/train/dog/dog.9301.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9301.jpg \n inflating: Cat_Dog_data/train/dog/dog.12405.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12405.jpg \n inflating: Cat_Dog_data/train/dog/dog.1985.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1985.jpg \n inflating: Cat_Dog_data/train/dog/dog.4625.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4625.jpg \n inflating: Cat_Dog_data/train/dog/dog.10212.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10212.jpg \n inflating: Cat_Dog_data/train/dog/dog.2254.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2254.jpg \n inflating: Cat_Dog_data/train/dog/dog.4155.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4155.jpg \n inflating: Cat_Dog_data/train/dog/dog.10562.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10562.jpg \n inflating: Cat_Dog_data/train/dog/dog.2524.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2524.jpg \n inflating: Cat_Dog_data/train/dog/dog.6742.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6742.jpg \n inflating: Cat_Dog_data/train/dog/dog.9471.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9471.jpg \n inflating: Cat_Dog_data/train/dog/dog.12375.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12375.jpg \n inflating: Cat_Dog_data/train/dog/dog.8009.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8009.jpg \n inflating: Cat_Dog_data/train/dog/dog.1993.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1993.jpg \n inflating: Cat_Dog_data/train/dog/dog.6024.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6024.jpg \n inflating: Cat_Dog_data/train/dog/dog.9317.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9317.jpg \n inflating: Cat_Dog_data/train/dog/dog.2242.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2242.jpg \n inflating: Cat_Dog_data/train/dog/dog.10204.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10204.jpg \n inflating: Cat_Dog_data/train/dog/dog.4633.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4633.jpg \n inflating: Cat_Dog_data/train/dog/dog.2256.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2256.jpg \n inflating: Cat_Dog_data/train/dog/dog.5539.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5539.jpg \n inflating: Cat_Dog_data/train/dog/dog.10210.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10210.jpg \n inflating: Cat_Dog_data/train/dog/dog.4627.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4627.jpg \n inflating: Cat_Dog_data/train/dog/dog.3148.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3148.jpg \n inflating: Cat_Dog_data/train/dog/dog.779.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.779.jpg \n inflating: Cat_Dog_data/train/dog/dog.12407.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12407.jpg \n inflating: Cat_Dog_data/train/dog/dog.1987.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1987.jpg \n inflating: Cat_Dog_data/train/dog/dog.9303.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9303.jpg \n inflating: Cat_Dog_data/train/dog/dog.1039.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1039.jpg \n inflating: Cat_Dog_data/train/dog/dog.6756.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6756.jpg \n inflating: Cat_Dog_data/train/dog/dog.9465.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9465.jpg \n inflating: Cat_Dog_data/train/dog/dog.12361.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12361.jpg \n inflating: Cat_Dog_data/train/dog/dog.7448.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7448.jpg \n inflating: Cat_Dog_data/train/dog/dog.4141.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4141.jpg \n inflating: Cat_Dog_data/train/dog/dog.11668.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11668.jpg \n inflating: Cat_Dog_data/train/dog/dog.10576.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10576.jpg \n inflating: Cat_Dog_data/train/dog/dog.2530.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2530.jpg \n inflating: Cat_Dog_data/train/dog/dog.8753.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8753.jpg \n inflating: Cat_Dog_data/train/dog/dog.7460.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7460.jpg \n inflating: Cat_Dog_data/train/dog/dog.12349.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12349.jpg \n inflating: Cat_Dog_data/train/dog/dog.3606.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3606.jpg \n inflating: Cat_Dog_data/train/dog/dog.11640.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11640.jpg \n inflating: Cat_Dog_data/train/dog/dog.4169.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4169.jpg \n inflating: Cat_Dog_data/train/dog/dog.5277.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5277.jpg \n inflating: Cat_Dog_data/train/dog/dog.11898.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11898.jpg \n inflating: Cat_Dog_data/train/dog/dog.2518.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2518.jpg \n inflating: Cat_Dog_data/train/dog/dog.10238.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10238.jpg \n inflating: Cat_Dog_data/train/dog/dog.989.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.989.jpg \n inflating: Cat_Dog_data/train/dog/dog.11126.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11126.jpg \n inflating: Cat_Dog_data/train/dog/dog.751.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.751.jpg \n inflating: Cat_Dog_data/train/dog/dog.3160.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3160.jpg \n inflating: Cat_Dog_data/train/dog/dog.8035.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8035.jpg \n inflating: Cat_Dog_data/train/dog/dog.7306.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7306.jpg \n inflating: Cat_Dog_data/train/dog/dog.6018.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6018.jpg \n inflating: Cat_Dog_data/train/dog/dog.1777.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1777.jpg \n inflating: Cat_Dog_data/train/dog/dog.8021.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8021.jpg \n inflating: Cat_Dog_data/train/dog/dog.7312.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7312.jpg \n inflating: Cat_Dog_data/train/dog/dog.1763.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1763.jpg \n inflating: Cat_Dog_data/train/dog/dog.11132.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11132.jpg \n inflating: Cat_Dog_data/train/dog/dog.745.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.745.jpg \n inflating: Cat_Dog_data/train/dog/dog.3612.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3612.jpg \n inflating: Cat_Dog_data/train/dog/dog.11654.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11654.jpg \n inflating: Cat_Dog_data/train/dog/dog.5263.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5263.jpg \n inflating: Cat_Dog_data/train/dog/dog.1005.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1005.jpg \n inflating: Cat_Dog_data/train/dog/dog.9459.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9459.jpg \n inflating: Cat_Dog_data/train/dog/dog.8747.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8747.jpg \n inflating: Cat_Dog_data/train/dog/dog.7474.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7474.jpg \n inflating: Cat_Dog_data/train/dog/dog.6959.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6959.jpg \n inflating: Cat_Dog_data/train/dog/dog.8974.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8974.jpg \n inflating: Cat_Dog_data/train/dog/dog.6781.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6781.jpg \n inflating: Cat_Dog_data/train/dog/dog.3821.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3821.jpg \n inflating: Cat_Dog_data/train/dog/dog.5288.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5288.jpg \n inflating: Cat_Dog_data/train/dog/dog.11867.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11867.jpg \n inflating: Cat_Dog_data/train/dog/dog.4196.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4196.jpg \n inflating: Cat_Dog_data/train/dog/dog.2281.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2281.jpg \n inflating: Cat_Dog_data/train/dog/dog.4828.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4828.jpg \n inflating: Cat_Dog_data/train/dog/dog.976.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.976.jpg \n inflating: Cat_Dog_data/train/dog/dog.1788.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1788.jpg \n inflating: Cat_Dog_data/train/dog/dog.1950.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1950.jpg \n inflating: Cat_Dog_data/train/dog/dog.1944.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1944.jpg \n inflating: Cat_Dog_data/train/dog/dog.2295.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2295.jpg \n inflating: Cat_Dog_data/train/dog/dog.962.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.962.jpg \n inflating: Cat_Dog_data/train/dog/dog.3835.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3835.jpg \n inflating: Cat_Dog_data/train/dog/dog.11873.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11873.jpg \n inflating: Cat_Dog_data/train/dog/dog.4182.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4182.jpg \n inflating: Cat_Dog_data/train/dog/dog.8960.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8960.jpg \n inflating: Cat_Dog_data/train/dog/dog.6795.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6795.jpg \n inflating: Cat_Dog_data/train/dog/dog.11683.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11683.jpg \n inflating: Cat_Dog_data/train/dog/dog.8790.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8790.jpg \n inflating: Cat_Dog_data/train/dog/dog.6965.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6965.jpg \n inflating: Cat_Dog_data/train/dog/dog.8948.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8948.jpg \n inflating: Cat_Dog_data/train/dog/dog.792.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.792.jpg \n inflating: Cat_Dog_data/train/dog/dog.4814.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4814.jpg \n inflating: Cat_Dog_data/train/dog/dog.786.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.786.jpg \n inflating: Cat_Dog_data/train/dog/dog.4800.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4800.jpg \n inflating: Cat_Dog_data/train/dog/dog.1978.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1978.jpg \n inflating: Cat_Dog_data/train/dog/dog.6971.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6971.jpg \n inflating: Cat_Dog_data/train/dog/dog.10589.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10589.jpg \n inflating: Cat_Dog_data/train/dog/dog.3809.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3809.jpg \n inflating: Cat_Dog_data/train/dog/dog.11697.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11697.jpg \n inflating: Cat_Dog_data/train/dog/dog.11318.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11318.jpg \n inflating: Cat_Dog_data/train/dog/dog.4431.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4431.jpg \n inflating: Cat_Dog_data/train/dog/dog.10006.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10006.jpg \n inflating: Cat_Dog_data/train/dog/dog.2040.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2040.jpg \n inflating: Cat_Dog_data/train/dog/dog.1549.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1549.jpg \n inflating: Cat_Dog_data/train/dog/dog.9115.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9115.jpg \n inflating: Cat_Dog_data/train/dog/dog.6226.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6226.jpg \n inflating: Cat_Dog_data/train/dog/dog.7138.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7138.jpg \n inflating: Cat_Dog_data/train/dog/dog.12177.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12177.jpg \n inflating: Cat_Dog_data/train/dog/dog.9673.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9673.jpg \n inflating: Cat_Dog_data/train/dog/dog.6540.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6540.jpg \n inflating: Cat_Dog_data/train/dog/dog.7886.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7886.jpg \n inflating: Cat_Dog_data/train/dog/dog.2726.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2726.jpg \n inflating: Cat_Dog_data/train/dog/dog.10760.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10760.jpg \n inflating: Cat_Dog_data/train/dog/dog.5049.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5049.jpg \n inflating: Cat_Dog_data/train/dog/dog.4357.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4357.jpg \n inflating: Cat_Dog_data/train/dog/dog.209.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.209.jpg \n inflating: Cat_Dog_data/train/dog/dog.3438.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3438.jpg \n inflating: Cat_Dog_data/train/dog/dog.10774.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10774.jpg \n inflating: Cat_Dog_data/train/dog/dog.8579.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8579.jpg \n inflating: Cat_Dog_data/train/dog/dog.12163.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12163.jpg \n inflating: Cat_Dog_data/train/dog/dog.9667.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9667.jpg \n inflating: Cat_Dog_data/train/dog/dog.6554.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6554.jpg \n inflating: Cat_Dog_data/train/dog/dog.7892.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7892.jpg \n inflating: Cat_Dog_data/train/dog/dog.9101.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9101.jpg \n inflating: Cat_Dog_data/train/dog/dog.6232.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6232.jpg \n inflating: Cat_Dog_data/train/dog/dog.2054.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2054.jpg \n inflating: Cat_Dog_data/train/dog/dog.1575.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1575.jpg \n inflating: Cat_Dog_data/train/dog/dog.9129.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9129.jpg \n inflating: Cat_Dog_data/train/dog/dog.7104.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7104.jpg \n inflating: Cat_Dog_data/train/dog/dog.8237.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8237.jpg \n inflating: Cat_Dog_data/train/dog/dog.3362.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3362.jpg \n inflating: Cat_Dog_data/train/dog/dog.11324.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11324.jpg \n inflating: Cat_Dog_data/train/dog/dog.5713.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5713.jpg \n inflating: Cat_Dog_data/train/dog/dog.5075.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5075.jpg \n inflating: Cat_Dog_data/train/dog/dog.11442.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11442.jpg \n inflating: Cat_Dog_data/train/dog/dog.235.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.235.jpg \n inflating: Cat_Dog_data/train/dog/dog.3404.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3404.jpg \n inflating: Cat_Dog_data/train/dog/dog.9897.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9897.jpg \n inflating: Cat_Dog_data/train/dog/dog.7662.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7662.jpg \n inflating: Cat_Dog_data/train/dog/dog.8551.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8551.jpg \n inflating: Cat_Dog_data/train/dog/dog.1213.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1213.jpg \n inflating: Cat_Dog_data/train/dog/dog.9883.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9883.jpg \n inflating: Cat_Dog_data/train/dog/dog.7676.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7676.jpg \n inflating: Cat_Dog_data/train/dog/dog.8545.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8545.jpg \n inflating: Cat_Dog_data/train/dog/dog.6568.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6568.jpg \n inflating: Cat_Dog_data/train/dog/dog.1207.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1207.jpg \n inflating: Cat_Dog_data/train/dog/dog.5061.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5061.jpg \n inflating: Cat_Dog_data/train/dog/dog.10748.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10748.jpg \n inflating: Cat_Dog_data/train/dog/dog.11456.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11456.jpg \n inflating: Cat_Dog_data/train/dog/dog.3410.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3410.jpg \n inflating: Cat_Dog_data/train/dog/dog.221.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.221.jpg \n inflating: Cat_Dog_data/train/dog/dog.10990.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10990.jpg \n inflating: Cat_Dog_data/train/dog/dog.3376.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3376.jpg \n inflating: Cat_Dog_data/train/dog/dog.547.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.547.jpg \n inflating: Cat_Dog_data/train/dog/dog.11330.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11330.jpg \n inflating: Cat_Dog_data/train/dog/dog.5707.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5707.jpg \n inflating: Cat_Dog_data/train/dog/dog.2068.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2068.jpg \n inflating: Cat_Dog_data/train/dog/dog.7110.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7110.jpg \n inflating: Cat_Dog_data/train/dog/dog.2083.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2083.jpg \n inflating: Cat_Dog_data/train/dog/dog.5934.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5934.jpg \n inflating: Cat_Dog_data/train/dog/dog.4394.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4394.jpg \n inflating: Cat_Dog_data/train/dog/dog.6583.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6583.jpg \n inflating: Cat_Dog_data/train/dog/dog.7845.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7845.jpg \n inflating: Cat_Dog_data/train/dog/dog.9868.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9868.jpg \n inflating: Cat_Dog_data/train/dog/dog.6597.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6597.jpg \n inflating: Cat_Dog_data/train/dog/dog.7851.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7851.jpg \n inflating: Cat_Dog_data/train/dog/dog.7689.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7689.jpg \n inflating: Cat_Dog_data/train/dog/dog.2929.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2929.jpg \n inflating: Cat_Dog_data/train/dog/dog.2097.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2097.jpg \n inflating: Cat_Dog_data/train/dog/dog.5920.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5920.jpg \n inflating: Cat_Dog_data/train/dog/dog.3389.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3389.jpg \n inflating: Cat_Dog_data/train/dog/dog.590.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.590.jpg \n inflating: Cat_Dog_data/train/dog/dog.5908.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5908.jpg \n inflating: Cat_Dog_data/train/dog/dog.7879.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7879.jpg \n inflating: Cat_Dog_data/train/dog/dog.9854.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9854.jpg \n inflating: Cat_Dog_data/train/dog/dog.12188.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12188.jpg \n inflating: Cat_Dog_data/train/dog/dog.8592.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8592.jpg \n inflating: Cat_Dog_data/train/dog/dog.2901.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2901.jpg \n inflating: Cat_Dog_data/train/dog/dog.11481.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11481.jpg \n inflating: Cat_Dog_data/train/dog/dog.10947.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10947.jpg \n inflating: Cat_Dog_data/train/dog/dog.2915.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2915.jpg \n inflating: Cat_Dog_data/train/dog/dog.11495.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11495.jpg \n inflating: Cat_Dog_data/train/dog/dog.10953.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10953.jpg \n inflating: Cat_Dog_data/train/dog/dog.9698.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9698.jpg \n inflating: Cat_Dog_data/train/dog/dog.9840.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9840.jpg \n inflating: Cat_Dog_data/train/dog/dog.8586.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8586.jpg \n inflating: Cat_Dog_data/train/dog/dog.2134.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2134.jpg \n inflating: Cat_Dog_data/train/dog/dog.10172.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10172.jpg \n inflating: Cat_Dog_data/train/dog/dog.4545.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4545.jpg \n inflating: Cat_Dog_data/train/dog/dog.9061.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9061.jpg \n inflating: Cat_Dog_data/train/dog/dog.6352.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6352.jpg \n inflating: Cat_Dog_data/train/dog/dog.9707.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9707.jpg \n inflating: Cat_Dog_data/train/dog/dog.8419.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8419.jpg \n inflating: Cat_Dog_data/train/dog/dog.4223.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4223.jpg \n inflating: Cat_Dog_data/train/dog/dog.10614.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10614.jpg \n inflating: Cat_Dog_data/train/dog/dog.2652.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2652.jpg \n inflating: Cat_Dog_data/train/dog/dog.369.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.369.jpg \n inflating: Cat_Dog_data/train/dog/dog.4237.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4237.jpg \n inflating: Cat_Dog_data/train/dog/dog.10600.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10600.jpg \n inflating: Cat_Dog_data/train/dog/dog.5129.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5129.jpg \n inflating: Cat_Dog_data/train/dog/dog.9713.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9713.jpg \n inflating: Cat_Dog_data/train/dog/dog.6420.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6420.jpg \n inflating: Cat_Dog_data/train/dog/dog.12017.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12017.jpg \n inflating: Cat_Dog_data/train/dog/dog.7058.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7058.jpg \n inflating: Cat_Dog_data/train/dog/dog.9075.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9075.jpg \n inflating: Cat_Dog_data/train/dog/dog.6346.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6346.jpg \n inflating: Cat_Dog_data/train/dog/dog.1429.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1429.jpg \n inflating: Cat_Dog_data/train/dog/dog.2120.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2120.jpg \n inflating: Cat_Dog_data/train/dog/dog.10166.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10166.jpg \n inflating: Cat_Dog_data/train/dog/dog.4551.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4551.jpg \n inflating: Cat_Dog_data/train/dog/dog.5897.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5897.jpg \n inflating: Cat_Dog_data/train/dog/dog.7070.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7070.jpg \n inflating: Cat_Dog_data/train/dog/dog.8343.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8343.jpg \n inflating: Cat_Dog_data/train/dog/dog.1401.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1401.jpg \n inflating: Cat_Dog_data/train/dog/dog.2108.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2108.jpg \n inflating: Cat_Dog_data/train/dog/dog.5667.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5667.jpg \n inflating: Cat_Dog_data/train/dog/dog.4579.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4579.jpg \n inflating: Cat_Dog_data/train/dog/dog.11250.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11250.jpg \n inflating: Cat_Dog_data/train/dog/dog.427.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.427.jpg \n inflating: Cat_Dog_data/train/dog/dog.3570.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3570.jpg \n inflating: Cat_Dog_data/train/dog/dog.341.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.341.jpg \n inflating: Cat_Dog_data/train/dog/dog.11536.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11536.jpg \n inflating: Cat_Dog_data/train/dog/dog.5101.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5101.jpg \n inflating: Cat_Dog_data/train/dog/dog.6408.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6408.jpg \n inflating: Cat_Dog_data/train/dog/dog.7716.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7716.jpg \n inflating: Cat_Dog_data/train/dog/dog.8425.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8425.jpg \n inflating: Cat_Dog_data/train/dog/dog.1373.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1373.jpg \n inflating: Cat_Dog_data/train/dog/dog.7702.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7702.jpg \n inflating: Cat_Dog_data/train/dog/dog.355.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.355.jpg \n inflating: Cat_Dog_data/train/dog/dog.3564.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3564.jpg \n inflating: Cat_Dog_data/train/dog/dog.11522.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11522.jpg \n inflating: Cat_Dog_data/train/dog/dog.5115.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5115.jpg \n inflating: Cat_Dog_data/train/dog/dog.5673.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5673.jpg \n inflating: Cat_Dog_data/train/dog/dog.11244.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11244.jpg \n inflating: Cat_Dog_data/train/dog/dog.433.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.433.jpg \n inflating: Cat_Dog_data/train/dog/dog.8357.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8357.jpg \n inflating: Cat_Dog_data/train/dog/dog.9049.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9049.jpg \n inflating: Cat_Dog_data/train/dog/dog.1415.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1415.jpg \n inflating: Cat_Dog_data/train/dog/dog.5840.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5840.jpg \n inflating: Cat_Dog_data/train/dog/dog.5698.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5698.jpg \n inflating: Cat_Dog_data/train/dog/dog.2691.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2691.jpg \n inflating: Cat_Dog_data/train/dog/dog.2849.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2849.jpg \n inflating: Cat_Dog_data/train/dog/dog.1398.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1398.jpg \n inflating: Cat_Dog_data/train/dog/dog.7931.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7931.jpg \n inflating: Cat_Dog_data/train/dog/dog.9908.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9908.jpg \n inflating: Cat_Dog_data/train/dog/dog.7925.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7925.jpg \n inflating: Cat_Dog_data/train/dog/dog.2685.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2685.jpg \n inflating: Cat_Dog_data/train/dog/dog.5854.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5854.jpg \n inflating: Cat_Dog_data/train/dog/dog.6385.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6385.jpg \n inflating: Cat_Dog_data/train/dog/dog.11293.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11293.jpg \n inflating: Cat_Dog_data/train/dog/dog.9920.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9920.jpg \n inflating: Cat_Dog_data/train/dog/dog.382.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.382.jpg \n inflating: Cat_Dog_data/train/dog/dog.10833.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10833.jpg \n inflating: Cat_Dog_data/train/dog/dog.2875.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2875.jpg \n inflating: Cat_Dog_data/train/dog/dog.396.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.396.jpg \n inflating: Cat_Dog_data/train/dog/dog.10827.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10827.jpg \n inflating: Cat_Dog_data/train/dog/dog.2861.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2861.jpg \n inflating: Cat_Dog_data/train/dog/dog.9934.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9934.jpg \n inflating: Cat_Dog_data/train/dog/dog.7919.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7919.jpg \n inflating: Cat_Dog_data/train/dog/dog.8394.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8394.jpg \n inflating: Cat_Dog_data/train/dog/dog.11287.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11287.jpg \n inflating: Cat_Dog_data/train/dog/dog.5868.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5868.jpg \n inflating: Cat_Dog_data/train/dog/dog.10199.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10199.jpg \n inflating: Cat_Dog_data/train/dog/dog.2450.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2450.jpg \n inflating: Cat_Dog_data/train/dog/dog.3996.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3996.jpg \n inflating: Cat_Dog_data/train/dog/dog.10416.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10416.jpg \n inflating: Cat_Dog_data/train/dog/dog.4021.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4021.jpg \n inflating: Cat_Dog_data/train/dog/dog.11708.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11708.jpg \n inflating: Cat_Dog_data/train/dog/dog.7528.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7528.jpg \n inflating: Cat_Dog_data/train/dog/dog.6636.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6636.jpg \n inflating: Cat_Dog_data/train/dog/dog.9505.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9505.jpg \n inflating: Cat_Dog_data/train/dog/dog.1159.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1159.jpg \n inflating: Cat_Dog_data/train/dog/dog.6150.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6150.jpg \n inflating: Cat_Dog_data/train/dog/dog.9263.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9263.jpg \n inflating: Cat_Dog_data/train/dog/dog.12.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12.jpg \n inflating: Cat_Dog_data/train/dog/dog.3028.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3028.jpg \n inflating: Cat_Dog_data/train/dog/dog.619.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.619.jpg \n inflating: Cat_Dog_data/train/dog/dog.4747.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4747.jpg \n inflating: Cat_Dog_data/train/dog/dog.5459.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5459.jpg \n inflating: Cat_Dog_data/train/dog/dog.10370.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10370.jpg \n inflating: Cat_Dog_data/train/dog/dog.2336.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2336.jpg \n inflating: Cat_Dog_data/train/dog/dog.4753.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4753.jpg \n inflating: Cat_Dog_data/train/dog/dog.10364.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10364.jpg \n inflating: Cat_Dog_data/train/dog/dog.2322.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2322.jpg \n inflating: Cat_Dog_data/train/dog/dog.9277.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9277.jpg \n inflating: Cat_Dog_data/train/dog/dog.12215.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12215.jpg \n inflating: Cat_Dog_data/train/dog/dog.6622.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6622.jpg \n inflating: Cat_Dog_data/train/dog/dog.9511.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9511.jpg \n inflating: Cat_Dog_data/train/dog/dog.2444.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2444.jpg \n inflating: Cat_Dog_data/train/dog/dog.3982.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3982.jpg \n inflating: Cat_Dog_data/train/dog/dog.10402.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10402.jpg \n inflating: Cat_Dog_data/train/dog/dog.4035.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4035.jpg \n inflating: Cat_Dog_data/train/dog/dog.8627.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8627.jpg \n inflating: Cat_Dog_data/train/dog/dog.7514.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7514.jpg \n inflating: Cat_Dog_data/train/dog/dog.9539.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9539.jpg \n inflating: Cat_Dog_data/train/dog/dog.1165.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1165.jpg \n inflating: Cat_Dog_data/train/dog/dog.5303.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5303.jpg \n inflating: Cat_Dog_data/train/dog/dog.11734.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11734.jpg \n inflating: Cat_Dog_data/train/dog/dog.3772.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3772.jpg \n inflating: Cat_Dog_data/train/dog/dog.625.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.625.jpg \n inflating: Cat_Dog_data/train/dog/dog.11052.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11052.jpg \n inflating: Cat_Dog_data/train/dog/dog.5465.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5465.jpg \n inflating: Cat_Dog_data/train/dog/dog.1603.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1603.jpg \n inflating: Cat_Dog_data/train/dog/dog.8141.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8141.jpg \n inflating: Cat_Dog_data/train/dog/dog.1617.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1617.jpg \n inflating: Cat_Dog_data/train/dog/dog.6178.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6178.jpg \n inflating: Cat_Dog_data/train/dog/dog.8155.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8155.jpg \n inflating: Cat_Dog_data/train/dog/dog.7266.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7266.jpg \n inflating: Cat_Dog_data/train/dog/dog.631.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.631.jpg \n inflating: Cat_Dog_data/train/dog/dog.3000.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3000.jpg \n inflating: Cat_Dog_data/train/dog/dog.11046.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11046.jpg \n inflating: Cat_Dog_data/train/dog/dog.10358.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10358.jpg \n inflating: Cat_Dog_data/train/dog/dog.5471.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5471.jpg \n inflating: Cat_Dog_data/train/dog/dog.2478.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2478.jpg \n inflating: Cat_Dog_data/train/dog/dog.5317.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5317.jpg \n inflating: Cat_Dog_data/train/dog/dog.11720.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11720.jpg \n inflating: Cat_Dog_data/train/dog/dog.4009.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4009.jpg \n inflating: Cat_Dog_data/train/dog/dog.157.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.157.jpg \n inflating: Cat_Dog_data/train/dog/dog.3766.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3766.jpg \n inflating: Cat_Dog_data/train/dog/dog.7500.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7500.jpg \n inflating: Cat_Dog_data/train/dog/dog.12229.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12229.jpg \n inflating: Cat_Dog_data/train/dog/dog.8800.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8800.jpg \n inflating: Cat_Dog_data/train/dog/dog.2493.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2493.jpg \n inflating: Cat_Dog_data/train/dog/dog.11913.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11913.jpg \n inflating: Cat_Dog_data/train/dog/dog.3955.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3955.jpg \n inflating: Cat_Dog_data/train/dog/dog.802.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.802.jpg \n inflating: Cat_Dog_data/train/dog/dog.4784.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4784.jpg \n inflating: Cat_Dog_data/train/dog/dog.6193.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6193.jpg \n inflating: Cat_Dog_data/train/dog/dog.1830.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1830.jpg \n inflating: Cat_Dog_data/train/dog/dog.6187.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6187.jpg \n inflating: Cat_Dog_data/train/dog/dog.816.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.816.jpg \n inflating: Cat_Dog_data/train/dog/dog.4948.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4948.jpg \n inflating: Cat_Dog_data/train/dog/dog.4790.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4790.jpg \n inflating: Cat_Dog_data/train/dog/dog.3799.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3799.jpg \n inflating: Cat_Dog_data/train/dog/dog.2487.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2487.jpg \n inflating: Cat_Dog_data/train/dog/dog.11907.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11907.jpg \n inflating: Cat_Dog_data/train/dog/dog.3941.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3941.jpg \n inflating: Cat_Dog_data/train/dog/dog.8814.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8814.jpg \n inflating: Cat_Dog_data/train/dog/dog.180.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.180.jpg \n inflating: Cat_Dog_data/train/dog/dog.3969.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3969.jpg \n inflating: Cat_Dog_data/train/dog/dog.8182.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8182.jpg \n inflating: Cat_Dog_data/train/dog/dog.1818.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1818.jpg \n inflating: Cat_Dog_data/train/dog/dog.4960.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4960.jpg \n inflating: Cat_Dog_data/train/dog/dog.11091.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11091.jpg \n inflating: Cat_Dog_data/train/dog/dog.4974.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4974.jpg \n inflating: Cat_Dog_data/train/dog/dog.11085.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11085.jpg \n inflating: Cat_Dog_data/train/dog/dog.8196.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8196.jpg \n inflating: Cat_Dog_data/train/dog/dog.9288.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9288.jpg \n inflating: Cat_Dog_data/train/dog/dog.8828.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8828.jpg \n inflating: Cat_Dog_data/train/dog/dog.6805.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6805.jpg \n inflating: Cat_Dog_data/train/dog/dog.194.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.194.jpg \n inflating: Cat_Dog_data/train/dog/dog.9289.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9289.jpg \n inflating: Cat_Dog_data/train/dog/dog.8197.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8197.jpg \n inflating: Cat_Dog_data/train/dog/dog.11084.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11084.jpg \n inflating: Cat_Dog_data/train/dog/dog.4975.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4975.jpg \n inflating: Cat_Dog_data/train/dog/dog.195.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.195.jpg \n inflating: Cat_Dog_data/train/dog/dog.6804.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6804.jpg \n inflating: Cat_Dog_data/train/dog/dog.8829.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8829.jpg \n inflating: Cat_Dog_data/train/dog/dog.6810.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6810.jpg \n inflating: Cat_Dog_data/train/dog/dog.3968.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3968.jpg \n inflating: Cat_Dog_data/train/dog/dog.181.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.181.jpg \n inflating: Cat_Dog_data/train/dog/dog.11090.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11090.jpg \n inflating: Cat_Dog_data/train/dog/dog.4961.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4961.jpg \n inflating: Cat_Dog_data/train/dog/dog.8183.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8183.jpg \n inflating: Cat_Dog_data/train/dog/dog.1819.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1819.jpg \n inflating: Cat_Dog_data/train/dog/dog.4791.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4791.jpg \n inflating: Cat_Dog_data/train/dog/dog.4949.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4949.jpg \n inflating: Cat_Dog_data/train/dog/dog.817.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.817.jpg \n inflating: Cat_Dog_data/train/dog/dog.6186.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6186.jpg \n inflating: Cat_Dog_data/train/dog/dog.7298.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7298.jpg \n inflating: Cat_Dog_data/train/dog/dog.6838.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6838.jpg \n inflating: Cat_Dog_data/train/dog/dog.8815.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8815.jpg \n inflating: Cat_Dog_data/train/dog/dog.3940.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3940.jpg \n inflating: Cat_Dog_data/train/dog/dog.11906.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11906.jpg \n inflating: Cat_Dog_data/train/dog/dog.2486.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2486.jpg \n inflating: Cat_Dog_data/train/dog/dog.3954.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3954.jpg \n inflating: Cat_Dog_data/train/dog/dog.11912.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11912.jpg \n inflating: Cat_Dog_data/train/dog/dog.2492.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2492.jpg \n inflating: Cat_Dog_data/train/dog/dog.8801.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8801.jpg \n inflating: Cat_Dog_data/train/dog/dog.6192.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6192.jpg \n inflating: Cat_Dog_data/train/dog/dog.1825.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1825.jpg \n inflating: Cat_Dog_data/train/dog/dog.4785.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4785.jpg \n inflating: Cat_Dog_data/train/dog/dog.803.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.803.jpg \n inflating: Cat_Dog_data/train/dog/dog.5470.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5470.jpg \n inflating: Cat_Dog_data/train/dog/dog.10359.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10359.jpg \n inflating: Cat_Dog_data/train/dog/dog.11047.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11047.jpg \n inflating: Cat_Dog_data/train/dog/dog.3001.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3001.jpg \n inflating: Cat_Dog_data/train/dog/dog.630.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.630.jpg \n inflating: Cat_Dog_data/train/dog/dog.7267.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7267.jpg \n inflating: Cat_Dog_data/train/dog/dog.8154.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8154.jpg \n inflating: Cat_Dog_data/train/dog/dog.6179.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6179.jpg \n inflating: Cat_Dog_data/train/dog/dog.1616.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1616.jpg \n inflating: Cat_Dog_data/train/dog/dog.1170.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1170.jpg \n inflating: Cat_Dog_data/train/dog/dog.12228.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12228.jpg \n inflating: Cat_Dog_data/train/dog/dog.7501.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7501.jpg \n inflating: Cat_Dog_data/train/dog/dog.8632.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8632.jpg \n inflating: Cat_Dog_data/train/dog/dog.3767.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3767.jpg \n inflating: Cat_Dog_data/train/dog/dog.156.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.156.jpg \n inflating: Cat_Dog_data/train/dog/dog.4008.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4008.jpg \n inflating: Cat_Dog_data/train/dog/dog.11721.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11721.jpg \n inflating: Cat_Dog_data/train/dog/dog.5316.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5316.jpg \n inflating: Cat_Dog_data/train/dog/dog.2479.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2479.jpg \n inflating: Cat_Dog_data/train/dog/dog.142.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.142.jpg \n inflating: Cat_Dog_data/train/dog/dog.3773.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3773.jpg \n inflating: Cat_Dog_data/train/dog/dog.11735.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11735.jpg \n inflating: Cat_Dog_data/train/dog/dog.5302.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5302.jpg \n inflating: Cat_Dog_data/train/dog/dog.1164.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1164.jpg \n inflating: Cat_Dog_data/train/dog/dog.9538.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9538.jpg \n inflating: Cat_Dog_data/train/dog/dog.7515.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7515.jpg \n inflating: Cat_Dog_data/train/dog/dog.8626.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8626.jpg \n inflating: Cat_Dog_data/train/dog/dog.7273.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7273.jpg \n inflating: Cat_Dog_data/train/dog/dog.8140.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8140.jpg \n inflating: Cat_Dog_data/train/dog/dog.1602.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1602.jpg \n inflating: Cat_Dog_data/train/dog/dog.5464.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5464.jpg \n inflating: Cat_Dog_data/train/dog/dog.11053.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11053.jpg \n inflating: Cat_Dog_data/train/dog/dog.624.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.624.jpg \n inflating: Cat_Dog_data/train/dog/dog.8168.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8168.jpg \n inflating: Cat_Dog_data/train/dog/dog.9276.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9276.jpg \n inflating: Cat_Dog_data/train/dog/dog.6145.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6145.jpg \n inflating: Cat_Dog_data/train/dog/dog.2323.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2323.jpg \n inflating: Cat_Dog_data/train/dog/dog.10365.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10365.jpg \n inflating: Cat_Dog_data/train/dog/dog.4752.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4752.jpg \n inflating: Cat_Dog_data/train/dog/dog.4034.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4034.jpg \n inflating: Cat_Dog_data/train/dog/dog.10403.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10403.jpg \n inflating: Cat_Dog_data/train/dog/dog.3983.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3983.jpg \n inflating: Cat_Dog_data/train/dog/dog.2445.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2445.jpg \n inflating: Cat_Dog_data/train/dog/dog.9510.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9510.jpg \n inflating: Cat_Dog_data/train/dog/dog.6623.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6623.jpg \n inflating: Cat_Dog_data/train/dog/dog.12214.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12214.jpg \n inflating: Cat_Dog_data/train/dog/dog.1158.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1158.jpg \n inflating: Cat_Dog_data/train/dog/dog.9504.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9504.jpg \n inflating: Cat_Dog_data/train/dog/dog.6637.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6637.jpg \n inflating: Cat_Dog_data/train/dog/dog.7529.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7529.jpg \n inflating: Cat_Dog_data/train/dog/dog.12200.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12200.jpg \n inflating: Cat_Dog_data/train/dog/dog.11709.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11709.jpg \n inflating: Cat_Dog_data/train/dog/dog.4020.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4020.jpg \n inflating: Cat_Dog_data/train/dog/dog.10417.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10417.jpg \n inflating: Cat_Dog_data/train/dog/dog.3997.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3997.jpg \n inflating: Cat_Dog_data/train/dog/dog.2451.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2451.jpg \n inflating: Cat_Dog_data/train/dog/dog.2337.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2337.jpg \n inflating: Cat_Dog_data/train/dog/dog.10371.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10371.jpg \n inflating: Cat_Dog_data/train/dog/dog.5458.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5458.jpg \n inflating: Cat_Dog_data/train/dog/dog.4746.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4746.jpg \n inflating: Cat_Dog_data/train/dog/dog.618.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.618.jpg \n inflating: Cat_Dog_data/train/dog/dog.3029.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3029.jpg \n inflating: Cat_Dog_data/train/dog/dog.13.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.13.jpg \n inflating: Cat_Dog_data/train/dog/dog.9262.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9262.jpg \n inflating: Cat_Dog_data/train/dog/dog.6151.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6151.jpg \n inflating: Cat_Dog_data/train/dog/dog.7918.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7918.jpg \n inflating: Cat_Dog_data/train/dog/dog.9935.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9935.jpg \n inflating: Cat_Dog_data/train/dog/dog.2860.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2860.jpg \n inflating: Cat_Dog_data/train/dog/dog.10826.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10826.jpg \n inflating: Cat_Dog_data/train/dog/dog.397.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.397.jpg \n inflating: Cat_Dog_data/train/dog/dog.5869.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5869.jpg \n inflating: Cat_Dog_data/train/dog/dog.11286.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11286.jpg \n inflating: Cat_Dog_data/train/dog/dog.8395.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8395.jpg \n inflating: Cat_Dog_data/train/dog/dog.8381.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8381.jpg \n inflating: Cat_Dog_data/train/dog/dog.11292.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11292.jpg \n inflating: Cat_Dog_data/train/dog/dog.2874.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2874.jpg \n inflating: Cat_Dog_data/train/dog/dog.10832.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10832.jpg \n inflating: Cat_Dog_data/train/dog/dog.383.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.383.jpg \n inflating: Cat_Dog_data/train/dog/dog.9921.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9921.jpg \n inflating: Cat_Dog_data/train/dog/dog.2684.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2684.jpg \n inflating: Cat_Dog_data/train/dog/dog.7924.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7924.jpg \n inflating: Cat_Dog_data/train/dog/dog.9909.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9909.jpg \n inflating: Cat_Dog_data/train/dog/dog.6384.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6384.jpg \n inflating: Cat_Dog_data/train/dog/dog.5855.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5855.jpg \n inflating: Cat_Dog_data/train/dog/dog.4593.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4593.jpg \n inflating: Cat_Dog_data/train/dog/dog.5841.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5841.jpg \n inflating: Cat_Dog_data/train/dog/dog.4587.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4587.jpg \n inflating: Cat_Dog_data/train/dog/dog.7930.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7930.jpg \n inflating: Cat_Dog_data/train/dog/dog.1399.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1399.jpg \n inflating: Cat_Dog_data/train/dog/dog.2848.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2848.jpg \n inflating: Cat_Dog_data/train/dog/dog.2690.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2690.jpg \n inflating: Cat_Dog_data/train/dog/dog.5114.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5114.jpg \n inflating: Cat_Dog_data/train/dog/dog.11523.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11523.jpg \n inflating: Cat_Dog_data/train/dog/dog.3565.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3565.jpg \n inflating: Cat_Dog_data/train/dog/dog.354.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.354.jpg \n inflating: Cat_Dog_data/train/dog/dog.8430.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8430.jpg \n inflating: Cat_Dog_data/train/dog/dog.7703.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7703.jpg \n inflating: Cat_Dog_data/train/dog/dog.1372.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1372.jpg \n inflating: Cat_Dog_data/train/dog/dog.1414.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1414.jpg \n inflating: Cat_Dog_data/train/dog/dog.9048.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9048.jpg \n inflating: Cat_Dog_data/train/dog/dog.8356.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8356.jpg \n inflating: Cat_Dog_data/train/dog/dog.3203.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3203.jpg \n inflating: Cat_Dog_data/train/dog/dog.432.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.432.jpg \n inflating: Cat_Dog_data/train/dog/dog.11245.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11245.jpg \n inflating: Cat_Dog_data/train/dog/dog.5672.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5672.jpg \n inflating: Cat_Dog_data/train/dog/dog.426.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.426.jpg \n inflating: Cat_Dog_data/train/dog/dog.3217.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3217.jpg \n inflating: Cat_Dog_data/train/dog/dog.11251.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11251.jpg \n inflating: Cat_Dog_data/train/dog/dog.4578.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4578.jpg \n inflating: Cat_Dog_data/train/dog/dog.5666.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5666.jpg \n inflating: Cat_Dog_data/train/dog/dog.2109.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2109.jpg \n inflating: Cat_Dog_data/train/dog/dog.1400.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1400.jpg \n inflating: Cat_Dog_data/train/dog/dog.8342.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8342.jpg \n inflating: Cat_Dog_data/train/dog/dog.7071.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7071.jpg \n inflating: Cat_Dog_data/train/dog/dog.8424.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8424.jpg \n inflating: Cat_Dog_data/train/dog/dog.7717.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7717.jpg \n inflating: Cat_Dog_data/train/dog/dog.6409.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6409.jpg \n inflating: Cat_Dog_data/train/dog/dog.1366.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1366.jpg \n inflating: Cat_Dog_data/train/dog/dog.10629.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10629.jpg \n inflating: Cat_Dog_data/train/dog/dog.5100.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5100.jpg \n inflating: Cat_Dog_data/train/dog/dog.11537.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11537.jpg \n inflating: Cat_Dog_data/train/dog/dog.340.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.340.jpg \n inflating: Cat_Dog_data/train/dog/dog.3571.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3571.jpg \n inflating: Cat_Dog_data/train/dog/dog.12016.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12016.jpg \n inflating: Cat_Dog_data/train/dog/dog.6421.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6421.jpg \n inflating: Cat_Dog_data/train/dog/dog.9712.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9712.jpg \n inflating: Cat_Dog_data/train/dog/dog.2647.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2647.jpg \n inflating: Cat_Dog_data/train/dog/dog.5128.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5128.jpg \n inflating: Cat_Dog_data/train/dog/dog.4236.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4236.jpg \n inflating: Cat_Dog_data/train/dog/dog.3559.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3559.jpg \n inflating: Cat_Dog_data/train/dog/dog.368.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.368.jpg \n inflating: Cat_Dog_data/train/dog/dog.5896.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5896.jpg \n inflating: Cat_Dog_data/train/dog/dog.11279.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11279.jpg \n inflating: Cat_Dog_data/train/dog/dog.10167.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10167.jpg \n inflating: Cat_Dog_data/train/dog/dog.2121.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2121.jpg \n inflating: Cat_Dog_data/train/dog/dog.1428.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1428.jpg \n inflating: Cat_Dog_data/train/dog/dog.6347.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6347.jpg \n inflating: Cat_Dog_data/train/dog/dog.9074.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9074.jpg \n inflating: Cat_Dog_data/train/dog/dog.7059.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7059.jpg \n inflating: Cat_Dog_data/train/dog/dog.6353.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6353.jpg \n inflating: Cat_Dog_data/train/dog/dog.9060.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9060.jpg \n inflating: Cat_Dog_data/train/dog/dog.5882.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5882.jpg \n inflating: Cat_Dog_data/train/dog/dog.4544.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4544.jpg \n inflating: Cat_Dog_data/train/dog/dog.10173.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10173.jpg \n inflating: Cat_Dog_data/train/dog/dog.2135.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2135.jpg \n inflating: Cat_Dog_data/train/dog/dog.10615.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10615.jpg \n inflating: Cat_Dog_data/train/dog/dog.4222.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4222.jpg \n inflating: Cat_Dog_data/train/dog/dog.12002.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12002.jpg \n inflating: Cat_Dog_data/train/dog/dog.8418.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8418.jpg \n inflating: Cat_Dog_data/train/dog/dog.6435.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6435.jpg \n inflating: Cat_Dog_data/train/dog/dog.9706.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9706.jpg \n inflating: Cat_Dog_data/train/dog/dog.8587.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8587.jpg \n inflating: Cat_Dog_data/train/dog/dog.9841.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9841.jpg \n inflating: Cat_Dog_data/train/dog/dog.9699.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9699.jpg \n inflating: Cat_Dog_data/train/dog/dog.10952.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10952.jpg \n inflating: Cat_Dog_data/train/dog/dog.11494.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11494.jpg \n inflating: Cat_Dog_data/train/dog/dog.2914.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2914.jpg \n inflating: Cat_Dog_data/train/dog/dog.585.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.585.jpg \n inflating: Cat_Dog_data/train/dog/dog.5909.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5909.jpg \n inflating: Cat_Dog_data/train/dog/dog.591.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.591.jpg \n inflating: Cat_Dog_data/train/dog/dog.10946.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10946.jpg \n inflating: Cat_Dog_data/train/dog/dog.11480.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11480.jpg \n inflating: Cat_Dog_data/train/dog/dog.2900.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2900.jpg \n inflating: Cat_Dog_data/train/dog/dog.8593.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8593.jpg \n inflating: Cat_Dog_data/train/dog/dog.12189.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12189.jpg \n inflating: Cat_Dog_data/train/dog/dog.9855.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9855.jpg \n inflating: Cat_Dog_data/train/dog/dog.7878.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7878.jpg \n inflating: Cat_Dog_data/train/dog/dog.2928.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2928.jpg \n inflating: Cat_Dog_data/train/dog/dog.4381.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4381.jpg \n inflating: Cat_Dog_data/train/dog/dog.7688.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7688.jpg \n inflating: Cat_Dog_data/train/dog/dog.7850.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7850.jpg \n inflating: Cat_Dog_data/train/dog/dog.6596.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6596.jpg \n inflating: Cat_Dog_data/train/dog/dog.3388.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3388.jpg \n inflating: Cat_Dog_data/train/dog/dog.5921.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5921.jpg \n inflating: Cat_Dog_data/train/dog/dog.2096.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2096.jpg \n inflating: Cat_Dog_data/train/dog/dog.5935.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5935.jpg \n inflating: Cat_Dog_data/train/dog/dog.7844.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7844.jpg \n inflating: Cat_Dog_data/train/dog/dog.6582.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6582.jpg \n inflating: Cat_Dog_data/train/dog/dog.4395.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4395.jpg \n inflating: Cat_Dog_data/train/dog/dog.10991.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10991.jpg \n inflating: Cat_Dog_data/train/dog/dog.220.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.220.jpg \n inflating: Cat_Dog_data/train/dog/dog.3411.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3411.jpg \n inflating: Cat_Dog_data/train/dog/dog.11457.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11457.jpg \n inflating: Cat_Dog_data/train/dog/dog.10749.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10749.jpg \n inflating: Cat_Dog_data/train/dog/dog.5060.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5060.jpg \n inflating: Cat_Dog_data/train/dog/dog.1206.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1206.jpg \n inflating: Cat_Dog_data/train/dog/dog.6569.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6569.jpg \n inflating: Cat_Dog_data/train/dog/dog.8544.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8544.jpg \n inflating: Cat_Dog_data/train/dog/dog.7677.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7677.jpg \n inflating: Cat_Dog_data/train/dog/dog.9882.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9882.jpg \n inflating: Cat_Dog_data/train/dog/dog.7111.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7111.jpg \n inflating: Cat_Dog_data/train/dog/dog.1560.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1560.jpg \n inflating: Cat_Dog_data/train/dog/dog.5706.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5706.jpg \n inflating: Cat_Dog_data/train/dog/dog.11331.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11331.jpg \n inflating: Cat_Dog_data/train/dog/dog.4418.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4418.jpg \n inflating: Cat_Dog_data/train/dog/dog.546.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.546.jpg \n inflating: Cat_Dog_data/train/dog/dog.3377.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3377.jpg \n inflating: Cat_Dog_data/train/dog/dog.5712.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5712.jpg \n inflating: Cat_Dog_data/train/dog/dog.11325.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11325.jpg \n inflating: Cat_Dog_data/train/dog/dog.3363.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3363.jpg \n inflating: Cat_Dog_data/train/dog/dog.552.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.552.jpg \n inflating: Cat_Dog_data/train/dog/dog.8236.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8236.jpg \n inflating: Cat_Dog_data/train/dog/dog.7105.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7105.jpg \n inflating: Cat_Dog_data/train/dog/dog.9128.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9128.jpg \n inflating: Cat_Dog_data/train/dog/dog.1574.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1574.jpg \n inflating: Cat_Dog_data/train/dog/dog.1212.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1212.jpg \n inflating: Cat_Dog_data/train/dog/dog.8550.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8550.jpg \n inflating: Cat_Dog_data/train/dog/dog.7663.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7663.jpg \n inflating: Cat_Dog_data/train/dog/dog.9896.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9896.jpg \n inflating: Cat_Dog_data/train/dog/dog.10985.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10985.jpg \n inflating: Cat_Dog_data/train/dog/dog.3405.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3405.jpg \n inflating: Cat_Dog_data/train/dog/dog.234.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.234.jpg \n inflating: Cat_Dog_data/train/dog/dog.11443.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11443.jpg \n inflating: Cat_Dog_data/train/dog/dog.5074.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5074.jpg \n inflating: Cat_Dog_data/train/dog/dog.7893.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7893.jpg \n inflating: Cat_Dog_data/train/dog/dog.6555.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6555.jpg \n inflating: Cat_Dog_data/train/dog/dog.9666.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9666.jpg \n inflating: Cat_Dog_data/train/dog/dog.12162.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12162.jpg \n inflating: Cat_Dog_data/train/dog/dog.8578.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8578.jpg \n inflating: Cat_Dog_data/train/dog/dog.10775.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10775.jpg \n inflating: Cat_Dog_data/train/dog/dog.2733.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2733.jpg \n inflating: Cat_Dog_data/train/dog/dog.2055.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2055.jpg \n inflating: Cat_Dog_data/train/dog/dog.10013.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10013.jpg \n inflating: Cat_Dog_data/train/dog/dog.4424.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4424.jpg \n inflating: Cat_Dog_data/train/dog/dog.6233.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6233.jpg \n inflating: Cat_Dog_data/train/dog/dog.9100.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9100.jpg \n inflating: Cat_Dog_data/train/dog/dog.7139.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7139.jpg \n inflating: Cat_Dog_data/train/dog/dog.9114.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9114.jpg \n inflating: Cat_Dog_data/train/dog/dog.1548.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1548.jpg \n inflating: Cat_Dog_data/train/dog/dog.2041.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2041.jpg \n inflating: Cat_Dog_data/train/dog/dog.10007.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10007.jpg \n inflating: Cat_Dog_data/train/dog/dog.4430.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4430.jpg \n inflating: Cat_Dog_data/train/dog/dog.11319.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11319.jpg \n inflating: Cat_Dog_data/train/dog/dog.3439.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3439.jpg \n inflating: Cat_Dog_data/train/dog/dog.208.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.208.jpg \n inflating: Cat_Dog_data/train/dog/dog.4356.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4356.jpg \n inflating: Cat_Dog_data/train/dog/dog.5048.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5048.jpg \n inflating: Cat_Dog_data/train/dog/dog.10761.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10761.jpg \n inflating: Cat_Dog_data/train/dog/dog.2727.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2727.jpg \n inflating: Cat_Dog_data/train/dog/dog.7887.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7887.jpg \n inflating: Cat_Dog_data/train/dog/dog.6541.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6541.jpg \n inflating: Cat_Dog_data/train/dog/dog.12176.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12176.jpg \n inflating: Cat_Dog_data/train/dog/dog.1979.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1979.jpg \n inflating: Cat_Dog_data/train/dog/dog.4801.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4801.jpg \n inflating: Cat_Dog_data/train/dog/dog.787.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.787.jpg \n inflating: Cat_Dog_data/train/dog/dog.11696.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11696.jpg \n inflating: Cat_Dog_data/train/dog/dog.3808.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3808.jpg \n inflating: Cat_Dog_data/train/dog/dog.10588.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10588.jpg \n inflating: Cat_Dog_data/train/dog/dog.8785.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8785.jpg \n inflating: Cat_Dog_data/train/dog/dog.6964.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6964.jpg \n inflating: Cat_Dog_data/train/dog/dog.8791.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8791.jpg \n inflating: Cat_Dog_data/train/dog/dog.11682.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11682.jpg \n inflating: Cat_Dog_data/train/dog/dog.4815.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4815.jpg \n inflating: Cat_Dog_data/train/dog/dog.793.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.793.jpg \n inflating: Cat_Dog_data/train/dog/dog.963.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.963.jpg \n inflating: Cat_Dog_data/train/dog/dog.1945.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1945.jpg \n inflating: Cat_Dog_data/train/dog/dog.8961.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8961.jpg \n inflating: Cat_Dog_data/train/dog/dog.4183.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4183.jpg \n inflating: Cat_Dog_data/train/dog/dog.11872.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11872.jpg \n inflating: Cat_Dog_data/train/dog/dog.3834.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3834.jpg \n inflating: Cat_Dog_data/train/dog/dog.11866.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11866.jpg \n inflating: Cat_Dog_data/train/dog/dog.5289.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5289.jpg \n inflating: Cat_Dog_data/train/dog/dog.3820.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3820.jpg \n inflating: Cat_Dog_data/train/dog/dog.6780.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6780.jpg \n inflating: Cat_Dog_data/train/dog/dog.8975.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8975.jpg \n inflating: Cat_Dog_data/train/dog/dog.6958.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6958.jpg \n inflating: Cat_Dog_data/train/dog/dog.1951.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1951.jpg \n inflating: Cat_Dog_data/train/dog/dog.1789.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1789.jpg \n inflating: Cat_Dog_data/train/dog/dog.977.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.977.jpg \n inflating: Cat_Dog_data/train/dog/dog.4829.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4829.jpg \n inflating: Cat_Dog_data/train/dog/dog.744.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.744.jpg \n inflating: Cat_Dog_data/train/dog/dog.3175.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3175.jpg \n inflating: Cat_Dog_data/train/dog/dog.5504.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5504.jpg \n inflating: Cat_Dog_data/train/dog/dog.1762.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1762.jpg \n inflating: Cat_Dog_data/train/dog/dog.7313.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7313.jpg \n inflating: Cat_Dog_data/train/dog/dog.8020.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8020.jpg \n inflating: Cat_Dog_data/train/dog/dog.7475.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7475.jpg \n inflating: Cat_Dog_data/train/dog/dog.8746.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8746.jpg \n inflating: Cat_Dog_data/train/dog/dog.9458.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9458.jpg \n inflating: Cat_Dog_data/train/dog/dog.1004.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1004.jpg \n inflating: Cat_Dog_data/train/dog/dog.5262.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5262.jpg \n inflating: Cat_Dog_data/train/dog/dog.2519.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2519.jpg \n inflating: Cat_Dog_data/train/dog/dog.5276.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5276.jpg \n inflating: Cat_Dog_data/train/dog/dog.11641.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11641.jpg \n inflating: Cat_Dog_data/train/dog/dog.3607.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3607.jpg \n inflating: Cat_Dog_data/train/dog/dog.12348.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12348.jpg \n inflating: Cat_Dog_data/train/dog/dog.8752.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8752.jpg \n inflating: Cat_Dog_data/train/dog/dog.1010.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1010.jpg \n inflating: Cat_Dog_data/train/dog/dog.1776.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1776.jpg \n inflating: Cat_Dog_data/train/dog/dog.6019.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6019.jpg \n inflating: Cat_Dog_data/train/dog/dog.8034.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8034.jpg \n inflating: Cat_Dog_data/train/dog/dog.3161.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3161.jpg \n inflating: Cat_Dog_data/train/dog/dog.750.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.750.jpg \n inflating: Cat_Dog_data/train/dog/dog.11127.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11127.jpg \n inflating: Cat_Dog_data/train/dog/dog.988.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.988.jpg \n inflating: Cat_Dog_data/train/dog/dog.5510.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5510.jpg \n inflating: Cat_Dog_data/train/dog/dog.9302.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9302.jpg \n inflating: Cat_Dog_data/train/dog/dog.6031.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6031.jpg \n inflating: Cat_Dog_data/train/dog/dog.1986.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1986.jpg \n inflating: Cat_Dog_data/train/dog/dog.12406.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12406.jpg \n inflating: Cat_Dog_data/train/dog/dog.778.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.778.jpg \n inflating: Cat_Dog_data/train/dog/dog.3149.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.3149.jpg \n inflating: Cat_Dog_data/train/dog/dog.4626.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4626.jpg \n inflating: Cat_Dog_data/train/dog/dog.10211.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10211.jpg \n inflating: Cat_Dog_data/train/dog/dog.5538.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.5538.jpg \n inflating: Cat_Dog_data/train/dog/dog.2531.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2531.jpg \n inflating: Cat_Dog_data/train/dog/dog.11669.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.11669.jpg \n inflating: Cat_Dog_data/train/dog/dog.4140.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4140.jpg \n inflating: Cat_Dog_data/train/dog/dog.7449.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.7449.jpg \n inflating: Cat_Dog_data/train/dog/dog.12360.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12360.jpg \n inflating: Cat_Dog_data/train/dog/dog.9464.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9464.jpg \n inflating: Cat_Dog_data/train/dog/dog.6757.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6757.jpg \n inflating: Cat_Dog_data/train/dog/dog.1038.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1038.jpg \n inflating: Cat_Dog_data/train/dog/dog.12374.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12374.jpg \n inflating: Cat_Dog_data/train/dog/dog.9470.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9470.jpg \n inflating: Cat_Dog_data/train/dog/dog.6743.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6743.jpg \n inflating: Cat_Dog_data/train/dog/dog.2525.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2525.jpg \n inflating: Cat_Dog_data/train/dog/dog.10563.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10563.jpg \n inflating: Cat_Dog_data/train/dog/dog.4154.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4154.jpg \n inflating: Cat_Dog_data/train/dog/dog.4632.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.4632.jpg \n inflating: Cat_Dog_data/train/dog/dog.10205.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.10205.jpg \n inflating: Cat_Dog_data/train/dog/dog.2243.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.2243.jpg \n inflating: Cat_Dog_data/train/dog/dog.9316.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.9316.jpg \n inflating: Cat_Dog_data/train/dog/dog.6025.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.6025.jpg \n inflating: Cat_Dog_data/train/dog/dog.8008.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.8008.jpg \n inflating: Cat_Dog_data/train/dog/dog.1992.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.1992.jpg \n inflating: Cat_Dog_data/train/dog/dog.12412.jpg \n inflating: __MACOSX/Cat_Dog_data/train/dog/._dog.12412.jpg \n"
],
[
"data_dir = 'Cat_Dog_data'\n\n# TODO: Define transforms for the training data and testing data\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\ntest_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n# Pass transforms in here, then run the next cell to see how the transforms look\ntrain_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\ntest_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)\n\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=64)",
"_____no_output_____"
]
],
[
[
"We can load in a model such as [DenseNet](http://pytorch.org/docs/0.3.0/torchvision/models.html#id5). Let's print out the model architecture so we can see what's going on.",
"_____no_output_____"
]
],
[
[
"model = models.densenet121(pretrained=True)\nmodel",
"_____no_output_____"
]
],
[
[
"This model is built out of two main parts, the features and the classifier. The features part is a stack of convolutional layers and overall works as a feature detector that can be fed into a classifier. The classifier part is a single fully-connected layer `(classifier): Linear(in_features=1024, out_features=1000)`. This layer was trained on the ImageNet dataset, so it won't work for our specific problem. That means we need to replace the classifier, but the features will work perfectly on their own. In general, I think about pre-trained networks as amazingly good feature detectors that can be used as the input for simple feed-forward classifiers.",
"_____no_output_____"
]
],
[
[
"# Freeze parameters so we don't backprop through them\nfor param in model.parameters():\n param.requires_grad = False\n\nfrom collections import OrderedDict\nclassifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(1024, 500)),\n ('relu', nn.ReLU()),\n ('fc2', nn.Linear(500, 2)),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n \nmodel.classifier = classifier",
"_____no_output_____"
]
],
[
[
"With our model built, we need to train the classifier. However, now we're using a **really deep** neural network. If you try to train this on a CPU like normal, it will take a long, long time. Instead, we're going to use the GPU to do the calculations. The linear algebra computations are done in parallel on the GPU leading to 100x increased training speeds. It's also possible to train on multiple GPUs, further decreasing training time.\n\nPyTorch, along with pretty much every other deep learning framework, uses [CUDA](https://developer.nvidia.com/cuda-zone) to efficiently compute the forward and backwards passes on the GPU. In PyTorch, you move your model parameters and other tensors to the GPU memory using `model.to('cuda')`. You can move them back from the GPU with `model.to('cpu')` which you'll commonly do when you need to operate on the network output outside of PyTorch. As a demonstration of the increased speed, I'll compare how long it takes to perform a forward and backward pass with and without a GPU.",
"_____no_output_____"
]
],
[
[
"import time",
"_____no_output_____"
],
[
"for device in ['cpu', 'cuda']:\n\n criterion = nn.NLLLoss()\n # Only train the classifier parameters, feature parameters are frozen\n optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)\n\n model.to(device)\n\n for ii, (inputs, labels) in enumerate(trainloader):\n\n # Move input and label tensors to the GPU\n inputs, labels = inputs.to(device), labels.to(device)\n\n start = time.time()\n\n outputs = model.forward(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n if ii==3:\n break\n \n print(f\"Device = {device}; Time per batch: {(time.time() - start)/3:.3f} seconds\")",
"Device = cpu; Time per batch: 4.035 seconds\nDevice = cuda; Time per batch: 0.008 seconds\n"
]
],
[
[
"You can write device agnostic code which will automatically use CUDA if it's enabled like so:\n```python\n# at beginning of the script\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n...\n\n# then whenever you get a new Tensor or Module\n# this won't copy if they are already on the desired device\ninput = data.to(device)\nmodel = MyModule(...).to(device)\n```\n\nFrom here, I'll let you finish training the model. The process is the same as before except now your model is much more powerful. You should get better than 95% accuracy easily.\n\n>**Exercise:** Train a pretrained models to classify the cat and dog images. Continue with the DenseNet model, or try ResNet, it's also a good model to try out first. Make sure you are only training the classifier and the parameters for the features part are frozen.",
"_____no_output_____"
]
],
[
[
"## TODO: Use a pretrained model to classify the cat and dog images",
"_____no_output_____"
],
[
"sum([p.numel() for p in model.parameters()])",
"_____no_output_____"
],
[
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nmodel = models.densenet121(pretrained=True)\n\n# Freeze parameters so we don't backprop through them\nfor param in model.parameters():\n param.requires_grad = False\n \nmodel.classifier = nn.Sequential(nn.Linear(1024, 256),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(256, 2),\n nn.LogSoftmax(dim=1))\n\ncriterion = nn.NLLLoss()\n\n# Only train the classifier parameters, feature parameters are frozen\noptimizer = optim.Adam(model.classifier.parameters(), lr=0.003)\nmodel.to(device)\n\nepochs = 1\nsteps = 0\nrunning_loss = 0\nprint_every = 5\n\ntrain_losses, test_losses = [], []\nfor e in range(epochs):\n running_loss = 0\n model.train()\n for images, labels in trainloader:\n steps += 1\n images, labels = images.to(device), labels.to(device)\n optimizer.zero_grad()\n log_ps = model(images)\n loss = criterion(log_ps, labels)\n loss.backward()\n optimizer.step()\n running_loss += loss.item()\n if steps % print_every == 0:\n test_loss = 0\n accuracy = 0\n model.eval()\n # Turn off gradients for validation, saves memory and computations\n with torch.no_grad():\n for images, labels in testloader:\n images, labels = images.to(device), labels.to(device)\n log_ps = model(images)\n test_loss += criterion(log_ps, labels)\n \n ps = torch.exp(log_ps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n \n train_losses.append(running_loss/len(trainloader))\n test_losses.append(test_loss/len(testloader))\n\n print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(running_loss/len(trainloader)),\n \"Test Loss: {:.3f}.. \".format(test_loss/len(testloader)),\n \"Test Accuracy: {:.3f}\".format(accuracy/len(testloader)))",
"Epoch: 1/1.. Training Loss: 0.016.. Test Loss: 0.522.. Test Accuracy: 0.548\nEpoch: 1/1.. Training Loss: 0.023.. Test Loss: 0.237.. Test Accuracy: 0.971\nEpoch: 1/1.. Training Loss: 0.027.. Test Loss: 0.145.. Test Accuracy: 0.973\nEpoch: 1/1.. Training Loss: 0.030.. Test Loss: 0.109.. Test Accuracy: 0.964\nEpoch: 1/1.. Training Loss: 0.033.. Test Loss: 0.081.. Test Accuracy: 0.976\nEpoch: 1/1.. Training Loss: 0.035.. Test Loss: 0.054.. Test Accuracy: 0.983\nEpoch: 1/1.. Training Loss: 0.037.. Test Loss: 0.048.. Test Accuracy: 0.983\nEpoch: 1/1.. Training Loss: 0.039.. Test Loss: 0.043.. Test Accuracy: 0.984\nEpoch: 1/1.. Training Loss: 0.040.. Test Loss: 0.039.. Test Accuracy: 0.986\nEpoch: 1/1.. Training Loss: 0.042.. Test Loss: 0.037.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.043.. Test Loss: 0.036.. Test Accuracy: 0.986\nEpoch: 1/1.. Training Loss: 0.044.. Test Loss: 0.039.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.045.. Test Loss: 0.043.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.046.. Test Loss: 0.034.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.048.. Test Loss: 0.039.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.050.. Test Loss: 0.031.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.051.. Test Loss: 0.030.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.052.. Test Loss: 0.051.. Test Accuracy: 0.983\nEpoch: 1/1.. Training Loss: 0.055.. Test Loss: 0.030.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.056.. Test Loss: 0.032.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.057.. Test Loss: 0.033.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.058.. Test Loss: 0.030.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.060.. Test Loss: 0.030.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.061.. Test Loss: 0.030.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.062.. Test Loss: 0.033.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.063.. Test Loss: 0.034.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.065.. Test Loss: 0.041.. Test Accuracy: 0.985\nEpoch: 1/1.. Training Loss: 0.066.. Test Loss: 0.030.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.068.. Test Loss: 0.035.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.070.. Test Loss: 0.031.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.072.. Test Loss: 0.027.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.074.. Test Loss: 0.038.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.075.. Test Loss: 0.041.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.077.. Test Loss: 0.030.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.079.. Test Loss: 0.026.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.080.. Test Loss: 0.043.. Test Accuracy: 0.986\nEpoch: 1/1.. Training Loss: 0.082.. Test Loss: 0.032.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.083.. Test Loss: 0.027.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.085.. Test Loss: 0.046.. Test Accuracy: 0.984\nEpoch: 1/1.. Training Loss: 0.087.. Test Loss: 0.028.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.088.. Test Loss: 0.035.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.089.. Test Loss: 0.034.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.091.. Test Loss: 0.028.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.093.. Test Loss: 0.032.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.094.. Test Loss: 0.027.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.096.. Test Loss: 0.035.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.097.. Test Loss: 0.028.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.099.. Test Loss: 0.029.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.101.. Test Loss: 0.031.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.102.. Test Loss: 0.029.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.103.. Test Loss: 0.029.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.106.. Test Loss: 0.028.. Test Accuracy: 0.990\nEpoch: 1/1.. Training Loss: 0.107.. Test Loss: 0.030.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.108.. Test Loss: 0.028.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.109.. Test Loss: 0.028.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.110.. Test Loss: 0.027.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.112.. Test Loss: 0.027.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.113.. Test Loss: 0.027.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.114.. Test Loss: 0.032.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.116.. Test Loss: 0.029.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.117.. Test Loss: 0.037.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.119.. Test Loss: 0.031.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.120.. Test Loss: 0.040.. Test Accuracy: 0.986\nEpoch: 1/1.. Training Loss: 0.122.. Test Loss: 0.028.. Test Accuracy: 0.988\nEpoch: 1/1.. Training Loss: 0.124.. Test Loss: 0.028.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.125.. Test Loss: 0.030.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.127.. Test Loss: 0.038.. Test Accuracy: 0.987\nEpoch: 1/1.. Training Loss: 0.128.. Test Loss: 0.029.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.130.. Test Loss: 0.028.. Test Accuracy: 0.989\nEpoch: 1/1.. Training Loss: 0.131.. Test Loss: 0.032.. Test Accuracy: 0.989\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e78915f0e21218f08624b1c42c5a48f8bccd89a8 | 927 | ipynb | Jupyter Notebook | examples/gallery/demos/bokeh/energy_sankey.ipynb | jsignell/holoviews | 4f9fd27367f23c3d067d176f638ec82e4b9ec8f0 | [
"BSD-3-Clause"
] | null | null | null | examples/gallery/demos/bokeh/energy_sankey.ipynb | jsignell/holoviews | 4f9fd27367f23c3d067d176f638ec82e4b9ec8f0 | [
"BSD-3-Clause"
] | null | null | null | examples/gallery/demos/bokeh/energy_sankey.ipynb | jsignell/holoviews | 4f9fd27367f23c3d067d176f638ec82e4b9ec8f0 | [
"BSD-3-Clause"
] | 1 | 2021-10-31T05:26:08.000Z | 2021-10-31T05:26:08.000Z | 15.982759 | 58 | 0.486516 | [
[
[
"import pandas as pd\nimport holoviews as hv\n\nhv.extension('bokeh')",
"_____no_output_____"
]
],
[
[
"## Declare data",
"_____no_output_____"
]
],
[
[
"edges = pd.read_csv('../../../assets/energy.csv')\nedges.head(5)",
"_____no_output_____"
]
],
[
[
"## Plot",
"_____no_output_____"
]
],
[
[
"hv.Sankey(edges).options(label_position='left')",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e789183b27c0046d5c1ccd45befecc88853af0df | 188,652 | ipynb | Jupyter Notebook | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 | ce0f0c997103f958db1f50c0f728a44ce9a28d75 | [
"Apache-2.0"
] | 21,043 | 2019-01-08T04:18:17.000Z | 2022-03-31T23:48:26.000Z | 12_custom_models_and_training_with_tensorflow.ipynb | learn2free/handson-ml2 | accd5ec24665ca4c55b0d9d616b16a89a773edf5 | [
"Apache-2.0"
] | 543 | 2019-02-12T12:27:31.000Z | 2022-03-31T09:19:56.000Z | 12_custom_models_and_training_with_tensorflow.ipynb | learn2free/handson-ml2 | accd5ec24665ca4c55b0d9d616b16a89a773edf5 | [
"Apache-2.0"
] | 10,215 | 2019-01-08T13:36:56.000Z | 2022-03-31T21:55:40.000Z | 29.38047 | 21,236 | 0.555547 | [
[
[
"**Chapter 12 – Custom Models and Training with TensorFlow**",
"_____no_output_____"
],
[
"_This notebook contains all the sample code in chapter 12._",
"_____no_output_____"
],
[
"<table align=\"left\">\n <td>\n <a href=\"https://colab.research.google.com/github/ageron/handson-ml2/blob/master/12_custom_models_and_training_with_tensorflow.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://kaggle.com/kernels/welcome?src=https://github.com/ageron/handson-ml2/blob/master/12_custom_models_and_training_with_tensorflow.ipynb\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" /></a>\n </td>\n</table>",
"_____no_output_____"
],
[
"# Setup",
"_____no_output_____"
],
[
"First, let's import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures. We also check that Python 3.5 or later is installed (although Python 2.x may work, it is deprecated so we strongly recommend you use Python 3 instead), as well as Scikit-Learn ≥0.20 and TensorFlow ≥2.0.",
"_____no_output_____"
]
],
[
[
"# Python ≥3.5 is required\nimport sys\nassert sys.version_info >= (3, 5)\n\n# Scikit-Learn ≥0.20 is required\nimport sklearn\nassert sklearn.__version__ >= \"0.20\"\n\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\n\n# TensorFlow ≥2.4 is required in this notebook\n# Earlier 2.x versions will mostly work the same, but with a few bugs\nimport tensorflow as tf\nfrom tensorflow import keras\nassert tf.__version__ >= \"2.4\"\n\n# Common imports\nimport numpy as np\nimport os\n\n# to make this notebook's output stable across runs\nnp.random.seed(42)\ntf.random.set_seed(42)\n\n# To plot pretty figures\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n\n# Where to save the figures\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"deep\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\nos.makedirs(IMAGES_PATH, exist_ok=True)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)",
"_____no_output_____"
]
],
[
[
"## Tensors and operations",
"_____no_output_____"
],
[
"### Tensors",
"_____no_output_____"
]
],
[
[
"tf.constant([[1., 2., 3.], [4., 5., 6.]]) # matrix",
"_____no_output_____"
],
[
"tf.constant(42) # scalar",
"_____no_output_____"
],
[
"t = tf.constant([[1., 2., 3.], [4., 5., 6.]])\nt",
"_____no_output_____"
],
[
"t.shape",
"_____no_output_____"
],
[
"t.dtype",
"_____no_output_____"
]
],
[
[
"### Indexing",
"_____no_output_____"
]
],
[
[
"t[:, 1:]",
"_____no_output_____"
],
[
"t[..., 1, tf.newaxis]",
"_____no_output_____"
]
],
[
[
"### Ops",
"_____no_output_____"
]
],
[
[
"t + 10",
"_____no_output_____"
],
[
"tf.square(t)",
"_____no_output_____"
],
[
"t @ tf.transpose(t)",
"_____no_output_____"
]
],
[
[
"### Using `keras.backend`",
"_____no_output_____"
]
],
[
[
"from tensorflow import keras\nK = keras.backend\nK.square(K.transpose(t)) + 10",
"_____no_output_____"
]
],
[
[
"### From/To NumPy",
"_____no_output_____"
]
],
[
[
"a = np.array([2., 4., 5.])\ntf.constant(a)",
"_____no_output_____"
],
[
"t.numpy()",
"_____no_output_____"
],
[
"np.array(t)",
"_____no_output_____"
],
[
"tf.square(a)",
"_____no_output_____"
],
[
"np.square(t)",
"_____no_output_____"
]
],
[
[
"### Conflicting Types",
"_____no_output_____"
]
],
[
[
"try:\n tf.constant(2.0) + tf.constant(40)\nexcept tf.errors.InvalidArgumentError as ex:\n print(ex)",
"cannot compute AddV2 as input #1(zero-based) was expected to be a float tensor but is a int32 tensor [Op:AddV2]\n"
],
[
"try:\n tf.constant(2.0) + tf.constant(40., dtype=tf.float64)\nexcept tf.errors.InvalidArgumentError as ex:\n print(ex)",
"cannot compute AddV2 as input #1(zero-based) was expected to be a float tensor but is a double tensor [Op:AddV2]\n"
],
[
"t2 = tf.constant(40., dtype=tf.float64)\ntf.constant(2.0) + tf.cast(t2, tf.float32)",
"_____no_output_____"
]
],
[
[
"### Strings",
"_____no_output_____"
]
],
[
[
"tf.constant(b\"hello world\")",
"_____no_output_____"
],
[
"tf.constant(\"café\")",
"_____no_output_____"
],
[
"u = tf.constant([ord(c) for c in \"café\"])\nu",
"_____no_output_____"
],
[
"b = tf.strings.unicode_encode(u, \"UTF-8\")\ntf.strings.length(b, unit=\"UTF8_CHAR\")",
"_____no_output_____"
],
[
"tf.strings.unicode_decode(b, \"UTF-8\")",
"_____no_output_____"
]
],
[
[
"### String arrays",
"_____no_output_____"
]
],
[
[
"p = tf.constant([\"Café\", \"Coffee\", \"caffè\", \"咖啡\"])",
"_____no_output_____"
],
[
"tf.strings.length(p, unit=\"UTF8_CHAR\")",
"_____no_output_____"
],
[
"r = tf.strings.unicode_decode(p, \"UTF8\")\nr",
"_____no_output_____"
],
[
"print(r)",
"<tf.RaggedTensor [[67, 97, 102, 233], [67, 111, 102, 102, 101, 101], [99, 97, 102, 102, 232], [21654, 21857]]>\n"
]
],
[
[
"### Ragged tensors",
"_____no_output_____"
]
],
[
[
"print(r[1])",
"tf.Tensor([ 67 111 102 102 101 101], shape=(6,), dtype=int32)\n"
],
[
"print(r[1:3])",
"<tf.RaggedTensor [[67, 111, 102, 102, 101, 101], [99, 97, 102, 102, 232]]>\n"
],
[
"r2 = tf.ragged.constant([[65, 66], [], [67]])\nprint(tf.concat([r, r2], axis=0))",
"<tf.RaggedTensor [[67, 97, 102, 233], [67, 111, 102, 102, 101, 101], [99, 97, 102, 102, 232], [21654, 21857], [65, 66], [], [67]]>\n"
],
[
"r3 = tf.ragged.constant([[68, 69, 70], [71], [], [72, 73]])\nprint(tf.concat([r, r3], axis=1))",
"<tf.RaggedTensor [[67, 97, 102, 233, 68, 69, 70], [67, 111, 102, 102, 101, 101, 71], [99, 97, 102, 102, 232], [21654, 21857, 72, 73]]>\n"
],
[
"tf.strings.unicode_encode(r3, \"UTF-8\")",
"_____no_output_____"
],
[
"r.to_tensor()",
"_____no_output_____"
]
],
[
[
"### Sparse tensors",
"_____no_output_____"
]
],
[
[
"s = tf.SparseTensor(indices=[[0, 1], [1, 0], [2, 3]],\n values=[1., 2., 3.],\n dense_shape=[3, 4])",
"_____no_output_____"
],
[
"print(s)",
"SparseTensor(indices=tf.Tensor(\n[[0 1]\n [1 0]\n [2 3]], shape=(3, 2), dtype=int64), values=tf.Tensor([1. 2. 3.], shape=(3,), dtype=float32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))\n"
],
[
"tf.sparse.to_dense(s)",
"_____no_output_____"
],
[
"s2 = s * 2.0",
"_____no_output_____"
],
[
"try:\n s3 = s + 1.\nexcept TypeError as ex:\n print(ex)",
"unsupported operand type(s) for +: 'SparseTensor' and 'float'\n"
],
[
"s4 = tf.constant([[10., 20.], [30., 40.], [50., 60.], [70., 80.]])\ntf.sparse.sparse_dense_matmul(s, s4)",
"_____no_output_____"
],
[
"s5 = tf.SparseTensor(indices=[[0, 2], [0, 1]],\n values=[1., 2.],\n dense_shape=[3, 4])\nprint(s5)",
"SparseTensor(indices=tf.Tensor(\n[[0 2]\n [0 1]], shape=(2, 2), dtype=int64), values=tf.Tensor([1. 2.], shape=(2,), dtype=float32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))\n"
],
[
"try:\n tf.sparse.to_dense(s5)\nexcept tf.errors.InvalidArgumentError as ex:\n print(ex)",
"indices[1] = [0,1] is out of order. Many sparse ops require sorted indices.\n Use `tf.sparse.reorder` to create a correctly ordered copy.\n\n [Op:SparseToDense]\n"
],
[
"s6 = tf.sparse.reorder(s5)\ntf.sparse.to_dense(s6)",
"_____no_output_____"
]
],
[
[
"### Sets",
"_____no_output_____"
]
],
[
[
"set1 = tf.constant([[2, 3, 5, 7], [7, 9, 0, 0]])\nset2 = tf.constant([[4, 5, 6], [9, 10, 0]])\ntf.sparse.to_dense(tf.sets.union(set1, set2))",
"_____no_output_____"
],
[
"tf.sparse.to_dense(tf.sets.difference(set1, set2))",
"_____no_output_____"
],
[
"tf.sparse.to_dense(tf.sets.intersection(set1, set2))",
"_____no_output_____"
]
],
[
[
"### Variables",
"_____no_output_____"
]
],
[
[
"v = tf.Variable([[1., 2., 3.], [4., 5., 6.]])",
"_____no_output_____"
],
[
"v.assign(2 * v)",
"_____no_output_____"
],
[
"v[0, 1].assign(42)",
"_____no_output_____"
],
[
"v[:, 2].assign([0., 1.])",
"_____no_output_____"
],
[
"try:\n v[1] = [7., 8., 9.]\nexcept TypeError as ex:\n print(ex)",
"'ResourceVariable' object does not support item assignment\n"
],
[
"v.scatter_nd_update(indices=[[0, 0], [1, 2]],\n updates=[100., 200.])",
"_____no_output_____"
],
[
"sparse_delta = tf.IndexedSlices(values=[[1., 2., 3.], [4., 5., 6.]],\n indices=[1, 0])\nv.scatter_update(sparse_delta)",
"_____no_output_____"
]
],
[
[
"### Tensor Arrays",
"_____no_output_____"
]
],
[
[
"array = tf.TensorArray(dtype=tf.float32, size=3)\narray = array.write(0, tf.constant([1., 2.]))\narray = array.write(1, tf.constant([3., 10.]))\narray = array.write(2, tf.constant([5., 7.]))",
"_____no_output_____"
],
[
"array.read(1)",
"_____no_output_____"
],
[
"array.stack()",
"_____no_output_____"
],
[
"mean, variance = tf.nn.moments(array.stack(), axes=0)\nmean",
"_____no_output_____"
],
[
"variance",
"_____no_output_____"
]
],
[
[
"## Custom loss function",
"_____no_output_____"
],
[
"Let's start by loading and preparing the California housing dataset. We first load it, then split it into a training set, a validation set and a test set, and finally we scale it:",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import fetch_california_housing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nhousing = fetch_california_housing()\nX_train_full, X_test, y_train_full, y_test = train_test_split(\n housing.data, housing.target.reshape(-1, 1), random_state=42)\nX_train, X_valid, y_train, y_valid = train_test_split(\n X_train_full, y_train_full, random_state=42)\n\nscaler = StandardScaler()\nX_train_scaled = scaler.fit_transform(X_train)\nX_valid_scaled = scaler.transform(X_valid)\nX_test_scaled = scaler.transform(X_test)",
"_____no_output_____"
],
[
"def huber_fn(y_true, y_pred):\n error = y_true - y_pred\n is_small_error = tf.abs(error) < 1\n squared_loss = tf.square(error) / 2\n linear_loss = tf.abs(error) - 0.5\n return tf.where(is_small_error, squared_loss, linear_loss)",
"_____no_output_____"
],
[
"plt.figure(figsize=(8, 3.5))\nz = np.linspace(-4, 4, 200)\nplt.plot(z, huber_fn(0, z), \"b-\", linewidth=2, label=\"huber($z$)\")\nplt.plot(z, z**2 / 2, \"b:\", linewidth=1, label=r\"$\\frac{1}{2}z^2$\")\nplt.plot([-1, -1], [0, huber_fn(0., -1.)], \"r--\")\nplt.plot([1, 1], [0, huber_fn(0., 1.)], \"r--\")\nplt.gca().axhline(y=0, color='k')\nplt.gca().axvline(x=0, color='k')\nplt.axis([-4, 4, 0, 4])\nplt.grid(True)\nplt.xlabel(\"$z$\")\nplt.legend(fontsize=14)\nplt.title(\"Huber loss\", fontsize=14)\nplt.show()",
"_____no_output_____"
],
[
"input_shape = X_train.shape[1:]\n\nmodel = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"selu\", kernel_initializer=\"lecun_normal\",\n input_shape=input_shape),\n keras.layers.Dense(1),\n])",
"_____no_output_____"
],
[
"model.compile(loss=huber_fn, optimizer=\"nadam\", metrics=[\"mae\"])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 2ms/step - loss: 1.0443 - mae: 1.4660 - val_loss: 0.2862 - val_mae: 0.5866\nEpoch 2/2\n363/363 [==============================] - 0s 737us/step - loss: 0.2379 - mae: 0.5407 - val_loss: 0.2382 - val_mae: 0.5281\n"
]
],
[
[
"## Saving/Loading Models with Custom Objects",
"_____no_output_____"
]
],
[
[
"model.save(\"my_model_with_a_custom_loss.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\"my_model_with_a_custom_loss.h5\",\n custom_objects={\"huber_fn\": huber_fn})",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 970us/step - loss: 0.2054 - mae: 0.4982 - val_loss: 0.2209 - val_mae: 0.5050\nEpoch 2/2\n363/363 [==============================] - 0s 769us/step - loss: 0.1999 - mae: 0.4900 - val_loss: 0.2127 - val_mae: 0.4986\n"
],
[
"def create_huber(threshold=1.0):\n def huber_fn(y_true, y_pred):\n error = y_true - y_pred\n is_small_error = tf.abs(error) < threshold\n squared_loss = tf.square(error) / 2\n linear_loss = threshold * tf.abs(error) - threshold**2 / 2\n return tf.where(is_small_error, squared_loss, linear_loss)\n return huber_fn",
"_____no_output_____"
],
[
"model.compile(loss=create_huber(2.0), optimizer=\"nadam\", metrics=[\"mae\"])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 1ms/step - loss: 0.2318 - mae: 0.4979 - val_loss: 0.2540 - val_mae: 0.4907\nEpoch 2/2\n363/363 [==============================] - 0s 749us/step - loss: 0.2309 - mae: 0.4960 - val_loss: 0.2372 - val_mae: 0.4879\n"
],
[
"model.save(\"my_model_with_a_custom_loss_threshold_2.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\"my_model_with_a_custom_loss_threshold_2.h5\",\n custom_objects={\"huber_fn\": create_huber(2.0)})",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 1ms/step - loss: 0.2147 - mae: 0.4800 - val_loss: 0.2133 - val_mae: 0.4654\nEpoch 2/2\n363/363 [==============================] - 0s 763us/step - loss: 0.2119 - mae: 0.4762 - val_loss: 0.1992 - val_mae: 0.4643\n"
],
[
"class HuberLoss(keras.losses.Loss):\n def __init__(self, threshold=1.0, **kwargs):\n self.threshold = threshold\n super().__init__(**kwargs)\n def call(self, y_true, y_pred):\n error = y_true - y_pred\n is_small_error = tf.abs(error) < self.threshold\n squared_loss = tf.square(error) / 2\n linear_loss = self.threshold * tf.abs(error) - self.threshold**2 / 2\n return tf.where(is_small_error, squared_loss, linear_loss)\n def get_config(self):\n base_config = super().get_config()\n return {**base_config, \"threshold\": self.threshold}",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"selu\", kernel_initializer=\"lecun_normal\",\n input_shape=input_shape),\n keras.layers.Dense(1),\n])",
"_____no_output_____"
],
[
"model.compile(loss=HuberLoss(2.), optimizer=\"nadam\", metrics=[\"mae\"])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 1ms/step - loss: 1.3123 - mae: 1.3345 - val_loss: 0.3378 - val_mae: 0.5485\nEpoch 2/2\n363/363 [==============================] - 0s 760us/step - loss: 0.2659 - mae: 0.5270 - val_loss: 0.2660 - val_mae: 0.5089\n"
],
[
"model.save(\"my_model_with_a_custom_loss_class.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\"my_model_with_a_custom_loss_class.h5\",\n custom_objects={\"HuberLoss\": HuberLoss})",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 966us/step - loss: 0.2286 - mae: 0.4970 - val_loss: 0.2120 - val_mae: 0.4723\nEpoch 2/2\n363/363 [==============================] - 0s 757us/step - loss: 0.2216 - mae: 0.4904 - val_loss: 0.2045 - val_mae: 0.4725\n"
],
[
"model.loss.threshold",
"_____no_output_____"
]
],
[
[
"## Other Custom Functions",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"def my_softplus(z): # return value is just tf.nn.softplus(z)\n return tf.math.log(tf.exp(z) + 1.0)\n\ndef my_glorot_initializer(shape, dtype=tf.float32):\n stddev = tf.sqrt(2. / (shape[0] + shape[1]))\n return tf.random.normal(shape, stddev=stddev, dtype=dtype)\n\ndef my_l1_regularizer(weights):\n return tf.reduce_sum(tf.abs(0.01 * weights))\n\ndef my_positive_weights(weights): # return value is just tf.nn.relu(weights)\n return tf.where(weights < 0., tf.zeros_like(weights), weights)",
"_____no_output_____"
],
[
"layer = keras.layers.Dense(1, activation=my_softplus,\n kernel_initializer=my_glorot_initializer,\n kernel_regularizer=my_l1_regularizer,\n kernel_constraint=my_positive_weights)",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"selu\", kernel_initializer=\"lecun_normal\",\n input_shape=input_shape),\n keras.layers.Dense(1, activation=my_softplus,\n kernel_regularizer=my_l1_regularizer,\n kernel_constraint=my_positive_weights,\n kernel_initializer=my_glorot_initializer),\n])",
"_____no_output_____"
],
[
"model.compile(loss=\"mse\", optimizer=\"nadam\", metrics=[\"mae\"])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 1ms/step - loss: 2.3829 - mae: 1.1635 - val_loss: 1.4154 - val_mae: 0.5607\nEpoch 2/2\n363/363 [==============================] - 0s 757us/step - loss: 0.6299 - mae: 0.5410 - val_loss: 1.4399 - val_mae: 0.5137\n"
],
[
"model.save(\"my_model_with_many_custom_parts.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\n \"my_model_with_many_custom_parts.h5\",\n custom_objects={\n \"my_l1_regularizer\": my_l1_regularizer,\n \"my_positive_weights\": my_positive_weights,\n \"my_glorot_initializer\": my_glorot_initializer,\n \"my_softplus\": my_softplus,\n })",
"_____no_output_____"
],
[
"class MyL1Regularizer(keras.regularizers.Regularizer):\n def __init__(self, factor):\n self.factor = factor\n def __call__(self, weights):\n return tf.reduce_sum(tf.abs(self.factor * weights))\n def get_config(self):\n return {\"factor\": self.factor}",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"selu\", kernel_initializer=\"lecun_normal\",\n input_shape=input_shape),\n keras.layers.Dense(1, activation=my_softplus,\n kernel_regularizer=MyL1Regularizer(0.01),\n kernel_constraint=my_positive_weights,\n kernel_initializer=my_glorot_initializer),\n])",
"_____no_output_____"
],
[
"model.compile(loss=\"mse\", optimizer=\"nadam\", metrics=[\"mae\"])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))",
"Epoch 1/2\n363/363 [==============================] - 1s 1ms/step - loss: 2.3829 - mae: 1.1635 - val_loss: 1.4154 - val_mae: 0.5607\nEpoch 2/2\n363/363 [==============================] - 0s 757us/step - loss: 0.6299 - mae: 0.5410 - val_loss: 1.4399 - val_mae: 0.5137\n"
],
[
"model.save(\"my_model_with_many_custom_parts.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\n \"my_model_with_many_custom_parts.h5\",\n custom_objects={\n \"MyL1Regularizer\": MyL1Regularizer,\n \"my_positive_weights\": my_positive_weights,\n \"my_glorot_initializer\": my_glorot_initializer,\n \"my_softplus\": my_softplus,\n })",
"_____no_output_____"
]
],
[
[
"## Custom Metrics",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"selu\", kernel_initializer=\"lecun_normal\",\n input_shape=input_shape),\n keras.layers.Dense(1),\n])",
"_____no_output_____"
],
[
"model.compile(loss=\"mse\", optimizer=\"nadam\", metrics=[create_huber(2.0)])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2)",
"Epoch 1/2\n363/363 [==============================] - 1s 572us/step - loss: 3.5903 - huber_fn: 1.5558\nEpoch 2/2\n363/363 [==============================] - 0s 552us/step - loss: 0.8054 - huber_fn: 0.3095\n"
]
],
[
[
"**Note**: if you use the same function as the loss and a metric, you may be surprised to see different results. This is generally just due to floating point precision errors: even though the mathematical equations are equivalent, the operations are not run in the same order, which can lead to small differences. Moreover, when using sample weights, there's more than just precision errors:\n* the loss since the start of the epoch is the mean of all batch losses seen so far. Each batch loss is the sum of the weighted instance losses divided by the _batch size_ (not the sum of weights, so the batch loss is _not_ the weighted mean of the losses).\n* the metric since the start of the epoch is equal to the sum of weighted instance losses divided by sum of all weights seen so far. In other words, it is the weighted mean of all the instance losses. Not the same thing.\n\nIf you do the math, you will find that loss = metric * mean of sample weights (plus some floating point precision error).",
"_____no_output_____"
]
],
[
[
"model.compile(loss=create_huber(2.0), optimizer=\"nadam\", metrics=[create_huber(2.0)])",
"_____no_output_____"
],
[
"sample_weight = np.random.rand(len(y_train))\nhistory = model.fit(X_train_scaled, y_train, epochs=2, sample_weight=sample_weight)",
"Epoch 1/2\n363/363 [==============================] - 1s 598us/step - loss: 0.1245 - huber_fn: 0.2515\nEpoch 2/2\n363/363 [==============================] - 0s 558us/step - loss: 0.1216 - huber_fn: 0.2473\n"
],
[
"history.history[\"loss\"][0], history.history[\"huber_fn\"][0] * sample_weight.mean()",
"_____no_output_____"
]
],
[
[
"### Streaming metrics",
"_____no_output_____"
]
],
[
[
"precision = keras.metrics.Precision()\nprecision([0, 1, 1, 1, 0, 1, 0, 1], [1, 1, 0, 1, 0, 1, 0, 1])",
"_____no_output_____"
],
[
"precision([0, 1, 0, 0, 1, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0])",
"_____no_output_____"
],
[
"precision.result()",
"_____no_output_____"
],
[
"precision.variables",
"_____no_output_____"
],
[
"precision.reset_states()",
"_____no_output_____"
]
],
[
[
"Creating a streaming metric:",
"_____no_output_____"
]
],
[
[
"class HuberMetric(keras.metrics.Metric):\n def __init__(self, threshold=1.0, **kwargs):\n super().__init__(**kwargs) # handles base args (e.g., dtype)\n self.threshold = threshold\n self.huber_fn = create_huber(threshold)\n self.total = self.add_weight(\"total\", initializer=\"zeros\")\n self.count = self.add_weight(\"count\", initializer=\"zeros\")\n def update_state(self, y_true, y_pred, sample_weight=None):\n metric = self.huber_fn(y_true, y_pred)\n self.total.assign_add(tf.reduce_sum(metric))\n self.count.assign_add(tf.cast(tf.size(y_true), tf.float32))\n def result(self):\n return self.total / self.count\n def get_config(self):\n base_config = super().get_config()\n return {**base_config, \"threshold\": self.threshold}",
"_____no_output_____"
],
[
"m = HuberMetric(2.)\n\n# total = 2 * |10 - 2| - 2²/2 = 14\n# count = 1\n# result = 14 / 1 = 14\nm(tf.constant([[2.]]), tf.constant([[10.]])) ",
"_____no_output_____"
],
[
"# total = total + (|1 - 0|² / 2) + (2 * |9.25 - 5| - 2² / 2) = 14 + 7 = 21\n# count = count + 2 = 3\n# result = total / count = 21 / 3 = 7\nm(tf.constant([[0.], [5.]]), tf.constant([[1.], [9.25]]))\n\nm.result()",
"_____no_output_____"
],
[
"m.variables",
"_____no_output_____"
],
[
"m.reset_states()\nm.variables",
"_____no_output_____"
]
],
[
[
"Let's check that the `HuberMetric` class works well:",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"selu\", kernel_initializer=\"lecun_normal\",\n input_shape=input_shape),\n keras.layers.Dense(1),\n])",
"_____no_output_____"
],
[
"model.compile(loss=create_huber(2.0), optimizer=\"nadam\", metrics=[HuberMetric(2.0)])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled.astype(np.float32), y_train.astype(np.float32), epochs=2)",
"Epoch 1/2\n363/363 [==============================] - 1s 592us/step - loss: 1.5182 - huber_metric: 1.5182\nEpoch 2/2\n363/363 [==============================] - 0s 538us/step - loss: 0.2909 - huber_metric: 0.2909\n"
],
[
"model.save(\"my_model_with_a_custom_metric.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\"my_model_with_a_custom_metric.h5\",\n custom_objects={\"huber_fn\": create_huber(2.0),\n \"HuberMetric\": HuberMetric})",
"_____no_output_____"
],
[
"model.fit(X_train_scaled.astype(np.float32), y_train.astype(np.float32), epochs=2)",
"Epoch 1/2\n363/363 [==============================] - 0s 545us/step - loss: 0.2350 - huber_metric: 0.2350\nEpoch 2/2\n363/363 [==============================] - 0s 524us/step - loss: 0.2278 - huber_metric: 0.2278\n"
]
],
[
[
"**Warning**: In TF 2.2, tf.keras adds an extra first metric in `model.metrics` at position 0 (see [TF issue #38150](https://github.com/tensorflow/tensorflow/issues/38150)). This forces us to use `model.metrics[-1]` rather than `model.metrics[0]` to access the `HuberMetric`.",
"_____no_output_____"
]
],
[
[
"model.metrics[-1].threshold",
"_____no_output_____"
]
],
[
[
"Looks like it works fine! More simply, we could have created the class like this:",
"_____no_output_____"
]
],
[
[
"class HuberMetric(keras.metrics.Mean):\n def __init__(self, threshold=1.0, name='HuberMetric', dtype=None):\n self.threshold = threshold\n self.huber_fn = create_huber(threshold)\n super().__init__(name=name, dtype=dtype)\n def update_state(self, y_true, y_pred, sample_weight=None):\n metric = self.huber_fn(y_true, y_pred)\n super(HuberMetric, self).update_state(metric, sample_weight)\n def get_config(self):\n base_config = super().get_config()\n return {**base_config, \"threshold\": self.threshold} ",
"_____no_output_____"
]
],
[
[
"This class handles shapes better, and it also supports sample weights.",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"selu\", kernel_initializer=\"lecun_normal\",\n input_shape=input_shape),\n keras.layers.Dense(1),\n])",
"_____no_output_____"
],
[
"model.compile(loss=keras.losses.Huber(2.0), optimizer=\"nadam\", weighted_metrics=[HuberMetric(2.0)])",
"_____no_output_____"
],
[
"sample_weight = np.random.rand(len(y_train))\nhistory = model.fit(X_train_scaled.astype(np.float32), y_train.astype(np.float32),\n epochs=2, sample_weight=sample_weight)",
"Epoch 1/2\n363/363 [==============================] - 1s 627us/step - loss: 0.7800 - HuberMetric: 1.5672\nEpoch 2/2\n363/363 [==============================] - 0s 607us/step - loss: 0.1462 - HuberMetric: 0.2939\n"
],
[
"history.history[\"loss\"][0], history.history[\"HuberMetric\"][0] * sample_weight.mean()",
"_____no_output_____"
],
[
"model.save(\"my_model_with_a_custom_metric_v2.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\"my_model_with_a_custom_metric_v2.h5\",\n custom_objects={\"HuberMetric\": HuberMetric})",
"_____no_output_____"
],
[
"model.fit(X_train_scaled.astype(np.float32), y_train.astype(np.float32), epochs=2)",
"Epoch 1/2\n363/363 [==============================] - 0s 578us/step - loss: 0.2377 - HuberMetric: 0.2377\nEpoch 2/2\n363/363 [==============================] - 0s 559us/step - loss: 0.2279 - HuberMetric: 0.2279\n"
],
[
"model.metrics[-1].threshold",
"_____no_output_____"
]
],
[
[
"## Custom Layers",
"_____no_output_____"
]
],
[
[
"exponential_layer = keras.layers.Lambda(lambda x: tf.exp(x))",
"_____no_output_____"
],
[
"exponential_layer([-1., 0., 1.])",
"_____no_output_____"
]
],
[
[
"Adding an exponential layer at the output of a regression model can be useful if the values to predict are positive and with very different scales (e.g., 0.001, 10., 10000):",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"relu\", input_shape=input_shape),\n keras.layers.Dense(1),\n exponential_layer\n])\nmodel.compile(loss=\"mse\", optimizer=\"sgd\")\nmodel.fit(X_train_scaled, y_train, epochs=5,\n validation_data=(X_valid_scaled, y_valid))\nmodel.evaluate(X_test_scaled, y_test)",
"Epoch 1/5\n363/363 [==============================] - 0s 828us/step - loss: 2.1275 - val_loss: 0.4457\nEpoch 2/5\n363/363 [==============================] - 0s 645us/step - loss: 0.4750 - val_loss: 0.3798\nEpoch 3/5\n363/363 [==============================] - 0s 656us/step - loss: 0.4230 - val_loss: 0.3548\nEpoch 4/5\n363/363 [==============================] - 0s 657us/step - loss: 0.3905 - val_loss: 0.3464\nEpoch 5/5\n363/363 [==============================] - 0s 664us/step - loss: 0.3784 - val_loss: 0.3449\n162/162 [==============================] - 0s 420us/step - loss: 0.3586\n"
],
[
"class MyDense(keras.layers.Layer):\n def __init__(self, units, activation=None, **kwargs):\n super().__init__(**kwargs)\n self.units = units\n self.activation = keras.activations.get(activation)\n\n def build(self, batch_input_shape):\n self.kernel = self.add_weight(\n name=\"kernel\", shape=[batch_input_shape[-1], self.units],\n initializer=\"glorot_normal\")\n self.bias = self.add_weight(\n name=\"bias\", shape=[self.units], initializer=\"zeros\")\n super().build(batch_input_shape) # must be at the end\n\n def call(self, X):\n return self.activation(X @ self.kernel + self.bias)\n\n def compute_output_shape(self, batch_input_shape):\n return tf.TensorShape(batch_input_shape.as_list()[:-1] + [self.units])\n\n def get_config(self):\n base_config = super().get_config()\n return {**base_config, \"units\": self.units,\n \"activation\": keras.activations.serialize(self.activation)}",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n MyDense(30, activation=\"relu\", input_shape=input_shape),\n MyDense(1)\n])",
"_____no_output_____"
],
[
"model.compile(loss=\"mse\", optimizer=\"nadam\")\nmodel.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))\nmodel.evaluate(X_test_scaled, y_test)",
"Epoch 1/2\n363/363 [==============================] - 1s 898us/step - loss: 4.1268 - val_loss: 0.9472\nEpoch 2/2\n363/363 [==============================] - 0s 707us/step - loss: 0.7086 - val_loss: 0.6219\n162/162 [==============================] - 0s 419us/step - loss: 0.5474\n"
],
[
"model.save(\"my_model_with_a_custom_layer.h5\")",
"_____no_output_____"
],
[
"model = keras.models.load_model(\"my_model_with_a_custom_layer.h5\",\n custom_objects={\"MyDense\": MyDense})",
"_____no_output_____"
],
[
"class MyMultiLayer(keras.layers.Layer):\n def call(self, X):\n X1, X2 = X\n print(\"X1.shape: \", X1.shape ,\" X2.shape: \", X2.shape) # Debugging of custom layer\n return X1 + X2, X1 * X2\n\n def compute_output_shape(self, batch_input_shape):\n batch_input_shape1, batch_input_shape2 = batch_input_shape\n return [batch_input_shape1, batch_input_shape2]",
"_____no_output_____"
]
],
[
[
"Our custom layer can be called using the functional API like this:",
"_____no_output_____"
]
],
[
[
"inputs1 = keras.layers.Input(shape=[2])\ninputs2 = keras.layers.Input(shape=[2])\noutputs1, outputs2 = MyMultiLayer()((inputs1, inputs2))",
"X1.shape: (None, 2) X2.shape: (None, 2)\n"
]
],
[
[
"Note that the `call()` method receives symbolic inputs, whose shape is only partially specified (at this stage, we don't know the batch size, which is why the first dimension is `None`):\n\nWe can also pass actual data to the custom layer. To test this, let's split each dataset's inputs into two parts, with four features each:",
"_____no_output_____"
]
],
[
[
"def split_data(data):\n columns_count = data.shape[-1]\n half = columns_count // 2\n return data[:, :half], data[:, half:]\n\nX_train_scaled_A, X_train_scaled_B = split_data(X_train_scaled)\nX_valid_scaled_A, X_valid_scaled_B = split_data(X_valid_scaled)\nX_test_scaled_A, X_test_scaled_B = split_data(X_test_scaled)\n\n# Printing the splitted data shapes\nX_train_scaled_A.shape, X_train_scaled_B.shape",
"_____no_output_____"
]
],
[
[
"Now notice that the shapes are fully specified:",
"_____no_output_____"
]
],
[
[
"outputs1, outputs2 = MyMultiLayer()((X_train_scaled_A, X_train_scaled_B))",
"X1.shape: (11610, 4) X2.shape: (11610, 4)\n"
]
],
[
[
"Let's build a more complete model using the functional API (this is just a toy example, don't expect awesome performance):",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)\n\ninput_A = keras.layers.Input(shape=X_train_scaled_A.shape[-1])\ninput_B = keras.layers.Input(shape=X_train_scaled_B.shape[-1])\nhidden_A, hidden_B = MyMultiLayer()((input_A, input_B))\nhidden_A = keras.layers.Dense(30, activation='selu')(hidden_A)\nhidden_B = keras.layers.Dense(30, activation='selu')(hidden_B)\nconcat = keras.layers.Concatenate()((hidden_A, hidden_B))\noutput = keras.layers.Dense(1)(concat)\nmodel = keras.models.Model(inputs=[input_A, input_B], outputs=[output])",
"X1.shape: (None, 4) X2.shape: (None, 4)\n"
],
[
"model.compile(loss='mse', optimizer='nadam')",
"_____no_output_____"
],
[
"model.fit((X_train_scaled_A, X_train_scaled_B), y_train, epochs=2,\n validation_data=((X_valid_scaled_A, X_valid_scaled_B), y_valid))",
"Epoch 1/2\nX1.shape: (None, 4) X2.shape: (None, 4)\nX1.shape: (None, 4) X2.shape: (None, 4)\n356/363 [============================>.] - ETA: 0s - loss: 3.6305X1.shape: (None, 4) X2.shape: (None, 4)\n363/363 [==============================] - 1s 1ms/step - loss: 3.5973 - val_loss: 1.3630\nEpoch 2/2\n363/363 [==============================] - 0s 1ms/step - loss: 1.0132 - val_loss: 0.9773\n"
]
],
[
[
"Now let's create a layer with a different behavior during training and testing:",
"_____no_output_____"
]
],
[
[
"class AddGaussianNoise(keras.layers.Layer):\n def __init__(self, stddev, **kwargs):\n super().__init__(**kwargs)\n self.stddev = stddev\n\n def call(self, X, training=None):\n if training:\n noise = tf.random.normal(tf.shape(X), stddev=self.stddev)\n return X + noise\n else:\n return X\n\n def compute_output_shape(self, batch_input_shape):\n return batch_input_shape",
"_____no_output_____"
]
],
[
[
"Here's a simple model that uses this custom layer:",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)\n\nmodel = keras.models.Sequential([\n AddGaussianNoise(stddev=1.0),\n keras.layers.Dense(30, activation=\"selu\"),\n keras.layers.Dense(1)\n])",
"_____no_output_____"
],
[
"model.compile(loss=\"mse\", optimizer=\"nadam\")\nmodel.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))\nmodel.evaluate(X_test_scaled, y_test)",
"Epoch 1/2\n363/363 [==============================] - 1s 892us/step - loss: 3.7869 - val_loss: 7.6082\nEpoch 2/2\n363/363 [==============================] - 0s 685us/step - loss: 1.2375 - val_loss: 4.4597\n162/162 [==============================] - 0s 416us/step - loss: 0.7560\n"
]
],
[
[
"## Custom Models",
"_____no_output_____"
]
],
[
[
"X_new_scaled = X_test_scaled",
"_____no_output_____"
],
[
"class ResidualBlock(keras.layers.Layer):\n def __init__(self, n_layers, n_neurons, **kwargs):\n super().__init__(**kwargs)\n self.hidden = [keras.layers.Dense(n_neurons, activation=\"elu\",\n kernel_initializer=\"he_normal\")\n for _ in range(n_layers)]\n\n def call(self, inputs):\n Z = inputs\n for layer in self.hidden:\n Z = layer(Z)\n return inputs + Z",
"_____no_output_____"
],
[
"class ResidualRegressor(keras.models.Model):\n def __init__(self, output_dim, **kwargs):\n super().__init__(**kwargs)\n self.hidden1 = keras.layers.Dense(30, activation=\"elu\",\n kernel_initializer=\"he_normal\")\n self.block1 = ResidualBlock(2, 30)\n self.block2 = ResidualBlock(2, 30)\n self.out = keras.layers.Dense(output_dim)\n\n def call(self, inputs):\n Z = self.hidden1(inputs)\n for _ in range(1 + 3):\n Z = self.block1(Z)\n Z = self.block2(Z)\n return self.out(Z)",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = ResidualRegressor(1)\nmodel.compile(loss=\"mse\", optimizer=\"nadam\")\nhistory = model.fit(X_train_scaled, y_train, epochs=5)\nscore = model.evaluate(X_test_scaled, y_test)\ny_pred = model.predict(X_new_scaled)",
"Epoch 1/5\n363/363 [==============================] - 1s 837us/step - loss: 22.7478\nEpoch 2/5\n363/363 [==============================] - 0s 739us/step - loss: 1.2735\nEpoch 3/5\n363/363 [==============================] - 0s 737us/step - loss: 0.9792\nEpoch 4/5\n363/363 [==============================] - 0s 740us/step - loss: 0.5905\nEpoch 5/5\n363/363 [==============================] - 0s 739us/step - loss: 0.5544\n162/162 [==============================] - 0s 526us/step - loss: 0.6513\n"
],
[
"model.save(\"my_custom_model.ckpt\")",
"WARNING:absl:Found untraced functions such as dense_1_layer_call_and_return_conditional_losses, dense_1_layer_call_fn, dense_2_layer_call_and_return_conditional_losses, dense_2_layer_call_fn, dense_3_layer_call_and_return_conditional_losses while saving (showing 5 of 20). These functions will not be directly callable after loading.\nWARNING:absl:Found untraced functions such as dense_1_layer_call_and_return_conditional_losses, dense_1_layer_call_fn, dense_2_layer_call_and_return_conditional_losses, dense_2_layer_call_fn, dense_3_layer_call_and_return_conditional_losses while saving (showing 5 of 20). These functions will not be directly callable after loading.\n"
],
[
"model = keras.models.load_model(\"my_custom_model.ckpt\")",
"_____no_output_____"
],
[
"history = model.fit(X_train_scaled, y_train, epochs=5)",
"Epoch 1/5\n363/363 [==============================] - 1s 851us/step - loss: 0.9476\nEpoch 2/5\n363/363 [==============================] - 0s 736us/step - loss: 0.6998\nEpoch 3/5\n363/363 [==============================] - 0s 737us/step - loss: 0.4668\nEpoch 4/5\n363/363 [==============================] - 0s 758us/step - loss: 0.4818\nEpoch 5/5\n363/363 [==============================] - 0s 756us/step - loss: 0.4591\n"
]
],
[
[
"We could have defined the model using the sequential API instead:",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"block1 = ResidualBlock(2, 30)\nmodel = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"elu\", kernel_initializer=\"he_normal\"),\n block1, block1, block1, block1,\n ResidualBlock(2, 30),\n keras.layers.Dense(1)\n])",
"_____no_output_____"
],
[
"model.compile(loss=\"mse\", optimizer=\"nadam\")\nhistory = model.fit(X_train_scaled, y_train, epochs=5)\nscore = model.evaluate(X_test_scaled, y_test)\ny_pred = model.predict(X_new_scaled)",
"Epoch 1/5\n363/363 [==============================] - 1s 709us/step - loss: 1.5508\nEpoch 2/5\n363/363 [==============================] - 0s 645us/step - loss: 0.5562\nEpoch 3/5\n363/363 [==============================] - 0s 625us/step - loss: 0.6406\nEpoch 4/5\n363/363 [==============================] - 0s 636us/step - loss: 0.3759\nEpoch 5/5\n363/363 [==============================] - 0s 623us/step - loss: 0.3875\n162/162 [==============================] - 0s 463us/step - loss: 0.4852\n"
]
],
[
[
"## Losses and Metrics Based on Model Internals",
"_____no_output_____"
],
[
"**Note**: the following code has two differences with the code in the book:\n1. It creates a `keras.metrics.Mean()` metric in the constructor and uses it in the `call()` method to track the mean reconstruction loss. Since we only want to do this during training, we add a `training` argument to the `call()` method, and if `training` is `True`, then we update `reconstruction_mean` and we call `self.add_metric()` to ensure it's displayed properly.\n2. Due to an issue introduced in TF 2.2 ([#46858](https://github.com/tensorflow/tensorflow/issues/46858)), we must not call `super().build()` inside the `build()` method.",
"_____no_output_____"
]
],
[
[
"class ReconstructingRegressor(keras.Model):\n def __init__(self, output_dim, **kwargs):\n super().__init__(**kwargs)\n self.hidden = [keras.layers.Dense(30, activation=\"selu\",\n kernel_initializer=\"lecun_normal\")\n for _ in range(5)]\n self.out = keras.layers.Dense(output_dim)\n self.reconstruction_mean = keras.metrics.Mean(name=\"reconstruction_error\")\n\n def build(self, batch_input_shape):\n n_inputs = batch_input_shape[-1]\n self.reconstruct = keras.layers.Dense(n_inputs)\n #super().build(batch_input_shape)\n\n def call(self, inputs, training=None):\n Z = inputs\n for layer in self.hidden:\n Z = layer(Z)\n reconstruction = self.reconstruct(Z)\n recon_loss = tf.reduce_mean(tf.square(reconstruction - inputs))\n self.add_loss(0.05 * recon_loss)\n if training:\n result = self.reconstruction_mean(recon_loss)\n self.add_metric(result)\n return self.out(Z)",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = ReconstructingRegressor(1)\nmodel.compile(loss=\"mse\", optimizer=\"nadam\")\nhistory = model.fit(X_train_scaled, y_train, epochs=2)\ny_pred = model.predict(X_test_scaled)",
"Epoch 1/2\n363/363 [==============================] - 1s 810us/step - loss: 1.6313 - reconstruction_error: 1.0474\nEpoch 2/2\n363/363 [==============================] - 0s 683us/step - loss: 0.4536 - reconstruction_error: 0.4022\n"
]
],
[
[
"## Computing Gradients with Autodiff",
"_____no_output_____"
]
],
[
[
"def f(w1, w2):\n return 3 * w1 ** 2 + 2 * w1 * w2",
"_____no_output_____"
],
[
"w1, w2 = 5, 3\neps = 1e-6\n(f(w1 + eps, w2) - f(w1, w2)) / eps",
"_____no_output_____"
],
[
"(f(w1, w2 + eps) - f(w1, w2)) / eps",
"_____no_output_____"
],
[
"w1, w2 = tf.Variable(5.), tf.Variable(3.)\nwith tf.GradientTape() as tape:\n z = f(w1, w2)\n\ngradients = tape.gradient(z, [w1, w2])",
"_____no_output_____"
],
[
"gradients",
"_____no_output_____"
],
[
"with tf.GradientTape() as tape:\n z = f(w1, w2)\n\ndz_dw1 = tape.gradient(z, w1)\ntry:\n dz_dw2 = tape.gradient(z, w2)\nexcept RuntimeError as ex:\n print(ex)",
"A non-persistent GradientTape can only be used tocompute one set of gradients (or jacobians)\n"
],
[
"with tf.GradientTape(persistent=True) as tape:\n z = f(w1, w2)\n\ndz_dw1 = tape.gradient(z, w1)\ndz_dw2 = tape.gradient(z, w2) # works now!\ndel tape",
"_____no_output_____"
],
[
"dz_dw1, dz_dw2",
"_____no_output_____"
],
[
"c1, c2 = tf.constant(5.), tf.constant(3.)\nwith tf.GradientTape() as tape:\n z = f(c1, c2)\n\ngradients = tape.gradient(z, [c1, c2])",
"_____no_output_____"
],
[
"gradients",
"_____no_output_____"
],
[
"with tf.GradientTape() as tape:\n tape.watch(c1)\n tape.watch(c2)\n z = f(c1, c2)\n\ngradients = tape.gradient(z, [c1, c2])",
"_____no_output_____"
],
[
"gradients",
"_____no_output_____"
],
[
"with tf.GradientTape() as tape:\n z1 = f(w1, w2 + 2.)\n z2 = f(w1, w2 + 5.)\n z3 = f(w1, w2 + 7.)\n\ntape.gradient([z1, z2, z3], [w1, w2])",
"_____no_output_____"
],
[
"with tf.GradientTape(persistent=True) as tape:\n z1 = f(w1, w2 + 2.)\n z2 = f(w1, w2 + 5.)\n z3 = f(w1, w2 + 7.)\n\ntf.reduce_sum(tf.stack([tape.gradient(z, [w1, w2]) for z in (z1, z2, z3)]), axis=0)\ndel tape",
"_____no_output_____"
],
[
"with tf.GradientTape(persistent=True) as hessian_tape:\n with tf.GradientTape() as jacobian_tape:\n z = f(w1, w2)\n jacobians = jacobian_tape.gradient(z, [w1, w2])\nhessians = [hessian_tape.gradient(jacobian, [w1, w2])\n for jacobian in jacobians]\ndel hessian_tape",
"_____no_output_____"
],
[
"jacobians",
"_____no_output_____"
],
[
"hessians",
"_____no_output_____"
],
[
"def f(w1, w2):\n return 3 * w1 ** 2 + tf.stop_gradient(2 * w1 * w2)\n\nwith tf.GradientTape() as tape:\n z = f(w1, w2)\n\ntape.gradient(z, [w1, w2])",
"_____no_output_____"
],
[
"x = tf.Variable(100.)\nwith tf.GradientTape() as tape:\n z = my_softplus(x)\n\ntape.gradient(z, [x])",
"_____no_output_____"
],
[
"tf.math.log(tf.exp(tf.constant(30., dtype=tf.float32)) + 1.)",
"_____no_output_____"
],
[
"x = tf.Variable([100.])\nwith tf.GradientTape() as tape:\n z = my_softplus(x)\n\ntape.gradient(z, [x])",
"_____no_output_____"
],
[
"@tf.custom_gradient\ndef my_better_softplus(z):\n exp = tf.exp(z)\n def my_softplus_gradients(grad):\n return grad / (1 + 1 / exp)\n return tf.math.log(exp + 1), my_softplus_gradients",
"_____no_output_____"
],
[
"def my_better_softplus(z):\n return tf.where(z > 30., z, tf.math.log(tf.exp(z) + 1.))",
"_____no_output_____"
],
[
"x = tf.Variable([1000.])\nwith tf.GradientTape() as tape:\n z = my_better_softplus(x)\n\nz, tape.gradient(z, [x])",
"_____no_output_____"
]
],
[
[
"# Computing Gradients Using Autodiff",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"l2_reg = keras.regularizers.l2(0.05)\nmodel = keras.models.Sequential([\n keras.layers.Dense(30, activation=\"elu\", kernel_initializer=\"he_normal\",\n kernel_regularizer=l2_reg),\n keras.layers.Dense(1, kernel_regularizer=l2_reg)\n])",
"_____no_output_____"
],
[
"def random_batch(X, y, batch_size=32):\n idx = np.random.randint(len(X), size=batch_size)\n return X[idx], y[idx]",
"_____no_output_____"
],
[
"def print_status_bar(iteration, total, loss, metrics=None):\n metrics = \" - \".join([\"{}: {:.4f}\".format(m.name, m.result())\n for m in [loss] + (metrics or [])])\n end = \"\" if iteration < total else \"\\n\"\n print(\"\\r{}/{} - \".format(iteration, total) + metrics,\n end=end)",
"_____no_output_____"
],
[
"import time\n\nmean_loss = keras.metrics.Mean(name=\"loss\")\nmean_square = keras.metrics.Mean(name=\"mean_square\")\nfor i in range(1, 50 + 1):\n loss = 1 / i\n mean_loss(loss)\n mean_square(i ** 2)\n print_status_bar(i, 50, mean_loss, [mean_square])\n time.sleep(0.05)",
"50/50 - loss: 0.0900 - mean_square: 858.5000\n"
]
],
[
[
"A fancier version with a progress bar:",
"_____no_output_____"
]
],
[
[
"def progress_bar(iteration, total, size=30):\n running = iteration < total\n c = \">\" if running else \"=\"\n p = (size - 1) * iteration // total\n fmt = \"{{:-{}d}}/{{}} [{{}}]\".format(len(str(total)))\n params = [iteration, total, \"=\" * p + c + \".\" * (size - p - 1)]\n return fmt.format(*params)",
"_____no_output_____"
],
[
"progress_bar(3500, 10000, size=6)",
"_____no_output_____"
],
[
"def print_status_bar(iteration, total, loss, metrics=None, size=30):\n metrics = \" - \".join([\"{}: {:.4f}\".format(m.name, m.result())\n for m in [loss] + (metrics or [])])\n end = \"\" if iteration < total else \"\\n\"\n print(\"\\r{} - {}\".format(progress_bar(iteration, total), metrics), end=end)",
"_____no_output_____"
],
[
"mean_loss = keras.metrics.Mean(name=\"loss\")\nmean_square = keras.metrics.Mean(name=\"mean_square\")\nfor i in range(1, 50 + 1):\n loss = 1 / i\n mean_loss(loss)\n mean_square(i ** 2)\n print_status_bar(i, 50, mean_loss, [mean_square])\n time.sleep(0.05)",
"50/50 [==============================] - loss: 0.0900 - mean_square: 858.5000\n"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"n_epochs = 5\nbatch_size = 32\nn_steps = len(X_train) // batch_size\noptimizer = keras.optimizers.Nadam(learning_rate=0.01)\nloss_fn = keras.losses.mean_squared_error\nmean_loss = keras.metrics.Mean()\nmetrics = [keras.metrics.MeanAbsoluteError()]",
"_____no_output_____"
],
[
"for epoch in range(1, n_epochs + 1):\n print(\"Epoch {}/{}\".format(epoch, n_epochs))\n for step in range(1, n_steps + 1):\n X_batch, y_batch = random_batch(X_train_scaled, y_train)\n with tf.GradientTape() as tape:\n y_pred = model(X_batch)\n main_loss = tf.reduce_mean(loss_fn(y_batch, y_pred))\n loss = tf.add_n([main_loss] + model.losses)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n for variable in model.variables:\n if variable.constraint is not None:\n variable.assign(variable.constraint(variable))\n mean_loss(loss)\n for metric in metrics:\n metric(y_batch, y_pred)\n print_status_bar(step * batch_size, len(y_train), mean_loss, metrics)\n print_status_bar(len(y_train), len(y_train), mean_loss, metrics)\n for metric in [mean_loss] + metrics:\n metric.reset_states()",
"Epoch 1/5\n11610/11610 [==============================] - mean: 1.3955 - mean_absolute_error: 0.5722\nEpoch 2/5\n11610/11610 [==============================] - mean: 0.6774 - mean_absolute_error: 0.5280\nEpoch 3/5\n11610/11610 [==============================] - mean: 0.6351 - mean_absolute_error: 0.5177\nEpoch 4/5\n11610/11610 [==============================] - mean: 0.6384 - mean_absolute_error: 0.5181\nEpoch 5/5\n11610/11610 [==============================] - mean: 0.6440 - mean_absolute_error: 0.5222\n"
],
[
"try:\n from tqdm.notebook import trange\n from collections import OrderedDict\n with trange(1, n_epochs + 1, desc=\"All epochs\") as epochs:\n for epoch in epochs:\n with trange(1, n_steps + 1, desc=\"Epoch {}/{}\".format(epoch, n_epochs)) as steps:\n for step in steps:\n X_batch, y_batch = random_batch(X_train_scaled, y_train)\n with tf.GradientTape() as tape:\n y_pred = model(X_batch)\n main_loss = tf.reduce_mean(loss_fn(y_batch, y_pred))\n loss = tf.add_n([main_loss] + model.losses)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n for variable in model.variables:\n if variable.constraint is not None:\n variable.assign(variable.constraint(variable)) \n status = OrderedDict()\n mean_loss(loss)\n status[\"loss\"] = mean_loss.result().numpy()\n for metric in metrics:\n metric(y_batch, y_pred)\n status[metric.name] = metric.result().numpy()\n steps.set_postfix(status)\n for metric in [mean_loss] + metrics:\n metric.reset_states()\nexcept ImportError as ex:\n print(\"To run this cell, please install tqdm, ipywidgets and restart Jupyter\")",
"_____no_output_____"
]
],
[
[
"## TensorFlow Functions",
"_____no_output_____"
]
],
[
[
"def cube(x):\n return x ** 3",
"_____no_output_____"
],
[
"cube(2)",
"_____no_output_____"
],
[
"cube(tf.constant(2.0))",
"_____no_output_____"
],
[
"tf_cube = tf.function(cube)\ntf_cube",
"_____no_output_____"
],
[
"tf_cube(2)",
"_____no_output_____"
],
[
"tf_cube(tf.constant(2.0))",
"_____no_output_____"
]
],
[
[
"### TF Functions and Concrete Functions",
"_____no_output_____"
]
],
[
[
"concrete_function = tf_cube.get_concrete_function(tf.constant(2.0))\nconcrete_function.graph",
"_____no_output_____"
],
[
"concrete_function(tf.constant(2.0))",
"_____no_output_____"
],
[
"concrete_function is tf_cube.get_concrete_function(tf.constant(2.0))",
"_____no_output_____"
]
],
[
[
"### Exploring Function Definitions and Graphs",
"_____no_output_____"
]
],
[
[
"concrete_function.graph",
"_____no_output_____"
],
[
"ops = concrete_function.graph.get_operations()\nops",
"_____no_output_____"
],
[
"pow_op = ops[2]\nlist(pow_op.inputs)",
"_____no_output_____"
],
[
"pow_op.outputs",
"_____no_output_____"
],
[
"concrete_function.graph.get_operation_by_name('x')",
"_____no_output_____"
],
[
"concrete_function.graph.get_tensor_by_name('Identity:0')",
"_____no_output_____"
],
[
"concrete_function.function_def.signature",
"_____no_output_____"
]
],
[
[
"### How TF Functions Trace Python Functions to Extract Their Computation Graphs",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef tf_cube(x):\n print(\"print:\", x)\n return x ** 3",
"_____no_output_____"
],
[
"result = tf_cube(tf.constant(2.0))",
"print: Tensor(\"x:0\", shape=(), dtype=float32)\n"
],
[
"result",
"_____no_output_____"
],
[
"result = tf_cube(2)\nresult = tf_cube(3)\nresult = tf_cube(tf.constant([[1., 2.]])) # New shape: trace!\nresult = tf_cube(tf.constant([[3., 4.], [5., 6.]])) # New shape: trace!\nresult = tf_cube(tf.constant([[7., 8.], [9., 10.], [11., 12.]])) # New shape: trace!\n",
"print: 2\nprint: 3\nprint: Tensor(\"x:0\", shape=(1, 2), dtype=float32)\nprint: Tensor(\"x:0\", shape=(2, 2), dtype=float32)\nWARNING:tensorflow:5 out of the last 5 calls to <function tf_cube at 0x7fbfc0363440> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
]
],
[
[
"It is also possible to specify a particular input signature:",
"_____no_output_____"
]
],
[
[
"@tf.function(input_signature=[tf.TensorSpec([None, 28, 28], tf.float32)])\ndef shrink(images):\n print(\"Tracing\", images)\n return images[:, ::2, ::2] # drop half the rows and columns",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"img_batch_1 = tf.random.uniform(shape=[100, 28, 28])\nimg_batch_2 = tf.random.uniform(shape=[50, 28, 28])\npreprocessed_images = shrink(img_batch_1) # Traces the function.\npreprocessed_images = shrink(img_batch_2) # Reuses the same concrete function.",
"Tracing Tensor(\"images:0\", shape=(None, 28, 28), dtype=float32)\n"
],
[
"img_batch_3 = tf.random.uniform(shape=[2, 2, 2])\ntry:\n preprocessed_images = shrink(img_batch_3) # rejects unexpected types or shapes\nexcept ValueError as ex:\n print(ex)",
"Python inputs incompatible with input_signature:\n inputs: (\n tf.Tensor(\n[[[0.7413678 0.62854624]\n [0.01738465 0.3431449 ]]\n\n [[0.51063764 0.3777541 ]\n [0.07321596 0.02137029]]], shape=(2, 2, 2), dtype=float32))\n input_signature: (\n TensorSpec(shape=(None, 28, 28), dtype=tf.float32, name=None))\n"
]
],
[
[
"### Using Autograph To Capture Control Flow",
"_____no_output_____"
],
[
"A \"static\" `for` loop using `range()`:",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef add_10(x):\n for i in range(10):\n x += 1\n return x",
"_____no_output_____"
],
[
"add_10(tf.constant(5))",
"_____no_output_____"
],
[
"add_10.get_concrete_function(tf.constant(5)).graph.get_operations()",
"_____no_output_____"
]
],
[
[
"A \"dynamic\" loop using `tf.while_loop()`:",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef add_10(x):\n condition = lambda i, x: tf.less(i, 10)\n body = lambda i, x: (tf.add(i, 1), tf.add(x, 1))\n final_i, final_x = tf.while_loop(condition, body, [tf.constant(0), x])\n return final_x",
"_____no_output_____"
],
[
"add_10(tf.constant(5))",
"_____no_output_____"
],
[
"add_10.get_concrete_function(tf.constant(5)).graph.get_operations()",
"_____no_output_____"
]
],
[
[
"A \"dynamic\" `for` loop using `tf.range()` (captured by autograph):",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef add_10(x):\n for i in tf.range(10):\n x = x + 1\n return x",
"_____no_output_____"
],
[
"add_10.get_concrete_function(tf.constant(0)).graph.get_operations()",
"_____no_output_____"
]
],
[
[
"### Handling Variables and Other Resources in TF Functions",
"_____no_output_____"
]
],
[
[
"counter = tf.Variable(0)\n\[email protected]\ndef increment(counter, c=1):\n return counter.assign_add(c)",
"_____no_output_____"
],
[
"increment(counter)\nincrement(counter)",
"_____no_output_____"
],
[
"function_def = increment.get_concrete_function(counter).function_def\nfunction_def.signature.input_arg[0]",
"_____no_output_____"
],
[
"counter = tf.Variable(0)\n\[email protected]\ndef increment(c=1):\n return counter.assign_add(c)",
"_____no_output_____"
],
[
"increment()\nincrement()",
"_____no_output_____"
],
[
"function_def = increment.get_concrete_function().function_def\nfunction_def.signature.input_arg[0]",
"_____no_output_____"
],
[
"class Counter:\n def __init__(self):\n self.counter = tf.Variable(0)\n\n @tf.function\n def increment(self, c=1):\n return self.counter.assign_add(c)",
"_____no_output_____"
],
[
"c = Counter()\nc.increment()\nc.increment()",
"_____no_output_____"
],
[
"@tf.function\ndef add_10(x):\n for i in tf.range(10):\n x += 1\n return x\n\nprint(tf.autograph.to_code(add_10.python_function))",
"def tf__add(x):\n with ag__.FunctionScope('add_10', 'fscope', ag__.ConversionOptions(recursive=True, user_requested=True, optional_features=(), internal_convert_user_code=True)) as fscope:\n do_return = False\n retval_ = ag__.UndefinedReturnValue()\n\n def get_state():\n return (x,)\n\n def set_state(vars_):\n nonlocal x\n (x,) = vars_\n\n def loop_body(itr):\n nonlocal x\n i = itr\n x = ag__.ld(x)\n x += 1\n i = ag__.Undefined('i')\n ag__.for_stmt(ag__.converted_call(ag__.ld(tf).range, (10,), None, fscope), None, loop_body, get_state, set_state, ('x',), {'iterate_names': 'i'})\n try:\n do_return = True\n retval_ = ag__.ld(x)\n except:\n do_return = False\n raise\n return fscope.ret(retval_, do_return)\n\n"
],
[
"def display_tf_code(func):\n from IPython.display import display, Markdown\n if hasattr(func, \"python_function\"):\n func = func.python_function\n code = tf.autograph.to_code(func)\n display(Markdown('```python\\n{}\\n```'.format(code)))",
"_____no_output_____"
],
[
"display_tf_code(add_10)",
"_____no_output_____"
]
],
[
[
"## Using TF Functions with tf.keras (or Not)",
"_____no_output_____"
],
[
"By default, tf.keras will automatically convert your custom code into TF Functions, no need to use\n`tf.function()`:",
"_____no_output_____"
]
],
[
[
"# Custom loss function\ndef my_mse(y_true, y_pred):\n print(\"Tracing loss my_mse()\")\n return tf.reduce_mean(tf.square(y_pred - y_true))",
"_____no_output_____"
],
[
"# Custom metric function\ndef my_mae(y_true, y_pred):\n print(\"Tracing metric my_mae()\")\n return tf.reduce_mean(tf.abs(y_pred - y_true))",
"_____no_output_____"
],
[
"# Custom layer\nclass MyDense(keras.layers.Layer):\n def __init__(self, units, activation=None, **kwargs):\n super().__init__(**kwargs)\n self.units = units\n self.activation = keras.activations.get(activation)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(name='kernel', \n shape=(input_shape[1], self.units),\n initializer='uniform',\n trainable=True)\n self.biases = self.add_weight(name='bias', \n shape=(self.units,),\n initializer='zeros',\n trainable=True)\n super().build(input_shape)\n\n def call(self, X):\n print(\"Tracing MyDense.call()\")\n return self.activation(X @ self.kernel + self.biases)",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"# Custom model\nclass MyModel(keras.models.Model):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.hidden1 = MyDense(30, activation=\"relu\")\n self.hidden2 = MyDense(30, activation=\"relu\")\n self.output_ = MyDense(1)\n\n def call(self, input):\n print(\"Tracing MyModel.call()\")\n hidden1 = self.hidden1(input)\n hidden2 = self.hidden2(hidden1)\n concat = keras.layers.concatenate([input, hidden2])\n output = self.output_(concat)\n return output\n\nmodel = MyModel()",
"_____no_output_____"
],
[
"model.compile(loss=my_mse, optimizer=\"nadam\", metrics=[my_mae])",
"_____no_output_____"
],
[
"model.fit(X_train_scaled, y_train, epochs=2,\n validation_data=(X_valid_scaled, y_valid))\nmodel.evaluate(X_test_scaled, y_test)",
"Epoch 1/2\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\n340/363 [===========================>..] - ETA: 0s - loss: 2.8762 - my_mae: 1.2771Tracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\n363/363 [==============================] - 1s 1ms/step - loss: 2.7755 - my_mae: 1.2455 - val_loss: 0.5569 - val_my_mae: 0.4819\nEpoch 2/2\n363/363 [==============================] - 0s 802us/step - loss: 0.4697 - my_mae: 0.4911 - val_loss: 0.4664 - val_my_mae: 0.4576\n162/162 [==============================] - 0s 469us/step - loss: 0.4164 - my_mae: 0.4639\n"
]
],
[
[
"You can turn this off by creating the model with `dynamic=True` (or calling `super().__init__(dynamic=True, **kwargs)` in the model's constructor):",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = MyModel(dynamic=True)",
"_____no_output_____"
],
[
"model.compile(loss=my_mse, optimizer=\"nadam\", metrics=[my_mae])",
"_____no_output_____"
]
],
[
[
"Not the custom code will be called at each iteration. Let's fit, validate and evaluate with tiny datasets to avoid getting too much output:",
"_____no_output_____"
]
],
[
[
"model.fit(X_train_scaled[:64], y_train[:64], epochs=1,\n validation_data=(X_valid_scaled[:64], y_valid[:64]), verbose=0)\nmodel.evaluate(X_test_scaled[:64], y_test[:64], verbose=0)",
"Tracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\n"
]
],
[
[
"Alternatively, you can compile a model with `run_eagerly=True`:",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = MyModel()",
"_____no_output_____"
],
[
"model.compile(loss=my_mse, optimizer=\"nadam\", metrics=[my_mae], run_eagerly=True)",
"_____no_output_____"
],
[
"model.fit(X_train_scaled[:64], y_train[:64], epochs=1,\n validation_data=(X_valid_scaled[:64], y_valid[:64]), verbose=0)\nmodel.evaluate(X_test_scaled[:64], y_test[:64], verbose=0)",
"Tracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\nTracing MyModel.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing MyDense.call()\nTracing loss my_mse()\nTracing metric my_mae()\n"
]
],
[
[
"## Custom Optimizers",
"_____no_output_____"
],
[
"Defining custom optimizers is not very common, but in case you are one of the happy few who gets to write one, here is an example:",
"_____no_output_____"
]
],
[
[
"class MyMomentumOptimizer(keras.optimizers.Optimizer):\n def __init__(self, learning_rate=0.001, momentum=0.9, name=\"MyMomentumOptimizer\", **kwargs):\n \"\"\"Call super().__init__() and use _set_hyper() to store hyperparameters\"\"\"\n super().__init__(name, **kwargs)\n self._set_hyper(\"learning_rate\", kwargs.get(\"lr\", learning_rate)) # handle lr=learning_rate\n self._set_hyper(\"decay\", self._initial_decay) # \n self._set_hyper(\"momentum\", momentum)\n \n def _create_slots(self, var_list):\n \"\"\"For each model variable, create the optimizer variable associated with it.\n TensorFlow calls these optimizer variables \"slots\".\n For momentum optimization, we need one momentum slot per model variable.\n \"\"\"\n for var in var_list:\n self.add_slot(var, \"momentum\")\n\n @tf.function\n def _resource_apply_dense(self, grad, var):\n \"\"\"Update the slots and perform one optimization step for one model variable\n \"\"\"\n var_dtype = var.dtype.base_dtype\n lr_t = self._decayed_lr(var_dtype) # handle learning rate decay\n momentum_var = self.get_slot(var, \"momentum\")\n momentum_hyper = self._get_hyper(\"momentum\", var_dtype)\n momentum_var.assign(momentum_var * momentum_hyper - (1. - momentum_hyper)* grad)\n var.assign_add(momentum_var * lr_t)\n\n def _resource_apply_sparse(self, grad, var):\n raise NotImplementedError\n\n def get_config(self):\n base_config = super().get_config()\n return {\n **base_config,\n \"learning_rate\": self._serialize_hyperparameter(\"learning_rate\"),\n \"decay\": self._serialize_hyperparameter(\"decay\"),\n \"momentum\": self._serialize_hyperparameter(\"momentum\"),\n }",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([keras.layers.Dense(1, input_shape=[8])])\nmodel.compile(loss=\"mse\", optimizer=MyMomentumOptimizer())\nmodel.fit(X_train_scaled, y_train, epochs=5)",
"Epoch 1/5\n363/363 [==============================] - 0s 444us/step - loss: 4.9648\nEpoch 2/5\n363/363 [==============================] - 0s 444us/step - loss: 1.7888\nEpoch 3/5\n363/363 [==============================] - 0s 437us/step - loss: 1.0021\nEpoch 4/5\n363/363 [==============================] - 0s 451us/step - loss: 0.7869\nEpoch 5/5\n363/363 [==============================] - 0s 446us/step - loss: 0.7122\n"
]
],
[
[
"# Exercises",
"_____no_output_____"
],
[
"## 1. to 11.\nSee Appendix A.",
"_____no_output_____"
],
[
"## 12. Implement a custom layer that performs _Layer Normalization_\n_We will use this type of layer in Chapter 15 when using Recurrent Neural Networks._",
"_____no_output_____"
],
[
"### a.\n_Exercise: The `build()` method should define two trainable weights *α* and *β*, both of shape `input_shape[-1:]` and data type `tf.float32`. *α* should be initialized with 1s, and *β* with 0s._",
"_____no_output_____"
],
[
"Solution: see below.",
"_____no_output_____"
],
[
"### b.\n_Exercise: The `call()` method should compute the mean_ μ _and standard deviation_ σ _of each instance's features. For this, you can use `tf.nn.moments(inputs, axes=-1, keepdims=True)`, which returns the mean μ and the variance σ<sup>2</sup> of all instances (compute the square root of the variance to get the standard deviation). Then the function should compute and return *α*⊗(*X* - μ)/(σ + ε) + *β*, where ⊗ represents itemwise multiplication (`*`) and ε is a smoothing term (small constant to avoid division by zero, e.g., 0.001)._",
"_____no_output_____"
]
],
[
[
"class LayerNormalization(keras.layers.Layer):\n def __init__(self, eps=0.001, **kwargs):\n super().__init__(**kwargs)\n self.eps = eps\n\n def build(self, batch_input_shape):\n self.alpha = self.add_weight(\n name=\"alpha\", shape=batch_input_shape[-1:],\n initializer=\"ones\")\n self.beta = self.add_weight(\n name=\"beta\", shape=batch_input_shape[-1:],\n initializer=\"zeros\")\n super().build(batch_input_shape) # must be at the end\n\n def call(self, X):\n mean, variance = tf.nn.moments(X, axes=-1, keepdims=True)\n return self.alpha * (X - mean) / (tf.sqrt(variance + self.eps)) + self.beta\n\n def compute_output_shape(self, batch_input_shape):\n return batch_input_shape\n\n def get_config(self):\n base_config = super().get_config()\n return {**base_config, \"eps\": self.eps}",
"_____no_output_____"
]
],
[
[
"Note that making _ε_ a hyperparameter (`eps`) was not compulsory. Also note that it's preferable to compute `tf.sqrt(variance + self.eps)` rather than `tf.sqrt(variance) + self.eps`. Indeed, the derivative of sqrt(z) is undefined when z=0, so training will bomb whenever the variance vector has at least one component equal to 0. Adding _ε_ within the square root guarantees that this will never happen.",
"_____no_output_____"
],
[
"### c.\n_Exercise: Ensure that your custom layer produces the same (or very nearly the same) output as the `keras.layers.LayerNormalization` layer._",
"_____no_output_____"
],
[
"Let's create one instance of each class, apply them to some data (e.g., the training set), and ensure that the difference is negligeable.",
"_____no_output_____"
]
],
[
[
"X = X_train.astype(np.float32)\n\ncustom_layer_norm = LayerNormalization()\nkeras_layer_norm = keras.layers.LayerNormalization()\n\ntf.reduce_mean(keras.losses.mean_absolute_error(\n keras_layer_norm(X), custom_layer_norm(X)))",
"_____no_output_____"
]
],
[
[
"Yep, that's close enough. To be extra sure, let's make alpha and beta completely random and compare again:",
"_____no_output_____"
]
],
[
[
"random_alpha = np.random.rand(X.shape[-1])\nrandom_beta = np.random.rand(X.shape[-1])\n\ncustom_layer_norm.set_weights([random_alpha, random_beta])\nkeras_layer_norm.set_weights([random_alpha, random_beta])\n\ntf.reduce_mean(keras.losses.mean_absolute_error(\n keras_layer_norm(X), custom_layer_norm(X)))",
"_____no_output_____"
]
],
[
[
"Still a negligeable difference! Our custom layer works fine.",
"_____no_output_____"
],
[
"## 13. Train a model using a custom training loop to tackle the Fashion MNIST dataset\n_The Fashion MNIST dataset was introduced in Chapter 10._",
"_____no_output_____"
],
[
"### a.\n_Exercise: Display the epoch, iteration, mean training loss, and mean accuracy over each epoch (updated at each iteration), as well as the validation loss and accuracy at the end of each epoch._",
"_____no_output_____"
]
],
[
[
"(X_train_full, y_train_full), (X_test, y_test) = keras.datasets.fashion_mnist.load_data()\nX_train_full = X_train_full.astype(np.float32) / 255.\nX_valid, X_train = X_train_full[:5000], X_train_full[5000:]\ny_valid, y_train = y_train_full[:5000], y_train_full[5000:]\nX_test = X_test.astype(np.float32) / 255.",
"_____no_output_____"
],
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"model = keras.models.Sequential([\n keras.layers.Flatten(input_shape=[28, 28]),\n keras.layers.Dense(100, activation=\"relu\"),\n keras.layers.Dense(10, activation=\"softmax\"),\n])",
"_____no_output_____"
],
[
"n_epochs = 5\nbatch_size = 32\nn_steps = len(X_train) // batch_size\noptimizer = keras.optimizers.Nadam(learning_rate=0.01)\nloss_fn = keras.losses.sparse_categorical_crossentropy\nmean_loss = keras.metrics.Mean()\nmetrics = [keras.metrics.SparseCategoricalAccuracy()]",
"_____no_output_____"
],
[
"with trange(1, n_epochs + 1, desc=\"All epochs\") as epochs:\n for epoch in epochs:\n with trange(1, n_steps + 1, desc=\"Epoch {}/{}\".format(epoch, n_epochs)) as steps:\n for step in steps:\n X_batch, y_batch = random_batch(X_train, y_train)\n with tf.GradientTape() as tape:\n y_pred = model(X_batch)\n main_loss = tf.reduce_mean(loss_fn(y_batch, y_pred))\n loss = tf.add_n([main_loss] + model.losses)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n for variable in model.variables:\n if variable.constraint is not None:\n variable.assign(variable.constraint(variable)) \n status = OrderedDict()\n mean_loss(loss)\n status[\"loss\"] = mean_loss.result().numpy()\n for metric in metrics:\n metric(y_batch, y_pred)\n status[metric.name] = metric.result().numpy()\n steps.set_postfix(status)\n y_pred = model(X_valid)\n status[\"val_loss\"] = np.mean(loss_fn(y_valid, y_pred))\n status[\"val_accuracy\"] = np.mean(keras.metrics.sparse_categorical_accuracy(\n tf.constant(y_valid, dtype=np.float32), y_pred))\n steps.set_postfix(status)\n for metric in [mean_loss] + metrics:\n metric.reset_states()\n",
"_____no_output_____"
]
],
[
[
"### b.\n_Exercise: Try using a different optimizer with a different learning rate for the upper layers and the lower layers._",
"_____no_output_____"
]
],
[
[
"keras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"lower_layers = keras.models.Sequential([\n keras.layers.Flatten(input_shape=[28, 28]),\n keras.layers.Dense(100, activation=\"relu\"),\n])\nupper_layers = keras.models.Sequential([\n keras.layers.Dense(10, activation=\"softmax\"),\n])\nmodel = keras.models.Sequential([\n lower_layers, upper_layers\n])",
"_____no_output_____"
],
[
"lower_optimizer = keras.optimizers.SGD(learning_rate=1e-4)\nupper_optimizer = keras.optimizers.Nadam(learning_rate=1e-3)",
"_____no_output_____"
],
[
"n_epochs = 5\nbatch_size = 32\nn_steps = len(X_train) // batch_size\nloss_fn = keras.losses.sparse_categorical_crossentropy\nmean_loss = keras.metrics.Mean()\nmetrics = [keras.metrics.SparseCategoricalAccuracy()]",
"_____no_output_____"
],
[
"with trange(1, n_epochs + 1, desc=\"All epochs\") as epochs:\n for epoch in epochs:\n with trange(1, n_steps + 1, desc=\"Epoch {}/{}\".format(epoch, n_epochs)) as steps:\n for step in steps:\n X_batch, y_batch = random_batch(X_train, y_train)\n with tf.GradientTape(persistent=True) as tape:\n y_pred = model(X_batch)\n main_loss = tf.reduce_mean(loss_fn(y_batch, y_pred))\n loss = tf.add_n([main_loss] + model.losses)\n for layers, optimizer in ((lower_layers, lower_optimizer),\n (upper_layers, upper_optimizer)):\n gradients = tape.gradient(loss, layers.trainable_variables)\n optimizer.apply_gradients(zip(gradients, layers.trainable_variables))\n del tape\n for variable in model.variables:\n if variable.constraint is not None:\n variable.assign(variable.constraint(variable)) \n status = OrderedDict()\n mean_loss(loss)\n status[\"loss\"] = mean_loss.result().numpy()\n for metric in metrics:\n metric(y_batch, y_pred)\n status[metric.name] = metric.result().numpy()\n steps.set_postfix(status)\n y_pred = model(X_valid)\n status[\"val_loss\"] = np.mean(loss_fn(y_valid, y_pred))\n status[\"val_accuracy\"] = np.mean(keras.metrics.sparse_categorical_accuracy(\n tf.constant(y_valid, dtype=np.float32), y_pred))\n steps.set_postfix(status)\n for metric in [mean_loss] + metrics:\n metric.reset_states()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e78925a0aab19468929ea4059e2a4330724308e1 | 10,982 | ipynb | Jupyter Notebook | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper | 8b30fe2cb972a603b6ce1d84004b418d52471a7e | [
"MIT"
] | null | null | null | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper | 8b30fe2cb972a603b6ce1d84004b418d52471a7e | [
"MIT"
] | null | null | null | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper | 8b30fe2cb972a603b6ce1d84004b418d52471a7e | [
"MIT"
] | null | null | null | 31.022599 | 266 | 0.547441 | [
[
[
"# Binary classifiers for sold Ebay shoe listings",
"_____no_output_____"
],
[
"## Connect to database and retrieve data",
"_____no_output_____"
]
],
[
[
"from sqlalchemy import create_engine\nimport pandas as pd\nfrom decouple import config\n\nDATABASE_URL = config('DATABASE_URL')\nengine = create_engine(DATABASE_URL)",
"_____no_output_____"
],
[
"df = pd.read_sql_query('select * from \"shoes\"',con=engine)",
"_____no_output_____"
]
],
[
[
"## Data Cleaning",
"_____no_output_____"
],
[
"### Replace missing values with average value",
"_____no_output_____"
]
],
[
[
"price_fillna_value = round(df[\"price\"].mean(),2)\nfree_shipping_fillna_value = int(df[\"free_shipping\"].mean())\ntotal_images_fillna_value = int(df[\"total_images\"].mean())\nseller_rating_fillna_value = int(df[\"seller_rating\"].mean())\nshoe_size_fillna_value = int(df[\"shoe_size\"].mean())\n\ndf[\"price\"].fillna(price_fillna_value,inplace=True)\ndf[\"free_shipping\"].fillna(free_shipping_fillna_value,inplace=True)\ndf[\"total_images\"].fillna(total_images_fillna_value,inplace=True)\ndf[\"seller_rating\"].fillna(seller_rating_fillna_value,inplace=True)\ndf[\"shoe_size\"].fillna(shoe_size_fillna_value,inplace=True)",
"_____no_output_____"
]
],
[
[
"## Define input and output features",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\nimport numpy as np\n\nfeatures = ['price','free_shipping', 'total_images', 'seller_rating', 'shoe_size', 'desc_fre_score', 'desc_avg_grade_score']\n\nX = np.array(df[features])\ny = np.array(df['sold'])\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)",
"_____no_output_____"
]
],
[
[
"## Train Classification Models",
"_____no_output_____"
],
[
"### Logisitic Regression",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score, f1_score\n\n\nreg_log = LogisticRegression()\nreg_log.fit(X_train, y_train)\ny_pred = reg_log.predict(X_test)\n\nprint(metrics.classification_report(y_test, y_pred))\nprint(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))\nprint(\"f1 score: \", f1_score(y_test, y_pred))",
" precision recall f1-score support\n\n False 0.70 1.00 0.83 45\n True 0.00 0.00 0.00 19\n\n accuracy 0.70 64\n macro avg 0.35 0.50 0.41 64\nweighted avg 0.49 0.70 0.58 64\n\nroc_auc_score: 0.5\nf1 score: 0.0\n"
]
],
[
[
"### Random Forest",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier\n\nreg_rf = RandomForestClassifier()\nreg_rf.fit(X_train, y_train)\ny_pred = reg_rf.predict(X_test)\n\nprint(metrics.classification_report(y_test, y_pred))\nprint(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))\nprint(\"f1 score: \", f1_score(y_test, y_pred))",
" precision recall f1-score support\n\n False 0.79 0.82 0.80 45\n True 0.53 0.47 0.50 19\n\n accuracy 0.72 64\n macro avg 0.66 0.65 0.65 64\nweighted avg 0.71 0.72 0.71 64\n\nroc_auc_score: 0.647953216374269\nf1 score: 0.5\n"
],
[
"feature_df = pd.DataFrame({'Importance':reg_rf.feature_importances_, 'Features': features })\nprint(feature_df)",
" Importance Features\n0 0.172318 price\n1 0.028320 free_shipping\n2 0.177162 total_images\n3 0.181760 seller_rating\n4 0.130010 shoe_size\n5 0.174685 desc_fre_score\n6 0.135746 desc_avg_grade_score\n"
]
],
[
[
"Given these feature importance values, a seller's rating has the most influence on the whether a shoe will sell, while free shipping has the least influence.",
"_____no_output_____"
],
[
"### SVM",
"_____no_output_____"
]
],
[
[
"from sklearn.svm import SVC\n\nreg_svc = SVC()\nreg_svc.fit(X_train, y_train)\ny_pred = reg_svc.predict(X_test)\n\nprint(metrics.classification_report(y_test, y_pred))\nprint(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))\nprint(\"f1 score: \", f1_score(y_test, y_pred))",
" precision recall f1-score support\n\n False 0.70 1.00 0.83 45\n True 0.00 0.00 0.00 19\n\n accuracy 0.70 64\n macro avg 0.35 0.50 0.41 64\nweighted avg 0.49 0.70 0.58 64\n\nroc_auc_score: 0.5\nf1 score: 0.0\n"
]
],
[
[
"### K-Nearest Neighbors",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsClassifier\n\nreg_knn = KNeighborsClassifier()\nreg_knn.fit(X_train, y_train)\ny_pred = reg_knn.predict(X_test)\n\nprint(metrics.classification_report(y_test, y_pred))\nprint(\"roc_auc_score: \", roc_auc_score(y_test, y_pred))\nprint(\"f1 score: \", f1_score(y_test, y_pred))",
" precision recall f1-score support\n\n False 0.75 0.91 0.82 45\n True 0.56 0.26 0.36 19\n\n accuracy 0.72 64\n macro avg 0.65 0.59 0.59 64\nweighted avg 0.69 0.72 0.68 64\n\nroc_auc_score: 0.5871345029239766\nf1 score: 0.35714285714285715\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7892873eb4275f2aa3ecc2f7c616179ab039ef0 | 173,545 | ipynb | Jupyter Notebook | demos/Spacer Length Analysis.ipynb | nataliyah123/phageParser | bc05d76c23d37ee80ffa2bbf6e7e977341bab3ee | [
"MIT"
] | 65 | 2017-05-10T15:26:18.000Z | 2022-03-07T07:10:12.000Z | demos/Spacer Length Analysis.ipynb | nataliyah123/phageParser | bc05d76c23d37ee80ffa2bbf6e7e977341bab3ee | [
"MIT"
] | 143 | 2017-03-22T22:55:16.000Z | 2020-02-13T15:52:03.000Z | demos/Spacer Length Analysis.ipynb | nataliyah123/phageParser | bc05d76c23d37ee80ffa2bbf6e7e977341bab3ee | [
"MIT"
] | 44 | 2017-03-22T20:47:16.000Z | 2022-03-15T21:45:12.000Z | 433.8625 | 51,290 | 0.928958 | [
[
[
"# phageParser - Analysis of Spacer Lengths",
"_____no_output_____"
],
[
"C.K. Yildirim ([email protected])\n\nThe latest version of this [IPython notebook](http://ipython.org/notebook.html) demo is available at [http://github.com/phageParser/phageParser](https://github.com/phageParser/phageParser/tree/django-dev/demos)\n\nTo run this notebook locally:\n* `git clone` or [download](https://github.com/phageParser/phageParser/archive/master.zip) this repository\n* Install [Jupyter Notebook](http://jupyter.org/install.html)\n* In a command prompt, type `jupyter notebook` - the notebook server will launch in your browser\n* Navigate to the phageParser/demos folder and open the notebook",
"_____no_output_____"
],
[
"## Introduction",
"_____no_output_____"
],
[
"This demo uses the REST API of phageParser to plot the distribution of spacer lengths.\nIn this case, the API is consumed using the requests library and the json responses are parsed for gathering\nbasepair length information of spacers.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"#Import packages\nimport requests\nimport json\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom matplotlib import mlab\nimport seaborn as sns\nimport pandas as pd\nfrom scipy.stats import poisson\nsns.set_palette(\"husl\")",
"_____no_output_____"
],
[
"#Url of the phageParser API\napiurl = 'https://phageparser.herokuapp.com'",
"_____no_output_____"
],
[
"#Get the initial page for listing of accessible objects and get url for spacers\nr=requests.get(apiurl)\nspacerurl = r.json()['organisms']",
"_____no_output_____"
],
[
"#API is accessible by chunks of spacers that are in each page, get the total number of pages from meta field\nr=requests.get(spacerurl)\nlast_page = r.json()['meta']['total_pages']",
"_____no_output_____"
],
[
"#Iterate through each page and store json response which only has length of spacers information\njbatches = []\nfor page in range(1,last_page):\n #Exclude every field on spacer object other than length and move to a certain page\n batch_url = spacerurl+'?page={}&exclude[]=*&include[]=loci.spacers.length'.format(page)\n spacer_batch = requests.get(batch_url).json()\n jbatches.append(spacer_batch)",
"_____no_output_____"
],
[
"#Get lengths of spacers per locus\norg_spacer={}\nfor batch in jbatches:\n for organism in batch['organisms']:\n locusspacerlens = {}\n if organism['loci'] == []:\n continue\n orgid = organism['loci'][0]['organism'] \n for locus in organism['loci']:\n spacerlens = []\n for spacer in locus['spacers']:\n spacerlens.append(spacer['length'])\n locusspacerlens[locus['id']]=np.array(spacerlens)\n org_spacer[orgid] = locusspacerlens",
"_____no_output_____"
],
[
"#Get the global mean and variance\nspacerbplengths = np.array([spacerlen for organism in org_spacer.values() for locusspacerlen in organism.values() for spacerlen in locusspacerlen]).flatten()\nmu, sigma = spacerbplengths.mean(), spacerbplengths.std()\nprint(\"Calculated mean basepair length for spacers is {:.2f}+/-{:.2f}\".format(mu,sigma))",
"Calculated mean basepair length for spacers is 35.11+/-3.95\n"
]
],
[
[
"Across the roughly ~3000 sequenced organisms that have what looks like a CRISPR locus, what is the distribution of CRISPR spacer lengths? The histogram below shows that spacer length is peaked at about 35 base pairs. \n\nThe standard deviation of spacer length is 4 base pairs, but the distribution has large tails - there are many more long spacers than would be expected if the lengths were normally distributed (black dashed line) or Poisson distributed (red dashed line).\n\nIndividual organisms (colours other than blue) have tighter distributions than the overall distribution.",
"_____no_output_____"
]
],
[
[
"#Plot histogram of spacer lengths across all organisms\n\nnorm = False # change to false to show totals, true to show everything normalized to 1\n\nplt.figure()\nbins=range(5,100)\nplt.hist(spacerbplengths,bins=bins,normed=norm,label='All organisms')\nplt.yscale('log')\nif norm == False:\n plt.ylim(5*10**-1,10**5)\nelse:\n plt.ylim(10**-6,10**0)\nplt.xlim(10,100)\n\n#Plot normal and poisson distribution of length\nx=np.unique(spacerbplengths)\nif norm == False:\n y = mlab.normpdf(x, mu, sigma)*len(spacerbplengths)\n y2 = poisson.pmf(x,mu)*len(spacerbplengths)\nelse:\n y = mlab.normpdf(x, mu, sigma)\n y2 = poisson.pmf(x,mu)\nplt.plot(x, y, 'k--', linewidth=1.5, label='Normal distribution')\nplt.plot(x, y2, 'r--',linewidth=1.5, label='Poissson distribution')\n\n#Plot histogram for a single organism\nfor i in range(4):\n org_id = random.choice(list(org_spacer.keys()))\n orgspacerlens = np.concatenate(list(org_spacer[org_id].values()))\n plt.hist(orgspacerlens,bins=bins, normed=norm)\n\nplt.ylabel(\"Number of spacers\")\nplt.xlabel(\"Spacer length\")\nplt.legend();",
"_____no_output_____"
]
],
[
[
"What the above plot suggests is that individual organisms and loci have narrow spacer length distributions but that the total distribution is quite broad. ",
"_____no_output_____"
]
],
[
[
"#Calculate means and standard deviations of spacer length for all individual loci\nmeans = []\nstds = []\nfor org in org_spacer.values():\n for arr in list(org.values()):\n means.append(np.mean(arr))\n stds.append(np.std(arr))\n \nprint(\"The mean of all individual locus standard deviations is \" \n + str(round(np.mean(stds),2)) \n + \", smaller than the spacer length standard deviations for all organisms combined.\") \nplt.figure()\nplt.hist(stds,bins=range(0,30))\nplt.xlabel(\"Standard deviation of spacer length within locus\")\nplt.ylabel(\"Number of loci\")\nplt.ylim(8*10**-1,10**4)\nplt.yscale('log');",
"The mean of all individual locus standard deviations is 1.31, smaller than the spacer length standard deviations for all organisms combined.\n"
]
],
[
[
"The following cumulative version of the total spacer length histogram shows again the deviation from normal distribution at large spacer lengths.",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(8,4), dpi=100)\n#Plot cumulative probability of data\nsorted_data = np.sort(spacerbplengths)\nax.step(sorted_data, 1-np.arange(sorted_data.size)/sorted_data.size, label='Data')\n#Plot normal distribution\nx=np.unique(sorted_data)\ny = mlab.normpdf(x, mu, sigma).cumsum()\ny /= y[-1]\nax.plot(x, 1-y, 'k--', linewidth=0.5, label='Normal distribution')\n\n#Format the figure and label\nax.set_yscale('log')\nax.grid(True)\nax.legend(loc='right')\nax.set_title('Cumulative step distribution of spacer lengths')\nax.set_xlabel(\"Spacer length (bps)\")\nax.set_ylabel('Likelihood of occurrence of smaller spacers')\nplt.show()",
"_____no_output_____"
],
[
"#Pick a random organism to plot the histogram for each locus\norg_id = random.choice(list(org_spacer.keys()))\norg_id=594\nlocusspacerlens = org_spacer[org_id]\nfig, ax = plt.subplots(figsize=(8,4),dpi=100)\nbins=range(30,45,1)\n#Plot histogram of spacer length frequency\nfor loc in locusspacerlens:\n sns.distplot(locusspacerlens[loc], ax=ax, kde=False, norm_hist=True, bins=bins)\nplt.xlim([30,45])\n\n#format the figure and label\nax.set_title(\"Histogram of spacer basepair lengths for organism with id {}\".format(org_id))\nax.set_xlabel(\"Spacer length (bps)\")\nax.set_ylabel(\"Occurence of spacers\")\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e78928b755594a8e0b27ee26ff4fc2a182d8fce4 | 6,377 | ipynb | Jupyter Notebook | examples/dynamics/controlled_oscillator.ipynb | hunse/nengo | 5fcd7b18aa9496e5c47c38c6408430cd9f68a720 | [
"BSD-2-Clause"
] | null | null | null | examples/dynamics/controlled_oscillator.ipynb | hunse/nengo | 5fcd7b18aa9496e5c47c38c6408430cd9f68a720 | [
"BSD-2-Clause"
] | null | null | null | examples/dynamics/controlled_oscillator.ipynb | hunse/nengo | 5fcd7b18aa9496e5c47c38c6408430cd9f68a720 | [
"BSD-2-Clause"
] | null | null | null | 32.871134 | 388 | 0.515133 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7893b81b63e323e81d24418b7478fec401703ae | 107,657 | ipynb | Jupyter Notebook | end_to_end/fraud_detection/pipeline-e2e.ipynb | qidewenwhen/amazon-sagemaker-examples | 77f7ad7970381a3c9ab74fc8604ab8903ec55c9b | [
"Apache-2.0"
] | null | null | null | end_to_end/fraud_detection/pipeline-e2e.ipynb | qidewenwhen/amazon-sagemaker-examples | 77f7ad7970381a3c9ab74fc8604ab8903ec55c9b | [
"Apache-2.0"
] | 1 | 2022-03-15T20:04:30.000Z | 2022-03-15T20:04:30.000Z | end_to_end/fraud_detection/pipeline-e2e.ipynb | vivekmadan2/amazon-sagemaker-examples | 4ccb050067c5305a50db750df3444dbc85600d5f | [
"Apache-2.0"
] | null | null | null | 105.857424 | 41,192 | 0.848445 | [
[
[
"# Fraud Detection for Automobile Claims: Create an End to End Pipeline",
"_____no_output_____"
],
[
"## Background\n\nIn this notebook, we will build a SageMaker Pipeline that automates the entire end-to-end process of preparing, training, and deploying a model that detects automobile claim fraud. For a more detailed explanation of each step of the pipeline, you can look the series of notebooks (listed below) that implements this same process using a manual approach. Please see the [README.md](README.md) for more information about this use case implemented by this series of notebooks. \n\n\n1. [Fraud Detection for Automobile Claims: Data Exploration](./0-AutoClaimFraudDetection.ipynb)\n1. [Fraud Detection for Automobile Claims: Data Preparation, Process, and Store Features](./1-data-prep-e2e.ipynb)\n1. [Fraud Detection for Automobile Claims: Train, Check Bias, Tune, Record Lineage, and Register a Model](./2-lineage-train-assess-bias-tune-registry-e2e.ipynb)\n1. [Fraud Detection for Automobile Claims: Mitigate Bias, Train, Register, and Deploy Unbiased Model](./3-mitigate-bias-train-model2-registry-e2e.ipynb)\n\n\n## Contents\n1. [Prerequisites](#Prerequisites)\n1. [Architecture: Create a SageMaker Pipeline to Automate All the Steps from Data Prep to Model Deployment](#Architecture:-Create-a-SageMaker-Pipeline-to-Automate-All-the-Steps-from-Data-Prep-to-Model-Deployment)\n1. [Creating an Automated Pipeline using SageMaker Pipeline](#Creating-an-Automated-Pipeline-using-SageMaker-Pipeline)\n1. [Clean-Up](#Clean-Up)",
"_____no_output_____"
],
[
"## Prerequisites\n----",
"_____no_output_____"
],
[
"### Install required and/or update third-party libraries",
"_____no_output_____"
]
],
[
[
"!python -m pip install -Uq pip\n!python -m pip install -q awswrangler==2.2.0 imbalanced-learn==0.7.0 sagemaker==2.41.0 boto3==1.17.70",
"_____no_output_____"
]
],
[
[
"### Import libraries",
"_____no_output_____"
]
],
[
[
"import json\nimport boto3\nimport pathlib\nimport sagemaker\nimport numpy as np\nimport pandas as pd\nimport awswrangler as wr\nimport string\n\nimport demo_helpers\n\nfrom sagemaker.xgboost.estimator import XGBoost\nfrom sagemaker.workflow.pipeline import Pipeline\nfrom sagemaker.workflow.steps import CreateModelStep\nfrom sagemaker.sklearn.processing import SKLearnProcessor\nfrom sagemaker.workflow.step_collections import RegisterModel\nfrom sagemaker.workflow.steps import ProcessingStep, TrainingStep\nfrom sagemaker.workflow.parameters import ParameterInteger, ParameterFloat, ParameterString",
"_____no_output_____"
]
],
[
[
"### Set region and boto3 config",
"_____no_output_____"
]
],
[
[
"# You can change this to a region of your choice\nimport sagemaker\n\nregion = sagemaker.Session().boto_region_name\nprint(\"Using AWS Region: {}\".format(region))\n\nboto3.setup_default_session(region_name=region)\nboto_session = boto3.Session(region_name=region)\n\ns3_client = boto3.client(\"s3\", region_name=region)\n\nsagemaker_boto_client = boto_session.client(\"sagemaker\")\nsagemaker_session = sagemaker.session.Session(\n boto_session=boto_session, sagemaker_client=sagemaker_boto_client\n)\nsagemaker_role = sagemaker.get_execution_role()\n\naccount_id = boto3.client(\"sts\").get_caller_identity()[\"Account\"]\n\nbucket = sagemaker_session.default_bucket()\nprefix = \"fraud-detect-demo\"\n\nclaims_fg_name = f\"{prefix}-claims\"\ncustomers_fg_name = f\"{prefix}-customers\"",
"_____no_output_____"
],
[
"# ======> Tons of output_paths\n\ntraining_job_output_path = f\"s3://{bucket}/{prefix}/training_jobs\"\nbias_report_output_path = f\"s3://{bucket}/{prefix}/clarify-bias\"\nexplainability_output_path = f\"s3://{bucket}/{prefix}/clarify-explainability\"\n\ntrain_data_uri = f\"s3://{bucket}/{prefix}/data/train/train.csv\"\ntest_data_uri = f\"s3://{bucket}/{prefix}/data/test/test.csv\"\ntrain_data_upsampled_s3_path = f\"s3://{bucket}/{prefix}/data/train/upsampled/train.csv\"\nprocessing_dir = \"/opt/ml/processing\"\ncreate_dataset_script_uri = f\"s3://{bucket}/{prefix}/code/create_dataset.py\"\npipeline_bias_output_path = f\"s3://{bucket}/{prefix}/clarify-output/pipeline/bias\"\ndeploy_model_script_uri = f\"s3://{bucket}/{prefix}/code/deploy_model.py\"\n\n# ======> variables used for parameterizing the notebook run\nflow_instance_count = 1\nflow_instance_type = \"ml.m5.4xlarge\"\n\ntrain_instance_count = 1\ntrain_instance_type = \"ml.m4.xlarge\"\n\ndeploy_model_instance_type = \"ml.m4.xlarge\"",
"_____no_output_____"
]
],
[
[
"## Architecture: Create a SageMaker Pipeline to Automate All the Steps from Data Prep to Model Deployment\n----\n\n",
"_____no_output_____"
],
[
"## Creating an Automated Pipeline using SageMaker Pipeline\n\n- [Step 1: Claims Data Wrangler Preprocessing Step](#Step-1:-Claims-Data-Wrangler-Preprocessing-Step)\n- [Step 2: Customers Data Wrangler Preprocessing Step](#Step-2:-Customers-Data-Wrangler-Preprocessing-Step)\n- [Step 3: Create Dataset and Train/Test Split](#Step-3:-Create-Dataset-and-Train/Test-Split)\n- [Step 4: Train XGBoost Model](#Step-4:-Train-XGBoost-Model)\n- [Step 5: Model Pre-Deployment Step](#Step-5:-Model-Pre-Deployment-Step)\n- [Step 6: Run Bias Metrics with Clarify](#Step-6:-Run-Bias-Metrics-with-Clarify)\n- [Step 7: Register Model](#Step-7:-Register-Model)\n- [Step 8: Deploy Model](#Step-8:-Deploy-Model)\n- [Step 9: Combine and Run the Pipeline Steps](#Step-9:-Combine-and-Run-the-Pipeline-Steps)\n\n",
"_____no_output_____"
],
[
"\n----\nNow that youve manually done each step in our machine learning workflow, you can certain steps to allow for faster model experimentation without sacrificing transparncy and model tracking. In this section you will create a pipeline which trains a new model, persists the model in SageMaker and then adds the model to the registry.",
"_____no_output_____"
],
[
"### Pipeline parameters\nAn important feature of SageMaker Pipelines is the ability to define the steps ahead of time, but be able to change the parameters to those steps at execution without having to re-define the pipeline. This can be achieved by using ParameterInteger, ParameterFloat or ParameterString to define a value upfront which can be modified when you call `pipeline.start(parameters=parameters)` later. Only certain parameters can be defined this way.",
"_____no_output_____"
]
],
[
[
"train_instance_param = ParameterString(\n name=\"TrainingInstance\",\n default_value=\"ml.m4.xlarge\",\n)\n\nmodel_approval_status = ParameterString(\n name=\"ModelApprovalStatus\", default_value=\"PendingManualApproval\"\n)",
"_____no_output_____"
]
],
[
[
"### Step 1: Claims Data Wrangler Preprocessing Step",
"_____no_output_____"
],
[
"### Upload raw data to S3\nBefore you can preprocess the raw data with Data Wrangler, it must exist in S3.",
"_____no_output_____"
]
],
[
[
"s3_client.upload_file(\n Filename=\"data/claims.csv\", Bucket=bucket, Key=f\"{prefix}/data/raw/claims.csv\"\n)\ns3_client.upload_file(\n Filename=\"data/customers.csv\", Bucket=bucket, Key=f\"{prefix}/data/raw/customers.csv\"\n)",
"_____no_output_____"
]
],
[
[
"### Update attributes within the `.flow` file \nData Wrangler will generate a .flow file. It contains a reference to an S3 bucket used during the Wrangling. This may be different from the one you have as a default in this notebook eg if the Wrangling was done by someone else, you will probably not have access to their bucket and you now need to point to your own S3 bucket so you can actually load the .flow file into Data Wrangler or access the data.\n\nAfter running the cell below you can open the `claims.flow` and `customers.flow` files and export the data to S3 or you can continue the guide using the provided `data/claims_preprocessed.csv` and `data/customers_preprocessed.csv` files.",
"_____no_output_____"
]
],
[
[
"claims_flow_template_file = \"claims_flow_template\"\n\nwith open(claims_flow_template_file, \"r\") as f:\n variables = {\"bucket\": bucket, \"prefix\": prefix}\n template = string.Template(f.read())\n claims_flow = template.substitute(variables)\n claims_flow = json.loads(claims_flow)\n\nwith open(\"claims.flow\", \"w\") as f:\n json.dump(claims_flow, f)\n\ncustomers_flow_template_file = \"customers_flow_template\"\n\nwith open(customers_flow_template_file, \"r\") as f:\n variables = {\"bucket\": bucket, \"prefix\": prefix}\n template = string.Template(f.read())\n customers_flow = template.substitute(variables)\n customers_flow = json.loads(customers_flow)\n\nwith open(\"customers.flow\", \"w\") as f:\n json.dump(customers_flow, f)",
"_____no_output_____"
]
],
[
[
"#### Upload flow to S3\nThis will become an input to the first step and, as such, needs to be in S3.",
"_____no_output_____"
]
],
[
[
"s3_client.upload_file(\n Filename=\"claims.flow\", Bucket=bucket, Key=f\"{prefix}/dataprep-notebooks/claims.flow\"\n)\nclaims_flow_uri = f\"s3://{bucket}/{prefix}/dataprep-notebooks/claims.flow\"\nprint(f\"Claims flow file uploaded to S3\")",
"_____no_output_____"
]
],
[
[
"#### Define the first Data Wrangler step's inputs",
"_____no_output_____"
]
],
[
[
"with open(\"claims.flow\", \"r\") as f:\n claims_flow = json.load(f)\n\nflow_step_inputs = []\n\n# flow file contains the code for each transformation\nflow_file_input = sagemaker.processing.ProcessingInput(\n source=claims_flow_uri, destination=f\"{processing_dir}/flow\", input_name=\"flow\"\n)\n\nflow_step_inputs.append(flow_file_input)\n\n# parse the flow file for S3 inputs to Data Wranger job\nfor node in claims_flow[\"nodes\"]:\n if \"dataset_definition\" in node[\"parameters\"]:\n data_def = node[\"parameters\"][\"dataset_definition\"]\n name = data_def[\"name\"]\n s3_input = sagemaker.processing.ProcessingInput(\n source=data_def[\"s3ExecutionContext\"][\"s3Uri\"],\n destination=f\"{processing_dir}/{name}\",\n input_name=name,\n )\n flow_step_inputs.append(s3_input)",
"_____no_output_____"
]
],
[
[
"#### Define outputs for first Data Wranger step",
"_____no_output_____"
]
],
[
[
"claims_output_name = (\n f\"{claims_flow['nodes'][-1]['node_id']}.{claims_flow['nodes'][-1]['outputs'][0]['name']}\"\n)\n\nflow_step_outputs = []\n\nflow_output = sagemaker.processing.ProcessingOutput(\n output_name=claims_output_name,\n feature_store_output=sagemaker.processing.FeatureStoreOutput(feature_group_name=claims_fg_name),\n app_managed=True,\n)\n\nflow_step_outputs.append(flow_output)",
"_____no_output_____"
]
],
[
[
"#### Define processor and processing step",
"_____no_output_____"
]
],
[
[
"# You can find the proper image uri by exporting your Data Wrangler flow to a pipeline notebook\n# =================================\nfrom sagemaker import image_uris\n\n# Pulls the latest data-wrangler container tag, i.e. \"1.x\"\n# The latest tested container version was \"1.11.0\"\nimage_uri = image_uris.retrieve(framework=\"data-wrangler\", region=region)\n\nprint(\"image_uri: {}\".format(image_uri))\n\nflow_processor = sagemaker.processing.Processor(\n role=sagemaker_role,\n image_uri=image_uri,\n instance_count=flow_instance_count,\n instance_type=flow_instance_type,\n max_runtime_in_seconds=86400,\n)\n\noutput_content_type = \"CSV\"\n\n# Output configuration used as processing job container arguments\nclaims_output_config = {claims_output_name: {\"content_type\": output_content_type}}\n\nclaims_flow_step = ProcessingStep(\n name=\"ClaimsDataWranglerProcessingStep\",\n processor=flow_processor,\n inputs=flow_step_inputs,\n outputs=flow_step_outputs,\n job_arguments=[f\"--output-config '{json.dumps(claims_output_config)}'\"],\n)",
"_____no_output_____"
]
],
[
[
"### Step 2: Customers Data Wrangler Preprocessing Step",
"_____no_output_____"
]
],
[
[
"s3_client.upload_file(\n Filename=\"customers.flow\", Bucket=bucket, Key=f\"{prefix}/dataprep-notebooks/customers.flow\"\n)\nclaims_flow_uri = f\"s3://{bucket}/{prefix}/dataprep-notebooks/customers.flow\"\nprint(f\"Customers flow file uploaded to S3\")",
"_____no_output_____"
],
[
"with open(\"customers.flow\", \"r\") as f:\n customers_flow = json.load(f)\n\nflow_step_inputs = []\n\n# flow file contains the code for each transformation\nflow_file_input = sagemaker.processing.ProcessingInput(\n source=claims_flow_uri, destination=f\"{processing_dir}/flow\", input_name=\"flow\"\n)\n\nflow_step_inputs.append(flow_file_input)\n\n# parse the flow file for S3 inputs to Data Wranger job\nfor node in customers_flow[\"nodes\"]:\n if \"dataset_definition\" in node[\"parameters\"]:\n data_def = node[\"parameters\"][\"dataset_definition\"]\n name = data_def[\"name\"]\n s3_input = sagemaker.processing.ProcessingInput(\n source=data_def[\"s3ExecutionContext\"][\"s3Uri\"],\n destination=f\"{processing_dir}/{name}\",\n input_name=name,\n )\n flow_step_inputs.append(s3_input)",
"_____no_output_____"
],
[
"customers_output_name = (\n f\"{customers_flow['nodes'][-1]['node_id']}.{customers_flow['nodes'][-1]['outputs'][0]['name']}\"\n)\n\nflow_step_outputs = []\n\nflow_output = sagemaker.processing.ProcessingOutput(\n output_name=customers_output_name,\n feature_store_output=sagemaker.processing.FeatureStoreOutput(\n feature_group_name=customers_fg_name\n ),\n app_managed=True,\n)\n\nflow_step_outputs.append(flow_output)\n\noutput_content_type = \"CSV\"\n\n# Output configuration used as processing job container arguments\ncustomers_output_config = {customers_output_name: {\"content_type\": output_content_type}}\n\ncustomers_flow_step = ProcessingStep(\n name=\"CustomersDataWranglerProcessingStep\",\n processor=flow_processor,\n inputs=flow_step_inputs,\n outputs=flow_step_outputs,\n job_arguments=[f\"--output-config '{json.dumps(customers_output_config)}'\"],\n)",
"_____no_output_____"
]
],
[
[
"### Step 3: Create Dataset and Train/Test Split",
"_____no_output_____"
]
],
[
[
"s3_client.upload_file(\n Filename=\"create_dataset.py\", Bucket=bucket, Key=f\"{prefix}/code/create_dataset.py\"\n)\n\ncreate_dataset_processor = SKLearnProcessor(\n framework_version=\"0.23-1\",\n role=sagemaker_role,\n instance_type=\"ml.m5.xlarge\",\n instance_count=1,\n base_job_name=\"fraud-detection-demo-create-dataset\",\n sagemaker_session=sagemaker_session,\n)\n\ncreate_dataset_step = ProcessingStep(\n name=\"CreateDataset\",\n processor=create_dataset_processor,\n outputs=[\n sagemaker.processing.ProcessingOutput(\n output_name=\"train_data\", source=\"/opt/ml/processing/output/train\"\n ),\n sagemaker.processing.ProcessingOutput(\n output_name=\"test_data\", source=\"/opt/ml/processing/output/test\"\n ),\n ],\n job_arguments=[\n \"--claims-feature-group-name\",\n claims_fg_name,\n \"--customers-feature-group-name\",\n customers_fg_name,\n \"--bucket-name\",\n bucket,\n \"--bucket-prefix\",\n prefix,\n \"--region\",\n region,\n ],\n code=create_dataset_script_uri,\n depends_on=[claims_flow_step.name, customers_flow_step.name],\n)",
"_____no_output_____"
]
],
[
[
"### Step 4: Train XGBoost Model\nIn this step we use the ParameterString `train_instance_param` defined at the beginning of the pipeline.\n",
"_____no_output_____"
]
],
[
[
"hyperparameters = {\n \"max_depth\": \"3\",\n \"eta\": \"0.2\",\n \"objective\": \"binary:logistic\",\n \"num_round\": \"100\",\n}\n\nxgb_estimator = XGBoost(\n entry_point=\"xgboost_starter_script.py\",\n output_path=training_job_output_path,\n code_location=training_job_output_path,\n hyperparameters=hyperparameters,\n role=sagemaker_role,\n instance_count=train_instance_count,\n instance_type=train_instance_param,\n framework_version=\"1.0-1\",\n)\n\ntrain_step = TrainingStep(\n name=\"XgboostTrain\",\n estimator=xgb_estimator,\n inputs={\n \"train\": sagemaker.inputs.TrainingInput(\n s3_data=create_dataset_step.properties.ProcessingOutputConfig.Outputs[\n \"train_data\"\n ].S3Output.S3Uri\n )\n },\n)",
"_____no_output_____"
]
],
[
[
"### Step 5: Model Pre-Deployment Step\n",
"_____no_output_____"
]
],
[
[
"model = sagemaker.model.Model(\n name=\"fraud-detection-demo-pipeline-xgboost\",\n image_uri=train_step.properties.AlgorithmSpecification.TrainingImage,\n model_data=train_step.properties.ModelArtifacts.S3ModelArtifacts,\n sagemaker_session=sagemaker_session,\n role=sagemaker_role,\n)\n\ninputs = sagemaker.inputs.CreateModelInput(instance_type=\"ml.m4.xlarge\")\n\ncreate_model_step = CreateModelStep(name=\"ModelPreDeployment\", model=model, inputs=inputs)",
"_____no_output_____"
]
],
[
[
"### Step 6: Run Bias Metrics with Clarify\n",
"_____no_output_____"
],
[
"#### Clarify configuration",
"_____no_output_____"
]
],
[
[
"bias_data_config = sagemaker.clarify.DataConfig(\n s3_data_input_path=create_dataset_step.properties.ProcessingOutputConfig.Outputs[\n \"train_data\"\n ].S3Output.S3Uri,\n s3_output_path=pipeline_bias_output_path,\n label=\"fraud\",\n dataset_type=\"text/csv\",\n)\n\nbias_config = sagemaker.clarify.BiasConfig(\n label_values_or_threshold=[0],\n facet_name=\"customer_gender_female\",\n facet_values_or_threshold=[1],\n)\n\nanalysis_config = bias_data_config.get_config()\nanalysis_config.update(bias_config.get_config())\nanalysis_config[\"methods\"] = {\"pre_training_bias\": {\"methods\": \"all\"}}\n\nclarify_config_dir = pathlib.Path(\"config\")\nclarify_config_dir.mkdir(exist_ok=True)\nwith open(clarify_config_dir / \"analysis_config.json\", \"w\") as f:\n json.dump(analysis_config, f)\n\ns3_client.upload_file(\n Filename=\"config/analysis_config.json\",\n Bucket=bucket,\n Key=f\"{prefix}/clarify-config/analysis_config.json\",\n)",
"_____no_output_____"
]
],
[
[
"#### Clarify processing step",
"_____no_output_____"
]
],
[
[
"clarify_processor = sagemaker.processing.Processor(\n base_job_name=\"fraud-detection-demo-clarify-processor\",\n image_uri=sagemaker.clarify.image_uris.retrieve(framework=\"clarify\", region=region),\n role=sagemaker.get_execution_role(),\n instance_count=1,\n instance_type=\"ml.c5.xlarge\",\n)\n\nclarify_step = ProcessingStep(\n name=\"ClarifyProcessor\",\n processor=clarify_processor,\n inputs=[\n sagemaker.processing.ProcessingInput(\n input_name=\"analysis_config\",\n source=f\"s3://{bucket}/{prefix}/clarify-config/analysis_config.json\",\n destination=\"/opt/ml/processing/input/config\",\n ),\n sagemaker.processing.ProcessingInput(\n input_name=\"dataset\",\n source=create_dataset_step.properties.ProcessingOutputConfig.Outputs[\n \"train_data\"\n ].S3Output.S3Uri,\n destination=\"/opt/ml/processing/input/data\",\n ),\n ],\n outputs=[\n sagemaker.processing.ProcessingOutput(\n source=\"/opt/ml/processing/output/analysis.json\",\n destination=pipeline_bias_output_path,\n output_name=\"analysis_result\",\n )\n ],\n)",
"_____no_output_____"
]
],
[
[
"### Step 7: Register Model\nIn this step you will use the ParameterString `model_approval_status` defined at the outset of the pipeline code.\n",
"_____no_output_____"
]
],
[
[
"mpg_name = prefix\n\nmodel_metrics = demo_helpers.ModelMetrics(\n bias=sagemaker.model_metrics.MetricsSource(\n s3_uri=clarify_step.properties.ProcessingOutputConfig.Outputs[\n \"analysis_result\"\n ].S3Output.S3Uri,\n content_type=\"application/json\",\n )\n)\n\nregister_step = RegisterModel(\n name=\"XgboostRegisterModel\",\n estimator=xgb_estimator,\n model_data=train_step.properties.ModelArtifacts.S3ModelArtifacts,\n content_types=[\"text/csv\"],\n response_types=[\"text/csv\"],\n inference_instances=[\"ml.t2.medium\", \"ml.m5.xlarge\"],\n transform_instances=[\"ml.m5.xlarge\"],\n model_package_group_name=mpg_name,\n approval_status=model_approval_status,\n model_metrics=model_metrics,\n)",
"_____no_output_____"
]
],
[
[
"### Step 8: Deploy Model",
"_____no_output_____"
]
],
[
[
"s3_client.upload_file(\n Filename=\"deploy_model.py\", Bucket=bucket, Key=f\"{prefix}/code/deploy_model.py\"\n)\n\ndeploy_model_processor = SKLearnProcessor(\n framework_version=\"0.23-1\",\n role=sagemaker_role,\n instance_type=\"ml.t3.medium\",\n instance_count=1,\n base_job_name=\"fraud-detection-demo-deploy-model\",\n sagemaker_session=sagemaker_session,\n)\n\ndeploy_step = ProcessingStep(\n name=\"DeployModel\",\n processor=deploy_model_processor,\n job_arguments=[\n \"--model-name\",\n create_model_step.properties.ModelName,\n \"--region\",\n region,\n \"--endpoint-instance-type\",\n deploy_model_instance_type,\n \"--endpoint-name\",\n \"xgboost-model-pipeline-0120\",\n ],\n code=deploy_model_script_uri,\n)",
"_____no_output_____"
]
],
[
[
"### Step 9: Combine and Run the Pipeline Steps\n\nThough easier to reason with, the parameters and steps don't need to be in order. The pipeline DAG will parse it out properly.",
"_____no_output_____"
]
],
[
[
"pipeline_name = f\"FraudDetectDemo\"\n%store pipeline_name\n\npipeline = Pipeline(\n name=pipeline_name,\n parameters=[train_instance_param, model_approval_status],\n steps=[\n claims_flow_step,\n customers_flow_step,\n create_dataset_step,\n train_step,\n create_model_step,\n clarify_step,\n register_step,\n deploy_step,\n ],\n)",
"_____no_output_____"
]
],
[
[
"### Submit the pipeline definition to the SageMaker Pipeline service\nNote: If an existing pipeline has the same name it will be overwritten.",
"_____no_output_____"
]
],
[
[
"pipeline.upsert(role_arn=sagemaker_role)",
"_____no_output_____"
]
],
[
[
"### View the entire pipeline definition\nViewing the pipeline definition will all the string variables interpolated may help debug pipeline bugs. It is commented out here due to length.",
"_____no_output_____"
]
],
[
[
"json.loads(pipeline.describe()[\"PipelineDefinition\"])",
"_____no_output_____"
]
],
[
[
"### Run the pipeline\nNote this will take about 23 minutes to complete. You can watch the progress of the Pipeline Job on your SageMaker Studio Components panel",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# Special pipeline parameters can be defined or changed here\nparameters = {\"TrainingInstance\": \"ml.m5.xlarge\"}",
"_____no_output_____"
],
[
"start_response = pipeline.start(parameters=parameters)",
"_____no_output_____"
],
[
"start_response.wait(delay=60, max_attempts=500)\nstart_response.describe()",
"_____no_output_____"
]
],
[
[
"<pre>\n</pre>",
"_____no_output_____"
],
[
"###after completion it will look something like this\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"## Clean Up\n----\nAfter running the demo, you should remove the resources which were created. You can also delete all the objects in the project's S3 directory by passing the keyword argument `delete_s3_objects=True`.",
"_____no_output_____"
]
],
[
[
"from demo_helpers import delete_project_resources",
"_____no_output_____"
],
[
"delete_project_resources(\n sagemaker_boto_client=sagemaker_boto_client,\n pipeline_name=pipeline_name,\n mpg_name=mpg_name,\n prefix=prefix,\n delete_s3_objects=False,\n bucket_name=bucket,\n)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
e7894756ea977b29d4ff1fe0f24363273ad5ae77 | 32,124 | ipynb | Jupyter Notebook | Exploring_Gaussian_Mixture_Models.ipynb | PatrickgHayes/gmm-dnn-for-interpretability | 83f88a5df726fbf4eacc68a679232e24c0d7b0f3 | [
"MIT"
] | null | null | null | Exploring_Gaussian_Mixture_Models.ipynb | PatrickgHayes/gmm-dnn-for-interpretability | 83f88a5df726fbf4eacc68a679232e24c0d7b0f3 | [
"MIT"
] | null | null | null | Exploring_Gaussian_Mixture_Models.ipynb | PatrickgHayes/gmm-dnn-for-interpretability | 83f88a5df726fbf4eacc68a679232e24c0d7b0f3 | [
"MIT"
] | null | null | null | 38.061611 | 132 | 0.51572 | [
[
[
"# DISTRIBUTION STATEMENT A. Approved for public release: distribution unlimited.\n#\n# This material is based upon work supported by the Assistant Secretary of Defense for Research and\n# Engineering under Air Force Contract No. FA8721-05-C-0002 and/or FA8702-15-D-0001. Any opinions,\n# findings, conclusions or recommendations expressed in this material are those of the author(s) and\n# do not necessarily reflect the views of the Assistant Secretary of Defense for Research and\n# Engineering.\n#\n# © 2018 Massachusetts Institute of Technology.\n#\n# MIT Proprietary, Subject to FAR52.227-11 Patent Rights - Ownership by the contractor (May 2014)\n#\n# The software/firmware is provided to you on an As-Is basis\n#\n# Delivered to the U.S. Government with Unlimited Rights, as defined in DFARS Part 252.227-7013 or\n# 7014 (Feb 2014). Notwithstanding any copyright notice, U.S. Government rights in this work are\n# defined by DFARS 252.227-7013 or DFARS 252.227-7014 as detailed above. Use of this work other than\n# as specifically authorized by the U.S. Government may violate any copyrights that exist in this\n# work.",
"_____no_output_____"
]
],
[
[
"# This is an important notebook for giving an intuition for how fitting gaussian mixture models to the latent space could work",
"_____no_output_____"
]
],
[
[
"a = np.ones((1, 1, 2, 2))\nnp.array([a[0]]).shape",
"_____no_output_____"
],
[
"%matplotlib notebook\nfrom mpl_toolkits import mplot3d\nimport torch\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom torch.nn import functional as F\nimport math\nfrom sklearn.neighbors.kde import KernelDensity\nfrom sklearn.model_selection import GridSearchCV\nfrom torch import nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport time\nfrom sklearn.mixture import GaussianMixture",
"_____no_output_____"
],
[
"samples = 500\nx = np.random.randint(-25, 25, samples) + np.random.random(samples)\ny = np.random.normal(0, 3, samples)\n\nline = np.hstack((x.reshape(-1, 1), y.reshape(-1, 1)))\ntheta = math.radians(-45)\nr = np.array([[np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)]])\n\nclockwise_line = line @ r\n\ntheta = math.radians(45)\nr = np.array([[np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)]])\n\ncounter_clockwise_line = line @ r\n\ndata = np.vstack((clockwise_line, counter_clockwise_line))\ndata[:, 0] += 0\ndata[:, 1] += 0\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.scatter(data[:, 0], data[:, 1])\nfig.subplots_adjust(bottom=0.15)\nfig.subplots_adjust(right=0.85)\nfig.canvas.draw()\ntime.sleep(0.1)\nplt.close(fig)",
"_____no_output_____"
],
[
"n_components = np.arange(1, 50)\nparams = {'n_components': n_components}\ngrid = GridSearchCV(GaussianMixture(covariance_type='full', random_state=42),\n params,\n cv=5)\ngrid.fit(data)\n\ngmm = grid.best_estimator_\nsamples, _ = gmm.sample(data.shape[0])",
"_____no_output_____"
],
[
"print(grid.best_params_)",
"_____no_output_____"
],
[
"# plot samples\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.scatter(samples[:, 0], samples[:, 1])\nfig.subplots_adjust(bottom=0.15)\nfig.subplots_adjust(right=0.85)\nfig.canvas.draw()\ntime.sleep(0.1)\nplt.close(fig)",
"_____no_output_____"
],
[
"xx, yy = np.mgrid[-30:30:1, -30:30:1]\n\nsh = xx.shape\n\nzz = np.stack((xx, yy)).transpose(1, 2, 0).reshape(-1, 2)\nzz = np.exp(gmm.score_samples(zz)).reshape(sh[0], sh[1]).transpose()\n\nfig = plt.figure(figsize=(12, 10))\nax = fig.add_subplot(1, 1, 1, projection='3d')\nsurf = ax.plot_surface(xx, yy, zz, rstride=1, cstride=1,\n cmap='viridis', edgecolor='none')\nax.view_init(90, 0)\nfig.colorbar(surf, shrink=0.5, aspect=5)\nfig.canvas.draw()",
"_____no_output_____"
]
],
[
[
"## Sweeeeet it doesn't model the original data perfectly but it does a pretty good job\n## Let's model the domains of individual neurons in a neural network!",
"_____no_output_____"
],
[
"### Here is our dataset",
"_____no_output_____"
]
],
[
[
"def create_sombreros(size=10):\n base_x = np.random.randint(-1, 1, size * 2) + np.random.random(size * 2)\n base_y = np.random.normal(0, 0.1, size * 2)\n base = np.hstack((base_x.reshape(-1, 1), base_y.reshape(-1, 1)))\n \n top_x = np.random.normal(0, 0.1, size)\n top_y = np.random.randint(1, 2, size) + np.random.random(size)\n top = np.hstack((top_x.reshape(-1, 1), top_y.reshape(-1, 1)))\n \n sombrero = np.vstack((base, top))\n \n theta = math.radians(45)\n r = np.array([[np.cos(theta), -np.sin(theta)]\n ,[np.sin(theta), np.cos(theta)]])\n \n right_sombrero = sombrero @ r\n right_sombrero[:, 0] += 1.5\n right_sombrero[:, 1] += 1.5\n \n theta = math.radians(-45)\n r = np.array([[np.cos(theta), -np.sin(theta)]\n ,[np.sin(theta), np.cos(theta)]])\n \n left_sombrero = sombrero @ r\n left_sombrero[:, 0] -= 1.5\n left_sombrero[:, 1] += 1.5\n \n theta = math.radians(180)\n r = np.array([[np.cos(theta), -np.sin(theta)]\n ,[np.sin(theta), np.cos(theta)]])\n \n upsidedown_sombrero = sombrero @ r\n upsidedown_sombrero[:, 0] += 0\n upsidedown_sombrero[:, 1] += 0\n \n data = np.vstack((left_sombrero, right_sombrero, upsidedown_sombrero))\n \n left_labels = np.array([0] * sombrero.shape[0])\n right_labels = np.array([1] * sombrero.shape[0])\n upsidedown_labels = np.array([2] * sombrero.shape[0])\n labels = np.concatenate((left_labels, right_labels, upsidedown_labels))\n \n return data, labels\n \ndata, labels = create_sombreros(size=100)\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nfor i in range(np.max(labels) + 1):\n idxs = np.argwhere(labels == i)\n ax.scatter(data[idxs, 0], data[idxs, 1])\n ax.axis('equal')\nfig.canvas.draw()\ntime.sleep(1)\nplt.close(fig)",
"_____no_output_____"
],
[
"n_components = np.arange(50, 52)\nparams = {'n_components': n_components}\ngrid = GridSearchCV(GaussianMixture(covariance_type='full', random_state=41),\n params,\n cv=5)\ngrid.fit(data)\n\ngmm = grid.best_estimator_\nprint(\"n_components= \" + str(grid.best_params_))\nsamples, _ = gmm.sample(data.shape[0])\n\n\n# Let's map the domain of the inputs\nxx, yy = np.mgrid[-3:3:0.1, -3:3:0.1]\n\nsh = xx.shape\n\nzz = np.stack((xx, yy)).transpose(1, 2, 0).reshape(-1, 2)\nzz = np.exp(gmm.score_samples(zz)).reshape(sh[0], sh[1]).transpose()\n\nfig = plt.figure(figsize=(12, 10))\nax = fig.add_subplot(1, 1, 1, projection='3d')\nsurf = ax.plot_surface(xx, yy, zz, rstride=1, cstride=1,\n cmap='viridis', edgecolor='none')\nax.view_init(90, 0)\nfig.colorbar(surf, shrink=0.5, aspect=5)\nfig.canvas.draw()",
"_____no_output_____"
],
[
"class VisualizeGaussiansNet(nn.Module):\n \n def __init__(self):\n super(VisualizeGaussiansNet, self).__init__()\n self.layer1 = nn.Linear(2, 3)\n self.layer2 = nn.Linear(3, 3)\n self.layer3 = nn.Linear(3, 3)\n \n self.input_gmm = None\n self.layer1_gmm = None\n self.layer2_gmm = None\n self.layer3_gmm = None\n return\n \n def forward(self, x): \n outputs = F.leaky_relu(self.layer1(x))\n outputs = F.leaky_relu(self.layer2(outputs))\n outputs = self.layer3(outputs)\n return outputs\n \n def fit_gmms(self, x, n_components=50):\n self.input_gmm = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(x.detach().numpy())\n \n outputs = self.layer1(x)\n \n self.layer1_gmm = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(outputs.detach().numpy())\n \n outputs = self.layer2(F.leaky_relu(outputs))\n \n self.layer2_gmm = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(outputs.detach().numpy())\n \n outputs = self.layer3(F.leaky_relu(outputs))\n \n self.layer3_gmm = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(outputs.detach().numpy())\n return\n \n def sample(self, target=None, sample_size=100, temp=1):\n # Layer 3\n if target is None:\n target, _ = self.layer3_gmm.sample()\n else:\n samples, _ = self.layer3_gmm.sample(sample_size)\n squashed_samples = F.softmax(torch.tensor(samples).float(), dim=1).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target, axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n target = samples[idx]\n \n #Layer 2\n samples, _ = self.layer2_gmm.sample(sample_size)\n squashed_samples = self.layer3(F.leaky_relu(torch.tensor(samples).float())).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target, axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n target = samples[idx]\n \n #Layer 1\n samples, _ = self.layer1_gmm.sample(sample_size)\n squashed_samples = self.layer2(F.leaky_relu(torch.tensor(samples).float())).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target, axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n target = samples[idx]\n \n # input\n samples, _ = self.input_gmm.sample(sample_size)\n squashed_samples = self.layer1(torch.tensor(samples).float()).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target, axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n target = samples[idx]\n return target\n \n def plot_3d(self, outputs, title, labels=None):\n print(title)\n data = outputs\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n if labels is None:\n ax.scatter3D(data[:, 0], data[:, 1], data[:, 2])\n else:\n for i in range(labels.max() + 1):\n idxs = np.argwhere(labels == i)\n ax.scatter3D(data[idxs, 0], data[idxs, 1], data[idxs, 2])\n fig.canvas.draw()\n return\n \n def plot_journey(self, x, labels, epoch):\n print(\"------------ Start of Epoch \" + str(epoch) + \" -------------\")\n print(\"Inputs\")\n data = x.detach().numpy()\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n for i in range(labels.max() + 1):\n idxs = np.argwhere(labels == i)\n ax.scatter(data[idxs, 0], data[idxs, 1])\n fig.canvas.draw()\n time.sleep(1)\n plt.close(fig)\n \n print(\"Inputs Sampled\")\n samples, _ = self.input_gmm.sample(data.shape[0])\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.scatter(samples[:, 0], samples[:, 1])\n fig.canvas.draw()\n time.sleep(1)\n plt.close(fig)\n \n outputs = self.layer1(x)\n samples, _ = self.layer1_gmm.sample(data.shape[0])\n \n self.plot_3d(outputs.detach().numpy(), \"Layer1\", labels=labels)\n self.plot_3d(samples, \"Layer1 Samples\")\n \n outputs = F.leaky_relu(outputs)\n \n self.plot_3d(outputs.detach().numpy(), \"Layer1 Squashed\", labels=labels)\n \n outputs = self.layer2(outputs)\n samples, _ = self.layer2_gmm.sample(data.shape[0])\n \n self.plot_3d(outputs.detach().numpy(), \"Layer2\", labels=labels)\n self.plot_3d(samples, \"Layer2 Samples\")\n \n outputs = F.leaky_relu(outputs)\n \n self.plot_3d(outputs.detach().numpy(), \"Layer2 Squashed\", labels=labels)\n \n outputs = self.layer3(outputs)\n samples, _ = self.layer3_gmm.sample(data.shape[0])\n \n self.plot_3d(outputs.detach().numpy(), \"Layer3\", labels=labels)\n self.plot_3d(samples, \"Layer3 Samples\")\n \n outputs = F.softmax(outputs, dim=1)\n \n self.plot_3d(outputs.detach().numpy(), \"Layer3 Squashed\", labels=labels)\n print(\"------------ End of Epoch \" + str(epoch) + \" -------------\")\n print()\n return",
"_____no_output_____"
],
[
"vis_net = VisualizeGaussiansNet()\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(vis_net.parameters(), lr=0.001)\n\ndata, labels = create_sombreros(size=100)\ndata, labels = Variable(torch.tensor(data).float()), Variable(torch.tensor(labels))\n\nprint_every = (5999,)\nloss_history = list()\nfor epoch in range(6000):\n running_loss = 0.0\n \n optimizer.zero_grad()\n \n outputs = vis_net(data)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n \n running_loss = loss.item()\n loss_history.append(running_loss)\n \n if epoch in print_every:\n print(\"Loss: \" + str(loss_history[-1]))\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(loss_history)\n fig.subplots_adjust(bottom=0.15)\n fig.canvas.draw()\n time.sleep(0.2)\n plt.close(fig)\n vis_net.fit_gmms(data, n_components=10)\n vis_net.plot_journey(data, labels.detach().numpy().reshape(-1), epoch)\nprint(\"Run plt.close('all') to close all the plots\")",
"_____no_output_____"
],
[
"plt.close('all')",
"_____no_output_____"
],
[
"samples = list()\n\nfor i in range(300):\n samples.append(vis_net.sample(target=np.array([[0, 0, 1]]), sample_size=300, temp=0.02))\n \nsamples = np.vstack(samples)\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.scatter(samples[:, 0], samples[:, 1])\nfig.subplots_adjust(bottom=0.15)\nfig.subplots_adjust(right=0.85)\nfig.canvas.draw()\ntime.sleep(0.2)\nplt.close(fig)",
"_____no_output_____"
]
],
[
[
"# There were somethings about the demo above that I didn't like.\nIt masked the problem of having to collide probability distributions. \n\nIt masked the problem of having to deal with overlapping convolutions.\n\nIt masked the problem of having to deal with inputs aren't drawn from a gaussian ",
"_____no_output_____"
],
[
"# Exploring Gaussian Mixture Models 2.0",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import make_moons",
"_____no_output_____"
],
[
"def create_moons(n_samples=300):\n samples, labels = make_moons(n_samples=n_samples, shuffle=False, noise=0.05)\n ys = (np.random.randint(-2, 2, n_samples) + np.random.uniform(0, 1, n_samples)).reshape(-1, 1)\n samples = np.hstack((samples, ys))\n return samples, labels\n\ndata, labels = create_moons()\nprint(data.shape)",
"_____no_output_____"
],
[
"fig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nif labels is None:\n ax.scatter3D(data[:, 0], data[:, 1], data[:, 2])\nelse:\n for i in range(labels.max() + 1):\n idxs = np.argwhere(labels == i)\n ax.scatter3D(data[idxs, 0], data[idxs, 1], data[idxs, 2])\nfig.canvas.draw()",
"_____no_output_____"
],
[
"class CollisionNet(nn.Module):\n \n def __init__(self):\n super(CollisionNet, self).__init__()\n self.layer1 = [nn.Linear(1, 1) for i in range(3)]\n self.layer2 = nn.Linear(3, 3)\n self.layer3 = nn.Linear(3, 2)\n \n self.input_gmm = [None for i in range(3)]\n self.layer1_gmm = None\n self.layer2_gmm = None\n self.layer3_gmm = None\n return\n \n def forward(self, x):\n outputs = list()\n for i in range(3):\n outputs.append(F.leaky_relu(self.layer1[i](x[:, i].view(-1, 1))))\n outputs = torch.cat(outputs, 1)\n outputs = F.leaky_relu(self.layer2(outputs))\n outputs = self.layer3(outputs)\n return outputs\n \n def fit_gmms(self, x, n_components=50):\n for i in range(3):\n self.input_gmm[i] = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(x[:, i].view(-1, 1).detach().numpy())\n \n outputs = list()\n for i in range(3):\n outputs.append(F.leaky_relu(self.layer1[i](x[:, i].view(-1, 1))))\n outputs = torch.cat(outputs, 1)\n \n self.layer1_gmm = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(outputs.detach().numpy())\n \n outputs = self.layer2(F.leaky_relu(outputs))\n \n self.layer2_gmm = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(outputs.detach().numpy())\n \n outputs = self.layer3(F.leaky_relu(outputs))\n \n self.layer3_gmm = GaussianMixture(covariance_type='full',\n n_components=n_components).fit(outputs.detach().numpy())\n return\n \n def sample(self, target=None, sample_size=100, temp=1):\n # Layer 3\n if target is None:\n target, _ = self.layer3_gmm.sample()\n else:\n samples, _ = self.layer3_gmm.sample(sample_size)\n squashed_samples = F.softmax(torch.tensor(samples).float(), dim=1).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target, axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n target = samples[idx]\n \n #Layer 2\n samples, _ = self.layer2_gmm.sample(sample_size)\n squashed_samples = self.layer3(F.leaky_relu(torch.tensor(samples).float())).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target, axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n target = samples[idx]\n \n #Layer 1\n samples, _ = self.layer1_gmm.sample(sample_size)\n squashed_samples = self.layer2(F.leaky_relu(torch.tensor(samples).float())).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target, axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n target = samples[idx]\n \n # input\n targets = list()\n for i in range(3):\n samples, _ = self.input_gmm[i].sample(sample_size)\n squashed_samples = self.layer1[i](torch.tensor(samples).float()).detach().numpy()\n negative_distances = -1 * np.linalg.norm(squashed_samples - target[i].reshape(-1, 1), axis=1) / temp\n probability_weights = F.softmax(torch.tensor(negative_distances).float(), dim=0).detach().numpy()\n idx = np.random.choice(np.arange(probability_weights.shape[0]), p=probability_weights)\n targets.append(samples[idx])\n return np.hstack(targets)\n \n def plot_3d(self, outputs, title, labels=None):\n print(title)\n data = outputs\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n if labels is None:\n ax.scatter3D(data[:, 0], data[:, 1], data[:, 2])\n else:\n for i in range(labels.max() + 1):\n idxs = np.argwhere(labels == i)\n ax.scatter3D(data[idxs, 0], data[idxs, 1], data[idxs, 2])\n fig.canvas.draw()\n return\n \n def plot_journey(self, x, labels, epoch):\n print(\"------------ Start of Epoch \" + str(epoch) + \" -------------\")\n self.plot_3d(x.detach().numpy(), \"Inputs\", labels=labels)\n \n samples = list()\n for i in range(3):\n sample, _ = self.input_gmm[i].sample(data.shape[0])\n samples.append(sample)\n samples = np.hstack(samples)\n self.plot_3d(samples, \"Input Samples\")\n \n outputs = list()\n for i in range(3):\n outputs.append(F.leaky_relu(self.layer1[i](x[:, i].view(-1, 1))))\n outputs = torch.cat(outputs, 1)\n samples, _ = self.layer1_gmm.sample(data.shape[0])\n \n self.plot_3d(outputs.detach().numpy(), \"Layer1\", labels=labels)\n self.plot_3d(samples, \"Layer1 Samples\")\n \n outputs = F.leaky_relu(outputs)\n \n self.plot_3d(outputs.detach().numpy(), \"Layer1 Squashed\", labels=labels)\n \n outputs = self.layer2(outputs)\n samples, _ = self.layer2_gmm.sample(data.shape[0])\n \n self.plot_3d(outputs.detach().numpy(), \"Layer2\", labels=labels)\n self.plot_3d(samples, \"Layer2 Samples\")\n \n outputs = F.leaky_relu(outputs)\n \n self.plot_3d(outputs.detach().numpy(), \"Layer2 Squashed\", labels=labels)\n \n outputs = self.layer3(outputs)\n outputs = torch.cat((outputs, torch.tensor(np.zeros((outputs.shape[0], 1))).float()), dim=1)\n samples, _ = self.layer3_gmm.sample(data.shape[0])\n samples = np.hstack((samples, np.zeros((samples.shape[0], 1))))\n \n self.plot_3d(outputs.detach().numpy(), \"Layer3\", labels=labels)\n self.plot_3d(samples, \"Layer3 Samples\")\n \n outputs = F.softmax(outputs, dim=1)\n \n self.plot_3d(outputs.detach().numpy(), \"Layer3 Squashed\", labels=labels)\n print(\"------------ End of Epoch \" + str(epoch) + \" -------------\")\n print()\n return",
"_____no_output_____"
],
[
"collision_net = CollisionNet()\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(collision_net.parameters(), lr=0.001)\n\ndata, labels = create_moons(n_samples=500)\ndata, labels = Variable(torch.tensor(data).float()), Variable(torch.tensor(labels))\n\nprint_every = (2, 100, 5999,)\nloss_history = list()\nfor epoch in range(6000):\n running_loss = 0.0\n \n optimizer.zero_grad()\n \n outputs = collision_net(data)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n \n running_loss = loss.item()\n loss_history.append(running_loss)\n \n if epoch in print_every:\n print(\"Loss: \" + str(loss_history[-1]))\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(loss_history)\n fig.subplots_adjust(bottom=0.15)\n fig.canvas.draw()\n time.sleep(0.2)\n plt.close(fig)\n collision_net.fit_gmms(data, n_components=100)\n collision_net.plot_journey(data, labels.detach().numpy().reshape(-1), epoch)\nprint(\"Run plt.close('all') to close all the plots\")",
"_____no_output_____"
],
[
"plt.close('all')",
"_____no_output_____"
],
[
"samples = list()\n\nfor i in range(300):\n samples.append(collision_net.sample(sample_size=300, temp=0.002))\n \nsamples = np.vstack(samples)\noutputs = collision_net(torch.tensor(samples).float()).detach().numpy()\nlabels = np.argmax(outputs, axis=1)\ndata = samples\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nif labels is None:\n ax.scatter3D(data[:, 0], data[:, 1], data[:, 2])\nelse:\n for i in range(labels.max() + 1):\n idxs = np.argwhere(labels == i)\n ax.scatter3D(data[idxs, 0], data[idxs, 1], data[idxs, 2])\ndata_, _ = create_moons(n_samples=300)\nax.scatter3D(data_[:, 0], data_[:, 1], data_[:, 2])\nfig.canvas.draw()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e78949567cb4be4dc209943b393687fbba700cb8 | 285,112 | ipynb | Jupyter Notebook | docs/notebooks/DDSetDebugger.ipynb | niMgnoeSeeL/debuggingbook | aa6b941e7caf22b2fdfa1ca8d7358fc36150cc3c | [
"MIT"
] | 107 | 2020-09-27T13:33:26.000Z | 2022-03-21T10:45:04.000Z | docs/notebooks/DDSetDebugger.ipynb | niMgnoeSeeL/debuggingbook | aa6b941e7caf22b2fdfa1ca8d7358fc36150cc3c | [
"MIT"
] | 26 | 2020-10-23T14:43:04.000Z | 2022-03-03T15:06:52.000Z | docs/notebooks/DDSetDebugger.ipynb | niMgnoeSeeL/debuggingbook | aa6b941e7caf22b2fdfa1ca8d7358fc36150cc3c | [
"MIT"
] | 20 | 2021-03-04T11:49:09.000Z | 2022-03-23T06:16:36.000Z | 39.903709 | 750 | 0.527266 | [
[
[
"# Generalizing Failure Circumstances\n\nOne central question in debugging is: _Does this bug occur in other situations, too?_ In this chapter, we present a technique that is set to _generalize_ the circumstances under which a failure occurs. The DDSET algorithm takes a failure-inducing input, breaks it into individual elements. For each element, it tries to find whether it can be replaced by others in the same category, and if so, it _generalizes_ the concrete element to the very category. The result is a _pattern_ that characterizes the failure condition: \"The failure occurs for all inputs of the form `(<expr> * <expr>)`.",
"_____no_output_____"
]
],
[
[
"from bookutils import YouTubeVideo\nYouTubeVideo(\"PV22XtIQU1s\")",
"_____no_output_____"
]
],
[
[
"**Prerequisites**\n\n* You should have read the [chapter on _delta debugging_](DeltaDebugger.ipynb).",
"_____no_output_____"
]
],
[
[
"import bookutils",
"_____no_output_____"
],
[
"import DeltaDebugger",
"_____no_output_____"
]
],
[
[
"## Synopsis\n<!-- Automatically generated. Do not edit. -->\n\nTo [use the code provided in this chapter](Importing.ipynb), write\n\n```python\n>>> from debuggingbook.DDSetDebugger import <identifier>\n```\n\nand then make use of the following features.\n\n\nThis chapter provides a class `DDSetDebugger`, implementing the DDSET algorithm for generalizing failure-inducing inputs. The `DDSetDebugger` is used as follows:\n\n```python\nwith DDSetDebugger(grammar) as dd:\n function(args...)\ndd\n```\n\nHere, `function(args...)` is a failing function call (= raises an execption) that takes at least one string argument; `grammar` is an [input grammar in fuzzingbook format](https://www.fuzzingbook.org/html/Grammars.html) that matches the format of this argument.\n\nThe result is a call of `function()` with an _abstract failure-inducing input_ – a variant of the conrete input in which parts are replaced by placeholders in the form `<name>`, where `<name>` is a nonterminal in the grammar. The failure has been verified to occur for a number of instantiations of `<name>`.\n\nHere is an example of how `DDSetDebugger` works. The concrete failing input `<foo>\"bar</foo>` is generalized to an _abstract failure-inducing input_:\n\n```python\n>>> with DDSetDebugger(SIMPLE_HTML_GRAMMAR) as dd:\n>>> remove_html_markup('<foo>\"bar</foo>')\n>>> dd\nremove_html_markup(s='<lt><id><gt>\"<plain-text><closing-tag>')\n```\nThe abstract input tells us that the failure occurs for whatever opening and closing HTML tags as long as there is a double quote between them.\n\nA programmatic interface is available as well. `generalize()` returns a mapping of argument names to (generalized) values:\n\n```python\n>>> dd.generalize()\n{'s': '<lt><id><gt>\"<plain-text><closing-tag>'}\n```\nUsing `fuzz()`, the abstract input can be instantiated to further concrete inputs, all set to produce the failure again:\n\n```python\n>>> for i in range(10):\n>>> print(dd.fuzz())\nremove_html_markup(s='<s1d>\"1</hF>')\nremove_html_markup(s='<H>\"c*C</l>')\nremove_html_markup(s='<Ah2>\"</v>')\nremove_html_markup(s='<a7>\")</NP>')\nremove_html_markup(s='<boyIIt640TF>\"</b08>')\nremove_html_markup(s='<dF>\"</fay>')\nremove_html_markup(s='<l2>\"\\t7</z>')\nremove_html_markup(s='<ci>\"</t>')\nremove_html_markup(s='<J>\"2</t>')\nremove_html_markup(s='<Fo9g>\"\\r~\\t\\r</D>')\n\n```\n`DDSetDebugger` can be customized by passing a subclass of `TreeGeneralizer`, which does the gist of the work; for details, see its constructor.\nThe full class hierarchy is shown below.\n\n\n\n",
"_____no_output_____"
],
[
"## A Failing Program\n\nAs with previous chapters, we use `remove_html_markup()` as our ongoing example. This function is set to remove HTML markup tags (like `<em>`) from a given string `s`, returning the plain text only. We use the version from [the chapter on asssertions](Assertions.ipynb), using an assertion as postcondition checker.",
"_____no_output_____"
]
],
[
[
"def remove_html_markup(s): # type: ignore\n tag = False\n quote = False\n out = \"\"\n\n for c in s:\n if c == '<' and not quote:\n tag = True\n elif c == '>' and not quote:\n tag = False\n elif c == '\"' or c == \"'\" and tag:\n quote = not quote\n elif not tag:\n out = out + c\n\n # postcondition\n assert '<' not in out and '>' not in out\n\n return out",
"_____no_output_____"
]
],
[
[
"For the most inputs, `remove_html_markup()` works just as expected:",
"_____no_output_____"
]
],
[
[
"remove_html_markup(\"Be <em>quiet</em>, he said\")",
"_____no_output_____"
]
],
[
[
"There are inputs, however, for which it fails:",
"_____no_output_____"
]
],
[
[
"BAD_INPUT = '<foo>\"bar</foo>'",
"_____no_output_____"
],
[
"from ExpectError import ExpectError",
"_____no_output_____"
],
[
"with ExpectError(AssertionError):\n remove_html_markup(BAD_INPUT)",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_58133/3787550988.py\", line 2, in <module>\n remove_html_markup(BAD_INPUT)\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_58133/2717035104.py\", line 17, in remove_html_markup\n assert '<' not in out and '>' not in out\nAssertionError (expected)\n"
],
[
"from bookutils import quiz",
"_____no_output_____"
]
],
[
[
"In contrast to the other chapters, our aim now is not to immediately go and debug `remove_html_markup()`. Instead, we focus on another important question: \n\n> Under which conditions precisely does `remove_html_markup()` fail?",
"_____no_output_____"
],
[
"This question can be generalized to\n\n> What is the set of inputs for which `remove_html_markup()` fails?",
"_____no_output_____"
],
[
"Our plan for this is to _generalize_ concrete inputs (such as `BAD_INPUTS`) into an *abstract failure-inducing inputs*. These are patterns formed from a concrete input, but in which specific _placeholders_ indicate sets of inputs that are permitted. In the abstract failure-inducing input\n\n```html\n<opening-tag>\"bar<closing-tag>\n```\n\nfor instance, `<opening-tag>` and `<closing-tag>` are placeholders for opening and closing HTML tags, respectively. The pattern indicates that any opening HTML tag and closing HTML tag can be present in the input, as long as the enclosed text reads `\"bar`.",
"_____no_output_____"
],
[
"Given a concrete failure-inducing input, our aim is to _generalize_ it as much as possible to such an abstract failure-inducing input. The resulting pattern should then\n\n* capture the _circumstances_ under which the program fails;\n* allow for _test generation_ by instantiating the placeholders;\n* help ensuring our fix is as _general as possible_.",
"_____no_output_____"
]
],
[
[
"quiz(\"If `s = '<foo>\\\"bar</foo>'` (i.e., `BAD_INPUT`), \"\n \"what is the value of `out` such that the assertion fails?\",\n [\n '`bar`',\n '`bar</foo>`',\n '`\"bar</foo>`',\n '`<foo>\"bar</foo>`',\n ], '9999999 // 4999999')",
"_____no_output_____"
]
],
[
[
"## Grammars\n\nTo determine abstract failure-inducing inputs, we need means to determine and characterize _sets of inputs_ – known in computer science as _languages_. To formally describe languages, the field of *formal languages* has devised a number of *language specifications* that describe a language. *Regular expressions* represent the simplest class of these languages to denote sets of strings: The regular expression `[a-z]*`, for instance, denotes a (possibly empty) sequence of lowercase letters. *Automata theory* connects these languages to automata that accept these inputs; *finite state machines*, for instance, can be used to specify the language of regular expressions.",
"_____no_output_____"
],
[
"Regular expressions are great for not-too-complex input formats, and the associated finite state machines have many properties that make them great for reasoning. To specify more complex inputs, though, they quickly encounter limitations. At the other end of the language spectrum, we have *universal grammars* that denote the language accepted by *Turing machines*. A Turing machine can compute anything that can be computed; and with Python being Turing-complete, this means that we can also use a Python program $p$ to specify or even enumerate legal inputs. But then, computer science theory also tells us that each such program has to be written specifically for the input to be considered, which is not the level of automation we want.",
"_____no_output_____"
],
[
"The middle ground between regular expressions and Turing machines is covered by *grammars*. Grammars are among the most popular (and best understood) formalisms to formally specify input languages. Using a grammar, one can express a wide range of the properties of an input language. Grammars are particularly great for expressing the *syntactical structure* of an input, and are the formalism of choice to express nested or recursive inputs. The grammars we use are so-called *context-free grammars*, one of the easiest and most popular grammar formalisms.",
"_____no_output_____"
],
[
"A grammar is defined as a mapping of _nonterminal_ symbols (denoted in `<angle brackets>` to lists of alternative _expansions_, which are strings containing _terminal_ symbols and possibly more _nonterminal_ symbols. To make the writing of grammars as simple as possible, we adopt the [fuzzingbook](https://www.fuzzingbook.org/) format that is based on strings and lists.",
"_____no_output_____"
]
],
[
[
"import fuzzingbook",
"_____no_output_____"
]
],
[
[
"Fuzzingbook grammars take the format of a _mapping_ between symbol names and expansions, where expansions are _lists_ of alternatives.",
"_____no_output_____"
]
],
[
[
"# ignore\nfrom typing import Any, Callable, Optional, Type, Tuple\nfrom typing import Dict, Union, List, cast, Generator",
"_____no_output_____"
],
[
"Grammar = Dict[str, # A grammar maps strings...\n List[\n Union[str, # to list of strings...\n Tuple[str, Dict[str, Any]] # or to pairs of strings and attributes.\n ]\n ]\n ]",
"_____no_output_____"
]
],
[
[
"A one-rule grammar for digits thus takes the form",
"_____no_output_____"
]
],
[
[
"DIGIT_GRAMMAR: Grammar = {\n \"<start>\":\n [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n}",
"_____no_output_____"
]
],
[
[
"which means that the `<start>` symbol can be expanded into any of the digits listed.",
"_____no_output_____"
],
[
"A full grammar for arithmetic expressions looks like this:",
"_____no_output_____"
]
],
[
[
"EXPR_GRAMMAR: Grammar = {\n \"<start>\":\n [\"<expr>\"],\n\n \"<expr>\":\n [\"<term> + <expr>\", \"<term> - <expr>\", \"<term>\"],\n\n \"<term>\":\n [\"<factor> * <term>\", \"<factor> / <term>\", \"<factor>\"],\n\n \"<factor>\":\n [\"+<factor>\",\n \"-<factor>\",\n \"(<expr>)\",\n \"<integer>.<integer>\",\n \"<integer>\"],\n\n \"<integer>\":\n [\"<digit><integer>\", \"<digit>\"],\n\n \"<digit>\":\n [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n}",
"_____no_output_____"
]
],
[
[
"From such a grammar, one can easily generate inputs that conform to the grammar.",
"_____no_output_____"
]
],
[
[
"from fuzzingbook.GrammarFuzzer import GrammarFuzzer",
"_____no_output_____"
],
[
"simple_expr_fuzzer = GrammarFuzzer(EXPR_GRAMMAR)",
"_____no_output_____"
],
[
"for i in range(10):\n fuzz_expr = simple_expr_fuzzer.fuzz()\n print(fuzz_expr)",
"3.8 + --62.912 - ++4 - +5 * 3.0 * 4\n7 * (75.5 - -6 + 5 - 4) + -(8 - 1) / 5 * 2\n(-(9) * +6 + 9 / 3 * 8 - 9 * 8 / 7) / -+-65\n(9 + 8) * 2 * (6 + 6 + 9) * 0 * 1.9 * 0\n(1 * 7 - 9 + 5) * 5 / 0 * 5 + 7 * 5 * 7\n-(6 / 9 - 5 - 3 - 1) - -1 / +1 + (9) / (8) * 6\n(+-(0 - (1) * 7 / 3)) / ((1 * 3 + 8) + 9 - +1 / --0) - 5 * (-+939.491)\n+2.9 * 0 / 501.19814 / --+--(6.05002)\n+-8.8 / (1) * -+1 + -8 + 9 - 3 / 8 * 6 + 4 * 3 * 5\n(+(8 / 9 - 1 - 7)) + ---06.30 / +4.39\n"
]
],
[
[
"Nonterminals as found in the grammar make natural _placeholders_ in abstract failure-inducing inputs. If we know, for instance, that it is not just the concrete failure-inducing input\n\n```python\n(2 * 3)\n```\n\nbut the abstract failure-inducing input\n\n```html\n(<expr> * <expr>)\n```\n\nthat causes the failure, we immediately see that the error is due to the multiplication operator rather than its operands.",
"_____no_output_____"
],
[
"Coming back to our `remove_html_markup()` example, let us create a simple grammar for HTML expressions. A `<html>` element is either plain text or tagged text.",
"_____no_output_____"
]
],
[
[
"SIMPLE_HTML_GRAMMAR: Grammar = {\n \"<start>\":\n [\"<html>\"],\n\n \"<html>\":\n [\"<plain-text>\", \"<tagged-text>\"],\n}",
"_____no_output_____"
]
],
[
[
"Plain text is a simple (possibly empty) sequence of letter, digits, punctuation, and whitespace. (Note how `<plain-text>` is either empty or some character followed by more plain text.) The characters `<` and `>` are not allowed, though.",
"_____no_output_____"
]
],
[
[
"import string",
"_____no_output_____"
],
[
"SIMPLE_HTML_GRAMMAR.update({\n \"<plain-text>\":\n [\"\", \"<plain-char><plain-text>\"],\n\n \"<plain-char>\":\n [\"<letter>\", \"<digit>\", \"<other>\", \"<whitespace>\"],\n\n \"<letter>\": list(string.ascii_letters),\n \"<digit>\": list(string.digits),\n \"<other>\": list(string.punctuation.replace('<', '').replace('>', '')),\n \"<whitespace>\": list(string.whitespace)\n})",
"_____no_output_____"
]
],
[
[
"Tagged text is a bit more complicated. We have opening tags `<foo>`, followed by some more HTML material, and then closed by a closing tag `</foo>`. (We do not insist that the two tags match.) A self-closing tag has the form `<br/>`. For compatibility reasons, we also allow just opening tags without closing tags, as in `<img>`.",
"_____no_output_____"
]
],
[
[
"SIMPLE_HTML_GRAMMAR.update({\n \"<tagged-text>\":\n [\"<opening-tag><html><closing-tag>\",\n \"<self-closing-tag>\",\n \"<opening-tag>\"],\n})",
"_____no_output_____"
]
],
[
[
"Since the characters `<` and `>` are already reserved for denoting nonterminal symbols, we use the special nonterminal symbols `<lt>` and `<gt>` that expand into `<` and `>`, respectively,",
"_____no_output_____"
]
],
[
[
"SIMPLE_HTML_GRAMMAR.update({\n \"<opening-tag>\":\n [\"<lt><id><gt>\",\n \"<lt><id><attrs><gt>\"],\n\n \"<lt>\": [\"<\"],\n \"<gt>\": [\">\"],\n\n \"<id>\":\n [\"<letter>\", \"<id><letter>\", \"<id><digit>\"],\n\n \"<closing-tag>\":\n [\"<lt>/<id><gt>\"],\n\n \"<self-closing-tag>\":\n [\"<lt><id><attrs>/<gt>\"],\n})",
"_____no_output_____"
]
],
[
[
"Finally, HTML tags can have attributes, which are enclosed in quotes.",
"_____no_output_____"
]
],
[
[
"SIMPLE_HTML_GRAMMAR.update({\n \"<attrs>\":\n [\"<attr>\", \"<attr><attrs>\" ],\n\n \"<attr>\":\n [\" <id>='<plain-text>'\",\n ' <id>=\"<plain-text>\"'],\n})",
"_____no_output_____"
]
],
[
[
"Again, we can generate inputs from the grammar.",
"_____no_output_____"
]
],
[
[
"simple_html_fuzzer = GrammarFuzzer(SIMPLE_HTML_GRAMMAR)",
"_____no_output_____"
],
[
"for i in range(10):\n fuzz_html = simple_html_fuzzer.fuzz()\n print(repr(fuzz_html))",
"'<T3 xG=\"\">'\n'<N9cd U=\\'\\' y=\\'l1\\' v0=\"\" tb4ya=\"\" UbD=\\'\\'>9</R>'\n'\\x0b'\n' ea\\\\\\\\'\n'&7'\n\"<c1 o2='' x9661lQo64T=''/>\"\n'<S4>'\n'<GMS></wAu>'\n'<j CI=\\'\\' T98sJ=\"\" DR4=\\'\\'/>'\n'<FQc90 Wt=\"\"/>'\n"
]
],
[
[
"Such inputs, of course, are great for systematic testing. Our sister book, [the fuzzing book](https://www.fuzzingbook.org/), covers these and more.",
"_____no_output_____"
],
[
"## Derivation Trees\n\nTo produce inputs from a grammar, the fuzzingbook `GrammarFuzzer` makes use of a structure called a *derivation tree* (also known as *syntax tree*). A derivation tree encodes the individual expansion steps undertaken while producing the output.",
"_____no_output_____"
]
],
[
[
"DerivationTree = Tuple[str, Optional[List[Any]]]",
"_____no_output_____"
]
],
[
[
"Let us illustrate derivation trees by example, using the last HTML output we produced.",
"_____no_output_____"
]
],
[
[
"fuzz_html",
"_____no_output_____"
]
],
[
[
"The `GrammarFuzzer` attribute `derivation_tree` holds the last tree used to produced this input. We can visualize the tree as follows:",
"_____no_output_____"
]
],
[
[
"# ignore\nfrom graphviz import Digraph",
"_____no_output_____"
],
[
"# ignore\ndef display_tree(tree: DerivationTree) -> Digraph:\n def graph_attr(dot: Digraph) -> None:\n dot.attr('node', shape='box', color='white', margin='0.0,0.0')\n dot.attr('node',\n fontname=\"'Fira Mono', 'Source Code Pro', 'Courier', monospace\")\n\n def node_attr(dot: Digraph, nid: str, symbol: str, ann: str) -> None:\n fuzzingbook.GrammarFuzzer.default_node_attr(dot, nid, symbol, ann)\n if symbol.startswith('<'):\n dot.node(repr(nid), fontcolor='#0060a0')\n else:\n dot.node(repr(nid), fontcolor='#00a060')\n dot.node(repr(nid), scale='2')\n\n return fuzzingbook.GrammarFuzzer.display_tree(tree,\n node_attr=node_attr,\n graph_attr=graph_attr)",
"_____no_output_____"
],
[
"display_tree(simple_html_fuzzer.derivation_tree)",
"_____no_output_____"
]
],
[
[
"From top to bottom, we see that the input was constructed from a `<start>` symbol, which then expanded into `html`, which then expanded into HTML text, and so on. Multiple children in a tree stand for a concatenation of individual symbols.",
"_____no_output_____"
],
[
"Internally, these trees come as pairs `(symbol, children)`, where `symbol` is the name of a node (say, `<html>`), and `children` is a (possibly empty) list of subtrees. Here are the topmost nodes of the above tree:",
"_____no_output_____"
]
],
[
[
"import pprint",
"_____no_output_____"
],
[
"pp = pprint.PrettyPrinter(depth=7)\npp.pprint(simple_html_fuzzer.derivation_tree)",
"('<start>', [('<html>', [('<tagged-text>', [('<self-closing-tag>', [...])])])])\n"
]
],
[
[
"To produce abstract failure-inducing patterns, we will work on this very structure. The idea is to\n\n1. systematically replace subtrees by other, generated, compatible subtrees (e.g. replace one `<html>` subtree in the concrete input by some other generated `<html>` subtree);\n2. see whether these subtrees also result in failures; and\n3. if they do, use the nonterminal (`<html>`) as a placeholder in the pattern.\n\nThis will involve some subtree manipulation, construction, and finally testing. First of all, though, we need to be able to turn an _existing input_ into a derivation tree.",
"_____no_output_____"
],
[
"## Parsing\n\nThe activity of creating a structure out of an unstructured input is called _parsing_. Generally speaking, a _parser_ uses a _grammar_ to create a _derivation tree_ (also called *parse tree* in parsing contexts) from a string input.",
"_____no_output_____"
],
[
"Again, there's a whole body of theory (and practice!) around constructing parsers. We make our life simple by using an existing parser (again, from [the fuzzing book](https://www.fuzzingbook.org/Parser.html)), which does just what we want. The `EarleyParser` is instantiated with a grammar such as `SIMPLE_HTML_GRAMMAR`:",
"_____no_output_____"
]
],
[
[
"from fuzzingbook.Parser import Parser, EarleyParser # minor dependency",
"_____no_output_____"
],
[
"simple_html_parser = EarleyParser(SIMPLE_HTML_GRAMMAR)",
"_____no_output_____"
]
],
[
[
"Its method `parse()` returns an iterator over multiple possible derivation trees. (There can be multiple trees because the grammar could be ambiguous). We are only interested in the first such tree. Let us parse `BAD_INPUT` and inspect the resulting ~parse tree~ ~syntax tree~ derivation tree:",
"_____no_output_____"
]
],
[
[
"bad_input_tree = list(simple_html_parser.parse(BAD_INPUT))[0]",
"_____no_output_____"
],
[
"display_tree(bad_input_tree)",
"_____no_output_____"
]
],
[
[
"This derivation tree has the same structure as the one created from our `GrammarFuzzer` above. We see how the `<tagged-text>` is composed of three elements:\n\n1. an`<opening-tag>` (`<foo>`);\n2. a `<html>` element which becomes `<plain-text>` (`\"bar`); and\n3. a `<closing-tag>` (`</foo>`).",
"_____no_output_____"
],
[
"We can easily turn the tree back into a string. The method `tree_to_string()` traverses the tree left-to-right and joins all nonterminal symbols.",
"_____no_output_____"
]
],
[
[
"from fuzzingbook.GrammarFuzzer import tree_to_string, all_terminals",
"_____no_output_____"
],
[
"tree_to_string(bad_input_tree)",
"_____no_output_____"
],
[
"assert tree_to_string(bad_input_tree) == BAD_INPUT",
"_____no_output_____"
]
],
[
[
"With this, we can now\n\n* parse an input into a tree structure;\n* (re-)create parts of the tree structure; and\n* turn the tree back into an input string.",
"_____no_output_____"
],
[
"## Mutating the Tree\n\nWe introduce a class `TreeMutator` that is set to mutate a tree. Its constructor takes a grammar and a tree.",
"_____no_output_____"
]
],
[
[
"from fuzzingbook.Grammars import is_valid_grammar",
"_____no_output_____"
],
[
"class TreeMutator:\n \"\"\"Grammar-based mutations of derivation trees.\"\"\"\n\n def __init__(self, grammar: Grammar, tree: DerivationTree,\n fuzzer: Optional[GrammarFuzzer] = None, log: Union[bool, int] = False):\n \"\"\"\n Constructor. \n `grammar` is the underlying grammar; \n `tree` is the tree to work on.\n `fuzzer` is the grammar fuzzer to use (default: `GrammarFuzzer`)\n \"\"\"\n\n assert is_valid_grammar(grammar)\n self.grammar = grammar\n self.tree = tree\n self.log = log\n\n if fuzzer is None:\n fuzzer = GrammarFuzzer(grammar)\n\n self.fuzzer = fuzzer",
"_____no_output_____"
]
],
[
[
"### Referencing Subtrees",
"_____no_output_____"
],
[
"To reference individual elements in the tree, we introduce the concept of a _path_. A path is a list of numbers indicating the children (starting with 0) we should follow. A path `[0, 0, 0, ..., 0]` stands for the leftmost child in a tree.",
"_____no_output_____"
]
],
[
[
"TreePath = List[int]",
"_____no_output_____"
]
],
[
[
"The method `get_subtree()` returns the subtree for a given path.",
"_____no_output_____"
]
],
[
[
"class TreeMutator(TreeMutator):\n def get_subtree(self, path: TreePath, tree: Optional[DerivationTree] = None) -> DerivationTree:\n \"\"\"Access a subtree based on `path` (a list of children numbers)\"\"\"\n if tree is None:\n tree = self.tree\n\n symbol, children = tree\n\n if not path or children is None:\n return tree\n\n return self.get_subtree(path[1:], children[path[0]])",
"_____no_output_____"
]
],
[
[
"Here's `get_subtree()` in action. We instantiate a `TreeMutator` on the `BAD_INPUT` tree as shown above and return the element at the path `[0, 0, 1, 0]` – i.e. follow the leftmost edge twice, than the second-to-leftmost edge, then the leftmost edge again. This gives us the `<plain-text>` subtree representing the string `\"bar`:",
"_____no_output_____"
]
],
[
[
"def bad_input_tree_mutator() -> TreeMutator:\n return TreeMutator(SIMPLE_HTML_GRAMMAR, bad_input_tree, log=2) ",
"_____no_output_____"
],
[
"plain_text_subtree = bad_input_tree_mutator().get_subtree([0, 0, 1, 0])\npp.pprint(plain_text_subtree)",
"('<plain-text>',\n [('<plain-char>', [('<other>', [('\"', [])])]),\n ('<plain-text>',\n [('<plain-char>', [('<letter>', [...])]),\n ('<plain-text>', [('<plain-char>', [...]), ('<plain-text>', [...])])])])\n"
],
[
"tree_to_string(plain_text_subtree)",
"_____no_output_____"
],
[
"# ignore\ndef primes_generator() -> Generator[int, None, None]:\n # Adapted from https://www.python.org/ftp/python/doc/nluug-paper.ps\n primes = [2]\n yield 2\n i = 3\n while True:\n for p in primes:\n if i % p == 0 or p * p > i:\n break\n\n if i % p != 0:\n primes.append(i)\n yield i\n\n i += 2",
"_____no_output_____"
],
[
"# ignore\nprime_numbers = primes_generator()",
"_____no_output_____"
],
[
"quiz(\"In `bad_input_tree`, what is \"\n \" the subtree at the path `[0, 0, 2, 1]` as string?\", \n [\n f\"`{tree_to_string(bad_input_tree_mutator().get_subtree([0, 0, 2, 0]))}`\",\n f\"`{tree_to_string(bad_input_tree_mutator().get_subtree([0, 0, 2, 1]))}`\",\n f\"`{tree_to_string(bad_input_tree_mutator().get_subtree([0, 0, 2]))}`\",\n f\"`{tree_to_string(bad_input_tree_mutator().get_subtree([0, 0, 0]))}`\",\n ], 'next(prime_numbers)', globals()\n )",
"_____no_output_____"
]
],
[
[
"### Creating new Subtrees\n\nThe method `new_tree()` creates a new subtree for the given `<start_symbol>` according to the rules of the grammar. It invokes `expand_tree()` on the given `GrammarFuzzer` – a method that takes an initial (empty) tree and expands it until no more expansions are left.",
"_____no_output_____"
]
],
[
[
"class TreeMutator(TreeMutator):\n def new_tree(self, start_symbol: str) -> DerivationTree:\n \"\"\"Create a new subtree for <start_symbol>.\"\"\"\n\n if self.log >= 2:\n print(f\"Creating new tree for {start_symbol}\")\n\n tree = (start_symbol, None)\n return self.fuzzer.expand_tree(tree)",
"_____no_output_____"
]
],
[
[
"Here is an example of `new_tree()`:",
"_____no_output_____"
]
],
[
[
"plain_text_tree = cast(TreeMutator, bad_input_tree_mutator()).new_tree('<plain-text>')\ndisplay_tree(plain_text_tree)",
"Creating new tree for <plain-text>\n"
],
[
"tree_to_string(plain_text_tree)",
"_____no_output_____"
]
],
[
[
"### Mutating the Tree\n\nWith us now being able to \n* access a particular path in the tree (`get_subtree()`) and\n* create a new subtree (`new_tree()`),\n\nwe can mutate the tree at a given path. This is the task of `mutate()`.",
"_____no_output_____"
]
],
[
[
"class TreeMutator(TreeMutator):\n def mutate(self, path: TreePath, tree: Optional[DerivationTree] = None) -> DerivationTree:\n \"\"\"Return a new tree mutated at `path`\"\"\"\n if tree is None:\n tree = self.tree\n assert tree is not None\n\n symbol, children = tree\n\n if not path or children is None:\n return self.new_tree(symbol)\n\n head = path[0]\n new_children = (children[:head] +\n [self.mutate(path[1:], children[head])] +\n children[head + 1:])\n return symbol, new_children",
"_____no_output_____"
]
],
[
[
"Here is an example of `mutate()` in action. We mutate `bad_input_tree` at the path `[0, 0, 1, 0]` – that is, `<plain-text>`:",
"_____no_output_____"
]
],
[
[
"mutated_tree = cast(TreeMutator, bad_input_tree_mutator()).mutate([0, 0, 1, 0])\ndisplay_tree(mutated_tree)",
"Creating new tree for <plain-text>\n"
]
],
[
[
"We see that the `<plain-text>` subtree is now different, which also becomes evident in the string representation.",
"_____no_output_____"
]
],
[
[
"tree_to_string(mutated_tree)",
"_____no_output_____"
]
],
[
[
"## Generalizing Trees\n\nNow for the main part – finding out which parts of a tree can be generalized. Our idea is to _test_ a finite number of mutations to a subtree (say, 10). If all of these tests fail as well, then we assume we can generalize the subtree to a placeholder.",
"_____no_output_____"
],
[
"We introduce a class `TreeGeneralizer` for this purpose. On top of `grammar` and `tree` already used for the `TreeMutator` constructor, the `TreeGeneralizer` also takes a `test` function.",
"_____no_output_____"
]
],
[
[
"class TreeGeneralizer(TreeMutator):\n \"\"\"Determine which parts of a derivation tree can be generalized.\"\"\"\n\n def __init__(self, grammar: Grammar, tree: DerivationTree, test: Callable,\n max_tries_for_generalization: int = 10, **kwargs: Any) -> None:\n \"\"\"\n Constructor. `grammar` and `tree` are as in `TreeMutator`.\n `test` is a function taking a string that either\n * raises an exception, indicating test failure;\n * or not, indicating test success.\n `max_tries_for_generalization` is the number of times\n an instantiation has to fail before it is generalized.\n \"\"\"\n\n super().__init__(grammar, tree, **kwargs)\n self.test = test\n self.max_tries_for_generalization = max_tries_for_generalization",
"_____no_output_____"
]
],
[
[
"The `test` function is used in `test_tree()`, returning `False` if the test fails (raising an exception), and `True` if the test passes (no exception).",
"_____no_output_____"
]
],
[
[
"class TreeGeneralizer(TreeGeneralizer):\n def test_tree(self, tree: DerivationTree) -> bool:\n \"\"\"Return True if testing `tree` passes, else False\"\"\"\n s = tree_to_string(tree)\n if self.log:\n print(f\"Testing {repr(s)}...\", end=\"\")\n try:\n self.test(s)\n except Exception as exc:\n if self.log:\n print(f\"FAIL ({type(exc).__name__})\")\n ret = False\n else:\n if self.log:\n print(f\"PASS\")\n ret = True\n\n return ret",
"_____no_output_____"
]
],
[
[
"### Testing for Generalization\n\nThe `can_generalize()` method brings the above methods together. It creates a number of tree mutations at the given path, and returns True if all of them produce a failure. (Note that this is not as sophisticated as our [delta debugger](DeltaDebugger.ipynb) implementation, which also checks that the _same_ error occurs.)",
"_____no_output_____"
]
],
[
[
"class TreeGeneralizer(TreeGeneralizer):\n def can_generalize(self, path: TreePath, tree: Optional[DerivationTree] = None) -> bool:\n \"\"\"Return True if the subtree at `path` can be generalized.\"\"\"\n for i in range(self.max_tries_for_generalization):\n mutated_tree = self.mutate(path, tree)\n if self.test_tree(mutated_tree):\n # Failure no longer occurs; cannot abstract\n return False\n\n return True",
"_____no_output_____"
]
],
[
[
"Let us put `TreeGeneralizer` into action. We can directly use `remove_html_markup()` as test function.",
"_____no_output_____"
]
],
[
[
"def bad_input_tree_generalizer(**kwargs: Any) -> TreeGeneralizer:\n return TreeGeneralizer(SIMPLE_HTML_GRAMMAR, bad_input_tree,\n remove_html_markup, **kwargs)",
"_____no_output_____"
]
],
[
[
"On our `BAD_INPUT` (and its tree), can we generalize the root `<html>` node? In other words, does the failure occur for all possible `<html>` inputs?",
"_____no_output_____"
]
],
[
[
"bad_input_tree_generalizer(log=True).can_generalize([0])",
"Testing \"<l35Gmq W2G571=''>\"...PASS\n"
]
],
[
[
"The answer is no. The first alternative passes the test; hence no generalization.",
"_____no_output_____"
],
[
"How about the middle `<plain_text>` part? Can we generalize this?",
"_____no_output_____"
]
],
[
[
"bad_input_tree_generalizer(log=True).can_generalize([0, 0, 1, 0])",
"Testing '<foo>8</foo>'...PASS\n"
]
],
[
[
"The answer is no – just as above.",
"_____no_output_____"
],
[
"How about the closing tag? Can we generalize this one?",
"_____no_output_____"
]
],
[
[
"bad_input_tree_generalizer(log=True).can_generalize([0, 0, 2])",
"Testing '<foo>\"bar</e7N>'...FAIL (AssertionError)\nTesting '<foo>\"bar</q37A>'...FAIL (AssertionError)\nTesting '<foo>\"bar</W>'...FAIL (AssertionError)\nTesting '<foo>\"bar</z93Q5>'...FAIL (AssertionError)\nTesting '<foo>\"bar</WR>'...FAIL (AssertionError)\nTesting '<foo>\"bar</m>'...FAIL (AssertionError)\nTesting '<foo>\"bar</Uy443wt1h7>'...FAIL (AssertionError)\nTesting '<foo>\"bar</fon2>'...FAIL (AssertionError)\nTesting '<foo>\"bar</M>'...FAIL (AssertionError)\nTesting '<foo>\"bar</g9>'...FAIL (AssertionError)\n"
]
],
[
[
"Yes, we can! All alternate instantiations of `<closing-tag>` result in a failure.",
"_____no_output_____"
]
],
[
[
"quiz(\"Is this also true for `<opening-tag>`?\",\n [\n \"Yes\",\n \"No\"\n ], '(\"Yes\" == \"Yes\") + (\"No\" == \"No\")')",
"_____no_output_____"
]
],
[
[
"Note that the above does not hold for `<opening-tag>`. If the attribute value contains a quote character, it will extend to the end of the input. This is another error, but not caught by our assertion; hence, the input will be flagged as passing:",
"_____no_output_____"
]
],
[
[
"BAD_ATTR_INPUT = '<foo attr=\"\\'\">bar</foo>'",
"_____no_output_____"
],
[
"remove_html_markup(BAD_ATTR_INPUT)",
"_____no_output_____"
]
],
[
[
"The effect of this is that there are patterns for `<opening-tag>` which do not cause the failure to occur; hence, `<opening-tag>` is not a fully valid generalization.",
"_____no_output_____"
],
[
"This, however, becomes apparent only if one of our generated tests includes a quote character in the attribute value. Since quote characters are as likely (or as unlikely) to appear as other characters, this effect may not become apparent in our default 10 tests:",
"_____no_output_____"
]
],
[
[
"bad_input_tree_generalizer().can_generalize([0, 0, 0])",
"_____no_output_____"
]
],
[
[
"It will become apparent, however, as we increase the number of tests:",
"_____no_output_____"
]
],
[
[
"bad_input_tree_generalizer(max_tries_for_generalization=100, log=True).can_generalize([0, 0, 0])",
"Testing '<Ada np=\\'7\\' y7v=\\'\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<B V=\\'\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<K v=\"$\" s5F=\"\\x0b\" q=\"\" E=\\'\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<Fcdt8 v7A4u=\\'.\\t\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<s n=\"\">\"bar</foo>'...FAIL (AssertionError)\nTesting '<W>\"bar</foo>'...FAIL (AssertionError)\nTesting '<ap>\"bar</foo>'...FAIL (AssertionError)\nTesting '<B1>\"bar</foo>'...FAIL (AssertionError)\nTesting '<Q00wY M=\\'\\r \\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<O6 d7=\"\" H=\\'\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<v1IH w=\"\" ZI=\"\" O=\"\">\"bar</foo>'...FAIL (AssertionError)\nTesting '<T1 w998=\\'a\\' j=\\'z\\n7\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<Dnh1>\"bar</foo>'...FAIL (AssertionError)\nTesting '<D F9=\"\" x4=\\'\\' Hup=\\'7\\n\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<l62E>\"bar</foo>'...FAIL (AssertionError)\nTesting '<k11 P8x5=\"\">\"bar</foo>'...FAIL (AssertionError)\nTesting '<V6LBVu>\"bar</foo>'...FAIL (AssertionError)\nTesting '<k9S>\"bar</foo>'...FAIL (AssertionError)\nTesting '<tU2J913 lQ6N=\\'\\' f=\\'*\\' V=\\'\\' b=\"\" l=\"\" G=\\'\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<X O=\"U~\">\"bar</foo>'...FAIL (AssertionError)\nTesting '<q4 W=\\'\\' i=\\'aA9\\' I=\\'9\\'>\"bar</foo>'...FAIL (AssertionError)\nTesting '<HK>\"bar</foo>'...FAIL (AssertionError)\nTesting '<T>\"bar</foo>'...FAIL (AssertionError)\nTesting '<NJc j32=\"\\x0b\">\"bar</foo>'...FAIL (AssertionError)\nTesting '<G>\"bar</foo>'...FAIL (AssertionError)\nTesting '<w B=\"\\r\">\"bar</foo>'...FAIL (AssertionError)\nTesting '<Ac1>\"bar</foo>'...FAIL (AssertionError)\nTesting '<vB y2=\\'7x\\'\\'>\"bar</foo>'...PASS\n"
]
],
[
[
"We see that our approach may _overgeneralize_ – producing a generalization that may be too lenient. In practice, this is not too much of a problem, as we would be interested in characterizing cases that trigger the failure, rather than characterizing a small subset that does not trigger the failure.",
"_____no_output_____"
],
[
"### Generalizable Paths\n\nUsing `can_generalize()`, we can devise a method `generalizable_paths()` that returns all paths in the tree that can be generalized.",
"_____no_output_____"
]
],
[
[
"class TreeGeneralizer(TreeGeneralizer):\n def find_paths(self, \n predicate: Callable[[TreePath, DerivationTree], bool], \n path: Optional[TreePath] = None, \n tree: Optional[DerivationTree] = None) -> List[TreePath]:\n \"\"\"\n Return a list of all paths for which `predicate` holds.\n `predicate` is a function `predicate`(`path`, `tree`), where\n `path` denotes a subtree in `tree`. If `predicate()` returns\n True, `path` is included in the returned list.\n \"\"\"\n\n if path is None:\n path = []\n assert path is not None\n\n if tree is None:\n tree = self.tree\n assert tree is not None\n\n symbol, children = self.get_subtree(path)\n\n if predicate(path, tree):\n return [path]\n\n paths = []\n if children is not None:\n for i, child in enumerate(children):\n child_symbol, _ = child\n if child_symbol in self.grammar:\n paths += self.find_paths(predicate, path + [i])\n\n return paths\n\n def generalizable_paths(self) -> List[TreePath]:\n \"\"\"Return a list of all paths whose subtrees can be generalized.\"\"\"\n return self.find_paths(self.can_generalize)",
"_____no_output_____"
]
],
[
[
"Here is `generalizable_paths()` in action. We obtain all (paths to) subtrees that can be generalized:",
"_____no_output_____"
]
],
[
[
"bad_input_generalizable_paths = \\\n cast(TreeGeneralizer, bad_input_tree_generalizer()).generalizable_paths()\nbad_input_generalizable_paths",
"_____no_output_____"
]
],
[
[
"To convert these subtrees into abstract failure-inducing patterns, the method `generalize_path()` returns a copy of the tree with the subtree replaced by a nonterminal without children:",
"_____no_output_____"
]
],
[
[
"class TreeGeneralizer(TreeGeneralizer):\n def generalize_path(self, path: TreePath, \n tree: Optional[DerivationTree] = None) -> DerivationTree:\n \"\"\"Return a copy of the tree in which the subtree at `path`\n is generalized (= replaced by a nonterminal without children)\"\"\"\n\n if tree is None:\n tree = self.tree\n assert tree is not None\n\n symbol, children = tree\n\n if not path or children is None:\n return symbol, None # Nonterminal without children\n\n head = path[0]\n new_children = (children[:head] +\n [self.generalize_path(path[1:], children[head])] +\n children[head + 1:])\n return symbol, new_children",
"_____no_output_____"
]
],
[
[
"The function `all_terminals()` expands these placeholders:",
"_____no_output_____"
]
],
[
[
"all_terminals(cast(TreeGeneralizer, bad_input_tree_generalizer()).generalize_path([0, 0, 0]))",
"_____no_output_____"
]
],
[
[
"Finally, the method `generalize()` obtains a tree in which all generalizable paths actually are generalized:",
"_____no_output_____"
]
],
[
[
"class TreeGeneralizer(TreeGeneralizer):\n def generalize(self) -> DerivationTree:\n \"\"\"Returns a copy of the tree in which all generalizable subtrees\n are generalized (= replaced by nonterminals without children)\"\"\"\n tree = self.tree\n assert tree is not None\n\n for path in self.generalizable_paths():\n tree = self.generalize_path(path, tree)\n\n return tree",
"_____no_output_____"
],
[
"abstract_failure_inducing_input = cast(TreeGeneralizer, bad_input_tree_generalizer()).generalize()",
"_____no_output_____"
]
],
[
[
"This gives us the final generalization of `BAD_INPUT`. In the abstract failure-inducing input, all generalizable elements are generalized.",
"_____no_output_____"
]
],
[
[
"all_terminals(abstract_failure_inducing_input)",
"_____no_output_____"
]
],
[
[
"We see that to obtain the failure, it suffices to have an `<opening-tag>`, followed by a quote and (any) `<plain-text>` and (any) `<closing-tag>`. Clearly, all that it takes to produce the failure is to have a double quote in the plain text.",
"_____no_output_____"
],
[
"Also note how this diagnosis was reached through _experiments_ only – just as with [delta debugging](DeltaDebugger.ipynb), we could treat the program under test as a black box. In contrast to delta debugging, however, we obtain an _abstraction_ that generalizes the circumstances under which a given failure occurs.",
"_____no_output_____"
],
[
"## Fuzzing with Patterns\n\nOne neat side effect of abstract failure-inducing patterns is that they can be easily instantiated into further test cases, all set to reproduce the failure in question. This gives us a test suite we can later test our fix against.",
"_____no_output_____"
],
[
"The method `fuzz_tree()` takes a tree representing an abstract failure-inducing input and instantiates all missing subtrees.",
"_____no_output_____"
]
],
[
[
"import copy",
"_____no_output_____"
],
[
"class TreeGeneralizer(TreeGeneralizer):\n def fuzz_tree(self, tree: DerivationTree) -> DerivationTree:\n \"\"\"Return an instantiated copy of `tree`.\"\"\"\n tree = copy.deepcopy(tree)\n return self.fuzzer.expand_tree(tree)",
"_____no_output_____"
],
[
"bitg = cast(TreeGeneralizer, bad_input_tree_generalizer())\nfor i in range(10):\n print(all_terminals(bitg.fuzz_tree(abstract_failure_inducing_input)))",
"<UzL3Ct6>\"</p>\n<nw10E6>\"</W>\n<h lV=\"'\">\"</x8>\n<k>\"</u>\n<a0 l0820650g='3'>\"</v5t>\n<zTg>\"</o1Z>\n<yMgT02p s=\"\" g94e='R'>\"</P2>\n<Y>\"</S9b>\n<X2566xS8v2>\"</r13>\n<D48>\"\t</R>\n"
]
],
[
[
"We can take these inputs and see whether they reproduce the failure in question:",
"_____no_output_____"
]
],
[
[
"successes = 0\nfailures = 0\ntrials = 1000\n\nfor i in range(trials):\n test_input = all_terminals(\n bitg.fuzz_tree(abstract_failure_inducing_input))\n try:\n remove_html_markup(test_input)\n except AssertionError:\n successes += 1\n else:\n failures += 1",
"_____no_output_____"
],
[
"successes, failures",
"_____no_output_____"
]
],
[
[
"We get an overall failure rate of ~98%, which is not bad at all.",
"_____no_output_____"
]
],
[
[
"failures / 1000",
"_____no_output_____"
]
],
[
[
"In our case, it is _overgeneralization_ (as discussed above) that is responsible for not reaching a 100% rate. (In all generality, we are trying to approximate the behavior of a Turing machine with a context free grammar, which is, well, always an approximation.) However, even a lower rate would still be useful, as any additional test case that reproduces a failure helps in ensuring the final fix is complete.",
"_____no_output_____"
],
[
"## Putting it all Together\n\nLet us now put together all this in a more convenient package that does not require the user to parse and unparse derivation trees.",
"_____no_output_____"
],
[
"Our `DDSetDebugger` is modeled after the `DeltaDebugger` from [the chapter on delta debugging](DeltaDebugger.ipynb). It is to be used as\n\n```python\nwith DDSetDebugger(grammar) as dd:\n some_failing_function(...)\n```\n\nAfter that, evaluating `dd` yields a generalized abstract failure-inducing input as a string.",
"_____no_output_____"
],
[
"Since `DDSetDebugger` accepts only one grammar, the function to be debugged should have exactly one string argument (besides other arguments); this string must fit the grammar.",
"_____no_output_____"
],
[
"### Constructor",
"_____no_output_____"
],
[
"The constructor puts together the various components. It allows for customization by subclassing.",
"_____no_output_____"
]
],
[
[
"from DeltaDebugger import CallCollector",
"_____no_output_____"
],
[
"class DDSetDebugger(CallCollector):\n \"\"\"\n Debugger implementing the DDSET algorithm for abstracting failure-inducing inputs.\n \"\"\"\n\n def __init__(self, grammar: Grammar, \n generalizer_class: Type = TreeGeneralizer,\n parser: Optional[Parser] = None,\n **kwargs: Any) -> None:\n \"\"\"Constructor.\n `grammar` is an input grammar in fuzzingbook format.\n `generalizer_class` is the tree generalizer class to use\n (default: `TreeGeneralizer`)\n `parser` is the parser to use (default: `EarleyParser(grammar)`).\n All other keyword args are passed to the tree generalizer, notably:\n `fuzzer` - the fuzzer to use (default: `GrammarFuzzer`), and\n `log` - enables debugging output if True.\n \"\"\"\n super().__init__()\n self.grammar = grammar\n assert is_valid_grammar(grammar)\n\n self.generalizer_class = generalizer_class\n\n if parser is None:\n parser = EarleyParser(grammar)\n self.parser = parser\n self.kwargs = kwargs\n\n # These save state for further fuzz() calls\n self.generalized_args: Dict[str, Any] = {}\n self.generalized_trees: Dict[str, DerivationTree] = {}\n self.generalizers: Dict[str, TreeGeneralizer] = {}",
"_____no_output_____"
]
],
[
[
"### Generalizing Arguments",
"_____no_output_____"
],
[
"The method `generalize()` is the many entry point. For all string arguments collected in the first function call, it generalizes the arguments and returns an abstract failure-inducing string.",
"_____no_output_____"
]
],
[
[
"class DDSetDebugger(DDSetDebugger):\n def generalize(self) -> Dict[str, Any]:\n \"\"\"\n Generalize arguments seen. For each function argument,\n produce an abstract failure-inducing input that characterizes\n the set of inputs for which the function fails.\n \"\"\"\n if self.generalized_args:\n return self.generalized_args\n\n self.generalized_args = copy.deepcopy(self.args())\n self.generalized_trees = {}\n self.generalizers = {}\n\n for arg in self.args():\n def test(value: Any) -> Any:\n return self.call({arg: value})\n\n value = self.args()[arg]\n if isinstance(value, str):\n tree = list(self.parser.parse(value))[0]\n gen = self.generalizer_class(self.grammar, tree, test, \n **self.kwargs)\n generalized_tree = gen.generalize()\n\n self.generalizers[arg] = gen\n self.generalized_trees[arg] = generalized_tree\n self.generalized_args[arg] = all_terminals(generalized_tree)\n\n return self.generalized_args",
"_____no_output_____"
],
[
"class DDSetDebugger(DDSetDebugger):\n def __repr__(self) -> str:\n \"\"\"Return a string representation of the generalized call.\"\"\"\n return self.format_call(self.generalize())",
"_____no_output_____"
]
],
[
[
"Here is an example of how `DDSetDebugger` would be used on our `BAD_INPUT` example. Simply evaluating the debugger yields a call with a generalized input.",
"_____no_output_____"
]
],
[
[
"with DDSetDebugger(SIMPLE_HTML_GRAMMAR) as dd:\n remove_html_markup(BAD_INPUT)\ndd",
"_____no_output_____"
]
],
[
[
"### Fuzzing\n\nThe `fuzz()` method produces instantiations of the abstract failure-inducing pattern.",
"_____no_output_____"
]
],
[
[
"class DDSetDebugger(DDSetDebugger):\n def fuzz_args(self) -> Dict[str, Any]:\n \"\"\"\n Return arguments randomly instantiated\n from the abstract failure-inducing pattern.\n \"\"\"\n if not self.generalized_trees:\n self.generalize()\n\n args = copy.deepcopy(self.generalized_args)\n for arg in args:\n if arg not in self.generalized_trees:\n continue\n\n tree = self.generalized_trees[arg]\n gen = self.generalizers[arg]\n instantiated_tree = gen.fuzz_tree(tree)\n args[arg] = all_terminals(instantiated_tree)\n\n return args\n\n def fuzz(self) -> str:\n \"\"\"\n Return a call with arguments randomly instantiated\n from the abstract failure-inducing pattern.\n \"\"\"\n return self.format_call(self.fuzz_args())",
"_____no_output_____"
]
],
[
[
"Here are some axamples of `fuzz()` in action:",
"_____no_output_____"
]
],
[
[
"with DDSetDebugger(SIMPLE_HTML_GRAMMAR) as dd:\n remove_html_markup(BAD_INPUT)",
"_____no_output_____"
],
[
"dd.fuzz()",
"_____no_output_____"
],
[
"dd.fuzz()",
"_____no_output_____"
],
[
"dd.fuzz()",
"_____no_output_____"
]
],
[
[
" These can be fed into `eval()`, set to produce more failing calls.",
"_____no_output_____"
]
],
[
[
"with ExpectError(AssertionError):\n eval(dd.fuzz())",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_58133/2072246869.py\", line 2, in <module>\n eval(dd.fuzz())\n File \"<string>\", line 1, in <module>\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_58133/2717035104.py\", line 17, in remove_html_markup\n assert '<' not in out and '>' not in out\nAssertionError (expected)\n"
]
],
[
[
"## More Examples\n\nLet us apply `DDSetDebugger` on more examples.",
"_____no_output_____"
],
[
"### Square Root\n\nOur first example is the `square_root()` function from [the chapter on assertions](Assertions.ipynb).",
"_____no_output_____"
]
],
[
[
"from Assertions import square_root # minor dependency",
"_____no_output_____"
]
],
[
[
"The `square_root()` function fails on a value of `-1`:",
"_____no_output_____"
]
],
[
[
"with ExpectError(AssertionError):\n square_root(-1)",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_58133/1205325604.py\", line 2, in <module>\n square_root(-1)\n File \"/Users/zeller/Projects/debuggingbook/notebooks/Assertions.ipynb\", line 55, in square_root\n assert x >= 0 # precondition\nAssertionError (expected)\n"
]
],
[
[
"We define a grammar for its arguments:",
"_____no_output_____"
]
],
[
[
"INT_GRAMMAR: Grammar = {\n \"<start>\":\n [\"<int>\"],\n\n \"<int>\":\n [\"<positive-int>\", \"-<positive-int>\"],\n\n \"<positive-int>\":\n [\"<digit>\", \"<nonzero-digit><positive-int>\"],\n\n \"<nonzero-digit>\": list(\"123456789\"),\n \n \"<digit>\": list(string.digits),\n}",
"_____no_output_____"
]
],
[
[
"The test function takes a string and converts it into an integer:",
"_____no_output_____"
]
],
[
[
"def square_root_test(s: str) -> None:\n return square_root(int(s))",
"_____no_output_____"
]
],
[
[
"With this, we can go and see whether we can generalize a failing input:",
"_____no_output_____"
]
],
[
[
"with DDSetDebugger(INT_GRAMMAR, log=True) as dd_square_root:\n square_root_test(\"-1\")",
"_____no_output_____"
],
[
"dd_square_root",
"Testing '-8'...FAIL (AssertionError)\nTesting '-316'...FAIL (AssertionError)\nTesting '8'...PASS\nTesting '684'...PASS\nTesting '-3'...FAIL (AssertionError)\nTesting '-870'...FAIL (AssertionError)\nTesting '-3'...FAIL (AssertionError)\nTesting '-3451'...FAIL (AssertionError)\nTesting '-8'...FAIL (AssertionError)\nTesting '-63213'...FAIL (AssertionError)\nTesting '-26'...FAIL (AssertionError)\nTesting '-4'...FAIL (AssertionError)\nTesting '-6'...FAIL (AssertionError)\nTesting '-8'...FAIL (AssertionError)\n"
]
],
[
[
"Success! Using `DDSetDebugger`, we have nicely generalized the failure-inducing input to a pattern `-<positive-int>` that translates into \"any negative number\".",
"_____no_output_____"
],
[
"### Middle\n\nThe `middle()` function from [the chapter on statistical debugging](StatisticalDebugger.ipynb) returns the middle of three numerical values `x`, `y`, and `z`.",
"_____no_output_____"
]
],
[
[
"from StatisticalDebugger import middle # minor dependency",
"_____no_output_____"
]
],
[
[
"We set up a test function that evaluates a string – a tuple of three arguments – and then tests `middle()`:",
"_____no_output_____"
]
],
[
[
"def middle_test(s: str) -> None:\n x, y, z = eval(s)\n assert middle(x, y, z) == sorted([x, y, z])[1]",
"_____no_output_____"
]
],
[
[
"The grammar for the three numbers simply puts three integers together:",
"_____no_output_____"
]
],
[
[
"XYZ_GRAMMAR: Grammar = {\n \"<start>\":\n [\"<int>, <int>, <int>\"],\n\n \"<int>\":\n [\"<positive-int>\", \"-<positive-int>\"],\n\n \"<positive-int>\":\n [\"<digit>\", \"<nonzero-digit><positive-int>\"],\n\n \"<nonzero-digit>\": list(\"123456789\"),\n \n \"<digit>\": list(string.digits),\n}",
"_____no_output_____"
]
],
[
[
"Here is an example of `middle()` failing:",
"_____no_output_____"
]
],
[
[
"with ExpectError(AssertionError):\n middle_test(\"2, 1, 3\")",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_58133/982110330.py\", line 2, in <module>\n middle_test(\"2, 1, 3\")\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_58133/3079946275.py\", line 3, in middle_test\n assert middle(x, y, z) == sorted([x, y, z])[1]\nAssertionError (expected)\n"
]
],
[
[
"What happens if we debug this with `DDSetDebugger`? We see that there is no abstraction at the syntax level that could characterize this failure:",
"_____no_output_____"
]
],
[
[
"with DDSetDebugger(XYZ_GRAMMAR, log=True) as dd_middle:\n middle_test(\"2, 1, 3\")",
"_____no_output_____"
],
[
"dd_middle",
"Testing '7, 4591, -0'...PASS\nTesting '6, 1, 3'...PASS\nTesting '7, 1, 3'...PASS\nTesting '7, 1, 3'...PASS\nTesting '2, -7, 3'...FAIL (AssertionError)\nTesting '2, 0, 3'...FAIL (AssertionError)\nTesting '2, -89, 3'...FAIL (AssertionError)\nTesting '2, 973, 3'...PASS\nTesting '2, 11, 3'...PASS\nTesting '2, 8, 3'...PASS\nTesting '2, 1, 9'...FAIL (AssertionError)\nTesting '2, 1, -16'...PASS\nTesting '2, 1, 35'...FAIL (AssertionError)\nTesting '2, 1, 6'...FAIL (AssertionError)\nTesting '2, 1, 53'...FAIL (AssertionError)\nTesting '2, 1, 5'...FAIL (AssertionError)\nTesting '2, 1, 737'...FAIL (AssertionError)\nTesting '2, 1, 28'...FAIL (AssertionError)\nTesting '2, 1, 3'...FAIL (AssertionError)\nTesting '2, 1, 5'...FAIL (AssertionError)\nTesting '2, 1, 5'...FAIL (AssertionError)\nTesting '2, 1, 56'...FAIL (AssertionError)\n"
]
],
[
[
"So, while there are failures that can be nicely characterized using abstractions of input elements, `middle()` is not one of them. Which is good, because this means that all our other techniques such as [statistical debugging](StatisticalDebugger.ipynb) and [dynamic invariants](DynamicInvariants.ipynb) still have a use case :-)",
"_____no_output_____"
],
[
"## Synopsis",
"_____no_output_____"
],
[
"This chapter provides a class `DDSetDebugger`, implementing the DDSET algorithm for generalizing failure-inducing inputs. The `DDSetDebugger` is used as follows:\n\n```python\nwith DDSetDebugger(grammar) as dd:\n function(args...)\ndd\n```\n\nHere, `function(args...)` is a failing function call (= raises an execption) that takes at least one string argument; `grammar` is an [input grammar in fuzzingbook format](https://www.fuzzingbook.org/html/Grammars.html) that matches the format of this argument.\n\nThe result is a call of `function()` with an _abstract failure-inducing input_ – a variant of the conrete input in which parts are replaced by placeholders in the form `<name>`, where `<name>` is a nonterminal in the grammar. The failure has been verified to occur for a number of instantiations of `<name>`.",
"_____no_output_____"
],
[
"Here is an example of how `DDSetDebugger` works. The concrete failing input `<foo>\"bar</foo>` is generalized to an _abstract failure-inducing input_:",
"_____no_output_____"
]
],
[
[
"with DDSetDebugger(SIMPLE_HTML_GRAMMAR) as dd:\n remove_html_markup('<foo>\"bar</foo>')\ndd",
"_____no_output_____"
]
],
[
[
"The abstract input tells us that the failure occurs for whatever opening and closing HTML tags as long as there is a double quote between them.",
"_____no_output_____"
],
[
"A programmatic interface is available as well. `generalize()` returns a mapping of argument names to (generalized) values:",
"_____no_output_____"
]
],
[
[
"dd.generalize()",
"_____no_output_____"
]
],
[
[
"Using `fuzz()`, the abstract input can be instantiated to further concrete inputs, all set to produce the failure again:",
"_____no_output_____"
]
],
[
[
"for i in range(10):\n print(dd.fuzz())",
"remove_html_markup(s='<s1d>\"1</hF>')\nremove_html_markup(s='<H>\"c*C</l>')\nremove_html_markup(s='<Ah2>\"</v>')\nremove_html_markup(s='<a7>\")</NP>')\nremove_html_markup(s='<boyIIt640TF>\"</b08>')\nremove_html_markup(s='<dF>\"</fay>')\nremove_html_markup(s='<l2>\"\\t7</z>')\nremove_html_markup(s='<ci>\"</t>')\nremove_html_markup(s='<J>\"2</t>')\nremove_html_markup(s='<Fo9g>\"\\r~\\t\\r</D>')\n"
]
],
[
[
"`DDSetDebugger` can be customized by passing a subclass of `TreeGeneralizer`, which does the gist of the work; for details, see its constructor.\nThe full class hierarchy is shown below.",
"_____no_output_____"
]
],
[
[
"# ignore\nfrom ClassDiagram import display_class_hierarchy",
"_____no_output_____"
],
[
"# ignore\ndisplay_class_hierarchy([DDSetDebugger, TreeGeneralizer],\n public_methods=[\n CallCollector.__init__,\n CallCollector.__enter__,\n CallCollector.__exit__,\n CallCollector.function,\n CallCollector.args,\n CallCollector.exception,\n CallCollector.call, # type: ignore\n DDSetDebugger.__init__,\n DDSetDebugger.__repr__,\n DDSetDebugger.fuzz,\n DDSetDebugger.fuzz_args,\n DDSetDebugger.generalize,\n ], project='debuggingbook')",
"_____no_output_____"
]
],
[
[
"## Lessons Learned\n\n* Generalizing failure-inducing inputs can yield important information for which inputs and under which circumstances a failure occurs.\n* Generalizing failure-inducing inputs is most useful if the input can be split into multiple elements, of which only a part are relevant for producing the error.\n* As they help in _parsing_ and _producing_ input, _grammars_ can play an important role in testing and debugging.",
"_____no_output_____"
],
[
"## Next Steps\n\nOur [next chapter](Repairer.ipynb) introduces _automated repair_ of programs, building on the fault localization and generalization mechanisms introduced so far.",
"_____no_output_____"
],
[
"## Background\n\nOur `DDSetDebugger` class implements the DDSET algorithm as introduced by Gopinath et al. in \\cite{Gopinath2020}. A [full-fledged implementation of DDSET](https://rahul.gopinath.org/post/2020/07/15/ddset/) with plenty of details and experiments is available as a Jupyter Notebook. Our implementation follows the [simplified implementation of DDSET, as described by Gopinath](https://rahul.gopinath.org/post/2020/08/03/simple-ddset/).\n\nThe potential for determining how input features relate to bugs is not nearly explored yet. \nThe ALHAZEN work by Kampmann et al. \\cite{Kampmann2020} generalizes over DDSET in a different way, by investigating _semantic_ features of input elements such as their numeric interpretation or length and their correlation with failures. Like DDSET, ALHAZEN also uses a feedback loop to strengthen or refute its hypotheses.\n\nIn recent work \\cite{Gopinath2021}, Gopinath has extended the concept of DDSET further. His work on _evocative expressions_ introduces a _pattern language_ in which arbitrary DDSET-like patterns can be combined into Boolean formula that even more precisely capture and produce failure circumstances. In particular, evocative expressions can _specialize_ grammars towards Boolean pattern combinations, thus allowing for great flexibility in testing and debugging.",
"_____no_output_____"
],
[
"## Exercises",
"_____no_output_____"
],
[
"### Exercise 1: Generalization and Specialization\n\nConsider the abstract failure-inducing input for `BAD_INPUT` we determined:",
"_____no_output_____"
]
],
[
[
"all_terminals(abstract_failure_inducing_input)",
"_____no_output_____"
]
],
[
[
"1. How does it change if you increase the number of test runs, using `max_tries_for_generalization`?\n2. What is the success rate of the new pattern?",
"_____no_output_____"
],
[
"**Solution.** We can compute this by increasing `max_tries_for_generalization`:",
"_____no_output_____"
]
],
[
[
"more_precise_bitg = \\\n cast(TreeGeneralizer, bad_input_tree_generalizer(max_tries_for_generalization=100))\n\nmore_precise_abstract_failure_inducing_input = \\\n more_precise_bitg.generalize()",
"_____no_output_____"
],
[
"all_terminals(more_precise_abstract_failure_inducing_input)",
"_____no_output_____"
]
],
[
[
"We see that we still have an opening tag; however, it no longer assumes attributes.",
"_____no_output_____"
],
[
"The success rate can be computed as before:",
"_____no_output_____"
]
],
[
[
"successes = 0\nfailures = 0\ntrials = 1000\n\nfor i in range(trials):\n test_input = all_terminals(\n more_precise_bitg.fuzz_tree(\n more_precise_abstract_failure_inducing_input))\n try:\n remove_html_markup(test_input)\n except AssertionError:\n successes += 1\n else:\n failures += 1",
"_____no_output_____"
],
[
"successes, failures",
"_____no_output_____"
],
[
"failures / 1000",
"_____no_output_____"
]
],
[
[
"We see that the success rate is now more than 99%, which is better than before. On the other hand, the pattern is now overly _special_, since there are `<opening-tags>` with attributes such that the failure occurs (but also some that cancel out the error).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e789551f3fdd7cab78cb8c2765d85cb6eef00db8 | 11,056 | ipynb | Jupyter Notebook | Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb | marceloestevam/Nanodegree_DataScientist | 3a775de1e86e0e12d0d361489eb75766a107b3cf | [
"CC0-1.0"
] | null | null | null | Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb | marceloestevam/Nanodegree_DataScientist | 3a775de1e86e0e12d0d361489eb75766a107b3cf | [
"CC0-1.0"
] | null | null | null | Chapter01__Introduction_to_Data_Science/How To Break Into the Field - Solution .ipynb | marceloestevam/Nanodegree_DataScientist | 3a775de1e86e0e12d0d361489eb75766a107b3cf | [
"CC0-1.0"
] | null | null | null | 35.098413 | 371 | 0.593253 | [
[
[
"### How To Break Into the Field\n\nNow you have had a closer look at the data, and you saw how I approached looking at how the survey respondents think you should break into the field. Let's recreate those results, as well as take a look at another question.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport HowToBreakIntoTheField as t\n%matplotlib inline\n\ndf = pd.read_csv('./survey_results_public.csv')\nschema = pd.read_csv('./survey_results_schema.csv')\ndf.head()",
"_____no_output_____"
]
],
[
[
"#### Question 1\n\n**1.** In order to understand how to break into the field, we will look at the **CousinEducation** field. Use the **schema** dataset to answer this question. Write a function called **get_description** that takes the **schema dataframe** and the **column** as a string, and returns a string of the description for that column.",
"_____no_output_____"
]
],
[
[
"def get_description(column_name, schema=schema):\n '''\n INPUT - schema - pandas dataframe with the schema of the developers survey\n column_name - string - the name of the column you would like to know about\n OUTPUT - \n desc - string - the description of the column\n '''\n desc = list(schema[schema['Column'] == column_name]['Question'])[0]\n return desc\n\n#test your code\n#Check your function against solution - you shouldn't need to change any of the below code\nget_description(df.columns[0]) # This should return a string of the first column description",
"_____no_output_____"
],
[
"#Check your function against solution - you shouldn't need to change any of the below code\ndescrips = set(get_description(col) for col in df.columns)\nt.check_description(descrips)",
"_____no_output_____"
]
],
[
[
"The question we have been focused on has been around how to break into the field. Use your **get_description** function below to take a closer look at the **CousinEducation** column.",
"_____no_output_____"
]
],
[
[
"get_description('CousinEducation')",
"_____no_output_____"
]
],
[
[
"#### Question 2\n\n**2.** Provide a pandas series of the different **CousinEducation** status values in the dataset. Store this pandas series in **cous_ed_vals**. If you are correct, you should see a bar chart of the proportion of individuals in each status. If it looks terrible, and you get no information from it, then you followed directions. However, we should clean this up!",
"_____no_output_____"
]
],
[
[
"cous_ed_vals = df.CousinEducation.value_counts()#Provide a pandas series of the counts for each CousinEducation status\n\ncous_ed_vals # assure this looks right",
"_____no_output_____"
],
[
"# The below should be a bar chart of the proportion of individuals in your ed_vals\n# if it is set up correctly.\n\n(cous_ed_vals/df.shape[0]).plot(kind=\"bar\");\nplt.title(\"Formal Education\");",
"_____no_output_____"
]
],
[
[
"We definitely need to clean this. Above is an example of what happens when you do not clean your data. Below I am using the same code you saw in the earlier video to take a look at the data after it has been cleaned.",
"_____no_output_____"
]
],
[
[
"possible_vals = [\"Take online courses\", \"Buy books and work through the exercises\", \n \"None of these\", \"Part-time/evening courses\", \"Return to college\",\n \"Contribute to open source\", \"Conferences/meet-ups\", \"Bootcamp\",\n \"Get a job as a QA tester\", \"Participate in online coding competitions\",\n \"Master's degree\", \"Participate in hackathons\", \"Other\"]\n\ndef clean_and_plot(df, title='Method of Educating Suggested', plot=True):\n '''\n INPUT \n df - a dataframe holding the CousinEducation column\n title - string the title of your plot\n axis - axis object\n plot - bool providing whether or not you want a plot back\n \n OUTPUT\n study_df - a dataframe with the count of how many individuals\n Displays a plot of pretty things related to the CousinEducation column.\n '''\n study = df['CousinEducation'].value_counts().reset_index()\n study.rename(columns={'index': 'method', 'CousinEducation': 'count'}, inplace=True)\n study_df = t.total_count(study, 'method', 'count', possible_vals)\n\n study_df.set_index('method', inplace=True)\n if plot:\n (study_df/study_df.sum()).plot(kind='bar', legend=None);\n plt.title(title);\n plt.show()\n props_study_df = study_df/study_df.sum()\n return props_study_df\n \nprops_df = clean_and_plot(df)",
"_____no_output_____"
]
],
[
[
"#### Question 4\n\n**4.** I wonder if some of the individuals might have bias towards their own degrees. Complete the function below that will apply to the elements of the **FormalEducation** column in **df**. ",
"_____no_output_____"
]
],
[
[
"def higher_ed(formal_ed_str):\n '''\n INPUT\n formal_ed_str - a string of one of the values from the Formal Education column\n \n OUTPUT\n return 1 if the string is in (\"Master's degree\", \"Professional degree\")\n return 0 otherwise\n \n '''\n if formal_ed_str in (\"Master's degree\", \"Professional degree\"):\n return 1\n else:\n return 0\n \n\ndf[\"FormalEducation\"].apply(higher_ed)[:5] #Test your function to assure it provides 1 and 0 values for the df",
"_____no_output_____"
],
[
"# Check your code here\ndf['HigherEd'] = df[\"FormalEducation\"].apply(higher_ed)\nhigher_ed_perc = df['HigherEd'].mean()\nt.higher_ed_test(higher_ed_perc)",
"_____no_output_____"
]
],
[
[
"#### Question 5\n\n**5.** Now we would like to find out if the proportion of individuals who completed one of these three programs feel differently than those that did not. Store a dataframe of only the individual's who had **HigherEd** equal to 1 in **ed_1**. Similarly, store a dataframe of only the **HigherEd** equal to 0 values in **ed_0**.\n\nNotice, you have already created the **HigherEd** column using the check code portion above, so here you only need to subset the dataframe using this newly created column.",
"_____no_output_____"
]
],
[
[
"ed_1 = df[df['HigherEd'] == 1] # Subset df to only those with HigherEd of 1\ned_0 = df[df['HigherEd'] == 0] # Subset df to only those with HigherEd of 0\n\n\nprint(ed_1['HigherEd'][:5]) #Assure it looks like what you would expect\nprint(ed_0['HigherEd'][:5]) #Assure it looks like what you would expect",
"_____no_output_____"
],
[
"#Check your subset is correct - you should get a plot that was created using pandas styling\n#which you can learn more about here: https://pandas.pydata.org/pandas-docs/stable/style.html\n\ned_1_perc = clean_and_plot(ed_1, 'Higher Formal Education', plot=False)\ned_0_perc = clean_and_plot(ed_0, 'Max of Bachelors Higher Ed', plot=False)\n\ncomp_df = pd.merge(ed_1_perc, ed_0_perc, left_index=True, right_index=True)\ncomp_df.columns = ['ed_1_perc', 'ed_0_perc']\ncomp_df['Diff_HigherEd_Vals'] = comp_df['ed_1_perc'] - comp_df['ed_0_perc']\ncomp_df.style.bar(subset=['Diff_HigherEd_Vals'], align='mid', color=['#d65f5f', '#5fba7d'])",
"_____no_output_____"
]
],
[
[
"#### Question 6\n\n**6.** What can you conclude from the above plot? Change the dictionary to mark **True** for the keys of any statements you can conclude, and **False** for any of the statements you cannot conclude.",
"_____no_output_____"
]
],
[
[
"sol = {'Everyone should get a higher level of formal education': False, \n 'Regardless of formal education, online courses are the top suggested form of education': True,\n 'There is less than a 1% difference between suggestions of the two groups for all forms of education': False,\n 'Those with higher formal education suggest it more than those who do not have it': True}\n\nt.conclusions(sol)",
"_____no_output_____"
]
],
[
[
"This concludes another look at the way we could compare education methods by those currently writing code in industry.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e78960dbf454e76e6a540be671bb326b17c76b29 | 143,238 | ipynb | Jupyter Notebook | .ipynb_checkpoints/ASAR-checkpoint.ipynb | siddharthshenoy/Keywordandsum | 3760e82eba9a5cbccadcf30b5bbe42fe538dacb9 | [
"MIT"
] | null | null | null | .ipynb_checkpoints/ASAR-checkpoint.ipynb | siddharthshenoy/Keywordandsum | 3760e82eba9a5cbccadcf30b5bbe42fe538dacb9 | [
"MIT"
] | null | null | null | .ipynb_checkpoints/ASAR-checkpoint.ipynb | siddharthshenoy/Keywordandsum | 3760e82eba9a5cbccadcf30b5bbe42fe538dacb9 | [
"MIT"
] | null | null | null | 42.962807 | 334 | 0.553247 | [
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"asar = \"./Animal Rescue incidents attended by LFB from Jan 2009.csv\"\nasar.encode('utf-8').strip()",
"_____no_output_____"
],
[
"record = pd.read_csv(asar, encoding= 'unicode_escape')",
"_____no_output_____"
],
[
"print(record.SpecialServiceType.unique())",
"['Animal assistance involving livestock - Other action'\n 'Animal rescue from below ground - Domestic pet'\n 'Animal rescue from water - Farm animal'\n 'Animal rescue from water - Domestic pet'\n 'Wild animal rescue from height'\n 'Animal rescue from height - Domestic pet'\n 'Animal rescue from water - Bird' 'Animal rescue from height - Bird'\n 'Wild animal rescue from water or mud'\n 'Animal assistance - Lift heavy livestock animal'\n 'Wild animal rescue from below ground'\n 'Animal rescue from below ground - Bird'\n 'Animal rescue from height - Farm animal'\n 'Animal rescue from below ground - Farm animal'\n 'Assist trapped domestic animal' 'Animal harm involving domestic animal'\n 'Animal assistance involving wild animal - Other action'\n 'Animal assistance involving domestic animal - Other action'\n 'Animal harm involving wild animal' 'Assist trapped livestock animal'\n 'Assist trapped wild animal' 'Animal assistance - Lift heavy wild animal'\n 'Animal assistance - Lift heavy domestic animal'\n 'Animal harm involving livestock']\n"
],
[
"import numpy as np\nimport pandas as pd\nseed = 69 # set random seed for whole document\n\n# Graph plotting\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Displaying dataframes\nfrom IPython.display import display\n\n# Natural Language Processing Thingamajibs\nimport re\nimport string\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom gensim.models import Word2Vec, word2vec\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_selection import chi2\nimport gensim\n\n# Classifiers\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import LinearSVC, SVC\n\n# Metrics to score classifiers\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, auc, roc_curve, log_loss\n\n# Data splitting, CV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score, KFold, StratifiedKFold\n\n# Lifesaver\nimport pickle",
"[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\siddharth\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n"
],
[
"asar = \"./Animal Rescue incidents attended by LFB from Jan 2009.csv\"\ndf = pd.read_csv(asar, encoding= 'unicode_escape')",
"_____no_output_____"
],
[
"df.rename(columns={'IncidentNumber':'S_NO',\n 'DateTimeOfCall':'DATE_TIME',\n 'CalYear':'YEAR',\n 'FinYear':'FYEAR',\n 'TypeOfIncident':'TYPE',\n 'PumpCount':'PUMP_COUNT',\n 'PumpHoursTotal':'PUMP_TOTAL',\n 'HourlyNotionalCost(」)':'HOUR_COST',\n 'IncidentNotionalCost(」)':'INCI_COST',\n 'FinalDescription':'MAIN_DESCRIPTION',\n 'AnimalGroupParent':'ANIMAL_TYPE',\n 'OriginofCall':'ORIGIN',\n 'PropertyType':'PROPERTY',\n 'PropertyCategory':'PROPERTYCATEGORY',\n 'SpecialServiceTypeCategory':'SERVICE_CATEGORY',\n 'SpecialServiceType':'SERVICE_TYPE',\n 'WardCode':'WARD_CODE',\n 'Ward':'WARD',\n 'BoroughCode':'BOROUGHCODE',\n 'Borough':'BOROUGH',\n 'StnGroundName':'GROUND_NAME',\n 'UPRN':'UPRN',\n 'Street':'Street',\n 'USRN':'USRN',\n 'PostcodeDistrict':'POST_CODE',\n 'Easting_m':'EASTING',\n 'Northing_m':'NORTHING',\n 'Easting_rounded':'EASTING_R',\n 'Northing_rounded':'NORTHING_R',\n 'Latitude':'LAT',\n 'Longitude':'LONGI'\n \n },inplace=True)",
"_____no_output_____"
],
[
"#since we wanna do complaint classification we just do the row with complaints/description in them",
"_____no_output_____"
],
[
"df.dropna(axis=0, subset=['MAIN_DESCRIPTION'], \n inplace=True)",
"_____no_output_____"
],
[
"#setting up dataframe for multiclass classification",
"_____no_output_____"
],
[
"# Subsetting dataframe into columns useful for our text multi-classification problem\ndf_product_and_complaint = df[['SERVICE_TYPE', 'MAIN_DESCRIPTION']]\n\n\n",
"_____no_output_____"
],
[
"## Pickling our subsetted dataframe\n#with open('df_product_and_complaint.pickle', 'wb') as to_write:\n# pickle.dump(df_product_and_complaint, to_write)",
"_____no_output_____"
],
[
"# Loading our pickled subsetted dataframe\nwith open('df_product_and_complaint.pickle', 'rb') as to_read:\n df_product_and_complaint = pickle.load(to_read)",
"_____no_output_____"
],
[
"df_product_and_complaint.info()\n#no null values nice",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 7307 entries, 0 to 7311\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 SERVICE_TYPE 7307 non-null object\n 1 MAIN_DESCRIPTION 7307 non-null object\n 2 S_ID 7307 non-null int64 \ndtypes: int64(1), object(2)\nmemory usage: 228.3+ KB\n"
],
[
"df_product_and_complaint.head(5)",
"_____no_output_____"
],
[
"df_product_and_complaint.SERVICE_TYPE.value_counts()",
"_____no_output_____"
]
],
[
[
"# Label encoding",
"_____no_output_____"
]
],
[
[
"# Applying encoding to the PRODUCT column\ndf_product_and_complaint['S_ID'] = df_product_and_complaint['SERVICE_TYPE'].factorize()[0]\n#factorize[0] arranges the index of each encoded number accordingly to the \n# index of your categorical variables in the service_type column\n\n# Creates a dataframe of the PRODUCT to their respective PRODUCT_ID\ncategory_id_df = df_product_and_complaint[['SERVICE_TYPE', 'S_ID']].drop_duplicates()\n\n# Dictionaries for future use. Creating our cheatsheets for what each encoded label represents.\ncategory_to_id = dict(category_id_df.values) # Creates a service_type: S_ID key-value pair\nid_to_category = dict(category_id_df[['S_ID', 'SERVICE_TYPE']].values) # Creates a S_ID: SERVICE_TYPE key-value pair",
"_____no_output_____"
],
[
"df_product_and_complaint.head(10)",
"_____no_output_____"
],
[
"#Now that we have encoded our columns, time to move on to the next step -- cleaning the fricken text data\n#But save our dataframe here so we don't run into memory issues later and we can start from a new starting point ",
"_____no_output_____"
],
[
"## Pickling reduced dataframe\n#with open('df_product_and_complaint.pickle', 'wb') as to_write:\n# pickle.dump(df_product_and_complaint, to_write)",
"_____no_output_____"
],
[
"# Loading Pickled DataFrame\nwith open('df_product_and_complaint.pickle', 'rb') as to_read:\n df_product_and_complaint = pickle.load(to_read)",
"_____no_output_____"
],
[
"# Reviewing our Loaded Dataframe\nprint(df_product_and_complaint.info())\nprint('--------------------------------------------------------------------------------------')\nprint(df_product_and_complaint.head().to_string())",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 7307 entries, 0 to 7311\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 SERVICE_TYPE 7307 non-null object\n 1 MAIN_DESCRIPTION 7307 non-null object\n 2 S_ID 7307 non-null int64 \ndtypes: int64(1), object(2)\nmemory usage: 228.3+ KB\nNone\n--------------------------------------------------------------------------------------\n SERVICE_TYPE MAIN_DESCRIPTION S_ID\n0 Animal assistance involving livestock - Other action DOG WITH JAW TRAPPED IN MAGAZINE RACK,B15 0\n1 Animal assistance involving livestock - Other action ASSIST RSPCA WITH FOX TRAPPED,B15 0\n2 Animal rescue from below ground - Domestic pet DOG CAUGHT IN DRAIN,B15 1\n3 Animal rescue from water - Farm animal HORSE TRAPPED IN LAKE,J17 2\n4 Animal assistance involving livestock - Other action RABBIT TRAPPED UNDER SOFA,B15 0\n"
]
],
[
[
"# Text Pre-Processing",
"_____no_output_____"
]
],
[
[
"# Looking at a sample text\nsample_complaint = list(df_product_and_complaint.MAIN_DESCRIPTION[:5])[4]\n\n# Converting to a list for TfidfVectorizer to use\nlist_sample_complaint = []\nlist_sample_complaint.append(sample_complaint)\nlist_sample_complaint",
"_____no_output_____"
],
[
"# Observing what words are extracted from a TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ntf_idf3 = TfidfVectorizer(stop_words='english')\ncheck3 = tf_idf3.fit_transform(list_sample_complaint)\n\nprint(tf_idf3.get_feature_names())",
"['b15', 'rabbit', 'sofa', 'trapped']\n"
]
],
[
[
"# Model/classifier selection",
"_____no_output_____"
],
[
"## train/startified/test splits",
"_____no_output_____"
]
],
[
[
" # Split the data into X and y data sets\nX, y = df_product_and_complaint.MAIN_DESCRIPTION, df_product_and_complaint.SERVICE_TYPE\nprint('X shape:', X.shape, 'y shape:', y.shape)",
"X shape: (7307,) y shape: (7307,)\n"
],
[
"# Split the data into X and y data sets\nX, y = df_product_and_complaint.MAIN_DESCRIPTION, df_product_and_complaint.SERVICE_TYPE\nprint('X shape:', X.shape, 'y shape:', y.shape)\nfrom sklearn.model_selection import train_test_split\n\nX_train_val, X_test, y_train_val, y_test = train_test_split(X, y, \n test_size=0.2, # 80% train/cv, 20% test\n stratify=y,\n random_state=seed)\nprint('X_train', X_train_val.shape)\nprint('y_train', y_train_val.shape)\nprint('X_test', X_test.shape)\nprint('y_test', y_test.shape)",
"X shape: (7307,) y shape: (7307,)\nX_train (5845,)\ny_train (5845,)\nX_test (1462,)\ny_test (1462,)\n"
],
[
"# Performing Text Pre-Processing\n\n# Import tfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# Text Preprocessing\n# The text needs to be transformed to vectors so as the algorithms will be able make predictions. \n# In this case it will be used the Term Frequency – Inverse Document Frequency (TFIDF) weight \n# to evaluate how important A WORD is to A DOCUMENT in a COLLECTION OF DOCUMENTS.\n\n# tfidf1 = 1-gram only. \ntfidf1 = TfidfVectorizer(sublinear_tf=True, # set to true to scale the term frequency in logarithmic scale.\n min_df=5,\n stop_words='english')\n\nX_train_val_tfidf1 = tfidf1.fit_transform(X_train_val).toarray()\nX_test_tfidf1 = tfidf1.transform(X_test)\n\n# tfidf2 = unigram and bigram\ntfidf2 = TfidfVectorizer(sublinear_tf=True, # set to true to scale the term frequency in logarithmic scale.\n min_df=5, \n ngram_range=(1,2), # we consider unigrams and bigrams\n stop_words='english')\nX_train_val_tfidf2 = tfidf2.fit_transform(X_train_val).toarray()\nX_test_tfidf2 = tfidf2.transform(X_test)\n\n\n# # StratifiedKFold -> Split 5\n# ## We now want to do stratified kfold to preserve the proportion of the category imbalances \n# # (number is split evenly from all the classes)\n\nkf = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)",
"_____no_output_____"
]
],
[
[
"# Baseline Model - Train/Stratified CV with MultinomialNB()",
"_____no_output_____"
]
],
[
[
"print('1-gram number of (rows, features):', X_train_val_tfidf1.shape)",
"1-gram number of (rows, features): (5845, 428)\n"
],
[
"def metric_cv_stratified(model, X_train_val, y_train_val, n_splits, name):\n \"\"\"\n Accepts a Model Object, converted X_train_val and y_train_val, n_splits, name\n and returns a dataframe with various cross-validated metric scores \n over a stratified n_splits kfold for a multi-class classifier.\n \"\"\"\n # Start timer\n import timeit\n start = timeit.default_timer()\n \n ### Computations below\n \n # StratifiedKFold\n ## We now want to do stratified kfold to preserve the proportion of the category imbalances \n # (number is split evenly from all the classes)\n from sklearn.model_selection import StratifiedKFold # incase user forgest to import\n kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)\n \n # Initializing Metrics\n accuracy = 0.0\n micro_f1 = 0.0\n macro_precision = 0.0\n macro_recall = 0.0\n macro_f1 = 0.0\n weighted_precision = 0.0\n weighted_recall = 0.0\n weighted_f1 = 0.0\n roc_auc = 0.0 #Not considering this score in this case\n \n # Storing metrics\n from sklearn.model_selection import cross_val_score # incase user forgets to import\n accuracy = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='accuracy'))\n micro_f1 = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='f1_micro'))\n macro_precision = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='precision_macro'))\n macro_recall = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='recall_macro'))\n macro_f1 = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='f1_macro'))\n weighted_precision = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='precision_weighted'))\n weighted_recall = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='recall_weighted'))\n weighted_f1 = np.mean(cross_val_score(model, X_train_val, y_train_val, cv=kf, scoring='f1_weighted'))\n \n # Stop timer\n stop = timeit.default_timer()\n elapsed_time = stop - start\n \n return pd.DataFrame({'Model' : [name],\n 'Accuracy' : [accuracy],\n 'Micro F1' : [micro_f1],\n 'Macro Precision': [macro_precision],\n 'Macro Recall' : [macro_recall],\n 'Macro F1score' : [macro_f1],\n 'Weighted Precision': [weighted_precision],\n 'Weighted Recall' : [weighted_recall],\n 'Weighted F1' : [weighted_f1],\n 'Time taken': [elapsed_time] # timetaken: to be used for comparison later\n })",
"_____no_output_____"
],
[
"# ## Data Science Story:\n# # Testing on MultinomialNB first\n\n# # Initialize Model Object\n# mnb = MultinomialNB()\n\n# results_cv_stratified_1gram = metric_cv_stratified(mnb, X_train_val_tfidf1, y_train_val, 5, 'MultinomialNB1')\n# results_cv_stratified_2gram = metric_cv_stratified(mnb, X_train_val_tfidf2, y_train_val, 5, 'MultinomialNB2')",
"_____no_output_____"
],
[
"results_cv_stratified_1gram",
"_____no_output_____"
],
[
"results_cv_stratified_2gram",
"_____no_output_____"
]
],
[
[
"# 1-gram",
"_____no_output_____"
]
],
[
[
"# ## Testing on all Models using 1-gram \n\n# # Initialize Model Object\n# gnb = GaussianNB()\n# mnb = MultinomialNB()\n# logit = LogisticRegression(random_state=seed)\n# randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n# linearsvc = LinearSVC()\n\n# ## We do NOT want these two. They take FOREVER to train AND predict\n# # knn = KNeighborsClassifier() \n# # decisiontree = DecisionTreeClassifier(random_state=seed)\n\n# # to concat all models\n# results_cv_straitified_1gram = pd.concat([metric_cv_stratified(mnb, X_train_val_tfidf1, y_train_val, 5, 'MultinomialNB1'),\n# metric_cv_stratified(gnb, X_train_val_tfidf1, y_train_val, 5, 'GaussianNB1'),\n# metric_cv_stratified(logit, X_train_val_tfidf1, y_train_val, 5, 'LogisticRegression1'),\n# metric_cv_stratified(randomforest, X_train_val_tfidf1, y_train_val, 5, 'RandomForest1'),\n# metric_cv_stratified(linearsvc, X_train_val_tfidf1, y_train_val, 5, 'LinearSVC1')\n# ], axis=0).reset_index()",
"_____no_output_____"
],
[
"results_cv_straitified_1gram",
"_____no_output_____"
],
[
"#with open('results_cv_straitified_1gram_df.pickle', 'wb') as to_write:\n# pickle.dump(results_cv_straitified_1gram, to_write)",
"_____no_output_____"
],
[
"with open('results_cv_straitified_1gram_df.pickle', 'rb') as to_read:\n results_cv_straitified_1gram = pickle.load(to_read)",
"_____no_output_____"
],
[
"## Testing on all Models using 2-gram \n\n# # Initialize Model Object\n# gnb = GaussianNB()\n# mnb = MultinomialNB()\n# logit = LogisticRegression(random_state=seed)\n# knn = KNeighborsClassifier()\n# decisiontree = DecisionTreeClassifier(random_state=seed)\n# randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n# linearsvc = LinearSVC()\n\n# # # to concat all models\n# results_cv_straitified_2gram = pd.concat([metric_cv_stratified(mnb, X_train_val_tfidf2, y_train_val, 5, 'MultinomialNB2'),\n# metric_cv_stratified(gnb, X_train_val_tfidf2, y_train_val, 5, 'GaussianNB2'),\n# metric_cv_stratified(logit, X_train_val_tfidf2, y_train_val, 5, 'LogisticRegression2'),\n# metric_cv_stratified(randomforest, X_train_val_tfidf2, y_train_val, 5, 'RandomForest2'),\n# metric_cv_stratified(linearsvc, X_train_val_tfidf2, y_train_val, 5, 'LinearSVC2')\n# ], axis=0).reset_index()",
"_____no_output_____"
],
[
"results_cv_straitified_2gram",
"_____no_output_____"
],
[
"results_cv_straitified_1gram",
"_____no_output_____"
],
[
"#with open('results_cv_straitified_2gram_df.pickle', 'wb') as to_write:\n# pickle.dump(results_cv_straitified_2gram, to_write)",
"_____no_output_____"
],
[
"with open('results_cv_straitified_2gram_df.pickle', 'rb') as to_read:\n results_cv_straitified_2gram = pickle.load(to_read)",
"_____no_output_____"
]
],
[
[
"# Using GloVe50d\n",
"_____no_output_____"
]
],
[
[
"#Each complaint is mapped to a feature vector by averaging the word embeddings of all words in the review. \n#These features are then fed into the defined function above for train/cross validation.",
"_____no_output_____"
],
[
"\n# ## Using pre-trained GloVe\n# #download from https://nlp.stanford.edu/projects/glove/\n\n# glove_file = glove_dir = 'glove.6B.50d.txt'\n# w2v_output_file = 'glove.6B.50d.txt.w2v'\n\n# # The following utility converts file formats\n# gensim.scripts.glove2word2vec.glove2word2vec(glove_file, w2v_output_file)\n\n# # Now we can load it!\n# glove_model_50d = gensim.models.KeyedVectors.load_word2vec_format(w2v_output_file, binary=False)\n\n# # Pickle glove model so we don't have to do the above steps again and keep the damn glove.6b.50d in our folder\n# with open('glove_model_50d.pickle', 'wb') as to_write:\n# pickle.dump(glove_model_50d, to_write)",
"_____no_output_____"
],
[
"# Load pickled glove_model\nwith open('glove_model_50d.pickle', 'rb') as to_read:\n glove_model_50d = pickle.load(to_read)\n \nnum_features = 50 # depends on the pre-trained model you are loading",
"_____no_output_____"
],
[
"def complaint_to_wordlist(review, remove_stopwords=False):\n \"\"\"\n Convert a complaint to a list of words. Removal of stop words is optional.\n \"\"\"\n # remove non-letters\n review_text = re.sub(\"[^a-zA-Z]\",\" \", review)\n \n # convert to lower case and split at whitespace\n words = review_text.lower().split()\n \n # remove stop words (false by default)\n if remove_stopwords:\n stops = set(stopwords.words(\"english\"))\n words = [w for w in words if not w in stops]\n\n return words # list of tokenized and cleaned words",
"_____no_output_____"
],
[
"# num_features refer to the dimensionality of the model you are using\n# model refers to the trained word2vec/glove model\n# words refer to the words in a single document/entry\n\ndef make_feature_vec(words, model, num_features):\n \"\"\"\n Average the word vectors for a set of words\n \"\"\"\n feature_vec = np.zeros((num_features,), # creates a zero matrix of (num_features, )\n dtype=\"float32\") # pre-initialize (for speed)\n \n # Initialize a counter for the number of words in a complaint\n nwords = 0.\n index2word_set = set(model.index2word) # words known to the model\n\n \n # Loop over each word in the comment and, if it is in the model's vocabulary, add its feature vector to the total\n for word in words: # for each word in the list of words\n if word in index2word_set: # if each word is found in the words known to the model\n nwords = nwords + 1. # add 1 to nwords\n feature_vec = np.add(feature_vec, model[word]) \n \n # Divide by the number of words to get the average \n if nwords > 0:\n feature_vec = np.divide(feature_vec, nwords)\n \n return feature_vec",
"_____no_output_____"
],
[
"# complaints refers to the whole corpus you intend to put in. \n# Therefore you need to append all these info from your df into a list first\n\ndef get_avg_feature_vecs(complaints, model, num_features):\n \"\"\"\n Calculate average feature vectors for ALL complaints\n \"\"\"\n # Initialize a counter for indexing \n counter = 0\n \n # pre-initialize (for speed)\n complaint_feature_vecs = np.zeros((len(complaints),num_features), dtype='float32') \n \n for complaint in complaints: # each complaint is made up of tokenized/cleaned/stopwords removed words\n complaint_feature_vecs[counter] = make_feature_vec(complaint, model, num_features)\n counter = counter + 1\n return complaint_feature_vecs",
"_____no_output_____"
],
[
"# # Tokenizing and vectorizing our Train_Val Complaints (80%)\n# clean_train_val_complaints = []\n# for complaint in X_train_val:\n# clean_train_val_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_train_val_glove_features = get_avg_feature_vecs(clean_train_val_complaints, glove_model_50d, num_features)\n\n# # Tokenizing and vectorizing our Test Complaints (20%)\n# clean_test_complaints = []\n# for complaint in X_train_val:\n# clean_test_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_test_glove_features = get_avg_feature_vecs(clean_test_complaints, glove_model_50d, num_features)",
"_____no_output_____"
],
[
"# ## Run the X_train_val_word2vec_features into our defined function for scoring \n\n# # Initialize Model Object\n# gnb = GaussianNB()\n# mnb = MultinomialNB()\n# logit = LogisticRegression(random_state=seed)\n# randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n# linearsvc = LinearSVC()\n\n\n# # to concat all models\n# results_cv_straitified_glove50d = pd.concat([\n# # metric_cv_stratified(mnb, X_train_val_glove_features, y_train_val, 5, 'MultinomialNB_glove50d'),\n# metric_cv_stratified(gnb, X_train_val_glove_features, y_train_val, 5, 'GaussianNB_glove50d'),\n# metric_cv_stratified(logit, X_train_val_glove_features, y_train_val, 5, 'LogisticRegression_glove50d'),\n# metric_cv_stratified(randomforest, X_train_val_glove_features, y_train_val, 5, 'RandomForest_glove50d'),\n# metric_cv_stratified(linearsvc, X_train_val_glove_features, y_train_val, 5, 'LinearSVC_glove50d')\n# ], axis=0).reset_index()",
"_____no_output_____"
],
[
"# # Saving Results into a DF\n# with open('results_cv_straitified_glove50d.pickle', 'wb') as to_write:\n# pickle.dump(results_cv_straitified_glove50d, to_write)",
"_____no_output_____"
],
[
"# Opening Results\nwith open('results_cv_straitified_glove50d.pickle', 'rb') as to_read:\n results_cv_straitified_glove50d = pickle.load(to_read)",
"_____no_output_____"
],
[
"results_cv_straitified_glove50d",
"_____no_output_____"
]
],
[
[
"### Using GloVe100d",
"_____no_output_____"
]
],
[
[
"del glove_model_50d, results_cv_straitified_glove50d",
"_____no_output_____"
],
[
"# ## Using pre-trained GloVe\n# # download from https://nlp.stanford.edu/projects/glove/\n\n# num_features = 100 # depends on the pre-trained model you are loading\n\n# glove_file = glove_dir = 'glove.6B.' + str(num_features) + 'd.txt'\n# w2v_output_file = 'glove.6B.' + str(num_features) + 'd.txt.w2v'\n\n# # The following utility converts file formats\n# gensim.scripts.glove2word2vec.glove2word2vec(glove_file, w2v_output_file)\n\n# # Now we can load it!\n# glove_model_100d = gensim.models.KeyedVectors.load_word2vec_format(w2v_output_file, binary=False)\n\n# # Pickle glove model so we don't have to do the above steps again and keep the damn glove.6b.50d in our folder\n# with open('glove_model_' + str(num_features) + 'd.pickle', 'wb') as to_write:\n# pickle.dump(glove_model_100d, to_write)",
"_____no_output_____"
],
[
"# Load pickled glove_model\nwith open('glove_model_100d.pickle', 'rb') as to_read:\n glove_model_100d = pickle.load(to_read)",
"_____no_output_____"
],
[
"# # For Train_Val Complaints (80%)\n# clean_train_val_complaints = []\n# for complaint in X_train_val:\n# clean_train_val_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_train_val_glove_features = get_avg_feature_vecs(clean_train_val_complaints, glove_model_100d, num_features)\n\n# # For Test Complaints (20%)\n# clean_test_complaints = []\n# for complaint in X_train_val:\n# clean_test_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_test_glove_features = get_avg_feature_vecs(clean_test_complaints, glove_model_100d, num_features)",
"_____no_output_____"
],
[
"# ## Run the X_train_val_word2vec_features into our defined function for scoring \n\n# # Initialize Model Object\n# gnb = GaussianNB()\n# mnb = MultinomialNB()\n# logit = LogisticRegression(random_state=seed)\n# randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n# linearsvc = LinearSVC()\n\n# ## We do NOT want these two. They take FOREVER to train AND predict\n# # knn = KNeighborsClassifier() \n# # decisiontree = DecisionTreeClassifier(random_state=seed)\n\n# # to concat all models\n# results_cv_straitified_glove100d = pd.concat([\n# # metric_cv_stratified(mnb, X_train_val_glove_features, y_train_val, 5, 'MultinomialNB_glove50d'),\n# metric_cv_stratified(gnb, X_train_val_glove_features, y_train_val, 5, 'GaussianNB_glove100d'),\n# metric_cv_stratified(logit, X_train_val_glove_features, y_train_val, 5, 'LogisticRegression_glove100d'),\n# metric_cv_stratified(randomforest, X_train_val_glove_features, y_train_val, 5, 'RandomForest_glove100d'),\n# metric_cv_stratified(linearsvc, X_train_val_glove_features, y_train_val, 5, 'LinearSVC_glove100d')\n# ], axis=0).reset_index()",
"_____no_output_____"
],
[
"# with open('results_cv_straitified_glove100d.pickle', 'wb') as to_write:\n# pickle.dump(results_cv_straitified_glove100d, to_write)",
"_____no_output_____"
],
[
"# Opening Results\nwith open('results_cv_straitified_glove100d.pickle', 'rb') as to_read:\n results_cv_straitified_glove100d = pickle.load(to_read)",
"_____no_output_____"
],
[
"results_cv_straitified_glove100d",
"_____no_output_____"
]
],
[
[
"### Using GloVe200d",
"_____no_output_____"
]
],
[
[
"del glove_model_100d, results_cv_straitified_glove100d",
"_____no_output_____"
],
[
"# ## Using pre-trained GloVe\n# # download from https://nlp.stanford.edu/projects/glove/\n\n# num_features = 200 # depends on the pre-trained model you are loading\n\n# glove_file = glove_dir = 'glove.6B.' + str(num_features) + 'd.txt'\n# w2v_output_file = 'glove.6B.' + str(num_features) + 'd.txt.w2v'\n\n# # The following utility converts file formats\n# gensim.scripts.glove2word2vec.glove2word2vec(glove_file, w2v_output_file)\n\n# # Now we can load it!\n# glove_model_200d = gensim.models.KeyedVectors.load_word2vec_format(w2v_output_file, binary=False)\n\n# # Pickle glove model so we don't have to do the above steps again and keep the damn glove.6b.50d in our folder\n# with open('glove_model_' + str(num_features) + 'd.pickle', 'wb') as to_write:\n# pickle.dump(glove_model_200d, to_write)",
"_____no_output_____"
],
[
"with open('glove_model_200d.pickle', 'rb') as to_read:\n glove_model_200d = pickle.load(to_read)",
"_____no_output_____"
],
[
"# # For Train_Val Complaints (80%)\n# clean_train_val_complaints = []\n# for complaint in X_train_val:\n# clean_train_val_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_train_val_glove_features = get_avg_feature_vecs(clean_train_val_complaints, glove_model_200d, num_features)\n\n# #Already run above\n# #For Test Complaints (20%)\n# clean_test_complaints = []\n# for complaint in X_train_val:\n# clean_test_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_test_glove_features = get_avg_feature_vecs(clean_test_complaints, glove_model_200d, num_features)",
"_____no_output_____"
],
[
"# ## Run the X_train_val_word2vec_features into our defined function for scoring \n\n# # Initialize Model Object\n# gnb = GaussianNB()\n# mnb = MultinomialNB()\n# logit = LogisticRegression(random_state=seed)\n# randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n# linearsvc = LinearSVC()\n\n# ## We do NOT want these two. They take FOREVER to train AND predict\n# # knn = KNeighborsClassifier() \n# # decisiontree = DecisionTreeClassifier(random_state=seed)\n\n# # to concat all models\n# results_cv_straitified_glove200d = pd.concat([\n# # metric_cv_stratified(mnb, X_train_val_glove_features, y_train_val, 5, 'MultinomialNB_glove50d'),\n# metric_cv_stratified(gnb, X_train_val_glove_features, y_train_val, 5, 'GaussianNB_glove200d'),\n# metric_cv_stratified(logit, X_train_val_glove_features, y_train_val, 5, 'LogisticRegression_glove200d'),\n# metric_cv_stratified(randomforest, X_train_val_glove_features, y_train_val, 5, 'RandomForest_glove200d'),\n# metric_cv_stratified(linearsvc, X_train_val_glove_features, y_train_val, 5, 'LinearSVC_glove200d')\n# ], axis=0).reset_index()",
"_____no_output_____"
],
[
"# with open('results_cv_straitified_glove200d.pickle', 'wb') as to_write:\n# pickle.dump(results_cv_straitified_glove200d, to_write)",
"_____no_output_____"
],
[
"with open('results_cv_straitified_glove200d.pickle', 'rb') as to_read:\n results_cv_straitified_glove200d = pickle.load(to_read)",
"_____no_output_____"
],
[
"results_cv_straitified_glove200d",
"_____no_output_____"
]
],
[
[
"### Using GloVe300d",
"_____no_output_____"
]
],
[
[
"del glove_model_200d, results_cv_straitified_glove200d",
"_____no_output_____"
],
[
"# ## Using pre-trained GloVe\n# # download from https://nlp.stanford.edu/projects/glove/\n\n# num_features = 300 # depends on the pre-trained model you are loading\n\n# glove_file = glove_dir = 'glove.6B.' + str(num_features) + 'd.txt'\n# w2v_output_file = 'glove.6B.' + str(num_features) + 'd.txt.w2v'\n\n# # The following utility converts file formats\n# gensim.scripts.glove2word2vec.glove2word2vec(glove_file, w2v_output_file)\n\n# # Now we can load it!\n# glove_model_300d = gensim.models.KeyedVectors.load_word2vec_format(w2v_output_file, binary=False)\n\n# # Pickle glove model so we don't have to do the above steps again and keep the damn glove.6b.50d in our folder\n# with open('glove_model_' + str(num_features) + 'd.pickle', 'wb') as to_write:\n# pickle.dump(glove_model_300d, to_write)",
"_____no_output_____"
],
[
"# # Load pickled glove_model\n# with open('glove_model_300d.pickle', 'rb') as to_read:\n# glove_model_300d = pickle.load(to_read)",
"_____no_output_____"
],
[
"\n# # For Train_Val Complaints (80%)\n# clean_train_val_complaints = []\n# for complaint in X_train_val:\n# clean_train_val_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_train_val_glove_features = get_avg_feature_vecs(clean_train_val_complaints, glove_model_300d, num_features)\n\n# #Already run above\n# # For Test Complaints (20%)\n# clean_test_complaints = []\n# for complaint in X_train_val:\n# clean_test_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_test_glove_features = get_avg_feature_vecs(clean_test_complaints, glove_model_300d, num_features)",
"_____no_output_____"
],
[
"# ## Run the X_train_val_word2vec_features into our defined function for scoring \n\n# # Initialize Model Object\n# gnb = GaussianNB()\n# mnb = MultinomialNB()\n# logit = LogisticRegression(random_state=seed)\n# randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n# linearsvc = LinearSVC()\n\n# ## We do NOT want these two. They take FOREVER to train AND predict\n# # knn = KNeighborsClassifier() \n# # decisiontree = DecisionTreeClassifier(random_state=seed)\n\n# # to concat all models\n# results_cv_straitified_glove300d= pd.concat([\n# # metric_cv_stratified(mnb, X_train_val_glove_features, y_train_val, 5, 'MultinomialNB_glove50d'),\n# metric_cv_stratified(gnb, X_train_val_glove_features, y_train_val, 5, 'GaussianNB_glove300d'),\n# metric_cv_stratified(logit, X_train_val_glove_features, y_train_val, 5, 'LogisticRegression_glove300d'),\n# metric_cv_stratified(randomforest, X_train_val_glove_features, y_train_val, 5, 'RandomForest_glove300d'),\n# metric_cv_stratified(linearsvc, X_train_val_glove_features, y_train_val, 5, 'LinearSVC_glove300d')\n# ], axis=0).reset_index()",
"_____no_output_____"
],
[
"\n# with open('results_cv_straitified_glove300d.pickle', 'wb') as to_write:\n# pickle.dump(results_cv_straitified_glove300d, to_write)",
"_____no_output_____"
],
[
"# Opening Results\nwith open('results_cv_straitified_glove300d.pickle', 'rb') as to_read:\n results_cv_straitified_glove300d = pickle.load(to_read)",
"_____no_output_____"
],
[
"results_cv_straitified_glove300d",
"_____no_output_____"
]
],
[
[
"# GoogleNews Word2Vec300d",
"_____no_output_____"
]
],
[
[
"del glove_model_300d, results_cv_straitified_glove300d",
"_____no_output_____"
],
[
"# ## Using pre-trained GoogleNews Word2Vec\n# # download from https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit\n\n# num_features = 300 # depends on the pre-trained model you are loading\n\n# # Path to where the word2vec file lives\n# google_vec_file = 'GoogleNews-vectors-negative300.bin'\n\n# # Load it! This might take a few minutes...\n# word2vec_model_300d = gensim.models.KeyedVectors.load_word2vec_format(google_vec_file, binary=True)\n# # it is just loading all the different weights (embedding) into python\n\n\n# # Pickle word2vec 300d model so we don't have to do the above steps again and keep the damn file in our folder\n# with open('word2vec_model_' + str(num_features) + 'd.pickle', 'wb') as to_write:\n# pickle.dump(word2vec_model_300d, to_write)",
"_____no_output_____"
],
[
"# Load pickled glove_model\nwith open('word2vec_model_300d.pickle', 'rb') as to_read:\n word2vec_model_300d = pickle.load(to_read)",
"_____no_output_____"
],
[
"# # For Train_Val Complaints (80%)\n# clean_train_val_complaints = []\n# for complaint in X_train_val:\n# clean_train_val_complaints.append(complaint_to_wordlist(complaint, True))\n\n# X_train_val_glove_features = get_avg_feature_vecs(clean_train_val_complaints, word2vec_model_300d, num_features)",
"_____no_output_____"
],
[
"# ## Run the X_train_val_word2vec_features into our defined function for scoring \n\n# # Initialize Model Object\n# gnb = GaussianNB()\n# mnb = MultinomialNB()\n# logit = LogisticRegression(random_state=seed)\n# randomforest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n# linearsvc = LinearSVC()\n\n# ## We do NOT want these two. They take FOREVER to train AND predict\n# # knn = KNeighborsClassifier() \n# # decisiontree = DecisionTreeClassifier(random_state=seed)\n\n# # to concat all models\n# results_cv_straitified_word2vec300d= pd.concat([\n# # metric_cv_stratified(mnb, X_train_val_glove_features, y_train_val, 5, 'MultinomialNB_glove50d'),\n# metric_cv_stratified(gnb, X_train_val_glove_features, y_train_val, 5, 'GaussianNB_word2vec300d'),\n# metric_cv_stratified(logit, X_train_val_glove_features, y_train_val, 5, 'LogisticRegression_word2vec300d'),\n# metric_cv_stratified(randomforest, X_train_val_glove_features, y_train_val, 5, 'RandomForest_word2vec300d'),\n# metric_cv_stratified(linearsvc, X_train_val_glove_features, y_train_val, 5, 'LinearSVC_word2vec300d')\n# ], axis=0).reset_index()",
"D:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Recall is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Precision is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\metrics\\_classification.py:1272: UndefinedMetricWarning: Recall is 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))\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\linear_model\\_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\linear_model\\_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\linear_model\\_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\linear_model\\_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\linear_model\\_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\nD:\\anacondasetup\\lib\\site-packages\\sklearn\\model_selection\\_split.py:667: UserWarning: The least populated class in y has only 2 members, which is less than n_splits=5.\n % (min_groups, self.n_splits)), UserWarning)\n"
],
[
"# with open('results_cv_straitified_word2vec300d.pickle', 'wb') as to_write:\n# pickle.dump(results_cv_straitified_word2vec300d, to_write)",
"_____no_output_____"
],
[
"# Opening Results\nwith open('results_cv_straitified_word2vec300d.pickle', 'rb') as to_read:\n results_cv_straitified_word2vec300d = pickle.load(to_read)",
"_____no_output_____"
],
[
"results_cv_straitified_word2vec300d",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e78965027cab9fe135956719fc12b2cddc3e6905 | 23,987 | ipynb | Jupyter Notebook | New_Language_Training_(Colab).ipynb | New-Languages-for-NLP/kanbun | 3cc586482f8f946c9ec1574adf02ce563af39767 | [
"MIT"
] | null | null | null | New_Language_Training_(Colab).ipynb | New-Languages-for-NLP/kanbun | 3cc586482f8f946c9ec1574adf02ce563af39767 | [
"MIT"
] | null | null | null | New_Language_Training_(Colab).ipynb | New-Languages-for-NLP/kanbun | 3cc586482f8f946c9ec1574adf02ce563af39767 | [
"MIT"
] | 1 | 2022-01-08T17:35:30.000Z | 2022-01-08T17:35:30.000Z | 34.024113 | 250 | 0.51457 | [
[
[
"<a href=\"https://colab.research.google.com/github/New-Languages-for-NLP/kanbun/blob/main/New_Language_Training_(Colab).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"For full documentation on this project, see [here](https://new-languages-for-nlp.github.io/course-materials/w2/projects.html)\n \nThis notebook: \n- Loads project file from GitHub\n- Loads assets from GitHub repo\n- installs the custom language object \n- converts the training data to spaCy binary\n- configure the project.yml file \n- train the model \n- assess performance \n- package the model (or push to huggingface) \n",
"_____no_output_____"
],
[
"# 1 Prepare the Notebook Environment",
"_____no_output_____"
]
],
[
[
"# @title Colab comes with spaCy v2, needs upgrade to v3\nGPU = True # @param {type:\"boolean\"}\n\n# Install spaCy v3 and libraries for GPUs and transformers\n!pip install spacy --upgrade\nif GPU:\n !pip install 'spacy[transformers,cuda111]'\n!pip install wandb spacy-huggingface-hub",
"_____no_output_____"
]
],
[
[
"The notebook will pull project files from your GitHub repository. \n\nNote that you need to set the langugage (lang), treebank (same as the repo name), test_size and package name in the project.yml file in your repository. ",
"_____no_output_____"
]
],
[
[
"private_repo = False # @param {type:\"boolean\"}\nrepo_name = \"kanbun\" # @param {type:\"string\"}\n\n!rm -rf /content/newlang_project\n!rm -rf $repo_name\nif private_repo:\n git_access_token = \"\" # @param {type:\"string\"}\n git_url = (\n f\"https://{git_access_token}@github.com/New-Languages-for-NLP/{repo_name}/\"\n )\n !git clone $git_url -b main\n !cp -r ./$repo_name/newlang_project .\n !mkdir newlang_project/assets/\n !mkdir newlang_project/configs/\n !mkdir newlang_project/corpus/\n !mkdir newlang_project/metrics/\n !mkdir newlang_project/packages/\n !mkdir newlang_project/training/\n !mkdir newlang_project/assets/$repo_name\n !cp -r ./$repo_name/* newlang_project/assets/$repo_name/\n !rm -rf ./$repo_name\nelse:\n !python -m spacy project clone newlang_project --repo https://github.com/New-Languages-for-NLP/$repo_name --branch main\n !python -m spacy project assets /content/newlang_project",
"_____no_output_____"
],
[
"# Install the custom language object from Cadet\n!python -m spacy project run install /content/newlang_project",
"_____no_output_____"
]
],
[
[
"# 2 Prepare the Data for Training",
"_____no_output_____"
]
],
[
[
"# @title (optional) cell to corrects a problem when your tokens have no pos value\n%%writefile /usr/local/lib/python3.7/dist-packages/spacy/training/converters/conllu_to_docs.py\nimport re\n\nfrom .conll_ner_to_docs import n_sents_info\nfrom ...training import iob_to_biluo, biluo_tags_to_spans\nfrom ...tokens import Doc, Token, Span\nfrom ...vocab import Vocab\nfrom wasabi import Printer\n\n\ndef conllu_to_docs(\n input_data,\n n_sents=10,\n append_morphology=False,\n ner_map=None,\n merge_subtokens=False,\n no_print=False,\n **_\n):\n \"\"\"\n Convert conllu files into JSON format for use with train cli.\n append_morphology parameter enables appending morphology to tags, which is\n useful for languages such as Spanish, where UD tags are not so rich.\n\n Extract NER tags if available and convert them so that they follow\n BILUO and the Wikipedia scheme\n \"\"\"\n MISC_NER_PATTERN = \"^((?:name|NE)=)?([BILU])-([A-Z_]+)|O$\"\n msg = Printer(no_print=no_print)\n n_sents_info(msg, n_sents)\n sent_docs = read_conllx(\n input_data,\n append_morphology=append_morphology,\n ner_tag_pattern=MISC_NER_PATTERN,\n ner_map=ner_map,\n merge_subtokens=merge_subtokens,\n )\n sent_docs_to_merge = []\n for sent_doc in sent_docs:\n sent_docs_to_merge.append(sent_doc)\n if len(sent_docs_to_merge) % n_sents == 0:\n yield Doc.from_docs(sent_docs_to_merge)\n sent_docs_to_merge = []\n if sent_docs_to_merge:\n yield Doc.from_docs(sent_docs_to_merge)\n\n\ndef has_ner(input_data, ner_tag_pattern):\n \"\"\"\n Check the MISC column for NER tags.\n \"\"\"\n for sent in input_data.strip().split(\"\\n\\n\"):\n lines = sent.strip().split(\"\\n\")\n if lines:\n while lines[0].startswith(\"#\"):\n lines.pop(0)\n for line in lines:\n parts = line.split(\"\\t\")\n id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts\n for misc_part in misc.split(\"|\"):\n if re.match(ner_tag_pattern, misc_part):\n return True\n return False\n\n\ndef read_conllx(\n input_data,\n append_morphology=False,\n merge_subtokens=False,\n ner_tag_pattern=\"\",\n ner_map=None,\n):\n \"\"\"Yield docs, one for each sentence\"\"\"\n vocab = Vocab() # need vocab to make a minimal Doc\n for sent in input_data.strip().split(\"\\n\\n\"):\n lines = sent.strip().split(\"\\n\")\n if lines:\n while lines[0].startswith(\"#\"):\n lines.pop(0)\n doc = conllu_sentence_to_doc(\n vocab,\n lines,\n ner_tag_pattern,\n merge_subtokens=merge_subtokens,\n append_morphology=append_morphology,\n ner_map=ner_map,\n )\n yield doc\n\n\ndef get_entities(lines, tag_pattern, ner_map=None):\n \"\"\"Find entities in the MISC column according to the pattern and map to\n final entity type with `ner_map` if mapping present. Entity tag is 'O' if\n the pattern is not matched.\n\n lines (str): CONLL-U lines for one sentences\n tag_pattern (str): Regex pattern for entity tag\n ner_map (dict): Map old NER tag names to new ones, '' maps to O.\n RETURNS (list): List of BILUO entity tags\n \"\"\"\n miscs = []\n for line in lines:\n parts = line.split(\"\\t\")\n id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts\n if \"-\" in id_ or \".\" in id_:\n continue\n miscs.append(misc)\n\n iob = []\n for misc in miscs:\n iob_tag = \"O\"\n for misc_part in misc.split(\"|\"):\n tag_match = re.match(tag_pattern, misc_part)\n if tag_match:\n prefix = tag_match.group(2)\n suffix = tag_match.group(3)\n if prefix and suffix:\n iob_tag = prefix + \"-\" + suffix\n if ner_map:\n suffix = ner_map.get(suffix, suffix)\n if suffix == \"\":\n iob_tag = \"O\"\n else:\n iob_tag = prefix + \"-\" + suffix\n break\n iob.append(iob_tag)\n return iob_to_biluo(iob)\n\n\ndef conllu_sentence_to_doc(\n vocab,\n lines,\n ner_tag_pattern,\n merge_subtokens=False,\n append_morphology=False,\n ner_map=None,\n):\n \"\"\"Create an Example from the lines for one CoNLL-U sentence, merging\n subtokens and appending morphology to tags if required.\n\n lines (str): The non-comment lines for a CoNLL-U sentence\n ner_tag_pattern (str): The regex pattern for matching NER in MISC col\n RETURNS (Example): An example containing the annotation\n \"\"\"\n # create a Doc with each subtoken as its own token\n # if merging subtokens, each subtoken orth is the merged subtoken form\n if not Token.has_extension(\"merged_orth\"):\n Token.set_extension(\"merged_orth\", default=\"\")\n if not Token.has_extension(\"merged_lemma\"):\n Token.set_extension(\"merged_lemma\", default=\"\")\n if not Token.has_extension(\"merged_morph\"):\n Token.set_extension(\"merged_morph\", default=\"\")\n if not Token.has_extension(\"merged_spaceafter\"):\n Token.set_extension(\"merged_spaceafter\", default=\"\")\n words, spaces, tags, poses, morphs, lemmas = [], [], [], [], [], []\n heads, deps = [], []\n subtok_word = \"\"\n in_subtok = False\n for i in range(len(lines)):\n line = lines[i]\n parts = line.split(\"\\t\")\n id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts\n if \".\" in id_:\n continue\n if \"-\" in id_:\n in_subtok = True\n if \"-\" in id_:\n in_subtok = True\n subtok_word = word\n subtok_start, subtok_end = id_.split(\"-\")\n subtok_spaceafter = \"SpaceAfter=No\" not in misc\n continue\n if merge_subtokens and in_subtok:\n words.append(subtok_word)\n else:\n words.append(word)\n if in_subtok:\n if id_ == subtok_end:\n spaces.append(subtok_spaceafter)\n else:\n spaces.append(False)\n elif \"SpaceAfter=No\" in misc:\n spaces.append(False)\n else:\n spaces.append(True)\n if in_subtok and id_ == subtok_end:\n subtok_word = \"\"\n in_subtok = False\n id_ = int(id_) - 1\n head = (int(head) - 1) if head not in (\"0\", \"_\") else id_\n tag = pos if tag == \"_\" else tag\n morph = morph if morph != \"_\" else \"\"\n dep = \"ROOT\" if dep == \"root\" else dep\n lemmas.append(lemma)\n if pos == \"_\":\n pos = \"\"\n poses.append(pos)\n tags.append(tag)\n morphs.append(morph)\n heads.append(head)\n deps.append(dep)\n\n doc = Doc(\n vocab,\n words=words,\n spaces=spaces,\n tags=tags,\n pos=poses,\n deps=deps,\n lemmas=lemmas,\n morphs=morphs,\n heads=heads,\n )\n for i in range(len(doc)):\n doc[i]._.merged_orth = words[i]\n doc[i]._.merged_morph = morphs[i]\n doc[i]._.merged_lemma = lemmas[i]\n doc[i]._.merged_spaceafter = spaces[i]\n ents = get_entities(lines, ner_tag_pattern, ner_map)\n doc.ents = biluo_tags_to_spans(doc, ents)\n\n if merge_subtokens:\n doc = merge_conllu_subtokens(lines, doc)\n\n # create final Doc from custom Doc annotation\n words, spaces, tags, morphs, lemmas, poses = [], [], [], [], [], []\n heads, deps = [], []\n for i, t in enumerate(doc):\n words.append(t._.merged_orth)\n lemmas.append(t._.merged_lemma)\n spaces.append(t._.merged_spaceafter)\n morphs.append(t._.merged_morph)\n if append_morphology and t._.merged_morph:\n tags.append(t.tag_ + \"__\" + t._.merged_morph)\n else:\n tags.append(t.tag_)\n poses.append(t.pos_)\n heads.append(t.head.i)\n deps.append(t.dep_)\n\n doc_x = Doc(\n vocab,\n words=words,\n spaces=spaces,\n tags=tags,\n morphs=morphs,\n lemmas=lemmas,\n pos=poses,\n deps=deps,\n heads=heads,\n )\n doc_x.ents = [Span(doc_x, ent.start, ent.end, label=ent.label) for ent in doc.ents]\n\n return doc_x\n\n\ndef merge_conllu_subtokens(lines, doc):\n # identify and process all subtoken spans to prepare attrs for merging\n subtok_spans = []\n for line in lines:\n parts = line.split(\"\\t\")\n id_, word, lemma, pos, tag, morph, head, dep, _1, misc = parts\n if \"-\" in id_:\n subtok_start, subtok_end = id_.split(\"-\")\n subtok_span = doc[int(subtok_start) - 1 : int(subtok_end)]\n subtok_spans.append(subtok_span)\n # create merged tag, morph, and lemma values\n tags = []\n morphs = {}\n lemmas = []\n for token in subtok_span:\n tags.append(token.tag_)\n lemmas.append(token.lemma_)\n if token._.merged_morph:\n for feature in token._.merged_morph.split(\"|\"):\n field, values = feature.split(\"=\", 1)\n if field not in morphs:\n morphs[field] = set()\n for value in values.split(\",\"):\n morphs[field].add(value)\n # create merged features for each morph field\n for field, values in morphs.items():\n morphs[field] = field + \"=\" + \",\".join(sorted(values))\n # set the same attrs on all subtok tokens so that whatever head the\n # retokenizer chooses, the final attrs are available on that token\n for token in subtok_span:\n token._.merged_orth = token.orth_\n token._.merged_lemma = \" \".join(lemmas)\n token.tag_ = \"_\".join(tags)\n token._.merged_morph = \"|\".join(sorted(morphs.values()))\n token._.merged_spaceafter = (\n True if subtok_span[-1].whitespace_ else False\n )\n\n with doc.retokenize() as retokenizer:\n for span in subtok_spans:\n retokenizer.merge(span)\n\n return doc",
"_____no_output_____"
],
[
"# Convert the conllu files from inception to spaCy binary format\n# Read the conll files with ner data and as ents to spaCy docs\n!python -m spacy project run convert /content/newlang_project -F",
"_____no_output_____"
],
[
"# test/train split\n!python -m spacy project run split /content/newlang_project",
"_____no_output_____"
],
[
"# Debug the data\n!python -m spacy project run debug /content/newlang_project",
"_____no_output_____"
]
],
[
[
"# 3 Model Training ",
"_____no_output_____"
]
],
[
[
"# train the model\n!python -m spacy project run train /content/newlang_project",
"_____no_output_____"
]
],
[
[
"If you get `ValueError: Could not find gold transition - see logs above.` \nYou may not have sufficent data to train on: https://github.com/explosion/spaCy/discussions/7282",
"_____no_output_____"
]
],
[
[
"# Evaluate the model using the test data\n!python -m spacy project run evaluate /content/newlang_project",
"_____no_output_____"
],
[
"# Find the path for your meta.json file\n# You'll need to add newlang_project/ + the path from the training step just after \"✔ Saved pipeline to output directory\"\n!ls newlang_project/training/urban-giggle/model-last",
"_____no_output_____"
],
[
"# Update meta.json\nimport spacy\nimport srsly\n\n# Change path to match that from the training cell where it says \"✔ Saved pipeline to output directory\"\nmeta_path = \"newlang_project/training/urban-giggle/model-last/meta.json\"\n\n# Replace values below for your project\nmy_meta = {\n \"lang\": \"yi\",\n \"name\": \"yiddish_sm\",\n \"version\": \"0.0.1\",\n \"description\": \"Yiddish pipeline optimized for CPU. Components: tok2vec, tagger, parser, senter, lemmatizer.\",\n \"author\": \"New Languages for NLP\",\n \"email\": \"[email protected]\",\n \"url\": \"https://newnlp.princeton.edu\",\n \"license\": \"MIT\",\n}\nmeta = spacy.util.load_meta(meta_path)\nmeta.update(my_meta)\nsrsly.write_json(meta_path, meta)\nmeta",
"_____no_output_____"
]
],
[
[
"### Download the trained model to your computer.\n",
"_____no_output_____"
]
],
[
[
"# Save the model to disk in a format that can be easily downloaded and re-used.\n!python -m spacy package ./newlang_project/training/urban-giggle/model-last newlang_project/export",
"_____no_output_____"
],
[
"from google.colab import files\n\n# replace with the path in the previous cell under \"✔ Successfully created zipped Python package\"\nfiles.download(\n \"newlang_project/export/yi_yiddish_sm-0.0.1/dist/yi_yiddish_sm-0.0.1.tar.gz\"\n)\n\n# once on your computer, you can pip install en_pipeline-0.0.0.tar.gz\n# Add to 4_trained_models folder in GitHub",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e78966d1d6f449f09399947968e036132e79dd89 | 4,060 | ipynb | Jupyter Notebook | something-learned/Interview/system-design-primer/solutions/object_oriented_design/lru_cache/lru_cache.ipynb | gopala-kr/Code-Rush-101 | dd27b767cdc0c667655ab8e32e020ed4248bd112 | [
"MIT"
] | 157 | 2017-04-02T12:30:52.000Z | 2022-03-27T10:29:39.000Z | solutions/object_oriented_design/lru_cache/lru_cache.ipynb | animesh371/system-design-primer | 684679f9a0b9dc25ce06ffdd6a22529b4db8bca7 | [
"CC-BY-4.0"
] | 30 | 2017-05-01T02:38:09.000Z | 2020-07-28T17:23:51.000Z | solutions/object_oriented_design/lru_cache/lru_cache.ipynb | animesh371/system-design-primer | 684679f9a0b9dc25ce06ffdd6a22529b4db8bca7 | [
"CC-BY-4.0"
] | 58 | 2017-03-20T14:36:43.000Z | 2022-03-07T00:35:38.000Z | 28.794326 | 183 | 0.495813 | [
[
[
"This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/system-design-primer-primer).",
"_____no_output_____"
],
[
"# Design an LRU cache",
"_____no_output_____"
],
[
"## Constraints and assumptions\n\n* What are we caching?\n * We are cahing the results of web queries\n* Can we assume inputs are valid or do we have to validate them?\n * Assume they're valid\n* Can we assume this fits memory?\n * Yes",
"_____no_output_____"
],
[
"## Solution",
"_____no_output_____"
]
],
[
[
"%%writefile lru_cache.py\nclass Node(object):\n\n def __init__(self, results):\n self.results = results\n self.next = next\n\n\nclass LinkedList(object):\n\n def __init__(self):\n self.head = None\n self.tail = None\n\n def move_to_front(self, node): # ...\n def append_to_front(self, node): # ...\n def remove_from_tail(self): # ...\n\n\nclass Cache(object):\n\n def __init__(self, MAX_SIZE):\n self.MAX_SIZE = MAX_SIZE\n self.size = 0\n self.lookup = {} # key: query, value: node\n self.linked_list = LinkedList()\n\n def get(self, query)\n \"\"\"Get the stored query result from the cache.\n \n Accessing a node updates its position to the front of the LRU list.\n \"\"\"\n node = self.lookup[query]\n if node is None:\n return None\n self.linked_list.move_to_front(node)\n return node.results\n\n def set(self, results, query):\n \"\"\"Set the result for the given query key in the cache.\n \n When updating an entry, updates its position to the front of the LRU list.\n If the entry is new and the cache is at capacity, removes the oldest entry\n before the new entry is added.\n \"\"\"\n node = self.lookup[query]\n if node is not None:\n # Key exists in cache, update the value\n node.results = results\n self.linked_list.move_to_front(node)\n else:\n # Key does not exist in cache\n if self.size == self.MAX_SIZE:\n # Remove the oldest entry from the linked list and lookup\n self.lookup.pop(self.linked_list.tail.query, None)\n self.linked_list.remove_from_tail()\n else:\n self.size += 1\n # Add the new key and value\n new_node = Node(results)\n self.linked_list.append_to_front(new_node)\n self.lookup[query] = new_node",
"Overwriting lru_cache.py\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
e78971fb87604801d3ae502e66b5ccd12c1370a4 | 17,878 | ipynb | Jupyter Notebook | Appendix-D-HInfinity-Filters.ipynb | wjdghksdl26/Kalman-and-Bayesian-Filters-in-Python | 6b1f8ff74d30680ede64cf9943b13b8bdb5db9e8 | [
"CC-BY-4.0"
] | 12,315 | 2015-01-07T12:06:26.000Z | 2022-03-31T11:03:03.000Z | Appendix-D-HInfinity-Filters.ipynb | wjdghksdl26/Kalman-and-Bayesian-Filters-in-Python | 6b1f8ff74d30680ede64cf9943b13b8bdb5db9e8 | [
"CC-BY-4.0"
] | 356 | 2015-01-09T18:53:02.000Z | 2022-03-14T20:21:06.000Z | Appendix-D-HInfinity-Filters.ipynb | wjdghksdl26/Kalman-and-Bayesian-Filters-in-Python | 6b1f8ff74d30680ede64cf9943b13b8bdb5db9e8 | [
"CC-BY-4.0"
] | 3,419 | 2015-01-02T20:47:47.000Z | 2022-03-31T18:07:33.000Z | 112.440252 | 14,172 | 0.865533 | [
[
[
"[Table of Contents](./table_of_contents.ipynb)",
"_____no_output_____"
],
[
"# H Infinity filter",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"#format the book\nimport book_format\nbook_format.set_style()",
"_____no_output_____"
]
],
[
[
"I am still mulling over how to write this chapter. In the meantime, Professor Dan Simon at Cleveland State University has an accessible introduction here:\n\nhttp://academic.csuohio.edu/simond/courses/eec641/hinfinity.pdf\n\nIn one sentence the $H_\\infty$ (H infinity) filter is like a Kalman filter, but it is robust in the face of non-Gaussian, non-predictable inputs.\n\n\nMy FilterPy library contains an H-Infinity filter. I've pasted some test code below which implements the filter designed by Simon in the article above. Hope it helps.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom filterpy.hinfinity import HInfinityFilter\n\ndt = 0.1\nf = HInfinityFilter(2, 1, dim_u=1, gamma=.01)\n\nf.F = np.array([[1., dt],\n [0., 1.]])\n\nf.H = np.array([[0., 1.]])\nf.G = np.array([[dt**2 / 2, dt]]).T\n\nf.P = 0.01\nf.W = np.array([[0.0003, 0.005],\n [0.0050, 0.100]])/ 1000 #process noise\n\nf.V = 0.01\nf.Q = 0.01\nu = 1. #acceleration of 1 f/sec**2\n\nxs = []\nvs = []\n\nfor i in range(1,40):\n f.update (5)\n #print(f.x.T)\n xs.append(f.x[0,0])\n vs.append(f.x[1,0])\n f.predict(u=u)\n\nplt.subplot(211)\nplt.plot(xs)\nplt.title('position')\nplt.subplot(212)\nplt.plot(vs) \nplt.title('velocity');",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e789749ef23a0bafc3841088745b090d7e7932b9 | 19,069 | ipynb | Jupyter Notebook | VIGA_PREPRO/new/Untitled19.ipynb | wmpjrufg/VIGA-PREPRO-ALGORITMOS | 65c56ae07ab95adc05314289ac57803a570724b0 | [
"MIT"
] | null | null | null | VIGA_PREPRO/new/Untitled19.ipynb | wmpjrufg/VIGA-PREPRO-ALGORITMOS | 65c56ae07ab95adc05314289ac57803a570724b0 | [
"MIT"
] | null | null | null | VIGA_PREPRO/new/Untitled19.ipynb | wmpjrufg/VIGA-PREPRO-ALGORITMOS | 65c56ae07ab95adc05314289ac57803a570724b0 | [
"MIT"
] | null | null | null | 49.788512 | 145 | 0.381667 | [
[
[
"################################################################################\n# UNIVERSIDADE FEDERAL DE CATALÃO (UFCAT)\n# WANDERLEI MALAQUIAS PEREIRA JUNIOR, ENG. CIVIL / PROF (UFCAT)\n# MATHEUS HENRIQUE MORATO DE MORAES ENG. CIVIL / PROF (UFCAT)\n# GUSTAVO GONÇALVES COSTA, ENG. CIVIL (UFCAT)\n################################################################################\n\n################################################################################\n# DESCRIÇÃO ALGORITMO:\n# BIBLIOTECA DE PERDAS DE PROTENSÃO DESENVOLVIDA PELO GRUPO DE PESQUISA E ESTU-\n# DOS EM ENGENHARIA (GPEE)\n################################################################################\n\n\n################################################################################\n# BIBLIOTECAS NATIVAS PYTHON\nimport numpy as np\n\n################################################################################\n# BIBLIOTECAS DESENVOLVEDORES GPEE\n\ndef PERDA_DESLIZAMENTO_ANCORAGEM(P_IT0, SIGMA_PIT0, A_SCP, L_0, DELTA_ANC, E_SCP):\n \"\"\"\n Esta função determina a perda de protensão por deslizamento da armadura na anco-\n ragem.\n \n Entrada:\n P_IT0 | Carga inicial de protensão | kN | float\n SIGMA_PIT0 | Tensão inicial de protensão | kN/m² | float\n A_SCP | Área de total de armadura protendida | m² | float\n L_0 | Comprimento da pista de protensão | m | float\n DELTA_ANC | Previsão do deslizamento do sistema de ancoragem | m | float\n E_SCP | Módulo de Young do aço protendido | kN/m² | float\n\n Saída:\n DELTAPERC | Perda percentual de protensão | % | float\n P_IT1 | Carga final de protensão | kN | float\n SIGMA_PIT1 | Tensão inicial de protensão | kN/m² | float\n \"\"\"\n # Pré-alongamento do cabo\n DELTAL_P = L_0 * (SIGMA_PIT0 / E_SCP)\n # Redução da deformação na armadura de protensão\n DELTAEPSILON_P = DELTA_ANC / (L_0 + DELTAL_P)\n # Perdas de protensão\n DELTASIGMA = E_SCP * DELTAEPSILON_P\n SIGMA_PIT1 = SIGMA_PIT0 - DELTASIGMA\n DELTAP = DELTASIGMA * A_SCP\n P_IT1 = P_IT0 - DELTAP\n DELTAPERC = (DELTAP / P_IT0) * 100\n return DELTAPERC, P_IT1, SIGMA_PIT1\n\ndef PERDA_DEFORMACAO_CONCRETO(E_SCP, E_CCP, P_IT0, SIGMA_PIT0, A_C, I_C, E_P, M_GPP):\n \"\"\"\n Esta função determina a perda de protensão devido a deformação inicial do concreto. \n \n Entrada:\n E_SCP | Módulo de Young do aço protendido | kN/m² | float\n E_CCP | Módulo de Young do concreto | kN/m² | float\n P_IT0 | Carga inicial de protensão | kN | float\n SIGMA_PIT0 | Tensão inicial de protensão | kN/m² | float\n A_C | Área bruta da seção | m² | float \n I_C | Inércia da seção bruta | m^4 | float\n E_P | Excentricidade de protensão | m | float \n M_GPP | Momento fletor devido ao peso próprio | kN.m | float \n \n Saída:\n DELTAPERC | Perda percentual de protensão | % | float\n P_IT1 | Carga final de protensão | kN | float\n SIGMA_PIT1 | Tensão inicial de protensão | kN/m² | float\n \"\"\"\n # Perdas de protensão\n ALPHA_P = E_SCP / E_CCP\n AUX_0 = P_IT0 / A_C\n AUX_1 = (P_IT0 * E_P ** 2) / I_C\n print(P_IT0 * E_P)\n AUX_2 = (M_GPP * E_P) / I_C\n DELTASIGMA = ALPHA_P * (AUX_0 + AUX_1 - AUX_2)\n print(DELTASIGMA)\n SIGMA_PIT1 = SIGMA_PIT0 - DELTASIGMA\n DELTAP = DELTASIGMA * A_SCP\n P_IT1 = P_IT0 - DELTAP\n DELTAPERC = (DELTAP / P_IT0) * 100\n return DELTAPERC, P_IT1, SIGMA_PIT1\n\ndef INTERPOLADOR (X_1, X_2, X_K, Y_1, Y_2):\n \"\"\"\n Esta função interpola lineramente valores.\n\n Entrada:\n X_1 | Valor inferior X_K | | float\n X_2 | Valor superior X_K | | float\n Y_1 | Valor inferior Y_K | | float\n Y_2 | Valor superior Y_K | | float\n X_K | Valor X de referência | | float\n\n Saída:\n Y_K | Valor interpolado Y | | float\n \"\"\"\n Y_K = Y_1 + (X_K - X_1) * ((Y_2 - Y_1) / (X_2 - X_1))\n return Y_K \n\ndef TABELA_PSI1000(TIPO_FIO_CORD_BAR, TIPO_ACO, RHO_SIGMA):\n \"\"\"\n Esta função encontra o fator Psi 1000 para cálculo da relaxação.\n\n Entrada:\n TIPO_FIO_CORD_BAR | Tipo de armadura de protensão de acordo com a aderência escolhida | | string\n | 'FIO' - Fio | |\n | 'COR' - Cordoalha | |\n | 'BAR' - BARRA | |\n TIPO_ACO | Tipo de aço | | string\n | 'RN' - Relaxação normal | |\n | 'RB' - Relaxação baixa | |\n RHO_SIGMA | Razão entre F_PK e SIGMA_PI | | float\n\n Saída:\n PSI_1000 | Valor médio da relaxação, medidos após 1.000 h, à temperatura constante de 20 °C | % | float \n \"\"\"\n # Cordoalhas\n if TIPO_FIO_CORD_BAR == 'COR':\n if TIPO_ACO == 'RN':\n if RHO_SIGMA <= 0.5:\n PSI_1000 = 0\n elif 0.5 < RHO_SIGMA and RHO_SIGMA <= 0.6:\n Y_0 = 0.00; Y_1 = 3.50\n X_0 = 0.50; X_1 = 0.60\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.6 < RHO_SIGMA and RHO_SIGMA <= 0.7:\n Y_0 = 3.50; Y_1 = 7.00\n X_0 = 0.60; X_1 = 0.70\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.7 < RHO_SIGMA and RHO_SIGMA <= 0.8:\n Y_0 = 7.00; Y_1 = 12.00\n X_0 = 0.70; X_1 = 0.80\n X_K = RHO_SIGMA \n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1) \n elif TIPO_ACO == 'RB':\n if RHO_SIGMA <= 0.5:\n PSI_1000 = 0\n elif 0.5 < RHO_SIGMA and RHO_SIGMA <= 0.6:\n Y_0 = 0.00; Y_1 = 1.30\n X_0 = 0.50; X_1 = 0.60\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.6 < RHO_SIGMA and RHO_SIGMA <= 0.7:\n Y_0 = 1.30; Y_1 = 2.50\n X_0 = 0.60; X_1 = 0.70\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.7 < RHO_SIGMA and RHO_SIGMA <= 0.8:\n Y_0 = 2.50; Y_1 = 3.50\n X_0 = 0.70; X_1 = 0.80\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n # Fio\n elif TIPO_FIO_CORD_BAR == 'FIO':\n if TIPO_ACO == 'RN':\n if RHO_SIGMA <= 0.5:\n PSI_1000 = 0\n elif 0.5 < RHO_SIGMA and RHO_SIGMA <= 0.6:\n Y_0 = 0.00; Y_1 = 2.50\n X_0 = 0.50; X_1 = 0.60\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.6 < RHO_SIGMA and RHO_SIGMA <= 0.7:\n Y_0 = 2.50; Y_1 = 5.00\n X_0 = 0.60; X_1 = 0.70\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.7 < RHO_SIGMA and RHO_SIGMA <= 0.8:\n Y_0 = 5.00; Y_1 = 8.50\n X_0 = 0.70; X_1 = 0.80\n X_K = RHO_SIGMA \n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1) \n elif TIPO_ACO == 'RB':\n if RHO_SIGMA <= 0.5:\n PSI_1000 = 0 \n elif 0.5 < RHO_SIGMA and RHO_SIGMA <= 0.6:\n Y_0 = 0.00; Y_1 = 1.00\n X_0 = 0.50; X_1 = 0.60\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.6 < RHO_SIGMA and RHO_SIGMA <= 0.7:\n Y_0 = 1.00; Y_1 = 2.00\n X_0 = 0.60; X_1 = 0.70\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1)\n elif 0.7 < RHO_SIGMA and RHO_SIGMA <= 0.8:\n Y_0 = 2.00; Y_1 = 3.00\n X_0 = 0.70; X_1 = 0.80\n X_K = RHO_SIGMA \n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1) \n # Barra\n elif TIPO_FIO_CORD_BAR == 'BAR':\n if RHO_SIGMA <= 0.5:\n PSI_1000 = 0 \n elif 0.5 < RHO_SIGMA and RHO_SIGMA <= 0.6:\n Y_0 = 0.00; Y_1 = 1.50\n X_0 = 0.50; X_1 = 0.60\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1) \n elif 0.6 < RHO_SIGMA and RHO_SIGMA <= 0.7:\n Y_0 = 1.50; Y_1 = 4.00\n X_0 = 0.60; X_1 = 0.70\n X_K = RHO_SIGMA\n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1) \n elif 0.7 < RHO_SIGMA and RHO_SIGMA <= 0.8:\n Y_0 = 4.00; Y_1 = 7.00\n X_0 = 0.70; X_1 = 0.80\n X_K = RHO_SIGMA \n PSI_1000 = INTERPOLADOR(X_0, X_1, X_K, Y_0, Y_1) \n return PSI_1000 \n\ndef PERDA_RELAXACAO_ARMADURA(P_IT0, SIGMA_PIT0, T_0, T_1, TEMP, F_PK, A_SCP, TIPO_FIO_CORD_BAR, TIPO_ACO):\n \"\"\"\n Esta função determina a perda de protensão por relaxação da armadura de protensão\n em peças de concreto protendido. \n \n Entrada:\n P_IT0 | Carga inicial de protensão | kN | float\n SIGMA_PIT0 | Tensão inicial de protensão | kN/m² | float\n T_0 | Tempo inicial de análise sem correção da temperatura | dias | float\n T_1 | Tempo final de análise sem correção da temperatura | dias | float \n TEMP | Temperatura de projeto | °C | float \n F_PK | Tensão última do aço | kN/m² | float\n A_SCP | Área de total de armadura protendida | m² | float\n TIPO_FIO_CORD_BAR | Tipo de armadura de protensão de acordo com a aderência escolhida | | string\n | 'FIO' - Fio | |\n | 'COR' - Cordoalha | |\n | 'BAR' - BARRA | |\n TIPO_ACO | Tipo de aço | | string\n | 'RN' - Relaxação normal | |\n | 'RB' - Relaxação baixa | |\n \n Saída:\n DELTAPERC | Perda percentual de protensão | % | float\n P_IT1 | Carga final de protensão | kN | float\n SIGMA_PIT1 | Tensão inicial de protensão | kN/m² | float\n \"\"\"\n # Determinação PSI_1000\n RHO_SIGMA = SIGMA_PIT0 / F_PK \n if T_1 > (20 * 365): \n PSI_1000 = 2.5\n else:\n PSI_1000 = TABELA_PSI1000(TIPO_FIO_CORD_BAR, TIPO_ACO, RHO_SIGMA)\n \n # Determinação do PSI no intervalo de tempo T_1 - T_0\n DELTAT_COR = (T_1 - T_0) * TEMP / 20\n PSI = PSI_1000 * (DELTAT_COR / 41.67) ** 0.15\n # Perdas de protensão\n DELTASIGMA = (PSI / 100) * SIGMA_PIT0\n SIGMA_PIT1 = SIGMA_PIT0 - DELTASIGMA\n DELTAP = DELTASIGMA * A_SCP\n P_IT1 = P_IT0 - DELTAP\n DELTAPERC = (DELTAP / P_IT0) * 100\n return DELTAPERC, P_IT1, SIGMA_PIT1\n",
"_____no_output_____"
],
[
"SIGMA_PIT0 = 1453E3\nA_SCP = 6.08 / 1E4\nP_IT0 = SIGMA_PIT0 * A_SCP\nL_0 = 150\nDELTA_ANC = 6 / 1E3\nE_SCP = 200E6\nDELTAPERC, P_IT1, SIGMA_PIT1 = PERDA_DESLIZAMENTO_ANCORAGEM(P_IT0, SIGMA_PIT0, A_SCP, L_0, DELTA_ANC, E_SCP)\nprint(DELTAPERC, P_IT1, SIGMA_PIT1)",
"0.5466138469606744 878.5950820886262 1445057.7008036615\n"
],
[
"T_0 = 0; T_1 = 1; TEMP = 20; F_PK = 1900E3\nTIPO_FIO_CORD_BAR = 'COR'; TIPO_ACO = 'RB'\nDELTAPERC, P_IT2, SIGMA_PIT2 = PERDA_RELAXACAO_ARMADURA(P_IT1, SIGMA_PIT1, T_0, T_1, TEMP, F_PK, A_SCP, TIPO_FIO_CORD_BAR, TIPO_ACO)\nprint(DELTAPERC, P_IT2, SIGMA_PIT2)",
"1.7748733018042064 863.0011325456704 1419409.7574764316\n"
],
[
"E_CCP = 28000E3\nA_C = 0.1245; I_C = 7.097 / 1E3; E_P = 0.30\nM_GPP = 155.50\n[DELTAPERC, P_IT3, SIGMA_PIT3] = PERDA_DEFORMACAO_CONCRETO(E_SCP, E_CCP, P_IT2, SIGMA_PIT2, A_C, I_C, E_P, M_GPP)\nprint(DELTAPERC, P_IT3, SIGMA_PIT3)",
"258.90033976370114\n80732.93781297505\n5.687782360782847 813.9155063553816 1338676.8196634564\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e78987e1c3ee8d698e7a3ba2795927baacc98558 | 123,216 | ipynb | Jupyter Notebook | python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb | rtp-aws/devpost_aws_disaster_recovery | 2ccfff2d8b85614f3043f09d98c9981dedf43c05 | [
"MIT"
] | 1 | 2022-01-13T23:36:05.000Z | 2022-01-13T23:36:05.000Z | python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb | rtp-aws/devpost_aws_disaster_recovery | 2ccfff2d8b85614f3043f09d98c9981dedf43c05 | [
"MIT"
] | 9 | 2022-01-13T19:34:34.000Z | 2022-01-14T19:41:18.000Z | python/d2l-en/mxnet/chapter_generative-adversarial-networks/gan.ipynb | rtp-aws/devpost_aws_disaster_recovery | 2ccfff2d8b85614f3043f09d98c9981dedf43c05 | [
"MIT"
] | null | null | null | 53.179111 | 1,167 | 0.512198 | [
[
[
"# Generative Adversarial Networks\n:label:`sec_basic_gan`\n\nThroughout most of this book, we have talked about how to make predictions. In some form or another, we used deep neural networks learned mappings from data examples to labels. This kind of learning is called discriminative learning, as in, we'd like to be able to discriminate between photos cats and photos of dogs. Classifiers and regressors are both examples of discriminative learning. And neural networks trained by backpropagation have upended everything we thought we knew about discriminative learning on large complicated datasets. Classification accuracies on high-res images has gone from useless to human-level (with some caveats) in just 5-6 years. We will spare you another spiel about all the other discriminative tasks where deep neural networks do astoundingly well.\n\nBut there is more to machine learning than just solving discriminative tasks. For example, given a large dataset, without any labels, we might want to learn a model that concisely captures the characteristics of this data. Given such a model, we could sample synthetic data examples that resemble the distribution of the training data. For example, given a large corpus of photographs of faces, we might want to be able to generate a new photorealistic image that looks like it might plausibly have come from the same dataset. This kind of learning is called generative modeling.\n\nUntil recently, we had no method that could synthesize novel photorealistic images. But the success of deep neural networks for discriminative learning opened up new possibilities. One big trend over the last three years has been the application of discriminative deep nets to overcome challenges in problems that we do not generally think of as supervised learning problems. The recurrent neural network language models are one example of using a discriminative network (trained to predict the next character) that once trained can act as a generative model.\n\nIn 2014, a breakthrough paper introduced Generative adversarial networks (GANs) :cite:`Goodfellow.Pouget-Abadie.Mirza.ea.2014`, a clever new way to leverage the power of discriminative models to get good generative models. At their heart, GANs rely on the idea that a data generator is good if we cannot tell fake data apart from real data. In statistics, this is called a two-sample test - a test to answer the question whether datasets $X=\\{x_1,\\ldots, x_n\\}$ and $X'=\\{x'_1,\\ldots, x'_n\\}$ were drawn from the same distribution. The main difference between most statistics papers and GANs is that the latter use this idea in a constructive way. In other words, rather than just training a model to say \"hey, these two datasets do not look like they came from the same distribution\", they use the [two-sample test](https://en.wikipedia.org/wiki/Two-sample_hypothesis_testing) to provide training signals to a generative model. This allows us to improve the data generator until it generates something that resembles the real data. At the very least, it needs to fool the classifier. Even if our classifier is a state of the art deep neural network.\n\n\n:label:`fig_gan`\n\n\nThe GAN architecture is illustrated in :numref:`fig_gan`.\nAs you can see, there are two pieces in GAN architecture - first off, we need a device (say, a deep network but it really could be anything, such as a game rendering engine) that might potentially be able to generate data that looks just like the real thing. If we are dealing with images, this needs to generate images. If we are dealing with speech, it needs to generate audio sequences, and so on. We call this the generator network. The second component is the discriminator network. It attempts to distinguish fake and real data from each other. Both networks are in competition with each other. The generator network attempts to fool the discriminator network. At that point, the discriminator network adapts to the new fake data. This information, in turn is used to improve the generator network, and so on.\n\n\nThe discriminator is a binary classifier to distinguish if the input $x$ is real (from real data) or fake (from the generator). Typically, the discriminator outputs a scalar prediction $o\\in\\mathbb R$ for input $\\mathbf x$, such as using a dense layer with hidden size 1, and then applies sigmoid function to obtain the predicted probability $D(\\mathbf x) = 1/(1+e^{-o})$. Assume the label $y$ for the true data is $1$ and $0$ for the fake data. We train the discriminator to minimize the cross-entropy loss, *i.e.*,\n\n$$ \\min_D \\{ - y \\log D(\\mathbf x) - (1-y)\\log(1-D(\\mathbf x)) \\},$$\n\nFor the generator, it first draws some parameter $\\mathbf z\\in\\mathbb R^d$ from a source of randomness, *e.g.*, a normal distribution $\\mathbf z \\sim \\mathcal{N} (0, 1)$. We often call $\\mathbf z$ as the latent variable.\nIt then applies a function to generate $\\mathbf x'=G(\\mathbf z)$. The goal of the generator is to fool the discriminator to classify $\\mathbf x'=G(\\mathbf z)$ as true data, *i.e.*, we want $D( G(\\mathbf z)) \\approx 1$.\nIn other words, for a given discriminator $D$, we update the parameters of the generator $G$ to maximize the cross-entropy loss when $y=0$, *i.e.*,\n\n$$ \\max_G \\{ - (1-y) \\log(1-D(G(\\mathbf z))) \\} = \\max_G \\{ - \\log(1-D(G(\\mathbf z))) \\}.$$\n\nIf the generator does a perfect job, then $D(\\mathbf x')\\approx 1$ so the above loss near 0, which results the gradients are too small to make a good progress for the discriminator. So commonly we minimize the following loss:\n\n$$ \\min_G \\{ - y \\log(D(G(\\mathbf z))) \\} = \\min_G \\{ - \\log(D(G(\\mathbf z))) \\}, $$\n\nwhich is just feed $\\mathbf x'=G(\\mathbf z)$ into the discriminator but giving label $y=1$.\n\n\nTo sum up, $D$ and $G$ are playing a \"minimax\" game with the comprehensive objective function:\n\n$$min_D max_G \\{ -E_{x \\sim \\text{Data}} log D(\\mathbf x) - E_{z \\sim \\text{Noise}} log(1 - D(G(\\mathbf z))) \\}.$$\n\n\n\nMany of the GANs applications are in the context of images. As a demonstration purpose, we are going to content ourselves with fitting a much simpler distribution first. We will illustrate what happens if we use GANs to build the world's most inefficient estimator of parameters for a Gaussian. Let us get started.\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfrom mxnet import autograd, gluon, init, np, npx\nfrom mxnet.gluon import nn\nfrom d2l import mxnet as d2l\n\nnpx.set_np()",
"_____no_output_____"
]
],
[
[
"## Generate Some \"Real\" Data\n\nSince this is going to be the world's lamest example, we simply generate data drawn from a Gaussian.\n",
"_____no_output_____"
]
],
[
[
"X = np.random.normal(0.0, 1, (1000, 2))\nA = np.array([[1, 2], [-0.1, 0.5]])\nb = np.array([1, 2])\ndata = np.dot(X, A) + b",
"_____no_output_____"
]
],
[
[
"Let us see what we got. This should be a Gaussian shifted in some rather arbitrary way with mean $b$ and covariance matrix $A^TA$.\n",
"_____no_output_____"
]
],
[
[
"d2l.set_figsize()\nd2l.plt.scatter(data[:100, (0)].asnumpy(), data[:100, (1)].asnumpy());\nprint(f'The covariance matrix is\\n{np.dot(A.T, A)}')",
"The covariance matrix is\n[[1.01 1.95]\n [1.95 4.25]]\n"
],
[
"batch_size = 8\ndata_iter = d2l.load_array((data,), batch_size)",
"_____no_output_____"
]
],
[
[
"## Generator\n\nOur generator network will be the simplest network possible - a single layer linear model. This is since we will be driving that linear network with a Gaussian data generator. Hence, it literally only needs to learn the parameters to fake things perfectly.\n",
"_____no_output_____"
]
],
[
[
"net_G = nn.Sequential()\nnet_G.add(nn.Dense(2))",
"_____no_output_____"
]
],
[
[
"## Discriminator\n\nFor the discriminator we will be a bit more discriminating: we will use an MLP with 3 layers to make things a bit more interesting.\n",
"_____no_output_____"
]
],
[
[
"net_D = nn.Sequential()\nnet_D.add(nn.Dense(5, activation='tanh'),\n nn.Dense(3, activation='tanh'),\n nn.Dense(1))",
"_____no_output_____"
]
],
[
[
"## Training\n\nFirst we define a function to update the discriminator.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef update_D(X, Z, net_D, net_G, loss, trainer_D):\n \"\"\"Update discriminator.\"\"\"\n batch_size = X.shape[0]\n ones = np.ones((batch_size,), ctx=X.ctx)\n zeros = np.zeros((batch_size,), ctx=X.ctx)\n with autograd.record():\n real_Y = net_D(X)\n fake_X = net_G(Z)\n # Do not need to compute gradient for `net_G`, detach it from\n # computing gradients.\n fake_Y = net_D(fake_X.detach())\n loss_D = (loss(real_Y, ones) + loss(fake_Y, zeros)) / 2\n loss_D.backward()\n trainer_D.step(batch_size)\n return float(loss_D.sum())",
"_____no_output_____"
]
],
[
[
"The generator is updated similarly. Here we reuse the cross-entropy loss but change the label of the fake data from $0$ to $1$.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef update_G(Z, net_D, net_G, loss, trainer_G):\n \"\"\"Update generator.\"\"\"\n batch_size = Z.shape[0]\n ones = np.ones((batch_size,), ctx=Z.ctx)\n with autograd.record():\n # We could reuse `fake_X` from `update_D` to save computation\n fake_X = net_G(Z)\n # Recomputing `fake_Y` is needed since `net_D` is changed\n fake_Y = net_D(fake_X)\n loss_G = loss(fake_Y, ones)\n loss_G.backward()\n trainer_G.step(batch_size)\n return float(loss_G.sum())",
"_____no_output_____"
]
],
[
[
"Both the discriminator and the generator performs a binary logistic regression with the cross-entropy loss. We use Adam to smooth the training process. In each iteration, we first update the discriminator and then the generator. We visualize both losses and generated examples.\n",
"_____no_output_____"
]
],
[
[
"def train(net_D, net_G, data_iter, num_epochs, lr_D, lr_G, latent_dim, data):\n loss = gluon.loss.SigmoidBCELoss()\n net_D.initialize(init=init.Normal(0.02), force_reinit=True)\n net_G.initialize(init=init.Normal(0.02), force_reinit=True)\n trainer_D = gluon.Trainer(net_D.collect_params(),\n 'adam', {'learning_rate': lr_D})\n trainer_G = gluon.Trainer(net_G.collect_params(),\n 'adam', {'learning_rate': lr_G})\n animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n xlim=[1, num_epochs], nrows=2, figsize=(5, 5),\n legend=['discriminator', 'generator'])\n animator.fig.subplots_adjust(hspace=0.3)\n for epoch in range(num_epochs):\n # Train one epoch\n timer = d2l.Timer()\n metric = d2l.Accumulator(3) # loss_D, loss_G, num_examples\n for X in data_iter:\n batch_size = X.shape[0]\n Z = np.random.normal(0, 1, size=(batch_size, latent_dim))\n metric.add(update_D(X, Z, net_D, net_G, loss, trainer_D),\n update_G(Z, net_D, net_G, loss, trainer_G),\n batch_size)\n # Visualize generated examples\n Z = np.random.normal(0, 1, size=(100, latent_dim))\n fake_X = net_G(Z).asnumpy()\n animator.axes[1].cla()\n animator.axes[1].scatter(data[:, 0], data[:, 1])\n animator.axes[1].scatter(fake_X[:, 0], fake_X[:, 1])\n animator.axes[1].legend(['real', 'generated'])\n # Show the losses\n loss_D, loss_G = metric[0]/metric[2], metric[1]/metric[2]\n animator.add(epoch + 1, (loss_D, loss_G))\n print(f'loss_D {loss_D:.3f}, loss_G {loss_G:.3f}, '\n f'{metric[2] / timer.stop():.1f} examples/sec')",
"_____no_output_____"
]
],
[
[
"Now we specify the hyperparameters to fit the Gaussian distribution.\n",
"_____no_output_____"
]
],
[
[
"lr_D, lr_G, latent_dim, num_epochs = 0.05, 0.005, 2, 20\ntrain(net_D, net_G, data_iter, num_epochs, lr_D, lr_G,\n latent_dim, data[:100].asnumpy())",
"loss_D 0.693, loss_G 0.693, 549.8 examples/sec\n"
]
],
[
[
"## Summary\n\n* Generative adversarial networks (GANs) composes of two deep networks, the generator and the discriminator.\n* The generator generates the image as much closer to the true image as possible to fool the discriminator, via maximizing the cross-entropy loss, *i.e.*, $\\max \\log(D(\\mathbf{x'}))$.\n* The discriminator tries to distinguish the generated images from the true images, via minimizing the cross-entropy loss, *i.e.*, $\\min - y \\log D(\\mathbf{x}) - (1-y)\\log(1-D(\\mathbf{x}))$.\n\n## Exercises\n\n* Does an equilibrium exist where the generator wins, *i.e.* the discriminator ends up unable to distinguish the two distributions on finite samples?\n",
"_____no_output_____"
],
[
"[Discussions](https://discuss.d2l.ai/t/408)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e78989131f86bbe2e3a2273e40b68efd15759b3b | 12,875 | ipynb | Jupyter Notebook | examples/unstructured_profilers.ipynb | taylorfturner/DataProfiler | e4548d5e6b83f8ef9a0b07c519e73a5228e1c79e | [
"Apache-2.0"
] | 690 | 2021-02-19T19:57:31.000Z | 2022-03-29T23:08:39.000Z | examples/unstructured_profilers.ipynb | taylorfturner/DataProfiler | e4548d5e6b83f8ef9a0b07c519e73a5228e1c79e | [
"Apache-2.0"
] | 179 | 2021-02-17T20:49:16.000Z | 2022-03-21T18:49:49.000Z | examples/unstructured_profilers.ipynb | taylorfturner/DataProfiler | e4548d5e6b83f8ef9a0b07c519e73a5228e1c79e | [
"Apache-2.0"
] | 48 | 2021-02-19T19:25:32.000Z | 2022-03-21T17:36:50.000Z | 31.711823 | 328 | 0.585165 | [
[
[
"# Unstructured Profilers",
"_____no_output_____"
],
[
"**Data profiling** - *is the process of examining a dataset and collecting statistical or informational summaries about said dataset.*\n\nThe Profiler class inside the DataProfiler is designed to generate *data profiles* via the Profiler class, which ingests either a Data class or a Pandas DataFrame. \n\nCurrently, the Data class supports loading the following file formats:\n\n* Any delimited (CSV, TSV, etc.)\n* JSON object\n* Avro\n* Parquet\n* Text files\n* Pandas Series/Dataframe\n\nOnce the data is loaded, the Profiler can calculate statistics and predict the entities (via the Labeler) of every column (csv) or key-value (JSON) store as well as dataset wide information, such as the number of nulls, duplicates, etc.\n\nThis example will look at specifically the unstructured data types for unstructured profiling. This means that only text files, lists of strings, single column pandas dataframes/series, or DataProfile Data objects in string format will work with the unstructured profiler. ",
"_____no_output_____"
],
[
"## Reporting",
"_____no_output_____"
],
[
"One of the primary purposes of the Profiler are to quickly identify what is in the dataset. This can be useful for analyzing a dataset prior to use or determining which columns could be useful for a given purpose.\n\nIn terms of reporting, there are multiple reporting options:\n\n* **Pretty**: Floats are rounded to four decimal places, and lists are shortened.\n* **Compact**: Similar to pretty, but removes detailed statistics\n* **Serializable**: Output is json serializable and not prettified\n* **Flat**: Nested Output is returned as a flattened dictionary\n\nThe **Pretty** and **Compact** reports are the two most commonly used reports and includes `global_stats` and `data_stats` for the given dataset. `global_stats` contains overall properties of the data such as samples used and file encoding. `data_stats` contains specific properties and statistics for each text sample.\n\nFor unstructured profiles, the report looks like this:\n\n```\n\"global_stats\": {\n \"samples_used\": int,\n \"empty_line_count\": int,\n \"file_type\": string,\n \"encoding\": string\n},\n\"data_stats\": {\n \"data_label\": {\n \"entity_counts\": {\n \"word_level\": dict(int),\n \"true_char_level\": dict(int),\n \"postprocess_char_level\": dict(int)\n },\n \"times\": dict(float)\n },\n \"statistics\": {\n \"vocab\": list(char),\n \"words\": list(string),\n \"word_count\": dict(int),\n \"times\": dict(float)\n }\n}\n```",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport json\n\ntry:\n sys.path.insert(0, '..')\n import dataprofiler as dp\nexcept ImportError:\n import dataprofiler as dp\n\ndata_path = \"../dataprofiler/tests/data\"\n\n# remove extra tf loggin\nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)",
"_____no_output_____"
],
[
"data = dp.Data(os.path.join(data_path, \"txt/discussion_reddit.txt\"))\nprofile = dp.Profiler(data)\n\nreport = profile.report(report_options={\"output_format\": \"pretty\"})\nprint(json.dumps(report, indent=4))",
"_____no_output_____"
]
],
[
[
"## Profiler Type",
"_____no_output_____"
],
[
"It should be noted, in addition to reading the input data from text files, DataProfiler allows the input data as a pandas dataframe, a pandas series, a list, and Data objects (when an unstructured format is selected) if the Profiler is explicitly chosen as unstructured.",
"_____no_output_____"
]
],
[
[
"# run data profiler and get the report\nimport pandas as pd\ndata = dp.Data(os.path.join(data_path, \"csv/SchoolDataSmall.csv\"), options={\"data_format\": \"records\"})\nprofile = dp.Profiler(data, profiler_type='unstructured')\n\nreport = profile.report(report_options={\"output_format\":\"pretty\"})\nprint(json.dumps(report, indent=4))",
"_____no_output_____"
]
],
[
[
"## Profiler options",
"_____no_output_____"
],
[
"The DataProfiler has the ability to turn on and off components as needed. This is accomplished via the `ProfilerOptions` class.\n\nFor example, if a user doesn't require vocab count information they may desire to turn off the word count functionality.\n\nBelow, let's remove the vocab count and set the stop words. \n\nFull list of options in the Profiler section of the [DataProfiler documentation](https://capitalone.github.io/DataProfiler).",
"_____no_output_____"
]
],
[
[
"data = dp.Data(os.path.join(data_path, \"txt/discussion_reddit.txt\"))\n\nprofile_options = dp.ProfilerOptions()\n\n# Setting multiple options via set\nprofile_options.set({ \"*.vocab.is_enabled\": False, \"*.is_case_sensitive\": True })\n\n# Set options via directly setting them\nprofile_options.unstructured_options.text.stop_words = [\"These\", \"are\", \"stop\", \"words\"]\n\nprofile = dp.Profiler(data, options=profile_options)\nreport = profile.report(report_options={\"output_format\": \"compact\"})\n\n# Print the report\nprint(json.dumps(report, indent=4))",
"_____no_output_____"
]
],
[
[
"## Updating Profiles",
"_____no_output_____"
],
[
"Beyond just profiling, one of the unique aspects of the DataProfiler is the ability to update the profiles. To update appropriately, the schema (columns / keys) must match appropriately.",
"_____no_output_____"
]
],
[
[
"# Load and profile a CSV file\ndata = dp.Data(os.path.join(data_path, \"txt/sentence-3x.txt\"))\nprofile = dp.Profiler(data)\n\n# Update the profile with new data:\nnew_data = dp.Data(os.path.join(data_path, \"txt/sentence-3x.txt\"))\nprofile.update_profile(new_data)\n\n# Take a peek at the data\nprint(data.data)\nprint(new_data.data)\n\n# Report the compact version of the profile\nreport = profile.report(report_options={\"output_format\": \"compact\"})\nprint(json.dumps(report, indent=4))",
"_____no_output_____"
]
],
[
[
"## Merging Profiles",
"_____no_output_____"
],
[
"Merging profiles are an alternative method for updating profiles. Particularly, multiple profiles can be generated seperately, then added together with a simple `+` command: `profile3 = profile1 + profile2`",
"_____no_output_____"
]
],
[
[
"# Load a CSV file with a schema\ndata1 = dp.Data(os.path.join(data_path, \"txt/sentence-3x.txt\"))\nprofile1 = dp.Profiler(data1)\n\n# Load another CSV file with the same schema\ndata2 = dp.Data(os.path.join(data_path, \"txt/sentence-3x.txt\"))\nprofile2 = dp.Profiler(data2)\n\n# Merge the profiles\nprofile3 = profile1 + profile2\n\n# Report the compact version of the profile\nreport = profile3.report(report_options={\"output_format\":\"compact\"})\nprint(json.dumps(report, indent=4))",
"_____no_output_____"
]
],
[
[
"As you can see, the `update_profile` function and the `+` operator function similarly. The reason the `+` operator is important is that it's possible to *save and load profiles*, which we cover next.",
"_____no_output_____"
],
[
"## Saving and Loading a Profile",
"_____no_output_____"
],
[
"Not only can the Profiler create and update profiles, it's also possible to save, load then manipulate profiles.",
"_____no_output_____"
]
],
[
[
"# Load data\ndata = dp.Data(os.path.join(data_path, \"txt/sentence-3x.txt\"))\n\n# Generate a profile\nprofile = dp.Profiler(data)\n\n# Save a profile to disk for later (saves as pickle file)\nprofile.save(filepath=\"my_profile.pkl\")\n\n# Load a profile from disk\nloaded_profile = dp.Profiler.load(\"my_profile.pkl\")\n\n# Report the compact version of the profile\nreport = profile.report(report_options={\"output_format\":\"compact\"})\nprint(json.dumps(report, indent=4))",
"_____no_output_____"
]
],
[
[
"With the ability to save and load profiles, profiles can be generated via multiple machines then merged. Further, profiles can be stored and later used in applications such as change point detection, synthetic data generation, and more. ",
"_____no_output_____"
]
],
[
[
"# Load a multiple files via the Data class\nfilenames = [\"txt/sentence-3x.txt\",\n \"txt/sentence.txt\"]\ndata_objects = []\nfor filename in filenames:\n data_objects.append(dp.Data(os.path.join(data_path, filename)))\n\nprint(data_objects)\n# Generate and save profiles\nfor i in range(len(data_objects)):\n profile = dp.Profiler(data_objects[i])\n report = profile.report(report_options={\"output_format\":\"compact\"})\n print(json.dumps(report, indent=4))\n profile.save(filepath=\"data-\"+str(i)+\".pkl\")\n\n\n# Load profiles and add them together\nprofile = None\nfor i in range(len(data_objects)):\n if profile is None:\n profile = dp.Profiler.load(\"data-\"+str(i)+\".pkl\")\n else:\n profile += dp.Profiler.load(\"data-\"+str(i)+\".pkl\")\n\n\n# Report the compact version of the profile\nreport = profile.report(report_options={\"output_format\":\"compact\"})\nprint(json.dumps(report, indent=4))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7898c6950237c467a15864312d66b994ae31555 | 23,448 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Stationarity-Decomposition-Periodicity-checkpoint.ipynb | ahtshamzafar1/Time-Series-Data-Analysis | 6cf6e5ffafe15bfec18a82292b04bad90a6dd608 | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Stationarity-Decomposition-Periodicity-checkpoint.ipynb | ahtshamzafar1/Time-Series-Data-Analysis | 6cf6e5ffafe15bfec18a82292b04bad90a6dd608 | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Stationarity-Decomposition-Periodicity-checkpoint.ipynb | ahtshamzafar1/Time-Series-Data-Analysis | 6cf6e5ffafe15bfec18a82292b04bad90a6dd608 | [
"MIT"
] | null | null | null | 49.572939 | 1,706 | 0.540984 | [
[
[
"import logging\nimport warnings\nimport itertools\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.stattools import kpss\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nfrom scipy.signal import find_peaks, find_peaks_cwt\n\nlogging.disable(logging.WARNING)\nwarnings.filterwarnings('ignore')\n",
"_____no_output_____"
]
],
[
[
"## Functions",
"_____no_output_____"
]
],
[
[
"def adf_test(time_series):\n \"\"\"\n param time_series: takes a time series list as an input\n return: True/False as a results of KPSS alongside the output in dataframe\n \"\"\"\n dftest = adfuller(time_series, autolag='AIC')\n dfoutput = pd.Series(dftest[0:4],\n index=[\n 'Test Statistic', 'p-value', '#Lags Used',\n 'Number of Observations Used'\n ])\n for key, value in dftest[4].items():\n dfoutput['Critical Value (%s)' % key] = value\n\n if dfoutput['p-value'] < 0.01:\n return True, dfoutput\n else:\n return False, dfoutput\n\n\ndef kpss_test(time_series):\n kpsstest = kpss(time_series, regression='c')\n dfoutput = pd.Series(kpsstest[0:3],\n index=['Test Statistic', 'p-value', 'Lags Used'])\n for key, value in kpsstest[3].items():\n dfoutput['Critical Value (%s)' % key] = value\n\n if dfoutput['p-value'] < 0.01:\n return False, dfoutput\n else:\n return True, dfoutput\n\n\ndef most_frequent(list):\n counter = 0\n num = list[0]\n\n for i in list:\n curr_frequency = list.count(i)\n if curr_frequency > counter:\n counter = curr_frequency\n num = i\n return num\n\n\ndef identify_cont_disc(df):\n \"\"\"\n :param df: the metric data column(s) that has no NAN or constant values\n :return: list of continuous metrics and their corresponding data column(s)\n \"\"\"\n raw_feature_list = df.columns\n raw_feature_list = list(raw_feature_list.values)\n\n # feature_list = df.columns\n discrete_features = []\n continuous_features = []\n for colum in raw_feature_list:\n if len(df[colum].unique()) < 20:\n # print(colum, ': ', df[colum].unique())\n discrete_features.append(colum)\n else:\n # print(colum, \": continuous features\")\n continuous_features.append(colum)\n df_cont = df[continuous_features].copy()\n\n df_disc = df[discrete_features].copy()\n\n return continuous_features, discrete_features\n\n\ndef analysisPeriod(df_raw, feature, time_feature, plot=False, verbose=False):\n \"\"\"\n :param df_raw: data set\n :param feature: metric name\n :param time_feature: time series name\n :param plot: visual analysis functionality\n :param verbose: print details on the console\n :return: stationary, seasonal, period, decomposed series\n \"\"\"\n\n ## INITIALIZATION: time series should be normalised into [0, 1]\n\n seasonal = False\n stationary = False\n df_ts = df_raw.copy()\n\n # Stationary Check\n # ADF TEST: Augmented Dickey–Fuller test\n # KPSS TEST: Kwiatkowski–Phillips–Schmidt–Shin TEST\n adf_result, adf_output = adf_test(df_ts[feature])\n kpss_result, kpss_output = kpss_test(df_ts[feature])\n\n if verbose:\n print('adf-Test')\n print(adf_result)\n print(adf_output)\n print('kpss-Test')\n print(kpss_result)\n print(kpss_output)\n\n # This is the code to use two tests, it will return true for stationary if or(test1,test2) = True\n if adf_result == True & kpss_result == True:\n stationary = True\n elif adf_result == True & kpss_result == False:\n stationary = False\n print(\"Difference Stationary\")\n elif adf_result == False & kpss_result == True:\n stationary = False\n print(\"Trend Stationary\")\n else:\n stationary = False\n\n # First: checking flat line.\n if np.all(np.isclose(df_ts[feature].values, df_ts[feature].values[0])):\n print('Constant series')\n seasonal = False\n period = 1\n result_add = None\n else:\n # If not flat line then:\n # Seasonality Check:\n\n # Automatic find the period based on Time Index\n\n # Shift windows to find autocorrelations\n shift_ = []\n for i in np.arange(len(df_ts[feature])):\n shift_.append(df_ts[feature].autocorr(lag=i))\n shift_ = np.array(shift_)\n\n # if max of Autocorelation greater than 0.9, we have seasonal\n if max(shift_) >= 0.9:\n seasonal = True\n\n # find peaks of autocorelation -> in order to find local maxima\n # peaks, _ = find_peaks(shift_, height=0.5)\n peaks = find_peaks_cwt(shift_, np.arange(1, 10))\n\n # turn peaks into differences between peaks\n diff = []\n for i in np.arange(len(peaks) - 1):\n diff.append(peaks[i + 1] - peaks[i])\n\n if len(diff) == 0: # can't find peaks\n first_period = 1 # need to check again this!\n else:\n # return the most distance between peaks -> that is period of data\n first_period = most_frequent(list(diff))\n\n if verbose:\n #print('Candidate periods:', set(diff))\n for eachdiff in diff:\n print(df_ts[feature].autocorr(lag=eachdiff), end='\\t')\n print()\n\n if (plot == True) & (verbose == True):\n plt.figure(figsize=(20, 3))\n sm.graphics.tsa.plot_acf(df_ts[feature].squeeze(),\n lags=int(first_period))\n\n # if period is too large\n if first_period > int(len(df_ts) / 2):\n if verbose:\n print('Frequency for Moving Average is over half size!')\n first_period = int(len(df_ts) / 2)\n\n # SEASONAL ANALYSIS\n\n if verbose:\n print('First period:', first_period)\n\n df_ts.index = pd.to_datetime(df_ts[time_feature],\n format='%Y-%m-%d %H:%M:%S')\n rolling_mean = df_ts[feature].rolling(window=int(first_period)).mean()\n \n exp1 = pd.Series(df_ts[feature].ewm(span=int(first_period),\n adjust=False).mean())\n \n exp1.index = pd.to_datetime(df_ts[time_feature],\n format='%Y-%m-%d %H:%M:%S')\n\n if (verbose == True) & (plot == True):\n df_ori = df_ts[[feature, time_feature]].copy()\n df_ori.set_index(time_feature, inplace=True)\n\n fig, ax = plt.subplots(figsize=(15, 4))\n\n df_ori.plot(ax=ax)\n exp1.plot(ax=ax)\n\n ax.legend([\n 'Original Series',\n 'Moving Average Series with P=%d' % first_period\n ])\n\n plt.show()\n\n # Using Moving Average\n result_add = seasonal_decompose(exp1,\n model='additive',\n extrapolate_trend='freq',\n freq=first_period)\n\n # Using STL\n # from statsmodels.tsa.seasonal import STL\n # stl = STL(exp1, period=first_period, robust=True)\n # result_add = stl.fit()\n\n # Only check the seasonal series to find again the best period\n arr_seasonal_ = pd.Series(result_add.seasonal + result_add.resid)\n\n # if seasonal is flat\n if np.all(np.isclose(arr_seasonal_, arr_seasonal_[0])):\n if verbose == True:\n print('Seasonal + Residual become flat')\n seasonal = False\n period = 1\n else:\n # if seasonal is not flat\n\n # Continue to use autocorrelation to find the period\n shift_ = []\n for i in np.arange(len(arr_seasonal_)):\n shift_.append(arr_seasonal_.autocorr(lag=i))\n\n shift_ = np.array(shift_)\n\n # Find peaks again for seasonal + residual\n peaks, _ = find_peaks(shift_, height=0.85, distance=7)\n # peaks = find_peaks_cwt(shift_,np.arange(1,10))\n\n # Looking for possible periods\n if len(peaks) < 2:\n if df_ts[feature].autocorr(lag=first_period) > 0.80:\n period = first_period\n seasonal = True\n else:\n period = 1\n seasonal = False\n result_add = None\n # result_add = seasonal_decompose(df_ts[feature], model='additive', extrapolate_trend='freq',freq=period)\n else:\n diff = []\n for i in np.arange(len(peaks)):\n if i + 1 < len(peaks):\n diff.append(peaks[i + 1] - peaks[i])\n\n if verbose:\n print('Candidate periods:', set(diff))\n for eachdiff in diff:\n print(df_ts[feature].autocorr(lag=eachdiff), end='\\t')\n print()\n\n if verbose:\n print('Peaks of autocorr:', diff)\n if 2 * most_frequent(list(diff)) > len(df_ts):\n seasonal = False\n period = 1\n result_add = None\n else:\n seasonal = True\n period = most_frequent(list(diff))\n\n if (plot == True) & (verbose == True):\n sm.graphics.tsa.plot_acf(exp1.squeeze(), lags=int(period) * 2)\n plt.show()\n\n # Final Decomposition\n\n result_add = seasonal_decompose(df_ts[feature],\n model='additive',\n extrapolate_trend='freq',\n freq=period)\n\n # plot results of decomposition\n if plot:\n plt.rcParams.update({'figure.figsize': (10, 10)})\n result_add.plot()\n plt.show()\n\n plt.figure(figsize=(20, 3))\n plt.plot(df_ts[feature].values, label=\"Timeseries\")\n plt.axvline(x=0, color='r', ls='--')\n plt.axvline(x=period, color='r', ls='--')\n plt.grid(True)\n plt.axis('tight')\n plt.legend(loc=\"best\", fontsize=13)\n plt.show()\n\n continuous, discrete = identify_cont_disc(df_raw[[feature]])\n\n return stationary, seasonal, period, result_add, continuous, discrete",
"_____no_output_____"
]
],
[
[
"## Timeseries Analysis",
"_____no_output_____"
]
],
[
[
"df_weather=pd.read_csv(r'C:\\Users\\ahtis\\OneDrive\\Desktop\\ARIMA\\data\\data.csv')\ndf_weather = df_weather[1:60]\ndf_weather = df_weather.dropna()\n\nfeature_name = \"glucose\" \n\ndf_weather[\"Timestamp\"] = pd.to_datetime(df_weather[\"Timestamp\"], format='%Y-%m-%d %H:%M:%S', utc=True)\ndf_weather[\"Timestamp\"] = pd.DatetimeIndex(df_weather[\"Timestamp\"], tz='Europe/Berlin')\n\nTimestamp = df_weather.columns[0]\n\nstationary, seasonal, period, resultdfs, continuous, discrete = analysisPeriod(\n df_weather.head(2500),\n feature=feature_name,\n time_feature=Timestamp,\n plot=True,\n verbose=True)\n\nprint(\"Timeseries %s is Stationary? %s \" % (feature_name, stationary))\n\nprint(\"Timeseries %s is Seasonal? %s \" % (feature_name, seasonal))\n\nif seasonal and period > 1:\n print(\"Period for Timeseries %s = %s \" % (feature_name, period))\nif seasonal and period == 1:\n print(\"Period for Timeseries %s is not found\" % (feature_name, period))\n\nif continuous:\n print(\"Timeseries %s is Continuous\" % (feature_name))\nelse:\n print(\"Timeseries %s is Discrete\" % (feature_name))",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7899aff6de6b7e35ff419c83f1d4626cdce931d | 7,515 | ipynb | Jupyter Notebook | genome_designer/debug/make_new_refs_clean.ipynb | churchlab/millstone | ddb5d003a5b8a7675e5a56bafd5c432d9642b473 | [
"MIT"
] | 45 | 2015-09-30T14:55:33.000Z | 2021-06-28T02:33:30.000Z | genome_designer/debug/make_new_refs_clean.ipynb | churchlab/millstone | ddb5d003a5b8a7675e5a56bafd5c432d9642b473 | [
"MIT"
] | 261 | 2015-06-03T20:41:56.000Z | 2022-03-07T08:46:10.000Z | genome_designer/debug/make_new_refs_clean.ipynb | churchlab/millstone | ddb5d003a5b8a7675e5a56bafd5c432d9642b473 | [
"MIT"
] | 22 | 2015-06-04T20:43:10.000Z | 2022-02-27T08:27:34.000Z | 34.315068 | 132 | 0.539055 | [
[
[
"This notebook can be used to generate fake structural variant test data for testing the genome finishing module.\nGiven a source fasta, bam, and paired-end fastqs and insertion parameters, it creates a directory with the following files:\n\n ref.fa\n reads.1.fq\n reads.2.fq",
"_____no_output_____"
]
],
[
[
"import sys\n\nfrom django.core.management import setup_environ\nimport settings\n\nsetup_environ(settings)",
"_____no_output_____"
],
[
"import random\nimport re\nimport os\n\nfrom Bio import SeqIO\nimport pysam\n\nfrom genome_finish.millstone_de_novo_fns import get_avg_genome_coverage\n\n\n# def _make_fake_insertion(ref_endpoints, ins_endpoints):\n\nref_endpoints = (2930000, 2940000)\nins_endpoints = (2932000, 2933000)\ndesired_coverage = 40\noutput_no_insertion_ref = True\n\ntest_number = 6\n\n\ntemplate_dir = '/home/wahern/projects/millstone/genome_designer/test_data/genome_finish_test/mg1655_test/templates'\n\nsource_fasta = os.path.join(template_dir, 'mg1655.fa')\nsource_bam = os.path.join(template_dir, 'lib1_rec07.bwa_align.bam')\nsource_fq1 = os.path.join(template_dir, 'lib1_rec07.1.fq')\nsource_fq2 = os.path.join(template_dir, 'lib1_rec07.2.fq')\n\n\ntest_dir = '/home/wahern/projects/millstone/genome_designer/test_data/genome_finish_test/mg1655_test'\noutput_dir = os.path.join(test_dir, str(test_number))\n\noutput_fasta = os.path.join(output_dir, 'ref.fa')\noutput_fq1 = os.path.join(output_dir, 'reads.1.fq')\noutput_fq2 = os.path.join(output_dir, 'reads.2.fq')\n\nassert not os.path.exists(output_dir)\n\n# Get sample\nif desired_coverage:\n coverage = get_avg_genome_coverage(source_bam)\n if desired_coverage > coverage:\n raise Exception('Desired coverage:' + str(desired_coverage) +\n ' is greater than the genome\\'s average coverage of ' +\n str(coverage))\n \n read_sampling_fraction = desired_coverage / coverage\n \n linecount = 0\n with open(source_fq1) as fh:\n for line in fh:\n linecount+=1\n \n include_read = [random.random() < read_sampling_fraction for i in xrange(linecount)]\n \n \n\nos.mkdir(output_dir)\n\n# Get source seqrecord\nwith open(source_fasta, 'r') as source_fasta_fh:\n source_seqrecord = SeqIO.parse(source_fasta_fh, 'fasta').next()\n output_seqrecord = (\n source_seqrecord[ref_endpoints[0]:ins_endpoints[0]] +\n source_seqrecord[ins_endpoints[1]:ref_endpoints[1]]\n )\n\n# Sanity check\nassert len(output_seqrecord) == ref_endpoints[1] - ref_endpoints[0] - (\n ins_endpoints[1] - ins_endpoints[0])\n\n# Add some metadata to the header.\noutput_seqrecord.id = source_seqrecord.id\noutput_seqrecord.description = source_seqrecord.description + (\n ', FAKE_SHORT: ' +\n '{ref_endpoints:' + str(ref_endpoints) + ', ' +\n 'ins_endpoints:' + str(ins_endpoints) + '}')\n\n# Write output fasta\nwith open(output_fasta, 'w') as fh:\n SeqIO.write([output_seqrecord], fh, 'fasta')\n\n# Get reads in region\nqnames_in_region = {}\nsource_af = pysam.AlignmentFile(source_bam)\nfor read in source_af.fetch('NC_000913', ref_endpoints[0], ref_endpoints[1]):\n if (not read.is_unmapped and\n ref_endpoints[0] <= read.reference_start <= ref_endpoints[1] and\n ref_endpoints[0] <= read.reference_end <= ref_endpoints[1]):\n qnames_in_region[read.qname] = True\nsource_af.close()\n\n# Go through fastqs and write reads in ROI to file\np1 = re.compile('@(\\S+)')\nfor input_fq_path, output_fq_path in [(source_fq1, output_fq1), (source_fq2, output_fq2)]:\n counter = 0\n if desired_coverage:\n iterator = iter(include_read)\n with open(input_fq_path, 'r') as in_fh, open(output_fq_path, 'w') as out_fh:\n for line in in_fh:\n m1 = p1.match(line)\n if m1:\n qname = m1.group(1)\n if qname in qnames_in_region:\n if desired_coverage:\n if iterator.next():\n out_fh.write(line)\n out_fh.write(in_fh.next())\n out_fh.write(in_fh.next())\n out_fh.write(in_fh.next())\n else:\n out_fh.write(line)\n out_fh.write(in_fh.next())\n out_fh.write(in_fh.next())\n out_fh.write(in_fh.next())\n \n\nif output_no_insertion_ref:\n # Get source seqrecord\n with open(source_fasta, 'r') as source_fasta_fh:\n source_seqrecord = SeqIO.parse(source_fasta_fh, 'fasta').next()\n output_seqrecord = (\n source_seqrecord[ref_endpoints[0]:ref_endpoints[1]]\n )\n\n # Add some metadata to the header.\n output_seqrecord.id = source_seqrecord.id\n output_seqrecord.description = source_seqrecord.description + (\n ', FAKE_SHORT: ' +\n '{ref_endpoints:' + str(ref_endpoints) + ', ' +\n 'ins_endpoints:None}')\n\n # Write output fasta\n no_ins_fasta = os.path.join(output_dir, 'no_ins_ref.fa')\n with open(no_ins_fasta, 'w') as fh:\n SeqIO.write([output_seqrecord], fh, 'fasta')\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
]
] |
e7899f69eb78cf9a936f8a12cf08979537c1925f | 204,573 | ipynb | Jupyter Notebook | code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb | proTao/LearningBayes | 2086f09013ab7e8a8f7cc330b93ef3a70c63d91a | [
"MIT"
] | null | null | null | code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb | proTao/LearningBayes | 2086f09013ab7e8a8f7cc330b93ef3a70c63d91a | [
"MIT"
] | null | null | null | code/.ipynb_checkpoints/chap05soln-checkpoint.ipynb | proTao/LearningBayes | 2086f09013ab7e8a8f7cc330b93ef3a70c63d91a | [
"MIT"
] | null | null | null | 120.977528 | 26,712 | 0.870745 | [
[
[
"# Think Bayes: Chapter 5\n\nThis notebook presents code and exercises from Think Bayes, second edition.\n\nCopyright 2016 Allen B. Downey\n\nMIT License: https://opensource.org/licenses/MIT",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function, division\n\n% matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\n\nfrom thinkbayes2 import Pmf, Cdf, Suite, Beta\nimport thinkplot",
"_____no_output_____"
]
],
[
[
"## Odds\n\nThe following function converts from probabilities to odds.",
"_____no_output_____"
]
],
[
[
"def Odds(p):\n return p / (1-p)",
"_____no_output_____"
]
],
[
[
"And this function converts from odds to probabilities.",
"_____no_output_____"
]
],
[
[
"def Probability(o):\n return o / (o+1)",
"_____no_output_____"
]
],
[
[
"If 20% of bettors think my horse will win, that corresponds to odds of 1:4, or 0.25.",
"_____no_output_____"
]
],
[
[
"p = 0.2\nOdds(p)",
"_____no_output_____"
]
],
[
[
"If the odds against my horse are 1:5, that corresponds to a probability of 1/6.",
"_____no_output_____"
]
],
[
[
"o = 1/5\nProbability(o)",
"_____no_output_____"
]
],
[
[
"We can use the odds form of Bayes's theorem to solve the cookie problem:",
"_____no_output_____"
]
],
[
[
"prior_odds = 1\nlikelihood_ratio = 0.75 / 0.5\npost_odds = prior_odds * likelihood_ratio\npost_odds",
"_____no_output_____"
]
],
[
[
"And then we can compute the posterior probability, if desired.",
"_____no_output_____"
]
],
[
[
"post_prob = Probability(post_odds)\npost_prob",
"_____no_output_____"
]
],
[
[
"If we draw another cookie and it's chocolate, we can do another update:",
"_____no_output_____"
]
],
[
[
"likelihood_ratio = 0.25 / 0.5\npost_odds *= likelihood_ratio\npost_odds",
"_____no_output_____"
]
],
[
[
"And convert back to probability.",
"_____no_output_____"
]
],
[
[
"post_prob = Probability(post_odds)\npost_prob",
"_____no_output_____"
]
],
[
[
"## Oliver's blood\n\nThe likelihood ratio is also useful for talking about the strength of evidence without getting bogged down talking about priors.\n\nAs an example, we'll solve this problem from MacKay's {\\it Information Theory, Inference, and Learning Algorithms}:\n\n> Two people have left traces of their own blood at the scene of a crime. A suspect, Oliver, is tested and found to have type 'O' blood. The blood groups of the two traces are found to be of type 'O' (a common type in the local population, having frequency 60) and of type 'AB' (a rare type, with frequency 1). Do these data [the traces found at the scene] give evidence in favor of the proposition that Oliver was one of the people [who left blood at the scene]?\n\nIf Oliver is\none of the people who left blood at the crime scene, then he\naccounts for the 'O' sample, so the probability of the data\nis just the probability that a random member of the population\nhas type 'AB' blood, which is 1%.\n\nIf Oliver did not leave blood at the scene, then we have two\nsamples to account for. If we choose two random people from\nthe population, what is the chance of finding one with type 'O'\nand one with type 'AB'? Well, there are two ways it might happen:\nthe first person we choose might have type 'O' and the second\n'AB', or the other way around. So the total probability is\n$2 (0.6) (0.01) = 1.2$%.\n\nSo the likelihood ratio is:",
"_____no_output_____"
]
],
[
[
"like1 = 0.01\nlike2 = 2 * 0.6 * 0.01\n\nlikelihood_ratio = like1 / like2\nlikelihood_ratio",
"_____no_output_____"
]
],
[
[
"Since the ratio is less than 1, it is evidence *against* the hypothesis that Oliver left blood at the scence.\n\nBut it is weak evidence. For example, if the prior odds were 1 (that is, 50% probability), the posterior odds would be 0.83, which corresponds to a probability of:",
"_____no_output_____"
]
],
[
[
"post_odds = 1 * like1 / like2\nProbability(post_odds)",
"_____no_output_____"
]
],
[
[
"So this evidence doesn't \"move the needle\" very much.",
"_____no_output_____"
],
[
"**Exercise:** Suppose other evidence had made you 90% confident of Oliver's guilt. How much would this exculpatory evince change your beliefs? What if you initially thought there was only a 10% chance of his guilt?\n\nNotice that evidence with the same strength has a different effect on probability, depending on where you started.",
"_____no_output_____"
]
],
[
[
"# Solution\n\npost_odds = Odds(0.9) * like1 / like2\nProbability(post_odds)",
"_____no_output_____"
],
[
"# Solution\n\npost_odds = Odds(0.1) * like1 / like2\nProbability(post_odds)",
"_____no_output_____"
]
],
[
[
"## Comparing distributions\n\nLet's get back to the Kim Rhode problem from Chapter 4:\n\n> At the 2016 Summer Olympics in the Women's Skeet event, Kim Rhode faced Wei Meng in the bronze medal match. They each hit 15 of 25 targets, sending the match into sudden death. In the first round, both hit 1 of 2 targets. In the next two rounds, they each hit 2 targets. Finally, in the fourth round, Rhode hit 2 and Wei hit 1, so Rhode won the bronze medal, making her the first Summer Olympian to win an individual medal at six consecutive summer games.\n\n>But after all that shooting, what is the probability that Rhode is actually a better shooter than Wei? If the same match were held again, what is the probability that Rhode would win?\n\nI'll start with a uniform distribution for `x`, the probability of hitting a target, but we should check whether the results are sensitive to that choice.\n\nFirst I create a Beta distribution for each of the competitors, and update it with the results.",
"_____no_output_____"
]
],
[
[
"rhode = Beta(1, 1, label='Rhode')\nrhode.Update((22, 11))",
"_____no_output_____"
],
[
"wei = Beta(1, 1, label='Wei')\nwei.Update((21, 12))",
"_____no_output_____"
]
],
[
[
"Based on the data, the distribution for Rhode is slightly farther right than the distribution for Wei, but there is a lot of overlap.",
"_____no_output_____"
]
],
[
[
"thinkplot.Pdf(rhode.MakePmf())\nthinkplot.Pdf(wei.MakePmf())\nthinkplot.Config(xlabel='x', ylabel='Probability')",
"_____no_output_____"
]
],
[
[
"To compute the probability that Rhode actually has a higher value of `p`, there are two options:\n\n1. Sampling: we could draw random samples from the posterior distributions and compare them.\n\n2. Enumeration: we could enumerate all possible pairs of values and add up the \"probability of superiority\".\n\nI'll start with sampling. The Beta object provides a method that draws a random value from a Beta distribution:",
"_____no_output_____"
]
],
[
[
"iters = 1000\ncount = 0\nfor _ in range(iters):\n x1 = rhode.Random()\n x2 = wei.Random()\n if x1 > x2:\n count += 1\n\ncount / iters",
"_____no_output_____"
]
],
[
[
"`Beta` also provides `Sample`, which returns a NumPy array, so we an perform the comparisons using array operations:",
"_____no_output_____"
]
],
[
[
"rhode_sample = rhode.Sample(iters)\nwei_sample = wei.Sample(iters)\nnp.mean(rhode_sample > wei_sample)",
"_____no_output_____"
]
],
[
[
"The other option is to make `Pmf` objects that approximate the Beta distributions, and enumerate pairs of values:",
"_____no_output_____"
]
],
[
[
"def ProbGreater(pmf1, pmf2):\n total = 0\n for x1, prob1 in pmf1.Items():\n for x2, prob2 in pmf2.Items():\n if x1 > x2:\n total += prob1 * prob2\n return total",
"_____no_output_____"
],
[
"pmf1 = rhode.MakePmf(1001)\npmf2 = wei.MakePmf(1001)\nProbGreater(pmf1, pmf2)",
"_____no_output_____"
],
[
"pmf1.ProbGreater(pmf2)",
"_____no_output_____"
],
[
"pmf1.ProbLess(pmf2)",
"_____no_output_____"
]
],
[
[
"**Exercise:** Run this analysis again with a different prior and see how much effect it has on the results.",
"_____no_output_____"
],
[
"## Simulation\n\nTo make predictions about a rematch, we have two options again:\n\n1. Sampling. For each simulated match, we draw a random value of `x` for each contestant, then simulate 25 shots and count hits.\n\n2. Computing a mixture. If we knew `x` exactly, the distribution of hits, `k`, would be binomial. Since we don't know `x`, the distribution of `k` is a mixture of binomials with different values of `x`.\n\nI'll do it by sampling first.",
"_____no_output_____"
]
],
[
[
"import random\n\ndef flip(p):\n return random.random() < p",
"_____no_output_____"
]
],
[
[
"`flip` returns True with probability `p` and False with probability `1-p`\n\nNow we can simulate 1000 rematches and count wins and losses.",
"_____no_output_____"
]
],
[
[
"iters = 1000\nwins = 0\nlosses = 0\n\nfor _ in range(iters):\n x1 = rhode.Random()\n x2 = wei.Random()\n \n count1 = count2 = 0\n for _ in range(25):\n if flip(x1):\n count1 += 1\n if flip(x2):\n count2 += 1\n \n if count1 > count2:\n wins += 1\n if count1 < count2:\n losses += 1\n \nwins/iters, losses/iters",
"_____no_output_____"
]
],
[
[
"Or, realizing that the distribution of `k` is binomial, we can simplify the code using NumPy:",
"_____no_output_____"
]
],
[
[
"rhode_rematch = np.random.binomial(25, rhode_sample)\nthinkplot.Hist(Pmf(rhode_rematch))",
"_____no_output_____"
],
[
"wei_rematch = np.random.binomial(25, wei_sample)\nnp.mean(rhode_rematch > wei_rematch)",
"_____no_output_____"
],
[
"np.mean(rhode_rematch < wei_rematch)",
"_____no_output_____"
]
],
[
[
"Alternatively, we can make a mixture that represents the distribution of `k`, taking into account our uncertainty about `x`:",
"_____no_output_____"
]
],
[
[
"from thinkbayes2 import MakeBinomialPmf\n\ndef MakeBinomialMix(pmf, label=''):\n mix = Pmf(label=label)\n for x, prob in pmf.Items():\n binom = MakeBinomialPmf(n=25, p=x)\n for k, p in binom.Items():\n mix[k] += prob * p\n return mix",
"_____no_output_____"
],
[
"rhode_rematch = MakeBinomialMix(rhode.MakePmf(), label='Rhode')\nwei_rematch = MakeBinomialMix(wei.MakePmf(), label='Wei')\nthinkplot.Pdf(rhode_rematch)\nthinkplot.Pdf(wei_rematch)\nthinkplot.Config(xlabel='hits')",
"_____no_output_____"
],
[
"rhode_rematch.ProbGreater(wei_rematch), rhode_rematch.ProbLess(wei_rematch)",
"_____no_output_____"
]
],
[
[
"Alternatively, we could use MakeMixture:",
"_____no_output_____"
]
],
[
[
"from thinkbayes2 import MakeMixture\n\ndef MakeBinomialMix2(pmf):\n binomials = Pmf()\n for x, prob in pmf.Items():\n binom = MakeBinomialPmf(n=25, p=x)\n binomials[binom] = prob\n return MakeMixture(binomials)",
"_____no_output_____"
]
],
[
[
"Here's how we use it.",
"_____no_output_____"
]
],
[
[
"rhode_rematch = MakeBinomialMix2(rhode.MakePmf())\nwei_rematch = MakeBinomialMix2(wei.MakePmf())\nrhode_rematch.ProbGreater(wei_rematch), rhode_rematch.ProbLess(wei_rematch)",
"_____no_output_____"
]
],
[
[
"**Exercise:** Run this analysis again with a different prior and see how much effect it has on the results.",
"_____no_output_____"
],
[
"## Distributions of sums and differences\n\nSuppose we want to know the total number of targets the two contestants will hit in a rematch. There are two ways we might compute the distribution of this sum:\n\n1. Sampling: We can draw samples from the distributions and add them up.\n\n2. Enumeration: We can enumerate all possible pairs of values.\n\nI'll start with sampling:",
"_____no_output_____"
]
],
[
[
"iters = 1000\npmf = Pmf()\nfor _ in range(iters):\n k = rhode_rematch.Random() + wei_rematch.Random()\n pmf[k] += 1\npmf.Normalize()\nthinkplot.Hist(pmf)",
"_____no_output_____"
]
],
[
[
"Or we could use `Sample` and NumPy:",
"_____no_output_____"
]
],
[
[
"ks = rhode_rematch.Sample(iters) + wei_rematch.Sample(iters)\npmf = Pmf(ks)\nthinkplot.Hist(pmf)",
"_____no_output_____"
]
],
[
[
"Alternatively, we could compute the distribution of the sum by enumeration:",
"_____no_output_____"
]
],
[
[
"def AddPmfs(pmf1, pmf2):\n pmf = Pmf()\n for v1, p1 in pmf1.Items():\n for v2, p2 in pmf2.Items():\n pmf[v1 + v2] += p1 * p2\n return pmf",
"_____no_output_____"
]
],
[
[
"Here's how it's used:",
"_____no_output_____"
]
],
[
[
"pmf = AddPmfs(rhode_rematch, wei_rematch)\nthinkplot.Pdf(pmf)",
"_____no_output_____"
]
],
[
[
"The `Pmf` class provides a `+` operator that does the same thing.",
"_____no_output_____"
]
],
[
[
"pmf = rhode_rematch + wei_rematch\nthinkplot.Pdf(pmf)",
"_____no_output_____"
]
],
[
[
"**Exercise:** The Pmf class also provides the `-` operator, which computes the distribution of the difference in values from two distributions. Use the distributions from the previous section to compute the distribution of the differential between Rhode and Wei in a rematch. On average, how many clays should we expect Rhode to win by? What is the probability that Rhode wins by 10 or more?",
"_____no_output_____"
]
],
[
[
"# Solution\n\npmf = rhode_rematch - wei_rematch\nthinkplot.Pdf(pmf)",
"_____no_output_____"
],
[
"# Solution\n\n# On average, we expect Rhode to win by about 1 clay.\n\npmf.Mean(), pmf.Median(), pmf.Mode()",
"_____no_output_____"
],
[
"# Solution\n\n# But there is, according to this model, a 2% chance that she could win by 10.\n\nsum([p for (x, p) in pmf.Items() if x >= 10])",
"_____no_output_____"
]
],
[
[
"## Distribution of maximum\n\nSuppose Kim Rhode continues to compete in six more Olympics. What should we expect her best result to be?\n\nOnce again, there are two ways we can compute the distribution of the maximum:\n\n1. Sampling.\n\n2. Analysis of the CDF.\n\nHere's a simple version by sampling:",
"_____no_output_____"
]
],
[
[
"iters = 1000\npmf = Pmf()\nfor _ in range(iters):\n ks = rhode_rematch.Sample(6)\n pmf[max(ks)] += 1\npmf.Normalize()\nthinkplot.Hist(pmf)",
"_____no_output_____"
]
],
[
[
"And here's a version using NumPy. I'll generate an array with 6 rows and 10 columns:",
"_____no_output_____"
]
],
[
[
"iters = 1000\nks = rhode_rematch.Sample((6, iters))\nks",
"_____no_output_____"
]
],
[
[
"Compute the maximum in each column:",
"_____no_output_____"
]
],
[
[
"maxes = np.max(ks, axis=0)\nmaxes[:10]",
"_____no_output_____"
]
],
[
[
"And then plot the distribution of maximums:",
"_____no_output_____"
]
],
[
[
"pmf = Pmf(maxes)\nthinkplot.Hist(pmf)",
"_____no_output_____"
]
],
[
[
"Or we can figure it out analytically. If the maximum is less-than-or-equal-to some value `k`, all 6 random selections must be less-than-or-equal-to `k`, so: \n\n$ CDF_{max}(x) = CDF(x)^6 $\n\n`Pmf` provides a method that computes and returns this `Cdf`, so we can compute the distribution of the maximum like this:",
"_____no_output_____"
]
],
[
[
"pmf = rhode_rematch.Max(6).MakePmf()\nthinkplot.Hist(pmf)",
"_____no_output_____"
]
],
[
[
"**Exercise:** Here's how Pmf.Max works:\n\n def Max(self, k):\n \"\"\"Computes the CDF of the maximum of k selections from this dist.\n\n k: int\n\n returns: new Cdf\n \"\"\"\n cdf = self.MakeCdf()\n cdf.ps **= k\n return cdf\n\nWrite a function that takes a Pmf and an integer `n` and returns a Pmf that represents the distribution of the minimum of `k` values drawn from the given Pmf. Use your function to compute the distribution of the minimum score Kim Rhode would be expected to shoot in six competitions.",
"_____no_output_____"
]
],
[
[
"def Min(pmf, k):\n cdf = pmf.MakeCdf()\n cdf.ps = 1 - (1-cdf.ps)**k\n return cdf",
"_____no_output_____"
],
[
"pmf = Min(rhode_rematch, 6).MakePmf()\nthinkplot.Hist(pmf)",
"_____no_output_____"
]
],
[
[
"## Exercises",
"_____no_output_____"
],
[
"**Exercise:** Suppose you are having a dinner party with 10 guests and 4 of them are allergic to cats. Because you have cats, you expect 50% of the allergic guests to sneeze during dinner. At the same time, you expect 10% of the non-allergic guests to sneeze. What is the distribution of the total number of guests who sneeze?",
"_____no_output_____"
]
],
[
[
"# Solution\n\nn_allergic = 4\nn_non = 6\np_allergic = 0.5\np_non = 0.1\npmf = MakeBinomialPmf(n_allergic, p_allergic) + MakeBinomialPmf(n_non, p_non)\nthinkplot.Hist(pmf)",
"_____no_output_____"
],
[
"# Solution\n\npmf.Mean()",
"_____no_output_____"
]
],
[
[
"**Exercise** [This study from 2015](http://onlinelibrary.wiley.com/doi/10.1111/apt.13372/full) showed that many subjects diagnosed with non-celiac gluten sensitivity (NCGS) were not able to distinguish gluten flour from non-gluten flour in a blind challenge.\n\nHere is a description of the study:\n\n>\"We studied 35 non-CD subjects (31 females) that were on a gluten-free diet (GFD), in a double-blind challenge study. Participants were randomised to receive either gluten-containing flour or gluten-free flour for 10 days, followed by a 2-week washout period and were then crossed over. The main outcome measure was their ability to identify which flour contained gluten.\n>\"The gluten-containing flour was correctly identified by 12 participants (34%)...\"\nSince 12 out of 35 participants were able to identify the gluten flour, the authors conclude \"Double-blind gluten challenge induces symptom recurrence in just one-third of patients fulfilling the clinical diagnostic criteria for non-coeliac gluten sensitivity.\"\n\nThis conclusion seems odd to me, because if none of the patients were sensitive to gluten, we would expect some of them to identify the gluten flour by chance. So the results are consistent with the hypothesis that none of the subjects are actually gluten sensitive.\n\nWe can use a Bayesian approach to interpret the results more precisely. But first we have to make some modeling decisions.\n\n1. Of the 35 subjects, 12 identified the gluten flour based on resumption of symptoms while they were eating it. Another 17 subjects wrongly identified the gluten-free flour based on their symptoms, and 6 subjects were unable to distinguish. So each subject gave one of three responses. To keep things simple I follow the authors of the study and lump together the second two groups; that is, I consider two groups: those who identified the gluten flour and those who did not.\n\n2. I assume (1) people who are actually gluten sensitive have a 95% chance of correctly identifying gluten flour under the challenge conditions, and (2) subjects who are not gluten sensitive have only a 40% chance of identifying the gluten flour by chance (and a 60% chance of either choosing the other flour or failing to distinguish).\n\nUsing this model, estimate the number of study participants who are sensitive to gluten. What is the most likely number? What is the 95% credible interval?",
"_____no_output_____"
]
],
[
[
"# Solution\n\n# Here's a class that models the study\n\nclass Gluten(Suite):\n \n def Likelihood(self, data, hypo):\n \"\"\"Computes the probability of the data under the hypothesis.\n \n data: tuple of (number who identified, number who did not)\n hypothesis: number of participants who are gluten sensitive\n \"\"\"\n # compute the number who are gluten sensitive, `gs`, and\n # the number who are not, `ngs`\n gs = hypo\n yes, no = data\n n = yes + no\n ngs = n - gs\n \n pmf1 = MakeBinomialPmf(gs, 0.95)\n pmf2 = MakeBinomialPmf(ngs, 0.4)\n pmf = pmf1 + pmf2\n return pmf[yes]",
"_____no_output_____"
],
[
"# Solution\n\nprior = Gluten(range(0, 35+1))\nthinkplot.Pdf(prior)",
"_____no_output_____"
],
[
"# Solution\n\nposterior = prior.Copy()\ndata = 12, 23\nposterior.Update(data)",
"_____no_output_____"
],
[
"# Solution\n\nthinkplot.Pdf(posterior)\nthinkplot.Config(xlabel='# who are gluten sensitive', \n ylabel='PMF', legend=False)",
"_____no_output_____"
],
[
"# Solution\n\nposterior.CredibleInterval(95)",
"_____no_output_____"
]
],
[
[
"**Exercise** Coming soon: the space invaders problem.",
"_____no_output_____"
]
],
[
[
"# Solution\n\n",
"_____no_output_____"
],
[
"# Solution\n \n",
"_____no_output_____"
],
[
"# Solution\n \n",
"_____no_output_____"
],
[
"# Solution\n \n",
"_____no_output_____"
],
[
"# Solution\n \n",
"_____no_output_____"
],
[
"# Solution\n \n",
"_____no_output_____"
],
[
"# Solution\n \n",
"_____no_output_____"
],
[
"# Solution\n \n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e789ac46a4b8d8bad6ea86ed939d32177c8dea8d | 26,680 | ipynb | Jupyter Notebook | disl4.ipynb | iamareebjamal/matlab-to-python | 1efad54b38f881e6a3c1e9f70a298e00ffbecfe2 | [
"MIT"
] | 1 | 2019-11-13T20:49:35.000Z | 2019-11-13T20:49:35.000Z | disl4.ipynb | iamareebjamal/matlab-to-python | 1efad54b38f881e6a3c1e9f70a298e00ffbecfe2 | [
"MIT"
] | null | null | null | disl4.ipynb | iamareebjamal/matlab-to-python | 1efad54b38f881e6a3c1e9f70a298e00ffbecfe2 | [
"MIT"
] | null | null | null | 242.545455 | 21,828 | 0.923051 | [
[
[
"import numpy as np\nfrom sympy import *\nimport matplotlib.pyplot as plt\n\nx = symbols('x')\ninit_printing(use_unicode=True)\n\nx_range = np.arange(0.001, 0.8, 0.05)\n\ndef compute(factor):\n xi = []\n c1 = 1./6\n c2 = factor*c1\n eqs = []\n for phi in x_range:\n c1a= (4.073*np.sqrt(c1)+1.053*c2)*0.5*(3*np.cos(1.5*phi)+np.cos(0.5*phi))\n c2a= 5.28*c2*np.sin(phi)*np.cos(phi)\n eq = c1a*x**(1.5)-x-c2a\n eqs.append(eq)\n # solx = solve(eq, x)\n # xi.append(solx[0])\n xi = [solve(eq, x) for eq in eqs]\n return xi\n\nfactors = (1./50, 1./10, 1, 5)\n\n# plt.ion()\n\nfor factor in factors:\n plt.plot(x_range, compute(factor))\n # plt.pause(0.01)\n\n# plt.ioff()\nplt.show()\n",
"30\n"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e789ace672effa4161c4ad11a53610e3789b6641 | 20,335 | ipynb | Jupyter Notebook | 2021 Весенний семестр/Практическое задание 2/Макаров Степан task2.ipynb | mosalov/Notebook_For_AI_Main | a693d29bf0bdcf824cb4f1eca86ff54b67ba7428 | [
"MIT"
] | 6 | 2021-09-20T10:28:18.000Z | 2022-03-14T18:39:17.000Z | 2021 Весенний семестр/Практическое задание 2/Макаров Степан task2.ipynb | mosalov/Notebook_For_AI_Main | a693d29bf0bdcf824cb4f1eca86ff54b67ba7428 | [
"MIT"
] | 122 | 2020-09-07T11:57:57.000Z | 2022-03-22T06:47:03.000Z | 2021 Весенний семестр/Практическое задание 2/Макаров Степан task2.ipynb | mosalov/Notebook_For_AI_Main | a693d29bf0bdcf824cb4f1eca86ff54b67ba7428 | [
"MIT"
] | 97 | 2020-09-07T11:32:19.000Z | 2022-03-31T10:27:38.000Z | 20,335 | 20,335 | 0.600295 | [
[
[
"# Зависимости\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.compose import ColumnTransformer\n\nfrom sklearn.svm import SVR, SVC\n\nfrom sklearn.metrics import mean_squared_error, f1_score",
"_____no_output_____"
],
[
"# Генерируем уникальный seed\nmy_code = \"Makarov\"\nseed_limit = 2 ** 32\nmy_seed = int.from_bytes(my_code.encode(), \"little\") % seed_limit\nprint(my_seed)",
"1634427213\n"
],
[
"# Читаем данные из файла\nexample_data = pd.read_csv(\"datasets/Fish.csv\")",
"_____no_output_____"
],
[
"example_data.head()",
"_____no_output_____"
],
[
"# Определим размер валидационной и тестовой выборок\nval_test_size = round(0.2*len(example_data))\nprint(val_test_size)",
"32\n"
],
[
"# Создадим обучающую, валидационную и тестовую выборки\nrandom_state = my_seed\ntrain_val, test = train_test_split(example_data, test_size=val_test_size, random_state=random_state)\ntrain, val = train_test_split(train_val, test_size=val_test_size, random_state=random_state)\nprint(len(train), len(val), len(test))",
"95 32 32\n"
],
[
"# Значения в числовых столбцах преобразуем к отрезку [0,1].\n# Для настройки скалировщика используем только обучающую выборку.\nnum_columns = ['Weight', 'Length1', 'Length2', 'Length3', 'Height', 'Width']\n\nct = ColumnTransformer(transformers=[('numerical', MinMaxScaler(), num_columns)], remainder='passthrough')\nct.fit(train)",
"_____no_output_____"
],
[
"# Преобразуем значения, тип данных приводим к DataFrame\nsc_train = pd.DataFrame(ct.transform(train))\nsc_test = pd.DataFrame(ct.transform(test))\nsc_val = pd.DataFrame(ct.transform(val))",
"_____no_output_____"
],
[
"# Устанавливаем названия столбцов\ncolumn_names = num_columns + ['Species']\nsc_train.columns = column_names\nsc_test.columns = column_names\nsc_val.columns = column_names",
"_____no_output_____"
],
[
"sc_train",
"_____no_output_____"
],
[
"# Задание №1 - анализ метода опорных векторов в задаче регрессии\n# https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html#sklearn.svm.SVR\n# kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'}, default='rbf'\n# Только для kernel = 'poly' : degreeint, default=3",
"_____no_output_____"
],
[
"# Выбираем 4 числовых переменных, три их них будут предикторами, одна - зависимой переменной\nn = 4\nlabels = random.sample(num_columns, n)\n\ny_label = labels[0]\nx_labels = labels[1:]\n\nprint(x_labels)\nprint(y_label)",
"['Height', 'Width', 'Weight']\nLength3\n"
],
[
"# Отберем необходимые параметры\nx_train = sc_train[x_labels]\nx_test = sc_test[x_labels]\nx_val = sc_val[x_labels]\n\ny_train = sc_train[y_label]\ny_test = sc_test[y_label]\ny_val = sc_val[y_label]",
"_____no_output_____"
],
[
"x_train",
"_____no_output_____"
],
[
"# Создайте 4 модели с различными ядрами: 'linear', 'poly', 'rbf', 'sigmoid'.\n# Решите получившуюся задачу регрессии с помощью созданных моделей и сравните их эффективность.\n# При необходимости применяйте параметр регуляризации C : float, default=1.0\nr_model_1 = SVR( kernel='linear', C=0.8)\nr_model_2 = SVR(kernel='poly', degree=3, C=1.0)\nr_model_3 = SVR(kernel='rbf', C=1.0)\nr_model_4 = SVR(kernel='sigmoid', C=0.6)",
"_____no_output_____"
],
[
"r_models = []\nr_models.append(r_model_1)\nr_models.append(r_model_2)\nr_models.append(r_model_3)\nr_models.append(r_model_4)",
"_____no_output_____"
],
[
"for model in r_models:\n model.fit(x_train, y_train)",
"_____no_output_____"
],
[
"mses = []\nfor model in r_models:\n val_pred = model.predict(x_val)\n mse = mean_squared_error(y_val, val_pred)\n mses.append(mse)\n print(mse)",
"0.005749571780574723\n0.02054829425176104\n0.003925875626006053\n5.026384455714856\n"
],
[
"i_min = mses.index(min(mses))\nbest_r_model = r_models[i_min]\nbest_r_model.get_params()",
"_____no_output_____"
],
[
"# Вычислим ошибку лучшей модели на тестовой выборке.\ntest_pred = best_r_model.predict(x_test)\nmse = mean_squared_error(y_test, test_pred)\nprint(mse)",
"0.00494460475394044\n"
],
[
"# Задание №2 - анализ метода опорных векторов в задаче классификации\n# https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC\n# kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'}, default='rbf'\n# Только для kernel = 'poly' : degreeint, default=3",
"_____no_output_____"
],
[
"# Выбираем 2 числовых переменных, которые будут параметрами элементов набора данных\n# Метка класса всегда 'Species'\nn = 2\nx_labels = random.sample(num_columns, n)\ny_label = 'Species'\n\nprint(x_labels)\nprint(y_label)",
"['Height', 'Length2']\nSpecies\n"
],
[
"# Отберем необходимые параметры\nx_train = sc_train[x_labels]\nx_test = sc_test[x_labels]\nx_val = sc_val[x_labels]\n\ny_train = sc_train[y_label]\ny_test = sc_test[y_label]\ny_val = sc_val[y_label]",
"_____no_output_____"
],
[
"x_train",
"_____no_output_____"
],
[
"# Создайте 4 модели с различными ядрами: 'linear', 'poly', 'rbf', 'sigmoid'.\n# Решите получившуюся задачу регрессии с помощью созданных моделей и сравните их эффективность.\n# При необходимости применяйте параметр регуляризации C : float, default=1.0\n# Укажите, какая модель решает задачу лучше других.\nc_model_1 = SVC(kernel='linear', C=0.8)\nc_model_2 = SVC(kernel='poly', degree=3, C=1.0)\nc_model_3 = SVC(kernel='rbf', C=1.0)\nc_model_4 = SVC(kernel='sigmoid', C=0.6)",
"_____no_output_____"
],
[
"c_models = []\nc_models.append(c_model_1)\nc_models.append(c_model_2)\nc_models.append(c_model_3)\nc_models.append(c_model_4)",
"_____no_output_____"
],
[
"for model in c_models:\n model.fit(x_train, y_train)",
"_____no_output_____"
],
[
"f1s = []\nfor model in c_models:\n val_pred = model.predict(x_val)\n f1 = f1_score(y_val, val_pred, average='weighted')\n f1s.append(f1)\n print(f1)",
"0.3833333333333333\n0.7861842105263158\n0.7861842105263158\n0.12964527027027026\n"
],
[
"i_min = f1s.index(min(f1s))\nbest_c_model = c_models[i_min]\nbest_c_model.get_params()",
"_____no_output_____"
],
[
"# Вычислим ошибку лучшей модели на тестовой выборке.\ntest_pred = best_c_model.predict(x_test)\nf1 = f1_score(y_test, test_pred, average='weighted')\nprint(f1)",
"0.2467948717948718\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",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e789b20d63668db56bd32226d56250324b9d7b6f | 94,611 | ipynb | Jupyter Notebook | _notebooks/2020-11-25-8020-pandas.ipynb | mcb00/blog_bak | acdb82b8f44ae6cbdde9e536f420af7b4de4ecef | [
"Apache-2.0"
] | null | null | null | _notebooks/2020-11-25-8020-pandas.ipynb | mcb00/blog_bak | acdb82b8f44ae6cbdde9e536f420af7b4de4ecef | [
"Apache-2.0"
] | 2 | 2020-11-17T17:56:58.000Z | 2020-11-23T07:31:58.000Z | _notebooks/2020-11-25-8020-pandas.ipynb | mattcbowers/blog | acdb82b8f44ae6cbdde9e536f420af7b4de4ecef | [
"Apache-2.0"
] | null | null | null | 35.355381 | 475 | 0.360814 | [
[
[
"# 'The 80/20 Pandas Tutorial: 5 Key Methods for the Majority of Your Data Transformation Needs'\n> An opinionated pandas tutorial on my preferred methods to accomplish the most essential data transformation tasks in a way that will make veteran R and tidyverse users smile.\n\n- toc: false\n- badges: true\n- comments: true\n- categories: [pandas, tidyverse]\n- hide: false\n- image: images/80_20_pandas.png",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"Ahh, pandas. In addition to being everyone's favorite vegetarian bear from south central China, it's also _the_ python library for working with tabular data, a.k.a. dataframes.\nWhen you dive into pandas, you'll quickly find out that there is a lot going on; indeed there are [hundreds](https://pandas.pydata.org/docs/reference/frame.html) of methods for operating on dataframes. But luckily for us, as with many areas of life, there is a [Pareto Principle](https://en.wikipedia.org/wiki/Pareto_principle), or 80/20 rule, that will help us focus on the small set of methods that collectively solve the majority of our data transformation needs.\n\nIf you're like me, then pandas is not your first data-handling tool; maybe you've been using SQL or R with `data.table` or `dplyr`. If so, that's great because you already have a sense for the key operations we need when working with tabular data. \nIn their book, [R for Data Science](https://r4ds.had.co.nz/), Garrett Grolemund and Hadley Wickham describe five essential operations for manipulating dataframes. I've found that these cover the majority of my data transformation tasks to prepare data for analysis, visualization, and modeling.\n\n\n1. filtering rows based on data values\n2. sorting rows based on data values\n3. selecting columns by name\n4. adding new columns based on the existing columns\n5. creating grouped summaries of the dataset\n\nI would add that we also need a way to build up more complex transformations by chaining these fundamental operations together sequentially. \n\nBefore we dive in, here's the TLDR on the pandas methods that I prefer for accomplishing these tasks, along with their equivalents from SQL and `dplyr` in R.\n",
"_____no_output_____"
],
[
"| description | pandas | SQL | dplyr \n|-----------------------------------------------|--------------------| |-------------------------\n| filter rows based on data values | `query()` | `WHERE` | `filter()` \n| sort rows based on data values | `sort_values()` | `ORDER BY` | `arrange()` \n| select columns by name | `filter()` | `SELECT` | `select()` \n| add new columns based on the existing columns | `assign()` | `AS` | `mutate()` \n| create grouped summaries of the dataset | `groupby()` <br> `apply()` | `GROUP BY` | `group_by()` <br> `summarise()`\n| chain operations together | `.` | | `%>%` ",
"_____no_output_____"
],
[
"## Imports and Data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"We'll use the [nycflights13](https://github.com/hadley/nycflights13) dataset which contains data on the 336,776 flights that departed from New York City in 2013.",
"_____no_output_____"
]
],
[
[
"# pull some data into a pandas dataframe\nflights = pd.read_csv('https://www.openintro.org/book/statdata/nycflights.csv')\n\nflights.head()",
"_____no_output_____"
]
],
[
[
"## Select rows based on their values with `query()`",
"_____no_output_____"
],
[
"`query()` lets you retain a subset of rows based on the values of the data; it's like `dplyr::filter()` in R or `WHERE` in SQL.\nIts argument is a string specifying the condition to be met for rows to be included in the result.\nYou specify the condition as an expression involving the column names and comparison operators like `<`, `>`, `<=`, `>=`, `==` (equal), and `~=` (not equal). \nYou can specify compound expressions using `and` and `or`,\nand you can even check if the column value matches any items in a list.",
"_____no_output_____"
]
],
[
[
"#hide_output\n# compare one column to a value\nflights.query('month == 6')\n\n# compare two column values\nflights.query('arr_delay > dep_delay')\n\n# using arithmetic\nflights.query('arr_delay > 0.5 * air_time')\n\n# using \"and\"\nflights.query('month == 6 and day == 1')\n\n# using \"or\"\nflights.query('origin == \"JFK\" or dest == \"JFK\"')\n\n# column value matching any item in a list\nflights.query('carrier in [\"AA\", \"UA\"]')",
"_____no_output_____"
]
],
[
[
"You may have noticed that it seems to be much more popular to filter pandas data frames using boolean indexing.\nIndeed when I ask my favorite search engine how to filter a pandas dataframe on its values, I find\n[this tutorial](https://cmdlinetips.com/2018/02/how-to-subset-pandas-dataframe-based-on-values-of-a-column/),\n[this blog post](https://medium.com/swlh/3-ways-to-filter-pandas-dataframe-by-column-values-dfb6609b31de),\n[various](https://stackoverflow.com/questions/17071871/how-to-select-rows-from-a-dataframe-based-on-column-values)\n[questions](https://stackoverflow.com/questions/11869910/pandas-filter-rows-of-dataframe-with-operator-chaining)\non Stack Overflow,\nand even [the pandas documentation](https://pandas.pydata.org/pandas-docs/stable/getting_started/intro_tutorials/03_subset_data.html),\nall espousing boolean indexing.\nHere's what it looks like.",
"_____no_output_____"
]
],
[
[
"#hide_output\n# canonical boolean indexing\nflights[(flights['carrier'] == \"AA\") & (flights['origin'] == \"JFK\")]\n\n# the equivalent use of query()\nflights.query('carrier == \"AA\" and origin == \"JFK\"')",
"_____no_output_____"
]
],
[
[
"There are a few reasons I prefer `query()` over boolean indexing.\n\n1. `query()` does not require me to type the dataframe name again, whereas boolean indexing requires me to type it every time I wish to refer to a column.\n1. `query()` makes the code easier to read and understand, especially when expressions get complex.\n1. `query()` is [more computationally efficient](https://jakevdp.github.io/PythonDataScienceHandbook/03.12-performance-eval-and-query.html) than boolean indexing.\n1. `query()` can safely be used in dot chains, which we'll see very soon.",
"_____no_output_____"
],
[
"## Select columns by name with `filter()`",
"_____no_output_____"
],
[
"`filter()` lets you pick out a specific set of columns by name; it's analogous to `dplyr::select()` in R or `SELECT` in SQL.\nYou can either provide exactly the column names you want, or you can grab all columns whose names contain a given substring or which match a given regular expression. This isn't a big deal when your dataframe has only a few columns, but is particularly useful when you have a dataframe with tens or hundreds of columns.",
"_____no_output_____"
]
],
[
[
"#hide_output\n# select a list of columns\nflights.filter(['origin', 'dest'])\n\n# select columns containing a particular substring\nflights.filter(like='time')\n\n# select columns matching a regular expression\nflights.filter(regex='e$')",
"_____no_output_____"
]
],
[
[
"## Sort rows with `sort_values()`",
"_____no_output_____"
],
[
"`sort_values()` changes the order of the rows based on the data values; it's like`dplyr::arrange()` in R or `ORDER BY` in SQL.\nYou can specify one or more columns on which to sort, where their order denotes the sorting priority. \nYou can also specify whether to sort in ascending or descending order.",
"_____no_output_____"
]
],
[
[
"#hide_output\n# sort by a single column\nflights.sort_values('air_time')\n\n# sort by a single column in descending order\nflights.sort_values('air_time', ascending=False)\n\n# sort by carrier, then within carrier, sort by descending distance\nflights.sort_values(['carrier', 'distance'], ascending=[True, False])",
"_____no_output_____"
]
],
[
[
"## Add new columns with `assign()`",
"_____no_output_____"
],
[
"`assign()` adds new columns which can be functions of the existing columns; it's like `dplyr::mutate()` from R.",
"_____no_output_____"
]
],
[
[
"#hide_output\n# add a new column based on other columns\nflights.assign(speed = lambda x: x.distance / x.air_time)\n\n# another new column based on existing columns\nflights.assign(gain = lambda x: x.dep_delay - x.arr_delay)",
"_____no_output_____"
]
],
[
[
"If you're like me, this way of using `assign()` might seem a little strange at first.\nLet's break it down.\nIn the call to `assign()` the keyword argument `speed` tells pandas the name of our new column.\nThe business to the right of the `=` is a inline lambda function that takes the dataframe we passed to `assign()` and returns the column we want to add.\n\nI like using `x` as the lambda argument because its easy to type and it evokes tabular data (think [design matrix](https://en.wikipedia.org/wiki/Design_matrix)), which reminds me that it refers to the entire dataframe.\nWe can then access the other columns in our dataframe using the dot like `x.other_column`.",
"_____no_output_____"
],
[
"It's true that you can skip the whole lambda business and refer to the dataframe to which you are assigning directly inside the assign. That might look like this.",
"_____no_output_____"
],
[
"```\nflights.assign(speed = flights.distance / flights.air_time)\n```",
"_____no_output_____"
],
[
"I prefer using a lambda for the following reasons.\n\n1. If you gave your dataframe a good name, using the lambda will save you from typing the name every time you want to refer to a column.\n1. The lambda makes your code more portable. Since you refer to the dataframe as a generic `x`, you can reuse this same assignment code on a dataframe with a different name.\n1. Most importantly, the lambda will allow you to harness the power of dot chaining. ",
"_____no_output_____"
],
[
"## Chain transformations together with the dot chain",
"_____no_output_____"
],
[
"One of the awesome things about pandas is that the `object.method()` paradigm lets us easily build up complex dataframe transformations from a sequence of method calls.\nIn R, this is effectively accomplished by the pipe `%>%` operator.\nFor example, suppose we want to look at high-speed flights from JFK to Honolulu, which would require us to query for JFK to Honolulu flights, assign a speed column, and maybe sort on that new speed column.\n\nWe can say:",
"_____no_output_____"
]
],
[
[
"#hide_output\n# neatly chain method calls together\n(\n flights\n .query('origin == \"JFK\"')\n .query('dest == \"HNL\"')\n .assign(speed = lambda x: x.distance / x.air_time)\n .sort_values(by='speed', ascending=False)\n .query('speed > 8.0')\n)",
"_____no_output_____"
]
],
[
[
"We compose the dot chain by wrapping the entire expression in parentheses and indenting each line within.\nThe first line is the name of the dataframe on which we are operating.\nEach subsequent line has a single method call.\n\nThere are a few great things about writing the code this way:\n1. Readability. It's easy to scan down the left margin of the code to see what's happening. The first line gives us our noun (the dataframe) and each subsequent line starts with a verb. \nYou could read this as \"take `flights` then query the rows where origin is JFK, then query for rows where destination is HNL, then assign a new column called speed, then sort the dataframe by speed, then query only for the rows where speed is greater than 8.0.\n1. Flexibility - It's easy to comment out individual lines and re-run the cell. It's also easy to reorder operations, since only one thing happens on each line.\n1. Neatness - We have not polluted our workspace with any intermediate variables, nor have we wasted any mental energy thinking of names for any temporary variables.",
"_____no_output_____"
],
[
"By default, dot chains do not modify the original dataframe; they just output a temporary result that we can inspect directly in the output.\nIf you want to store the result, or pass it along to another function (e.g. for plotting), you can simply assign the entire dot chain to a variable.",
"_____no_output_____"
]
],
[
[
"#hide_output\n# sotre the output of the dot chain in a new dataframe\nflights_high_speed = (\n flights\n .assign(speed = lambda x: x.distance / x.air_time)\n .query('speed > 8.0')\n)",
"_____no_output_____"
]
],
[
[
"## Collapsing rows into grouped summaries with `groupby()`",
"_____no_output_____"
],
[
"`groupby()` combined with `apply()` gives us flexibility and control over our grouped summaries; it's like `dplyr::group_by()` and `dplyr::summarise()` in R.\nThis is the primary pattern I use for SQL-style groupby operations in pandas. Specifically it unlocks the following essential functionality you're used to having in SQL.\n1. specify the names of the aggregation columns we create\n1. specify which aggregation function to use on which columns\n1. compose more complex aggregations such as the proportion of rows meeting some condition\n1. aggregate over arbitrary functions of multiple columns\n\nLet's check out the departure delay stats for each carrier.",
"_____no_output_____"
]
],
[
[
"# grouped summary with groupby and apply\n(\n flights\n .groupby(['carrier'])\n .apply(lambda d: pd.Series({\n 'n_flights': len(d),\n 'med_delay': d.dep_delay.median(),\n 'avg_delay': d.dep_delay.mean(),\n }))\n .head()\n)",
"_____no_output_____"
]
],
[
[
"While you might be used to `apply()` acting over the rows or columns of a dataframe, here we're calling apply on a grouped dataframe object, so it's acting over the _groups_.\nAccording to the [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html):\n\n> The function passed to apply must take a dataframe as its first argument and return a dataframe, a series or a scalar. apply will then take care of combining the results back together into a single dataframe or series. apply is therefore a highly flexible grouping method.\n\nWe need to supply `apply()` with a function that takes each chunk of the grouped dataframe and returns (in our case) a series object with one element for each new aggregation column.\nNotice that I use a lambda to specify the function we pass to `apply())`, and that I name its argument `d`, \nwhich reminds me that it's a dataframe.\nMy lambda returns a pandas series whose index entries specify the new aggregation column names, and whose values constitute the results of the aggregations for each group.\nPandas will then stitch everything back together into a lovely dataframe.\n\nNotice how nice the code looks when we use this pattern. Each aggregation is specified on its own line, which makes it easy to see what aggregation columns we're creating and allows us to comment, uncomment, and reorder the aggregations without breaking anything.",
"_____no_output_____"
],
[
"Here are some more complex aggregations to illustrate some useful patterns.",
"_____no_output_____"
]
],
[
[
"# more complex grouped summary\n(\n flights\n .groupby(['carrier'])\n .apply(lambda d: pd.Series({\n 'avg_gain': np.mean(d.dep_delay - d.arr_delay), \n 'pct_delay_gt_30': np.mean(d.dep_delay > 30), \n 'pct_late_dep_early_arr': np.mean((d.dep_delay > 0) & (d.arr_delay < 0)), \n 'avg_arr_given_dep_delay_gt_0': d.query('dep_delay > 0').arr_delay.mean(),\n 'cor_arr_delay_dep_delay': np.corrcoef(d.dep_delay, d.arr_delay)[0,1],\n }))\n .head()\n)",
"_____no_output_____"
]
],
[
[
"Here's what's happening.\n\n* `np.mean(d.dep_delay - d.arr_delay)` aggregates over the difference of two columns.\n* `np.mean(d.dep_delay > 30)` computes the proportion of rows where the delay is greater than 30 minutes. Generating a boolean series based on some condition and then using `mean()` to find the proportion comes up all the time.\n* `np.mean((d.dep_delay > 0) & (d.arr_delay < 0))` shows that we can compute proportions where conditions on multiple columns are met.\n* `d.query('dep_delay > 0').arr_delay.mean()` computes the average arrival delay on flights where the departure was delayed. Here we first filter each grouped dataframe down to the subset of rows where departure delay is greater than zero using `query()`, and then we take the mean of the remaining arrival delays.\n* `np.corrcoef(d.dep_delay, d.arr_delay)[0,1]` computes the correlation coefficient between departure and arrival delays. Remember we can use pretty much any reduction operation to collapse values down to a scalar.",
"_____no_output_____"
],
[
"You might have noticed that the canonical pandas approach for grouped summaries is to use `agg()`.\nThat works well if you need to apply the same aggregation function on each column in the dataframe, e.g. taking the mean of every column.\nBut because of the kind of data I work with these days, it's much more common for me to use customized aggregations like those above, so the `groupby()` `apply()` idiom works best for me.",
"_____no_output_____"
],
[
"## Wrapping Up",
"_____no_output_____"
],
[
"There you have it, how to pull off the five most essential data transformation tasks using pandas in a style reminiscent of my beloved `dplyr`.\nRemember that part of the beauty of pandas is that since there are so many ways to do most tasks, you can develop your own style based on the kind of data you work with, what you like about other tools, how you see others using the tools, and of course your own taste and preferences.\n\nIf you found this post helpful or if you have your own preferred style for accomplishing any of these key transformations with pandas, do let me know about it in the comments.\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"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e789b6e063a90ff3378c91c5dca55889acb3c938 | 236,570 | ipynb | Jupyter Notebook | LatitudeTable.ipynb | kssumanth27/notebooks | ff0b3a85b5c1eb90d3a7b80f75e3244e7a038221 | [
"MIT"
] | null | null | null | LatitudeTable.ipynb | kssumanth27/notebooks | ff0b3a85b5c1eb90d3a7b80f75e3244e7a038221 | [
"MIT"
] | null | null | null | LatitudeTable.ipynb | kssumanth27/notebooks | ff0b3a85b5c1eb90d3a7b80f75e3244e7a038221 | [
"MIT"
] | null | null | null | 490.809129 | 201,856 | 0.922881 | [
[
[
"# Data Transfer",
"_____no_output_____"
],
[
"### This notebook has information regarding the data transfer per latitude in 12 day chunks run for 60 days",
"_____no_output_____"
]
],
[
[
"from lusee.observation import LObservation\nfrom lusee.lunar_satellite import LSatellite, ObservedSatellite\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import curve_fit\nimport time",
"_____no_output_____"
]
],
[
[
"## The demodulation function below follows the formula from the excel sheet. Each variable closely matches the varibles from excel sheet",
"_____no_output_____"
]
],
[
[
"def demodulation(dis_range, rate_pw2, extra_ant_gain):\n R = np.array([430,1499.99,1500,1999.99,2000,2999.99,3000,4499.99,4500,7499.99,7500,10000])\n Pt_error = np.array([11.00,11.00,8.50,8.50,6.00,6.00,4.00,4.00,3.00,3.00,2.50,2.50])\n Antenna_gain = np.arange(11)\n SANT = np.array([21.8,21.8,21.6,21.2,20.6,19.9,18.9,17.7,16.4,14.6,12.6])\n \n Srange_max = 8887.0 #Slant Range\n Srange_min = 2162.0\n Srange_mean = 6297.0\n\n Freq_MHz = 2250.0\n Asset_EIRP = 13.0 + extra_ant_gain#dBW\n\n Srange = dis_range\n\n free_space_path_loss = -20*np.log10(4*np.pi*Freq_MHz*1000000*Srange*1000/300000000)\n\n R_interp = np.linspace(430,10000,1000)\n Pt_error_intp = interp1d(R,Pt_error)\n\n Off_pt_angle = 0\n Pt_error_main = Pt_error_intp(Srange)\n\n Antenna_gain_intp = np.linspace(0,10,1000)\n SANT_intp = interp1d(Antenna_gain,SANT,fill_value=\"extrapolate\")\n #print(Off_pt_angle + Pt_error_main)\n SANT_main = SANT_intp(Off_pt_angle+Pt_error_main)\n\n Antenna_return_loss = 15\n Mismatch_loss = 10*np.log10(1-(10**(-Antenna_return_loss/20))**2)\n\n SC_noise_temp = 26.8\n SCGT = SANT_main + Mismatch_loss - SC_noise_temp\n\n Uplink_CN0 = Asset_EIRP + free_space_path_loss + SCGT - 10*np.log10(1.38e-23)\n\n Mod_loss = 0.0 #says calculated but given\n Implementation_loss = -1.0 #assumed\n Pll_bw_Hz = 700 #assumed\n Pll_bw_dB = 10*np.log10(Pll_bw_Hz)\n SN_loop = 17.9470058901322\n\n Carrier_margin = Uplink_CN0 + Implementation_loss - Pll_bw_dB - SN_loop\n\n Coded_symb_rt_input = rate_pw2\n Coded_symb_rt = 2**Coded_symb_rt_input\n\n Code_rate = 0.662430862918876 #theory\n Data_rate = Coded_symb_rt * Code_rate\n\n EbN0 = Uplink_CN0 + Implementation_loss - 10*np.log10(Data_rate*1000)\n\n Threshold_EbN0 = 2.1\n Data_demod_margin = EbN0 - Threshold_EbN0\n \n return Data_demod_margin",
"_____no_output_____"
]
],
[
[
"### The below function and the curve_fit is written to calculate the antenna gain that is added to EIRP from above function",
"_____no_output_____"
]
],
[
[
"def ext_gain(x,a,b,c): \n return a*x**2 + b*x + c",
"_____no_output_____"
],
[
"gain_data = [6.5,4.5,0]\nang_gain = [90,60,30]\n\npopt,pcov = curve_fit(ext_gain,ang_gain,gain_data)\npopt",
"_____no_output_____"
]
],
[
[
"## The below cell plots the histograms of altitude(deg) and Distance(Km) for 13 different latitudes from 30 to -90",
"_____no_output_____"
]
],
[
[
"maxi = np.zeros(shape = 13)\nmini = np.zeros(shape = 13)\navg = np.zeros(shape = 13)\n\nfor i in range(13):\n num = 30+i*(-10)\n obs = LObservation(lunar_day = \"FY2024\", lun_lat_deg = num, deltaT_sec=10*60)\n S = LSatellite()\n obsat = ObservedSatellite(obs,S)\n transits = obsat.get_transit_indices()\n trans_time = np.array([])\n dist_lun = np.array([])\n alt_lun = np.array([])\n\n for j in range(len(transits)):\n k,l = transits[j]\n trans_time = np.append(trans_time,l-k)\n dist_lun = np.append(dist_lun,obsat.dist_km()[k:l])\n alt_lun = np.append(alt_lun,obsat.alt_rad()[k:l]/np.pi*180)\n \n maxi[i] = np.max(trans_time)*10/(60)\n mini[i] = np.min(trans_time)*10/(60)\n avg[i] = np.average(trans_time)*10/(60)\n \n fig, axs = plt.subplots(figsize =(10, 7))\n \n type(dist_lun)\n\n # was not sure on how wide the bins should be\n plt.hist2d(dist_lun, alt_lun,bins = [20,20]) \n plt.title(\"Time availability (10mins) -- Lat = %i deg\" %num)\n \n axs.set_xlabel('distance (km)') \n axs.set_ylabel('altitude (deg)')\n\n cbar = plt.colorbar()\n cbar.set_label('Transit 10Minutes')",
"_____no_output_____"
]
],
[
[
"## The cell below calculates the data transfer transfer in kbs. The variable that are commented out will be removed in next revision of this file. \n\n## Disclaimer: This cell takes around 90 mins to run, which includes, calculating the variables from the lusee.lunar_satellite which takes most time followed by the repetitive use of the demodulation function. I'll try to create an numpy array that saves the calculations from LObservation function, so that repeated time taking process can be saved.",
"_____no_output_____"
],
[
"### I didn't color code the speeds yet. I don't know how to do that right away, might need some time.",
"_____no_output_____"
],
[
"### I'm not comfortable with arrays yet, hence I used list to save the data transfers, which I'll optimize in future versions",
"_____no_output_____"
]
],
[
[
"t0 = time.time()\n#main_max = np.zeros(shape = 13)\n#main_min = np.zeros(shape = 13)\n#main_mean = np.zeros(shape = 13)\n\n#counti_list = []\n#counti_list_max = []\n#counti_list_min = []\n#counti_list_mean = []\n\ndatai_list = []\ndatai_list_max = []\ndatai_list_min = []\ndatai_list_mean = []\nfor i in range(13): # This loop iterates every calculation for 13 latitudes\n num = 30+i*(-10)\n obs = LObservation(lunar_day = \"2025-02-01 13:00:00 to 2025-04-01 16:00:00\",lun_lat_deg = num, deltaT_sec=60)\n S = LSatellite()\n obsat = ObservedSatellite(obs,S)\n transits = obsat.get_transit_indices()\n \n \n # counti = np.zeros(shape = 49)\n # counti_max = np.zeros(shape = 49)\n # counti_min = np.zeros(shape = 49)\n #counti_mean = np.zeros(shape = 49)\n \n ## The datai_max, min, mean are not written right now.\n datai = np.zeros(shape = 49)\n datai_max = np.zeros(shape = 49)\n datai_min = np.zeros(shape = 49)\n datai_mean = np.zeros(shape = 49)\n print(\"loop number\",i)\n for c in range(49): #This loop iterates for 12 day chunks\n \n#maxcount = np.array([])\n#mincount = np.array([])\n #countcount = np.array([])\n #count_decoy = 0\n #count_decoy = np.zeros((len(transits)))\n for t in range(len(transits)): # This loop iterates for each visible transit range\n \n #count_decoy = 0\n ti,tf = transits[t]\n if ti>24*60*(c) and ti<24*60*(c+12):\n \n for talt in obsat.alt_rad()[ti:tf]:\n \n \n if talt > 0.3: # This if loop checks for the altitude > 0.3 rad; and calculates the data \n # transferred for wrt the distance by caluculating the demodulation (> 3.0)\n \n dis_r = obsat.dist_km()[ti:tf][np.where(obsat.alt_rad()[ti:tf] == talt)]\n #print(dis_r)\n pw2 = 12\n extra_gain = ext_gain(talt*180/(np.pi),*popt)\n demod = demodulation(dis_r,pw2,extra_gain)\n while demod <= 3.0:\n #r\n pw2 = pw2 - 1\n demod= demodulation(dis_r,pw2,extra_gain)\n \n datai[c] = datai[c] + 60*2**pw2\n #counti[c] = counti[c] + 1\n #count_decoy = count_decoy + 1\n #count_decoy = counti[c]-count_decoy\n #print(count_decoy)\n #countcount = np.append(countcount,count_decoy)\n #counti_max[c] = np.max(countcount)\n #counti_min[c] = np.min(countcount)\n #counti_mean[c] = np.average(countcount)\n #print(countcount)\n #counti_list_max.append(counti_max.tolist())\n #counti_list.append(counti.tolist())\n #counti_list_min.append(counti_min.tolist())\n #counti_list_mean.append(counti_mean.tolist())\n datai_list.append(datai.tolist())\n \n #main_max[i] = np.max(counti_max)\n #main_min[i] = np.min(counti_min)\n #main_mean[i] = np.mean(counti_mean)\n\nprint(main_max)\nprint(main_min)\nprint(main_mean)\nt1 = time.time()\nprint(\"time elapsed: {}s\".format(t1-t0))",
"loop number 0\nloop number 1\nloop number 2\nloop number 3\nloop number 4\nloop number 5\nloop number 6\nloop number 7\nloop number 8\nloop number 9\nloop number 10\nloop number 11\nloop number 12\n[ 82. 124. 194. 317. 394. 427. 443. 452. 455. 454. 448. 437. 416.]\n[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 290. 377. 415.]\n[ 39.24483393 48.92472818 82.43428713 149.45121242 189.05772082\n 219.24983257 243.30419658 256.93997946 261.02817024 303.46666957\n 379.54920344 406.90021949 415.97606692]\ntime elapsed: 5399.114231586456s\n"
]
],
[
[
"### ignore the above o/p, the main o/ps are below.",
"_____no_output_____"
]
],
[
[
"print(datai_list)",
"[[40396800.0, 49996800.0, 56417280.0, 59781120.0, 61593600.0, 62945280.0, 63851520.0, 65602560.0, 67338240.0, 67829760.0, 75617280.0, 79027200.0, 75386880.0, 76677120.0, 78382080.0, 80332800.0, 78520320.0, 77168640.0, 76262400.0, 74511360.0, 71301120.0, 65295360.0, 49658880.0, 37770240.0, 29767680.0, 26741760.0, 27417600.0, 32117760.0, 47892480.0, 55127040.0, 59274240.0, 61393920.0, 62469120.0, 63713280.0, 65095680.0, 66846720.0, 67491840.0, 67968000.0, 77184000.0, 79779840.0, 75909120.0, 77383680.0, 78750720.0, 77905920.0, 76830720.0, 75586560.0, 74204160.0, 71531520.0, 66370560.0], [66677760.0, 73589760.0, 78044160.0, 79872000.0, 80102400.0, 80102400.0, 80102400.0, 78366720.0, 73912320.0, 68136960.0, 69365760.0, 70410240.0, 68858880.0, 79065600.0, 88166400.0, 98019840.0, 100523520.0, 100523520.0, 100523520.0, 100369920.0, 98649600.0, 94440960.0, 80893440.0, 70955520.0, 62031360.0, 55864320.0, 56962560.0, 59243520.0, 72437760.0, 77783040.0, 80209920.0, 80778240.0, 80778240.0, 80778240.0, 79656960.0, 75525120.0, 70041600.0, 64926720.0, 70579200.0, 74142720.0, 76646400.0, 86085120.0, 94056960.0, 100492800.0, 100492800.0, 100492800.0, 100492800.0, 99264000.0, 95700480.0], [112588800.0, 114293760.0, 114785280.0, 115276800.0, 115276800.0, 114639360.0, 110860800.0, 103879680.0, 93696000.0, 81016320.0, 75248640.0, 72990720.0, 74227200.0, 90094080.0, 107112960.0, 126512640.0, 133847040.0, 137725440.0, 138577920.0, 138577920.0, 138024960.0, 136965120.0, 128202240.0, 119884800.0, 111006720.0, 106291200.0, 107397120.0, 104908800.0, 113978880.0, 114631680.0, 115176960.0, 115176960.0, 115176960.0, 112335360.0, 106168320.0, 96376320.0, 84280320.0, 71992320.0, 72729600.0, 77698560.0, 85593600.0, 102666240.0, 117588480.0, 131781120.0, 136742400.0, 138355200.0, 138355200.0, 138355200.0, 135406080.0], [185111040.0, 181893120.0, 176785920.0, 170603520.0, 163008000.0, 156595200.0, 147601920.0, 134814720.0, 116659200.0, 95408640.0, 83842560.0, 66117120.0, 77752320.0, 98603520.0, 124001280.0, 153169920.0, 166164480.0, 175518720.0, 182269440.0, 187115520.0, 192468480.0, 201523200.0, 197591040.0, 193528320.0, 188467200.0, 184496640.0, 182538240.0, 184296960.0, 181992960.0, 177000960.0, 170711040.0, 165864960.0, 160512000.0, 148938240.0, 137694720.0, 121658880.0, 100339200.0, 81262080.0, 78259200.0, 73451520.0, 92282880.0, 118464000.0, 140912640.0, 164782080.0, 174881280.0, 182008320.0, 187130880.0, 192299520.0, 190978560.0], [254768640.0, 243809280.0, 231306240.0, 219624960.0, 202383360.0, 189465600.0, 174159360.0, 154030080.0, 129323520.0, 98741760.0, 79902720.0, 61839360.0, 75770880.0, 104855040.0, 138785280.0, 180357120.0, 200332800.0, 215424000.0, 227819520.0, 239685120.0, 256865280.0, 269614080.0, 273500160.0, 277079040.0, 277562880.0, 274782720.0, 267863040.0, 256942080.0, 246566400.0, 235130880.0, 222735360.0, 210869760.0, 193689600.0, 179665920.0, 161533440.0, 137725440.0, 107558400.0, 78996480.0, 73121280.0, 69849600.0, 96145920.0, 130375680.0, 160919040.0, 194419200.0, 210746880.0, 223749120.0, 235476480.0, 246689280.0, 246320640.0], [338411520.0, 320256000.0, 299850240.0, 279006720.0, 248601600.0, 228756480.0, 205294080.0, 177768960.0, 144867840.0, 107942400.0, 63959040.0, 57131520.0, 69504000.0, 100546560.0, 138439680.0, 190663680.0, 217198080.0, 240583680.0, 261081600.0, 281218560.0, 310448640.0, 332221440.0, 346521600.0, 358440960.0, 367664640.0, 368593920.0, 363471360.0, 341875200.0, 325017600.0, 304366080.0, 283868160.0, 263731200.0, 234501120.0, 211868160.0, 185356800.0, 154176000.0, 116782080.0, 82114560.0, 69473280.0, 63590400.0, 91161600.0, 128156160.0, 164666880.0, 211176960.0, 235714560.0, 255966720.0, 276672000.0, 296885760.0, 296885760.0], [387870720.0, 362350080.0, 332682240.0, 307814400.0, 270428160.0, 241205760.0, 210915840.0, 174074880.0, 137664000.0, 97328640.0, 58398720.0, 52055040.0, 63467520.0, 91668480.0, 129000960.0, 188098560.0, 222236160.0, 253716480.0, 280657920.0, 306048000.0, 346490880.0, 375598080.0, 398638080.0, 418713600.0, 434688000.0, 436270080.0, 438581760.0, 396165120.0, 370629120.0, 341644800.0, 314703360.0, 289313280.0, 248870400.0, 219102720.0, 184481280.0, 147571200.0, 105991680.0, 73359360.0, 51456000.0, 58168320.0, 82490880.0, 119592960.0, 158100480.0, 214709760.0, 246259200.0, 273830400.0, 299205120.0, 323827200.0, 323827200.0], [439249920.0, 408506880.0, 372925440.0, 335462400.0, 281103360.0, 244915200.0, 208166400.0, 166210560.0, 125329920.0, 90178560.0, 56808960.0, 51156480.0, 61985280.0, 87290880.0, 123763200.0, 187484160.0, 225768960.0, 262840320.0, 300595200.0, 336399360.0, 391403520.0, 424896000.0, 454103040.0, 479854080.0, 493493760.0, 493562880.0, 492817920.0, 444556800.0, 414888960.0, 381350400.0, 343595520.0, 307791360.0, 252787200.0, 218065920.0, 177054720.0, 135659520.0, 98388480.0, 70540800.0, 51440640.0, 56924160.0, 79388160.0, 113018880.0, 154567680.0, 217397760.0, 253824000.0, 291763200.0, 327859200.0, 364615680.0, 364300800.0], [458457600.0, 428613120.0, 391572480.0, 348641280.0, 284820480.0, 245214720.0, 207083520.0, 165027840.0, 124270080.0, 73658880.0, 60372480.0, 56071680.0, 63805440.0, 81822720.0, 110615040.0, 168007680.0, 205340160.0, 245460480.0, 287961600.0, 331292160.0, 392793600.0, 427146240.0, 456268800.0, 482941440.0, 499991040.0, 520097280.0, 507494400.0, 465615360.0, 437268480.0, 402247680.0, 360737280.0, 317406720.0, 255905280.0, 218350080.0, 176601600.0, 135168000.0, 98926080.0, 58882560.0, 56931840.0, 61332480.0, 77076480.0, 103050240.0, 138816000.0, 195494400.0, 235023360.0, 277017600.0, 320378880.0, 362465280.0, 360468480.0], [425825280.0, 397255680.0, 364723200.0, 324641280.0, 261143040.0, 221160960.0, 183836160.0, 149990400.0, 121259520.0, 85194240.0, 70371840.0, 71861760.0, 78435840.0, 93573120.0, 114616320.0, 162362880.0, 200017920.0, 240215040.0, 282485760.0, 324533760.0, 382940160.0, 415188480.0, 441853440.0, 454456320.0, 464724480.0, 477772800.0, 468449280.0, 432092160.0, 405143040.0, 371857920.0, 335247360.0, 293038080.0, 231490560.0, 193413120.0, 158369280.0, 128455680.0, 104010240.0, 73420800.0, 65157120.0, 75893760.0, 88911360.0, 110261760.0, 136558080.0, 189918720.0, 229562880.0, 271403520.0, 314065920.0, 353326080.0, 348165120.0], [366881280.0, 347750400.0, 328727040.0, 303467520.0, 256419840.0, 225776640.0, 198681600.0, 171486720.0, 149130240.0, 119278080.0, 109340160.0, 114739200.0, 118609920.0, 127088640.0, 136473600.0, 169935360.0, 195479040.0, 222466560.0, 247549440.0, 276648960.0, 322160640.0, 347543040.0, 370122240.0, 378554880.0, 387916800.0, 401856000.0, 397148160.0, 371566080.0, 353541120.0, 330892800.0, 310325760.0, 281771520.0, 233379840.0, 203573760.0, 178007040.0, 153830400.0, 134899200.0, 110484480.0, 105914880.0, 116467200.0, 123686400.0, 136488960.0, 149529600.0, 188321280.0, 215132160.0, 242334720.0, 268615680.0, 297530880.0, 288944640.0], [288814080.0, 278131200.0, 270259200.0, 256488960.0, 230515200.0, 217336320.0, 210677760.0, 199380480.0, 189012480.0, 169313280.0, 161817600.0, 165235200.0, 168038400.0, 175280640.0, 180480000.0, 204357120.0, 217520640.0, 231006720.0, 238709760.0, 251827200.0, 276748800.0, 288714240.0, 299781120.0, 300426240.0, 302906880.0, 312353280.0, 308928000.0, 290949120.0, 281172480.0, 267901440.0, 259722240.0, 245944320.0, 220354560.0, 207797760.0, 201914880.0, 191362560.0, 181562880.0, 163315200.0, 157032960.0, 166671360.0, 172876800.0, 183183360.0, 189411840.0, 214172160.0, 227581440.0, 241029120.0, 248555520.0, 261442560.0, 249653760.0], [249784320.0, 259384320.0, 259399680.0, 259384320.0, 249784320.0, 249784320.0, 259399680.0, 259384320.0, 259399680.0, 249784320.0, 249784320.0, 259399680.0, 259399680.0, 249784320.0, 249784320.0, 259399680.0, 259384320.0, 259399680.0, 249784320.0, 249784320.0, 259384320.0, 259399680.0, 259384320.0, 249784320.0, 249784320.0, 259384320.0, 259384320.0, 249784320.0, 249799680.0, 259399680.0, 259399680.0, 259384320.0, 249784320.0, 249784320.0, 259415040.0, 259399680.0, 259399680.0, 249784320.0, 249784320.0, 259399680.0, 259399680.0, 249784320.0, 249784320.0, 259399680.0, 259384320.0, 259399680.0, 249784320.0, 249784320.0, 230568960.0]]\n"
],
[
"data_total_GB = [[z/(8*1024*1024) for z in y]for y in datai_list]",
"_____no_output_____"
],
[
"print(data_total_GB)",
"[[4.815673828125, 5.9600830078125, 6.7254638671875, 7.12646484375, 7.342529296875, 7.503662109375, 7.6116943359375, 7.8204345703125, 8.02734375, 8.0859375, 9.0142822265625, 9.4207763671875, 8.98681640625, 9.140625, 9.3438720703125, 9.576416015625, 9.3603515625, 9.19921875, 9.0911865234375, 8.8824462890625, 8.499755859375, 7.7838134765625, 5.9197998046875, 4.5025634765625, 3.548583984375, 3.1878662109375, 3.2684326171875, 3.8287353515625, 5.709228515625, 6.5716552734375, 7.0660400390625, 7.3187255859375, 7.4468994140625, 7.59521484375, 7.760009765625, 7.96875, 8.045654296875, 8.1024169921875, 9.2010498046875, 9.510498046875, 9.049072265625, 9.224853515625, 9.3878173828125, 9.287109375, 9.158935546875, 9.0106201171875, 8.8458251953125, 8.5272216796875, 7.9119873046875], [7.9486083984375, 8.7725830078125, 9.3035888671875, 9.521484375, 9.5489501953125, 9.5489501953125, 9.5489501953125, 9.342041015625, 8.81103515625, 8.12255859375, 8.26904296875, 8.3935546875, 8.2086181640625, 9.42535400390625, 10.51025390625, 11.68487548828125, 11.98333740234375, 11.98333740234375, 11.98333740234375, 11.96502685546875, 11.75994873046875, 11.25823974609375, 9.64324951171875, 8.45855712890625, 7.39471435546875, 6.6595458984375, 6.79046630859375, 7.0623779296875, 8.63525390625, 9.2724609375, 9.561767578125, 9.6295166015625, 9.6295166015625, 9.6295166015625, 9.495849609375, 9.0032958984375, 8.349609375, 7.7398681640625, 8.4136962890625, 8.8385009765625, 9.136962890625, 10.26214599609375, 11.21246337890625, 11.97967529296875, 11.97967529296875, 11.97967529296875, 11.97967529296875, 11.83319091796875, 11.40838623046875], [13.421630859375, 13.6248779296875, 13.6834716796875, 13.7420654296875, 13.7420654296875, 13.66607666015625, 13.21563720703125, 12.3834228515625, 11.16943359375, 9.65789794921875, 8.9703369140625, 8.701171875, 8.84857177734375, 10.74005126953125, 12.76885986328125, 15.08148193359375, 15.955810546875, 16.41815185546875, 16.519775390625, 16.519775390625, 16.453857421875, 16.3275146484375, 15.28289794921875, 14.2913818359375, 13.2330322265625, 12.6708984375, 12.802734375, 12.506103515625, 13.58734130859375, 13.6651611328125, 13.73016357421875, 13.73016357421875, 13.73016357421875, 13.39141845703125, 12.65625, 11.48895263671875, 10.0469970703125, 8.5821533203125, 8.6700439453125, 9.26239013671875, 10.20355224609375, 12.23876953125, 14.01763916015625, 15.70953369140625, 16.30096435546875, 16.49322509765625, 16.49322509765625, 16.49322509765625, 16.14166259765625], [22.06695556640625, 21.683349609375, 21.07452392578125, 20.3375244140625, 19.43206787109375, 18.6676025390625, 17.59552001953125, 16.0711669921875, 13.9068603515625, 11.37359619140625, 9.99481201171875, 7.88177490234375, 9.268798828125, 11.75445556640625, 14.7821044921875, 18.25927734375, 19.808349609375, 20.9234619140625, 21.72821044921875, 22.305908203125, 22.94403076171875, 24.0234375, 23.5546875, 23.07037353515625, 22.467041015625, 21.99371337890625, 21.76025390625, 21.96990966796875, 21.69525146484375, 21.10015869140625, 20.350341796875, 19.77264404296875, 19.134521484375, 17.75482177734375, 16.41448974609375, 14.50286865234375, 11.96136474609375, 9.68719482421875, 9.3292236328125, 8.756103515625, 11.0009765625, 14.12200927734375, 16.798095703125, 19.6435546875, 20.84747314453125, 21.69708251953125, 22.3077392578125, 22.92388916015625, 22.76641845703125], [30.37078857421875, 29.0643310546875, 27.5738525390625, 26.18133544921875, 24.1259765625, 22.5860595703125, 20.76141357421875, 18.36181640625, 15.41656494140625, 11.77093505859375, 9.525146484375, 7.371826171875, 9.0325927734375, 12.49969482421875, 16.54449462890625, 21.500244140625, 23.88153076171875, 25.6805419921875, 27.158203125, 28.57269287109375, 30.6207275390625, 32.1405029296875, 32.603759765625, 33.0303955078125, 33.08807373046875, 32.75665283203125, 31.9317626953125, 30.6298828125, 29.39300537109375, 28.02978515625, 26.5521240234375, 25.13763427734375, 23.089599609375, 21.4178466796875, 19.25628662109375, 16.41815185546875, 12.82196044921875, 9.4171142578125, 8.71673583984375, 8.32672119140625, 11.46148681640625, 15.5419921875, 19.18304443359375, 23.17657470703125, 25.12298583984375, 26.6729736328125, 28.07098388671875, 29.40765380859375, 29.36370849609375], [40.341796875, 38.177490234375, 35.74493408203125, 33.26019287109375, 29.6356201171875, 27.2698974609375, 24.47296142578125, 21.19171142578125, 17.26959228515625, 12.86773681640625, 7.62451171875, 6.81060791015625, 8.2855224609375, 11.986083984375, 16.5032958984375, 22.7288818359375, 25.89202880859375, 28.6798095703125, 31.12335205078125, 33.52386474609375, 37.00836181640625, 39.6038818359375, 41.30859375, 42.7294921875, 43.82904052734375, 43.9398193359375, 43.32916259765625, 40.75469970703125, 38.7451171875, 36.28326416015625, 33.8397216796875, 31.439208984375, 27.9547119140625, 25.25665283203125, 22.09625244140625, 18.37921142578125, 13.9215087890625, 9.788818359375, 8.2818603515625, 7.58056640625, 10.8673095703125, 15.27740478515625, 19.62982177734375, 25.17425537109375, 28.099365234375, 30.51361083984375, 32.98187255859375, 35.39154052734375, 35.39154052734375], [46.23779296875, 43.19549560546875, 39.6588134765625, 36.6943359375, 32.237548828125, 28.75396728515625, 25.14312744140625, 20.7513427734375, 16.41082763671875, 11.60247802734375, 6.961669921875, 6.2054443359375, 7.56591796875, 10.927734375, 15.37811279296875, 22.423095703125, 26.49261474609375, 30.245361328125, 33.45703125, 36.4837646484375, 41.304931640625, 44.7747802734375, 47.5213623046875, 49.91455078125, 51.81884765625, 52.0074462890625, 52.28302001953125, 47.2265625, 44.18243408203125, 40.72723388671875, 37.51556396484375, 34.48883056640625, 29.66766357421875, 26.11907958984375, 21.99188232421875, 17.59185791015625, 12.63519287109375, 8.7451171875, 6.134033203125, 6.9342041015625, 9.83367919921875, 14.256591796875, 18.8470458984375, 25.59539794921875, 29.35638427734375, 32.64312744140625, 35.66802978515625, 38.60321044921875, 38.60321044921875], [52.3626708984375, 48.69781494140625, 44.4561767578125, 39.990234375, 33.5101318359375, 29.1961669921875, 24.81536865234375, 19.8138427734375, 14.94049072265625, 10.7501220703125, 6.77215576171875, 6.09832763671875, 7.38922119140625, 10.4058837890625, 14.75372314453125, 22.349853515625, 26.91375732421875, 31.3330078125, 35.833740234375, 40.1019287109375, 46.658935546875, 50.65155029296875, 54.13330078125, 57.20306396484375, 58.82904052734375, 58.8372802734375, 58.74847412109375, 52.99530029296875, 49.4586181640625, 45.46051025390625, 40.95977783203125, 36.69158935546875, 30.13458251953125, 25.9954833984375, 21.1065673828125, 16.171875, 11.72882080078125, 8.40911865234375, 6.1322021484375, 6.785888671875, 9.46380615234375, 13.472900390625, 18.4259033203125, 25.91583251953125, 30.2581787109375, 34.7808837890625, 39.0838623046875, 43.465576171875, 43.42803955078125], [54.65240478515625, 51.09466552734375, 46.6790771484375, 41.561279296875, 33.9532470703125, 29.23187255859375, 24.686279296875, 19.6728515625, 14.81414794921875, 8.78082275390625, 7.19696044921875, 6.68426513671875, 7.606201171875, 9.7540283203125, 13.18634033203125, 20.028076171875, 24.47845458984375, 29.26116943359375, 34.32769775390625, 39.49310302734375, 46.82464599609375, 50.9197998046875, 54.3914794921875, 57.57110595703125, 59.60357666015625, 62.00042724609375, 60.498046875, 55.50567626953125, 52.12646484375, 47.95166015625, 43.00323486328125, 37.83782958984375, 30.50628662109375, 26.02935791015625, 21.05255126953125, 16.11328125, 11.79290771484375, 7.01934814453125, 6.78680419921875, 7.3114013671875, 9.188232421875, 12.2845458984375, 16.54815673828125, 23.30474853515625, 28.0169677734375, 33.0230712890625, 38.192138671875, 43.209228515625, 42.97119140625], [50.7623291015625, 47.3565673828125, 43.4783935546875, 38.70025634765625, 31.13067626953125, 26.36444091796875, 21.91497802734375, 17.8802490234375, 14.45526123046875, 10.15594482421875, 8.38897705078125, 8.56658935546875, 9.35028076171875, 11.15478515625, 13.663330078125, 19.35516357421875, 23.843994140625, 28.6358642578125, 33.6749267578125, 38.68743896484375, 45.6500244140625, 49.49432373046875, 52.67303466796875, 54.1754150390625, 55.39947509765625, 56.9549560546875, 55.843505859375, 51.5093994140625, 48.29681396484375, 44.32891845703125, 39.964599609375, 34.932861328125, 27.5958251953125, 23.056640625, 18.87908935546875, 15.3131103515625, 12.39898681640625, 8.75244140625, 7.767333984375, 9.0472412109375, 10.59906005859375, 13.14422607421875, 16.27899169921875, 22.64007568359375, 27.36602783203125, 32.35382080078125, 37.4395751953125, 42.1197509765625, 41.5045166015625], [43.73565673828125, 41.455078125, 39.18731689453125, 36.1761474609375, 30.567626953125, 26.9146728515625, 23.6846923828125, 20.44281005859375, 17.7777099609375, 14.21905517578125, 13.03436279296875, 13.677978515625, 14.139404296875, 15.150146484375, 16.2689208984375, 20.25787353515625, 23.30291748046875, 26.52008056640625, 29.51019287109375, 32.9791259765625, 38.404541015625, 41.43035888671875, 44.12200927734375, 45.12725830078125, 46.2432861328125, 47.90496826171875, 47.34375, 44.29412841796875, 42.1453857421875, 39.44549560546875, 36.99371337890625, 33.58978271484375, 27.821044921875, 24.26788330078125, 21.2200927734375, 18.3380126953125, 16.08123779296875, 13.1707763671875, 12.62603759765625, 13.88397216796875, 14.74456787109375, 16.270751953125, 17.8253173828125, 22.44964599609375, 25.645751953125, 28.8885498046875, 32.021484375, 35.46844482421875, 34.44488525390625], [34.4293212890625, 33.15582275390625, 32.2174072265625, 30.57586669921875, 27.47955322265625, 25.90850830078125, 25.11474609375, 23.76800537109375, 22.53204345703125, 20.1837158203125, 19.2901611328125, 19.69757080078125, 20.03173828125, 20.89508056640625, 21.514892578125, 24.36126708984375, 25.93048095703125, 27.53814697265625, 28.4564208984375, 30.0201416015625, 32.99102783203125, 34.41741943359375, 35.7366943359375, 35.8135986328125, 36.10931396484375, 37.23541259765625, 36.82708740234375, 34.683837890625, 33.51837158203125, 31.93634033203125, 30.9613037109375, 29.31884765625, 26.268310546875, 24.77142333984375, 24.07012939453125, 22.81219482421875, 21.64398193359375, 19.46868896484375, 18.71978759765625, 19.8687744140625, 20.6085205078125, 21.837158203125, 22.57965087890625, 25.53131103515625, 27.12982177734375, 28.73291015625, 29.630126953125, 31.1663818359375, 29.76104736328125], [29.776611328125, 30.9210205078125, 30.9228515625, 30.9210205078125, 29.776611328125, 29.776611328125, 30.9228515625, 30.9210205078125, 30.9228515625, 29.776611328125, 29.776611328125, 30.9228515625, 30.9228515625, 29.776611328125, 29.776611328125, 30.9228515625, 30.9210205078125, 30.9228515625, 29.776611328125, 29.776611328125, 30.9210205078125, 30.9228515625, 30.9210205078125, 29.776611328125, 29.776611328125, 30.9210205078125, 30.9210205078125, 29.776611328125, 29.7784423828125, 30.9228515625, 30.9228515625, 30.9210205078125, 29.776611328125, 29.776611328125, 30.9246826171875, 30.9228515625, 30.9228515625, 29.776611328125, 29.776611328125, 30.9228515625, 30.9228515625, 29.776611328125, 29.776611328125, 30.9228515625, 30.9210205078125, 30.9228515625, 29.776611328125, 29.776611328125, 27.4859619140625]]\n"
],
[
"fig = plt.figure(figsize=(12,12))\n#figsize=(15,15)\nplt.plot(range(49),data_total_GB[0],label=\"30deg\")\nplt.plot(range(49),data_total_GB[1],label=\"20deg\")\nplt.plot(range(49),data_total_GB[2],label=\"10deg\")\nplt.plot(range(49),data_total_GB[3],label=\"0deg\")\nplt.plot(range(49),data_total_GB[4],label=\"-10deg\")\nplt.plot(range(49),data_total_GB[5],label=\"-20deg\")\nplt.plot(range(49),data_total_GB[6],label=\"-30deg\")\nplt.plot(range(49),data_total_GB[7],label=\"-40deg\")\nplt.plot(range(49),data_total_GB[8],label=\"-50deg\")\nplt.plot(range(49),data_total_GB[9],label=\"-60deg\")\nplt.plot(range(49),data_total_GB[10],label=\"-70deg\",linestyle=\"--\")\nplt.plot(range(49),data_total_GB[11],label=\"-80deg\",linestyle=\"--\")\nplt.plot(range(49),data_total_GB[12],label=\"-90deg\",linestyle=\"--\")\nplt.xlabel(\"12 days\") #each number represents 1 12 day chunk\nplt.ylabel(\"Total Data Transfer(GB)\")\nplt.legend()\nplt.show()\n\nfig.savefig(\"data.png\",bbox_inches = \"tight\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e789b8552bb3bd41c0ed8346cebb1c5c8c3b1f42 | 94,949 | ipynb | Jupyter Notebook | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples | bb4a4ed78cd4f3673bd6894f0b92ab08aa7f8f29 | [
"Apache-2.0"
] | null | null | null | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples | bb4a4ed78cd4f3673bd6894f0b92ab08aa7f8f29 | [
"Apache-2.0"
] | null | null | null | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples | bb4a4ed78cd4f3673bd6894f0b92ab08aa7f8f29 | [
"Apache-2.0"
] | null | null | null | 102.095699 | 29,108 | 0.770403 | [
[
[
"# Amazon SageMaker Debugger - Using built-in rule\n[Amazon SageMaker](https://aws.amazon.com/sagemaker/) is managed platform to build, train and host maching learning models. Amazon SageMaker Debugger is a new feature which offers the capability to debug machine learning models during training by identifying and detecting problems with the models in near real-time. \n\nIn this notebook you'll be looking at how to use a SageMaker provided built in rule during a TensorFlow training job.\n\n## How does Amazon SageMaker Debugger work?\n\nAmazon SageMaker Debugger lets you go beyond just looking at scalars like losses and accuracies during training and gives you full visibility into all tensors 'flowing through the graph' during training. Furthermore, it helps you monitor your training in near real-time using rules and provides you alerts, once it has detected inconsistency in training flow.\n\n### Concepts\n* **Tensors**: These represent the state of the training network at intermediate points during its execution\n* **Debug Hook**: Hook is the construct with which Amazon SageMaker Debugger looks into the training process and captures the tensors requested at the desired step intervals\n* **Rule**: A logical construct, implemented as Python code, which helps analyze the tensors captured by the hook and report anomalies, if at all\n\nWith these concepts in mind, let's understand the overall flow of things that Amazon SageMaker Debugger uses to orchestrate debugging\n\n### Saving tensors during training\n\nThe tensors captured by the debug hook are stored in the S3 location specified by you. There are two ways you can configure Amazon SageMaker Debugger to save tensors:\n\n#### With no changes to your training script\nIf you use one of Amazon SageMaker provided [Deep Learning Containers](https://docs.aws.amazon.com/sagemaker/latest/dg/pre-built-containers-frameworks-deep-learning.html) for 1.15, then you don't need to make any changes to your training script for the tensors to be stored. Amazon SageMaker Debugger will use the configuration you provide through Amazon SageMaker SDK's Tensorflow `Estimator` when creating your job to save the tensors in the fashion you specify. You can review the script we are going to use at [src/mnist_zerocodechange.py](src/mnist_zerocodechange.py). You will note that this is an untouched TensorFlow script which uses the `tf.estimator` interface. Please note that Amazon SageMaker Debugger only supports `tf.keras`, `tf.Estimator` and `tf.MonitoredSession` interfaces. Full description of support is available at [Amazon SageMaker Debugger with TensorFlow ](https://github.com/awslabs/sagemaker-debugger/tree/master/docs/tensorflow.md)\n\n#### Orchestrating your script to store tensors\nFor other containers, you need to make couple of lines of changes to your training script. The Amazon SageMaker Debugger exposes a library `smdebug` which allows you to capture these tensors and save them for analysis. It's highly customizable and allows to save the specific tensors you want at different frequencies and possibly with other configurations. Refer [DeveloperGuide](https://github.com/awslabs/sagemaker-debugger/tree/master/docs) for details on how to use the Debugger library with your choice of framework in your training script. Here we have an example script orchestrated at [src/mnist_byoc](src/mnist_byoc.py). You also need to ensure that your container has the `smdebug` library installed.\n\n### Analysis of tensors\n\nOnce the tensors are saved, Amazon SageMaker Debugger can be configured to run debugging ***Rules*** on them. At a very broad level, a rule is python code used to detect certain conditions during training. Some of the conditions that a data scientist training an algorithm may care about are monitoring for gradients getting too large or too small, detecting overfitting, and so on. Amazon Sagemaker Debugger will come pre-packaged with certain first-party (1P) rules. Users can write their own rules using Amazon Sagemaker Debugger APIs. You can also analyze raw tensor data outside of the Rules construct in say, a Sagemaker notebook, using Amazon Sagemaker Debugger's full set of APIs. This notebook will show you how to use a built in SageMaker Rule with your training job as well as provide a sneak peak into these APIs for interactive exploration. Please refer [Analysis Developer Guide](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md) for more on these APIs.\n\n## Setup\n\nFollow this one time setup to get your notebook up and running to use Amazon SageMaker Debugger. This is only needed because we plan to perform interactive analysis using this library in the notebook. ",
"_____no_output_____"
]
],
[
[
"! pip install smdebug",
"Requirement already satisfied: smdebug in /opt/conda/lib/python3.7/site-packages (0.7.2)\nRequirement already satisfied: boto3>=1.10.32 in /opt/conda/lib/python3.7/site-packages (from smdebug) (1.12.45)\nRequirement already satisfied: protobuf>=3.6.0 in /opt/conda/lib/python3.7/site-packages (from smdebug) (3.11.3)\nRequirement already satisfied: packaging in /opt/conda/lib/python3.7/site-packages (from smdebug) (20.1)\nRequirement already satisfied: numpy<2.0.0,>1.16.0 in /opt/conda/lib/python3.7/site-packages (from smdebug) (1.18.1)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in /opt/conda/lib/python3.7/site-packages (from boto3>=1.10.32->smdebug) (0.9.5)\nRequirement already satisfied: botocore<1.16.0,>=1.15.45 in /opt/conda/lib/python3.7/site-packages (from boto3>=1.10.32->smdebug) (1.15.45)\nRequirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /opt/conda/lib/python3.7/site-packages (from boto3>=1.10.32->smdebug) (0.3.3)\nRequirement already satisfied: six>=1.9 in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.0->smdebug) (1.14.0)\nRequirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.0->smdebug) (45.2.0.post20200210)\nRequirement already satisfied: pyparsing>=2.0.2 in /opt/conda/lib/python3.7/site-packages (from packaging->smdebug) (2.4.6)\nRequirement already satisfied: python-dateutil<3.0.0,>=2.1 in /opt/conda/lib/python3.7/site-packages (from botocore<1.16.0,>=1.15.45->boto3>=1.10.32->smdebug) (2.8.1)\nRequirement already satisfied: docutils<0.16,>=0.10 in /opt/conda/lib/python3.7/site-packages (from botocore<1.16.0,>=1.15.45->boto3>=1.10.32->smdebug) (0.15.2)\nRequirement already satisfied: urllib3<1.26,>=1.20; python_version != \"3.4\" in /opt/conda/lib/python3.7/site-packages (from botocore<1.16.0,>=1.15.45->boto3>=1.10.32->smdebug) (1.25.8)\n"
]
],
[
[
"With the setup out of the way let's start training our TensorFlow model in SageMaker with the debugger enabled.\n\n## Training TensorFlow models in SageMaker with Amazon SageMaker Debugger\n\n### SageMaker TensorFlow as a framework\n\nWe'll train a TensorFlow model in this notebook with Amazon Sagemaker Debugger enabled and monitor the training jobs with Amazon Sagemaker Debugger Rules. This will be done using Amazon SageMaker [TensorFlow 1.15.0](https://docs.aws.amazon.com/sagemaker/latest/dg/pre-built-containers-frameworks-deep-learning.html) Container as a framework.\n",
"_____no_output_____"
]
],
[
[
"import boto3\nimport os\nimport sagemaker\nfrom sagemaker.tensorflow import TensorFlow",
"_____no_output_____"
]
],
[
[
"Let's import the libraries needed for our demo of Amazon SageMaker Debugger.",
"_____no_output_____"
]
],
[
[
"from sagemaker.debugger import Rule, DebuggerHookConfig, TensorBoardOutputConfig, CollectionConfig, rule_configs",
"_____no_output_____"
]
],
[
[
"Now we'll define the configuration for our training to run. We'll using image recognition using MNIST dataset as our training example.",
"_____no_output_____"
]
],
[
[
"# define the entrypoint script\nentrypoint_script='src/mnist_zerocodechange.py'\n\nhyperparameters = {\n \"num_epochs\": 1\n}",
"_____no_output_____"
],
[
"!pygmentize src/mnist_zerocodechange.py",
"\u001b[33m\"\"\"\u001b[39;49;00m\n\u001b[33mThis script is a simple MNIST training script which uses Tensorflow's Estimator interface.\u001b[39;49;00m\n\u001b[33mIt is designed to be used with SageMaker Debugger in an official SageMaker Framework container (i.e. AWS Deep Learning Container). You will notice that this script looks exactly like a normal TensorFlow training script.\u001b[39;49;00m\n\u001b[33mThe hook needed by SageMaker Debugger to save tensors during training will be automatically added in those environments. \u001b[39;49;00m\n\u001b[33mThe hook will load configuration from json configuration that SageMaker will put in the training container from the configuration provided using the SageMaker python SDK when creating a job.\u001b[39;49;00m\n\u001b[33mFor more information, please refer to https://github.com/awslabs/sagemaker-debugger/blob/master/docs/sagemaker.md \u001b[39;49;00m\n\u001b[33m\"\"\"\u001b[39;49;00m\n\n\u001b[37m# Standard Library\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36margparse\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mrandom\u001b[39;49;00m\n\n\u001b[37m# Third Party\u001b[39;49;00m\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\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtensorflow\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mtf\u001b[39;49;00m\n\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mlogging\u001b[39;49;00m\nlogging.getLogger().setLevel(logging.INFO)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\u001b[33m\"\u001b[39;49;00m\u001b[33m--lr\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[36mtype\u001b[39;49;00m=\u001b[36mfloat\u001b[39;49;00m, default=\u001b[34m0.001\u001b[39;49;00m)\nparser.add_argument(\u001b[33m\"\u001b[39;49;00m\u001b[33m--random_seed\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[36mtype\u001b[39;49;00m=\u001b[36mbool\u001b[39;49;00m, default=\u001b[34mFalse\u001b[39;49;00m)\nparser.add_argument(\u001b[33m\"\u001b[39;49;00m\u001b[33m--num_epochs\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[36mtype\u001b[39;49;00m=\u001b[36mint\u001b[39;49;00m, default=\u001b[34m5\u001b[39;49;00m, help=\u001b[33m\"\u001b[39;49;00m\u001b[33mNumber of epochs to train for\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\nparser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--num_steps\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mint\u001b[39;49;00m,\n help=\u001b[33m\"\u001b[39;49;00m\u001b[33mNumber of steps to train for. If this\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mis passed, it overrides num_epochs\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n)\nparser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--num_eval_steps\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mint\u001b[39;49;00m,\n help=\u001b[33m\"\u001b[39;49;00m\u001b[33mNumber of steps to evaluate for. If this\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n \u001b[33m\"\u001b[39;49;00m\u001b[33mis passed, it doesnt evaluate over the full eval set\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n)\nparser.add_argument(\u001b[33m\"\u001b[39;49;00m\u001b[33m--model_dir\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[36mtype\u001b[39;49;00m=\u001b[36mstr\u001b[39;49;00m, default=\u001b[33m\"\u001b[39;49;00m\u001b[33m/tmp/mnist_model\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\nargs = parser.parse_args()\n\n\u001b[37m# these random seeds are only intended for test purpose.\u001b[39;49;00m\n\u001b[37m# for now, 2,2,12 could promise no assert failure when running tests.\u001b[39;49;00m\n\u001b[37m# if you wish to change the number, notice that certain steps' tensor value may be capable of variation\u001b[39;49;00m\n\u001b[34mif\u001b[39;49;00m args.random_seed:\n tf.set_random_seed(\u001b[34m2\u001b[39;49;00m)\n np.random.seed(\u001b[34m2\u001b[39;49;00m)\n random.seed(\u001b[34m12\u001b[39;49;00m)\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mcnn_model_fn\u001b[39;49;00m(features, labels, mode):\n \u001b[33m\"\"\"Model function for CNN.\"\"\"\u001b[39;49;00m\n \u001b[37m# Input Layer\u001b[39;49;00m\n input_layer = tf.reshape(features[\u001b[33m\"\u001b[39;49;00m\u001b[33mx\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m], [-\u001b[34m1\u001b[39;49;00m, \u001b[34m28\u001b[39;49;00m, \u001b[34m28\u001b[39;49;00m, \u001b[34m1\u001b[39;49;00m])\n\n \u001b[37m# Convolutional Layer #1\u001b[39;49;00m\n conv1 = tf.layers.conv2d(\n inputs=input_layer, filters=\u001b[34m32\u001b[39;49;00m, kernel_size=[\u001b[34m5\u001b[39;49;00m, \u001b[34m5\u001b[39;49;00m], padding=\u001b[33m\"\u001b[39;49;00m\u001b[33msame\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, activation=tf.nn.relu\n )\n\n \u001b[37m# Pooling Layer #1\u001b[39;49;00m\n pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[\u001b[34m2\u001b[39;49;00m, \u001b[34m2\u001b[39;49;00m], strides=\u001b[34m2\u001b[39;49;00m)\n\n \u001b[37m# Convolutional Layer #2 and Pooling Layer #2\u001b[39;49;00m\n conv2 = tf.layers.conv2d(\n inputs=pool1, filters=\u001b[34m64\u001b[39;49;00m, kernel_size=[\u001b[34m5\u001b[39;49;00m, \u001b[34m5\u001b[39;49;00m], padding=\u001b[33m\"\u001b[39;49;00m\u001b[33msame\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, activation=tf.nn.relu\n )\n pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[\u001b[34m2\u001b[39;49;00m, \u001b[34m2\u001b[39;49;00m], strides=\u001b[34m2\u001b[39;49;00m)\n\n \u001b[37m# Dense Layer\u001b[39;49;00m\n pool2_flat = tf.reshape(pool2, [-\u001b[34m1\u001b[39;49;00m, \u001b[34m7\u001b[39;49;00m * \u001b[34m7\u001b[39;49;00m * \u001b[34m64\u001b[39;49;00m])\n dense = tf.layers.dense(inputs=pool2_flat, units=\u001b[34m1024\u001b[39;49;00m, activation=tf.nn.relu)\n dropout = tf.layers.dropout(\n inputs=dense, rate=\u001b[34m0.4\u001b[39;49;00m, training=mode == tf.estimator.ModeKeys.TRAIN\n )\n\n \u001b[37m# Logits Layer\u001b[39;49;00m\n logits = tf.layers.dense(inputs=dropout, units=\u001b[34m10\u001b[39;49;00m)\n\n predictions = {\n \u001b[37m# Generate predictions (for PREDICT and EVAL mode)\u001b[39;49;00m\n \u001b[33m\"\u001b[39;49;00m\u001b[33mclasses\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: tf.argmax(\u001b[36minput\u001b[39;49;00m=logits, axis=\u001b[34m1\u001b[39;49;00m),\n \u001b[37m# Add `softmax_tensor` to the graph. It is used for PREDICT and by the\u001b[39;49;00m\n \u001b[37m# `logging_hook`.\u001b[39;49;00m\n \u001b[33m\"\u001b[39;49;00m\u001b[33mprobabilities\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: tf.nn.softmax(logits, name=\u001b[33m\"\u001b[39;49;00m\u001b[33msoftmax_tensor\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m),\n }\n\n \u001b[34mif\u001b[39;49;00m mode == tf.estimator.ModeKeys.PREDICT:\n \u001b[34mreturn\u001b[39;49;00m tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n \u001b[37m# Calculate Loss (for both TRAIN and EVAL modes)\u001b[39;49;00m\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n \u001b[37m# Configure the Training Op (for TRAIN mode)\u001b[39;49;00m\n \u001b[34mif\u001b[39;49;00m mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=args.lr)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n \u001b[34mreturn\u001b[39;49;00m tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n \u001b[37m# Add evaluation metrics (for EVAL mode)\u001b[39;49;00m\n eval_metric_ops = {\n \u001b[33m\"\u001b[39;49;00m\u001b[33maccuracy\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: tf.metrics.accuracy(labels=labels, predictions=predictions[\u001b[33m\"\u001b[39;49;00m\u001b[33mclasses\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m])\n }\n \u001b[34mreturn\u001b[39;49;00m tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)\n\n\n\u001b[37m# Load training and eval data\u001b[39;49;00m\n((train_data, train_labels), (eval_data, eval_labels)) = tf.keras.datasets.mnist.load_data()\n\ntrain_data = train_data / np.float32(\u001b[34m255\u001b[39;49;00m)\ntrain_labels = train_labels.astype(np.int32) \u001b[37m# not required\u001b[39;49;00m\n\neval_data = eval_data / np.float32(\u001b[34m255\u001b[39;49;00m)\neval_labels = eval_labels.astype(np.int32) \u001b[37m# not required\u001b[39;49;00m\n\nmnist_classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, model_dir=args.model_dir)\n\ntrain_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\u001b[33m\"\u001b[39;49;00m\u001b[33mx\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: train_data}, y=train_labels, batch_size=\u001b[34m128\u001b[39;49;00m, num_epochs=args.num_epochs, shuffle=\u001b[34mTrue\u001b[39;49;00m\n)\n\neval_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\u001b[33m\"\u001b[39;49;00m\u001b[33mx\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: eval_data}, y=eval_labels, num_epochs=\u001b[34m1\u001b[39;49;00m, shuffle=\u001b[34mFalse\u001b[39;49;00m\n)\n\nmnist_classifier.train(input_fn=train_input_fn, steps=args.num_steps)\n\nmnist_classifier.evaluate(input_fn=eval_input_fn, steps=args.num_eval_steps)\n"
]
],
[
[
"### Setting up the Estimator\n\nNow it's time to setup our TensorFlow estimator. We've added new parameters to the estimator to enable your training job for debugging through Amazon SageMaker Debugger. These new parameters are explained below.\n\n* **debugger_hook_config**: This new parameter accepts a local path where you wish your tensors to be written to and also accepts the S3 URI where you wish your tensors to be uploaded to. SageMaker will take care of uploading these tensors transparently during execution.\n* **rules**: This new parameter will accept a list of rules you wish to evaluate against the tensors output by this training job. For rules, Amazon SageMaker Debugger supports two types:\n * **SageMaker Rules**: These are rules specially curated by the data science and engineering teams in Amazon SageMaker which you can opt to evaluate against your training job.\n * **Custom Rules**: You can optionally choose to write your own rule as a Python source file and have it evaluated against your training job. To provide Amazon SageMaker Debugger to evaluate this rule, you would have to provide the S3 location of the rule source and the evaluator image.\n \n#### Using Amazon SageMaker Rules\n \nIn this example we'll demonstrate how to use SageMaker rules to be evaluated against your training. You can find the list of SageMaker rules and the configurations best suited for using them [here](https://github.com/awslabs/sagemaker-debugger-rulesconfig).\n\nThe rules we'll use are **VanishingGradient** and **LossNotDecreasing**. As the names suggest, the rules will attempt to evaluate if there are vanishing gradients in the tensors captured by the debugging hook during training and also if the loss is not decreasing.",
"_____no_output_____"
]
],
[
[
"rules = [\n Rule.sagemaker(rule_configs.vanishing_gradient()), \n Rule.sagemaker(rule_configs.loss_not_decreasing())\n]\n\nestimator = TensorFlow(\n role=sagemaker.get_execution_role(),\n base_job_name='smdebugger-demo-mnist-tensorflow',\n train_instance_count=1,\n train_instance_type='ml.m4.xlarge',\n train_volume_size=400,\n entry_point=entrypoint_script,\n framework_version='1.15',\n py_version='py3',\n train_max_run=3600,\n script_mode=True,\n hyperparameters=hyperparameters,\n ## New parameter\n rules = rules\n)",
"_____no_output_____"
]
],
[
[
"*Note that Amazon Sagemaker Debugger is only supported for py_version='py3' currently.*\n\nLet's start the training by calling `fit()` on the TensorFlow estimator.",
"_____no_output_____"
]
],
[
[
"estimator.fit(wait=True)",
"2020-04-27 23:56:40 Starting - Starting the training job...\n2020-04-27 23:57:04 Starting - Launching requested ML instances\n********* Debugger Rule Status *********\n*\n* VanishingGradient: InProgress \n* LossNotDecreasing: InProgress \n*\n****************************************\n...\n2020-04-27 23:57:36 Starting - Preparing the instances for training.........\n2020-04-27 23:59:10 Downloading - Downloading input data\n2020-04-27 23:59:10 Training - Downloading the training image...\n2020-04-27 23:59:30 Training - Training image download completed. Training in progress..\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/__init__.py:1473: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead.\n\u001b[0m\n\u001b[34m2020-04-27 23:59:36,257 sagemaker-containers INFO Imported framework sagemaker_tensorflow_container.training\u001b[0m\n\u001b[34m2020-04-27 23:59:36,263 sagemaker-containers INFO No GPUs detected (normal if no gpus installed)\u001b[0m\n\u001b[34m2020-04-27 23:59:36,707 sagemaker-containers INFO No GPUs detected (normal if no gpus installed)\u001b[0m\n\u001b[34m2020-04-27 23:59:36,727 sagemaker-containers INFO No GPUs detected (normal if no gpus installed)\u001b[0m\n\u001b[34m2020-04-27 23:59:36,746 sagemaker-containers INFO No GPUs detected (normal if no gpus installed)\u001b[0m\n\u001b[34m2020-04-27 23:59:36,760 sagemaker-containers INFO Invoking user script\n\u001b[0m\n\u001b[34mTraining Env:\n\u001b[0m\n\u001b[34m{\n \"additional_framework_parameters\": {},\n \"channel_input_dirs\": {},\n \"current_host\": \"algo-1\",\n \"framework_module\": \"sagemaker_tensorflow_container.training:main\",\n \"hosts\": [\n \"algo-1\"\n ],\n \"hyperparameters\": {\n \"model_dir\": \"s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model\",\n \"num_epochs\": 3\n },\n \"input_config_dir\": \"/opt/ml/input/config\",\n \"input_data_config\": {},\n \"input_dir\": \"/opt/ml/input\",\n \"is_master\": true,\n \"job_name\": \"smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900\",\n \"log_level\": 20,\n \"master_hostname\": \"algo-1\",\n \"model_dir\": \"/opt/ml/model\",\n \"module_dir\": \"s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/source/sourcedir.tar.gz\",\n \"module_name\": \"mnist_zerocodechange\",\n \"network_interface_name\": \"eth0\",\n \"num_cpus\": 4,\n \"num_gpus\": 0,\n \"output_data_dir\": \"/opt/ml/output/data\",\n \"output_dir\": \"/opt/ml/output\",\n \"output_intermediate_dir\": \"/opt/ml/output/intermediate\",\n \"resource_config\": {\n \"current_host\": \"algo-1\",\n \"hosts\": [\n \"algo-1\"\n ],\n \"network_interface_name\": \"eth0\"\n },\n \"user_entry_point\": \"mnist_zerocodechange.py\"\u001b[0m\n\u001b[34m}\n\u001b[0m\n\u001b[34mEnvironment variables:\n\u001b[0m\n\u001b[34mSM_HOSTS=[\"algo-1\"]\u001b[0m\n\u001b[34mSM_NETWORK_INTERFACE_NAME=eth0\u001b[0m\n\u001b[34mSM_HPS={\"model_dir\":\"s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model\",\"num_epochs\":3}\u001b[0m\n\u001b[34mSM_USER_ENTRY_POINT=mnist_zerocodechange.py\u001b[0m\n\u001b[34mSM_FRAMEWORK_PARAMS={}\u001b[0m\n\u001b[34mSM_RESOURCE_CONFIG={\"current_host\":\"algo-1\",\"hosts\":[\"algo-1\"],\"network_interface_name\":\"eth0\"}\u001b[0m\n\u001b[34mSM_INPUT_DATA_CONFIG={}\u001b[0m\n\u001b[34mSM_OUTPUT_DATA_DIR=/opt/ml/output/data\u001b[0m\n\u001b[34mSM_CHANNELS=[]\u001b[0m\n\u001b[34mSM_CURRENT_HOST=algo-1\u001b[0m\n\u001b[34mSM_MODULE_NAME=mnist_zerocodechange\u001b[0m\n\u001b[34mSM_LOG_LEVEL=20\u001b[0m\n\u001b[34mSM_FRAMEWORK_MODULE=sagemaker_tensorflow_container.training:main\u001b[0m\n\u001b[34mSM_INPUT_DIR=/opt/ml/input\u001b[0m\n\u001b[34mSM_INPUT_CONFIG_DIR=/opt/ml/input/config\u001b[0m\n\u001b[34mSM_OUTPUT_DIR=/opt/ml/output\u001b[0m\n\u001b[34mSM_NUM_CPUS=4\u001b[0m\n\u001b[34mSM_NUM_GPUS=0\u001b[0m\n\u001b[34mSM_MODEL_DIR=/opt/ml/model\u001b[0m\n\u001b[34mSM_MODULE_DIR=s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/source/sourcedir.tar.gz\u001b[0m\n\u001b[34mSM_TRAINING_ENV={\"additional_framework_parameters\":{},\"channel_input_dirs\":{},\"current_host\":\"algo-1\",\"framework_module\":\"sagemaker_tensorflow_container.training:main\",\"hosts\":[\"algo-1\"],\"hyperparameters\":{\"model_dir\":\"s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model\",\"num_epochs\":3},\"input_config_dir\":\"/opt/ml/input/config\",\"input_data_config\":{},\"input_dir\":\"/opt/ml/input\",\"is_master\":true,\"job_name\":\"smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900\",\"log_level\":20,\"master_hostname\":\"algo-1\",\"model_dir\":\"/opt/ml/model\",\"module_dir\":\"s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/source/sourcedir.tar.gz\",\"module_name\":\"mnist_zerocodechange\",\"network_interface_name\":\"eth0\",\"num_cpus\":4,\"num_gpus\":0,\"output_data_dir\":\"/opt/ml/output/data\",\"output_dir\":\"/opt/ml/output\",\"output_intermediate_dir\":\"/opt/ml/output/intermediate\",\"resource_config\":{\"current_host\":\"algo-1\",\"hosts\":[\"algo-1\"],\"network_interface_name\":\"eth0\"},\"user_entry_point\":\"mnist_zerocodechange.py\"}\u001b[0m\n\u001b[34mSM_USER_ARGS=[\"--model_dir\",\"s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model\",\"--num_epochs\",\"3\"]\u001b[0m\n\u001b[34mSM_OUTPUT_INTERMEDIATE_DIR=/opt/ml/output/intermediate\u001b[0m\n\u001b[34mSM_HP_MODEL_DIR=s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model\u001b[0m\n\u001b[34mSM_HP_NUM_EPOCHS=3\u001b[0m\n\u001b[34mPYTHONPATH=/opt/ml/code:/usr/local/bin:/usr/lib/python36.zip:/usr/lib/python3.6:/usr/lib/python3.6/lib-dynload:/usr/local/lib/python3.6/dist-packages:/usr/lib/python3/dist-packages\n\u001b[0m\n\u001b[34mInvoking script with the following command:\n\u001b[0m\n\u001b[34m/usr/bin/python3 mnist_zerocodechange.py --model_dir s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model --num_epochs 3\n\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/__init__.py:1473: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead.\n\u001b[0m\n\u001b[34mDownloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\u001b[0m\n\u001b[34m#015 8192/11490434 [..............................] - ETA: 0s#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#015 106496/11490434 [..............................] - ETA: 5s#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#015 737280/11490434 [>.............................] - ETA: 1s#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#015 5210112/11490434 [============>.................] - ETA: 0s#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#015 6987776/11490434 [=================>............] - ETA: 0s#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#010#01511493376/11490434 [==============================] - 0s 0us/step\u001b[0m\n\u001b[34mINFO:tensorflow:Using default config.\u001b[0m\n\u001b[34mINFO:tensorflow:Using config: {'_model_dir': 's3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true\u001b[0m\n\u001b[34mgraph_options {\n rewrite_options {\n meta_optimizer_iterations: ONE\n }\u001b[0m\n\u001b[34m}\u001b[0m\n\u001b[34m, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fb77f42d1d0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:114: The name tf.estimator.inputs.numpy_input_fn is deprecated. Please use tf.compat.v1.estimator.inputs.numpy_input_fn instead.\n\u001b[0m\n\u001b[34m[2020-04-27 23:59:39.646 ip-10-0-201-124.us-east-2.compute.internal:26 INFO json_config.py:90] Creating hook from json_config at /opt/ml/input/config/debughookconfig.json.\u001b[0m\n\u001b[34m[2020-04-27 23:59:39.647 ip-10-0-201-124.us-east-2.compute.internal:26 INFO hook.py:183] tensorboard_dir has not been set for the hook. SMDebug will not be exporting tensorboard summaries.\u001b[0m\n\u001b[34m[2020-04-27 23:59:39.647 ip-10-0-201-124.us-east-2.compute.internal:26 INFO hook.py:228] Saving to /opt/ml/output/tensors\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py:62: QueueRunner.__init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mTo construct input pipelines, use the `tf.data` module.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py:62: QueueRunner.__init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mTo construct input pipelines, use the `tf.data` module.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_functions.py:500: add_queue_runner (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mTo construct input pipelines, use the `tf.data` module.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_functions.py:500: add_queue_runner (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mTo construct input pipelines, use the `tf.data` module.\u001b[0m\n\u001b[34mINFO:tensorflow:Calling model_fn.\u001b[0m\n\u001b[34mINFO:tensorflow:Calling model_fn.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:54: conv2d (from tensorflow.python.layers.convolutional) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse `tf.keras.layers.Conv2D` instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:54: conv2d (from tensorflow.python.layers.convolutional) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse `tf.keras.layers.Conv2D` instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/layers/convolutional.py:424: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mPlease use `layer.__call__` method instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/layers/convolutional.py:424: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mPlease use `layer.__call__` method instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:58: max_pooling2d (from tensorflow.python.layers.pooling) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse keras.layers.MaxPooling2D instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:58: max_pooling2d (from tensorflow.python.layers.pooling) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse keras.layers.MaxPooling2D instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:68: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse keras.layers.Dense instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:68: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse keras.layers.Dense instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:70: dropout (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse keras.layers.dropout instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:70: dropout (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse keras.layers.dropout instead.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:88: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:88: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/losses/losses_impl.py:121: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse tf.where in 2.0, which has the same broadcast rule as np.where\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/losses/losses_impl.py:121: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse tf.where in 2.0, which has the same broadcast rule as np.where\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:92: The name tf.train.GradientDescentOptimizer is deprecated. Please use tf.compat.v1.train.GradientDescentOptimizer instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:92: The name tf.train.GradientDescentOptimizer is deprecated. Please use tf.compat.v1.train.GradientDescentOptimizer instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:93: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:93: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n\u001b[0m\n\u001b[34mINFO:tensorflow:Done calling model_fn.\u001b[0m\n\u001b[34mINFO:tensorflow:Done calling model_fn.\u001b[0m\n\u001b[34mINFO:tensorflow:Create CheckpointSaverHook.\u001b[0m\n\u001b[34mINFO:tensorflow:Create CheckpointSaverHook.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/horovod/tensorflow/__init__.py:117: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/horovod/tensorflow/__init__.py:117: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/horovod/tensorflow/__init__.py:143: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/horovod/tensorflow/__init__.py:143: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n\u001b[0m\n\u001b[34m[2020-04-27 23:59:40.256 ip-10-0-201-124.us-east-2.compute.internal:26 INFO hook.py:364] Monitoring the collections: gradients, losses, sm_metrics, metrics\u001b[0m\n\u001b[34mINFO:tensorflow:Graph was finalized.\u001b[0m\n\u001b[34mINFO:tensorflow:Graph was finalized.\u001b[0m\n\u001b[34mINFO:tensorflow:Running local_init_op.\u001b[0m\n\u001b[34mINFO:tensorflow:Running local_init_op.\u001b[0m\n\u001b[34mINFO:tensorflow:Done running local_init_op.\u001b[0m\n\u001b[34mINFO:tensorflow:Done running local_init_op.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/monitored_session.py:888: start_queue_runners (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mTo construct input pipelines, use the `tf.data` module.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/monitored_session.py:888: start_queue_runners (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mTo construct input pipelines, use the `tf.data` module.\u001b[0m\n\u001b[34mINFO:tensorflow:Saving checkpoints for 0 into s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt.\u001b[0m\n\u001b[34mINFO:tensorflow:Saving checkpoints for 0 into s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt.\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/smdebug/tensorflow/session.py:304: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse `tf.compat.v1.graph_util.extract_sub_graph`\u001b[0m\n\u001b[34mWARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/smdebug/tensorflow/session.py:304: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\u001b[0m\n\u001b[34mInstructions for updating:\u001b[0m\n\u001b[34mUse `tf.compat.v1.graph_util.extract_sub_graph`\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.3208826, step = 1\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.3208826, step = 1\u001b[0m\n\u001b[34mERROR:root:'NoneType' object has no attribute 'write'\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 7.73273\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 7.73273\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2985032, step = 101 (12.933 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2985032, step = 101 (12.933 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.0584\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.0584\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2796118, step = 201 (12.409 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2796118, step = 201 (12.409 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.16216\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.16216\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2400365, step = 301 (12.252 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2400365, step = 301 (12.252 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.20902\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.20902\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.244422, step = 401 (12.182 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.244422, step = 401 (12.182 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.29027\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.29027\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2057943, step = 501 (12.062 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.2057943, step = 501 (12.062 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.12505\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.12505\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.1722574, step = 601 (12.308 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.1722574, step = 601 (12.308 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.21211\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.21211\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.126483, step = 701 (12.177 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.126483, step = 701 (12.177 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.54074\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.54074\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.0739117, step = 801 (11.708 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.0739117, step = 801 (11.708 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.60594\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.60594\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.023419, step = 901 (11.620 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 2.023419, step = 901 (11.620 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.60855\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.60855\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.9700434, step = 1001 (11.791 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.9700434, step = 1001 (11.791 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.33646\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.33646\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.8422208, step = 1101 (11.821 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.8422208, step = 1101 (11.821 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.58772\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.58772\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.7151158, step = 1201 (11.644 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.7151158, step = 1201 (11.644 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.54481\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.54481\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.4826751, step = 1301 (11.703 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.4826751, step = 1301 (11.703 sec)\u001b[0m\n\n2020-04-28 00:02:39 Uploading - Uploading generated training model\u001b[34mINFO:tensorflow:global_step/sec: 8.40044\u001b[0m\n\u001b[34mINFO:tensorflow:global_step/sec: 8.40044\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.3823929, step = 1401 (11.904 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:loss = 1.3823929, step = 1401 (11.904 sec)\u001b[0m\n\u001b[34mINFO:tensorflow:Saving checkpoints for 1407 into s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt.\u001b[0m\n\u001b[34mINFO:tensorflow:Saving checkpoints for 1407 into s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt.\u001b[0m\n\u001b[34mINFO:tensorflow:Loss for final step: 1.3139015.\u001b[0m\n\u001b[34mINFO:tensorflow:Loss for final step: 1.3139015.\u001b[0m\n\u001b[34mINFO:tensorflow:Calling model_fn.\u001b[0m\n\u001b[34mINFO:tensorflow:Calling model_fn.\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:98: The name tf.metrics.accuracy is deprecated. Please use tf.compat.v1.metrics.accuracy instead.\n\u001b[0m\n\u001b[34mWARNING:tensorflow:From mnist_zerocodechange.py:98: The name tf.metrics.accuracy is deprecated. Please use tf.compat.v1.metrics.accuracy instead.\n\u001b[0m\n\u001b[34mINFO:tensorflow:Done calling model_fn.\u001b[0m\n\u001b[34mINFO:tensorflow:Done calling model_fn.\u001b[0m\n\u001b[34mINFO:tensorflow:Starting evaluation at 2020-04-28T00:02:32Z\u001b[0m\n\u001b[34mINFO:tensorflow:Starting evaluation at 2020-04-28T00:02:32Z\u001b[0m\n\u001b[34m[2020-04-28 00:02:32.878 ip-10-0-201-124.us-east-2.compute.internal:26 INFO hook.py:364] Monitoring the collections: gradients, losses, sm_metrics, metrics\u001b[0m\n\u001b[34mINFO:tensorflow:Graph was finalized.\u001b[0m\n\u001b[34mINFO:tensorflow:Graph was finalized.\u001b[0m\n\u001b[34mINFO:tensorflow:Restoring parameters from s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt-1407\u001b[0m\n\u001b[34mINFO:tensorflow:Restoring parameters from s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt-1407\u001b[0m\n\u001b[34mINFO:tensorflow:Running local_init_op.\u001b[0m\n\u001b[34mINFO:tensorflow:Running local_init_op.\u001b[0m\n\u001b[34mINFO:tensorflow:Done running local_init_op.\u001b[0m\n\u001b[34mINFO:tensorflow:Done running local_init_op.\u001b[0m\n\u001b[34mINFO:tensorflow:Finished evaluation at 2020-04-28-00:02:36\u001b[0m\n\u001b[34mINFO:tensorflow:Finished evaluation at 2020-04-28-00:02:36\u001b[0m\n\u001b[34mINFO:tensorflow:Saving dict for global step 1407: accuracy = 0.7942, global_step = 1407, loss = 1.2718687\u001b[0m\n\u001b[34mINFO:tensorflow:Saving dict for global step 1407: accuracy = 0.7942, global_step = 1407, loss = 1.2718687\u001b[0m\n\u001b[34mINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1407: s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt-1407\u001b[0m\n\u001b[34mINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1407: s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/model/model.ckpt-1407\u001b[0m\n\u001b[34m[2020-04-28 00:02:37.390 ip-10-0-201-124.us-east-2.compute.internal:26 INFO utils.py:25] The end of training job file will not be written for jobs running under SageMaker.\u001b[0m\n\u001b[34m2020-04-28 00:02:37,661 sagemaker_tensorflow_container.training WARNING No model artifact is saved under path /opt/ml/model. Your training job will not save any model files to S3.\u001b[0m\n\u001b[34mFor details of how to construct your training script see:\u001b[0m\n\u001b[34mhttps://sagemaker.readthedocs.io/en/stable/using_tf.html#adapting-your-local-tensorflow-script\u001b[0m\n\u001b[34m2020-04-28 00:02:37,662 sagemaker-containers INFO Reporting training SUCCESS\u001b[0m\n\n2020-04-28 00:03:10 Completed - Training job completed\n\n********* Debugger Rule Status *********\n*\n* VanishingGradient: NoIssuesFound \n* LossNotDecreasing: NoIssuesFound \n*\n****************************************\nTraining seconds: 241\nBillable seconds: 241\n"
]
],
[
[
"## Result \n\nAs a result of calling the `fit()` Amazon SageMaker Debugger kicked off two rule evaluation jobs to monitor vanishing gradient and loss decrease, in parallel with the training job. The rule evaluation status(es) will be visible in the training logs at regular intervals. As you can see, in the summary, there was no step in the training which reported vanishing gradients in the tensors. Although, the loss was not found to be decreasing at step 1900.",
"_____no_output_____"
]
],
[
[
"estimator.latest_training_job.rule_job_summary()",
"_____no_output_____"
]
],
[
[
"Let's try and look at the logs of the rule job for loss not decreasing. To do that, we'll use this utlity function to get a link to the rule job logs.",
"_____no_output_____"
]
],
[
[
"def _get_rule_job_name(training_job_name, rule_configuration_name, rule_job_arn):\n \"\"\"Helper function to get the rule job name with correct casing\"\"\"\n return \"{}-{}-{}\".format(\n training_job_name[:26], rule_configuration_name[:26], rule_job_arn[-8:]\n )\n \ndef _get_cw_url_for_rule_job(rule_job_name, region):\n return \"https://{}.console.aws.amazon.com/cloudwatch/home?region={}#logStream:group=/aws/sagemaker/ProcessingJobs;prefix={};streamFilter=typeLogStreamPrefix\".format(region, region, rule_job_name)\n\n\ndef get_rule_jobs_cw_urls(estimator):\n region = boto3.Session().region_name\n training_job = estimator.latest_training_job\n training_job_name = training_job.describe()[\"TrainingJobName\"]\n rule_eval_statuses = training_job.describe()[\"DebugRuleEvaluationStatuses\"]\n \n result={}\n for status in rule_eval_statuses:\n if status.get(\"RuleEvaluationJobArn\", None) is not None:\n rule_job_name = _get_rule_job_name(training_job_name, status[\"RuleConfigurationName\"], status[\"RuleEvaluationJobArn\"])\n result[status[\"RuleConfigurationName\"]] = _get_cw_url_for_rule_job(rule_job_name, region)\n return result\n\nget_rule_jobs_cw_urls(estimator)",
"_____no_output_____"
]
],
[
[
"## Data Analysis - Interactive Exploration\nNow that we have trained a job, and looked at automated analysis through rules, let us also look at another aspect of Amazon SageMaker Debugger. It allows us to perform interactive exploration of the tensors saved in real time or after the job. Here we focus on after-the-fact analysis of the above job. We import the `smdebug` library, which defines a concept of Trial that represents a single training run. Note how we fetch the path to debugger artifacts for the above job.",
"_____no_output_____"
]
],
[
[
"from smdebug.trials import create_trial\ntrial = create_trial(estimator.latest_job_debugger_artifacts_path())",
"[2020-04-28 00:07:09.068 f8455ab5c5ab:546 INFO s3_trial.py:42] Loading trial debug-output at path s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/debug-output\n"
]
],
[
[
"We can list all the tensors that were recorded to know what we want to plot. Each one of these names is the name of a tensor, which is auto-assigned by TensorFlow. In some frameworks where such names are not available, we try to create a name based on the layer's name and whether it is weight, bias, gradient, input or output.",
"_____no_output_____"
]
],
[
[
"trial.tensor_names()",
"[2020-04-28 00:07:11.217 f8455ab5c5ab:546 INFO trial.py:198] Training has ended, will refresh one final time in 1 sec.\n[2020-04-28 00:07:12.236 f8455ab5c5ab:546 INFO trial.py:210] Loaded all steps\n"
]
],
[
[
"We can also retrieve tensors by some default collections that `smdebug` creates from your training job. Here we are interested in the losses collection, so we can retrieve the names of tensors in losses collection as follows. Amazon SageMaker Debugger creates default collections such as weights, gradients, biases, losses automatically. You can also create custom collections from your tensors.",
"_____no_output_____"
]
],
[
[
"trial.tensor_names(collection=\"losses\")",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport re\n\n# Define a function that, for the given tensor name, walks through all \n# the iterations for which we have data and fetches the value.\n# Returns the set of steps and the values\ndef get_data(trial, tname):\n tensor = trial.tensor(tname)\n steps = tensor.steps()\n vals = [tensor.value(s) for s in steps]\n return steps, vals\n\ndef plot_tensors(trial, collection_name, ylabel=''):\n \"\"\"\n Takes a `trial` and plots all tensors that match the given regex.\n \"\"\"\n plt.figure(\n num=1, figsize=(8, 8), dpi=80,\n facecolor='w', edgecolor='k')\n\n tensors = trial.tensor_names(collection=collection_name)\n\n for tensor_name in sorted(tensors):\n steps, data = get_data(trial, tensor_name)\n plt.plot(steps, data, label=tensor_name)\n\n plt.legend(bbox_to_anchor=(1.04,1), loc='upper left')\n plt.xlabel('Iteration')\n plt.ylabel(ylabel)\n plt.show()\n \nplot_tensors(trial, \"losses\", ylabel=\"Loss\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e789c3529fe25a6e539bc5f2f444f75f8450ecf0 | 88,885 | ipynb | Jupyter Notebook | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale | 091df5518c25b50ef523a803ac747c63be76f670 | [
"CC0-1.0"
] | null | null | null | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale | 091df5518c25b50ef523a803ac747c63be76f670 | [
"CC0-1.0"
] | null | null | null | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale | 091df5518c25b50ef523a803ac747c63be76f670 | [
"CC0-1.0"
] | null | null | null | 69.933124 | 42,476 | 0.825269 | [
[
[
"# Récursivité",
"_____no_output_____"
],
[
"## Introduction",
"_____no_output_____"
],
[
"**Objectifs**:\n- Comprendre que des problèmes complexes qui peuvent être difficiles à résoudre avec les «techniques habituelles» peuvent avoir une solution récursive simple,\n- Apprendre à formuler des programmes récursivement,\n- Comprendre et appliquer les trois lois de la récursivité,\n- Comprendre la récursivité comme une forme d'itération,\n- Implémenter une solution récursive à un problème,\n- Comprendre comment la récursion fonctionne à bas niveau.",
"_____no_output_____"
],
[
"La récursivité est une *méthode de résolution de problème*. Elle consiste à **découper le problème, puis les sous-problèmes obtenus ... jusqu'à obtenir des sous-problèmes si petits qu'ils puissent être résolus de façon directe**. ",
"_____no_output_____"
],
[
"Ordinairement, la récursivité nécessite qu'une fonction s'appelle **elle-même**.",
"_____no_output_____"
],
[
"## Exemple de la somme d'une liste de nombres",
"_____no_output_____"
],
[
"Pour illustrer le propos, considérons le problème classique qui consiste à *calculer la somme d'une liste de nombres*. \n\nVoici sa solution «classique»:",
"_____no_output_____"
]
],
[
[
"def sommer(nbs):\n somme = 0 # accu\n for nb in nbs:\n somme = somme + nb # ou somme += nb\n return somme\n\nassert sommer([5, 4, 7]) == 16",
"_____no_output_____"
]
],
[
[
"La somme se produit alors comme suit: $$\n(\\underbrace{\n (\\underbrace{\n (\\underbrace{(0+5)}_{\\text{it. 1}\n } +4)\n }_{\\text{it. 2}}+7)\n}_{\\text{it. 3}})\n$$",
"_____no_output_____"
],
[
"Mais supposez un instant que nous ne disposions ni de boucle `while`, ni de boucle `for`.",
"_____no_output_____"
],
[
"Comme mathématiquement: \n\n$$(((5) + 4)+7)=5+4+7=(5+(4+(7)))$$",
"_____no_output_____"
],
[
"nous pouvons utiliser la dernière expression pour découper simplement le problème en deux parties:",
"_____no_output_____"
],
[
"1. Récupérer le *premier* nombre de la liste: `5`,",
"_____no_output_____"
],
[
"2. calculer la somme des nombres *restants*: `sommer([4, 7])`,",
"_____no_output_____"
],
[
"3. ajouter les valeurs obtenues aux deux premières étapes: `5 + sommer([4, 7])`.",
"_____no_output_____"
],
[
"Les points 1. et 3. sont élémentaires et le **point 2.** est un problème **similaire** au problème initial **mais plus petit**.",
"_____no_output_____"
],
[
"On peut alors réappliquer **le même** découpage à ce sous-problème ... jusqu'à obtenir un sous-problème **si petit** qu'on puisse le *résoudre directement*: \n> si la liste à sommer ne contient qu'un nombre, sa somme est simplement ce nombre.",
"_____no_output_____"
],
[
"Pour notre exemple cela donne: \n\n```\nsommer([5, 4, 7]) = 5 + sommer([4, 7])\n sommer([4, 7]) = 4 + sommer([7])\n sommer([7]) = 7\n = 4 + 7\n = 5 + 11\n= 16\n```",
"_____no_output_____"
],
[
"ou en «applatissant»:\n```\nsommer([5, 4, 7]) = 5 + sommer([4, 7])\n = 5 + (4 + sommer([7]))\n = 5 + (4 + (7))\n = 5 + (4 + 7)\n = 5 + 11\n = 16\n```",
"_____no_output_____"
],
[
"En généralisant, cela donne:\n\n``` \nsommer(nbs) = \n nbs[0] si taille nbs vaut 1\n nbs[0] + sommer(nbs[1:]) sinon\n```",
"_____no_output_____"
],
[
"ou en paraphrasant l'étape «récursive» (la deuxième):\n> Pour sommer des nombres, ajouter le premier à la *somme* de ceux qui restent.",
"_____no_output_____"
],
[
"Python (comme la plupart des langages de programmation) autorise qu'une fonction *s'appelle elle-même*. Nous expliquerons plus tard comment cela est possible.",
"_____no_output_____"
],
[
"Voici donc une **solution récursive** au problème de la somme:",
"_____no_output_____"
]
],
[
[
"def sommer(nbs):\n # cas où le problème est suffisemment petit\n if len(nbs) == 1:\n return nbs[0]\n \n # si le problème est trop gros\n else:\n # découpage\n premier, *reste = nbs # ou premier = nbs[0]; reste = nbs[1:]\n # résolution du sous-pb en appelant **cette** fonction\n somme_reste = sommer(reste)\n # combinaison\n return premier + somme_reste\n\nassert sommer([5, 4, 7]) == 16",
"_____no_output_____"
]
],
[
[
"En utilisant la **composition** et les **tranches** \\[*slices*\\], on peut exprimer cela de façon plus concise:",
"_____no_output_____"
]
],
[
[
"def sommer(nbs):\n if len(nbs) == 1: return nbs[0] # cas de base\n return nbs[0] + sommer(nbs[1:]) # appel récursif\n\nassert sommer([5, 4, 7]) == 16",
"_____no_output_____"
]
],
[
[
"voir dans [Python Tutor](http://pythontutor.com/visualize.html#code=def%20sommer%28nbs%29%3A%0A%20%20%20%20if%20len%28nbs%29%20%3D%3D%201%3A%20return%20nbs%5B0%5D%0A%20%20%20%20return%20nbs%5B0%5D%20%2B%20sommer%28nbs%5B1%3A%5D%29%0A%0Aprint%28sommer%28%5B5,%204,%207%5D%29%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)",
"_____no_output_____"
],
[
"Encore plus court en utilisant l'opérateur ternaire `expr1 if cond else expr2`",
"_____no_output_____"
]
],
[
[
"def sommer(nbs):\n return nbs[0] + sommer(nbs[1:]) if len(nbs) > 1 else nbs[0]\n\nassert sommer([5, 4, 7]) == 16",
"_____no_output_____"
]
],
[
[
"Voici les **points clés** de ce code:",
"_____no_output_____"
],
[
"1. On commence par vérifier si on est dans le **cas de base**: celui d'un problème suffisemment simple pour être résolu directement. C'est notre garde fou...!",
"_____no_output_____"
],
[
"2. **Récursion**: Si on est pas dans le cas de base, notre fonction *s'appelle elle-même* - on appelle cela un **appel récursif** - avec un argument qui exprime un problème plus simple - `[4, 7]` - par rapport à l'argument initial - `[5, 4, 7]`.",
"_____no_output_____"
],
[
"### Illustrations",
"_____no_output_____"
],
[
"Les numéros entourés précisent l'ordre des événements:",
"_____no_output_____"
],
[
"<center><img src=\"attachment:c8bcee87-5b73-46b5-9641-f79e4cdd1908.png\"/></center>",
"_____no_output_____"
],
[
"En voici une autre en «poupées russes»:",
"_____no_output_____"
],
[
"<center><img src=\"attachment:4a19a908-1a18-4158-a155-1c3b252c9ce0.png\"/></center>",
"_____no_output_____"
],
[
"### Visualiser les appels et retours",
"_____no_output_____"
],
[
"Pour visualiser cela depuis le code, on peut utiliser des `print`:",
"_____no_output_____"
]
],
[
[
"def sommer_voir(nbs):\n print(f'appel de sommer({nbs})')\n \n if len(nbs) == 1: \n print(f'retour de sommer({nbs}): -> {nbs[0]}')\n return nbs[0]\n \n reste = sommer_voir(nbs[1:])\n print(f'retour de sommer({nbs}): {nbs[0]} + {reste} -> {nbs[0] + reste}')\n return nbs[0] + reste\n\nsommer_voir([5, 4, 7]) == 16",
"_____no_output_____"
]
],
[
[
"On peut même mieux voir l'imbrication des appels en décalant le texte affiché en fonction de l'ordre d'appel:",
"_____no_output_____"
]
],
[
[
"def sommer_voir(nbs, n=0):\n dec = ' ' * n # niveau de décalage\n print(f'{dec}appel de sommer({nbs})')\n \n if len(nbs) == 1: \n print(f'{dec}retour de sommer({nbs}): -> {nbs[0]}')\n return nbs[0]\n \n reste = sommer_voir(nbs[1:], n+1)\n print(f'{dec}retour de sommer({nbs}): {nbs[0]} + {reste} -> {nbs[0] + reste}')\n return nbs[0] + reste\n\nsommer_voir([4, 7, 36, 12, 28])",
"_____no_output_____"
]
],
[
[
"## Synthèse",
"_____no_output_____"
],
[
"Un **algorithme récursif** doit respecter les trois lois qui suivent:",
"_____no_output_____"
],
[
"1. Il doit posséder un (ou plusieurs) **cas de base(s)**: problème(s) si simple(s) qu'on peut le(s) résoudre directement,",
"_____no_output_____"
],
[
"2. Il doit modifier son état de façon à **progresser** vers l'un des cas de bases: **partage** du problème en sous-problèmes,",
"_____no_output_____"
],
[
"3. Il doit s'appeler lui-même, on dit **récursivement**.",
"_____no_output_____"
],
[
"Pour notre exemple:",
"_____no_output_____"
],
[
"1. **cas de base**: liste de taille 1, le résultat est son unique élément,",
"_____no_output_____"
],
[
"2. **partage**: la liste initiale est scindée en:\n - son *premier élément*,\n - les éléments *restants*: ils sont moins nombreux qu'initialement et on se rapproche donc du cas de base (*progression*).",
"_____no_output_____"
],
[
"3. **s'appelle lui-même**: on appelle récursivement la fonction sur les éléments *restants*.",
"_____no_output_____"
],
[
"## Exercices",
"_____no_output_____"
],
[
"### Exercice 1",
"_____no_output_____"
],
[
"On définit la **factorielle d'un entier positif ou nul** $n$ comme le produit de tous les entiers de $1$ à $n$ (inclus). En mathématique, elle se note $n!$ (lire «factorielle $n$»).\n\nPar exemple: $4!=1\\times 2\\times 3\\times 4=24$.\n\nOn peut aussi définir la factorielle d'un entier de façon **récursive**: \n\n$$n!=\\left\\{\\begin{array}{l}\n1\\text{ si } n\\in\\{0;1\\}\\cr\nn\\times (n-1)! \\text{ sinon}\n\\end{array}\\right.$$\n\nPar exemple: $$\\begin{eqnarray}\n4!&=&4\\times 3!\\cr\n&=& 4\\times (3\\times 2!)\\cr\n&=& 4\\times (3\\times (2\\times 1!))\\cr\n&=& 4\\times (3\\times (2\\times 1))\\cr\n&=& 24\\end{eqnarray}$$\n\nDéfinir une fonction *récursive* `fact` qui prend un entier positif en argument et renvoie sa factorielle.",
"_____no_output_____"
]
],
[
[
"def fact(n):\n pass",
"_____no_output_____"
]
],
[
[
"**Solution**",
"_____no_output_____"
]
],
[
[
"def fact(n):\n if n > 1: return n * fact(n - 1)\n return 1\n\nfact(4)",
"_____no_output_____"
]
],
[
[
"***",
"_____no_output_____"
],
[
"### Exercice 2",
"_____no_output_____"
],
[
"Définir de façon récursive `puissance(x, n)` qui calcule $x^n$ (comment passe-t-on de $x^{n-1}$ à $x^n$)",
"_____no_output_____"
]
],
[
[
"def puissance(x, n):\n pass",
"_____no_output_____"
]
],
[
[
"**Solution**",
"_____no_output_____"
]
],
[
[
"def puissance(x, n):\n if n > 0: return x * puissance(x, n-1)\n return 1 # x^0=1 quel que soit x\n\nassert puissance(2, 10) == 1024",
"_____no_output_____"
]
],
[
[
"***",
"_____no_output_____"
],
[
"### Exercice 3",
"_____no_output_____"
],
[
"Définir de façon récursive `maximum(nbs)` qui renvoie la plus grande valeur de la liste `nbs`.",
"_____no_output_____"
]
],
[
[
"def maximum(nbs):\n pass",
"_____no_output_____"
]
],
[
[
"**Solution**",
"_____no_output_____"
]
],
[
[
"def maximum(nbs):\n if len(nbs) == 1: return nbs[0]\n prem, *reste = nbs\n m = maximum(reste)\n return m if m > prem else prem\n\nassert maximum([2, 5, -1, 12, 3]) == 12",
"_____no_output_____"
]
],
[
[
"***",
"_____no_output_____"
],
[
"### Exercice 4",
"_____no_output_____"
],
[
"1. Définir de façon récursive `base2(n)` qui renvoie l'écriture en base 2 de l'entier positif $n$ (sous la forme d'une chaîne de caractères).",
"_____no_output_____"
]
],
[
[
"def base2(n):\n pass",
"_____no_output_____"
]
],
[
[
"**Solution**",
"_____no_output_____"
]
],
[
[
"def base2(n):\n if n in [0, 1]: return str(n)\n q, r = n // 2, n % 2\n return base2(q) + str(r)\n\nassert base2(13) == '1101' # 1huit+1quatre+0deux+1un",
"_____no_output_____"
]
],
[
[
"2. De même, définir récursivement `base16(n)`",
"_____no_output_____"
]
],
[
[
"def base16(n):\n pass",
"_____no_output_____"
]
],
[
[
"**Solution**",
"_____no_output_____"
]
],
[
[
"def base16(n):\n if n in list(range(10)): return str(n)\n d = {10: \"A\", 11: \"B\", 12: \"C\", 13: \"D\", 14: \"E\", 15: \"F\"}\n if n in d: return d[n]\n q, r = n // 16, n % 16\n return base16(q) + base16(r)\n\nassert base16(43) == '2B' # 2 seize + B un",
"_____no_output_____"
]
],
[
[
"***",
"_____no_output_____"
],
[
"### Exercice 5",
"_____no_output_____"
],
[
"En tenant compte de l'observation suivante:\n> si $q$ et $r$ sont respectivement le quotient et le reste de la division euclidienne de $n$ par $2$, alors $n=2q+r$ et: \n>\n>$$x^n=x^{2q+r}=x^{2q}x^r=(x^{q})^{2}x^r$$\n\nredéfinir de façon récursive la fonction `puissance(x, n)` de l'exercice 2.",
"_____no_output_____"
]
],
[
[
"def puissance_bis(x, n):\n pass\n\nassert puissance_bis(2, 10) == 1024\nassert puissance_bis(5, 3) == 125",
"_____no_output_____"
]
],
[
[
"**Solution**",
"_____no_output_____"
]
],
[
[
"def puissance_bis(x, n):\n if n == 0: return 1\n q, r = n // 2, n % 2\n tmp = puissance_bis(x, q)\n return tmp * tmp * (1 if r == 0 else x)\n\nassert puissance_bis(2, 10) == 1024\nassert puissance_bis(5, 3) == 125",
"_____no_output_____"
]
],
[
[
"Exécuter alors les cellules qui suivent:\n\n*Note*: `%timeit` est une directive spéciale des notebooks qui permet de mesurer le temps moyen mis par une fonction pour s'exécuter.",
"_____no_output_____"
]
],
[
[
"%timeit puissance_bis(2, 1024)",
"_____no_output_____"
],
[
"%timeit puissance(2, 1024)",
"_____no_output_____"
],
[
"%timeit 23 ** 50",
"_____no_output_____"
]
],
[
[
"Comment expliquer les différences observées?",
"_____no_output_____"
],
[
"Si $n=2^{10}$: $$x^{2^{10}}=\\left(x^{2^{9}}\\right)^2=\\left(\\left(x^{2^{8}}\\right)^2 \\right)^2=\\dots$$\nCela doit vous faire «sentir» qu'il y aura $10$ appels récursifs (et non $1024$), autrement dit $\\log_2(n)$ appels récursifs...",
"_____no_output_____"
],
[
"***",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
e789c6223c90d6b11f209103aebca9e630542a1c | 53,140 | ipynb | Jupyter Notebook | numpy_practice.ipynb | ftconan/numpy_tutorial | 0cca229357e975e3a30fe099f2d1a3158b1712ca | [
"MIT"
] | null | null | null | numpy_practice.ipynb | ftconan/numpy_tutorial | 0cca229357e975e3a30fe099f2d1a3158b1712ca | [
"MIT"
] | null | null | null | numpy_practice.ipynb | ftconan/numpy_tutorial | 0cca229357e975e3a30fe099f2d1a3158b1712ca | [
"MIT"
] | null | null | null | 25.160985 | 232 | 0.473391 | [
[
[
"import numpy as np",
"_____no_output_____"
],
[
"# 1、导入numpy作为np,并查看版本\nnp.__version__",
"_____no_output_____"
],
[
"# 2、如何创建一维数组?\narr = np.arange(10)\narr",
"_____no_output_____"
],
[
"# 3. 如何创建一个布尔数组?\nnp.full((3, 3), True, dtype=bool)\n\n# Alternate method:\nnp.ones((3,3), dtype=bool)",
"_____no_output_____"
],
[
"# 4. 如何从一维数组中提取满足指定条件的元素?\n# input\narr = np.array([0,1,2,3,4,5,6,7,8,9])\n\n# Solution\narr[arr % 2 == 1]",
"_____no_output_____"
],
[
"# 5. 如何用numpy数组中的另一个值替换满足条件的元素项?\narr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\narr[arr % 2 == 1] = -1\narr",
"_____no_output_____"
],
[
"# 6. 如何在不影响原始数组的情况下替换满足条件的元素项?\narr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\nout = np.where(arr % 2 == 1, -1, arr)\nprint(arr)\nout",
"[0 1 2 3 4 5 6 7 8 9]\n"
],
[
"# 7. 如何改变数组的形状?\n# input\narr = np.arange(10)\n\narr.reshape(2, -1)",
"_____no_output_____"
],
[
"# 8. 如何垂直叠加两个数组?\n# input \na = np.arange(10).reshape(2, -1)\nb = np.repeat(1, 10).reshape(2, -1)\n\nnp.concatenate([a, b], axis=1)\n\n# np.hstack([a, b])\n\n# np.c_[a, b]",
"_____no_output_____"
],
[
"# 10. 如何在无硬编码的情况下生成numpy中的自定义序列?\n# input \na = np.array([1,2,3])\n\nnp.r_[np.repeat(a,3), np.tile(a,3)]",
"_____no_output_____"
],
[
"# 11. 如何获取两个numpy数组之间的公共项?\n# input\na = np.array([1,2,3,2,3,4,3,4,5,6])\nb = np.array([7,2,10,2,7,4,9,4,9,8])\n\nnp.intersect1d(a, b)",
"_____no_output_____"
],
[
"# 12. 如何从一个数组中删除存在于另一个数组中的项?\n# input\na = np.array([1,2,3,4,5])\nb = np.array([5,6,7,8,9])\n\nnp.setdiff1d(a, b)",
"_____no_output_____"
],
[
"# 13. 如何得到两个数组元素匹配的位置?\n# input\na = np.array([1,2,3,2,3,4,3,4,5,6])\nb = np.array([7,2,10,2,7,4,9,4,9,8])\n\nnp.where(a == b)",
"_____no_output_____"
],
[
"# 14. 如何从numpy数组中提取给定范围内的所有数字?\n# input \na = np.arange(15)\n\nindex = np.where((a >= 5) & (a <= 10))\na[index]\n\nindex = np.where(np.logical_and(a>=5, a<=10))\na[index]\n\na[(a >= 5) & (a <= 10)]",
"_____no_output_____"
],
[
"# 15. 如何创建一个python函数来处理scalars并在numpy数组上工作?\n# input\ndef maxx(x, y):\n \"\"\"\n Get the maximum of two items\n \"\"\"\n if x >= y:\n return x\n else:\n return y\n \npair_max = np.vectorize(maxx, otypes=[float])\na = np.array([5, 7, 9, 8, 6, 4, 5])\nb = np.array([6, 3, 4, 8, 9, 7, 1])\n\npair_max(a, b)",
"_____no_output_____"
],
[
"# 16. 如何交换二维numpy数组中的两列?\n# input\narr = np.arange(9).reshape(3,3)\n\narr[:, [1,0,2]]",
"_____no_output_____"
],
[
"# 17. 如何交换二维numpy数组中的两行?\n# input\narr = np.arange(9).reshape(3,3)\n\narr[[1,0,2],:]",
"_____no_output_____"
],
[
"# 18. 如何反转二维数组的行?\n# input\narr = np.arange(9).reshape(3,3)\n\narr[::-1]",
"_____no_output_____"
],
[
"# 19. 如何反转二维数组的列?\n# input\narr = np.arange(9).reshape(3,3)\n\narr[:, ::-1]",
"_____no_output_____"
],
[
"# 20. 如何创建包含5到10之间随机浮动的二维数组?\n# input\narr = np.arange(9).reshape(3,3)\n\nrand_arr = np.random.randint(low=5, high=10, size=(5,3)) + np.random.random((5,3))\nprint(rand_arr)\n\nrand_arr = np.random.uniform(5,10, size=(5,3))\nprint(rand_arr)",
"[[5.83324485 9.11264899 5.62102214]\n [8.90329542 7.92795401 5.09063659]\n [7.07766163 7.5416475 5.20600689]\n [5.7473502 6.92799137 5.10984294]\n [9.76542382 9.39143882 8.12676812]]\n[[8.34973364 8.61858126 5.62465369]\n [9.56098291 8.44790994 6.05900427]\n [8.65649496 6.42933142 6.2398012 ]\n [6.53948937 5.10838042 7.92418224]\n [5.00120129 7.91160146 8.34387512]]\n"
],
[
"# 21. 如何在numpy数组中只打印小数点后三位?\n# input\nrand_arr = np.random.random((5,3))\n\nnp.set_printoptions(precision=3)\nrand_arr[:4]",
"_____no_output_____"
],
[
"# 22. 如何通过e式科学记数法(如1e10)来打印一个numpy数组?\n# input\nnp.random.seed(100)\nrand_arr = np.random.random([3,3])/1e3\nrand_arr\n\n#np.set_printoptions(suppress=False)\n#rand_arr = np.random.random([3,3])/1e3\n#rand_arr\n\n#np.set_printoptions(suppress=True, precision=6)\n# rand_arr",
"_____no_output_____"
],
[
"# 23. 如何限制numpy数组输出中打印的项目数?\n# input\na = np.arange(15)\n\nnp.set_printoptions(threshold=6)\na = np.arange(15)\na",
"_____no_output_____"
],
[
"# 24. 打印完整的numpy数组a而不截断。\n# input \nnp.set_printoptions(threshold=6)\na = np.arange(15)\n\nnp.set_printoptions(threshold=np.nan)\na",
"_____no_output_____"
],
[
"# 25. 如何导入数字和文本的数据集保持文本在numpy数组中完好无损?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\n\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\n\niris[:3]",
"_____no_output_____"
],
[
"# 26. 如何从1维元组数组中提取特定列?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_1d = np.genfromtxt(url, delimiter=',', dtype=None)\nprint(iris_1d.shape)\n\nspecies = np.array([row[4] for row in iris_1d])\nspecies[:5]",
"(150,)\n"
],
[
"# 27. 如何将1维元组数组转换为2维numpy数组?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_1d = np.genfromtxt(url, delimiter=',', dtype=None)\n\niris_2d = np.array([row.tolist()[:4] for row in iris_1d])\niris_2d[:4]\n\niris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])\niris_2d[:4]",
"/usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py:4: VisibleDeprecationWarning: Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.\n after removing the cwd from sys.path.\n"
],
[
"# 28. 如何计算numpy数组的均值,中位数,标准差?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nsepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])\n\nmu, med, sd = np.mean(sepallength), np.mean(sepallength), np.std(sepallength)\nprint(mu, med, sd)",
"5.843333333333334 5.843333333333334 0.8253012917851409\n"
],
[
"# 29. 如何规范化数组,使数组的值正好介于0和1之间?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\nsepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])\n\nSmax, Smin = sepallength.max(), sepallength.min()\nS = (sepallength - Smin)/(Smax - Smin)\n\nS = (sepallength -Smin)/sepallength.ptp()\nS",
"_____no_output_____"
],
[
"# 30. 如何计算Softmax得分?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nsepallength = np.array([float(row[0]) for row in iris])\n\ndef softmax(x):\n \"\"\"\n softmax\n \"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0)\n\nprint(softmax(sepallength))",
"[0.002 0.002 0.001 0.001 0.002 0.003 0.001 0.002 0.001 0.002 0.003 0.002\n 0.002 0.001 0.004 0.004 0.003 0.002 0.004 0.002 0.003 0.002 0.001 0.002\n 0.002 0.002 0.002 0.002 0.002 0.001 0.002 0.003 0.002 0.003 0.002 0.002\n 0.003 0.002 0.001 0.002 0.002 0.001 0.001 0.002 0.002 0.002 0.002 0.001\n 0.003 0.002 0.015 0.008 0.013 0.003 0.009 0.004 0.007 0.002 0.01 0.002\n 0.002 0.005 0.005 0.006 0.004 0.011 0.004 0.004 0.007 0.004 0.005 0.006\n 0.007 0.006 0.008 0.01 0.012 0.011 0.005 0.004 0.003 0.003 0.004 0.005\n 0.003 0.005 0.011 0.007 0.004 0.003 0.003 0.006 0.004 0.002 0.004 0.004\n 0.004 0.007 0.002 0.004 0.007 0.004 0.016 0.007 0.009 0.027 0.002 0.02\n 0.011 0.018 0.009 0.008 0.012 0.004 0.004 0.008 0.009 0.03 0.03 0.005\n 0.013 0.004 0.03 0.007 0.011 0.018 0.007 0.006 0.008 0.018 0.022 0.037\n 0.008 0.007 0.006 0.03 0.007 0.008 0.005 0.013 0.011 0.013 0.004 0.012\n 0.011 0.011 0.007 0.009 0.007 0.005]\n"
],
[
"# 31. 如何找到numpy数组的百分位数?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\nsepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])\n\nnp.percentile(sepallength, q=[5, 95])",
"_____no_output_____"
],
[
"# 32. 如何在数组中的随机位置插入值?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(url, delimiter=',', dtype='object')\n\ni, j = np.where(iris_2d)\nnp.random.seed(100)\niris_2d[np.random.choice((i), 20), np.random.choice((j), 20)] = np.nan\n\nnp.random.seed(100)\niris_2d[np.random.choice(150, size=20), np.random.randint(4, size=20)] = np.nan\n\nprint(iris_2d[:10])",
"[[b'5.1' b'3.5' b'1.4' b'0.2' b'Iris-setosa']\n [b'4.9' b'3.0' b'1.4' b'0.2' b'Iris-setosa']\n [b'4.7' b'3.2' b'1.3' b'0.2' b'Iris-setosa']\n [b'4.6' b'3.1' b'1.5' b'0.2' b'Iris-setosa']\n [b'5.0' b'3.6' b'1.4' b'0.2' b'Iris-setosa']\n [b'5.4' b'3.9' b'1.7' b'0.4' b'Iris-setosa']\n [b'4.6' b'3.4' b'1.4' b'0.3' b'Iris-setosa']\n [b'5.0' b'3.4' b'1.5' b'0.2' b'Iris-setosa']\n [b'4.4' nan b'1.4' b'0.2' b'Iris-setosa']\n [b'4.9' b'3.1' b'1.5' b'0.1' b'Iris-setosa']]\n"
],
[
"# 33. 如何在numpy数组中找到缺失值的位置?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(url, delimiter=',', dtype='float')\niris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan\n\nprint('Number of missing values: \\n', np.isnan(iris_2d[:, 0]).sum())\nprint('Position of missing values: \\n', np.where(np.isnan(iris_2d[:, 0])))",
"Number of missing values: \n 5\nPosition of missing values: \n (array([ 38, 80, 106, 113, 121]),)\n"
],
[
"# 34. 如何根据两个或多个条件过滤numpy数组?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])\n\ncondition = (iris_2d[:, 2] > 1.5) & (iris_2d[:, 0] < 5.0)\niris_2d[condition]",
"_____no_output_____"
],
[
"# 35. 如何从numpy数组中删除包含缺失值的行?\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])\n\nany_nan_in_row = np.array([~np.any(row) for row in iris_2d])\niris_2d[any_nan_in_row][:5]\n\niris_2d[np.sum(np.isnan(iris_2d), axis=1) == 0][:5]",
"_____no_output_____"
],
[
"# 36. 如何找到numpy数组的两列之间的相关性?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])\n\n# Solution 1\nnp.corrcoef(iris[:, 0], iris[:, 2])[0, 1]\n\n# Solution 2\nfrom scipy.stats.stats import pearsonr \ncorr, p_value = pearsonr(iris[:, 0], iris[:, 2])\nprint(corr)",
"0.8717541573048712\n"
],
[
"# 37. 如何查找给定数组是否具有任何空值?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])\n\nnp.isnan(iris_2d).any()",
"_____no_output_____"
],
[
"# 38. 如何在numpy数组中用0替换所有缺失值?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])\niris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan\n\niris_2d[np.isnan(iris_2d)] = 0\niris_2d[:4]",
"_____no_output_____"
],
[
"# 39. 如何在numpy数组中查找唯一值的计数?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\nspecies = np.array([row.tolist()[4] for row in iris])\nnp.unique(species, return_counts=False)",
"_____no_output_____"
],
[
"# 40. 如何将数字转换为分类(文本)数组?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\npetal_length_bin = np.digitize(iris[:, 2].astype('float'), [0, 3, 5, 10])\nlabel_map = {1: 'small', 2: 'medium', 3: 'large', 4: np.nan}\npetal_length_cat = [label_map[x] for x in petal_length_bin]\npetal_length_cat[:4]",
"_____no_output_____"
],
[
"# 41. 如何从numpy数组的现有列创建新列?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\nsepallength = iris_2d[:, 0].astype('float')\npetallength = iris_2d[:, 2].astype('float')\nvolume = (np.pi * petallength * (sepallength ** 2))/3\n\nvolume = volume[:, np.newaxis]\n\nout = np.hstack([iris_2d, volume])\nout[:4]",
"_____no_output_____"
],
[
"# 42. 如何在numpy中进行概率抽样?\n# Import iris keeping the text column intact\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\n\nspecies = iris[:, 4]\n\nnp.random.seed(100)\na = np.array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])\nspecies_out = np.random.choice(a, 150, p=[0.5, 0.25, 0.25])\n\nnp.random.seed(100)\nprobs = np.r_[np.linspace(0, 0.500, num=50), np.linspace(0.501, .750, num=50), np.linspace(.751, 1.0, num=50)]\nindex = np.searchsorted(probs, np.random.random(150))\nspecies_out = species[index]\nprint(np.unique(species_out, return_counts=True))",
"(array([b'Iris-setosa', b'Iris-versicolor', b'Iris-virginica'],\n dtype=object), array([77, 37, 36]))\n"
],
[
"# 43. 如何在按另一个数组分组时获取数组的第二大值?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\npetal_len_setosa = iris[iris[:, 4] == b'Iris-setosa', [2]].astype('float')\nnp.unique(np.sort(petal_len_setosa))[-2]",
"_____no_output_____"
],
[
"# 44. 如何按列对2D数组进行排序\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\nprint(iris[iris[:, 0].argsort()][:20])",
"[[b'4.3' b'3.0' b'1.1' b'0.1' b'Iris-setosa']\n [b'4.4' b'3.2' b'1.3' b'0.2' b'Iris-setosa']\n [b'4.4' b'3.0' b'1.3' b'0.2' b'Iris-setosa']\n [b'4.4' b'2.9' b'1.4' b'0.2' b'Iris-setosa']\n [b'4.5' b'2.3' b'1.3' b'0.3' b'Iris-setosa']\n [b'4.6' b'3.6' b'1.0' b'0.2' b'Iris-setosa']\n [b'4.6' b'3.1' b'1.5' b'0.2' b'Iris-setosa']\n [b'4.6' b'3.4' b'1.4' b'0.3' b'Iris-setosa']\n [b'4.6' b'3.2' b'1.4' b'0.2' b'Iris-setosa']\n [b'4.7' b'3.2' b'1.3' b'0.2' b'Iris-setosa']\n [b'4.7' b'3.2' b'1.6' b'0.2' b'Iris-setosa']\n [b'4.8' b'3.0' b'1.4' b'0.1' b'Iris-setosa']\n [b'4.8' b'3.0' b'1.4' b'0.3' b'Iris-setosa']\n [b'4.8' b'3.4' b'1.9' b'0.2' b'Iris-setosa']\n [b'4.8' b'3.4' b'1.6' b'0.2' b'Iris-setosa']\n [b'4.8' b'3.1' b'1.6' b'0.2' b'Iris-setosa']\n [b'4.9' b'2.4' b'3.3' b'1.0' b'Iris-versicolor']\n [b'4.9' b'2.5' b'4.5' b'1.7' b'Iris-virginica']\n [b'4.9' b'3.1' b'1.5' b'0.1' b'Iris-setosa']\n [b'4.9' b'3.1' b'1.5' b'0.1' b'Iris-setosa']]\n"
],
[
"# 45. 如何在numpy数组中找到最常见的值?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\nvals, counts = np.unique(iris[:, 2],return_counts=True)\nprint(vals[np.argmax(counts)])",
"b'1.5'\n"
],
[
"# 46. 如何找到第一次出现的值大于给定值的位置?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\n\nnp.argwhere(iris[:, 3].astype(float) > 1.0)[0]",
"_____no_output_____"
],
[
"# 47. 如何将大于给定值的所有值替换为给定的截止值?\n# Input\nnp.set_printoptions(precision=2)\nnp.random.seed(100)\na = np.random.uniform(1,50, 20)\n\nnp.clip(a, a_min=10, a_max=30)\nprint(np.where(a < 10, 10, np.where(a > 30, 30, a)))",
"[27.63 14.64 21.8 30. 10. 10. 30. 30. 10. 29.18 30. 11.25\n 10.08 10. 11.77 30. 30. 10. 30. 14.43]\n"
],
[
"# 48. 如何从numpy数组中获取最大n值的位置?\n# input\nnp.random.seed(100)\na = np.random.uniform(1,50, 20)\n\nprint(a.argsort())\nnp.argpartition(-a, 5)[:5]\n\na[a.argsort()][-5:]\n\nnp.sort(a)[-5:]\nnp.partition(a, kth=-5)[-5:]\n\na[np.argpartition(-a, 5)][:5]",
"[ 4 13 5 8 17 12 11 14 19 1 2 0 9 6 16 18 7 3 10 15]\n"
],
[
"# 49. 如何计算数组中所有可能值的行数?\n# input\nnp.random.seed(100)\narr = np.random.randint(1,11,size=(6, 10))\narr\n\ndef counts_of_all_values_rowwise(arr2d):\n num_counts_array = [np.unique(row, return_counts=True) for row in arr2d]\n return ([[int(b[a==i]) if i in a else 0 for i in np.unique(arr2d)] for a, b in num_counts_array])\n\nprint(np.arange(1, 11))\ncounts_of_all_values_rowwise(arr)\n\narr = np.array([np.array(list('bill clinton')), np.array(list('narendramodi')), np.array(list('jjayalalitha'))])\nprint(np.unique(arr))\ncounts_of_all_values_rowwise(arr)",
"[ 1 2 3 4 5 6 7 8 9 10]\n[' ' 'a' 'b' 'c' 'd' 'e' 'h' 'i' 'j' 'l' 'm' 'n' 'o' 'r' 't' 'y']\n"
],
[
"# 50. 如何将数组转换为平面一维数组?\n# input\narr1 = np.arange(3)\narr2 = np.arange(3,7)\narr3 = np.arange(7,10)\n\narray_of_arrays = np.array([arr1, arr2, arr3])\nprint('array_of_arrays', array_of_arrays)\n\narr_2d = np.array([a for arr in array_of_arrays for a in arr])\n\narr_2d = np.concatenate(array_of_arrays)\nprint(arr_2d)",
"array_of_arrays [array([0, 1, 2]) array([3, 4, 5, 6]) array([7, 8, 9])]\n[0 1 2 3 4 5 6 7 8 9]\n"
],
[
"# 51. 如何在numpy中为数组生成单热编码?\n# input\nnp.random.seed(101) \narr = np.random.randint(1,4, size=6)\narr\n\ndef one_hot_encodings(arr):\n uniqs = np.unique(arr)\n out = np.zeros((arr.shape[0], uniqs.shape[0]))\n \n for i, k in enumerate(arr):\n out[i, k - 1] = 1\n \n return out\n\none_hot_encodings(arr)\n\n(arr[:, None] == np.unique(arr)).view(np.int8)",
"_____no_output_____"
],
[
"# 52. 如何创建按分类变量分组的行号?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\nspecies = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)\nnp.random.seed(100)\nspecies_small = np.sort(np.random.choice(species, size=20))\nspecies_small\n\nprint([i for val in np.unique(species_small) for i, grp in enumerate(species_small[species_small==val])])",
"[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5]\n"
],
[
"# 53. 如何根据给定的分类变量创建组ID?\n# input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\nspecies = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)\nspecies_small = np.sort(np.random.choice(species, size=20))\nspecies_small\n\noutput = [np.argwhere(np.unique(species_small) == s).tolist()[0][0] for val in np.unique(species_small) for s in species_small[species_small==val]]\n\noutput = []\nuniqs = np.unique(species_small)\n\nfor val in uniqs:\n for s in species_small[species_small==val]:\n groupid = np.argwhere(uniqs == s).tolist()[0][0] # groupid\n output.append(groupid)\n \nprint(output)",
"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2]\n"
],
[
"# 54. 如何使用numpy对数组中的项进行排名?\n# input\nnp.random.seed(10)\na = np.random.randint(20, size=10)\nprint('Array: ', a)\n\nprint(a.argsort().argsort())\nprint('Array: ', a)",
"Array: [ 9 4 15 0 17 16 17 8 9 0]\n[4 2 6 0 8 7 9 3 5 1]\nArray: [ 9 4 15 0 17 16 17 8 9 0]\n"
],
[
"# 55. 如何使用numpy对多维数组中的项进行排名?\n# input\nnp.random.seed(10)\na = np.random.randint(20, size=[2,5])\nprint(a)\n\nprint(a.ravel().argsort().argsort().reshape(a.shape))",
"[[ 9 4 15 0 17]\n [16 17 8 9 0]]\n[[4 2 6 0 8]\n [7 9 3 5 1]]\n"
],
[
"# 56. 如何在二维numpy数组的每一行中找到最大值?\n# input\nnp.random.seed(100)\na = np.random.randint(1,10, [5,3])\na\n\nnp.amax(a, axis=1)\n\nnp.apply_along_axis(np.max, arr=a, axis=1)",
"_____no_output_____"
],
[
"# 57. 如何计算二维numpy数组每行的最小值?\n# input\nnp.random.seed(100)\na = np.random.randint(1,10, [5,3])\na\n\nnp.apply_along_axis(lambda x: np.min(x)/np.max(x), arr=a, axis=1)",
"_____no_output_____"
],
[
"# 58. 如何在numpy数组中找到重复的记录?\n# Input\nnp.random.seed(100)\na = np.random.randint(0, 5, 10)\nprint('Array: ', a)\n\nout = np.full(a.shape[0], True)\nunique_positions = np.unique(a, return_index=True)[1]\n\nout[unique_positions] = False\nprint(out)",
"Array: [0 0 3 0 2 4 2 2 2 2]\n[False True False True False False True True True True]\n"
],
[
"# 59. 如何找出数字的分组均值?\n# Input\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(url, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n\nnumeric_column = iris[:, 1].astype('float')\ngrouping_column = iris[:, 4]\n\n[[group_val, numeric_column[grouping_column==group_val].mean()] for group_val in np.unique(grouping_column)]\n\noutput = []\nfor group_val in np.unique(grouping_column):\n output.append([group_val, numeric_column[grouping_column==group_val].mean()])\n \noutput",
"_____no_output_____"
],
[
"# 60. 如何将PIL图像转换为numpy数组?\n# input\nfrom io import BytesIO\nfrom PIL import Image\nimport PIL, requests\n\n# Import image from URL\nURL = 'https://upload.wikimedia.org/wikipedia/commons/8/8b/Denali_Mt_McKinley.jpg'\nresponse = requests.get(URL)\n\nI = Image.open(BytesIO(response.content))\nI = I.resize([150, 150])\narr = np.array(I)\n\nim = PIL.Image.fromarray(np.uint8(arr))\nImage.Image.show(im)",
"_____no_output_____"
],
[
"# 61. 如何删除numpy数组中所有缺少的值?\n# input\nnp.array([1,2,3,np.nan,5,6,7,np.nan])\n\na[~np.isnan(a)]",
"_____no_output_____"
],
[
"# 62. 如何计算两个数组之间的欧氏距离?\n# Input\na = np.array([1,2,3,4,5])\nb = np.array([4,5,6,7,8])\n\ndist = np.linalg.norm(a - b)\ndist",
"_____no_output_____"
],
[
"# 63. 如何在一维数组中找到所有的局部极大值(或峰值)?\n# input\na = np.array([1, 3, 7, 1, 2, 6, 0, 1])\n\ndoublediff = np.diff(np.sign(np.diff(a)))\npeak_locations = np.where(doublediff == -2)[0] + 1\npeak_locations",
"_____no_output_____"
],
[
"# 64. 如何从二维数组中减去一维数组,其中一维数组的每一项从各自的行中减去?\n# input\na_2d = np.array([[3,3,3],[4,4,4],[5,5,5]])\nb_1d = np.array([1,1,1])\n \nprint(a_2d - b_1d[:, None])",
"[[2 2 2]\n [3 3 3]\n [4 4 4]]\n"
],
[
"# 65. 如何查找数组中项的第n次重复索引?\n# input\nx = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2])\nn = 5\n\n[i for i, v in enumerate(x) if v == 1][n-1]\n\n\nnp.where(x == 1)[0][n - 1]",
"_____no_output_____"
],
[
"# 66. 如何将numpy的datetime 64对象转换为datetime的datetime对象?\n# input\ndt64 = np.datetime64('2018-02-25 22:10:10')\n\nfrom datetime import datetime\ndt64.tolist()\n\ndt64.astype(datetime)",
"_____no_output_____"
],
[
"# 67. 如何计算numpy数组的移动平均值?\n# input \nnp.random.seed(100)\nZ = np.random.randint(10, size=10)\nprint('array: ', Z)\n\ndef moving_average(a, n=3):\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] -ret[:-n]\n \n return ret[n - 1:] / n\n\nmoving_average(Z, n=3).round(3)\n\nnp.convolve(Z, np.ones(3)/3, mode='valid')",
"array: [8 8 3 7 7 0 4 2 5 2]\n"
],
[
"# 68. 如何在给定起始点、长度和步骤的情况下创建一个numpy数组序列?\n# input \nlength = 10\nstart = 5\nstep = 3\n\ndef seq(start, length, step):\n end = start + (step*length)\n return np.arange(start, end, step)\n\nseq(start, length, step)",
"_____no_output_____"
],
[
"# 69. 如何填写不规则系列的numpy日期中的缺失日期?\n# Input\ndates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2)\nprint(dates)\n\nfilled_in = np.array([np.arange(date, (date+d)) for date, d in zip(dates, np.diff(dates))]).reshape(-1)\n\noutput = np.hstack([filled_in, dates[-1]])\noutput\n\nout = []\nfor date, d in zip(dates, np.diff(dates)):\n out.append(np.arange(date, (date+d)))\n\nfilled_in = np.array(out).reshape(-1)\n\noutput = np.hstack([filled_in, dates[-1]])\noutput",
"['2018-02-01' '2018-02-03' '2018-02-05' '2018-02-07' '2018-02-09'\n '2018-02-11' '2018-02-13' '2018-02-15' '2018-02-17' '2018-02-19'\n '2018-02-21' '2018-02-23']\n"
],
[
"# 70. 如何从给定的一维数组创建步长?\n# input\narr = np.arange(15) \narr\n\ndef gen_strides(a, stride_len=5, window_len=5):\n n_strides = ((a.size-window_len)//stride_len) + 1\n # return np.array([a[s:(s+window_len)] for s in np.arange(0, a.size, stride_len)[:n_strides]])\n return np.array([a[s:(s+window_len)] for s in np.arange(0, n_strides*stride_len, stride_len)])\n\nprint(gen_strides(np.arange(15), stride_len=2, window_len=4))",
"[[ 0 1 2 3]\n [ 2 3 4 5]\n [ 4 5 6 7]\n [ 6 7 8 9]\n [ 8 9 10 11]\n [10 11 12 13]]\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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e789c8410bd2ae6839560f5d5bad3ba7893718e4 | 4,808 | ipynb | Jupyter Notebook | ipynb/Senegal.ipynb | oscovida/oscovida.github.io | c74d6da79feda1b5ccce107ad3acd48cf0e74c1c | [
"CC-BY-4.0"
] | 2 | 2020-06-19T09:16:14.000Z | 2021-01-24T17:47:56.000Z | ipynb/Senegal.ipynb | oscovida/oscovida.github.io | c74d6da79feda1b5ccce107ad3acd48cf0e74c1c | [
"CC-BY-4.0"
] | 8 | 2020-04-20T16:49:49.000Z | 2021-12-25T16:54:19.000Z | ipynb/Senegal.ipynb | oscovida/oscovida.github.io | c74d6da79feda1b5ccce107ad3acd48cf0e74c1c | [
"CC-BY-4.0"
] | 4 | 2020-04-20T13:24:45.000Z | 2021-01-29T11:12:12.000Z | 28.790419 | 161 | 0.510399 | [
[
[
"# Senegal\n\n* Homepage of project: https://oscovida.github.io\n* Plots are explained at http://oscovida.github.io/plots.html\n* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Senegal.ipynb)",
"_____no_output_____"
]
],
[
[
"import datetime\nimport time\n\nstart = datetime.datetime.now()\nprint(f\"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}\")",
"_____no_output_____"
],
[
"%config InlineBackend.figure_formats = ['svg']\nfrom oscovida import *",
"_____no_output_____"
],
[
"overview(\"Senegal\", weeks=5);",
"_____no_output_____"
],
[
"overview(\"Senegal\");",
"_____no_output_____"
],
[
"compare_plot(\"Senegal\", normalise=True);\n",
"_____no_output_____"
],
[
"# load the data\ncases, deaths = get_country_data(\"Senegal\")\n\n# get population of the region for future normalisation:\ninhabitants = population(\"Senegal\")\nprint(f'Population of \"Senegal\": {inhabitants} people')\n\n# compose into one table\ntable = compose_dataframe_summary(cases, deaths)\n\n# show tables with up to 1000 rows\npd.set_option(\"max_rows\", 1000)\n\n# display the table\ntable",
"_____no_output_____"
]
],
[
[
"# Explore the data in your web browser\n\n- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Senegal.ipynb)\n- and wait (~1 to 2 minutes)\n- Then press SHIFT+RETURN to advance code cell to code cell\n- See http://jupyter.org for more details on how to use Jupyter Notebook",
"_____no_output_____"
],
[
"# Acknowledgements:\n\n- Johns Hopkins University provides data for countries\n- Robert Koch Institute provides data for within Germany\n- Atlo Team for gathering and providing data from Hungary (https://atlo.team/koronamonitor/)\n- Open source and scientific computing community for the data tools\n- Github for hosting repository and html files\n- Project Jupyter for the Notebook and binder service\n- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))\n\n--------------------",
"_____no_output_____"
]
],
[
[
"print(f\"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and \"\n f\"deaths at {fetch_deaths_last_execution()}.\")",
"_____no_output_____"
],
[
"# to force a fresh download of data, run \"clear_cache()\"",
"_____no_output_____"
],
[
"print(f\"Notebook execution took: {datetime.datetime.now()-start}\")\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
e789cdf0928bbaa7c628feeea123662777127bb8 | 14,301 | ipynb | Jupyter Notebook | docs/notebooks/Importing.ipynb | TheV1rtuoso/debuggingbook | dd4a1605cff793f614e67fbaef74de7d20e0519c | [
"MIT"
] | null | null | null | docs/notebooks/Importing.ipynb | TheV1rtuoso/debuggingbook | dd4a1605cff793f614e67fbaef74de7d20e0519c | [
"MIT"
] | null | null | null | docs/notebooks/Importing.ipynb | TheV1rtuoso/debuggingbook | dd4a1605cff793f614e67fbaef74de7d20e0519c | [
"MIT"
] | null | null | null | 31.224891 | 335 | 0.604293 | [
[
[
"# Using Debuggingbook Code in your own Programs\n\nThis notebook has instructions on how to use the `debuggingbook` code in your own programs.",
"_____no_output_____"
],
[
"In short, there are three ways:\n\n1. Simply run the notebooks in your browser, using the \"mybinder\" environment. Choose \"Resources->Edit as Notebook\" in any of the `fuzzingbook.org` pages; this will lead you to a preconfigured Jupyter Notebook environment where you can toy around at your leisure.\n2. Import the code for your own Python programs. Using `pip install fuzzingbook`, you can install all code and start using it from your own code. See \"Can I import the code for my own Python projects?\", below.\n3. Download or check out the code and/or the notebooks from the project site. This allows you to edit and run all things locally. However, be sure to also install the required packages; see below for details.",
"_____no_output_____"
],
[
"## Can I import the code for my own Python projects?\n\nYes, you can! (If you like Python, that is.) We provide a `debuggingbook` Python package that you can install using the `pip` package manager:\n\n```shell\n$ pip install debuggingbook\n```\n\nAs of `debuggingbook 1.1`, this is set up such that additional required Python packages are also installed. However, also see \"Install Additional Non-Python Packages\" below.\n\nOnce `pip` is complete, you can import individual classes, constants, or functions from each notebook using\n\n```python\n>>> from debuggingbook.<notebook> import <identifier>\n```\n\nwhere `<identifier>` is the name of the class, constant, or function to use, and `<notebook>` is the name of the respective notebook. (If you read this at debuggingbook.org, then the notebook name is the identifier preceding `\".html\"` in the URL).\n\nHere is an example importing `Debugger` from [the chapter on debuggers](Debugger.ipynb), whose notebook name is `Debugger`:\n\n```python\n>>> from debuggingbook.Debugger import Debugger\n>>> with Debugger():\n function_to_be_observed()\n```\n\nThe \"Synopsis\" section at the beginning of a chapter gives a short survey on useful code features you can use.",
"_____no_output_____"
],
[
"## Which OS and Python versions are required?\n\nAs of `debuggingbook 1.1`, Python 3.9 and later is required. Specifically, we use Python 3.9.7 for development and testing. This is also the version to be used if you check out the code from git, and the version you get if you use the debugging book within the \"mybinder\" environment.\n\nTo use the `debuggingbook` code with earlier Python versions, use\n\n```shell\n$ pip install 'debuggingbook=1.0.1'\n```\n\nOur notebooks generally assume a Unix-like environment; the code is tested on Linux and macOS. System-independent code may also run on Windows.",
"_____no_output_____"
],
[
"## Can I use the code from within a Jupyter notebook?\n\nYes, you can! First, you install the `debuggingbook` package (as above); you can then access all code right from your notebook.\n\nAnother way to use the code is to _import the notebooks directly_. Download the notebooks from the menu. Then, add your own notebooks into the same folder. After importing `bookutils`, you can then simply import the code from other notebooks, just as our own notebooks do.\n\nHere is again the above example, importing `Debugger` from [the chapter on debuggers](Debugger.ipynb) – but now from a notebook:",
"_____no_output_____"
]
],
[
[
"import bookutils",
"_____no_output_____"
],
[
"from Debugger import Debugger",
"_____no_output_____"
],
[
"with Debugger():\n x = 1 + 1",
"_____no_output_____"
]
],
[
[
"If you'd like to share your notebook, let us know; we can integrate it in the repository or even in the book.",
"_____no_output_____"
],
[
"## Can I check out the code from git and get the latest and greatest?\n\nYes, you can! We have a few continuous integration (CI) workflows running which do exactly that. After cloning the repository from [the project page](https://github.com/uds-se/debuggingbook/) and installing the additional packages (see below), you can `cd` into `notebooks` and start `jupyter` right away!\n\nThere also is a `Makefile` provided with literally hundreds of targets; most important are the ones we also use in continuous integration:\n\n* `make check-imports` checks whether your code is free of syntax errors\n* `make check-style` checks whether your code is free of type errors\n* `make check-code` runs all derived code, testing it\n* `make check-notebooks` runs all notebooks, testing them\n\nIf you want to contribute to the project, ensure that the above tests run through.\n\nThe `Makefile` has many more, often experimental, targets. `make markdown` creates a `.md` variant in `markdown/`, and there's also `make word` and `make epub`, which are set to create Word and EPUB variants (with mixed results). Try `make help` for commonly used targets.",
"_____no_output_____"
],
[
"## Can I just run the Python code? I mean, without Notebooks?\n\nYes, you can! You can download the code as Python programs; simply select \"Resources → Download Code\" for one chapter or \"Resources → All Code\" for all chapters. These code files can be executed, yielding (hopefully) the same results as the notebooks.\n\nThe code files can also be edited if you wish, but (a) they are very obviously generated from notebooks, (b) therefore not much fun to work with, and (c) if you fix any errors, you'll have to back-propagate them to the notebook before you can make a pull request. Use code files only under severely constrained circumstances.\n\nIf you only want to **use** the Python code, install the code package (see below).",
"_____no_output_____"
],
[
"## Which other Packages do I need to use the Python Modules?\n\nWe have attempted to limit the dependencies to a minimum (sometimes using ugly hacks). Generally speaking, if you encounter that a module `X` is not found, just do `pip install X`. Most notebooks only need modules that are part of the standard Python library.\n\nFor a full list of dependencies, there are two sources.",
"_____no_output_____"
],
[
"### Step 1: Install Required Python Packages\n\nThe [`requirements.txt` file within the project root folder](https://github.com/uds-se/debuggingbook/tree/master/) lists all _Python packages required_.\n\nYou can do\n\n```sh\n$ pip install -r requirements.txt\n```\n\nto install all required packages (but using `pipenv` is preferred; see below).",
"_____no_output_____"
],
[
"### Step 2: Install Additional Non-Python Packages\n\nThe [`apt.txt` file in the `binder/` folder](https://github.com/uds-se/debuggingbook/tree/master/binder) lists all _Linux_ packages required.\n\nIn most cases, however, it suffices to install the `dot` graph drawing program (part of the `graphviz` package). Here are some instructions:",
"_____no_output_____"
],
[
"#### Installing Graphviz on Linux\n\n```sh\n$ sudo apt-get install graphviz\n```\n\nto install it. ",
"_____no_output_____"
],
[
"#### Installing Graphviz on macOS\n\nOn macOS, if you use `conda`, run\n\n```sh\n$ conda install graphviz\n```\n\nIf you use HomeBrew, run\n\n```sh\n$ brew install graphviz\n```",
"_____no_output_____"
],
[
"## Installing the Debuggingbook in an Isolated Environment\n\nIf you wish to install the debuggingbook in an environment that is isolated from your system interpreter,\nwe recommend using [Pipenv](https://pipenv.pypa.io/), which can automatically create a so called *virtual environment* hosting all required packages.\n\nTo accomplish this, please follow these steps:",
"_____no_output_____"
],
[
"### Step 1: Install PyEnv\n\nOptionally install `pyenv` following the [official instructions](https://github.com/pyenv/pyenv#installation) if you are on a Unix operating system.\nIf you are on Windows, consider using [pyenv-win](https://github.com/pyenv-win/pyenv-win) instead.\nThis will allow you to seamlessly install any version of Python.",
"_____no_output_____"
],
[
"### Step 2: Install PipEnv\n\nInstall Pipenv following the official [installation instructions](https://pypi.org/project/pipenv/).\nIf you have `pyenv` installed, Pipenv can automatically download and install the appropriate version of the Python distribution.\nOtherwise, Pipenv will use your system interpreter, which may or may not be the right version.",
"_____no_output_____"
],
[
"### Step 3: Install Python Packages\n\nRun\n\n```sh\n$ pipenv install -r requirements.txt\n``` \n\nin the `debuggingbook` root directory.",
"_____no_output_____"
],
[
"### Step 4: Install Additional Non-Python Packages\n\nSee above for instructions on how to install additional non-python packages.",
"_____no_output_____"
],
[
"### Step 5: Enter the Environment\n\nEnter the environment with \n\n```sh\n$ pipenv shell\n```\n\nwhere you can now execute\n\n```sh\n$ make -k check-code\n```\n\nto run the tests.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e789ce58b805700a8ee2a4abb90ad2dcc6a50d10 | 102,764 | ipynb | Jupyter Notebook | examples/3GPP/Uniformity.ipynb | datactive/bigbang | ea2e9aab156490d1af965409adb60b68291281dc | [
"MIT"
] | 71 | 2016-10-08T18:42:39.000Z | 2022-03-10T10:06:53.000Z | examples/3GPP/Uniformity.ipynb | datactive/bigbang | ea2e9aab156490d1af965409adb60b68291281dc | [
"MIT"
] | 307 | 2016-07-10T17:37:41.000Z | 2022-03-31T16:39:33.000Z | examples/3GPP/Uniformity.ipynb | datactive/bigbang | ea2e9aab156490d1af965409adb60b68291281dc | [
"MIT"
] | 21 | 2016-10-07T23:49:50.000Z | 2022-02-08T17:25:22.000Z | 437.293617 | 95,576 | 0.932476 | [
[
[
"import datetime\nimport pytz\nimport glob\nimport re\n\nimport numpy as np\nimport pandas as pd\n\nimport pylab\nfrom colour import Color\nfrom pylab import cm\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nfrom bigbang import listserv\nfrom bigbang.analysis.listserv import ListservArchive\nfrom bigbang.analysis.listserv import ListservList\nfrom bigbang.visualisation import stackedareachart\nfrom bigbang.visualisation import lines\nfrom bigbang.visualisation import utils\nfrom bigbang.analysis.utils import (\n get_index_of_msgs_with_subject,\n get_index_of_msgs_with_datetime,\n)\nfrom bigbang.visualisation.utils import create_color_palette",
"_____no_output_____"
],
[
"mlist_name = \"3GPP_TSG_CT_WG4\"\nfilepath = f\"path_to_bigbang/archives/3GPP/{mlist_name}.h5\" # change this to your own folder structure\ndf = pd.read_hdf(filepath, 'df')\n\nmlist = ListservList.from_pandas_dataframe(\n df=df,\n name=mlist_name,\n filepath=filepath,\n)\n\nmlist.df = mlist.df[mlist.df['from'].notna()]\nmlist.df = mlist.df[mlist.df['comments-to'].notna()]\n\nstandard_release_info = pd.read_csv(\n \"path_to_bigbang/bigbang/analysis/3GPP_standards_release_dates.csv\", # change this to your own folder structure\n sep=\",\",\n header=2,\n index_col=False,\n)\nstandard_release_info['Start date'] = pd.to_datetime(standard_release_info['Start date'], format='%Y-%m-%d')\nstandard_release_year = [dt.year for dt in standard_release_info['Start date']]\n\n# Entities in Focus\neois = [\n \"huawei.com\",\n \"huawei.comcc\",\n \"tencent.com\",\n \"xiaomi.com\",\n \"chinamobile.com\",\n \"hisilicon.comzte.com.cn\",\n \"chinatelecom.cn\",\n \"chinaunicom.cn\",\n \"catt.cn\",\n \"caict.ac.cn\",\n]",
"_____no_output_____"
],
[
"dic = {}\nfor eoi in eois:\n mask = []\n for index, row in mlist.df.iterrows():\n domains = []\n generator = ListservList.iterator_name_localpart_domain([row[\"from\"]])\n for _, _, domain in generator:\n domains.append(domain)\n generator = ListservList.iterator_name_localpart_domain([row[\"comments-to\"]])\n for _, _, domain in generator:\n domains.append(domain)\n if eoi in domains:\n mask.append(True)\n else:\n mask.append(False)\n \n if any(mask) is True:\n _mlist = ListservList.from_pandas_dataframe(\n df=mlist.df.loc[mask],\n name=mlist_name,\n filepath=filepath,\n )\n _dic = _mlist.get_messagescount(\n header_fields=['from', 'comments-to'], per_address_field='localpart', per_year=True,\n )\n\n dic[eoi] = _dic",
"_____no_output_____"
],
[
"fig, axis = plt.subplots(\n 2, 1,\n figsize=(7, 6),\n sharex=True, sharey='row',\n #gridspec_kw={'height_ratios': [2, 1]},\n facecolor=\"w\", edgecolor=\"k\",\n)\nfig.subplots_adjust(\n hspace=0.05,\n wspace=0.0,\n)\n\neois_colors = create_color_palette(eois, return_dict=True)\nfor coi in eois:\n if coi not in list(dic.keys()):\n continue\n \n data = dic[coi]['from']\n x = list(data.keys())\n ylabels = stackedareachart.get_ylabels(data)\n y = stackedareachart.data_transformation(data, ylabels)\n for iy, ylab in enumerate(ylabels):\n if iy == 0:\n axis[0].plot(\n x,\n y[iy, :],\n color=eois_colors[coi],\n linewidth=3,\n label=coi,\n )\n else:\n axis[0].plot(\n x,\n y[iy, :],\n color=eois_colors[coi],\n linewidth=3,\n )\n \n data = dic[coi]['comments-to']\n x = list(data.keys())\n ylabels = stackedareachart.get_ylabels(data)\n y = stackedareachart.data_transformation(data, ylabels)\n for iy, ylab in enumerate(ylabels):\n axis[1].plot(\n x,\n y[iy, :],\n color=eois_colors[coi],\n linewidth=3,\n )\n \nfor yr in standard_release_year:\n axis[0].axvline(x=yr, linestyle=':', color='k', alpha=0.5, zorder=0)\n axis[1].axvline(x=yr, linestyle=':', color='k', alpha=0.5, zorder=0)\n\naxis[0].set_xlim(2005, 2021)\n#axis[0].set_ylim(0.0, 0.49)\n\naxis[1].set_xlim(2005, 2021)\n#axis[1].set_ylim(0.0, 0.49)\n\naxis[0].set_title(mlist_name)\naxis[1].set_xlabel('Year')\naxis[0].set_ylabel('Nr of send msgs')\naxis[1].set_ylabel('Nr of received msgs')\naxis[0].legend(loc=2, edgecolor='white', facecolor='white', framealpha=0.7)\n\n\"\"\"\nplt.savefig(\n f\"uniformity_messages_coun_{mlist_name}.png\",\n format='png',\n transparent=True,\n dpi=300,\n bbox_inches='tight',\n)#\"\"\"",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
e789d58b67707e5354ee41170f43bbfa924a8739 | 198,145 | ipynb | Jupyter Notebook | notebooks/vb_gauss_biclusters_demo.ipynb | susnato/probml-notebooks | 95a1a1045ed96ce8ca9f59b8664b1356098d427f | [
"MIT"
] | null | null | null | notebooks/vb_gauss_biclusters_demo.ipynb | susnato/probml-notebooks | 95a1a1045ed96ce8ca9f59b8664b1356098d427f | [
"MIT"
] | 1 | 2022-03-30T20:00:48.000Z | 2022-03-30T20:30:42.000Z | notebooks/vb_gauss_biclusters_demo.ipynb | susnato/probml-notebooks | 95a1a1045ed96ce8ca9f59b8664b1356098d427f | [
"MIT"
] | 1 | 2022-02-16T04:34:27.000Z | 2022-02-16T04:34:27.000Z | 667.154882 | 32,162 | 0.932524 | [
[
[
"<a href=\"https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/vb_gauss_biclusters_demo.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"!pip install superimport \n!git clone --depth 1 https://github.com/probml/pyprobml &> /dev/null \n\n",
"Collecting superimport\n Downloading superimport-0.3.4.tar.gz (6.0 kB)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from superimport) (2.23.0)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->superimport) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->superimport) (2021.10.8)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->superimport) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->superimport) (3.0.4)\nBuilding wheels for collected packages: superimport\n Building wheel for superimport (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for superimport: filename=superimport-0.3.4-py3-none-any.whl size=5888 sha256=59226707868d91b7569f803f4c77f5eaba2741a6ae132856793a4e69c7ba7177\n Stored in directory: /root/.cache/pip/wheels/6c/66/dc/337052d868002cf3830606ee34d91d1ceff6a67bf8df982c72\nSuccessfully built superimport\nInstalling collected packages: superimport\nSuccessfully installed superimport-0.3.4\n"
],
[
"!pip install flax",
"Collecting flax\n Downloading flax-0.4.0-py3-none-any.whl (176 kB)\n\u001b[?25l\r\u001b[K |█▉ | 10 kB 17.7 MB/s eta 0:00:01\r\u001b[K |███▊ | 20 kB 24.2 MB/s eta 0:00:01\r\u001b[K |█████▋ | 30 kB 12.6 MB/s eta 0:00:01\r\u001b[K |███████▍ | 40 kB 9.6 MB/s eta 0:00:01\r\u001b[K |█████████▎ | 51 kB 4.6 MB/s eta 0:00:01\r\u001b[K |███████████▏ | 61 kB 4.9 MB/s eta 0:00:01\r\u001b[K |█████████████ | 71 kB 4.5 MB/s eta 0:00:01\r\u001b[K |██████████████▉ | 81 kB 5.0 MB/s eta 0:00:01\r\u001b[K |████████████████▊ | 92 kB 5.0 MB/s eta 0:00:01\r\u001b[K |██████████████████▌ | 102 kB 4.2 MB/s eta 0:00:01\r\u001b[K |████████████████████▍ | 112 kB 4.2 MB/s eta 0:00:01\r\u001b[K |██████████████████████▎ | 122 kB 4.2 MB/s eta 0:00:01\r\u001b[K |████████████████████████ | 133 kB 4.2 MB/s eta 0:00:01\r\u001b[K |██████████████████████████ | 143 kB 4.2 MB/s eta 0:00:01\r\u001b[K |███████████████████████████▉ | 153 kB 4.2 MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▋ | 163 kB 4.2 MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▌| 174 kB 4.2 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 176 kB 4.2 MB/s \n\u001b[?25hRequirement already satisfied: msgpack in /usr/local/lib/python3.7/dist-packages (from flax) (1.0.3)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from flax) (3.2.2)\nCollecting optax\n Downloading optax-0.1.0-py3-none-any.whl (126 kB)\n\u001b[?25l\r\u001b[K |██▋ | 10 kB 21.1 MB/s eta 0:00:01\r\u001b[K |█████▏ | 20 kB 28.5 MB/s eta 0:00:01\r\u001b[K |███████▊ | 30 kB 35.5 MB/s eta 0:00:01\r\u001b[K |██████████▎ | 40 kB 39.7 MB/s eta 0:00:01\r\u001b[K |█████████████ | 51 kB 40.6 MB/s eta 0:00:01\r\u001b[K |███████████████▌ | 61 kB 44.5 MB/s eta 0:00:01\r\u001b[K |██████████████████ | 71 kB 32.6 MB/s eta 0:00:01\r\u001b[K |████████████████████▋ | 81 kB 34.0 MB/s eta 0:00:01\r\u001b[K |███████████████████████▎ | 92 kB 30.0 MB/s eta 0:00:01\r\u001b[K |█████████████████████████▉ | 102 kB 25.6 MB/s eta 0:00:01\r\u001b[K |████████████████████████████▍ | 112 kB 25.6 MB/s eta 0:00:01\r\u001b[K |███████████████████████████████ | 122 kB 25.6 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 126 kB 25.6 MB/s \n\u001b[?25hRequirement already satisfied: jax>=0.2.21 in /usr/local/lib/python3.7/dist-packages (from flax) (0.2.25)\nRequirement already satisfied: numpy>=1.12 in /usr/local/lib/python3.7/dist-packages (from flax) (1.19.5)\nRequirement already satisfied: opt-einsum in /usr/local/lib/python3.7/dist-packages (from jax>=0.2.21->flax) (3.3.0)\nRequirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from jax>=0.2.21->flax) (1.0.0)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from jax>=0.2.21->flax) (3.10.0.2)\nRequirement already satisfied: scipy>=1.2.1 in /usr/local/lib/python3.7/dist-packages (from jax>=0.2.21->flax) (1.4.1)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from absl-py->jax>=0.2.21->flax) (1.15.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->flax) (3.0.7)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->flax) (1.3.2)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->flax) (2.8.2)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->flax) (0.11.0)\nRequirement already satisfied: jaxlib>=0.1.37 in /usr/local/lib/python3.7/dist-packages (from optax->flax) (0.1.71+cuda111)\nCollecting chex>=0.0.4\n Downloading chex-0.1.0-py3-none-any.whl (65 kB)\n\u001b[K |████████████████████████████████| 65 kB 3.0 MB/s \n\u001b[?25hRequirement already satisfied: toolz>=0.9.0 in /usr/local/lib/python3.7/dist-packages (from chex>=0.0.4->optax->flax) (0.11.2)\nRequirement already satisfied: dm-tree>=0.1.5 in /usr/local/lib/python3.7/dist-packages (from chex>=0.0.4->optax->flax) (0.1.6)\nRequirement already satisfied: flatbuffers<3.0,>=1.12 in /usr/local/lib/python3.7/dist-packages (from jaxlib>=0.1.37->optax->flax) (2.0)\nInstalling collected packages: chex, optax, flax\nSuccessfully installed chex-0.1.0 flax-0.4.0 optax-0.1.0\n"
],
[
"%run pyprobml/scripts/vb_gauss_cholesky_biclusters_demo.py",
"INFO:absl:Unable to initialize backend 'tpu_driver': NOT_FOUND: Unable to find driver in registry given worker: \nINFO:absl:Unable to initialize backend 'gpu': FAILED_PRECONDITION: No visible GPU devices.\nINFO:absl:Unable to initialize backend 'tpu': INVALID_ARGUMENT: TpuPlatform is not available.\nWARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)\n"
],
[
"plt.show()\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e789e1158f7252f2115fa8b70e3ed6c4539bca82 | 259,258 | ipynb | Jupyter Notebook | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia | 2f3d0a1eca0e3163565a17dcb35074e0808ed176 | [
"Apache-2.0"
] | null | null | null | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia | 2f3d0a1eca0e3163565a17dcb35074e0808ed176 | [
"Apache-2.0"
] | null | null | null | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia | 2f3d0a1eca0e3163565a17dcb35074e0808ed176 | [
"Apache-2.0"
] | 2 | 2020-08-03T13:02:06.000Z | 2020-11-04T03:15:44.000Z | 457.24515 | 25,520 | 0.946096 | [
[
[
"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score as auc\nfrom sklearn.metrics import roc_curve, f1_score, balanced_accuracy_score, accuracy_score\nfrom sklearn.metrics import confusion_matrix as cm\nimport matplotlib.pyplot as plt\nimport nltk",
"_____no_output_____"
],
[
"def return_no_words(x):\n x = nltk.tokenize.word_tokenize(x)\n return len(x)",
"_____no_output_____"
],
[
"def report_results(results_path):\n results = pd.read_csv(results_path)\n # 1 prediction distribution of aggression\n # 0 negative prediction distribution of aggression\n plt.hist([results[\"y_predict_prob_1\"],results[\"y_predict_prob_0\"]])\n plt.ylim(0, 25000)\n\n # predict.prob scores\n fpr, tpr, thrshold = roc_curve(results[\"y_true_bool\"], results[\"y_predict_prob_1\"])\n roc_auc = auc(results[\"y_true_bool\"], results[\"y_predict_prob_1\"])\n print(\"AUC score\", roc_auc)\n plt.figure()\n lw = 2\n plt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n # predict scores\n fpr, tpr, thrshold = roc_curve(results[\"y_true_binary\"], results[\"y_prediction\"])\n roc_auc = auc(results[\"y_true_binary\"], results[\"y_prediction\"])\n print(\"AUC score\", roc_auc)\n # Confusion Matrix\n tn, fp, fn, tp = cm(y_true=results[\"y_true_binary\"], y_pred=results[\"y_prediction\"]).ravel()\n print(\"CM\", tn, fp, fn, tp)\n F1_score = f1_score(y_true=results[\"y_true_binary\"], y_pred=results[\"y_prediction\"])\n print(\"F1-score\", F1_score)\n #imbalanced accuracy score - NOT TO Trust\n imbalanced_accuracy_score = accuracy_score(y_true=results[\"y_true_binary\"], y_pred=results[\"y_prediction\"])\n print(\"imbalanced_accuracy_score\", imbalanced_accuracy_score)",
"_____no_output_____"
]
],
[
[
"# Aggression linear word oh",
"_____no_output_____"
]
],
[
[
"report_results(\"linear_word_oh_aggression_prediction_results.csv\")",
"AUC score 0.9434281464773387\n"
]
],
[
[
"# Aggression linear char oh",
"_____no_output_____"
]
],
[
[
"report_results(\"linear_char_oh_aggression_prediction_results.csv\")",
"AUC score 0.9173706304487989\n"
]
],
[
[
"# Aggression mlp word oh",
"_____no_output_____"
]
],
[
[
"report_results(\"mlp_word_oh_aggression_prediction_results.csv\")",
"AUC score 0.9413535359427857\n"
]
],
[
[
"# Aggression mlp char oh",
"_____no_output_____"
]
],
[
[
"report_results(\"mlp_char_oh_aggression_prediction_results.csv\")",
"AUC score 0.9377764851936341\n"
]
],
[
[
"# Agression lstm word",
"_____no_output_____"
]
],
[
[
"report_results(\"lstm_word_oh_aggression_prediction_results.csv\")",
"AUC score 0.9555933152450244\n"
]
],
[
[
"# Aggression lstm char",
"_____no_output_____"
]
],
[
[
"report_results(\"lstm_char_oh_aggression_prediction_results.csv\")",
"AUC score 0.7929897055078095\n"
]
],
[
[
"# aggression conv-lstm word",
"_____no_output_____"
]
],
[
[
"report_results(\"conv_lstm_word_oh_aggression_prediction_results.csv\")",
"AUC score 0.9002429773190748\n"
]
],
[
[
"# aggression conv-lstm char",
"_____no_output_____"
]
],
[
[
"report_results(\"conv_lstm_char_oh_aggression_prediction_results.csv\")",
"AUC score 0.9298119174163423\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e789ec7ed9c439a1632f83010e337f04cd767415 | 18,945 | ipynb | Jupyter Notebook | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml | 502dce1f81fd13f8f78f5af23248ff7edfc7137d | [
"MIT"
] | 3 | 2020-09-15T18:17:40.000Z | 2020-10-19T09:47:07.000Z | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml | 502dce1f81fd13f8f78f5af23248ff7edfc7137d | [
"MIT"
] | null | null | null | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml | 502dce1f81fd13f8f78f5af23248ff7edfc7137d | [
"MIT"
] | null | null | null | 27.377168 | 121 | 0.411876 | [
[
[
"# starting with preprocessed data as done in 04_feature_engineering.ipynb\nfrom utils.utils_04 import *",
"_____no_output_____"
],
[
"xTrain.head()",
"_____no_output_____"
]
],
[
[
"# Individual Classifiers",
"_____no_output_____"
],
[
"## Gaussian Naive Bayes",
"_____no_output_____"
]
],
[
[
"from sklearn.naive_bayes import GaussianNB\nestimator = GaussianNB()\n\nparam_grid = {}\n\ngnb_best_score_, gnb_best_params_ = parameterTune(estimator, param_grid)\ngnb_df = test_eval(GaussianNB, gnb_best_params_)",
"_____no_output_____"
],
[
"print('best_score_:',gnb_best_score_,'\\nbest_params_:',gnb_best_params_)",
"best_score_: 0.7677044755508129 \nbest_params_: {}\n"
]
],
[
[
"## Logistic Regression",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LogisticRegression\nestimator = LogisticRegression(tol=1e-4, solver='liblinear', random_state=1)\n\nparam_grid = {\n 'max_iter' : [1000, 2000, 3000],\n 'penalty' : ['l1', 'l2'],\n 'solver' : ['liblinear']\n}\n\nlrc_best_score_, lrc_best_params_ = parameterTune(estimator, param_grid)\nlrc_df = test_eval(LogisticRegression, lrc_best_params_)",
"_____no_output_____"
],
[
"print('best_score_:',lrc_best_score_,'\\nbest_params_:',lrc_best_params_)",
"best_score_: 0.8260247316552632 \nbest_params_: {'max_iter': 1000, 'penalty': 'l1', 'solver': 'liblinear'}\n"
]
],
[
[
"## K-Neighbors Classifier",
"_____no_output_____"
]
],
[
[
"from sklearn.neighbors import KNeighborsClassifier\nestimator = KNeighborsClassifier()\n\nparam_grid = {\n 'n_neighbors' : [3, 5, 7, 10],\n 'weights' : ['uniform', 'distance'],\n 'p' : [1, 2]\n}\n\nknn_best_score_, knn_best_params_ = parameterTune(estimator, param_grid)\nknn_df = test_eval(KNeighborsClassifier, knn_best_params_)",
"_____no_output_____"
],
[
"print('best_score_:',knn_best_score_,'\\nbest_params_:',knn_best_params_)",
"best_score_: 0.8282907538760906 \nbest_params_: {'n_neighbors': 10, 'p': 1, 'weights': 'uniform'}\n"
]
],
[
[
"## Support Vector Classifier",
"_____no_output_____"
]
],
[
[
"from sklearn.svm import SVC\nestimator = SVC()\n\nparam_grid = [\n { 'kernel' : ['linear'],\n 'C' : [0.1, 1, 10, 100]},\n \n { 'kernel' : ['rbf'],\n 'C' : [0.1, 1, 10, 100],\n 'gamma' : ['scale', 'auto', 1e-1, 1e-2, 1e-3, 1e-4],},\n]\n\nsvc_best_score_, svc_best_params_ = parameterTune(estimator, param_grid)\nsvc_df = test_eval(SVC, svc_best_params_)",
"_____no_output_____"
],
[
"print('best_score_:',svc_best_score_,'\\nbest_params_:',svc_best_params_)",
"best_score_: 0.8372418555018518 \nbest_params_: {'C': 100, 'gamma': 0.01, 'kernel': 'rbf'}\n"
]
],
[
[
"# Ensembles",
"_____no_output_____"
],
[
"## 1. Bagging",
"_____no_output_____"
],
[
"## Random Forest Classifier",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier\nestimator = RandomForestClassifier()\n\nparam_grid = {\n 'n_estimators' : [50, 100, 250, 500, 750, 1000],\n 'criterion' : [\"gini\", \"entropy\"],\n 'max_depth' : [2,5,10,15,20],\n 'max_features' : [\"auto\",\"sqrt\"],\n}\n\nrfc_best_score_, rfc_best_params_ = parameterTune(estimator, param_grid)\nrfc_df = test_eval(RandomForestClassifier, rfc_best_params_)",
"_____no_output_____"
],
[
"print('best_score_:',rfc_best_score_,'\\nbest_params_:',rfc_best_params_)",
"best_score_: 0.8338773460548616 \nbest_params_: {'criterion': 'gini', 'max_depth': 5, 'max_features': 'auto', 'n_estimators': 500}\n"
]
],
[
[
"## 2. Boosting",
"_____no_output_____"
],
[
"## AdaBoostClassifier",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import AdaBoostClassifier\nestimator = AdaBoostClassifier()\n\nparam_grid = {\n 'n_estimators' : [20, 50, 100, 250],\n}\n\nadb_best_score_, adb_best_params_ = parameterTune(estimator, param_grid)\nadb_df = test_eval(AdaBoostClassifier, adb_best_params_)",
"_____no_output_____"
],
[
"print('best_score_:',adb_best_score_,'\\nbest_params_:',adb_best_params_)",
"best_score_: 0.8249513527085558 \nbest_params_: {'n_estimators': 50}\n"
]
],
[
[
"## GradientBoostingClassifier",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import GradientBoostingClassifier\nestimator = GradientBoostingClassifier()\n\nparam_grid = {\n 'loss' : ['deviance', 'exponential'],\n 'learning_rate' : [0.1, 0.01],\n 'n_estimators' : [100, 250, 500],\n 'subsample' : [0.75, 0.9, 1.0],\n 'max_depth' : [1, 2, 3, 5, 7],\n}\n\ngdb_best_score_, gdb_best_params_ = parameterTune(estimator, param_grid)\ngdb_df = test_eval(GradientBoostingClassifier, gdb_best_params_)",
"_____no_output_____"
],
[
"print('best_score_:',gdb_best_score_,'\\nbest_params_:',gdb_best_params_)",
"best_score_: 0.8473667691921412 \nbest_params_: {'learning_rate': 0.1, 'loss': 'deviance', 'max_depth': 2, 'n_estimators': 250, 'subsample': 0.9}\n"
]
],
[
[
"# Submission File",
"_____no_output_____"
]
],
[
[
"pd.DataFrame({\n 'GaussianNB' : gnb_best_score_,\n 'LogisticRegression' : lrc_best_score_,\n 'KNeighborsClassifier' : knn_best_score_,\n 'SVC' : svc_best_score_,\n 'RandomForestClassifier' : rfc_best_score_,\n 'AdaBoostClassifier' : adb_best_score_,\n 'GradientBoostingClassifier' : gdb_best_score_\n}, index=['Accuracy'])",
"_____no_output_____"
],
[
"best_params = {\n 'GaussianNB' : gnb_best_params_,\n 'LogisticRegression' : lrc_best_params_,\n 'KNeighborsClassifier' : knn_best_params_,\n 'SVC' : svc_best_params_,\n 'RandomForestClassifier' : rfc_best_params_,\n 'AdaBoostClassifier' : adb_best_params_,\n 'GradientBoostingClassifier' : gdb_best_params_\n}\n\nwith open(\"./results/05_.json\", 'w') as file:\n json.dump(best_params, file)",
"_____no_output_____"
],
[
"#adb_df.to_csv('./results/05_01_adb.csv', index=None) #0.76315\n#gdb_df.to_csv('./results/05_02_gdb.csv', index=None) #0.77033",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e789f61125cefe1c6c2e4f08fa4c4ec61887b562 | 6,093 | ipynb | Jupyter Notebook | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook | b194955856181e4006a3174151370847cbdd9f1e | [
"MIT"
] | null | null | null | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook | b194955856181e4006a3174151370847cbdd9f1e | [
"MIT"
] | null | null | null | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook | b194955856181e4006a3174151370847cbdd9f1e | [
"MIT"
] | null | null | null | 24.869388 | 119 | 0.544888 | [
[
[
"# Tipos de Muestreo",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as signal\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
]
],
[
[
"## Funciones para el Muestreo",
"_____no_output_____"
]
],
[
[
"def mIdeal(senal,t_senal,Ts,Fs_orig):\n #tomo una muestra cada Ts y guardo en un vector\n senal_mues1 = senal[np.arange(0,len(senal),int(np.round(Ts*Fs_orig)))]\n #creo un vector de tiempos asociado a la muestras\n t_ideal = t_senal[np.arange(0,len(senal),int(np.round(Ts*Fs_orig)))]\n #t_ideal = np.arange(0,len(senal_mues1)*Ts,Ts)\n return t_ideal, senal_mues1",
"_____no_output_____"
]
],
[
[
"## Funcion para la Transformada de Fourier",
"_____no_output_____"
]
],
[
[
"def TFourier(signal,fs,unidadesx):#unidadesx = 0 en Hz, 1 rad/s\n FFT = abs(np.fft.fftshift(np.fft.fft(signal)))\n nFFT = len(FFT)\n fFFT = np.arange(-nFFT/2,nFFT/2)*(fs/nFFT)\n if unidadesx == 1:\n fFFT= fFFT*2*np.pi\n return fFFT,FFT",
"_____no_output_____"
]
],
[
[
"## Señales",
"_____no_output_____"
]
],
[
[
"# Se lavanta senial de un archivo separado por comas (.csv)\npath_ECG = './external_files/ECG.csv'\nsenal_ECG = np.genfromtxt(path_ECG, delimiter=',')",
"_____no_output_____"
],
[
"fs_ECG = 1000 # Hz: frecuencia la cual fueron muestrados los datos originales, que se simulan como analogicos\nt_ECG = np.arange(0,len(senal_ECG)/fs_ECG,1/fs_ECG)\n\n# Calculo de la T.Fourier\nfFFT_ECG,FFT_ECG = TFourier(senal_ECG,fs_ECG,0)",
"_____no_output_____"
],
[
"# Graficacion de la senial y su espectro\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 8))\nax1.plot(t_ECG,senal_ECG)\nax1.set_title(\"Señal Original de ECG\")\nax1.set_xlabel(\"Tiempo [s]\")\nax1.set_ylabel(\"Amplitud\")\nax1.grid(linestyle='--')\nax2.plot(fFFT_ECG,FFT_ECG)\nax2.set_xlim([-60,60])\nax2.set_title(\"Transformada de Fourier de señal de ECG\")\nax2.set_xlabel(\"Frecuencia [Hz]\")\nax2.set_ylabel(\"Amplitud\")\nax2.grid(linestyle='--')\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"## Muestreo Ideal",
"_____no_output_____"
]
],
[
[
"# Identifico la frecuencia maxima de la \nfmax_ECG = 60 #a partir del espectro veo que la frecuencia \nfs_muest_ECG = 2*fmax_ECG*1.25\nTs_ECG = 1/fs_muest_ECG",
"_____no_output_____"
],
[
"# Se realiza el muestreo ideal\nt_ideal, sign_ideal = mIdeal(senal_ECG,t_ECG,Ts_ECG,fs_ECG)\n\nt_min = -0.1\nt_max = 3.0\n\n# Graficacion\nfig, (ax1,ax2) = plt.subplots(2, 1, figsize=(16, 12))\nax1.stem(t_ideal,sign_ideal)\nax1.set_xlim(t_min,t_max)\nax1.set_title(\"Señal muestreada idealmente\")\nax1.set_xlabel(\"Tiempo [s]\")\nax1.set_ylabel(\"Amplitud\")\nax1.grid(linestyle='--')\n\nax2.stem(t_ideal,sign_ideal)\nax2.plot(t_ECG,senal_ECG,'--r')\nax2.set_xlim(t_min,t_max)\nax2.set_title(\"Señal Muestreada y Original\")\nax2.set_xlabel(\"Tiempo [s]\")\nax2.set_ylabel(\"Amplitud\")\nax2.grid(linestyle='--')\nax2.legend(['Señal Original','Muestreo ideal'])\n\nfig2, (ax3) = plt.subplots(1, 1, figsize=(16, 12))\nax3.stem(t_ideal,sign_ideal)\nax3.plot(t_ECG,senal_ECG,'--r')\nax3.set_xlim(0.5,1.1)\nax3.set_title(\"Señal Muestreada y Original\")\nax3.set_xlabel(\"Tiempo [s]\")\nax3.set_ylabel(\"Amplitud\")\nax3.grid(linestyle='--')\nax3.legend(['Señal Original','Muestreo ideal'])\n\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e789fb6a28fc5e447a94b729f6d5662246672780 | 99,770 | ipynb | Jupyter Notebook | Data Visualization/Matplotlib/4. Histogram.ipynb | shreejitverma/Data-Scientist | 03c06936e957f93182bb18362b01383e5775ffb1 | [
"MIT"
] | 2 | 2022-03-12T04:53:03.000Z | 2022-03-27T12:39:21.000Z | Data Visualization/.ipynb_checkpoints/Histogram-checkpoint.ipynb | shreejitverma/Data-Scientist | 03c06936e957f93182bb18362b01383e5775ffb1 | [
"MIT"
] | null | null | null | Data Visualization/.ipynb_checkpoints/Histogram-checkpoint.ipynb | shreejitverma/Data-Scientist | 03c06936e957f93182bb18362b01383e5775ffb1 | [
"MIT"
] | 2 | 2022-03-12T04:52:21.000Z | 2022-03-27T12:45:32.000Z | 417.447699 | 14,438 | 0.938669 | [
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n%matplotlib inline ",
"_____no_output_____"
]
],
[
[
"# Histogram",
"_____no_output_____"
]
],
[
[
"x = np.random.normal(size = 2000)\nplt.hist(x, bins=40, color='yellowgreen')\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()",
"_____no_output_____"
],
[
"x = np.random.rand(2000)\nplt.hist(x, bins=30 ,color='#D4AC0D')\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()",
"_____no_output_____"
],
[
"# Using Edge Color for readability\nplt.figure(figsize=(10,8))\nx = np.random.normal(size = 2000)\nplt.hist(x, bins=40, color='yellowgreen' , edgecolor=\"#6A9662\")\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Binning",
"_____no_output_____"
]
],
[
[
"# Binning\nplt.figure(figsize=(10,8))\nx = np.random.normal(size = 2000)\nplt.hist(x, bins=30, color='yellowgreen' , edgecolor=\"#6A9662\")\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()\n\nplt.figure(figsize=(10,8))\nplt.hist(x, bins=20, color='yellowgreen' , edgecolor=\"#6A9662\")\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()\n\nplt.figure(figsize=(10,8))\nplt.hist(x, bins=10, color='yellowgreen' , edgecolor=\"#6A9662\")\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()\n",
"_____no_output_____"
]
],
[
[
"#### Plotting Multiple Histograms",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(8,11))\nx = np.random.normal(-4,1,size = 800)\ny = np.random.normal(0,1.5,size = 800)\nz = np.random.normal(3.5,1,size = 800)\nplt.hist(x, bins=30, color='yellowgreen' , alpha=0.6)\nplt.hist(y, bins=30, color='#FF8F00' , alpha=0.6)\nplt.hist(z, bins=30, color='blue' , alpha=0.6)\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()",
"_____no_output_____"
],
[
"# Using Histogram to plot a cumulative distribution function\nplt.figure(figsize=(10,8))\nx = np.random.rand(2000)\nplt.hist(x, bins=30 ,color='#ffa41b' , edgecolor=\"#639a67\",cumulative=True)\nplt.gca().set(title='Histogram', ylabel='Frequency')\nplt.show()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e789fdc8e59a54fa5cfc6399f023695643c9eb8c | 27,818 | ipynb | Jupyter Notebook | plots/terra_analysis.ipynb | wckdouglas/cfNA | 1e3d25bdb067b43d24c394bf586a33f372e3d4e2 | [
"MIT"
] | 2 | 2021-12-15T04:42:46.000Z | 2021-12-21T16:30:04.000Z | plots/terra_analysis.ipynb | elifesciences-publications/cfNA | 1e3d25bdb067b43d24c394bf586a33f372e3d4e2 | [
"MIT"
] | null | null | null | plots/terra_analysis.ipynb | elifesciences-publications/cfNA | 1e3d25bdb067b43d24c394bf586a33f372e3d4e2 | [
"MIT"
] | 2 | 2020-09-22T08:45:54.000Z | 2021-07-31T15:04:04.000Z | 125.306306 | 21,054 | 0.853404 | [
[
[
"%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom pybedtools import BedTool\nimport pysam\nimport glob\nfrom operator import itemgetter\nfrom collections import defaultdict\nimport os\nfrom plotting_utils import label_sample\nfrom multiprocessing import Pool",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
],
[
"#%%bash\n#\n#REF_PATH=/stor/work/Lambowitz/ref/hg19\n#zcat $REF_PATH/genome/rmsk.bed.gz | grep 'TTAGGG\\|CCCTAA' > $REF_PATH/new_genes/TERRA.bed",
"_____no_output_____"
],
[
"def define_strand(terra_strand, aln):\n strand = ''\n sense_terra_positive = not aln.is_reverse and terra_strand == \"forward\"\n sense_terra_negative = aln.is_reverse and terra_strand == '-'\n \n if sense_terra_positive or sense_terra_negative:\n strand = 'Sense'\n else:\n strand = \"Antisense\"\n return strand\n \ndef dict_to_df(terra_dict):\n ds = []\n for terra_strand, d1 in terra_dict.items():\n for express_strand, d2 in d1.items():\n ds.append(pd.DataFrame({'isize': list(d2.keys()),\n 'count': list(d2.values())}) \\\n .assign(express_strand = express_strand,\n terra_strand = terra_strand))\n return pd.concat(ds)\n \ndef extract_terra_length(bam):\n samplename = os.path.basename(bam)\n print('Running %s' %samplename)\n \n terra_bed = '/stor/work/Lambowitz/ref/hg19/new_genes/TERRA.bed'\n terra_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))\n pair_count = 0\n with open(terra_bed) as bed, pysam.Samfile(bam,'rb') as bam:\n for terra in bed:\n fields = terra.split('\\t')\n chrom, start, end, name = itemgetter(0,1,2,3)(fields)\n terra_strand = 'forward' if 'TTAGGG' in name else 'reverse'\n start, end = int(start), int(end)\n \n for aln in bam.fetch(chrom, start, end):\n if aln.is_read1:\n express_strand = define_strand(terra_strand, aln)\n isize = aln.template_length\n terra_dict[terra_strand + '_' + name][express_strand][abs(isize)] += 1\n pair_count += 1\n print('%s: %i TERRA fragments' %(samplename, pair_count))\n return dict_to_df(terra_dict) \\\n .assign(samplename = samplename)",
"_____no_output_____"
],
[
"project_path = '/stor/work/Lambowitz/cdw2854/cell_Free_nucleotides/tgirt_map'\nbam_path = project_path + '/merged_bam'\nbam_files = map(lambda x: bam_path + '/' + x, ['unfragmented.bam',\n 'alkaline_hydrolysis.bam',\n 'untreated.bam'])\np = Pool(24)\ndfs = p.map(extract_terra_length, bam_files)\np.close()\np.join()",
"Running unfragmented.bam\nRunning alkaline_hydrolysis.bam\nRunning untreated.bam\nunfragmented.bam: 2503 TERRA fragments\nuntreated.bam: 2467 TERRA fragments\nalkaline_hydrolysis.bam: 2646 TERRA fragments\n"
],
[
"terra_df = pd.concat(dfs) \\\n .assign(isize = lambda d: np.where(d.isize > 75, 75, d.isize))\\\n .assign(samplename = lambda d: d.samplename.str.replace('.bam','').map(label_sample))\\\n .groupby(['samplename','express_strand','isize'], as_index=False)\\\n .agg({'count': 'sum'})\\\n .sort_values('isize')\n\nfig = plt.figure(figsize=(10,5))\n\nfor i, (strand, strand_df) in enumerate(terra_df.groupby('express_strand')):\n ax = fig.add_subplot(1,2,i+1)\n for sample, sample_df in strand_df.groupby('samplename'):\n ax.hist(sample_df.isize, \n weights = sample_df['count'], \n label = sample,\n bins=20,\n alpha = 0.6)\n \n if i == 0:\n ax.set_ylabel('Number of fragment')\n ax.set_title(strand)\nax.legend(title='')\nsns.despine()",
"/stor/work/Lambowitz/cdw2854/src/miniconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e789fffb90a4e9931887692939db0cb412a7fe44 | 81,803 | ipynb | Jupyter Notebook | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab | a9bf415f51dd8ea91255a12b0537518679f65873 | [
"Apache-2.0"
] | 2 | 2018-08-30T06:54:20.000Z | 2019-01-22T15:56:38.000Z | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab | a9bf415f51dd8ea91255a12b0537518679f65873 | [
"Apache-2.0"
] | null | null | null | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab | a9bf415f51dd8ea91255a12b0537518679f65873 | [
"Apache-2.0"
] | 1 | 2019-01-22T15:56:24.000Z | 2019-01-22T15:56:24.000Z | 117.196275 | 22,028 | 0.8425 | [
[
[
"# Linear regression from scratch\n\nPowerful ML libraries can eliminate repetitive work, but if you rely too much on abstractions, you might never learn how neural networks really work under the hood. So for this first example, let's get our hands dirty and build everything from scratch, relying only on autograd and NDArray. First, we'll import the same dependencies as in the [autograd chapter](../chapter01_crashcourse/autograd.ipynb). We'll also import the powerful `gluon` package but in this chapter, we'll only be using it for data loading.",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\nimport mxnet as mx\nfrom mxnet import nd, autograd, gluon\nmx.random.seed(1)",
"_____no_output_____"
]
],
[
[
"## Set the context\n\nWe'll also want to specify the contexts where computation should happen. This tutorial is so simple that you could probably run it on a calculator watch. But, to develop good habits we're going to specify two contexts: one for data and one for our models. ",
"_____no_output_____"
]
],
[
[
"data_ctx = mx.cpu()\nmodel_ctx = mx.cpu()",
"_____no_output_____"
]
],
[
[
"## Linear regression\n\n\nTo get our feet wet, we'll start off by looking at the problem of regression.\nThis is the task of predicting a *real valued target* $y$ given a data point $x$.\nIn linear regression, the simplest and still perhaps the most useful approach,\nwe assume that prediction can be expressed as a *linear* combination of the input features \n(thus giving the name *linear* regression):\n\n$$\\hat{y} = w_1 \\cdot x_1 + ... + w_d \\cdot x_d + b$$\n\n\nGiven a collection of data points $X$, and corresponding target values $\\boldsymbol{y}$, \nwe'll try to find the *weight* vector $\\boldsymbol{w}$ and bias term $b$ \n(also called an *offset* or *intercept*)\nthat approximately associate data points $\\boldsymbol{x}_i$ with their corresponding labels ``y_i``. \nUsing slightly more advanced math notation, we can express the predictions $\\boldsymbol{\\hat{y}}$\ncorresponding to a collection of datapoints $X$ via the matrix-vector product:\n\n$$\\boldsymbol{\\hat{y}} = X \\boldsymbol{w} + b$$\n\n\nBefore we can get going, we will need two more things \n\n* Some way to measure the quality of the current model \n* Some way to manipulate the model to improve its quality\n\n\n### Square loss\nIn order to say whether we've done a good job, \nwe need some way to measure the quality of a model. \nGenerally, we will define a *loss function*\nthat says *how far* are our predictions from the correct answers.\nFor the classical case of linear regression, \nwe usually focus on the squared error.\nSpecifically, our loss will be the sum, over all examples, of the squared error $(y_i-\\hat{y})^2)$ on each:\n\n$$\\ell(y, \\hat{y}) = \\sum_{i=1}^n (\\hat{y}_i-y_i)^2.$$\n\n\nFor one-dimensional data, we can easily visualize the relationship between our single feature and the target variable. It's also easy to visualize a linear predictor and it's error on each example. \nNote that squared loss *heavily penalizes outliers*. For the visualized predictor below, the lone outlier would contribute most of the loss.\n\n\n\n\n### Manipulating the model\n\nFor us to minimize the error,\nwe need some mechanism to alter the model.\nWe do this by choosing values of the *parameters*\n$\\boldsymbol{w}$ and $b$.\nThis is the only job of the learning algorithm.\nTake training data ($X$, $y$) and the functional form of the model $\\hat{y} = X\\boldsymbol{w} + b$.\nLearning then consists of choosing the best possible $\\boldsymbol{w}$ and $b$ based on the available evidence.\n\n\n\n\n\n### Historical note\n\nYou might reasonably point out that linear regression is a classical statistical model.\n[According to Wikipedia](https://en.wikipedia.org/wiki/Regression_analysis#History), \nLegendre first developed the method of least squares regression in 1805,\nwhich was shortly thereafter rediscovered by Gauss in 1809. \nPresumably, Legendre, who had Tweeted about the paper several times,\nwas peeved that Gauss failed to cite his arXiv preprint. \n\n\n\n\nMatters of provenance aside, you might wonder - if Legendre and Gauss \nworked on linear regression, does that mean there were the original deep learning researchers?\nAnd if linear regression doesn't wholly belong to deep learning, \nthen why are we presenting a linear model \nas the first example in a tutorial series on neural networks? \nWell it turns out that we can express linear regression \nas the simplest possible (useful) neural network. \nA neural network is just a collection of nodes (aka neurons) connected by directed edges. \nIn most networks, we arrange the nodes into layers with each feeding its output into the layer above. \nTo calculate the value of any node, we first perform a weighted sum of the inputs (according to weights ``w``) \nand then apply an *activation function*. \nFor linear regression, we only have two layers, one corresponding to the input (depicted in orange) \nand a one-node layer (depicted in green) correspnding to the ouput.\nFor the output node the activation function is just the identity function.\n\n\n\nWhile you certainly don't have to view linear regression through the lens of deep learning, \nyou can (and we will!).\nTo ground the concepts that we just discussed in code, \nlet's actually code up a neural network for linear regression from scratch.\n\n\nTo get going, we will generate a simple synthetic dataset by sampling random data points ``X[i]`` and corresponding labels ``y[i]`` in the following manner. Out inputs will each be sampled from a random normal distribution with mean $0$ and variance $1$. Our features will be independent. Another way of saying this is that they will have diagonal covariance. The labels will be generated accoding to the *true* labeling function `y[i] = 2 * X[i][0]- 3.4 * X[i][1] + 4.2 + noise` where the noise is drawn from a random gaussian with mean ``0`` and variance ``.01``. We could express the labeling function in mathematical notation as:\n$$y = X \\cdot w + b + \\eta, \\quad \\text{for } \\eta \\sim \\mathcal{N}(0,\\sigma^2)$$ \n",
"_____no_output_____"
]
],
[
[
"num_inputs = 2\nnum_outputs = 1\nnum_examples = 10000\n\ndef real_fn(X):\n return 2 * X[:, 0] - 3.4 * X[:, 1] + 4.2\n \nX = nd.random_normal(shape=(num_examples, num_inputs), ctx=data_ctx)\nnoise = .1 * nd.random_normal(shape=(num_examples,), ctx=data_ctx)\ny = real_fn(X) + noise",
"_____no_output_____"
]
],
[
[
"Notice that each row in ``X`` consists of a 2-dimensional data point and that each row in ``Y`` consists of a 1-dimensional target value. ",
"_____no_output_____"
]
],
[
[
"print(X[0])\nprint(y[0])",
"\n[-1.22338355 2.39233518]\n<NDArray 2 @cpu(0)>\n\n[-6.09602737]\n<NDArray 1 @cpu(0)>\n"
]
],
[
[
"Note that because our synthetic features `X` live on `data_ctx` and because our noise also lives on `data_ctx`, the labels `y`, produced by combining `X` and `noise` in `real_fn` also live on `data_ctx`. \nWe can confirm that for any randomly chosen point, \na linear combination with the (known) optimal parameters \nproduces a prediction that is indeed close to the target value",
"_____no_output_____"
]
],
[
[
"print(2 * X[0, 0] - 3.4 * X[0, 1] + 4.2)",
"\n[-6.38070679]\n<NDArray 1 @cpu(0)>\n"
]
],
[
[
"We can visualize the correspondence between our second feature (``X[:, 1]``) and the target values ``Y`` by generating a scatter plot with the Python plotting package ``matplotlib``. Make sure that ``matplotlib`` is installed. Otherwise, you may install it by running ``pip2 install matplotlib`` (for Python 2) or ``pip3 install matplotlib`` (for Python 3) on your command line. \n\nIn order to plot with ``matplotlib`` we'll just need to convert ``X`` and ``y`` into NumPy arrays by using the `.asnumpy()` function. ",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nplt.scatter(X[:, 1].asnumpy(),y.asnumpy())\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Data iterators\n\nOnce we start working with neural networks, we're going to need to iterate through our data points quickly. We'll also want to be able to grab batches of ``k`` data points at a time, to shuffle our data. In MXNet, data iterators give us a nice set of utilities for fetching and manipulating data. In particular, we'll work with the simple ``DataLoader`` class, that provides an intuitive way to use an ``ArrayDataset`` for training models.\n\n\nWe can load `X` and `y` into an ArrayDataset, by calling `gluon.data.ArrayDataset(X, y)`. It's ok for `X` to be a multi-deminsional input array (say, of images) and `y` to be just a one-dimensional array of labels. The one requirement is that they have equal lengths along the first axis, i.e., `len(X) == len(y)`. \n\nGiven an `ArrayDataset`, we can create a DataLoader which will grab random batches of data from an `ArrayDataset`. We'll want to specify two arguments. First, we'll need to say the `batch_size`, i.e., how many examples we want to grab at a time. Second, we'll want to specify whether or not to shuffle the data between iterations through the dataset. ",
"_____no_output_____"
]
],
[
[
"batch_size = 4\ntrain_data = gluon.data.DataLoader(gluon.data.ArrayDataset(X, y),\n batch_size=batch_size, shuffle=True)",
"_____no_output_____"
]
],
[
[
"Once we've initialized our DataLoader (``train_data``), we can easily fetch batches by iterating over `train_data` just as if it were a Python list. You can use for favorite iterating techniques like foreach loops: `for data, label in train_data` or enumerations: `for i, (data, label) in enumerate(train_data)`. \nFirst, let's just grab one batch and break out of the loop.",
"_____no_output_____"
]
],
[
[
"for i, (data, label) in enumerate(train_data):\n print(data, label)\n break",
"\n[[-0.14732301 -1.32803488]\n [-0.56128627 0.48301753]\n [ 0.75564283 -0.12659997]\n [-0.96057719 -0.96254188]]\n<NDArray 4x2 @cpu(0)> \n[ 8.25711536 1.30587864 6.15542459 5.48825312]\n<NDArray 4 @cpu(0)>\n"
]
],
[
[
"If we run that same code again you'll notice that we get a different batch. That's because we instructed the `DataLoader` that `shuffle=True`. ",
"_____no_output_____"
]
],
[
[
"for i, (data, label) in enumerate(train_data):\n print(data, label)\n break",
"\n[[-0.59027743 -1.52694809]\n [-0.00750104 2.68466949]\n [ 1.50308061 0.54902577]\n [ 1.69129586 0.32308948]]\n<NDArray 4x2 @cpu(0)> \n[ 8.28844357 -5.07566643 5.3666563 6.52408457]\n<NDArray 4 @cpu(0)>\n"
]
],
[
[
"Finally, if we actually pass over the entire dataset, and count the number of batches, we'll find that there are 2500 batches. We expect this because our dataset has 10,000 examples we configure the `DataLoader` with a batch size of 4.",
"_____no_output_____"
]
],
[
[
"counter = 0\nfor i, (data, label) in enumerate(train_data):\n pass\nprint(i+1)",
"2500\n"
]
],
[
[
"## Model parameters\n\nNow let's allocate some memory for our parameters and set their initial values. We'll want to initialize these parameters on the `model_ctx`. ",
"_____no_output_____"
]
],
[
[
"w = nd.random_normal(shape=(num_inputs, num_outputs), ctx=model_ctx)\nb = nd.random_normal(shape=num_outputs, ctx=model_ctx)\nparams = [w, b]",
"_____no_output_____"
]
],
[
[
"In the succeeding cells, we're going to update these parameters to better fit our data. This will involve taking the gradient (a multi-dimensional derivative) of some *loss function* with respect to the parameters. We'll update each parameter in the direction that reduces the loss. But first, let's just allocate some memory for each gradient.",
"_____no_output_____"
]
],
[
[
"for param in params:\n param.attach_grad()",
"_____no_output_____"
]
],
[
[
"## Neural networks\n\nNext we'll want to define our model. In this case, we'll be working with linear models, the simplest possible *useful* neural network. To calculate the output of the linear model, we simply multiply a given input with the model's weights (``w``), and add the offset ``b``.",
"_____no_output_____"
]
],
[
[
"def net(X):\n return mx.nd.dot(X, w) + b",
"_____no_output_____"
]
],
[
[
"Ok, that was easy.",
"_____no_output_____"
],
[
"## Loss function\n\nTrain a model means making it better and better over the course of a period of training. But in order for this goal to make any sense at all, we first need to define what *better* means in the first place. In this case, we'll use the squared distance between our prediction and the true value. ",
"_____no_output_____"
]
],
[
[
"def square_loss(yhat, y): \n return nd.mean((yhat - y) ** 2)",
"_____no_output_____"
]
],
[
[
"## Optimizer\n\nIt turns out that linear regression actually has a closed-form solution. However, most interesting models that we'll care about cannot be solved analytically. So we'll solve this problem by stochastic gradient descent. At each step, we'll estimate the gradient of the loss with respect to our weights, using one batch randomly drawn from our dataset. Then, we'll update our parameters a small amount in the direction that reduces the loss. The size of the step is determined by the *learning rate* ``lr``. ",
"_____no_output_____"
]
],
[
[
"def SGD(params, lr): \n for param in params:\n param[:] = param - lr * param.grad",
"_____no_output_____"
]
],
[
[
"## Execute training loop\n\nNow that we have all the pieces, we just need to wire them together by writing a training loop. \nFirst we'll define ``epochs``, the number of passes to make over the dataset. Then for each pass, we'll iterate through ``train_data``, grabbing batches of examples and their corresponding labels. \n\nFor each batch, we'll go through the following ritual:\n \n* Generate predictions (``yhat``) and the loss (``loss``) by executing a forward pass through the network.\n* Calculate gradients by making a backwards pass through the network (``loss.backward()``). \n* Update the model parameters by invoking our SGD optimizer. \n",
"_____no_output_____"
]
],
[
[
"epochs = 10\nlearning_rate = .0001\nnum_batches = num_examples/batch_size\n\nfor e in range(epochs):\n cumulative_loss = 0\n # inner loop\n for i, (data, label) in enumerate(train_data):\n data = data.as_in_context(model_ctx)\n label = label.as_in_context(model_ctx).reshape((-1, 1))\n with autograd.record():\n output = net(data)\n loss = square_loss(output, label)\n loss.backward()\n SGD(params, learning_rate)\n cumulative_loss += loss.asscalar()\n print(cumulative_loss / num_batches)",
"24.6606138554\n9.09776815639\n3.36058844271\n1.24549788469\n0.465710770596\n0.178157229481\n0.0721970594548\n0.0331197250206\n0.0186954441286\n0.0133724625537\n"
]
],
[
[
"## Visualizing our training progess\n\nIn the succeeding chapters, we'll introduce more realistic data, fancier models, more complicated loss functions, and more. But the core ideas are the same and the training loop will look remarkably familiar. Because these tutorials are self-contained, you'll get to know this ritual quite well. In addition to updating out model, we'll often want to do some bookkeeping. Among other things, we might want to keep track of training progress and visualize it graphically. We demonstrate one slighly more sophisticated training loop below.",
"_____no_output_____"
]
],
[
[
"############################################\n# Re-initialize parameters because they \n# were already trained in the first loop\n############################################\nw[:] = nd.random_normal(shape=(num_inputs, num_outputs), ctx=model_ctx)\nb[:] = nd.random_normal(shape=num_outputs, ctx=model_ctx)\n\n############################################\n# Script to plot the losses over time\n############################################\ndef plot(losses, X, sample_size=100):\n xs = list(range(len(losses)))\n f, (fg1, fg2) = plt.subplots(1, 2)\n fg1.set_title('Loss during training')\n fg1.plot(xs, losses, '-r')\n fg2.set_title('Estimated vs real function')\n fg2.plot(X[:sample_size, 1].asnumpy(),\n net(X[:sample_size, :]).asnumpy(), 'or', label='Estimated')\n fg2.plot(X[:sample_size, 1].asnumpy(),\n real_fn(X[:sample_size, :]).asnumpy(), '*g', label='Real')\n fg2.legend()\n\n plt.show()\n\nlearning_rate = .0001\nlosses = []\nplot(losses, X)\n\nfor e in range(epochs):\n cumulative_loss = 0\n for i, (data, label) in enumerate(train_data):\n data = data.as_in_context(model_ctx)\n label = label.as_in_context(model_ctx).reshape((-1, 1))\n with autograd.record():\n output = net(data)\n loss = square_loss(output, label)\n loss.backward()\n SGD(params, learning_rate)\n cumulative_loss += loss.asscalar()\n\n print(\"Epoch %s, batch %s. Mean loss: %s\" % (e, i, cumulative_loss/num_batches))\n losses.append(cumulative_loss/num_batches)\n \nplot(losses, X)",
"_____no_output_____"
]
],
[
[
"## Conclusion \n\nYou've seen that using just mxnet.ndarray and mxnet.autograd, we can build statistical models from scratch. In the following tutorials, we'll build on this foundation, introducing the basic ideas behind modern neural networks and demonstrating the powerful abstractions in MXNet's `gluon` package for building complex models with little code. ",
"_____no_output_____"
],
[
"## Next\n[Linear regression with gluon](../chapter02_supervised-learning/linear-regression-gluon.ipynb)",
"_____no_output_____"
],
[
"For whinges or inquiries, [open an issue on GitHub.](https://github.com/zackchase/mxnet-the-straight-dope)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"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",
"markdown"
]
] |
e78a1263ae42644929d6984aa5792560faa4f647 | 23,302 | ipynb | Jupyter Notebook | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop | aedb1f5d93577c81bc3dd0da5e46e02586941541 | [
"Apache-2.0"
] | null | null | null | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop | aedb1f5d93577c81bc3dd0da5e46e02586941541 | [
"Apache-2.0"
] | null | null | null | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop | aedb1f5d93577c81bc3dd0da5e46e02586941541 | [
"Apache-2.0"
] | null | null | null | 60.367876 | 9,833 | 0.58613 | [
[
[
"\n\n\n\n[](https://githubtocolab.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/NER_PT.ipynb)\n\n\n",
"_____no_output_____"
],
[
"# **Detect entities in Portuguese text**",
"_____no_output_____"
],
[
"## 1. Colab Setup",
"_____no_output_____"
]
],
[
[
"# Install PySpark and Spark NLP\n! pip install -q pyspark==3.1.2 spark-nlp\n\n# Install Spark NLP Display lib\n! pip install --upgrade -q spark-nlp-display",
"_____no_output_____"
]
],
[
[
"## 2. Start the Spark session",
"_____no_output_____"
]
],
[
[
"import json\nimport pandas as pd\nimport numpy as np\n\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql import SparkSession\nimport pyspark.sql.functions as F\nfrom sparknlp.annotator import *\nfrom sparknlp.base import *\nimport sparknlp\nfrom sparknlp.pretrained import PretrainedPipeline\n\nspark = sparknlp.start()",
"_____no_output_____"
]
],
[
[
"## 3. Select the DL model",
"_____no_output_____"
]
],
[
[
"# If you change the model, re-run all the cells below.\n# Applicable models: wikiner_840B_300, wikiner_6B_300, wikiner_6B_100\nMODEL_NAME = \"wikiner_840B_300\"",
"_____no_output_____"
]
],
[
[
"## 4. Some sample examples",
"_____no_output_____"
]
],
[
[
"# Enter examples to be transformed as strings in this list\ntext_list = [\n \"\"\"William Henry Gates III (nascido em 28 de outubro de 1955) é um magnata americano de negócios, desenvolvedor de software, investidor e filantropo. Ele é mais conhecido como co-fundador da Microsoft Corporation. Durante sua carreira na Microsoft, Gates ocupou os cargos de presidente, diretor executivo (CEO), presidente e diretor de arquitetura de software, além de ser o maior acionista individual até maio de 2014. Ele é um dos empreendedores e pioneiros mais conhecidos da revolução dos microcomputadores nas décadas de 1970 e 1980. Nascido e criado em Seattle, Washington, Gates co-fundou a Microsoft com o amigo de infância Paul Allen em 1975, em Albuquerque, Novo México; tornou-se a maior empresa de software de computador pessoal do mundo. Gates liderou a empresa como presidente e CEO até deixar o cargo em janeiro de 2000, mas ele permaneceu como presidente e tornou-se arquiteto-chefe de software. No final dos anos 90, Gates foi criticado por suas táticas de negócios, que foram consideradas anticompetitivas. Esta opinião foi confirmada por várias decisões judiciais. Em junho de 2006, Gates anunciou que iria passar para um cargo de meio período na Microsoft e trabalhar em período integral na Fundação Bill & Melinda Gates, a fundação de caridade privada que ele e sua esposa, Melinda Gates, estabeleceram em 2000. [ 9] Ele gradualmente transferiu seus deveres para Ray Ozzie e Craig Mundie. Ele deixou o cargo de presidente da Microsoft em fevereiro de 2014 e assumiu um novo cargo como consultor de tecnologia para apoiar a recém-nomeada CEO Satya Nadella.\"\"\",\n \"\"\"A Mona Lisa é uma pintura a óleo do século XVI, criada por Leonardo. É realizada no Louvre, em Paris.\"\"\"\n]",
"_____no_output_____"
]
],
[
[
"## 5. Define Spark NLP pipeline",
"_____no_output_____"
]
],
[
[
"document_assembler = DocumentAssembler() \\\n .setInputCol('text') \\\n .setOutputCol('document')\n\ntokenizer = Tokenizer() \\\n .setInputCols(['document']) \\\n .setOutputCol('token')\n\n# The wikiner_840B_300 is trained with glove_840B_300, so the embeddings in the\n# pipeline should match. Same applies for the other available models.\nif MODEL_NAME == \"wikiner_840B_300\":\n embeddings = WordEmbeddingsModel.pretrained('glove_840B_300', lang='xx') \\\n .setInputCols(['document', 'token']) \\\n .setOutputCol('embeddings')\nelif MODEL_NAME == \"wikiner_6B_300\":\n embeddings = WordEmbeddingsModel.pretrained('glove_6B_300', lang='xx') \\\n .setInputCols(['document', 'token']) \\\n .setOutputCol('embeddings')\nelif MODEL_NAME == \"wikiner_6B_100\":\n embeddings = WordEmbeddingsModel.pretrained('glove_100d') \\\n .setInputCols(['document', 'token']) \\\n .setOutputCol('embeddings')\n\nner_model = NerDLModel.pretrained(MODEL_NAME, 'pt') \\\n .setInputCols(['document', 'token', 'embeddings']) \\\n .setOutputCol('ner')\n\nner_converter = NerConverter() \\\n .setInputCols(['document', 'token', 'ner']) \\\n .setOutputCol('ner_chunk')\n\nnlp_pipeline = Pipeline(stages=[\n document_assembler, \n tokenizer,\n embeddings,\n ner_model,\n ner_converter\n])",
"glove_840B_300 download started this may take some time.\nApproximate size to download 2.3 GB\n[OK!]\nwikiner_840B_300 download started this may take some time.\nApproximate size to download 14.5 MB\n[OK!]\n"
]
],
[
[
"## 6. Run the pipeline",
"_____no_output_____"
]
],
[
[
"empty_df = spark.createDataFrame([['']]).toDF('text')\npipeline_model = nlp_pipeline.fit(empty_df)\ndf = spark.createDataFrame(pd.DataFrame({'text': text_list}))\nresult = pipeline_model.transform(df)",
"_____no_output_____"
]
],
[
[
"## 7. Visualize results",
"_____no_output_____"
]
],
[
[
"from sparknlp_display import NerVisualizer\n\nNerVisualizer().display(\n result = result.collect()[0],\n label_col = 'ner_chunk',\n document_col = 'document'\n)",
"_____no_output_____"
]
]
] | [
"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"
]
] |
e78a13d84383c8aeb7eb8df0bc7602f0608583be | 4,623 | ipynb | Jupyter Notebook | docs/bfgs.ipynb | rocketscience0/cs207-FinalProject | bb2a38bc2ca341c55cf544d316318798b42efde7 | [
"MIT"
] | 1 | 2019-11-12T18:03:52.000Z | 2019-11-12T18:03:52.000Z | docs/bfgs.ipynb | rocketscience0/cs207-FinalProject | bb2a38bc2ca341c55cf544d316318798b42efde7 | [
"MIT"
] | 3 | 2019-11-19T20:45:05.000Z | 2019-12-10T14:33:21.000Z | docs/bfgs.ipynb | rocketscience0/cs207-FinalProject | bb2a38bc2ca341c55cf544d316318798b42efde7 | [
"MIT"
] | null | null | null | 27.849398 | 320 | 0.505516 | [
[
[
"The test function is $y = 5x^2+10x-8$. BFGS's method is implemented to find the minimum of the test function. The user should be able to find the x and y of the minmium as well as access the jacobian of eaach optimization step.\n\nFirst, we instantiate a `Number(5)` as the initial guess ($x_0$) of the root to the minimum. The `bfgs()` method takes the test function and the initial guess. \n\nSecond, the function and its derivative are evaluated at $x_0$. BFGS requires a speculated Hessian, and the initial guess is usually an identity matrix, or in the scalar case, 1. The initial guess of hessian is stored in $b_0$ Then an intermediate $s_0$ is determined through solving $b_0s_0=-\\nabla func(x_0)$\n\nThird, $x_1$'s value is set to be $x_0+s_0$\n\nFourth, another intermediate $y_0$'s value is set to be $\\nabla(x_1)-\\nabla(x_0)$\n\nFifth, $b_1$ is updated and its value is equal to $b_1=b_0+\\Delta b_0$, where $\\Delta b_0$ is equivalent to $\\frac{y_0}{s_0}-b0$\n\nSixth, The values of $b_0$ and $x_0$ are updated with $b_1$ and $x_1$, respectively. Such process repeats until the jacobian turns 0\n\nNote, in our example, ",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('..')\n\nimport autodiff.operations as operations\nfrom autodiff.structures import Number\nimport numpy as np\n\n\ndef func(x):\n return 5 * x ** 2 + 10 * x - 8\n\ndef bfgs(func, initial_guess):\n \n #bfgs for scalar functions\n \n x0 = initial_guess\n \n #initial guess of hessian\n b0 = 1\n \n fxn0 = func(x0)\n\n fpxn0 = fxn0.jacobian(x0)\n \n jacobians = []\n \n jacobians.append(fpxn0)\n \n while(np.abs(fpxn0)>1*10**-7):\n fxn0 = func(x0)\n\n fpxn0 = fxn0.jacobian(x0)\n\n s0 = -fpxn0/b0\n\n x1=x0+s0 \n \n fxn1 = func(x1)\n fpxn1 = fxn1.jacobian(x1)\n \n \n y0 = fpxn1-fpxn0\n \n if y0 == 0:\n break\n \n #delta_b = y0**2/(y0*s0)-b0*s0**2*b0/(s0*b0*s0)\n delta_b = y0/s0-b0\n b1 = b0 + delta_b\n \n x0 = x1\n \n b0 = b1\n \n jacobians.append(fpxn1)\n\n \n \n return x0,func(x0),jacobians\n \nx0 = Number(5)\nxstar,minimum,jacobians = bfgs(func,x0)\n\nprint(\"The jacobians at 1st, 2nd and final steps are:\",jacobians,'. The jacobian value is 0 in the last step, indicating completion of the optimization process.')\nprint()\nprint(\"The x* is\", xstar )",
"The jacobians at 1st, 2nd and final steps are: [60, -540.0, 0.0] . The jacobian value is 0 in the last step, indicating completion of the optimization process.\n\nThe x* is Number(val=-1.0)\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
e78a179d859992a5b30730fc7e90fee56e496bda | 180,085 | ipynb | Jupyter Notebook | notebook/chapter14_combining_models.ipynb | hedwig100/PRML | 992f2c07e88b2bad331e08303bdba84684f04d40 | [
"MIT"
] | 1 | 2022-02-19T09:44:11.000Z | 2022-02-19T09:44:11.000Z | notebook/chapter14_combining_models.ipynb | hedwig100/PRML | 992f2c07e88b2bad331e08303bdba84684f04d40 | [
"MIT"
] | null | null | null | notebook/chapter14_combining_models.ipynb | hedwig100/PRML | 992f2c07e88b2bad331e08303bdba84684f04d40 | [
"MIT"
] | 1 | 2022-01-07T11:08:10.000Z | 2022-01-07T11:08:10.000Z | 296.680395 | 41,220 | 0.910398 | [
[
[
"import numpy as np\n\nfrom prml.utils.datasets import RegressionDataGenerator,ClassificationDataGenerator2\nfrom prml.utils.plot import plot_regression1D,plot_classifier\nfrom prml.linear_classifier import Classifier \nfrom prml.linear_regression import Regression,LinearRegression",
"_____no_output_____"
]
],
[
[
"# Commity ",
"_____no_output_____"
]
],
[
[
"class Commity():\n def __init__(self,M) -> None:\n self.M = M \n self.model = [LinearRegression(basis_function=\"polynomial\",deg=3) for _ in range(M)]\n \n def fit(self,X,y):\n n = len(X) \n sample = int(n*0.8) \n for i in range(self.M):\n idx = np.random.randint(0,n,sample) \n X_bootstrap,y_bootstrap = X[idx],y[idx] \n self.model[i].fit(X_bootstrap,y_bootstrap) \n \n def predict(self,X):\n y_pred = self.model[0].predict(X) \n for i in range(self.M-1):\n y_pred += self.model[i+1].predict(X)\n return y_pred/self.M ",
"_____no_output_____"
],
[
"def f(x):\n return np.sin(x) + x \n\ngenerator = RegressionDataGenerator(f) \nX,y = generator(n=100,std=0.6) \n\n# in many cases, a commity model has worse results ..., maybe because of data size of each model is smaller than that of non commity model\nlr = LinearRegression(basis_function=\"polynomial\",deg=3) \nlr.fit(X,y)\nplot_regression1D(X,y,lr,\"Linear Regression\",f)\n\ncom = Commity(M=5)\ncom.fit(X,y)\nplot_regression1D(X,y,com,\"Commity\",f)",
"RMSE : 0.14445858781232257\n"
]
],
[
[
"# AdaBoost",
"_____no_output_____"
]
],
[
[
"class AdaBoost(Classifier):\n \"\"\"AdaBoost \n\n weak_learner is decision stump\n\n Attributes:\n M (int): number of weak leaner \n weak_leaner (list): list of data about weak learner \n\n \"\"\"\n def __init__(self,M=5) -> None:\n \"\"\"__init__\n\n Args:\n M (int): number of weak leaner \n\n \"\"\"\n super(AdaBoost,self).__init__()\n self.M = M \n\n def fit(self,X,y):\n \"\"\"fit \n\n only accept N_dim = 2 data\n\n Args:\n X (2-D array): shape = (N_samples,2),\n y (1-D array or 2-D array) : if 1-D array, y should be label-encoded, but 2-D arrray, y should be one-hot-encoded. should be 2-class data. \n\n \"\"\"\n y = self._onehot_to_label(y) \n y[y == 0.0] = -1.0\n y = y.astype(\"int\")\n N = len(X)\n sort_idx = np.argsort(X,axis=0)\n weight = np.ones(N)/N \n weak_learner = [None]*self.M \n\n for i in range(self.M):\n x_border,x_more_or_less,x_score = self._weak_learn(X[:,0],sort_idx[:,0],y,weight) \n y_border,y_more_or_less,y_score = self._weak_learn(X[:,1],sort_idx[:,1],y,weight) \n\n if x_score < y_score:\n ax = \"x\"\n border,more_or_less = x_border,x_more_or_less\n else:\n ax = \"y\" \n border,more_or_less = y_border,y_more_or_less\n \n miss = self._miss_idx(X,y,ax,border,more_or_less) \n eps = np.sum(miss*weight)/np.sum(weight) \n alpha = np.log((1 - eps)/eps) \n weight *= np.exp(alpha*miss) \n\n weak_learner[i] = {\n \"ax\":ax,\n \"border\":border,\n \"more_or_less\":more_or_less,\n \"alpha\":alpha \n }\n\n self.weak_learner = weak_learner \n\n def _weak_learn(self,X,sort_idx,y,weight):\n weight_sum = weight.sum()\n more_score = weight[y != 1].sum() # score when all data is asigned 1\n\n border,more_or_less,score = X[sort_idx[0]]-1,\"more\",more_score \n for i in range(len(X)):\n if y[sort_idx[i]] == 1:\n more_score += weight[sort_idx[i]]\n else:\n more_score -= weight[sort_idx[i]]\n\n less_score = weight_sum - more_score\n if more_score < score:\n border,more_or_less,score = X[sort_idx[i]],\"more\",more_score\n if less_score < score:\n border,more_or_less,score = X[sort_idx[i]],\"less\",less_score\n \n return border,more_or_less,score \n \n def _miss_idx(self,X,y,ax,border,more_or_less):\n y_pred = self._predict(X,ax,border,more_or_less) \n return (y_pred != y).astype(\"int\")\n\n def _predict(self,X,ax,border,more_or_less):\n if more_or_less == \"more\":\n if ax == \"x\":\n class1 = X[:,0] > border \n elif ax == \"y\":\n class1 = X[:,1] > border \n elif more_or_less == \"less\":\n if ax == \"x\":\n class1 = X[:,0] <= border \n elif ax == 'y':\n class1 = X[:,1] <= border \n pred = np.zeros(len(X)) - 1\n pred[class1] = 1 \n return pred \n\n def predict(self,X):\n \"\"\"predict \n\n Args:\n X (2-D array) : explanatory variable, shape = (N_samples,2)\n \n Returns: \n y (1-D array or 2-D array) : if 1-D array, y should be label-encoded, but 2-D arrray, y should be one-hot-encoded. This depends on parameter y when fitting. \n\n \"\"\"\n\n y_pred = np.zeros(len(X))\n for i in range(self.M):\n pred = self._predict(\n X,\n self.weak_learner[i][\"ax\"],\n self.weak_learner[i][\"border\"],\n self.weak_learner[i][\"more_or_less\"],\n )\n y_pred += self.weak_learner[i][\"alpha\"]*pred\n \n y_pred = np.sign(y_pred)\n return self._inverse_transform(y_pred)",
"_____no_output_____"
],
[
"generator = ClassificationDataGenerator2(f=np.sin)\nX,y = generator(n=100,x_lower=0,x_upper=2*np.pi,y_lower=-1.2,y_upper=1.2)\n\nab = AdaBoost(M=20)\nab.fit(X,y)\nplot_classifier(X,y,ab,title=\"AdaBoost\")",
"_____no_output_____"
]
],
[
[
"# CART",
"_____no_output_____"
]
],
[
[
"class CARTRegressor():\n \"\"\"CARTRegressor \n\n Attributes:\n lamda (float): regularizatioin parameter\n tree (object): parameter \n\n \"\"\"\n def __init__(self,lamda=1e-2):\n \"\"\"__init__\n \n Args:\n lamda (float): regularizatioin parameter\n\n \"\"\"\n self.lamda = lamda \n\n def fit(self,X,y):\n \"\"\"fit \n\n Args:\n X (2-D array) : explanatory variable,shape = (N_samples,N_dim)\n y (1-D array) : target variable, shape = (N_samples) \n \n \"\"\"\n\n N = len(X)\n leaves = np.zeros(N)\n num_nodes = 1\n num_leaves = 1\n tree = []\n\n while True:\n if num_leaves == 0:\n break\n for leaf in range(num_nodes-num_leaves,num_nodes):\n idx = np.arange(N)[leaf == leaves]\n if len(idx) == 1:\n num_leaves -= 1\n tree.append({\n \"border\": None, \n \"target\": y[idx][0]\n }) # has no child\n continue\n\n ax,border,score,more_index,less_index = -1,None,1e20,None,None\n for m in range(X.shape[1]):\n now_border,now_score,now_more_index,now_less_index = self._find_boundry(idx,X[idx,m],y[idx])\n if now_score < score:\n ax,border,score,more_index,less_index = m,now_border,now_score,now_more_index,now_less_index\n\n if border is None: \n num_leaves -= 1\n tree.append({\n \"border\": None,\n \"target\": y[idx].mean()\n }) # has no child\n continue\n\n tree.append({\n \"left_index\": num_nodes, \n \"right_index\": num_nodes+1, \n \"border\": border, \n \"ax\": ax\n })\n\n leaves[less_index] = num_nodes\n leaves[more_index] = num_nodes+1 \n\n num_nodes += 2 \n num_leaves += 1\n\n self.tree = tree \n\n def _find_boundry(self,idx,X,y):\n n = len(idx)\n sort_idx = np.argsort(X)\n all_sum = np.sum(y)\n right_sum = all_sum \n\n # when all data is in one leaf\n score_now = self._error_function(y,right_sum/n) + self.lamda \n border_index,score = None,score_now\n pred = np.zeros(n)\n\n for i in range(n-1):\n right_sum -= y[sort_idx[i]]\n left_sum = all_sum - right_sum\n pred[sort_idx[i+1:]] = right_sum/(n-i-1) \n pred[sort_idx[:i+1]] = left_sum/(i+1)\n score_now = self._error_function(y,pred) + self.lamda*2\n if score_now < score:\n border_index,score = i,score_now\n \n if border_index is None: # no division\n return None,1e20,None,None \n\n border = X[sort_idx[border_index]]\n more_index = idx[sort_idx[border_index+1:]] \n less_index = idx[sort_idx[:border_index+1]]\n return border,score,more_index,less_index \n \n def _error_function(self,y,pred):\n return np.mean((y-pred)**2)\n \n def _predict(self,X,p_id=0):\n if self.tree[p_id][\"border\"] is None: \n return np.zeros(len(X)) + self.tree[p_id][\"target\"] \n \n ax = self.tree[p_id][\"ax\"]\n border = self.tree[p_id][\"border\"]\n y = np.zeros(len(X))\n y[X[:,ax] > border] = self._predict(X[X[:,ax] > border],p_id=self.tree[p_id][\"right_index\"])\n y[X[:,ax] <= border] = self._predict(X[X[:,ax] <= border],p_id=self.tree[p_id][\"left_index\"])\n return y \n\n def predict(self,X):\n \"\"\"predict \n\n Args:\n X (2-D array) : explanatory variable, shape = (N_samples,N_dim)\n \n Returns: \n y (1-D array) : predictive value\n\n \"\"\"\n y = self._predict(X)\n return y ",
"_____no_output_____"
],
[
"generator = RegressionDataGenerator(f=np.sin) \nX,y = generator(n=100,std=0.2)\ncart = CARTRegressor(lamda=1e-2) \ncart.fit(X,y.ravel())\nplot_regression1D(X,y,cart,title=\"CART Regressor\",f=np.sin)",
"RMSE : 1.00482444289275\n"
]
],
[
[
"# Linear Mixture",
"_____no_output_____"
]
],
[
[
"class LinearMixture(Regression):\n \"\"\"LinearMixture\n\n Attributes:\n K (int): number of mixture modesl \n max_iter (int): max iteration \n threshold (float): threshold for EM algorithm \n pi (1-D array): mixture, which model is chosen\n weight (2-D array): shape = (K,M), M is dimension of feature space, weight\n beta (float): precision parameter\n\n \"\"\"\n def __init__(self,K=3,max_iter=100,threshold=1e-3,basis_function=\"gauss\",mu=None,s=None,deg=None):\n super(LinearMixture,self).__init__(basis_function,mu,s,deg)\n self.K = K \n self.max_iter = max_iter \n self.threshold = threshold\n\n def _gauss(self,x,mu,beta):\n return (beta/2*np.pi)**0.5 * np.exp(-beta/2*(x-mu)**2)\n\n def fit(self,X,y):\n \"\"\"fit \n\n Args:\n X (2-D array) : explanatory variable,shape = (N_samples,N_dim)\n y (1-D array) : target variable, shape = (N_samples) \n\n \"\"\" \n\n design_mat = self.make_design_mat(X)\n N,M = design_mat.shape\n gamma = np.random.rand(N,self.K) + 1\n gamma /= gamma.sum(axis=1,keepdims=True)\n\n for _ in range(self.max_iter):\n \n # M step \n pi = gamma.mean(axis = 0)\n R = gamma.T.reshape(self.K,N,1)\n weight = np.linalg.inv(design_mat.T@(R*design_mat))@design_mat.T@(R*y.reshape(-1,1))\n weight = weight.reshape((self.K,M))\n beta = N/np.sum(gamma*(y.reshape(-1,1) - [email protected])**2)\n\n # E step \n gauss = pi*np.exp(-beta/2*(y.reshape(-1,1) - [email protected])**2) + 1e-10\n new_gamma = gauss/gauss.sum(axis=1,keepdims=True) \n\n if np.mean((new_gamma - gamma)**2)**0.5 < self.threshold:\n gamma = new_gamma \n break \n\n gamma = new_gamma \n \n self.pi = pi \n self.weight = weight \n self.beta = beta \n\n def predict(self,X):\n \"\"\"predict\n\n Args:\n X (2-D array) : data,shape = (N_samples,N_dim)\n Returns:\n y (1-D array) : predicted value, shape = (N_samples)\n\n \"\"\" \n \n design_mat = self.make_design_mat(X)\n return np.dot([email protected],self.pi)",
"_____no_output_____"
],
[
"generator = RegressionDataGenerator(f=np.sin) \nX,y = generator(n=100,std=0.2)\nlinMix = LinearMixture(K=5,basis_function=\"polynomial\",deg=4)\nlinMix.fit(X,y.ravel())\nplot_regression1D(X,y,linMix,title=\"Linear Mixture\",f=np.sin)",
"RMSE : 0.9774354228059758\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e78a1eca8807dbcff9860ab7c3576893283245bf | 63,904 | ipynb | Jupyter Notebook | ch03_regression/3-2.ipynb | CaptLWM/AI | de2fd06c7acdb1e6f37747fc7d1ff36b74417938 | [
"MIT"
] | null | null | null | ch03_regression/3-2.ipynb | CaptLWM/AI | de2fd06c7acdb1e6f37747fc7d1ff36b74417938 | [
"MIT"
] | null | null | null | ch03_regression/3-2.ipynb | CaptLWM/AI | de2fd06c7acdb1e6f37747fc7d1ff36b74417938 | [
"MIT"
] | null | null | null | 77.272068 | 14,106 | 0.833594 | [
[
[
"# 선형 회귀",
"_____no_output_____"
],
[
"<table align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/rickiepark/hg-mldl/blob/master/3-2.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />구글 코랩에서 실행하기</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"## k-최근접 이웃의 한계",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nperch_length = np.array(\n [8.4, 13.7, 15.0, 16.2, 17.4, 18.0, 18.7, 19.0, 19.6, 20.0, \n 21.0, 21.0, 21.0, 21.3, 22.0, 22.0, 22.0, 22.0, 22.0, 22.5, \n 22.5, 22.7, 23.0, 23.5, 24.0, 24.0, 24.6, 25.0, 25.6, 26.5, \n 27.3, 27.5, 27.5, 27.5, 28.0, 28.7, 30.0, 32.8, 34.5, 35.0, \n 36.5, 36.0, 37.0, 37.0, 39.0, 39.0, 39.0, 40.0, 40.0, 40.0, \n 40.0, 42.0, 43.0, 43.0, 43.5, 44.0]\n )\nperch_weight = np.array(\n [5.9, 32.0, 40.0, 51.5, 70.0, 100.0, 78.0, 80.0, 85.0, 85.0, \n 110.0, 115.0, 125.0, 130.0, 120.0, 120.0, 130.0, 135.0, 110.0, \n 130.0, 150.0, 145.0, 150.0, 170.0, 225.0, 145.0, 188.0, 180.0, \n 197.0, 218.0, 300.0, 260.0, 265.0, 250.0, 250.0, 300.0, 320.0, \n 514.0, 556.0, 840.0, 685.0, 700.0, 700.0, 690.0, 900.0, 650.0, \n 820.0, 850.0, 900.0, 1015.0, 820.0, 1100.0, 1000.0, 1100.0, \n 1000.0, 1000.0]\n )",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\n# 훈련 세트와 테스트 세트로 나눕니다\ntrain_input, test_input, train_target, test_target = train_test_split(\n perch_length, perch_weight, random_state=42)\n# 훈련 세트와 테스트 세트를 2차원 배열로 바꿉니다\ntrain_input = train_input.reshape(-1, 1)\ntest_input = test_input.reshape(-1, 1)",
"_____no_output_____"
],
[
"from sklearn.neighbors import KNeighborsRegressor\n\nknr = KNeighborsRegressor(n_neighbors=3)\n# k-최근접 이웃 회귀 모델을 훈련합니다\nknr.fit(train_input, train_target)",
"_____no_output_____"
],
[
"print(knr.predict([[50]]))",
"[1033.33333333]\n"
],
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# 50cm 농어의 이웃을 구합니다\ndistances, indexes = knr.kneighbors([[50]])\n\n# 훈련 세트의 산점도를 그립니다\nplt.scatter(train_input, train_target)\n# 훈련 세트 중에서 이웃 샘플만 다시 그립니다\nplt.scatter(train_input[indexes], train_target[indexes], marker='D')\n# 50cm 농어 데이터\nplt.scatter(50, 1033, marker='^')\nplt.show()",
"_____no_output_____"
],
[
"print(np.mean(train_target[indexes]))",
"1033.3333333333333\n"
],
[
"print(knr.predict([[100]]))",
"[1033.33333333]\n"
],
[
"# 100cm 농어의 이웃을 구합니다\ndistances, indexes = knr.kneighbors([[100]])\n\n# 훈련 세트의 산점도를 그립니다\u001f\nplt.scatter(train_input, train_target)\n# 훈련 세트 중에서 이웃 샘플만 다시 그립니다\u001f\nplt.scatter(train_input[indexes], train_target[indexes], marker='D')\n# 100cm 농어 데이터\nplt.scatter(100, 1033, marker='^')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 선형 회귀",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LinearRegression",
"_____no_output_____"
],
[
"lr = LinearRegression()\n# 선형 회귀 모델 훈련\nlr.fit(train_input, train_target)",
"_____no_output_____"
],
[
"# 50cm 농어에 대한 예측\nprint(lr.predict([[50]]))",
"[1241.83860323]\n"
],
[
"print(lr.coef_, lr.intercept_)",
"[39.01714496] -709.0186449535477\n"
],
[
"# 훈련 세트의 산점도를 그립니다\u001f\nplt.scatter(train_input, train_target)\n# 15에서 50까지 1차 방정식 그래프를 그립니다\nplt.plot([15, 50], [15*lr.coef_+lr.intercept_, 50*lr.coef_+lr.intercept_])\n# 50cm 농어 데이터\nplt.scatter(50, 1241.8, marker='^')\nplt.show()",
"_____no_output_____"
],
[
"print(lr.score(train_input, train_target))\nprint(lr.score(test_input, test_target))",
"0.9398463339976039\n0.8247503123313558\n"
]
],
[
[
"## 다항 회귀",
"_____no_output_____"
]
],
[
[
"train_poly = np.column_stack((train_input ** 2, train_input))\ntest_poly = np.column_stack((test_input ** 2, test_input))",
"_____no_output_____"
],
[
"print(train_poly.shape, test_poly.shape)",
"(42, 2) (14, 2)\n"
],
[
"lr = LinearRegression()\nlr.fit(train_poly, train_target)\n\nprint(lr.predict([[50**2, 50]]))",
"[1573.98423528]\n"
],
[
"print(lr.coef_, lr.intercept_)",
"[ 1.01433211 -21.55792498] 116.0502107827827\n"
],
[
"# 구간별 직선을 그리기 위해 15에서 49까지 정수 배열을 만듭니다\npoint = np.arange(15, 50)\n# 훈련 세트의 산점도를 그립니다\nplt.scatter(train_input, train_target)\n# 15에서 49까지 2차 방정식 그래프를 그립니다\nplt.plot(point, 1.01*point**2 - 21.6*point + 116.05)\n# 50cm 농어 데이터\nplt.scatter([50], [1574], marker='^')\nplt.show()",
"_____no_output_____"
],
[
"print(lr.score(train_poly, train_target))\nprint(lr.score(test_poly, test_target))",
"0.9706807451768623\n0.9775935108325122\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e78a1f5b1a3b4eea62eabff843410f50d102a5a4 | 13,747 | ipynb | Jupyter Notebook | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk | 2a97d94612b82cd58a7d4c6b2bb014f2f29f65b0 | [
"Apache-2.0"
] | 18 | 2020-01-24T23:27:07.000Z | 2022-02-02T15:23:29.000Z | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/libraries | 2a97d94612b82cd58a7d4c6b2bb014f2f29f65b0 | [
"Apache-2.0"
] | 4 | 2018-11-12T00:34:22.000Z | 2018-11-15T06:04:00.000Z | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/libraries | 2a97d94612b82cd58a7d4c6b2bb014f2f29f65b0 | [
"Apache-2.0"
] | 5 | 2020-03-05T00:35:54.000Z | 2022-01-02T22:21:49.000Z | 25.410351 | 227 | 0.457627 | [
[
[
"# Orbit Computation",
"_____no_output_____"
],
[
"This tutorial demonstrates how to generate satellite orbits using various models.",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\nimport plotly.graph_objs as go\n\nfrom ostk.physics.units import Length\nfrom ostk.physics.units import Angle\nfrom ostk.physics.time import Scale\nfrom ostk.physics.time import Instant\nfrom ostk.physics.time import Duration\nfrom ostk.physics.time import Interval\nfrom ostk.physics.time import DateTime\nfrom ostk.physics.coordinate.spherical import LLA\nfrom ostk.physics.coordinate import Frame\nfrom ostk.physics import Environment\nfrom ostk.physics.environment.objects.celestial_bodies import Earth\n\nfrom ostk.astrodynamics import Trajectory\nfrom ostk.astrodynamics.trajectory import Orbit\nfrom ostk.astrodynamics.trajectory.orbit.models import Kepler\nfrom ostk.astrodynamics.trajectory.orbit.models.kepler import COE\nfrom ostk.astrodynamics.trajectory.orbit.models import SGP4\nfrom ostk.astrodynamics.trajectory.orbit.models.sgp4 import TLE",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## SGP4",
"_____no_output_____"
],
[
"### Computation",
"_____no_output_____"
]
],
[
[
"environment = Environment.default()",
"_____no_output_____"
]
],
[
[
"Create a Classical Orbital Element (COE) set:",
"_____no_output_____"
]
],
[
[
"a = Length.kilometers(7000.0)\ne = 0.0001\ni = Angle.degrees(35.0)\nraan = Angle.degrees(40.0)\naop = Angle.degrees(45.0)\nnu = Angle.degrees(50.0)\n\ncoe = COE(a, e, i, raan, aop, nu)",
"_____no_output_____"
]
],
[
[
"Setup a Keplerian orbital model:",
"_____no_output_____"
]
],
[
[
"epoch = Instant.date_time(DateTime(2018, 1, 1, 0, 0, 0), Scale.UTC)\nearth = environment.access_celestial_object_with_name(\"Earth\")\n\nkeplerian_model = Kepler(coe, epoch, earth, Kepler.PerturbationType.No)",
"_____no_output_____"
]
],
[
[
"Create a Two-Line Element (TLE) set:",
"_____no_output_____"
]
],
[
[
"tle = TLE(\n \"1 39419U 13066D 18260.77424112 .00000022 00000-0 72885-5 0 9996\",\n \"2 39419 97.6300 326.6556 0013847 175.2842 184.8495 14.93888428262811\"\n)",
"_____no_output_____"
]
],
[
[
"Setup a SGP4 orbital model:",
"_____no_output_____"
]
],
[
[
"sgp4_model = SGP4(tle)",
"_____no_output_____"
]
],
[
[
"Setup the orbit:",
"_____no_output_____"
]
],
[
[
"# orbit = Orbit(keplerian_model, environment.access_celestial_object_with_name(\"Earth\"))\norbit = Orbit(sgp4_model, environment.access_celestial_object_with_name(\"Earth\"))",
"_____no_output_____"
]
],
[
[
"Now that the orbit is set, we can compute the satellite position:",
"_____no_output_____"
]
],
[
[
"start_instant = Instant.date_time(DateTime(2018, 9, 5, 0, 0, 0), Scale.UTC)\nend_instant = Instant.date_time(DateTime(2018, 9, 6, 0, 0, 0), Scale.UTC)",
"_____no_output_____"
],
[
"interval = Interval.closed(start_instant, end_instant)",
"_____no_output_____"
],
[
"step = Duration.minutes(1.0)",
"_____no_output_____"
]
],
[
[
"Generate a time grid:",
"_____no_output_____"
]
],
[
[
"instants = interval.generate_grid(step)",
"_____no_output_____"
],
[
"states = [[instant, orbit.get_state_at(instant)] for instant in instants]",
"_____no_output_____"
],
[
"def convert_state (instant, state):\n \n lla = LLA.cartesian(state.get_position().in_frame(Frame.ITRF(), state.get_instant()).get_coordinates(), Earth.equatorial_radius, Earth.flattening)\n \n return [\n repr(instant),\n float(instant.get_modified_julian_date(Scale.UTC)),\n *state.get_position().get_coordinates().transpose()[0].tolist(),\n *state.get_velocity().get_coordinates().transpose()[0].tolist(),\n float(lla.get_latitude().in_degrees()),\n float(lla.get_longitude().in_degrees()),\n float(lla.get_altitude().in_meters())\n ]",
"_____no_output_____"
],
[
"orbit_data = [convert_state(instant, state) for [instant, state] in states]",
"_____no_output_____"
],
[
"orbit_df = pd.DataFrame(orbit_data, columns=['$Time^{UTC}$', '$MJD^{UTC}$', '$x_{x}^{ECI}$', '$x_{y}^{ECI}$', '$x_{z}^{ECI}$', '$v_{x}^{ECI}$', '$v_{y}^{ECI}$', '$v_{z}^{ECI}$', '$Latitude$', '$Longitude$', '$Altitude$'])",
"_____no_output_____"
]
],
[
[
"### Output",
"_____no_output_____"
],
[
"Table:",
"_____no_output_____"
]
],
[
[
"orbit_df.head()",
"_____no_output_____"
]
],
[
[
"2D plot, over **World Map**:",
"_____no_output_____"
]
],
[
[
"figure = go.Figure(\n data = go.Scattergeo(\n lon = orbit_df['$Longitude$'],\n lat = orbit_df['$Latitude$'],\n mode = 'lines',\n line = go.scattergeo.Line(\n width = 1,\n color = 'red'\n )\n ),\n layout = go.Layout(\n title = None,\n showlegend = False,\n height=1000,\n geo = go.layout.Geo(\n showland = True,\n landcolor = 'rgb(243, 243, 243)',\n countrycolor = 'rgb(204, 204, 204)'\n )\n )\n)\n\nfigure.show()",
"_____no_output_____"
]
],
[
[
"3D plot, in **Earth Fixed** frame:",
"_____no_output_____"
]
],
[
[
"figure = go.Figure(\n data = [\n go.Scattergeo(\n lon = orbit_df['$Longitude$'],\n lat = orbit_df['$Latitude$'],\n mode = 'lines',\n line = go.scattergeo.Line(\n width = 2,\n color = 'rgb(255, 62, 79)'\n )\n )\n ],\n layout = go.Layout(\n title = None,\n showlegend = False,\n width = 800,\n height = 800,\n geo = go.layout.Geo(\n showland = True,\n showlakes = True,\n showcountries = False,\n showocean = True,\n countrywidth = 0.0,\n landcolor = 'rgb(100, 100, 100)',\n lakecolor = 'rgb(240, 240, 240)',\n oceancolor = 'rgb(240, 240, 240)',\n projection = dict( \n type = 'orthographic',\n rotation = dict(\n lon = -100,\n lat = 40,\n roll = 0\n ) \n ),\n lonaxis = dict( \n showgrid = True,\n gridcolor = 'rgb(102, 102, 102)',\n gridwidth = 0.5\n ),\n lataxis = dict( \n showgrid = True,\n gridcolor = 'rgb(102, 102, 102)',\n gridwidth = 0.5\n )\n )\n )\n)\n\nfigure.show()",
"_____no_output_____"
]
],
[
[
"3D plot, in **Earth Inertial** frame:",
"_____no_output_____"
]
],
[
[
"theta = np.linspace(0, 2 * np.pi, 30)\nphi = np.linspace(0, np.pi, 30)\n\ntheta_grid, phi_grid = np.meshgrid(theta, phi)\n\nr = float(Earth.equatorial_radius.in_meters())\n\nx = r * np.cos(theta_grid) * np.sin(phi_grid)\ny = r * np.sin(theta_grid) * np.sin(phi_grid)\nz = r * np.cos(phi_grid)\n\nearth = go.Surface(\n x=x,\n y=y,\n z=z,\n colorscale='Viridis',\n showscale=False\n)\n\ntrace = go.Scatter3d(\n x=orbit_df['$x_{x}^{ECI}$'],\n y=orbit_df['$x_{y}^{ECI}$'],\n z=orbit_df['$x_{z}^{ECI}$'],\n mode='lines',\n marker=dict(\n size=0,\n color=orbit_df['$x_{z}^{ECI}$'],\n colorscale='Viridis',\n showscale=False\n ),\n line=dict(\n color=orbit_df['$x_{z}^{ECI}$'],\n width=1\n )\n)\n\nfigure = go.Figure(\n data = [earth, trace],\n layout = go.Layout(\n title = None,\n width = 800,\n height = 1000,\n showlegend = False,\n scene = go.layout.Scene(\n xaxis = dict(\n gridcolor = 'rgb(255, 255, 255)',\n zerolinecolor = 'rgb(255, 255, 255)',\n showbackground = True,\n backgroundcolor = 'rgb(230, 230,230)'\n ),\n yaxis = dict(\n gridcolor = 'rgb(255, 255, 255)',\n zerolinecolor = 'rgb(255, 255, 255)',\n showbackground = True,\n backgroundcolor = 'rgb(230, 230,230)'\n ),\n zaxis = dict(\n gridcolor = 'rgb(255, 255, 255)',\n zerolinecolor = 'rgb(255, 255, 255)',\n showbackground = True,\n backgroundcolor = 'rgb(230, 230,230)'\n ),\n camera = dict(\n up = dict(\n x = 0,\n y = 0,\n z = 1\n ),\n eye = dict(\n x = -1.7428,\n y = 1.0707,\n z = 0.7100,\n )\n ),\n aspectratio = dict(x = 1, y = 1, z = 1),\n aspectmode = 'manual'\n )\n )\n)\n\nfigure.show()",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e78a2ca0f9b3dd9d212b0213ead62619a2be8ec6 | 10,630 | ipynb | Jupyter Notebook | silver/C05_Global_And_Local_Phase.ipynb | VGGatGitHub/QWorld-silver | 4da363df7d8544959ff80f6e71fccc520db86745 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2021-05-26T13:35:30.000Z | 2021-05-26T13:35:30.000Z | silver/C05_Global_And_Local_Phase.ipynb | Innanov/QSilver | 99fc53d9c0f77dd1122e65ec24117574fff7c8a5 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | silver/C05_Global_And_Local_Phase.ipynb | Innanov/QSilver | 99fc53d9c0f77dd1122e65ec24117574fff7c8a5 | [
"Apache-2.0",
"CC-BY-4.0"
] | 2 | 2021-12-01T17:41:53.000Z | 2022-01-07T20:11:11.000Z | 49.44186 | 449 | 0.549106 | [
[
[
"<table align=\"left\" width=\"100%\"> <tr>\n <td style=\"background-color:#ffffff;\">\n <a href=\"http://qworld.lu.lv\" target=\"_blank\"><img src=\"..\\images\\qworld.jpg\" width=\"35%\" align=\"left\"> </a></td>\n <td style=\"background-color:#ffffff;vertical-align:bottom;text-align:right;\">\n prepared by Maksim Dimitrijev (<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{\\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 } $\n$ \\newcommand{\\Y}{ \\mymatrix{rr}{0 & -i \\\\ i & 0} } $ $ \\newcommand{\\S}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & i} } $ \n$ \\newcommand{\\T}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & e^{i \\frac{pi}{4}}} } $ \n$ \\newcommand{\\Sdg}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & -i} } $ \n$ \\newcommand{\\Tdg}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & e^{-i \\frac{pi}{4}}} } $\n$ \\newcommand{\\qgate}[1]{ \\mathop{\\textit{#1} } }$",
"_____no_output_____"
],
[
"<h1> Global and local phase </h1>",
"_____no_output_____"
],
[
"A generic qubit can be in state $\\ket{\\psi} = \\alpha \\ket{0} + \\beta \\ket{1}$, where $\\alpha, \\beta \\in \\mathbb{C}$ and $\\mathopen|\\alpha\\mathclose|^2 + \\mathopen|\\beta\\mathclose|^2 = 1$. Both amplitudes can be complex values, and each complex number has a real and an imaginary part. Therefore, we have 4 different numbers that describe the state of a qubit. \n\nCan we have more concise way to represent the state of a qubit? Understanding of complex numbers and global and local phase can help us to improve the situation.",
"_____no_output_____"
],
[
"<h2> Another representation of a state </h2>\n\nAt the given moment we have 4 numbers to represent the state of a qubit. We can reduce this to three numbers, since $\\mathopen|\\alpha\\mathclose|^2 + \\mathopen|\\beta\\mathclose|^2 = 1$. How the result will look like? Since there is a correspondence between two amplitudes and complex numbers can be represented in polar form, the community has found the following representation of the state of a qubit with three angles:\n\n$$\n\\ket{\\psi} = e^{i\\delta} ( \\cos{\\frac{\\theta}{2}} \\ket{0} + e^{i\\phi} \\sin{\\frac{\\theta}{2}} \\ket{1} ),\n$$\n\nwhere $0 \\leq \\theta \\leq \\pi$ and $0 \\leq \\phi, \\delta < 2\\pi$.",
"_____no_output_____"
],
[
"<h2> Global phase </h2>\n\nSuppose that we have a qubit and its state is either $ \\ket{\\psi} $ or $ e^{i\\delta} \\ket{\\psi} $, where $0 \\leq \\delta < 2\\pi$.\n\nIs there any sequence of one-qubit gates such that we can measure different results after applying them?",
"_____no_output_____"
],
[
"All one-qubit gates are $ 2 \\times 2 $ matrices, and their application is represented by a single matrix: $ A_n \\cdot \\cdots \\cdot A_2 \\cdot A_1 = A $.\n\nBy linearity, if $ A \\ket{\\psi} = \\ket{u} $, then $ A e^{i\\delta} \\ket{\\psi} = e^{i\\delta} \\ket{u} $. Thus, after measurement, the probabilities of observing state $ \\ket{0} $ and state $ \\ket{1} $ are the same in both cases. Therefore, we cannot distinguish them.\n\nEven though the states $ \\ket{0} $ and $ e^{i\\delta} \\ket{0} $ are different mathematically, they are assumed the same from the physical point of view. ",
"_____no_output_____"
],
[
"The complex number $ e^{i\\delta} $ in front of $ e^{i\\delta} \\ket{\\psi} $ is called as _global phase_.\n\nTherefore, two vectors that differ by a global phase factor, in quantum mechanics are considered equivalent, and so we have $ \\ket{\\psi} \\equiv e^{i\\delta} \\ket{\\psi} $ for any quantum state $\\ket{\\psi}$ and any $0 \\leq \\delta < 2\\pi$.\n\nNow we can describe the state of a qubit with two numbers - angles $\\theta$ and $\\phi$:\n\n$$\n\\ket{\\psi} = \\cos{\\frac{\\theta}{2}} \\ket{0} + e^{i\\phi} \\sin{\\frac{\\theta}{2}} \\ket{1},\n$$\n\nwhere $0 \\leq \\theta \\leq \\pi$ and $0 \\leq \\phi < 2\\pi$.",
"_____no_output_____"
],
[
"<h2> Local phase </h2>\n\nIn our last form of the state representation we have an amplitude multiplier $e^{i\\phi}$. What if we have a similar multiplier also for the amplitude of state $\\ket{0}$? \n\nThen we would have the following state: \n\n$$e^{i\\gamma} \\cos{\\frac{\\theta}{2}} \\ket{0} + e^{i\\phi} \\sin{\\frac{\\theta}{2}} \\ket{1} = e^{i\\gamma}(\\cos{\\frac{\\theta}{2}} \\ket{0} + e^{i(\\phi-\\gamma)} \\sin{\\frac{\\theta}{2}} \\ket{1}) = \\cos{\\frac{\\theta}{2}} \\ket{0} + e^{i(\\phi-\\gamma)} \\sin{\\frac{\\theta}{2}} \\ket{1}.$$ \n\nTherefore, there is no need for second such multiplier, and having one related to the state $\\ket{1}$ is a convention.\n\nOne more useful fact is that $\\mathopen|e^{i\\phi}\\mathclose| = 1$ for any $\\phi$. This means that this multiplier does not affect the probabilities to observe state $\\ket{0}$ or $\\ket{1}$ after the measurement. This means that only parameter $\\theta$ influences the probability to observe state $\\ket{0}$ or $\\ket{1}$ after the measurement.\n\nAlthough $e^{i\\phi}$ does not influence the measurement outcome, it influences the overall computation, as you could notice in previous notebook, where we affected the phase for the state $\\ket{1}$. The number $e^{i\\phi}$ shows additional relation between states $\\ket{0}$ and $\\ket{1}$, like one more dimension added to the computation, and is called local phase. As you have noticed, local phase indeed is important for the computation.",
"_____no_output_____"
],
[
"<h3> Task 1 </h3>\n\nFind the probabilities of observing states $\\ket{0}$ and $\\ket{1}$ for the qubits in the following states:\n\n<ul>\n <li>$\\cos{\\frac{\\pi}{3}} \\ket{0} + e^{i\\pi} \\sin{\\frac{\\pi}{3}} \\ket{1}$</li>\n <li>$\\cos{\\frac{\\pi}{4}} \\ket{0} + e^{i\\frac{\\pi}{4}} \\sin{\\frac{\\pi}{4}} \\ket{1}$</li>\n <li>$\\cos{\\frac{\\pi}{6}} \\ket{0} + i \\sin{\\frac{\\pi}{6}} \\ket{1}$</li>\n</ul>",
"_____no_output_____"
],
[
"<a href=\"C05_Global_And_Local_Phase_Solutions.ipynb#task1\">click for our solution</a>",
"_____no_output_____"
],
[
"<h3> Task 2 </h3>\n\nImplement a function that calculates the probabilities of observing states $\\ket{0}$ and $\\ket{1}$ given the angle of a quantum state. Assuming that the quantum state is of the form $\\cos{\\frac{\\theta}{2}} \\ket{0} + e^{i\\phi} \\sin{\\frac{\\theta}{2}} \\ket{1}$, $\\theta$ and $\\phi$ should be provided to the function as parameters. Check the quantum states given in Task 1 and compare the results.",
"_____no_output_____"
]
],
[
[
"#\n# your solution is here\n#\n",
"_____no_output_____"
]
],
[
[
"<a href=\"C05_Global_And_Local_Phase_Solutions.ipynb#task2\">click for our solution</a>",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e78a39d9eae90f176e06989609ded86d12588e3f | 4,172 | ipynb | Jupyter Notebook | ipynb/Germany-Bayern-LK-Kitzingen.ipynb | RobertRosca/oscovida.github.io | d609949076e3f881e38ec674ecbf0887e9a2ec25 | [
"CC-BY-4.0"
] | null | null | null | ipynb/Germany-Bayern-LK-Kitzingen.ipynb | RobertRosca/oscovida.github.io | d609949076e3f881e38ec674ecbf0887e9a2ec25 | [
"CC-BY-4.0"
] | null | null | null | ipynb/Germany-Bayern-LK-Kitzingen.ipynb | RobertRosca/oscovida.github.io | d609949076e3f881e38ec674ecbf0887e9a2ec25 | [
"CC-BY-4.0"
] | null | null | null | 29.174825 | 181 | 0.516299 | [
[
[
"# Germany: LK Kitzingen (Bayern)\n\n* Homepage of project: https://oscovida.github.io\n* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Bayern-LK-Kitzingen.ipynb)",
"_____no_output_____"
]
],
[
[
"import datetime\nimport time\n\nstart = datetime.datetime.now()\nprint(f\"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}\")",
"_____no_output_____"
],
[
"%config InlineBackend.figure_formats = ['svg']\nfrom oscovida import *",
"_____no_output_____"
],
[
"overview(country=\"Germany\", subregion=\"LK Kitzingen\");",
"_____no_output_____"
],
[
"# load the data\ncases, deaths, region_label = germany_get_region(landkreis=\"LK Kitzingen\")\n\n# compose into one table\ntable = compose_dataframe_summary(cases, deaths)\n\n# show tables with up to 500 rows\npd.set_option(\"max_rows\", 500)\n\n# display the table\ntable",
"_____no_output_____"
]
],
[
[
"# Explore the data in your web browser\n\n- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Bayern-LK-Kitzingen.ipynb)\n- and wait (~1 to 2 minutes)\n- Then press SHIFT+RETURN to advance code cell to code cell\n- See http://jupyter.org for more details on how to use Jupyter Notebook",
"_____no_output_____"
],
[
"# Acknowledgements:\n\n- Johns Hopkins University provides data for countries\n- Robert Koch Institute provides data for within Germany\n- Open source and scientific computing community for the data tools\n- Github for hosting repository and html files\n- Project Jupyter for the Notebook and binder service\n- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))\n\n--------------------",
"_____no_output_____"
]
],
[
[
"print(f\"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and \"\n f\"deaths at {fetch_deaths_last_execution()}.\")",
"_____no_output_____"
],
[
"# to force a fresh download of data, run \"clear_cache()\"",
"_____no_output_____"
],
[
"print(f\"Notebook execution took: {datetime.datetime.now()-start}\")\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
e78a41c9752a1638e0a95d4b5311fbb91ae58b05 | 5,326 | ipynb | Jupyter Notebook | untoken.ipynb | gdoteof/DiscordChatExporter | 88f3901ce693d8a249f109fa305430b3405210b3 | [
"MIT"
] | null | null | null | untoken.ipynb | gdoteof/DiscordChatExporter | 88f3901ce693d8a249f109fa305430b3405210b3 | [
"MIT"
] | null | null | null | untoken.ipynb | gdoteof/DiscordChatExporter | 88f3901ce693d8a249f109fa305430b3405210b3 | [
"MIT"
] | null | null | null | 24.209091 | 233 | 0.39617 | [
[
[
"<a href=\"https://colab.research.google.com/github/gdoteof/DiscordChatExporter/blob/master/untoken.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"test_str=\"xxup copy of course appear of course or half - dressed on his gf ill cross ! i was unemployed vans - land through the smallest shoes leave\"\n",
"_____no_output_____"
],
[
"for x in test_str.split():\n print (f'{x}')",
"xxup\ncopy\nof\ncourse\nappear\nof\ncourse\nor\nhalf\n-\ndressed\non\nhis\ngf\nill\ncross\n!\ni\nwas\nunemployed\nvans\n-\nland\nthrough\nthe\nsmallest\nshoes\nleave\n"
]
],
[
[
"xxup is a token which mean the next word should be uppercased.\n",
"_____no_output_____"
]
],
[
[
"pieces = test_str.split()\nfor idx,val in enumerate(pieces):\n print(f'{idx}:{val}')",
"0:xxup\n1:copy\n2:of\n3:course\n4:appear\n5:of\n6:course\n7:or\n8:half\n9:-\n10:dressed\n11:on\n12:his\n13:gf\n14:ill\n15:cross\n16:!\n17:i\n18:was\n19:unemployed\n20:vans\n21:-\n22:land\n23:through\n24:the\n25:smallest\n26:shoes\n27:leave\n"
],
[
"def un_xxup(str):\n pieces = test_str.split()\n for index,value in enumerate(pieces):\n if value == 'xxup':\n pieces[index+1] = pieces[index+1].capitalize()\n del pieces[index]\n return \" \".join(pieces)",
"_____no_output_____"
],
[
"un_xxup(test_str)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e78a48fa9be985be1f1b4731ddf83e9aea574d18 | 574,503 | ipynb | Jupyter Notebook | TD1_Timeseries_Analysis.ipynb | RomainBnfn/Timeseries-Sequence-Processing-2021 | eb45b856b99e52807d544a1eb7adf4b2cf987b45 | [
"CC0-1.0"
] | null | null | null | TD1_Timeseries_Analysis.ipynb | RomainBnfn/Timeseries-Sequence-Processing-2021 | eb45b856b99e52807d544a1eb7adf4b2cf987b45 | [
"CC0-1.0"
] | null | null | null | TD1_Timeseries_Analysis.ipynb | RomainBnfn/Timeseries-Sequence-Processing-2021 | eb45b856b99e52807d544a1eb7adf4b2cf987b45 | [
"CC0-1.0"
] | null | null | null | 376.229862 | 88,700 | 0.920352 | [
[
[
"<a href=\"https://colab.research.google.com/github/nTrouvain/TD1-Timeseries-Analysis/blob/main/TD1_Timeseries_Analysis.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# TD1: Timeseries analysis using autoregressive methods and general Box-Jenkins methods\n\nSome useful translations, just in case:\n\n- **a timeseries**: une série temporelle (always plural in English)\n- **a trend**: une tendance\n- **a lag**: un retard, un décalage dans le temps\n- **stationary**: stationnaire\n\n\nSome interesting content to dive deeper and/or go further about timeseries analysis, or that might help you during the TD:\n\n- [The engineering statistics handbook on timeseries analysis](https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc4.htm)\n\n- [A Stanford class on autoregressive models seen as generative models](https://deepgenerativemodels.github.io/notes/) (and more on deep generative models)",
"_____no_output_____"
]
],
[
[
"!pip install statsmodels==0.12.1\n!pip install sktime",
"Collecting statsmodels==0.12.1\n Downloading statsmodels-0.12.1-cp38-none-win_amd64.whl (9.2 MB)\nRequirement already satisfied: patsy>=0.5 in c:\\programdata\\anaconda3\\lib\\site-packages (from statsmodels==0.12.1) (0.5.1)\nRequirement already satisfied: scipy>=1.1 in c:\\programdata\\anaconda3\\lib\\site-packages (from statsmodels==0.12.1) (1.6.2)\nRequirement already satisfied: numpy>=1.15 in c:\\programdata\\anaconda3\\lib\\site-packages (from statsmodels==0.12.1) (1.20.1)\nRequirement already satisfied: pandas>=0.21 in c:\\programdata\\anaconda3\\lib\\site-packages (from statsmodels==0.12.1) (1.2.4)\nRequirement already satisfied: pytz>=2017.3 in c:\\programdata\\anaconda3\\lib\\site-packages (from pandas>=0.21->statsmodels==0.12.1) (2021.1)\nRequirement already satisfied: python-dateutil>=2.7.3 in c:\\programdata\\anaconda3\\lib\\site-packages (from pandas>=0.21->statsmodels==0.12.1) (2.8.1)\nRequirement already satisfied: six in c:\\programdata\\anaconda3\\lib\\site-packages (from patsy>=0.5->statsmodels==0.12.1) (1.15.0)\nInstalling collected packages: statsmodels\n Attempting uninstall: statsmodels\n Found existing installation: statsmodels 0.12.2\n Uninstalling statsmodels-0.12.2:\n"
],
[
"import requests\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels\nimport sktime\nimport scipy",
"_____no_output_____"
]
],
[
[
"## 1. Analysis\n\nFor this exercise, we will use a timeseries representing daily average temperature in Melbourne, Australia between 1980 and 1990.\n\nThis timeseries will be stored in a [Pandas DataFrame object](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html), a standard to handle tabular data in Python.\n\nThis analysis will follow the steps proposed by George Box and Gwilym Jenkins in 1970, called [Box-Jenkins method](https://en.wikipedia.org/wiki/Box%E2%80%93Jenkins_method), which emphasizes issues encountered when appliying autoregressive methods.",
"_____no_output_____"
]
],
[
[
"# Read data from remote repository\ndf = pd.read_csv(\"https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv\", index_col=0)",
"_____no_output_____"
],
[
"# Display the 5 first data points\ndf.head()",
"_____no_output_____"
]
],
[
[
"### 1.1 Run-plots analysis\n\n\"Run-plots\" are the simplest representation of a timeseries, where the x-axis represents time and the y-axis represents the observed variable, here temperature in Celsius degrees.\n\n\n**Question: Given the figures and the statistic test below, what hypothesis can you draw regarding the behaviour of this timeseries? Is is stationary? Does it displays seasonality? Trending? Explain. You can create additional figures if you need.**",
"_____no_output_____"
],
[
"The timeseries seems to be quite stationary because the result of the test result return a p-value << 0.5, so the non stationary hypothesis is rejected (so it's probably stationary). Moreover, the trend of the curve is like a sinus curve (with a period of one year). ",
"_____no_output_____"
]
],
[
[
"# Plot the full timeseries\ndf.plot(figsize=(20, 4), title=\"Temperature in Melbourne - 1980 to 1990\")",
"_____no_output_____"
],
[
"# Plot the first year of data\ndf.iloc[:365].plot(figsize=(20, 4), title=\"Temperature in Melbourne - one year\")",
"_____no_output_____"
]
],
[
[
"The Augmented Dickey-Fuller test is a statistical test used to check\nthe stationarity of a timeseries. It is implemented in the `adfuller()` function in `statsmodels`.",
"_____no_output_____"
]
],
[
[
"from statsmodels.tsa.stattools import adfuller\n\nadf, p, *other_stuff = adfuller(df)\n\nprint(f\"p-value (95% confidence interval): {p:g}, statistics: {adf:g}\")",
"p-value (95% confidence interval): 0.000247083, statistics: -4.4448\n"
]
],
[
[
"### 1.2 Autocorrelation and partial autocorrelation\n\nAutocorrelation (and partial autocorrelation) are metrics that can be computed to evaluate **how dependent the variable is from its $n$ previous values**, what is called a **lag (of length n)**.\n\n**Question: Plot $X[t-1]$ versus $X[t]$, for all $t$. What can you conclude on the autocorrelation of the series with a lag of 1? You can also compute the Pearson correlation coefficient between $X[t-1]$ and $X[t]$.**\n\n*Some help:*\n\n- You can create a new DataFrame with all values shifted from $n$ timestep using the `.shift()` method of the DataFrame. See Pandas documentation for more.\n\n- You can plot some data versius some other using the `plt.scatter(X, Y)` method of Matplotlib. This plots a dot on the figure for every couple `(x, y)`\nin `X` and `Y`. See Matplotlib documentation for more.\n\n- Pearson coefficient can be computed using the DataFrame `.corr()` method. This method computes the correlation coefficient between all variables (*columns*) in the DataFrame. Try appliying this method to a DataFrame where one column is $X[t]$ and another column is the shifted timeseries $X[t-1]$. Note that you can merge two DataFrames into one using the function `pd.concat(dataframes)` of Pandas. See Pandas documentation for more.",
"_____no_output_____"
]
],
[
[
"# Create a shifted version of the timeseries:\ndf_shifted = df.shift(periods=1)\n",
"_____no_output_____"
],
[
"# Plot df vs. df_shifted\nplt.figure(figsize=(5, 5))\nplt.scatter(df, df_shifted)\n\nplt.xlabel(\"X[t]\")\nplt.ylabel(\"X[t-1]\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"It seems to be like X[t] timeseries explains globaly the X[t-1] timeseries because the graph above is quite like a linear graph. But in middle of the graph, the line is very thick so it's difficult to explain the X[t-1] by the X[t] value. ~ not high correlated ",
"_____no_output_____"
],
[
"**Pearson correlation coefficient**\n\nTo compute this coefficient, we first need to ensure that our variable follows a normal distribution. Let's plot the distribution, using the `.hist()` method of DataFrame objects:\n\n*(Optional)* Perform a normality test, using `scipy.stats.normaltest`.",
"_____no_output_____"
]
],
[
[
"# Plot of the distribution of the variable\n# (in our case, the temperature histogram)\n\ndf.hist()\n# The hist graph seems to be an normal dist hist with a ~ mean of 12",
"_____no_output_____"
],
[
"from scipy import stats\n\n# Normality test\nk2, p = scipy.stats.normaltest(df)\n\nprint(f\"p-value (95% confidence interval): {p[0]:g}, statistics: {k2[0]:g}\")\n# The result results with a p-value of 0.00009 << 0.05 so we can reject the null hypothesis of non normal distribution\n",
"p-value (95% confidence interval): 9.89899e-05, statistics: 18.441\n"
],
[
"# (Optional) Compute Pearson coefficients\n \n# First, concatenate df and df_shifted in df_all, following axis 1\n# (concatenate columns, not rows !)\ndf_all = pd.concat([df, df_shifted[1:]], axis=1)\n\n# Rename the columns\ndf_all.columns = [\"X[t]\", \"X[t-1]\"]\ndf_all.head()\n\n# Compute correlation and print it\ndf_all.corr()\n# The cor between X[t] and X[t-1] is 0.77, this is very closer to 1 than 0 so we can suggest that there is a link between those two vars",
"_____no_output_____"
]
],
[
[
"We can see that the value has a quite normal distribution so we can calculate the Pearson Correlation Value. The correlation between X[t-1] and X[t] is 0.77 (~ close to 1) so the two var are very correlated. We probably explain X[t] by X[t-1].",
"_____no_output_____"
],
[
"---\nWe will now compute autocorrelation function (ACF) and partial autocorrelation function (PACF) of the timeseries. These functions compute correlation (or partial correlation) between $X[t]$ and $X[t-n]$, for an interval of different lags $n$. For now, we only evaluated correlation for lag $n=1$.\n\n**Question: Plot the ACF and the PACF of the timeseries, with $n={1, \\dots, 31}$ (one month lag) and $n={1, \\dots, 730}$ (2 years lag). What is your hypothesis on the lag to use to create the model ?**\n\n\n*Some help:*\n\n- See documentation of `statsmodels.graphics.tsaplots.plot_acf` to understand how to change the number of lags to plot.\n\n- **Autocorrelation** is the result of the multiplication (or convolution) of all points of the signal with themselves, shifted in time by a lag of $n$. The **autocorrelation function** (ACF) is the function giving autocorrelation for any lag $n$.\n\n- **Partial autocorrelation** is similar to autocorrelation, but the correlation between two points of the signal is computed assuming that this two points are independent from all points between them in time. The **partial autocorrelation function** (PACF) is the function giving partial autocorrelation for any lag $n$.\n\n- Autocorrelation is helpful to check if a process in autoregressive. **Autoregressive processes are auto-correlated**.\n\n- Partial autocorrelation is helpful to find the order of an autoregressive process, i.e. **how many past steps are needed to predict the future one**.",
"_____no_output_____"
]
],
[
[
"from statsmodels.graphics.tsaplots import plot_pacf, plot_acf",
"_____no_output_____"
]
],
[
[
"#### 1.2.1 Autocorrelation",
"_____no_output_____"
]
],
[
[
"# Plot autocorrelation for lags between 1 and 730 days\nplot_acf(df.values.squeeze(), lags=730)\nplt.show()",
"_____no_output_____"
],
[
"# Plot autocorrelation for lags between 1 and 31 days\nplot_acf(df.values.squeeze(), lags=31)\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### 1.2.2 Partial autocorrelation",
"_____no_output_____"
]
],
[
[
"# Plot partial autocorrelation for lags between 1 and 730 days\nplot_pacf(df.values.squeeze(), lags=730)\nplt.show()",
"_____no_output_____"
],
[
"# Plot partial autocorrelation for lags between 1 and 31 days\nplot_pacf(df.values, lags=31)\nplt.show()",
"_____no_output_____"
]
],
[
[
"The correlation seem to be the strongest with a lag which is a multiple of 180.2 (1/2 year), but verry bad monthly or with any other lag.",
"_____no_output_____"
],
[
"## 2. Modeling",
"_____no_output_____"
],
[
"### 2.0 Modeling: AR from scratch (just as an example, nothing to do here)\n\nAR stands for AutoRegressive. Autoregressive models describe the value of any points in a timeseries given the values of $p$ previous points, establishing a linear relashionship between them such that:\n\n$$\nX_t = \\alpha + \\beta_1 X_{t-1} + \\beta_2 X_{t-2} + ... + \\beta_{p} X_{t-p} + \\epsilon_t\n$$\n\nwhere $X$ is a timeseries, $p$ is the lag used in the AR model, also called the **order** of the model, and $\\beta=\\{\\beta, \\dots, \\beta_p\\}$ and $\\alpha$ are the parameters we want to estimate. $\\epsilon_t$ is a white noise random process that we will consider to be 0 for all time steps in our model.\n\n$X_t$ is therefore linearly dependent from its $p$ previous values $X_{t-1}, \\dots, X_{t-p}$. We can learn $\\beta_{[1, p]}$ and $\\alpha$ using a linear regression defined by:\n\n$$\n[\\alpha, \\beta_{[1, p]}] = X \\cdot X_{lags}^\\intercal \\cdot (X_{lags} \\cdot X_{lags}^\\intercal)^{-1}\n$$\n\nwhere $X$ is the whole timeseries with an available lag ($t-p$ timesteps have $p$ past values, the $p$ first timesteps do not have pasts values), and $X_{lags}$ are the $X_{t-1}, \\dots, X_{t-p}$ for all time steps with an available lag $t-p$.",
"_____no_output_____"
]
],
[
[
"# We store all values of the series in a numpy array called series\nseries = df[\"Temp\"].values",
"_____no_output_____"
],
[
"def auto_regression(series, order):\n \n n_points = len(series)\n\n # All lagged values will be stored in y_lag.\n # If order is 7, for each timestep we will store 7 values.\n X_lag = np.zeros((order, n_points-order))\n\n # All current values will be stores in X.\n X = np.zeros((1, n_points-order))\n for i in range(0, n_points-order-1):\n X_lag[:, i] = series[i:i+order] # get the lagged values\n X[:, i] = series[i+order+1] # get the current value\n\n # Add a constant term (c=1) to X_lag to compute alpha in the linear\n # regression\n X_lag = np.vstack((np.ones((1, n_points-order)), X_lag))\n\n # Linear regression\n coef = np.dot(np.dot(X, X_lag.T), scipy.linalg.pinv(np.dot(X_lag, X_lag.T)))\n \n alpha = coef[:, 0]\n beta = coef[:, 1:]\n\n return alpha, beta",
"_____no_output_____"
],
[
"alpha, beta = auto_regression(series, order=3)",
"_____no_output_____"
]
],
[
[
"Now that we have our coefficients learned, we can make predictions.",
"_____no_output_____"
]
],
[
[
"lag = beta.shape[1]\n\nY_truth = [] # real timeseries\nY_pred = [] # predictions\nfor i in range(0, len(series)-lag-1):\n # apply the equation of AR using the coefficients at each time steps\n y = alpha + np.dot(beta, series[i:i+lag]) # y[t] = alpha + y[t-1]*beta1 + y[t-2]*beta2 + ...\n\n Y_pred.append(y)\n Y_truth.append(series[i+lag+1])\n\nY_pred = np.array(Y_pred).flatten()\nY_truth = np.array(Y_truth).flatten()",
"_____no_output_____"
],
[
"# Plot the results for one year\nplt.plot(series[lag+1:lag+366], label=\"True series\")\nplt.plot(Y_pred[:365], label=\"Predicted values\")\nplt.title(f'Lag of {lag}')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"And here are our coefficients:",
"_____no_output_____"
]
],
[
[
"coefs = np.c_[alpha, beta]\nplt.bar(np.arange(coefs.shape[1]), coefs.flatten())\nlabels = ['$\\\\alpha$']\nfor i in range(beta.shape[1]):\n labels.append(f\"$\\\\beta_{i+1}$\")\n\nplt.xticks(np.arange(coefs.shape[1]), labels)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 2.1 Modeling : ARIMA\n",
"_____no_output_____"
]
],
[
[
"from statsmodels.tsa.arima.model import ARIMA",
"_____no_output_____"
]
],
[
[
"ARIMA is an acronym that stands for AutoRegressive Integrated Moving Average, capturing the key aspects of the model :\n\n- **AR** : *AutoRegressive* A model that uses the dependent relationship between an observation and some number of lagged observations.\nA pure AR model is such that :\n$$\nY_t = \\alpha + \\beta_1 Y_{t-1} + \\beta_2 Y_{t-2} + ... + \\beta_{p} Y_{t-p} + \\epsilon_1\n$$\n- **I** : *Integrated* The use of differencing of raw observations in order to make the time series stationary\n- **MA** : *Moving Average* A model that uses the dependency between an observation and a residual error from a moving average model applied to lagged observations\nA pure moving average model is such that :\n$$\nY_t = \\alpha + \\epsilon_t + \\phi_1 \\epsilon_{t-1} + \\phi_2 \\epsilon_{t-2} + ... + \\phi_q \\epsilon_{t-q}\n$$\n\n\nThus finally, the equation for ARIMA becomes :\n$$\nY_t = \\alpha + \\beta_1 Y_{t-1} + ... + \\beta_p Y_{t-p} \\epsilon_t + \\phi_1 \\epsilon_{t-1} + ... + \\phi_q \\epsilon_{t-q} \n$$\n\nEach of these components is specified in the model as a parameter :\n- **p** : number of lag observations\n- **d** : number of times that raw observations are differenced. \nIt is the minimum number of differencing needed to make the series stationary. If the time series is already stationary, then d= 0\n- **q** : size of moving average window\n\nNow, we will fit an ARIMA forecast model to the daily minimum temperature data.\nThe data contains a one-year seasonal component :\n",
"_____no_output_____"
]
],
[
[
"# seasonal difference\ndifferenced = df.diff(365) \n# trim off the first year of empty data\ndifferenced = differenced[365:]",
"_____no_output_____"
],
[
"# Create an ARIMA model (check the statsmodels docs) (p,d,q)\n# d = 0 because the serie is stationary (see before)\nmodel = ARIMA(series, order=(3, 0, 15))\n\n# fit model\nmodel_fit = model.fit()\nprint(model_fit.summary())",
"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\statsmodels\\base\\model.py:566: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals\n warnings.warn(\"Maximum Likelihood optimization failed to \"\n"
],
[
"# reviewing the residual errors\n# line plot\nresiduals = pd.DataFrame(model_fit.resid)\nresiduals.plot()\nplt.show()\n# density plot\nresiduals.plot(kind='kde')\nplt.show()\n# summary stats\nprint(\"Residuals stats:\", residuals.describe())",
"_____no_output_____"
]
],
[
[
"To evaluate the ARIMA model, we will use walk forward validation. First we split the data into a training and testing set (initially, a year is a good interval to test for this dataset given the seasonal nature). \nA model will be constructed on the historic data and predict the next time step. The real observation of the time step will be added to the history, a new model constructed and the next time step predicted. \nThe forecasts will be collected together to the final observations to give an error score (for example, RSME : root mean square error)",
"_____no_output_____"
]
],
[
[
"from math import sqrt\nfrom sklearn.metrics import mean_squared_error\n\n# rolling forecast with ARIMA\n\ntrain, test = differenced.iloc[:-365], differenced.iloc[-365:]\n\n# walk-forward validation\nvalues = train.values\nhistory = [v for v in values]\npredictions = list()\ntest_values = test.values\nfor t in range(len(test_values)):\n # fit model\n model = ARIMA(history, order=(7,0,0))\n model_fit = model.fit()\n # make prediction \n yhat = model_fit.forecast()[0]\n predictions.append(yhat)\n history.append(test_values[t])\n\n# evaluate forecast\nrsme = sqrt(mean_squared_error(test_values, predictions))\nprint('RSME : ', rsme)\n\n# plot forecasts against actual outcomes\nplt.plot(test)\nplt.plot(predictions, color='red')\nplt.show()",
"RSME : 3.0962731960398195\n"
]
],
[
[
"We can also use the predict() function on the results object to make predictions. It accepts the index of the time steps to make predictions as arguments. These indexes are relative to the start of the training dataset. ",
"_____no_output_____"
]
],
[
[
"forecast = model_fit.predict(start=len(train.values), end=len(differenced.values), typ='levels')\nplt.plot(test)\nplt.plot(forecast, color='red')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Exercise: Mauna Loa CO<sub>2</sub> concentration levels (1975 - 2021)\n\n\nCarbon dioxyde (CO<sub>2</sub>) is a gas naturaly present in our environment. However, the concentration of CO<sub>2</sub> is increasing every year, mainly because of human activities. It is one of the major cause of global warming, and its value is precautiounously measured since 1973 at the Mauna Loa observatory, in Hawaii.\n\nWe will get interested on the measures performed between 1975 and 2021. The dataset is composed of monthly averaged values. Values are expressed in *ppm* (parts-per-million).\n\n**Question: Appliying the method described above, model the behaviour of this timeseries.**\n\n**Question: Using your model, make predictions from 2001 to 2021, and evaluate the performance of your model. Make some projections about the evolution of the concentration after 2021.**\n\n**Do not forget to explain your hypotheses, choices and results.**\n\n*Some help*\n\n- Be careful ! This timeseries is more difficult to model (do not forget the stationarity property...)\n- If a timeseries is not stationary, one can **differenciate** its values over time to create a stationary approximation of the timeseries (like ARIMA does). You can also **remove the linear trend** from the data. Differencing (for an order 1 differenciation) implies transforming $X[t]$ into $X[t] - X[t-1]$.\n- Maybe a seasonal model (SARIMA, ...) could be interesting ?\n- You can do projections by using the model as a **generative model**: using the predicted value $X[t]$, you can predict $X[t+1$] using $X[t]$, then predict $X[t+2]$ using $X[t+1]$ and so on, using only the predictions of your model. For instance, with a dataset stopping in December 2021, you can predict January 2022 using December 2021, which you know from the dataset. Then, you can predict February 2022 from January 2022, March 2022 from February 2022...\n\n*Reference:*\n\nK.W. Thoning, A.M. Crotwell, and J.W. Mund (2021), Atmospheric Carbon Dioxide Dry Air Mole Fractions from continuous measurements at Mauna Loa, Hawaii, Barrow, Alaska, American Samoa and South Pole. 1973-2020, Version 2021-08-09 National Oceanic and Atmospheric Administration (NOAA), Global Monitoring Laboratory (GML), Boulder, Colorado, USA",
"_____no_output_____"
]
],
[
[
"ts = pd.read_csv(\"https://gml.noaa.gov/aftp/data/trace_gases/co2/in-situ/surface/mlo/co2_mlo_surface-insitu_1_ccgg_MonthlyData.txt\",\n header=150, sep=\" \")\n\nts = ts[ts[\"year\"] > 1975]\n\ntime_index = pd.DatetimeIndex(pd.to_datetime(ts[[\"year\", \"month\", \"day\"]]))\nts = ts.set_index(time_index)\nts = pd.Series(ts[\"value\"])",
"_____no_output_____"
],
[
"ts.plot(figsize=(10, 5))\n\nplt.xlabel(\"Time\")\nplt.ylabel(\"CO2 (ppm)\")\nplt.show()",
"_____no_output_____"
],
[
"# Plot the first year of data\nts.iloc[:365].plot(figsize=(20, 4), title=\"CO2 (ppm) in one year\")",
"_____no_output_____"
],
[
"from statsmodels.tsa.stattools import adfuller\n\n# The curve of the values seems to increase over years so it might not be stationary\nadf, p, *other_stuff = adfuller(ts)\n\nprint(f\"p-value (95% confidence interval): {p:g}, statistics: {adf:g}\")\n# p-value 1 >> 0.05 so we can't reject the hypothesis of non stationiary (Ok !)",
"p-value (95% confidence interval): 1, statistics: 3.50104\n"
],
[
"# Create a shifted version of the timeseries:\nts_shifted = ts.shift(periods=1)\nplt.figure(figsize=(5, 5))\nplt.scatter(ts, ts_shifted)\n\nplt.xlabel(\"X[t]\")\nplt.ylabel(\"X[t-1]\")\nplt.show()\n\n# It seems that X[t] explain perfectly X[t-1]",
"_____no_output_____"
],
[
"ts.hist()",
"_____no_output_____"
],
[
"from scipy import stats\n# It not seems to be normaly distribuated\nk2, p = scipy.stats.normaltest(ts)\n\nprint(f\"p-value (95% confidence interval): {p:g}, statistics: {k2:g}\")\n\n# p-value is 5e-36 << 0.5 so we can reject the null hypothesis of non normal distribution",
"p-value (95% confidence interval): 5.4641e-36, statistics: 162.39\n"
]
],
[
[
"***(Your code and explanations here and below)***",
"_____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"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e78a6512e8e2bc77a8bf82ac377cd8a6f96e89f5 | 6,181 | ipynb | Jupyter Notebook | guides/kmeans_clustering_step_by_step_guide.ipynb | RelevanceAI/RelevanceAI | a0542f35153d9c842f3d2cd0955d6b07f6dfc07b | [
"Apache-2.0"
] | 21 | 2021-11-23T13:01:36.000Z | 2022-03-23T03:45:30.000Z | guides/kmeans_clustering_step_by_step_guide.ipynb | RelevanceAI/RelevanceAI | a0542f35153d9c842f3d2cd0955d6b07f6dfc07b | [
"Apache-2.0"
] | 217 | 2021-11-23T00:11:01.000Z | 2022-03-30T08:11:49.000Z | guides/kmeans_clustering_step_by_step_guide.ipynb | RelevanceAI/RelevanceAI | a0542f35153d9c842f3d2cd0955d6b07f6dfc07b | [
"Apache-2.0"
] | 4 | 2022-01-04T01:48:30.000Z | 2022-02-11T03:19:32.000Z | 20.952542 | 190 | 0.547161 | [
[
[
"# 🍔 K Means Clustering Step By Step",
"_____no_output_____"
],
[
"# Installation",
"_____no_output_____"
]
],
[
[
"# remove `!` if running the line in a terminal\n!pip install -U RelevanceAI[notebook]==2.0.0",
"_____no_output_____"
]
],
[
[
"# Setup",
"_____no_output_____"
],
[
"First, you need to set up a client object to interact with RelevanceAI.",
"_____no_output_____"
]
],
[
[
"from relevanceai import Client\n\nclient = Client()",
"_____no_output_____"
]
],
[
[
"# Data",
"_____no_output_____"
],
[
"You will need to have a dataset under your Relevance AI account. You can either use our e-commerce dataset as shown below or follow the tutorial on how to create your own dataset.\n\nOur e-commerce dataset includes fields such as `product_title`, as well as the vectorized version of the field `product_title_clip_vector_`. Loading these documents can be done via:\n\n",
"_____no_output_____"
],
[
"## Load the data",
"_____no_output_____"
]
],
[
[
"from relevanceai.utils.datasets import get_ecommerce_dataset_encoded\n\ndocuments = get_ecommerce_dataset_encoded()\n{k: v for k, v in documents[0].items() if \"_vector_\" not in k}",
"_____no_output_____"
]
],
[
[
"## Upload the data to Relevance AI",
"_____no_output_____"
],
[
"Run the following cell, to upload these documents into your personal Relevance AI account under the name `quickstart_clustering_kmeans`",
"_____no_output_____"
]
],
[
[
"ds = client.Dataset(\"quickstart_kmeans_clustering\")\nds.insert_documents(documents)",
"_____no_output_____"
]
],
[
[
"## Check the data",
"_____no_output_____"
]
],
[
[
"ds.health()",
"_____no_output_____"
],
[
"ds.schema",
"_____no_output_____"
]
],
[
[
"# Clustering",
"_____no_output_____"
],
[
"We apply the Kmeams clustering algorithm to the vector field, `product_title_clip_vector_`",
"_____no_output_____"
]
],
[
[
"from sklearn.cluster import KMeans\n\nVECTOR_FIELD = \"product_title_clip_vector_\"\nKMEAN_NUMBER_OF_CLUSTERS = 5\nALIAS = \"kmeans_\" + str(KMEAN_NUMBER_OF_CLUSTERS)\n\nmodel = KMeans(n_clusters=KMEAN_NUMBER_OF_CLUSTERS)\nclusterer = client.ClusterOps(alias=ALIAS, model=model)\nclusterer.run(\n dataset_id=\"quickstart_kmeans_clustering\",\n vector_fields=[\"product_title_clip_vector_\"],\n)",
"_____no_output_____"
],
[
"# List closest to center of the cluster\n\nclusterer.list_closest(\n dataset_id=\"quickstart_kmeans_clustering\", vector_field=\"product_title_clip_vector_\"\n)",
"_____no_output_____"
],
[
"# List furthest from the center of the cluster\n\nclusterer.list_furthest(\n dataset_id=\"quickstart_kmeans_clustering\", vector_field=\"product_title_clip_vector_\"\n)",
"_____no_output_____"
]
],
[
[
"We download a small sample and show the clustering results using our json_shower.",
"_____no_output_____"
]
],
[
[
"from relevanceai import show_json\n\nsample_documents = ds.sample(n=5)\nsamples = [\n {\n \"product_title\": d[\"product_title\"],\n \"cluster\": d[\"_cluster_\"][VECTOR_FIELD][ALIAS],\n }\n for d in sample_documents\n]\n\nshow_json(samples, text_fields=[\"product_title\", \"cluster\"])",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e78a6f36e1e522c60b84b8b38ce5627777555e93 | 6,287 | ipynb | Jupyter Notebook | docs/source/examples/Image Processing.ipynb | akhand1111/ipywidgets | a6228df8a24079bd4f8b6c1645b31e1c00218535 | [
"BSD-3-Clause"
] | 1 | 2019-09-08T18:11:03.000Z | 2019-09-08T18:11:03.000Z | docs/source/examples/Image Processing.ipynb | akhand1111/ipywidgets | a6228df8a24079bd4f8b6c1645b31e1c00218535 | [
"BSD-3-Clause"
] | 3 | 2020-01-18T12:26:26.000Z | 2020-01-20T13:17:32.000Z | docs/source/examples/Image Processing.ipynb | akhand1111/ipywidgets | a6228df8a24079bd4f8b6c1645b31e1c00218535 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T05:58:42.000Z | 2021-01-28T05:58:42.000Z | 27.696035 | 240 | 0.556068 | [
[
[
"# Image Manipulation with skimage",
"_____no_output_____"
],
[
"This example builds a simple UI for performing basic image manipulation with [scikit-image](http://scikit-image.org/).",
"_____no_output_____"
]
],
[
[
"# Stdlib imports\nfrom io import BytesIO\n\n# Third-party libraries\nfrom IPython.display import Image\nfrom ipywidgets import interact, interactive, fixed\nimport matplotlib as mpl\nfrom skimage import data, filters, io, img_as_float\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"Let's load an image from scikit-image's collection, stored in the `data` module. These come back as regular numpy arrays:",
"_____no_output_____"
]
],
[
[
"i = img_as_float(data.coffee())\ni.shape",
"_____no_output_____"
]
],
[
[
"Let's make a little utility function for displaying Numpy arrays with the IPython display protocol:",
"_____no_output_____"
]
],
[
[
"def arr2img(arr):\n \"\"\"Display a 2- or 3-d numpy array as an image.\"\"\"\n if arr.ndim == 2:\n format, cmap = 'png', mpl.cm.gray\n elif arr.ndim == 3:\n format, cmap = 'jpg', None\n else:\n raise ValueError(\"Only 2- or 3-d arrays can be displayed as images.\")\n # Don't let matplotlib autoscale the color range so we can control overall luminosity\n vmax = 255 if arr.dtype == 'uint8' else 1.0\n with BytesIO() as buffer:\n mpl.image.imsave(buffer, arr, format=format, cmap=cmap, vmin=0, vmax=vmax)\n out = buffer.getvalue()\n return Image(out)",
"_____no_output_____"
],
[
"arr2img(i)",
"_____no_output_____"
]
],
[
[
"Now, let's create a simple \"image editor\" function, that allows us to blur the image or change its color balance:",
"_____no_output_____"
]
],
[
[
"def edit_image(image, sigma=0.1, R=1.0, G=1.0, B=1.0):\n new_image = filters.gaussian(image, sigma=sigma, multichannel=True)\n new_image[:,:,0] = R*new_image[:,:,0]\n new_image[:,:,1] = G*new_image[:,:,1]\n new_image[:,:,2] = B*new_image[:,:,2]\n return arr2img(new_image)",
"_____no_output_____"
]
],
[
[
"We can call this function manually and get a new image. For example, let's do a little blurring and remove all the red from the image:",
"_____no_output_____"
]
],
[
[
"edit_image(i, sigma=5, R=0.1)",
"_____no_output_____"
]
],
[
[
"But it's a lot easier to explore what this function does by controlling each parameter interactively and getting immediate visual feedback. IPython's `ipywidgets` package lets us do that with a minimal amount of code:",
"_____no_output_____"
]
],
[
[
"lims = (0.0,1.0,0.01)\ninteract(edit_image, image=fixed(i), sigma=(0.0,10.0,0.1), R=lims, G=lims, B=lims);",
"_____no_output_____"
]
],
[
[
"# Browsing the scikit-image gallery, and editing grayscale and jpg images\n\nThe coffee cup isn't the only image that ships with scikit-image, the `data` module has others. Let's make a quick interactive explorer for this:",
"_____no_output_____"
]
],
[
[
"def choose_img(name):\n # Let's store the result in the global `img` that we can then use in our image editor below\n global img\n img = getattr(data, name)()\n return arr2img(img)\n\n# Skip 'load' and 'lena', two functions that don't actually return images\ninteract(choose_img, name=sorted(set(data.__all__)-{'lena', 'load'}));",
"_____no_output_____"
]
],
[
[
"And now, let's update our editor to cope correctly with grayscale and color images, since some images in the scikit-image collection are grayscale. For these, we ignore the red (R) and blue (B) channels, and treat 'G' as 'Grayscale':",
"_____no_output_____"
]
],
[
[
"lims = (0.0, 1.0, 0.01)\n\ndef edit_image(image, sigma, R, G, B):\n new_image = filters.gaussian(image, sigma=sigma, multichannel=True)\n if new_image.ndim == 3:\n new_image[:,:,0] = R*new_image[:,:,0]\n new_image[:,:,1] = G*new_image[:,:,1]\n new_image[:,:,2] = B*new_image[:,:,2]\n else:\n new_image = G*new_image\n return arr2img(new_image)\n\ninteract(edit_image, image=fixed(img), sigma=(0.0, 10.0, 0.1), \n R=lims, G=lims, B=lims);",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e78a769ebaa5355eebabd6a72bf40252e5e43454 | 289,070 | ipynb | Jupyter Notebook | misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb | srcole/qwm | 83eb7d6209f9ef45bd475166039afb15702b2eda | [
"MIT"
] | 13 | 2016-01-27T17:46:29.000Z | 2021-06-07T22:35:15.000Z | misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb | srcole/qwm | 83eb7d6209f9ef45bd475166039afb15702b2eda | [
"MIT"
] | null | null | null | misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb | srcole/qwm | 83eb7d6209f9ef45bd475166039afb15702b2eda | [
"MIT"
] | 19 | 2016-07-03T18:04:06.000Z | 2021-04-20T06:21:50.000Z | 1,383.110048 | 284,916 | 0.948563 | [
[
[
"# Compare phase estimation methods on hippocampal theta oscillations",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport scipy as sp\n\n%matplotlib notebook\n%config InlineBackend.figure_format = 'retina'\n%matplotlib inline\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"# Load data",
"_____no_output_____"
]
],
[
[
"x = np.load('/gh/data2/hc3/npy/gor01/2006-6-7_16-40-19/10/lfp_0.npy')\nx = x[10000:30000]\nFs = 1252",
"_____no_output_____"
]
],
[
[
"# Preprocess data",
"_____no_output_____"
]
],
[
[
"cflow = 50\nNtapslow = 501\ncfhigh = 1\nNtapshigh = 1001\n\nfrom misshapen import nonshape\nx = nonshape.highpass_default(x, Fs, cfhigh, Ntapshigh)\nx = nonshape.lowpass_default(x, Fs, cflow, Ntapslow)",
"_____no_output_____"
]
],
[
[
"# Compute phase time series",
"_____no_output_____"
],
[
"### Bandpass + hilbert",
"_____no_output_____"
]
],
[
[
"f_range = (4,10)\nx_filt, _ = nonshape.bandpass_default(x, f_range, Fs, rmv_edge=False)\npha_h = np.angle(sp.signal.hilbert(x_filt))",
"_____no_output_____"
]
],
[
[
"### Peak and trough interpolation",
"_____no_output_____"
]
],
[
[
"Ps, Ts = nonshape.findpt(x, f_range, Fs)\npha_pt = nonshape.wfpha(x, Ps, Ts)",
"_____no_output_____"
]
],
[
[
"# Compare phase time series",
"_____no_output_____"
]
],
[
[
"t = np.arange(0,len(x)/Fs, 1/Fs)\ntlims = [1,3]\nsamps = np.logical_and(t>=tlims[0],t<tlims[1])\n\nplt.figure(figsize=(16,6))\nplt.subplot(2,1,1)\nplt.plot(t[samps],x[samps],'k')\nplt.xlim(tlims)\nplt.ylabel('Voltage (uV)',size=20)\nplt.subplot(2,1,2)\nplt.plot(t[samps],pha_h[samps],'r',label='Hilbert')\nplt.plot(t[samps],pha_pt[samps],'b',label='waveform')\nplt.xlim(tlims)\nplt.xlabel('Time (s)',size=20)\nplt.ylabel('Phase (rad)',size=20)\nplt.legend(loc='best',title='Phase estimate method')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e78a8faface10bf9befa6009c889fb25c3095365 | 3,875 | ipynb | Jupyter Notebook | Projects/Housing/Code/Housing data download.ipynb | drnesr/Machine_Learning | 78f6b0c47fb45f39daff60325a32ee15aa9f9a2b | [
"MIT"
] | null | null | null | Projects/Housing/Code/Housing data download.ipynb | drnesr/Machine_Learning | 78f6b0c47fb45f39daff60325a32ee15aa9f9a2b | [
"MIT"
] | null | null | null | Projects/Housing/Code/Housing data download.ipynb | drnesr/Machine_Learning | 78f6b0c47fb45f39daff60325a32ee15aa9f9a2b | [
"MIT"
] | null | null | null | 23.628049 | 102 | 0.557935 | [
[
[
"## Downloading data dynamically",
"_____no_output_____"
]
],
[
[
"# Required libraries\nimport os\nimport tarfile\nimport urllib",
"_____no_output_____"
],
[
"# DOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml2/master/\"\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml/master/\"\n# HOUSING_PATH = os.path.join('datasets', 'housing')\nHOUSING_PATH = '../Datasets'\nHOUSING_URL = DOWNLOAD_ROOT + \"datasets/housing/housing.tgz\"\nprint(HOUSING_URL)\nprint('https://raw.githubusercontent.com/ageron/handson-ml/master/datasets/housing/housing.tgz')",
"https://raw.githubusercontent.com/ageron/handson-ml/master/datasets/housing/housing.tgz\nhttps://raw.githubusercontent.com/ageron/handson-ml/master/datasets/housing/housing.tgz\n"
],
[
"def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):\n os.makedirs(housing_path, exist_ok=True)\n tgz_path = os.path.join(housing_path, 'housing.tgz')\n urllib.request.urlretrieve(housing_url, tgz_path)\n # print('1')\n housing_tgz = tarfile.open(tgz_path)\n # print('2')\n housing_tgz.extractall(path=housing_path)\n # print('3')\n housing_tgz.close()\n print(\"*File downloaded and extracted successfully*\")",
"_____no_output_____"
],
[
"fetch_housing_data()",
"1\n2\n3\n*File downloaded and extracted successfully*\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e78a9472653d9da424835b974654032e53b01133 | 14,389 | ipynb | Jupyter Notebook | PSForest_example.ipynb | nishiwen1214/PSForest | 87aa70e6044c393b4aaf243bf9d49fae3355a03d | [
"MIT"
] | 35 | 2021-09-03T13:36:32.000Z | 2021-12-13T12:48:42.000Z | PSForest_example.ipynb | nishiwen1214/PSForest | 87aa70e6044c393b4aaf243bf9d49fae3355a03d | [
"MIT"
] | null | null | null | PSForest_example.ipynb | nishiwen1214/PSForest | 87aa70e6044c393b4aaf243bf9d49fae3355a03d | [
"MIT"
] | 1 | 2022-01-17T10:53:43.000Z | 2022-01-17T10:53:43.000Z | 30.614894 | 103 | 0.470776 | [
[
[
"import numpy as np\nimport pandas as pd\nimport random\nimport uuid\nimport time\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\n# from sklearn.datasets import fetch_mldata\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, f1_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_iris, load_digits\n\n\nfrom PSForest import PSForest\nimport os\nimport pickle\nimport matplotlib.pyplot as plt\nimport h5py\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nimport memory_profiler",
"_____no_output_____"
]
],
[
[
"Load dataset:\nMNIST and CIFAR10",
"_____no_output_____"
]
],
[
[
"mnist = fetch_openml(\"mnist_784\")\nmnist.data.shape\n\nprint('Data: {}, target: {}'.format(mnist.data.shape, mnist.target.shape))",
"Data: (70000, 784), target: (70000,)\n"
],
[
"X_train, X_test, y_train, y_test = train_test_split(\n mnist.data,\n mnist.target,\n test_size=1/7,\n random_state=0,\n)\n\nX_train = X_train.values.reshape((len(X_train), 784))\nX_test = X_test.values.reshape((len(X_test), 784))\n\n\n#Limit the size of the dataset\n\nX_train = X_train[:1000]\ny_train = y_train[:1000]\nX_test = X_test[:500]\ny_test = y_test[:500]\n\nprint('X_train:', X_train.shape, X_train.dtype)\nprint('y_train:', y_train.shape, y_train.dtype)\nprint('X_test:', X_test.shape)\nprint('y_test:', y_test.shape)\n# X_train",
"X_train: (1000, 784) float64\ny_train: (1000,) category\nX_test: (500, 784)\ny_test: (500,)\n"
],
[
"%matplotlib inline\ndef load_CIFAR_batch(filename):\n with open(filename, 'rb') as f:\n datadict = pickle.load(f,encoding='latin1')\n X = datadict['data']\n Y = datadict['labels']\n X = X.reshape(10000, 3, 32, 32).transpose(0,2,3,1).astype(\"float\")\n Y = np.array(Y)\n return X, Y\ndef load_CIFAR10():\n xs = []\n ys = []\n for b in range(1,6):\n f = os.path.join('datasets', 'cifar-10-batches-py', 'data_batch_%d' % (b, ))\n X, Y = load_CIFAR_batch(f)\n xs.append(X)\n ys.append(Y) \n Xtr = np.concatenate(xs)\n Ytr = np.concatenate(ys)\n del X, Y\n Xte, Yte = load_CIFAR_batch(os.path.join('datasets', 'cifar-10-batches-py', 'test_batch'))\n return Xtr, Ytr, Xte, Yte",
"_____no_output_____"
],
[
"X_train, y_train, X_test, y_test = load_CIFAR10()\nclasses = ['plane', 'car', 'bird', 'cat', 'dear', 'dog', 'frog', 'horse', 'ship', 'truck']\nnum_classes = len(classes)\nnum_each_class = 7\n\nfor y, cls in enumerate(classes):\n idxs = np.flatnonzero(y_train == y)\n idxs = np.random.choice(idxs, num_each_class, replace=False)\n for i, idx in enumerate(idxs):\n plt_idx = i * num_classes + (y + 1)\n plt.subplot(num_each_class, num_classes, plt_idx)\n plt.imshow(X_train[idx].astype('uint8'))\n plt.axis('off')\n if i == 0:\n plt.title(cls)\nplt.show()\nX_train.shape",
"_____no_output_____"
],
[
"X_train = np.reshape(X_train, (X_train.shape[0], -1))\nX_test = np.reshape(X_test, (X_test.shape[0], -1))\n# Divide the sub-data set\ny_train = y_train[:1000]\ny_test = y_test[:1000]\nX_train = X_train[:1000]\nX_test = X_test[:1000]\nX_train.shape",
"_____no_output_____"
]
],
[
[
"## Using the PSForest",
"_____no_output_____"
]
],
[
[
"start =time.clock()\nbefore_mem = memory_profiler.memory_usage()\n# Create PSForest model\nps_forest = PSForest(\n estimators_config={\n 'mgs': [{\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'max_features': 1,\n 'min_samples_split': 10,\n 'n_jobs': -1,\n }\n }, {\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'max_features': 1,\n 'min_samples_split': 10,\n 'n_jobs': -1,\n }\n },{\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 'sqrt',\n 'n_jobs': -1,\n }\n },{\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 'sqrt',\n 'n_jobs': -1,\n }\n }],\n 'cascade': [{\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 1,\n 'oob_score':True,\n 'n_jobs': -1,\n }\n }, {\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 'sqrt',\n 'oob_score':True,\n 'n_jobs': -1,\n }\n }, {\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 1,\n 'oob_score':True,\n 'n_jobs': -1,\n }\n }, {\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 'sqrt',\n 'oob_score':True,\n 'n_jobs': -1,\n } \n },{\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 1,\n 'oob_score':True,\n 'n_jobs': -1,\n }\n }, {\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 'sqrt',\n 'oob_score':True,\n 'n_jobs': -1,\n }\n }, {\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 1,\n 'oob_score':True,\n 'n_jobs': -1,\n }\n }, {\n 'estimator_class': RandomForestClassifier,\n 'estimator_params': {\n 'n_estimators': 500,\n 'min_samples_split': 10,\n 'max_features': 'sqrt',\n 'oob_score':True,\n 'n_jobs': -1,\n } \n }]\n },\n stride_ratios=[1/256,1/128,1/64,1/32,1/16,1/8,1/4],\n)\n\n# ps_forest.fit(X_train, y_train) # with Multi-Grained Pooling\nps_forest.fit_c(X_train, y_train) # without Multi-Grained Pooling\nafter_mem = memory_profiler.memory_usage()\nend = time.clock()\nprint(\"Memory (Before): {}Mb\".format(before_mem))\nprint(\"Memory (After): {}Mb\".format(after_mem))\nprint(\"Memory consumption: {}Mb\".format(after_mem[0] - before_mem[0])) ",
"<Gate-CascadeForest forests=8> - Cascade fitting for X ((1000, 784)) and y ((1000,)) started\n<Gate-CascadeForest forests=8> - Level #1:: X with shape: (1000, 784)\n<Gate-CascadeForest forests=8> - Level 1:: got all predictions\n<Gate-CascadeForest forests=8> - Level 1:: got accuracy 0.87\n<Gate-CascadeForest forests=8> - Level #2:: X with shape: (1000, 844)\n"
],
[
"# y_pred = ps_forest.predict(X_test) # with Multi-Grained Pooling\ny_pred = ps_forest.predict_c(X_test) # without Multi-Grained Pooling\nprint('Prediction shape:', y_pred.shape)\nprint(\n 'Accuracy:', accuracy_score(y_test, y_pred),\n 'F1 score:', f1_score(y_test, y_pred, average='weighted')\n)\n\nprint('Running time: %s Seconds'%(end-start))\n",
"<Gate-CascadeForest forests=8> - Shape of predictions: (8, 500, 10) shape of X: (500, 784)\n"
],
[
"# RandomForest\nrf = RandomForestClassifier()\nrf.fit(X_train, y_train)\nrf_y_pred = rf.predict(X_test)\nacc = accuracy_score(y_test, rf_y_pred)\nprint('accuracy:', acc)",
"accuracy: 0.896\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e78a9776f3b6e74f06bb63a831cbc98fb008dd89 | 2,497 | ipynb | Jupyter Notebook | scala/Optional side-effect.ipynb | ashishpatel26/learning | b9e9472a70841061d2e755659872c8b093124f89 | [
"MIT"
] | 54 | 2017-09-10T17:28:21.000Z | 2021-12-17T14:55:04.000Z | scala/Optional side-effect.ipynb | parvathirajan/learning | bb112015d4513414bf86c7392c12b13f8d0fdd21 | [
"MIT"
] | 1 | 2019-07-04T21:57:14.000Z | 2019-07-04T21:57:14.000Z | scala/Optional side-effect.ipynb | parvathirajan/learning | bb112015d4513414bf86c7392c12b13f8d0fdd21 | [
"MIT"
] | 36 | 2017-11-13T16:54:58.000Z | 2022-02-07T11:20:20.000Z | 18.774436 | 194 | 0.507008 | [
[
[
"# Optional side-effect",
"_____no_output_____"
]
],
[
[
"val nameOpt = Option(\"Amir\")\n\ndef printName(name: String) = println(name)",
"_____no_output_____"
],
[
"nameOpt.foreach(printName)",
"Amir"
],
[
"val anotherOpt = None",
"_____no_output_____"
],
[
"anotherOpt.foreach(printName)",
"_____no_output_____"
]
],
[
[
"This is a great pattern for optinally generating side-effects given an option that you take from the command line, namely in conjunction with [scallop](https://github.com/scallop/scallop).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e78aa2136d23e935c3e88d9e5973241a09973832 | 229,650 | ipynb | Jupyter Notebook | Python/Jupyter/.ipynb_checkpoints/Untitled3-checkpoint.ipynb | YagoLopes/apoio-css | 91c34b798bc67d95a9494abb87fe0e9898d94e75 | [
"MIT"
] | 1 | 2020-07-25T00:24:10.000Z | 2020-07-25T00:24:10.000Z | Python/Jupyter/.ipynb_checkpoints/Untitled3-checkpoint.ipynb | YagoLopes/apoio-css | 91c34b798bc67d95a9494abb87fe0e9898d94e75 | [
"MIT"
] | 11 | 2021-03-10T15:57:06.000Z | 2022-02-27T03:34:45.000Z | Python/Jupyter/.ipynb_checkpoints/Untitled3-checkpoint.ipynb | YagoLopes/apoio-css | 91c34b798bc67d95a9494abb87fe0e9898d94e75 | [
"MIT"
] | null | null | null | 37.286897 | 92 | 0.299639 | [
[
[
"import pandas as pd ",
"_____no_output_____"
],
[
"dataset = pd.read_csv('/home/yago/analisedados/kaggle_medical.csv', sep=',')",
"_____no_output_____"
],
[
"type(dataset)",
"_____no_output_____"
],
[
"dataset.head()",
"_____no_output_____"
],
[
"dataset.columns",
"_____no_output_____"
],
[
"dataset.count()",
"_____no_output_____"
],
[
"dataset.describe()",
"_____no_output_____"
],
[
"pd.value_counts(dataset['bedrooms'])",
"_____no_output_____"
],
[
"dataset.loc[dataset['bedrooms']==3]",
"_____no_output_____"
],
[
"dataset.loc[(dataset['bedrooms']==3) & (dataset['bathrooms'] > 2)]",
"_____no_output_____"
],
[
"dataset.sort_values(by='price', ascending=False)",
"_____no_output_____"
],
[
"dataset[dataset['bedrooms']==4].count()",
"_____no_output_____"
],
[
"dataset['size'] = (dataset['bedrooms']*20)",
"_____no_output_____"
],
[
"dataset['size']",
"_____no_output_____"
],
[
"#Ver a distribuição da coluna\npd.value_counts(dataset['cat_size'])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e78ab52e15acbdc0efd85d54a824d6b8ad70e33e | 36,378 | ipynb | Jupyter Notebook | europython_2015_logging_talk.ipynb | stbaercom/europython2015_logging | b9bc4a32db294f6300ca1c83efacce4967ba5b2f | [
"MIT"
] | 2 | 2018-07-27T14:42:38.000Z | 2019-05-26T13:08:56.000Z | europython_2015_logging_talk.ipynb | stbaercom/europython2015_logging | b9bc4a32db294f6300ca1c83efacce4967ba5b2f | [
"MIT"
] | null | null | null | europython_2015_logging_talk.ipynb | stbaercom/europython2015_logging | b9bc4a32db294f6300ca1c83efacce4967ba5b2f | [
"MIT"
] | 2 | 2015-07-21T13:40:33.000Z | 2019-08-28T01:37:55.000Z | 27.249438 | 1,134 | 0.508054 | [
[
[
"from __future__ import print_function\nimport presentation_helper",
"_____no_output_____"
]
],
[
[
"<center>\n<img width=\"95%\" src=\"figures/europython_title_img.png\"/>\n</center>",
"_____no_output_____"
],
[
"## Agenda\n\n- Why Logging\n- How does Logging work for you?\n- Optional Content",
"_____no_output_____"
],
[
"## The Presentation\n- The slides, support code and jypyter notebook are on Github\n- [https://github.com/stbaercom/europython2015_logging](https://github.com/stbaercom/europython2015_logging)",
"_____no_output_____"
],
[
"## A Simple Program, Without any Logging",
"_____no_output_____"
]
],
[
[
"from datetime import datetime\n\ndef my_division_p(dividend, divisor):\n try:\n print(\"Debug, Division : {}/{}\".format(dividend,divisor))\n result = dividend / divisor\n return result\n except (ZeroDivisionError, TypeError):\n print(\"Error, Division Failed\")\n return None\ndef division_task_handler_p(task):\n print(\"Handling division task,{} items\".format(len(task)))\n result = []\n for i, task in enumerate(task):\n print(\"Doing devision iteration {} on {:%Y}\".format(i,datetime.now()))\n dividend, divisor = task\n result.append(my_division_p(dividend,divisor))\n return result",
"_____no_output_____"
]
],
[
[
"## Let us Have a Look at the Output",
"_____no_output_____"
]
],
[
[
"task = [(3,4),(5,1.4),(2,0),(3,5),(\"10\",1)]\ndivision_task_handler_p(task)",
"Handling division task,5 items\nDoing devision iteration 0 on 2015\nDebug, Division : 3/4\nDoing devision iteration 1 on 2015\nDebug, Division : 5/1.4\nDoing devision iteration 2 on 2015\nDebug, Division : 2/0\nError, Division Failed\nDoing devision iteration 3 on 2015\nDebug, Division : 3/5\nDoing devision iteration 4 on 2015\nDebug, Division : 10/1\nError, Division Failed\n"
]
],
[
[
"## The Problems with ``print()``\n\n- We don't have a way to select the types of messages we are interested in\n- We have to add all information (timestamps, etc...) by ourselves\n- All our messages will look slightly different\n- We have only limited control where our message end up",
"_____no_output_____"
],
[
"## What is Different with Logging?\n- We have more structure, and easier parsing\n- The logging module provides some extra informaiton (Logger, Level, and Formating)\n- We Handling of exception essentially for free.",
"_____no_output_____"
],
[
"## Aspects of a Logging Message",
"_____no_output_____"
],
[
"<center>\n<img width=\"95%\" src=\"figures/DimensionsLogging.png\"/>\n</center>",
"_____no_output_____"
],
[
"## Using the Logging Module for Comparison",
"_____no_output_____"
]
],
[
[
"import log1; logging = log1.get_clean_logging()\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger()\n\ndef my_division(dividend, divisor):\n try:\n log.debug(\"Division : %s/%s\", dividend, divisor)\n result = dividend / divisor\n return result\n except (ZeroDivisionError, TypeError):\n log.exception(\"Error, Division Failed\")\n return None\n\ndef division_task_handler(task):\n log.info(\"Handling division task,%s items\",len(task))\n result = []\n for i, task in enumerate(task):\n log.info(\"Doing devision iteration %s\",i)\n dividend, divisor = task\n result.append(my_division(dividend,divisor))\n return result",
"_____no_output_____"
]
],
[
[
"## The Call and the Log Messages",
"_____no_output_____"
]
],
[
[
"task = [(3,4),(2,0),(3,5),(\"10\",1)]\ndivision_task_handler(task)",
"INFO:root:Handling division task,4 items\nINFO:root:Doing devision iteration 0\nDEBUG:root:Division : 3/4\nINFO:root:Doing devision iteration 1\nDEBUG:root:Division : 2/0\nERROR:root:Error, Division Failed\nTraceback (most recent call last):\n File \"<ipython-input-10-a904db1e3e23>\", line 8, in my_division\n result = dividend / divisor\nZeroDivisionError: division by zero\nINFO:root:Doing devision iteration 2\nDEBUG:root:Division : 3/5\nINFO:root:Doing devision iteration 3\nDEBUG:root:Division : 10/1\nERROR:root:Error, Division Failed\nTraceback (most recent call last):\n File \"<ipython-input-10-a904db1e3e23>\", line 8, in my_division\n result = dividend / divisor\nTypeError: unsupported operand type(s) for /: 'str' and 'int'\n"
]
],
[
[
"## How does the Logging Module represent these Aspect",
"_____no_output_____"
],
[
"<center>\n<img width=\"90%\" src=\"figures/DimensionsLoggingImp.png\"/>\n</center>",
"_____no_output_____"
],
[
"## Back to Code. How does Logging Work?",
"_____no_output_____"
]
],
[
[
"import log1;logging = log1.get_clean_logging() # this would be import logging outside this notebook\n\nlogging.debug(\"Find me in the log\")\nlogging.info(\"I am hidden\")\nlogging.warn(\"I am here\")\nlogging.error(\"As am I\")\ntry: \n 1/0; \nexcept:\n logging.exception(\" And I\")\nlogging.critical(\"Me, of course\")",
"WARNING:root:I am here\nERROR:root:As am I\nERROR:root: And I\nTraceback (most recent call last):\n File \"<ipython-input-12-75f8227eec02>\", line 8, in <module>\n 1/0;\nZeroDivisionError: division by zero\nCRITICAL:root:Me, of course\n"
]
],
[
[
"## More Complex Logging Setup with ``basicConfig()``",
"_____no_output_____"
]
],
[
[
"import log1;logging = log1.get_clean_logging()\n\ndatefmt = \"%Y-%m-%d %H:%M:%S\"\nmsgfmt = \"%(asctime)s,%(msecs)03d %(levelname)-10s %(name)-15s : %(message)s\"\nlogging.basicConfig(level=logging.DEBUG, format=msgfmt, datefmt=datefmt)\nlogging.debug(\"Now I show up \")\nlogging.info(\"Now this is %s logging!\",\"good\")\nlogging.warn(\"I am here. %-4i + %-4i = %i\",1,3,1+3)\nlogging.error(\"As am I\")\ntry: \n 1/0; \nexcept:\n logging.exception(\" And I\")",
"2015-07-19 20:19:55,551 DEBUG root : Now I show up \n2015-07-19 20:19:55,552 INFO root : Now this is good logging!\n2015-07-19 20:19:55,552 WARNING root : I am here. 1 + 3 = 4\n2015-07-19 20:19:55,552 ERROR root : As am I\n2015-07-19 20:19:55,553 ERROR root : And I\nTraceback (most recent call last):\n File \"<ipython-input-13-63765f2f7e9f>\", line 12, in <module>\n 1/0;\nZeroDivisionError: division by zero\n"
]
],
[
[
"## Some (personal) Remarks about ``basicConfig()``\n- `basicConfig()` does save you some typing, but I would go for the 'normal' setup. \n- Using `basicConfig()` is a matter of personal taste.\n- The normal setup makes the structure clearer.\n- Keep in mind that basicConfig() is meant to be called once...",
"_____no_output_____"
],
[
"## Using the Standard Configuration",
"_____no_output_____"
]
],
[
[
"import log1, json, logging.config;logging = log1.get_clean_logging()\ndatefmt = \"%Y-%m-%d %H:%M:%S\"\nmsgfmt = \"%(asctime)s,%(msecs)03d %(levelname)-6s %(name)-10s : %(message)s\"\n\nlog = logging.getLogger() \nlog.setLevel(logging.DEBUG)\nlh = logging.StreamHandler()\nlf = logging.Formatter(fmt=msgfmt, datefmt=datefmt)\nlh.setFormatter(lf)\nlog.addHandler(lh)\n\nlog.info(\"Now this is %s logging!\",\"good\")\nlog.debug(\"A slightly more complex message %s + %s = %s\",1,2,1+2)",
"2015-07-19 20:19:55,571 INFO root : Now this is good logging!\n2015-07-19 20:19:55,572 DEBUG root : A slightly more complex message 1 + 2 = 3\n"
]
],
[
[
"## Now, back to the Theory. What have we Build?\n<center>\n<img src=\"figures/LogTree_Basic.png\" width=\"90%\"/>\n</center>",
"_____no_output_____"
],
[
"## How do we get from the Configuration to the Log Message?\n<center>\n<img src=\"figures/Format.png\" width=\"95%\"/>\n</center>",
"_____no_output_____"
],
[
"## Formatting : Attributes Available for the Logging Call",
"_____no_output_____"
],
[
"<table height=\"80%\" class=\"bst\"><tr><th>Attribute</th><th>Description</th></tr><tr><td>args</td><td>Tuple of arguments passed to the logging call</td></tr><tr><td>asctime</td><td>Log record creation time, formatted</td></tr><tr><td>created</td><td>Log record creation time, seconds since the Epoch</td></tr><tr><td>exc_info</td><td>Exception information / stack trace, if any</td></tr><tr><td>filename</td><td>Filename portion of pathname for the logging module</td></tr><tr><td>funcName</td><td>Name of function containing the logging call</td></tr><tr><td>levelname</td><td>Name of Logging Level</td></tr><tr><td>levelno</td><td>Number of Logging Level</td></tr><tr><td>lineno</td><td>Line number in source code for the logging call</td></tr><tr><td>module</td><td>Module (name portion of filename).</td></tr><tr><td>message</td><td>Logged message</td></tr><tr><td>name</td><td>Name of the logger used to log the call.</td></tr><tr><td>pathname</td><td>pathname of source file</td></tr><tr><td>process</td><td>Process ID</td></tr><tr><td>processName</td><td>Process name</td></tr><tr><td>...</td><td>...</td></tr></table>",
"_____no_output_____"
],
[
"## Using ``dictConfig()``",
"_____no_output_____"
]
],
[
[
"import log1, json, logging.config;logging = log1.get_clean_logging()\nconf_dict = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'longformat': {\n 'format': \"%(asctime)s,%(msecs)03d %(levelname)-10s %(name)-15s : %(message)s\",\n 'datefmt': \"%Y-%m-%d %H:%M:%S\"}},\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': \"longformat\"}},\n 'loggers':{\n '': {\n 'level': 'DEBUG',\n 'handlers': ['console']}}}\nlogging.config.dictConfig(conf_dict) \nlog = logging.getLogger() \nlog.info(\"Now this is %s logging!\",\"good\")",
"2015-07-19 20:19:55,602 INFO root : Now this is good logging!\n"
]
],
[
[
"## Adding a ``Filehandler`` to the Logger",
"_____no_output_____"
]
],
[
[
"import log1, json, logging.config;logging = log1.get_clean_logging()\nbase_config = json.load(open(\"conf_dict.json\"))\n\nbase_config['handlers']['logfile'] = {\n 'class' : 'logging.FileHandler',\n 'mode' : 'w',\n 'filename' : 'logfile.txt',\n 'formatter': \"longformat\"}\nbase_config['loggers']['']['handlers'].append('logfile')\nlogging.config.dictConfig(base_config)\nlog = logging.getLogger() \nlog.info(\"Now this is %s logging!\",\"good\")\n!cat logfile.txt",
"2015-07-19 20:19:55,618 INFO root : Now this is good logging!\n"
]
],
[
[
" ## Another look at the logging object tree\n<center>\n<img src=\"figures/LogTree_File.png\" width=\"80%\"/>\n</center>",
"_____no_output_____"
],
[
"## Set the Level on the ``FileHandler``",
"_____no_output_____"
]
],
[
[
"import log1, json, logging.config;logging = log1.get_clean_logging()\n\nfile_config = json.load(open(\"conf_dict_with_file.json\"))\nfile_config['handlers']['logfile']['level'] = \"WARN\"\nlogging.config.dictConfig(file_config)\nlog = logging.getLogger() \nlog.info(\"Now this is %s logging!\",\"good\")\nlog.warning(\"Now this is %s logging!\",\"worrisome\")\n!cat logfile.txt",
"2015-07-20 19:04:03,132 INFO root : Now this is good logging!\n2015-07-20 19:04:03,133 WARNING root : Now this is worrisome logging!\n"
]
],
[
[
"## Adding Child Loggers under the Root",
"_____no_output_____"
]
],
[
[
"import log1,json,logging.config;logging = log1.get_clean_logging()\nlogging.config.dictConfig(json.load(open(\"conf_dict.json\")))\nlog = logging.getLogger(\"\") \nchild_A = logging.getLogger(\"A\") \nchild_B = logging.getLogger(\"B\") \nchild_B_A = logging.getLogger(\"B.A\")\nlog.info(\"Now this is %s logging!\",\"good\")\nchild_A.info(\"Now this is more logging!\")\nlog.warning(\"Now this is %s logging!\",\"worrisome\")",
"2015-07-19 20:19:55,865 INFO root : Now this is good logging!\n2015-07-19 20:19:55,866 INFO A : Now this is more logging!\n2015-07-19 20:19:55,867 WARNING root : Now this is worrisome logging!\n"
]
],
[
[
" ## Looking at the tree of Logging Objects\n<center>\n<img src=\"figures/LogTree_Full.png\" width=\"90%\"/>\n</center>",
"_____no_output_____"
],
[
"## Best Practices for the Logging Tree\n- Use ``.getLogger(__name__)`` per module to define loggers under the root logger\n- Set propagate to True on each Logger\n- Attach Handlers and Filters as needed to control output from the Logging hierarchy",
"_____no_output_____"
],
[
"## Filter - Now that things are Getting Complicated\n- With more loggers and handlers in the tree of logging objects, things are getting complicated\n- We may not want every logger to send log records to every filter\n- The logging level gives us some control, there are limits\n- Filters are one solution to this problem\n- Filter can also **add** information to records, thus helping with structured logging",
"_____no_output_____"
],
[
"## Using Filters\n<center>\n<img src=\"figures/LogTree_Filter.png\" width=\"80%\"/>\n</center>",
"_____no_output_____"
],
[
"## An Example for using Filter Objects",
"_____no_output_____"
]
],
[
[
"import log1,json,logging.config;logging = log1.get_clean_logging()\nlogging.config.dictConfig(json.load(open(\"conf_dict.json\")))\n\ndef log_filter(rec): # Callables work with 3.2 and later\n if 'please' in rec.msg.lower():\n return True\n return False\nlog = logging.getLogger(\"\") \nlog.addFilter(log_filter)\nchild_A = logging.getLogger(\"A\") \n\nlog.info(\"Just log me\")\nchild_A.info(\"Just log me\")\nlog.info(\"Hallo, Please log me\")\n",
"2015-07-20 08:01:55,108 INFO A : Just log me\n2015-07-20 08:01:55,108 INFO root : Hallo, Please log me\n"
]
],
[
[
"## The Way of a Logging Record\n<center>\n<img src=\"figures/LoggingFlow.png\" width=\"100%\"/>\n</center>",
"_____no_output_____"
],
[
"## A second Example for Filters, in the LogHandler",
"_____no_output_____"
]
],
[
[
"import log1, json, logging.config;logging = log1.get_clean_logging()\ndatefmt = \"%Y-%m-%d %H:%M:%S\"\nmsgfmt = \"%(asctime)s,%(msecs)03d %(levelname)-6s %(name)-10s : %(message)s\"\nlog_reg = None\ndef handler_filter(rec): # Callables work with 3.2 and later\n global log_reg\n if 'please' in rec.msg.lower():\n rec.msg = rec.msg + \" (I am nice)\" # Changing the record\n rec.args = (rec.args[0].upper(), rec.args[1] + 10)\n rec.__dict__['custom_name'] = \"Important context information\"\n log_reg = rec\n return True\n return False\nlog = logging.getLogger() \nlh = logging.StreamHandler()\nlf = logging.Formatter(fmt=msgfmt, datefmt=datefmt)\nlh.setFormatter(lf)\nlog.addHandler(lh)\nlh.addFilter(handler_filter)\nlog.warn(\"I am a bold Logger\",\"good\")\nlog.warn(\"Hi, I am %s. I am %i seconds old. Please log me\",\"Loggy\", 1)\n",
"2015-07-19 20:19:55,905 WARNING root : Hi, I am LOGGY. I am 11 seconds old. Please log me (I am nice)\n"
]
],
[
[
"# Things you might want to know ( if we still have some time)",
"_____no_output_____"
],
[
"## A short look at our LogRecord",
"_____no_output_____"
]
],
[
[
"print(log_reg)\nlog_reg.__dict__",
"<LogRecord: root, 30, <ipython-input-20-d1d101ab918f>, 25, \"Hi, I am %s. I am %i seconds old. Please log me (I am nice)\">\n"
]
],
[
[
"## Logging Performance - Slow, but Fast Enough\n<table class=\"bst\"><tr><th>Scenario (10000 Call, 3 Logs per call)</th><th>Runtime</th></tr><tr><td>Full Logging with buffered writes</td><td>3.096s</td></tr><tr><td>Disable Caller information</td><td>2.868s</td></tr><tr><td>Check Logging Lvl before Call, Logging disabled</td><td>0.186s</td></tr><tr><td>Logging module level disabled</td><td>0.181s</td></tr><tr><td>No Logging calls at all</td><td>0.157s</td></tr></table>",
"_____no_output_____"
],
[
"## Getting the current Logging Tree",
"_____no_output_____"
]
],
[
[
"import json, logging.config\nconfig = json.load(open(\"conf_dict_with_file.json\"))\nlogging.config.dictConfig(config)\nimport requests\nimport logging_tree\nlogging_tree.printout()",
"<--\"\"\n Level DEBUG\n Handler Stream <IPython.kernel.zmq.iostream.OutStream object at 0x105d043c8>\n Formatter fmt='%(asctime)s,%(msecs)03d %(levelname)-10s %(name)-15s : %(message)s' datefmt='%Y-%m-%d %H:%M:%S'\n Handler File '/Users/imhiro/AllFiles/0021_travel_events_conferences_workshops/2015-07-19_europython/github/logfile.txt'\n Formatter fmt='%(asctime)s,%(msecs)03d %(levelname)-10s %(name)-15s : %(message)s' datefmt='%Y-%m-%d %H:%M:%S'\n |\n o \"IPKernelApp\"\n | Level WARNING\n | Propagate OFF\n | Disabled\n | Handler Stream <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>\n | Formatter <IPython.config.application.LevelFormatter object at 0x104b362e8>\n |\n o<--[concurrent]\n | |\n | o<--\"concurrent.futures\"\n | Level NOTSET so inherits level DEBUG\n | Disabled\n |\n o<--\"requests\"\n | Level NOTSET so inherits level DEBUG\n | Handler <logging.NullHandler object at 0x106f75a20>\n | |\n | o<--[requests.packages]\n | |\n | o<--\"requests.packages.urllib3\"\n | Level NOTSET so inherits level DEBUG\n | Handler <logging.NullHandler object at 0x106f759b0>\n | |\n | o<--\"requests.packages.urllib3.connectionpool\"\n | | Level NOTSET so inherits level DEBUG\n | |\n | o<--\"requests.packages.urllib3.poolmanager\"\n | | Level NOTSET so inherits level DEBUG\n | |\n | o<--[requests.packages.urllib3.util]\n | |\n | o<--\"requests.packages.urllib3.util.retry\"\n | Level NOTSET so inherits level DEBUG\n |\n o<--\"tornado\"\n Level NOTSET so inherits level DEBUG\n Disabled\n |\n o<--\"tornado.access\"\n | Level NOTSET so inherits level DEBUG\n | Disabled\n |\n o<--\"tornado.application\"\n | Level NOTSET so inherits level DEBUG\n | Disabled\n |\n o<--\"tornado.general\"\n Level NOTSET so inherits level DEBUG\n Disabled\n"
]
],
[
[
"## Reconfiguration\n- It is possible to change the logging configuration at runtime\n- It is even part of the standard library\n- Still, some caution is in order",
"_____no_output_____"
],
[
"## Reloading the configuration _can_ disable the existing loggers",
"_____no_output_____"
]
],
[
[
"import log1,json,logging,logging.config;logging = log1.get_clean_logging()\n\n#Load Config, define a child logger (could also be a module)\nlogging.config.dictConfig(json.load(open(\"conf_dict_with_file.json\")))\nchild_log = logging.getLogger(\"somewhere\") \n\n#Reload Config\nlogging.config.dictConfig(json.load(open(\"conf_dict_with_file.json\")))\n\n\n#Our childlogger was disables\nchild_log.info(\"Now this is %s logging!\",\"good\")\n",
"_____no_output_____"
]
],
[
[
"## Reloading can happen in place",
"_____no_output_____"
]
],
[
[
"import log1, json, logging, logging.config;logging = log1.get_clean_logging()\n\nconfig = json.load(open(\"conf_dict_with_file.json\"))\n#Load Config, define a child logger (could also be a module)\n\nlogging.config.dictConfig(config)\nchild_log = logging.getLogger(\"somewhere\") \nconfig['disable_existing_loggers'] = False\n#Reload Config\nlogging.config.dictConfig(config)\n\n\n#Our childlogger was disables\nchild_log.info(\"Now this is %s logging!\",\"good\")\n\n",
"2015-07-19 20:20:42,290 INFO somewhere : Now this is good logging!\n"
]
],
[
[
"# Successful Logging to all of You",
"_____no_output_____"
]
],
[
[
"from presentation_helper import customize_settings\ncustomize_settings()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e78ab70907f50a762f0a92398383e1bd4c9f5b8f | 109,914 | ipynb | Jupyter Notebook | ThinkBayes_Chapter_9.ipynb | ricardoV94/ThinkBayesPymc3 | d2053afedcfaf6df4e3c2db4a345de1581c7b78e | [
"MIT"
] | 2 | 2021-04-27T07:28:12.000Z | 2022-01-03T10:47:46.000Z | ThinkBayes_Chapter_9.ipynb | ricardoV94/ThinkBayesPymc3 | d2053afedcfaf6df4e3c2db4a345de1581c7b78e | [
"MIT"
] | null | null | null | ThinkBayes_Chapter_9.ipynb | ricardoV94/ThinkBayesPymc3 | d2053afedcfaf6df4e3c2db4a345de1581c7b78e | [
"MIT"
] | 1 | 2021-04-27T07:22:25.000Z | 2021-04-27T07:22:25.000Z | 236.374194 | 29,902 | 0.89469 | [
[
[
"<a href=\"https://colab.research.google.com/github/ricardoV94/ThinkBayesPymc3/blob/master/ThinkBayes_Chapter_9.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"%%capture\npip install arviz",
"_____no_output_____"
],
[
"import numpy as np\nimport pymc3 as pm\nimport theano.tensor as tt\nimport arviz as az\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"## 9.1 Paintball",
"_____no_output_____"
]
],
[
[
"def StrafingSpeed(alpha, beta, x):\n theta = tt.arctan2(x-alpha, beta)\n speed = beta / tt.cos(theta)**2\n return speed",
"_____no_output_____"
],
[
"with pm.Model() as m_9_3:\n\n obs_beta = pm.Data('obs_beta', [10])\n\n alpha = pm.Uniform('alpha', lower=0, upper=31, observed=10)\n beta = pm.Uniform('beta', lower=1, upper=51, observed=obs_beta)\n location = pm.Uniform('location', lower=0, upper=31)\n\n speed = pm.Deterministic('speed', StrafingSpeed(alpha, beta, location))\n like = pm.Potential('like', -np.log(speed)) # Equivalent to 1/speed",
"_____no_output_____"
],
[
"traces_m_9_3 = []\nfor beta in (10, 20, 40):\n with m_9_3:\n pm.set_data({'obs_beta': [beta]})\n traces_m_9_3.append(pm.sample(5000, progressbar=False))",
"Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nSequential sampling (2 chains in 1 job)\nNUTS: [location]\nAuto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nSequential sampling (2 chains in 1 job)\nNUTS: [location]\nAuto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nSequential sampling (2 chains in 1 job)\nNUTS: [location]\n"
],
[
"sns.kdeplot(traces_m_9_3[0]['location'], label='beta = 10', color='darkblue')\nsns.kdeplot(traces_m_9_3[1]['location'], label='beta = 20')\nsns.kdeplot(traces_m_9_3[2]['location'], label='beta = 40', color='lightblue')\nplt.xlim([0,30])\nplt.xlabel('Distace')\nplt.ylabel('Prob');",
"_____no_output_____"
]
],
[
[
"### 9.5 Joint distributions\nResults are very different from those of the book. Posterior is much more narrow.",
"_____no_output_____"
]
],
[
[
"with pm.Model() as m_9_5:\n\n alpha = pm.Uniform('alpha', lower=0, upper=31)\n beta = pm.Uniform('beta', lower=1, upper=51)\n location = pm.Uniform('location', lower=0, upper=31, observed=[15, 16, 18, 21])\n\n speed = pm.Deterministic('speed', StrafingSpeed(alpha, beta, location))\n like = pm.Potential('like', -tt.log(speed))\n\n trace_m_9_5 = pm.sample(5000)",
"Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nSequential sampling (2 chains in 1 job)\nNUTS: [beta, alpha]\n100%|██████████| 5500/5500 [00:04<00:00, 1282.30it/s]\n100%|██████████| 5500/5500 [00:03<00:00, 1414.00it/s]\nThe number of effective samples is smaller than 25% for some parameters.\n"
],
[
"bins = np.linspace(0, 51, 50)\nplt.hist(trace_m_9_5['alpha'], cumulative=True, bins=bins, density=True, histtype='step', lw=2, label='alpha')\nplt.hist(trace_m_9_5['beta'], cumulative=True, bins=bins, density=True, histtype='step', lw=2, color='lightblue', label='beta')\nplt.ylabel('Prob')\nplt.xlabel('Distance')\nplt.legend(loc=4);",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 2, figsize=(12,4))\npm.plot_posterior(trace_m_9_5['alpha'], credible_interval=.5, ax=ax[0])\npm.plot_posterior(trace_m_9_5['beta'], credible_interval=.5, ax=ax[1])",
"_____no_output_____"
],
[
"sns.kdeplot(trace_m_9_5['alpha'], trace_m_9_5['beta'], shade=True, n_levels=3, shade_lowest=False);\nplt.ylabel('beta')\nplt.xlabel('alpha');",
"_____no_output_____"
]
],
[
[
"### 9.6 Conditional Distributions",
"_____no_output_____"
]
],
[
[
"with pm.Model() as m_9_6:\n\n obs_beta = pm.Data('obs_beta', 10)\n\n alpha = pm.Uniform('alpha', lower=0, upper=31)\n beta = pm.Uniform('beta', lower=1, upper=51, observed=obs_beta)\n location = pm.Uniform('location', lower=0, upper=31, observed=[15, 16, 18, 21])\n\n speed = pm.Deterministic('speed', StrafingSpeed(alpha, beta, location))\n like = pm.Potential('like', -np.log(speed))",
"_____no_output_____"
],
[
"traces_m_9_6 = []\nfor beta in (10, 20, 40):\n with m_9_6:\n pm.set_data({'obs_beta': beta})\n traces_m_9_6.append(pm.sample(5000, progressbar=False))",
"Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nSequential sampling (2 chains in 1 job)\nNUTS: [alpha]\nAuto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nSequential sampling (2 chains in 1 job)\nNUTS: [alpha]\nAuto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nSequential sampling (2 chains in 1 job)\nNUTS: [alpha]\n"
],
[
"sns.kdeplot(traces_m_9_6[0]['alpha'], label='beta = 10', color='darkblue')\nsns.kdeplot(traces_m_9_6[1]['alpha'], label='beta = 20')\nsns.kdeplot(traces_m_9_6[2]['alpha'], label='beta = 40', color='lightblue')\nplt.xlim([0,30])\nplt.xlabel('Distace')\nplt.ylabel('Prob');",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e78accaada9c36b6acba673a0c1bf89eb12b3741 | 764,963 | ipynb | Jupyter Notebook | experiments/ede_exp/notebooks/train_expv1.ipynb | IeAT-ASPIDE/Event-Detection-Engine | 08f36d5fa56cae0e9ef86f61edf193aa4e780177 | [
"Apache-2.0"
] | null | null | null | experiments/ede_exp/notebooks/train_expv1.ipynb | IeAT-ASPIDE/Event-Detection-Engine | 08f36d5fa56cae0e9ef86f61edf193aa4e780177 | [
"Apache-2.0"
] | 20 | 2020-12-09T15:07:25.000Z | 2022-01-30T20:40:31.000Z | experiments/ede_exp/notebooks/train_expv1.ipynb | IeAT-ASPIDE/Event-Detection-Engine | 08f36d5fa56cae0e9ef86f61edf193aa4e780177 | [
"Apache-2.0"
] | null | null | null | 716.257491 | 395,594 | 0.746329 | [
[
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix\n# from sklearn.externals import joblib\nimport joblib\nimport os\nimport seaborn as sns\n%matplotlib inline\n\n\npath_parent = os.path.dirname(os.getcwd())\ndata_dir = os.path.join(path_parent,'data')\nmodel_dir = os.path.join(path_parent,'models')\nprocessed_dir = os.path.join(data_dir,'processed')\ndf_anomaly = pd.read_csv(os.path.join(processed_dir,\"anomaly_anotated.csv\"))\ndf_audsome = pd.read_csv(os.path.join(processed_dir,\"anomaly_anotated_audsome.csv\"))",
"_____no_output_____"
],
[
"data = df_anomaly\nprint(\"Remove unwanted columns\")\nprint(data.shape)\ndata.drop(['t1','t2','t3','t4'], axis=1, inplace=True)\nprint(data.shape)",
"Remove unwanted columns\n(4800, 67)\n(4800, 63)\n"
],
[
"#Creating the dependent variable class\nfactor = pd.factorize(data['target'])\ndata.target = factor[0]\ndefinitions = factor[1]\nprint(data.target.head())\nprint(definitions)",
"0 0\n1 0\n2 0\n3 0\n4 0\nName: target, dtype: int64\nIndex(['copy', 'mem', '0', 'dummy', 'cpu'], dtype='object')\n"
],
[
"#Spliting into X and y\nX = data.drop('target', axis=1)\ny = data['target']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 21)",
"_____no_output_____"
],
[
"# Plot class distribution\nsns.countplot(y_train)",
"_____no_output_____"
],
[
"# Feature Scaling\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n",
"_____no_output_____"
],
[
"#RandomForest\nclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 42)\nclassifier.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predicting the Test set results\ny_pred = classifier.predict(X_test)\n# Reverse factorize (converting y_pred from 0s,1s and 2s to Iris-setosa, Iris-versicolor and Iris-virginica\n# reversefactor = dict(zip(range(3),definitions))\n# y_test_f = np.vectorize(reversefactor.get)(y_test)\n# y_pred_f = np.vectorize(reversefactor.get)(y_pred)\n# Making the Confusion Matrix\n# print(pd.crosstab(y_test_f, y_pred_f, rownames=['Actual Anomalies'], colnames=['Predicted Anomalies']))",
"_____no_output_____"
],
[
"# Scoring\nfrom sklearn.metrics import precision_score, recall_score, jaccard_similarity_score, roc_auc_score, accuracy_score, classification_report, balanced_accuracy_score\n# print(y_test)\n# print(y_pred)\n\nprint(\"Accuracy score is: {}\".format(accuracy_score(y_test, y_pred)))\nprint(\"Ballanced accuracy score is: {}\".format(balanced_accuracy_score(y_test, y_pred)))\nprint(\"Jaccard score: {}\".format(jaccard_similarity_score(y_test, y_pred)))\nprint(\"Full classification report\")\nprint(classification_report(y_test, y_pred, target_names=definitions))",
"Accuracy score is: 0.9833333333333333\nBallanced accuracy score is: 0.979723031206516\nJaccard score: 0.9833333333333333\nFull classification report\n precision recall f1-score support\n\n copy 0.99 0.98 0.98 135\n mem 0.99 0.99 0.99 349\n 0 0.98 0.98 0.98 465\n dummy 0.97 0.97 0.97 137\n cpu 0.98 0.97 0.98 114\n\n accuracy 0.98 1200\n macro avg 0.98 0.98 0.98 1200\nweighted avg 0.98 0.98 0.98 1200\n\n"
],
[
"print(\"Confusion matrix\")\n\ncf_matrix = confusion_matrix(y_test, y_pred)\nsns.heatmap(cf_matrix, annot=True, yticklabels=list(definitions), xticklabels=list(definitions))",
"Confusion matrix\n"
],
[
"# Extract Feature importance\nimport matplotlib.pyplot as plt\n\nfeat_importances = pd.Series(classifier.feature_importances_, index=X.columns)\nsorted_feature = feat_importances.sort_values(ascending=True)\n# Plot the feature importances of the forest\nplt.figure()\nplt.title(\"Feature importances\")\nplt.barh(range(X.shape[1]), sorted_feature,\n color=\"r\", align=\"center\")\n# If you want to define your own labels,\n# change indices to a list of labels on the following line.\nplt.yticks(range(X.shape[1]), sorted_feature.index)\nplt.ylim([-1, X.shape[1]])\nplt.show()",
"_____no_output_____"
],
[
"# Example one vs all: https://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html\n# example: https://gabrielziegler3.medium.com/multiclass-multilabel-classification-with-xgboost-66195e4d9f2d\n#XGBOOST\nimport xgboost as xgb\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\n# If Python API is used dmatrix must be created manually\ndtrain = xgb.DMatrix(data=X_train, label=y_train)\ndtest = xgb.DMatrix(data=X_test)\n\nparams = {\n 'max_depth': 6,\n 'objective': 'multi:softmax', # error evaluation for multiclass training\n 'num_class': len(definitions),\n}\n# Python API\n# bst = xgb.train(params, dtrain)\n\n# SKlearn API\nbst = xgb.XGBClassifier(**params)\nbst.fit(X_train, y_train)",
"_____no_output_____"
],
[
"pred = bst.predict(X_test)",
"_____no_output_____"
],
[
"print(\"Accuracy score is: {}\".format(accuracy_score(y_test, pred)))\nprint(\"Ballanced accuracy score is: {}\".format(balanced_accuracy_score(y_test, pred)))\nprint(\"Jaccard score: {}\".format(jaccard_similarity_score(y_test, pred)))\nprint(\"Full classification report\")\nprint(classification_report(y_test, pred, target_names=definitions))",
"Accuracy score is: 0.9816666666666667\nBallanced accuracy score is: 0.9765304186938882\nJaccard score: 0.9816666666666667\nFull classification report\n precision recall f1-score support\n\n copy 0.99 0.99 0.99 135\n mem 1.00 0.99 0.99 349\n 0 0.97 0.98 0.98 465\n dummy 0.96 0.96 0.96 137\n cpu 0.99 0.96 0.98 114\n\n accuracy 0.98 1200\n macro avg 0.98 0.98 0.98 1200\nweighted avg 0.98 0.98 0.98 1200\n\n"
],
[
"print(\"Confusion matrix\")\n\ncf_matrix = confusion_matrix(pred, y_pred)\nsns.heatmap(cf_matrix, annot=True, yticklabels=list(definitions), xticklabels=list(definitions))\n",
"Confusion matrix\n"
],
[
"bst.feature_importances_\n\n\nxgb.plot_importance(bst)\nplt.title(\"xgboost.plot_importance(model)\")\nplt.show()\n# bst.feature_importances_",
"_____no_output_____"
],
[
"import shap\nshap.initjs()\nexplainer = shap.TreeExplainer(bst)\nshap_values = explainer.shap_values(X_train)\n# print(shap_values.shape)\n# shap.force_plot(explainer.expected_value[0], shap_values[0])",
"_____no_output_____"
],
[
"# shap.summary_plot(shap_values[0], X_train)",
"_____no_output_____"
],
[
"#https://www.kaggle.com/stuarthallows/using-xgboost-with-scikit-learn\n#Cross validation example\n# kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n#\n# scores = []\n#\n# for train_index, test_index in kfold.split(X):\n# X_train, X_test = X[train_index], X[test_index]\n# y_train, y_test = y[train_index], y[test_index]\n#\n# xgb_model = xgb.XGBRegressor(objective=\"reg:linear\")\n# xgb_model.fit(X_train, y_train)\n#\n# y_pred = xgb_model.predict(X_test)\n#\n# scores.append(mean_squared_error(y_test, y_pred))\n#\n# display_scores(np.sqrt(scores))",
"_____no_output_____"
],
[
"# Deep learnin: https://machinelearningmastery.com/multi-label-classification-with-deep-learning/\n# https://machinelearningmastery.com/how-to-develop-convolutional-neural-network-models-for-time-series-forecasting/\n# https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/\n# https://www.analyticsvidhya.com/blog/2020/10/multivariate-multi-step-time-series-forecasting-using-stacked-lstm-sequence-to-sequence-autoencoder-in-tensorflow-2-0-keras/\n# https://machinelearningmastery.com/multi-class-classification-tutorial-keras-deep-learning-library/\n# https://hub.packtpub.com/using-genetic-algorithms-for-optimizing-your-models-tutorial/\nfrom sklearn.model_selection import RepeatedKFold\nfrom sklearn.preprocessing import OneHotEncoder\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\n\n# get the model\ndef get_model(n_inputs, n_outputs):\n\tmodel = Sequential()\n\tmodel.add(Dense(20, input_dim=n_inputs, kernel_initializer='he_uniform', activation='relu'))\n\tmodel.add(Dense(n_outputs, activation='sigmoid'))\n\tmodel.compile(loss='binary_crossentropy', optimizer='adam')\n\treturn model",
"_____no_output_____"
],
[
"# evaluate a model using repeated k-fold cross-validation\ndef evaluate_model(X, y):\n\tresults = list()\n\tn_inputs, n_outputs = X.shape[1], y.shape[1]\n\t# define evaluation procedure\n\tcv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)\n\t# enumerate folds\n\tfor train_ix, test_ix in cv.split(X):\n\t\t# prepare data\n\t\tX_train, X_test = X[train_ix], X[test_ix]\n\t\ty_train, y_test = y[train_ix], y[test_ix]\n\t\t# define model\n\t\tmodel = get_model(n_inputs, n_outputs)\n\t\t# fit model\n\t\tmodel.fit(X_train, y_train, verbose=0, epochs=100)\n\t\t# make a prediction on the test set\n\t\tyhat = model.predict(X_test)\n\t\t# round probabilities to class labels\n\t\tyhat = yhat.round()\n\t\t# calculate accuracy\n\t\tacc = accuracy_score(y_test, yhat)\n\t\t# store result\n\t\tprint('>%.3f' % acc)\n\t\tresults.append(acc)\n\treturn results\n\n\ny_oh = pd.get_dummies(y_train, prefix='target')\ny_test_oh = pd.get_dummies(y_test, prefix='target')\n# enc.categories_\n#train\ndef train_dnn(X, y):\n print(y.shape)\n n_inputs, n_outputs = X.shape[1], y.shape[1]\n # define model\n model = get_model(n_inputs, n_outputs)\n # fit model\n model.fit(np.asarray(X), np.asarray(y), verbose=1, epochs=100)\n # make a prediction on the test set\n yhat = model.predict(np.asarray(X_test))\n # round probabilities to class labels\n yhat = yhat.round()\n # calculate accuracy\n acc = accuracy_score(np.asarray(y_test_oh), yhat)\n # store result\n print('>%.3f' % acc)\n print(classification_report(y_test_oh, yhat))\n\n return model, yhat\n\n\nmodel, yhat = train_dnn(X_train, y_oh)",
"(3600, 5)\nTrain on 3600 samples\nEpoch 1/100\n3600/3600 [==============================] - 1s 329us/sample - loss: 0.4025\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 2/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.2116\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 3/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.1519\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 4/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.1270\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 5/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.1143\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 6/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.1064\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 7/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.1005\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 8/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0960\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 9/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0923\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 10/100\n3600/3600 [==============================] - 0s 56us/sample - loss: 0.0893\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 11/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0863\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 12/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0839\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 13/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0814\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 14/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0792\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 15/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0772\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 16/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0756\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 17/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0741\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 18/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0727\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 19/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0713\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 20/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0706\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 21/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0698\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 22/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0684\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 23/100\n3600/3600 [==============================] - 0s 56us/sample - loss: 0.0678\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 24/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0675\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 25/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0664\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 26/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0659\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 27/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0654\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 28/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0646\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 29/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0641\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 30/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0639\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 31/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0632\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 32/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0627\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 33/100\n3600/3600 [==============================] - 0s 60us/sample - loss: 0.0627\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 34/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0619\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 35/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0617\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 36/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0613\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 37/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0610\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 38/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0612\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 39/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0603\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 40/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0604\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 41/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0600\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 42/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0595\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 43/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0588\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 44/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0591\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 45/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0589\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 46/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0588\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 47/100\n3600/3600 [==============================] - 0s 59us/sample - loss: 0.0582\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 48/100\n3600/3600 [==============================] - 0s 57us/sample - loss: 0.0586\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 49/100\n3600/3600 [==============================] - 0s 61us/sample - loss: 0.0578\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 50/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0582\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 51/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0573\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 52/100\n3600/3600 [==============================] - 0s 75us/sample - loss: 0.0580\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 53/100\n3600/3600 [==============================] - 0s 77us/sample - loss: 0.0572\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 54/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0567\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 55/100\n3600/3600 [==============================] - 0s 80us/sample - loss: 0.0570\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 56/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0570\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 57/100\n3600/3600 [==============================] - 0s 85us/sample - loss: 0.0567\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 58/100\n3600/3600 [==============================] - 0s 80us/sample - loss: 0.0563\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 59/100\n3600/3600 [==============================] - 0s 79us/sample - loss: 0.0562\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 60/100\n3600/3600 [==============================] - 0s 78us/sample - loss: 0.0563\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 61/100\n3600/3600 [==============================] - 0s 80us/sample - loss: 0.0555\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 62/100\n3600/3600 [==============================] - 0s 74us/sample - loss: 0.0563\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 63/100\n3600/3600 [==============================] - 0s 75us/sample - loss: 0.0559\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 64/100\n3600/3600 [==============================] - 0s 78us/sample - loss: 0.0554\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 65/100\n3600/3600 [==============================] - 0s 80us/sample - loss: 0.0553\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 66/100\n3600/3600 [==============================] - 0s 76us/sample - loss: 0.0554\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 67/100\n3600/3600 [==============================] - 0s 77us/sample - loss: 0.0553\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 68/100\n3600/3600 [==============================] - 0s 77us/sample - loss: 0.0551\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 69/100\n3600/3600 [==============================] - 0s 84us/sample - loss: 0.0546\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 70/100\n3600/3600 [==============================] - 0s 74us/sample - loss: 0.0547\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 71/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0546\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 72/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0543\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 73/100\n3600/3600 [==============================] - 0s 82us/sample - loss: 0.0544\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 74/100\n3600/3600 [==============================] - 0s 77us/sample - loss: 0.0539\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 75/100\n3600/3600 [==============================] - 0s 77us/sample - loss: 0.0543\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 76/100\n3600/3600 [==============================] - 0s 71us/sample - loss: 0.0544\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 77/100\n3600/3600 [==============================] - 0s 64us/sample - loss: 0.0539\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 78/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0543\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 79/100\n3600/3600 [==============================] - 0s 58us/sample - loss: 0.0540\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 80/100\n3600/3600 [==============================] - 0s 74us/sample - loss: 0.0533\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 81/100\n3600/3600 [==============================] - 0s 77us/sample - loss: 0.0536\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 82/100\n3600/3600 [==============================] - 0s 82us/sample - loss: 0.0539\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 83/100\n3600/3600 [==============================] - 0s 76us/sample - loss: 0.0539\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 84/100\n3600/3600 [==============================] - 0s 74us/sample - loss: 0.0531\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 85/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0536\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 86/100\n3600/3600 [==============================] - 0s 76us/sample - loss: 0.0532\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 87/100\n3600/3600 [==============================] - 0s 80us/sample - loss: 0.0533\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 88/100\n3600/3600 [==============================] - 0s 78us/sample - loss: 0.0528\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 89/100\n3600/3600 [==============================] - 0s 76us/sample - loss: 0.0527\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 90/100\n3600/3600 [==============================] - 0s 79us/sample - loss: 0.0527\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 91/100\n3600/3600 [==============================] - 0s 79us/sample - loss: 0.0522\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 92/100\n3600/3600 [==============================] - 0s 76us/sample - loss: 0.0526\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 93/100\n3600/3600 [==============================] - 0s 79us/sample - loss: 0.0524\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 94/100\n3600/3600 [==============================] - 0s 79us/sample - loss: 0.0522\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 95/100\n3600/3600 [==============================] - 0s 81us/sample - loss: 0.0519\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 96/100\n3600/3600 [==============================] - 0s 78us/sample - loss: 0.0519\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 97/100\n3600/3600 [==============================] - 0s 79us/sample - loss: 0.0520\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 98/100\n3600/3600 [==============================] - 0s 83us/sample - loss: 0.0517\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 99/100\n3600/3600 [==============================] - 0s 77us/sample - loss: 0.0522\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 100/100\n3600/3600 [==============================] - 0s 80us/sample - loss: 0.0521\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n>0.945\n precision recall f1-score support\n\n 0 0.99 0.98 0.98 135\n 1 0.99 0.99 0.99 349\n 2 0.95 0.93 0.94 465\n 3 0.81 0.91 0.85 137\n 4 0.97 0.96 0.97 114\n\n micro avg 0.95 0.95 0.95 1200\n macro avg 0.94 0.95 0.95 1200\nweighted avg 0.95 0.95 0.95 1200\n samples avg 0.95 0.95 0.95 1200\n\n"
],
[
"# Reverse one hot encoding\ndef reverse_oh(y_oh):\n decode = []\n for r in y_oh:\n # print(r)\n result = np.where(r == 1.)[0]\n # print(result)\n #check if network asigned more than one or non labels\n if len(result) > 1 or len(result) == 0:\n if len(result) > 1:\n result = np.array([result[0]]) # select first class\n elif len(result) == 0:\n result = np.array([0])\n\n decode.append(result[0])\n return decode\n\ndecode = reverse_oh(yhat)\n# print(decode)\n# print(y_test)\n# print(y_test.describe)\n\n\nprint(\"Confusion matrix\")\nprint(\"Accuracy score is: {}\".format(accuracy_score(y_test, decode)))\nprint(\"Ballanced accuracy score is: {}\".format(balanced_accuracy_score(y_test, decode)))\nprint(\"Jaccard score: {}\".format(jaccard_similarity_score(y_test, decode)))\nprint(\"Full classification report\")\ncf_matrix = confusion_matrix(y_test, decode)\nsns.heatmap(cf_matrix, annot=True, yticklabels=list(definitions), xticklabels=list(definitions))\n# evaluate model\n# results = evaluate_model(X, y)\n# summarize performance\n# print('Accuracy: %.3f (%.3f)' % (mean(results), std(results)))",
"Confusion matrix\nAccuracy score is: 0.9483333333333334\nBallanced accuracy score is: 0.9468262013903205\nJaccard score: 0.9483333333333334\nFull classification report\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e78ade2d70a51d4a1eee2b525c48abf6939e2a18 | 3,068 | ipynb | Jupyter Notebook | Module 4/multilinear_regression.ipynb | axel-sirota/interpreting-data-with-advanced-models | 699dd8281c78d88b31b59f43bdf2f29a57f3f94c | [
"MIT"
] | 1 | 2021-12-10T13:15:01.000Z | 2021-12-10T13:15:01.000Z | Module 4/multilinear_regression.ipynb | axel-sirota/interpreting-data-with-advanced-models | 699dd8281c78d88b31b59f43bdf2f29a57f3f94c | [
"MIT"
] | null | null | null | Module 4/multilinear_regression.ipynb | axel-sirota/interpreting-data-with-advanced-models | 699dd8281c78d88b31b59f43bdf2f29a57f3f94c | [
"MIT"
] | 2 | 2021-04-13T06:07:56.000Z | 2021-12-10T13:15:09.000Z | 27.150442 | 161 | 0.574316 | [
[
[
"\n# Multiple Linear Regression\n\n",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.model_selection import train_test_split\n\ndiabetes = datasets.load_diabetes() #load dataset\ndiabetes_X = diabetes.data\nX_train, X_test, y_train, y_test = train_test_split(diabetes_X, diabetes.target, test_size=0.20, random_state=42, shuffle=True) #split 20% into test set\ny_test = y_test.reshape(-1,1)\ny_train = y_train.reshape(-1, 1)",
"_____no_output_____"
],
[
"print('Size of the training set is {}'.format(X_train.shape))\nprint('Size of the Label training set is {}'.format(y_train.shape))\nprint('Size of the Label teest set is {}'.format(y_test.shape))\nprint('Size of the test set is {}'.format(X_test.shape))",
"Size of the training set is (353, 10)\nSize of the Label training set is (353, 1)\nSize of the Label teest set is (89, 1)\nSize of the test set is (89, 10)\n"
],
[
"# Create linear regression object\nregr = linear_model.LinearRegression()\n\n# Train the model using the training sets\nregr.fit(X_train, y_train)\n\n# Make predictions using the testing set\ny_pred = regr.predict(X_test)\n\n# The coefficients\nprint('Coefficients: \\n', regr.coef_)\n# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(y_test, y_pred))\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % r2_score(y_test, y_pred))",
"Coefficients: \n [[ 37.90031426 -241.96624835 542.42575342 347.70830529 -931.46126093\n 518.04405547 163.40353476 275.31003837 736.18909839 48.67112488]]\nMean squared error: 2900.17\nVariance score: 0.45\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e78ae769e39e6285853be49965eaf7276c345054 | 1,106 | ipynb | Jupyter Notebook | lectures/lecture_slides/5_heterogeneity_and_determinants.ipynb | luward/Project-Module-in-Management-and-Applied-Economics | e7040a414a0e69e8a409f03c54787174309256ff | [
"MIT"
] | null | null | null | lectures/lecture_slides/5_heterogeneity_and_determinants.ipynb | luward/Project-Module-in-Management-and-Applied-Economics | e7040a414a0e69e8a409f03c54787174309256ff | [
"MIT"
] | null | null | null | lectures/lecture_slides/5_heterogeneity_and_determinants.ipynb | luward/Project-Module-in-Management-and-Applied-Economics | e7040a414a0e69e8a409f03c54787174309256ff | [
"MIT"
] | null | null | null | 27.65 | 472 | 0.596745 | [
[
[
"# Heterogeneity and Determinants",
"_____no_output_____"
],
[
"<iframe src=\"https://www.slideshare.net/slideshow/embed_code/key/6js7YMQc5JnBl6\" width=\"595\" height=\"485\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" style=\"border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;\" allowfullscreen> </iframe> <div style=\"margin-bottom:5px\"> <strong> <a href=\"https://www.slideshare.net/secret/6js7YMQc5JnBl6\" title=\"01 Introduction\" target=\"_blank\"></a> </strong></div>",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown"
]
] |
e78ae9a5c1524b1f50f9ffb03a8393203b6d9e22 | 48,825 | ipynb | Jupyter Notebook | notebooks/Untitled1.ipynb | dwr-psandhu/barrier_analysis | 310df6c9b704de11710b1e9ad2e10ab1fa406600 | [
"MIT"
] | null | null | null | notebooks/Untitled1.ipynb | dwr-psandhu/barrier_analysis | 310df6c9b704de11710b1e9ad2e10ab1fa406600 | [
"MIT"
] | null | null | null | notebooks/Untitled1.ipynb | dwr-psandhu/barrier_analysis | 310df6c9b704de11710b1e9ad2e10ab1fa406600 | [
"MIT"
] | null | null | null | 69.157224 | 8,923 | 0.571244 | [
[
[
"import param\nimport panel as pn\npn.extension()",
"_____no_output_____"
],
[
"\nclass S(param.Parameterized):\n abclist = param.Selector()#objects=[\"red\", \"yellow\", \"green\"])\n \n @param.depends('abclist',watch=True)\n def abclist_changed(self):\n print(' changed: ',self.abclist.value)",
"_____no_output_____"
],
[
"s=S()\ns.param.abclist.objects=['d','e','f']",
"_____no_output_____"
],
[
"pn.Param(s.param.abclist)",
"_____no_output_____"
],
[
"s2=S()",
"_____no_output_____"
],
[
"pn.Param(s2.param.abclist)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e78aec63cf952c1a358a1f1d41caa4b5c6e98433 | 11,741 | ipynb | Jupyter Notebook | Data_Cleaning.ipynb | duartele/exerc-jupyternotebook | 29236eadb600acd0737cd023d6337bc01739b3da | [
"MIT"
] | null | null | null | Data_Cleaning.ipynb | duartele/exerc-jupyternotebook | 29236eadb600acd0737cd023d6337bc01739b3da | [
"MIT"
] | null | null | null | Data_Cleaning.ipynb | duartele/exerc-jupyternotebook | 29236eadb600acd0737cd023d6337bc01739b3da | [
"MIT"
] | null | null | null | 27.561033 | 240 | 0.500043 | [
[
[
"<a href=\"https://colab.research.google.com/github/duartele/exerc-jupyternotebook/blob/main/Data_Cleaning.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"## Handling missing values",
"_____no_output_____"
]
],
[
[
"# get the number of missing data points per column\nmissing_values_count = nfl_data.isnull().sum()\n\n# how many total missing values do we have?\ntotal_cells = np.product(nfl_data.shape)\ntotal_missing = missing_values_count.sum()\n\n# percent of data that is missing\npercent_missing = (total_missing/total_cells) * 100\nprint(percent_missing)",
"_____no_output_____"
],
[
"# replace all NA's the value that comes directly after it in the same column, \n# then replace all the remaining na's with 0\nsubset_nfl_data.fillna(method='bfill', axis=0).fillna(0)",
"_____no_output_____"
]
],
[
[
"## Scaling and normalization",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# for Box-Cox Transformation\nfrom scipy import stats\n# for min_max scaling\nfrom mlxtend.preprocessing import minmax_scaling\n\n# set seed for reproducibility\nnp.random.seed(0)",
"_____no_output_____"
]
],
[
[
" In scaling, you're changing the range of your data",
"_____no_output_____"
]
],
[
[
"# generate 1000 data points randomly drawn from an exponential distribution\noriginal_data = np.random.exponential(size=1000)\n\n# mix-max scale the data between 0 and 1\nscaled_data = minmax_scaling(original_data, columns=[0])\n\n# plot both together to compare\nfig, ax = plt.subplots(1,2)\nsns.distplot(original_data, ax=ax[0])\nax[0].set_title(\"Original Data\")\nsns.distplot(scaled_data, ax=ax[1])\nax[1].set_title(\"Scaled data\")",
"_____no_output_____"
]
],
[
[
"In normalization, you're changing the shape of the distribution of your data.",
"_____no_output_____"
]
],
[
[
"# normalize the exponential data with boxcox\nnormalized_data = stats.boxcox(original_data)",
"_____no_output_____"
]
],
[
[
"# Parsing Dates - it will be \"object\" if you don't parse it.",
"_____no_output_____"
]
],
[
[
"import datetime",
"_____no_output_____"
]
],
[
[
"if a date is MM/DD/YY (02/25/17) the format is \"%m/%d/%y\"\n\"%Y\" (upper y) is used if the year has four digits (2017)\nThat is (02/25/2017) the format is \"%m/%d/%Y\"\nOther formats: DD/MM/YY (25/02/17 - \"%d/%m/%y\") ; DD-MM-YY (25-02-17 - \"%d-%m-%y\"). At the end, the date will be show as the defaut YYYY-MM-DD (datetime64)",
"_____no_output_____"
]
],
[
[
"# create a new column, date_parsed, with the parsed dates\nlandslides['date_parsed'] = pd.to_datetime(landslides['date'], format=\"%m/%d/%y\")",
"_____no_output_____"
]
],
[
[
"If your dates is with multiple formats, you can use \"infer_datetime_format\".",
"_____no_output_____"
]
],
[
[
"landslides['date_parsed'] = pd.to_datetime(landslides['Date'], infer_datetime_format=True)",
"_____no_output_____"
],
[
"day_of_month_landslides = landslides['date_parsed'].dt.day",
"_____no_output_____"
]
],
[
[
"To check if everything looks right",
"_____no_output_____"
]
],
[
[
"date_lengths = earthquakes.Date.str.len()\ndate_lengths.value_counts()\n\n#or showing trhough a histogram of the day (values must be in [0,31] )",
"_____no_output_____"
],
[
"#In that example, 3 dates have len of 24. So we run this code\nindices = np.where([date_lengths == 24])[1]\nprint('Indices with corrupted data:', indices)\nearthquakes.loc[indices]",
"_____no_output_____"
],
[
"#Fixing manually the incorrect dates\nearthquakes.loc[3378, \"Date\"] = \"02/23/1975\"",
"_____no_output_____"
]
],
[
[
"# Character Encodings",
"_____no_output_____"
]
],
[
[
"# helpful character encoding module\nimport chardet",
"_____no_output_____"
],
[
"# look at the first ten thousand bytes to guess the character encoding\nwith open(\"../input/kickstarter-projects/ks-projects-201801.csv\", 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n\n# check what the character encoding might be\nprint(result)",
"_____no_output_____"
],
[
"# read in the file with the encoding detected by chardet\nkickstarter_2016 = pd.read_csv(\"../input/kickstarter-projects/ks-projects-201612.csv\", encoding='Windows-1252')\n\n# look at the first few lines\nkickstarter_2016.head()",
"_____no_output_____"
]
],
[
[
"Exercises",
"_____no_output_____"
]
],
[
[
"#1 - class bytes We need to create a new_entry in bytes (UTF-8is defaut)\nsample_entry = b'\\xa7A\\xa6n'\nprint(sample_entry)\nprint('data type:', type(sample_entry))\n#solution - Try using .decode() to get the string, then .encode() to get the bytes representation, encoded in UTF-8.\nbefore = sample_entry.decode(\"big5-tw\")\nnew_entry = before.encode()\n",
"_____no_output_____"
]
],
[
[
"# Inconsistent Data",
"_____no_output_____"
]
],
[
[
"# helpful modules\nimport fuzzywuzzy\nfrom fuzzywuzzy import process\nimport chardet",
"_____no_output_____"
],
[
"# get the top 10 closest matches to \"south korea\"\n# The closer str has ratio of 100\nmatches = fuzzywuzzy.process.extract(\"south korea\", countries, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio)",
"_____no_output_____"
],
[
"# function to replace rows in the provided column of the provided dataframe\n# that match the provided string above the provided ratio with the provided string\ndef replace_matches_in_column(df, column, string_to_match, min_ratio = 47):\n # get a list of unique strings\n strings = df[column].unique()\n \n # get the top 10 closest matches to our input string\n matches = fuzzywuzzy.process.extract(string_to_match, strings, \n limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio)\n\n # only get matches with a ratio >= min_ratio\n close_matches = [matches[0] for matches in matches if matches[1] >= min_ratio]\n\n # get the rows of all the close matches in our dataframe\n rows_with_matches = df[column].isin(close_matches)\n\n # replace all rows with close matches with the input matches \n df.loc[rows_with_matches, column] = string_to_match",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e78aef08196cf8901f96d5d9df8b69dd1fe83c76 | 5,971 | ipynb | Jupyter Notebook | 03-advanced-expression.ipynb | JeremyLikness/IQueryableExpressionExamples | 81f7cd04ce625555f4c6c40742f1bfe3121f1595 | [
"MIT"
] | 2 | 2020-09-28T19:20:21.000Z | 2020-11-11T22:11:11.000Z | 03-advanced-expression.ipynb | JeremyLikness/IQueryableExpressionExamples | 81f7cd04ce625555f4c6c40742f1bfe3121f1595 | [
"MIT"
] | null | null | null | 03-advanced-expression.ipynb | JeremyLikness/IQueryableExpressionExamples | 81f7cd04ce625555f4c6c40742f1bfe3121f1595 | [
"MIT"
] | 1 | 2020-11-11T22:11:16.000Z | 2020-11-11T22:11:16.000Z | 42.65 | 1,025 | 0.644616 | [
[
[
"using System.Linq.Expressions;\n\nvar x = Expression.Parameter(typeof(int), \"x\");\nvar y = Expression.Parameter(typeof(int), \"y\");\n\nvar add = Expression.Add(x, y);\nvar subtract = Expression.Subtract(x, y);\n\nvar choose = Expression.IfThenElse(\n Expression.GreaterThan(x, y),\n subtract,\n add);\n\nvar lambda = Expression.Lambda<Func<int,int,int>>(\n choose,\n new[] { x, y });\n\ndisplay(lambda.ToString());",
"_____no_output_____"
],
[
"using System.Linq.Expressions;\n\nvar x = Expression.Parameter(typeof(int), \"x\");\nvar y = Expression.Parameter(typeof(int), \"y\");\n\nvar add = Expression.Add(x, y);\nvar subtract = Expression.Subtract(x, y);\nvar test = Expression.GreaterThan(x, y);\n\nvar returnTarget = Expression.Label(typeof(int));\n\nvar whenTrue = Expression.Return(\n returnTarget,\n subtract);\n\nvar whenFalse = Expression.Return(\n returnTarget,\n add);\n\nvar expr = Expression.Block(\n Expression.IfThenElse(test, whenTrue, whenFalse),\n Expression.Label(returnTarget, Expression.Constant(0)));\n\nvar lambda = Expression.Lambda<Func<int, int, int>>(\n expr,\n new[] { x, y });\n \ndisplay(lambda.ToString());\nvar fn = lambda.Compile();\ndisplay(fn.ToString());\ndisplay(fn(40,2));\ndisplay(fn(2,40));",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
e78af073e35e890307994b9acd55459e55ec5a37 | 84,425 | ipynb | Jupyter Notebook | data/Scraping Fantasy Football Data - FINAL-Week3.ipynb | zgscherrer/Project-Fantasy-Football | 8c3d4249edc103f8606a1df25ebce5fd866da6c5 | [
"MIT"
] | null | null | null | data/Scraping Fantasy Football Data - FINAL-Week3.ipynb | zgscherrer/Project-Fantasy-Football | 8c3d4249edc103f8606a1df25ebce5fd866da6c5 | [
"MIT"
] | null | null | null | data/Scraping Fantasy Football Data - FINAL-Week3.ipynb | zgscherrer/Project-Fantasy-Football | 8c3d4249edc103f8606a1df25ebce5fd866da6c5 | [
"MIT"
] | 1 | 2018-09-30T08:37:32.000Z | 2018-09-30T08:37:32.000Z | 41.711957 | 305 | 0.498241 | [
[
[
"## Scraping Fantasy Football Data (Week 3 Projections/Week 2 Actuals)\nNeed to scrape the following data:\n- Weekly Player PPR Projections: ESPN, CBS, Fantasy Sharks, Scout Fantasy Sporsts, (and tried Fantasy Football Today but doesn't have defense projections currently, so exclude)\n- Previous Week Player Actual PPR Results\n- Weekly Fanduel Player Salary (can manually download csv from a Thurs-Sun contest and then import)",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport requests\n# import json\n# from bs4 import BeautifulSoup\n\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n# from selenium.common.exceptions import NoSuchElementException",
"_____no_output_____"
],
[
"#function to initiliaze selenium web scraper\ndef instantiate_selenium_driver():\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_argument('--window-size=1420,1080')\n #chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n driver = webdriver.Chrome('..\\plugins\\chromedriver.exe', \n chrome_options=chrome_options)\n return driver",
"_____no_output_____"
],
[
"#function to save dataframes to pickle archive\n#file name: don't include csv in file name, function will also add a timestamp to the archive\n#directory name don't include final backslash\ndef save_to_pickle(df, directory_name, file_name):\n lt = time.localtime()\n full_file_name = f\"{file_name}_{lt.tm_year}-{lt.tm_mon}-{lt.tm_mday}-{lt.tm_hour}-{lt.tm_min}.pkl\"\n path = f\"{directory_name}/{full_file_name}\"\n df.to_pickle(path)\n print(f\"Pickle saved to: {path}\")",
"_____no_output_____"
],
[
"#remove name suffixes of II III IV or Jr. or Sr. or random * from names to easier match other databases\n#also remove periods from first name T.J. make TJ (just remove periods from whole name in function)\ndef remove_suffixes_periods(name):\n #remove periods and any asterisks\n name = name.replace(\".\", \"\")\n name = name.replace(\"*\", \"\")\n \n #remove any suffixes by splitting the name on spaces and then rebuilding the name with only the first two of the list (being first/last name)\n name_split = name.split(\" \")\n name_final = \" \".join(name_split[0:2]) #rebuild\n \n# #old suffix removal process (created some errors for someone with Last Name starting with V)\n# for suffix in [\" III\", \" II\", \" IV\", \" V\", \" Jr.\", \" Sr.\"]:\n# name = name.replace(suffix, \"\")\n\n return name_final",
"_____no_output_____"
],
[
"#function to rename defense position labels so all matach\n#this will be used since a few players have same name as another player, but currently none that\n#are at same position need to create a function that gets all the defense labels the same, so that\n#when merge, can merge by both player name and position to prevent bad merges\n#input of pos will be the value of the column that getting mapped\ndef convert_defense_label(pos):\n defense_labels_scraped = ['DST', 'D', 'Def', 'DEF']\n if pos in defense_labels_scraped:\n #conver defense position labels to espn format\n pos = 'D/ST'\n return pos",
"_____no_output_____"
]
],
[
[
"### Get Weekly Player Actual Fantasy PPR Points\nGet from ESPN's Scoring Leaders table\n\nhttp://games.espn.com/ffl/leaders?&scoringPeriodId=1&seasonId=2018&slotCategoryId=0&leagueID=0\n- scoringPeriodId = week of the season\n- seasonId = year\n- slotCategoryId = position, where 'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, 'D/ST':16\n- leagueID = scoring type, PPR Standard is 0",
"_____no_output_____"
]
],
[
[
"##SCRAPE ESPN SCORING LEADERS TABLE FOR ACTUAL FANTASY PPR POINTS##\n\n#input needs to be year as four digit number and week as number \n#returns dataframe of scraped data\ndef scrape_actual_PPR_player_points_ESPN(week, year):\n #instantiate the driver\n driver = instantiate_selenium_driver()\n \n #initialize dataframe for all data\n player_actual_ppr = pd.DataFrame()\n \n #url that returns info has different code for each position\n position_ids = {'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, 'D/ST':16}\n\n #cycle through each position webpage to create comprehensive dataframe\n for pos, pos_id in position_ids.items():\n #note leagueID=0 is for PPR standard scoring\n url_start_pos = f\"http://games.espn.com/ffl/leaders?&scoringPeriodId={week}&seasonId={year}&slotCategoryId={pos_id}&leagueID=0\"\n driver.get(url_start_pos)\n \n #each page only gets 50 results, so cycle through next button until next button no longer exists\n while True:\n #read in the table from ESPN, by using the class, and use the 1st row index for column header\n player_actual_ppr_table_page = pd.read_html(driver.page_source,\n attrs={'class': 'playerTableTable'}, #return only the table of this class, which has the player data\n header=[1])[0] #returns table in a list, so get zeroth table\n\n #easier to just assign the player position rather than try to scrape it out\n player_actual_ppr_table_page['POS'] = pos\n\n #replace any placeholder string -- or --/-- with None type to not confuse calculations later\n player_actual_ppr_table_page.replace({'--': None, '--/--': None}, inplace=True)\n \n\n#if want to extract more detailed data from this, can do added reformatting, etc., but not doing that for our purposes\n# #rename D/ST columns so don't get misassigned to wrong columns\n# if pos == 'D/ST':\n# player_actual_ppr_table_page.rename(columns={'SCK':'D/ST_Sack', \n# 'FR':'D/ST_FR', 'INT':'D/ST_INT',\n# 'TD':'D/ST_TD', 'BLK':'D/ST_BLK', 'PA':'D/ST_PA'},\n# inplace=True)\n \n# #rename/recalculate Kicker columns so don't get misassigned to wrong columns\n# elif pos == 'K':\n# player_actual_ppr_table_page.rename(columns={'1-39':'KICK_FG_1-39', '40-49':'KICK_FG_40-49',\n# '50+':'KICK_FG_50+', 'TOT':'KICK_FG',\n# 'XP':'KICK_XP'},\n# inplace=True)\n \n# #if wanted to use all the kicker data could fix this code snipit - erroring out because can't split None types\n# #just want made FG's for each bucket and overall FGAtt and XPAtt\n# player_actual_ppr_table_page['KICK_FGAtt'] = player_actual_ppr_table_page['KICK_FG'].map(\n# lambda x: x.split(\"/\")[-1]).astype('float64')\n# player_actual_ppr_table_page['KICK_XPAtt'] = player_actual_ppr_table_page['KICK_XP'].map(\n# lambda x: x.split(\"/\")[-1]).astype('float64')\n# player_actual_ppr_table_page['KICK_FG_1-39'] = player_actual_ppr_table_page['KICK_FG_1-39'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# player_actual_ppr_table_page['KICK_FG_40-49'] = player_actual_ppr_table_page['KICK_FG_40-49'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# player_actual_ppr_table_page['KICK_FG_50+'] = player_actual_ppr_table_page['KICK_FG_50+'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# player_actual_ppr_table_page['KICK_FG'] = player_actual_ppr_table_page['KICK_FG'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# player_actual_ppr_table_page['KICK_XP'] = player_actual_ppr_table_page['KICK_XP'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# player_actual_ppr_table_page['KICK_FG%'] = player_actual_ppr_table_page['KICK_FG'] / espn_proj_table_page['KICK_FGAtt']\n \n \n #add page data to overall dataframe\n player_actual_ppr = pd.concat([player_actual_ppr, player_actual_ppr_table_page],\n ignore_index=True,\n sort=False)\n\n #click to next page to get next 40 results, but check that it exists\n try:\n next_button = driver.find_element_by_partial_link_text('NEXT')\n next_button.click()\n except EC.NoSuchElementException:\n break\n \n driver.quit()\n \n #drop any completely blank columns\n player_actual_ppr.dropna(axis='columns', how='all', inplace=True)\n \n #add columns that give week/season\n player_actual_ppr['WEEK'] = week\n player_actual_ppr['SEASON'] = year\n \n return player_actual_ppr",
"_____no_output_____"
],
[
"###FORMAT/EXTRACT ACTUAL PLAYER PPR DATA###\n#(you could make this more complex if want to extract some of the subdata)\n\ndef format_extract_PPR_player_points_ESPN(df_scraped_ppr_espn):\n #split out player, team, position based on ESPN's formatting\n def split_player_team_pos_espn(play_team_pos):\n #incoming string for players: 'Todd Gurley II, LAR RB' or 'Drew Brees, NO\\xa0QB'\n #incoming string for players with special designations: 'Aaron Rodgers, GB\\xa0QB Q'\n #incoming string for D/ST: 'Jaguars D/ST\\xa0D/ST'\n\n #operations if D/ST\n if \"D/ST\" in play_team_pos:\n player = play_team_pos.split(' D/ST\\xa0')[0]\n team = player.split()[0]\n\n #operations for regular players\n else:\n player = play_team_pos.split(',')[0]\n team_pos = play_team_pos.split(',')[1]\n team = team_pos.split()[0]\n\n return player, team\n\n \n df_scraped_ppr_espn[['PLAYER', 'TEAM']] = df_scraped_ppr_espn.apply(\n lambda x: split_player_team_pos_espn(x['PLAYER, TEAM POS']),\n axis='columns',\n result_type='expand')\n\n \n #need to remove name suffixes so can match players easier to other data - see function defined above\n df_scraped_ppr_espn['PLAYER'] = df_scraped_ppr_espn['PLAYER'].map(remove_suffixes_periods)\n\n #convert PTS to float type (sometimes zeros have been stored as strings)\n df_scraped_ppr_espn['PTS'] = df_scraped_ppr_espn['PTS'].astype('float64')\n \n #for this function only extract 'PLAYER', 'POS', 'TEAM', 'PTS'\n df_scraped_ppr_espn = df_scraped_ppr_espn[['PLAYER', 'POS', 'TEAM', 'PTS', 'WEEK']].sort_values('PTS', ascending=False)\n \n\n return df_scraped_ppr_espn",
"_____no_output_____"
],
[
"#CALL SCRAPE AND FORMATTING OF ACTUAL PPR WEEK 2- AND SAVE TO PICKLES FOR LATER USE\n\n#scrape data and save the messy full dataframe\ndf_wk2_player_actual_ppr_scrape = scrape_actual_PPR_player_points_ESPN(2, 2018)\nsave_to_pickle(df_wk2_player_actual_ppr_scrape, 'pickle_archive', 'Week2_Player_Actual_PPR_messy_scrape')\n\n#format data to extract just player pts/playr/pos/team/weel and save the data\ndf_wk2_player_actual_ppr = format_extract_PPR_player_points_ESPN(df_wk2_player_actual_ppr_scrape)\n#rename PTS column to something more descriptive \ndf_wk2_player_actual_ppr.rename(columns={'PTS':'FPTS_PPR_ACTUAL'}, inplace=True) \nsave_to_pickle(df_wk2_player_actual_ppr, 'pickle_archive', 'Week2_Player_Actual_PPR')\nprint(df_wk2_player_actual_ppr.shape)\ndf_wk2_player_actual_ppr.head()",
"Pickle saved to: pickle_archive/Week2_Player_Actual_PPR_messy_scrape_2018-9-18-17-59.pkl\nPickle saved to: pickle_archive/Week2_Player_Actual_PPR_2018-9-18-17-59.pkl\n(1009, 5)\n"
]
],
[
[
"### Get ESPN Player Fantasy Points Projections for Week \nGet from ESPN's Projections Table\n\nhttp://games.espn.com/ffl/tools/projections?&scoringPeriodId=1&seasonId=2018&slotCategoryId=0&leagueID=0\n- scoringPeriodId = week of the season\n- seasonId = year\n- slotCategoryId = position, where 'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, 'D/ST':16\n- leagueID = scoring type, PPR Standard is 0",
"_____no_output_____"
]
],
[
[
"##SCRAPE ESPN PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS##\n\n#input needs to be year as four digit number and week as number \n#returns dataframe of scraped data\ndef scrape_weekly_player_projections_ESPN(week, year):\n #instantiate the driver on the ESPN projections page\n driver = instantiate_selenium_driver()\n \n #initialize dataframe for all data\n proj_ppr_espn = pd.DataFrame()\n \n #url that returns info has different code for each position\n position_ids = {'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, 'D/ST':16}\n\n #cycle through each position webpage to create comprehensive dataframe\n for pos, pos_id in position_ids.items():\n #note leagueID=0 is for PPR standard scoring\n url_start_pos = f\"http://games.espn.com/ffl/tools/projections?&scoringPeriodId={week}&seasonId={year}&slotCategoryId={pos_id}&leagueID=0\" \n driver.get(url_start_pos)\n \n #each page only gets 50 results, so cycle through next button until next button no longer exists\n while True:\n #read in the table from ESPN, by using the class, and use the 1st row index for column header\n proj_ppr_espn_table_page = pd.read_html(driver.page_source,\n attrs={'class': 'playerTableTable'}, #return only the table of this class, which has the player data\n header=[1])[0] #returns table in a list, so get zeroth table\n\n #easier to just assign the player position rather than try to scrape it out\n proj_ppr_espn_table_page['POS'] = pos\n\n #replace any placeholder string -- or --/-- with None type to not confuse calculations later\n proj_ppr_espn_table_page.replace({'--': None, '--/--': None}, inplace=True)\n\n\n#if want to extract more detailed data from this, can do added reformatting, etc., but not doing that for our purposes\n# #rename D/ST columns so don't get misassigned to wrong columns\n# if pos == 'D/ST':\n# proj_ppr_espn_table_page.rename(columns={'SCK':'D/ST_Sack', \n# 'FR':'D/ST_FR', 'INT':'D/ST_INT',\n# 'TD':'D/ST_TD', 'BLK':'D/ST_BLK', 'PA':'D/ST_PA'},\n# inplace=True)\n \n# #rename/recalculate Kicker columns so don't get misassigned to wrong columns\n# elif pos == 'K':\n# proj_ppr_espn_table_page.rename(columns={'1-39':'KICK_FG_1-39', '40-49':'KICK_FG_40-49',\n# '50+':'KICK_FG_50+', 'TOT':'KICK_FG',\n# 'XP':'KICK_XP'},\n# inplace=True)\n \n# #if wanted to use all the kicker data could fix this code snipit - erroring out because can't split None types\n# #just want made FG's for each bucket and overall FGAtt and XPAtt\n# proj_ppr_espn_table_page['KICK_FGAtt'] = proj_ppr_espn_table_page['KICK_FG'].map(\n# lambda x: x.split(\"/\")[-1]).astype('float64')\n# proj_ppr_espn_table_page['KICK_XPAtt'] = proj_ppr_espn_table_page['KICK_XP'].map(\n# lambda x: x.split(\"/\")[-1]).astype('float64')\n# proj_ppr_espn_table_page['KICK_FG_1-39'] = proj_ppr_espn_table_page['KICK_FG_1-39'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# proj_ppr_espn_table_page['KICK_FG_40-49'] = proj_ppr_espn_table_page['KICK_FG_40-49'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# proj_ppr_espn_table_page['KICK_FG_50+'] = proj_ppr_espn_table_page['KICK_FG_50+'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# proj_ppr_espn_table_page['KICK_FG'] = proj_ppr_espn_table_page['KICK_FG'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# proj_ppr_espn_table_page['KICK_XP'] = proj_ppr_espn_table_page['KICK_XP'].map(\n# lambda x: x.split(\"/\")[0]).astype('float64')\n# proj_ppr_espn_table_page['KICK_FG%'] = proj_ppr_espn_table_page['KICK_FG'] / espn_proj_table_page['KICK_FGAtt']\n \n \n #add page data to overall dataframe\n proj_ppr_espn = pd.concat([proj_ppr_espn, proj_ppr_espn_table_page],\n ignore_index=True,\n sort=False)\n\n #click to next page to get next 40 results, but check that it exists\n try:\n next_button = driver.find_element_by_partial_link_text('NEXT')\n next_button.click()\n except EC.NoSuchElementException:\n break\n \n driver.quit()\n \n #drop any completely blank columns\n proj_ppr_espn.dropna(axis='columns', how='all', inplace=True)\n \n #add columns that give week/season\n proj_ppr_espn['WEEK'] = week\n proj_ppr_espn['SEASON'] = year\n \n return proj_ppr_espn",
"_____no_output_____"
],
[
"#formatting/extracting function is same for ESPN Actual/PPR Projections, so don't need new function",
"_____no_output_____"
],
[
"#WEEK 3 PROJECTIONS\n#CALL SCRAPE AND FORMATTING OF ESPN WEEKLY PROJECTIONS - AND SAVE TO PICKLES FOR LATER USE\n\n#scrape data and save the messy full dataframe\ndf_wk3_ppr_proj_espn_scrape = scrape_weekly_player_projections_ESPN(3, 2018)\nsave_to_pickle(df_wk3_ppr_proj_espn_scrape, 'pickle_archive', 'Week2_PPR_Projections_ESPN_messy_scrape')\n\n#format data to extract just player pts/playr/pos/team/week and save the data\ndf_wk3_ppr_proj_espn = format_extract_PPR_player_points_ESPN(df_wk3_ppr_proj_espn_scrape)\n#rename PTS column to something more descriptive \ndf_wk3_ppr_proj_espn.rename(columns={'PTS':'FPTS_PPR_ESPN'}, inplace=True) \nsave_to_pickle(df_wk3_ppr_proj_espn, 'pickle_archive', 'Week3_PPR_Projections_ESPN')\nprint(df_wk3_ppr_proj_espn.shape)\ndf_wk3_ppr_proj_espn.head()",
"Pickle saved to: pickle_archive/Week2_PPR_Projections_ESPN_messy_scrape_2018-9-18-18-3.pkl\nPickle saved to: pickle_archive/Week3_PPR_Projections_ESPN_2018-9-18-18-3.pkl\n(1009, 5)\n"
]
],
[
[
"### Get CBS Player Fantasy Points Projections for Week \nGet from CBS's Projections Table\n\nhttps://www.cbssports.com/fantasy/football/stats/sortable/points/QB/ppr/projections/2018/2?&print_rows=9999\n- QB is where position goes\n- 2018 is where season goes\n- 2 is where week goes\n- print_rows = 9999 gives all results in one table",
"_____no_output_____"
]
],
[
[
"##SCRAPE CBS PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS##\n\n#input needs to be year as four digit number and week as number \n#returns dataframe of scraped data\ndef scrape_weekly_player_projections_CBS(week, year):\n ###GET PROJECTIONS FROM CBS###\n #CBS has separate tables for each position, so need to cycle through them\n #but url can return all list so don't need to go page by page\n proj_ppr_cbs = pd.DataFrame()\n \n positions = ['QB', 'RB', 'WR', 'TE', 'K', 'DST']\n header_row_index = {'QB':2, 'RB':2, 'WR':2, 'TE':2, 'K':1, 'DST':1}\n \n for position in positions:\n #url just needs to change position\n url = f\"https://www.cbssports.com/fantasy/football/stats/sortable/points/{position}/ppr/projections/{year}/{week}?&print_rows=9999\"\n \n #read in the table from CBS by class, and use the 2nd row index for column header\n proj_ppr_cbs_pos = pd.read_html(url, \n attrs={'class': 'data'}, #return only the table of this class, which has the player data\n header=[header_row_index[position]])[0] #returns table in a list, so get table\n proj_ppr_cbs_pos['POS'] = position\n \n #add the table to the overall df\n proj_ppr_cbs = pd.concat([proj_ppr_cbs, proj_ppr_cbs_pos], \n ignore_index=True, \n sort=False)\n\n #some tables include the page selector as the bottom row of the table,\n #so need to find the index values of those rows and then drop them from the table\n index_pages_rows = list(proj_ppr_cbs[proj_ppr_cbs['Player'].str.contains('Pages')].index)\n proj_ppr_cbs.drop(index_pages_rows, axis='index', inplace=True)\n \n #add columns that give week/season\n proj_ppr_cbs['WEEK'] = week\n proj_ppr_cbs['SEASON'] = year\n \n return proj_ppr_cbs ",
"_____no_output_____"
],
[
"###FORMAT/EXTRACT ACTUAL PLAYER PPR DATA###\n#(you could make this more complex if want to extract some of the subdata)\n\ndef format_extract_PPR_player_points_CBS(df_scraped_ppr_cbs):\n# #could include this extra data if you want to extract it\n# #calculate completion percentage\n# df_cbs_proj['COMPLETION_PERCENTAGE'] = df_cbs_proj.CMP/df_cbs_proj.ATT\n\n\n# #rename some of columns so don't lose meaning\n# df_cbs_proj.rename(columns={'ATT':'PASS_ATT', 'CMP':'PASS_COMP', 'COMPLETION_PERCENTAGE': 'PASS_COMP_PCT',\n# 'YD': 'PASS_YD', 'TD':'PASS_TD', 'INT':'PASS_INT', 'RATE':'PASS_RATE', \n# 'ATT.1': 'RUSH_ATT', 'YD.1': 'RUSH_YD', 'AVG': 'RUSH_AVG', 'TD.1':'RUSH_TD',\n# 'TARGT': 'RECV_TARGT', 'RECPT': 'RECV_RECPT', 'YD.2':'RECV_YD', 'AVG.1':'RECV_AVG', 'TD.2':'RECV_TD',\n# 'FPTS':'PTS',\n# 'FG':'KICK_FG', 'FGA': 'KICK_FGAtt', 'XP':'KICK_XP', 'XPAtt':'KICK_XPAtt', \n# 'Int':'D/ST_INT', 'Sty':'D/ST_Sty', 'Sack':'D/ST_Sack', 'TK':'D/ST_TK',\n# 'DFR':'D/ST_FR', 'FF':'D/ST_FF', 'DTD':'D/ST_TD',\n# 'Pa':'D/ST_PtsAll', 'PaNetA':'D/ST_PaYdA', 'RuYdA':'D/ST_RuYdA', 'TyDa':'D/ST_ToYdA'},\n# inplace=True)\n\n\n# #calculate passing, rushing, total yards/game\n# df_cbs_proj['D/ST_PaYd/G'] = df_cbs_proj['D/ST_PaYdA']/16\n# df_cbs_proj['D/ST_RuYd/G'] = df_cbs_proj['D/ST_RuYdA']/16\n# df_cbs_proj['D/ST_ToYd/G'] = df_cbs_proj['D/ST_ToYdA']/16\n\n\n #rename FPTS to PTS\n df_scraped_ppr_cbs.rename(columns={'FPTS':'FPTS_PPR_CBS'}, inplace=True) \n \n\n #split out player, team\n def split_player_team(play_team):\n #incoming string for players: 'Todd Gurley, LAR'\n #incoming string for DST: 'Jaguars, JAC'\n\n #operations if D/ST (can tell if there is only two items in a list separated by a space, instead of three)\n if len(play_team.split()) == 2:\n player = play_team.split(',')[0] #+ ' D/ST'\n team = play_team.split(',')[1]\n\n #operations for regular players\n else:\n player = play_team.split(',')[0]\n team = play_team.split(',')[1]\n \n #remove any possible name suffixes to merge with other data better\n player = remove_suffixes_periods(player)\n \n return player, team\n\n \n df_scraped_ppr_cbs[['PLAYER', 'TEAM']] = df_scraped_ppr_cbs.apply(\n lambda x: split_player_team(x['Player']),\n axis='columns',\n result_type='expand')\n\n \n #convert defense position label to espn standard\n df_scraped_ppr_cbs['POS'] = df_scraped_ppr_cbs['POS'].map(convert_defense_label)\n \n \n #for this function only extract 'PLAYER', 'POS', 'TEAM', 'PTS'\n df_scraped_ppr_cbs = df_scraped_ppr_cbs[['PLAYER', 'POS', 'TEAM', 'FPTS_PPR_CBS', 'WEEK']].sort_values('FPTS_PPR_CBS', ascending=False)\n\n\n return df_scraped_ppr_cbs",
"_____no_output_____"
],
[
"#WEEK 3 PROJECTIONS\n#CALL SCRAPE AND FORMATTING OF CBS WEEKLY PROJECTIONS - AND SAVE TO PICKLES FOR LATER USE\n\n#scrape data and save the messy full dataframe\ndf_wk3_ppr_proj_cbs_scrape = scrape_weekly_player_projections_CBS(3, 2018)\nsave_to_pickle(df_wk3_ppr_proj_cbs_scrape, 'pickle_archive', 'Week3_PPR_Projections_CBS_messy_scrape')\n\n#format data to extract just player pts/playr/pos/team/week and save the data\ndf_wk3_ppr_proj_cbs = format_extract_PPR_player_points_CBS(df_wk3_ppr_proj_cbs_scrape)\nsave_to_pickle(df_wk3_ppr_proj_cbs, 'pickle_archive', 'Week3_PPR_Projections_CBS')\nprint(df_wk3_ppr_proj_cbs.shape)\ndf_wk3_ppr_proj_cbs.head()",
"Pickle saved to: pickle_archive/Week3_PPR_Projections_CBS_messy_scrape_2018-9-18-18-4.pkl\nPickle saved to: pickle_archive/Week3_PPR_Projections_CBS_2018-9-18-18-4.pkl\n(830, 5)\n"
]
],
[
[
"### Get Fantasy Sharks Player Points Projection for Week\nThey have a json option that gets updated weekly (don't appear to store previous week projections). The json defaults to PPR (which is lucky for us) and has an all players option.\n\nhttps://www.fantasysharks.com/apps/Projections/WeeklyProjections.php?pos=ALL&format=json\nIt returns a list of players, each saved as a dictionary.\n\n[\n {\n \"Rank\": 1,\n \"ID\": \"4925\",\n \"Name\": \"Brees, Drew\",\n \"Pos\": \"QB\",\n \"Team\": \"NOS\",\n \"Opp\": \"CLE\",\n \"Comp\": \"27.49\",\n \"PassYards\": \"337\",\n \"PassTD\": 2.15,\n \"Int\": \"0.61\",\n \"Att\": \"1.5\",\n \"RushYards\": \"0\",\n \"RushTD\": 0.12,\n \"Rec\": \"0\",\n \"RecYards\": \"0\",\n \"RecTD\": 0,\n \"FantasyPoints\": 26\n },\n \nBut the json is only for current week, can't get other week data - so instead use this url exampe:\nhttps://www.fantasysharks.com/apps/bert/forecasts/projections.php?Position=99&scoring=2&Segment=628&uid=4\n- Segment is the week/season id - for 2018 week 1 starts at 628 and adds 1 for each additional week\n- Position=99 is all positions\n- scoring=2 is PPR default\n",
"_____no_output_____"
]
],
[
[
"##SCRAPE FANTASY SHARKS PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS##\n\n#input needs to be week as number (year isn't used, but keep same format as others)\n#returns dataframe of scraped data\ndef scrape_weekly_player_projections_Sharks(week, year):\n #fantasy sharks url - segment for 2018 week 1 starts at 628 and adds 1 for each additional week\n segment = 627 + week\n #Position=99 is all positions, and scoring=2 is PPR default\n sharks_weekly_url = f\"https://www.fantasysharks.com/apps/bert/forecasts/projections.php?Position=99&scoring=2&Segment={segment}&uid=4\"\n\n #since don't need to iterate over pages, can just use reqeuests instead of selenium scraper\n #however with requests, need to include headers because this website was rejecting the request since it knew python was running it - need to spoof a browser header\n #other possible headers: 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)'}\n #response returns html\n response = requests.get(sharks_weekly_url, headers=headers)\n\n #extract the table data from the html response (call response.text) and get table with player data\n proj_ppr_sharks = pd.read_html(response.text, #response.text gives the html of the page request\n attrs={'id': 'toolData'}, #return only the table of this id, which has the player data\n header = 0 #header is the 0th row\n )[0] #pd.read_html returns a list of tables even though only one in it, select the table\n \n #the webpage uses different tiers, which add extra rows to the table - get rid of those\n #also sometimes repeats the column headers for readability as scrolling - get rid of those\n #so need to find the index values of those bad rows and then drop them from the table\n index_pages_rows = list(proj_ppr_sharks[proj_ppr_sharks['#'].str.contains('Tier|#')].index)\n proj_ppr_sharks.drop(index_pages_rows, axis='index', inplace=True)\n \n #add columns that give week/season\n proj_ppr_sharks['WEEK'] = week\n proj_ppr_sharks['SEASON'] = year\n \n return proj_ppr_sharks ",
"_____no_output_____"
],
[
"###FORMAT/EXTRACT ACTUAL PLAYER PPR DATA###\n#(you could make this more complex if want to extract some of the subdata like opposing team (OPP)\n\ndef format_extract_PPR_player_points_Sharks(df_scraped_ppr_sharks):\n #rename PTS to FPTS_PPR_SHARKS and a few others\n df_scraped_ppr_sharks.rename(columns={'Pts':'FPTS_PPR_SHARKS',\n 'Player': 'PLAYER',\n 'Tm': 'TEAM',\n 'Position': 'POS'},\n inplace=True) \n \n #they have player name as Last Name, First Name - reorder to First Last\n def modify_player_name(player, pos):\n #incoming string for players: 'Johnson, David' Change to: 'David Johnson'\n #incoming string for defense: 'Lions, Detroit' Change to: 'Lions'\n if pos == 'D':\n player_formatted = player.split(', ')[0]\n else:\n player_formatted = ' '.join(player.split(', ')[::-1])\n player_formatted = remove_suffixes_periods(player_formatted)\n \n #name overrides - some spelling differences from ESPN/CBS\n if player_formatted == 'Steven Hauschka':\n player_formatted = 'Stephen Hauschka'\n elif player_formatted == 'Josh Bellamy':\n player_formatted = 'Joshua Bellamy'\n elif player_formatted == 'Joshua Perkins': \n player_formatted = 'Josh Perkins'\n \n return player_formatted\n\n df_scraped_ppr_sharks['PLAYER'] = df_scraped_ppr_sharks.apply(\n lambda row: modify_player_name(row['PLAYER'], row['POS']),\n axis='columns')\n \n \n #convert FPTS to float type (currently stored as string)\n df_scraped_ppr_sharks['FPTS_PPR_SHARKS'] = df_scraped_ppr_sharks['FPTS_PPR_SHARKS'].astype('float64')\n\n \n #convert defense position label to espn standard\n df_scraped_ppr_sharks['POS'] = df_scraped_ppr_sharks['POS'].map(convert_defense_label)\n\n \n #for this function only extract 'PLAYER', 'POS', 'TEAM', 'FPTS'\n df_scraped_ppr_sharks = df_scraped_ppr_sharks[['PLAYER', 'POS', 'TEAM', 'FPTS_PPR_SHARKS', 'WEEK']].sort_values('FPTS_PPR_SHARKS', ascending=False)\n\n\n return df_scraped_ppr_sharks",
"_____no_output_____"
],
[
"#WEEK 3 PROJECTIONS\n#CALL SCRAPE AND FORMATTING OF FANTASY SHARKS WEEKLY PROJECTIONS - AND SAVE TO PICKLES FOR LATER USE\n\n#scrape data and save the messy full dataframe\ndf_wk3_ppr_proj_sharks_scrape = scrape_weekly_player_projections_Sharks(3, 2018)\nsave_to_pickle(df_wk3_ppr_proj_sharks_scrape, 'pickle_archive', 'Week3_PPR_Projections_Sharks_messy_scrape')\n\n#format data to extract just player pts/playr/pos/team and save the data\ndf_wk3_ppr_proj_sharks = format_extract_PPR_player_points_Sharks(df_wk3_ppr_proj_sharks_scrape)\nsave_to_pickle(df_wk3_ppr_proj_sharks, 'pickle_archive', 'Week3_PPR_Projections_Sharks')\nprint(df_wk3_ppr_proj_sharks.shape)\ndf_wk3_ppr_proj_sharks.head()",
"Pickle saved to: pickle_archive/Week3_PPR_Projections_Sharks_messy_scrape_2018-9-18-18-4.pkl\nPickle saved to: pickle_archive/Week3_PPR_Projections_Sharks_2018-9-18-18-4.pkl\n(971, 5)\n"
]
],
[
[
"### Get Scout Fantasy Sports Player Fantasy Points Projections for Week \nGet from Scout Fantasy Sports Projections Table\n\nhttps://fftoolbox.scoutfantasysports.com/football/rankings/?pos=rb&week=2&noppr=false\n- pos is position with options of 'QB','RB','WR','TE', 'K', 'DEF'\n- week is week of year\n- noppr is set to false when you want the ppr projections\n- it also returns one long table (no pagination required)",
"_____no_output_____"
]
],
[
[
"##SCRAPE Scout PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS##\n\n#input needs to be year as four digit number and week as number \n#returns dataframe of scraped data\ndef scrape_weekly_player_projections_SCOUT(week, year):\n ###GET PROJECTIONS FROM SCOUT###\n #SCOUT has separate tables for each position, so need to cycle through them\n #but url can return whole list so don't need to go page by page\n proj_ppr_scout = pd.DataFrame()\n \n positions = ['QB', 'RB', 'WR', 'TE', 'K', 'DEF']\n \n for position in positions:\n #url just needs to change position and week\n url = f\"https://fftoolbox.scoutfantasysports.com/football/rankings/?pos={position}&week={week}&noppr=false\"\n \n #response returns html\n response = requests.get(url, verify=False) #need verify false otherwise requests won't work on this site\n\n #extract the table data from the html response (call response.text) and get table with player data\n proj_ppr_scout_pos = pd.read_html(response.text, #response.text gives the html of the page request\n attrs={'class': 'responsive-table'}, #return only the table of this class, which has the player data\n header=0 #header is the 0th row\n )[0] #returns list of tables so get the table\n \n #add the table to the overall df\n proj_ppr_scout = pd.concat([proj_ppr_scout, proj_ppr_scout_pos], \n ignore_index=True, \n sort=False)\n\n #ads are included in table rows (eg 'googletag.defineSlot(\"/7103/SMG_FFToolBox/728x...')\n #so need to find the index values of those rows and then drop them from the table\n index_ads_rows = list(proj_ppr_scout[proj_ppr_scout['#'].str.contains('google')].index)\n proj_ppr_scout.drop(index_ads_rows, axis='index', inplace=True)\n \n #add columns that give week/season\n proj_ppr_scout['WEEK'] = week\n proj_ppr_scout['SEASON'] = year\n \n return proj_ppr_scout \n",
"_____no_output_____"
],
[
"###FORMAT/EXTRACT ACTUAL PLAYER PPR DATA###\n#(you could make this more complex if want to extract some of the subdata)\n\ndef format_extract_PPR_player_points_SCOUT(df_scraped_ppr_scout):\n #rename columns\n df_scraped_ppr_scout.rename(columns={'Projected Pts.':'FPTS_PPR_SCOUT',\n 'Player':'PLAYER',\n 'Pos':'POS',\n 'Team':'TEAM'},\n inplace=True) \n \n\n #some players (very few - mostly kickers) seem to have name as last, first instead of written out\n #also rename defenses from City/State to Mascot\n #create dictionary for geographical location to mascot (use this for some Defense renaming) based on this website's naming\n NFL_team_mascot = {'Arizona': 'Cardinals',\n 'Atlanta': 'Falcons',\n 'Baltimore': 'Ravens',\n 'Buffalo': 'Bills',\n 'Carolina': 'Panthers',\n 'Chicago': 'Bears',\n 'Cincinnati': 'Bengals',\n 'Cleveland': 'Browns',\n 'Dallas': 'Cowboys',\n 'Denver': 'Broncos',\n 'Detroit': 'Lions',\n 'Green Bay': 'Packers',\n 'Houston': 'Texans',\n 'Indianapolis': 'Colts',\n 'Jacksonville': 'Jaguars',\n 'Kansas City': 'Chiefs',\n #'Los Angeles': 'Rams',\n 'Miami': 'Dolphins',\n 'Minnesota': 'Vikings',\n 'New England': 'Patriots',\n 'New Orleans': 'Saints',\n 'New York Giants': 'Giants',\n 'New York Jets': 'Jets',\n 'Oakland': 'Raiders',\n 'Philadelphia': 'Eagles',\n 'Pittsburgh': 'Steelers',\n #'Los Angeles': 'Chargers',\n 'Seattle': 'Seahawks',\n 'San Francisco': '49ers',\n 'Tampa Bay': 'Buccaneers',\n 'Tennessee': 'Titans',\n 'Washington': 'Redskins'}\n #get Los Angelse defense data for assigning D's\n LosAngeles_defense_ranks = [int(x) for x in df_scraped_ppr_scout['#'][df_scraped_ppr_scout.PLAYER == 'Los Angeles'].tolist()]\n print(LosAngeles_defense_ranks)\n #in this function the defense rename here is SUPER GLITCHY since there are two Defenses' names 'Los Angeles', for now this code assumes the higher pts Defense is LA Rams\n def modify_player_name_scout(player, pos, rank):\n #defense need to change from city to mascot\n if pos == 'Def':\n #if Los Angeles is geographic location, then use minimum rank to Rams (assuming they are better defense)\n if player == 'Los Angeles' and int(rank) == min(LosAngeles_defense_ranks):\n player_formatted = 'Rams'\n elif player == 'Los Angeles' and int(rank) == max(LosAngeles_defense_ranks):\n player_formatted = 'Chargers'\n else: \n player_formatted = NFL_team_mascot.get(player)\n else:\n #if incoming string for players: 'Johnson, David' Change to: 'David Johnson' (this is rare - mostly for kickers on this site for som reason)\n if ',' in player:\n player = ' '.join(player.split(', ')[::-1])\n #remove suffixes/periods for all players \n player_formatted = remove_suffixes_periods(player)\n \n #hard override of some player names that don't match to ESPN naming\n if player_formatted == 'Juju Smith-Schuster': \n player_formatted = 'JuJu Smith-Schuster'\n elif player_formatted == 'Steven Hauschka':\n player_formatted = 'Stephen Hauschka'\n \n return player_formatted\n \n \n df_scraped_ppr_scout['PLAYER'] = df_scraped_ppr_scout.apply(\n lambda row: modify_player_name_scout(row['PLAYER'], row['POS'], row['#']),\n axis='columns')\n\n \n #convert defense position label to espn standard\n df_scraped_ppr_scout['POS'] = df_scraped_ppr_scout['POS'].map(convert_defense_label)\n \n\n #for this function only extract 'PLAYER', 'POS', 'TEAM', 'PTS', 'WEEK' (note Team is blank because webpage uses images for teams)\n df_scraped_ppr_scout = df_scraped_ppr_scout[['PLAYER', 'POS', 'TEAM', 'FPTS_PPR_SCOUT', 'WEEK']].sort_values('FPTS_PPR_SCOUT', ascending=False)\n\n\n return df_scraped_ppr_scout",
"_____no_output_____"
],
[
"#WEEK 3 PROJECTIONS\n#CALL SCRAPE AND FORMATTING OF SCOUT WEEKLY PROJECTIONS - AND SAVE TO PICKLES FOR LATER USE\n\n#scrape data and save the messy full dataframe\ndf_wk3_ppr_proj_scout_scrape = scrape_weekly_player_projections_SCOUT(3, 2018)\nsave_to_pickle(df_wk3_ppr_proj_scout_scrape, 'pickle_archive', 'Week3_PPR_Projections_SCOUT_messy_scrape')\n\n#format data to extract just player pts/playr/pos/team and save the data\ndf_wk3_ppr_proj_scout = format_extract_PPR_player_points_SCOUT(df_wk3_ppr_proj_scout_scrape)\nsave_to_pickle(df_wk3_ppr_proj_scout, 'pickle_archive', 'Week3_PPR_Projections_SCOUT')\nprint(df_wk3_ppr_proj_scout.shape)\ndf_wk3_ppr_proj_scout.head()",
"C:\\Users\\micha\\Anaconda3\\envs\\PythonData\\lib\\site-packages\\urllib3\\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nC:\\Users\\micha\\Anaconda3\\envs\\PythonData\\lib\\site-packages\\urllib3\\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nC:\\Users\\micha\\Anaconda3\\envs\\PythonData\\lib\\site-packages\\urllib3\\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nC:\\Users\\micha\\Anaconda3\\envs\\PythonData\\lib\\site-packages\\urllib3\\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nC:\\Users\\micha\\Anaconda3\\envs\\PythonData\\lib\\site-packages\\urllib3\\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nC:\\Users\\micha\\Anaconda3\\envs\\PythonData\\lib\\site-packages\\urllib3\\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n"
]
],
[
[
"### Get FanDuel Player Salaries for Week \n#### just import the Thurs-Mon game salaries (they differ for each game type, and note they don't include Kickers in the Thurs-Mon)\nGo to a FanDuel Thurs-Mon competition and Download a csv of players, which we then upload and format in python.",
"_____no_output_____"
]
],
[
[
"###FORMAT/EXTRACT FANDUEL SALARY INFO###\n\ndef format_extract_FanDuel(df_fanduel_csv, week, year):\n #rename columns\n df_fanduel_csv.rename(columns={'Position':'POS',\n 'Nickname':'PLAYER',\n 'Team':'TEAM',\n 'Salary':'SALARY_FANDUEL'},\n inplace=True) \n \n #add week/season columns\n df_fanduel_csv['WEEK'] = week\n df_fanduel_csv['SEASON'] = year\n\n #fix names\n def modify_player_name_fanduel(player, pos):\n #defense comes in as 'Dallas Cowboys' or 'Tampa Bay Buccaneers' need to split and take last word, which is the team mascot, just 'Cowboys' or 'Buccaneers'\n if pos == 'D':\n player_formatted = player.split()[-1]\n \n else:\n #need to remove suffixes, etc. \n player_formatted = remove_suffixes_periods(player)\n \n #hard override of some player names that don't match to ESPN naming\n if player_formatted == 'Josh Bellamy':\n player_formatted = 'Joshua Bellamy'\n \n return player_formatted\n \n \n df_fanduel_csv['PLAYER'] = df_fanduel_csv.apply(\n lambda row: modify_player_name_fanduel(row['PLAYER'], row['POS']),\n axis='columns')\n\n \n #convert defense position label to espn standard\n df_fanduel_csv['POS'] = df_fanduel_csv['POS'].map(convert_defense_label)\n \n \n #for this function only extract 'PLAYER', 'POS', 'TEAM', 'SALARY', 'WEEK' (note Team is blank because webpage uses images for teams)\n df_fanduel_csv = df_fanduel_csv[['PLAYER', 'POS', 'TEAM', 'SALARY_FANDUEL', 'WEEK']].sort_values('SALARY_FANDUEL', ascending=False)\n\n\n return df_fanduel_csv",
"_____no_output_____"
],
[
"#WEEK 3 FANDUEL SALARIES\n\n#import csv from FanDuel\ndf_wk3_fanduel_csv = pd.read_csv('fanduel_salaries/Week3-FanDuel-NFL-2018-09-20-28399-players-list.csv')\n\n#format data to extract just player salary/player/pos/team and save the data\ndf_wk3_fanduel = format_extract_FanDuel(df_wk3_fanduel_csv, 3, 2018)\nsave_to_pickle(df_wk3_fanduel, 'pickle_archive', 'Week3_Salary_FanDuel')\nprint(df_wk3_fanduel.shape)\ndf_wk3_fanduel.head()",
"Pickle saved to: pickle_archive/Week3_Salary_FanDuel_2018-9-18-18-5.pkl\n(665, 5)\n"
]
],
[
[
"##### !!!FFtoday apparently doesn't do weekly projections for Defenses, so don't use it for now (can check back in future and see if updated)!!!\n\n#### Get FFtoday Player Fantasy Points Projections for Week \nGet from FFtoday's Projections Table\n\nhttp://www.fftoday.com/rankings/playerwkproj.php?Season=2018&GameWeek=2&PosID=10&LeagueID=107644\n- Season = year\n- GameWeek = week\n- PosID = the id for each position 'QB':10, 'RB':20, 'WR':30, 'TE':40, 'K':80, 'DEF':99\n- LeagueID = the scoring type, 107644 gives FFToday PPR scoring",
"_____no_output_____"
]
],
[
[
"# ##SCRAPE FFtoday PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS##\n\n# #input needs to be year as four digit number and week as number \n# #returns dataframe of scraped data\n# def scrape_weekly_player_projections_FFtoday(week, year):\n# #instantiate selenium driver\n# driver = instantiate_selenium_driver()\n \n# #initialize dataframe for all data\n# proj_ppr_fft = pd.DataFrame()\n \n# #url that returns info has different code for each position and also takes year variable\n# position_ids = {'QB':10, 'RB':20, 'WR':30, 'TE':40, 'K':80, 'DEF':99}\n\n\n# #cycle through each position webpage to create comprehensive dataframe\n# for pos, pos_id in position_ids.items():\n# url_start_pos = f\"http://www.fftoday.com/rankings/playerwkproj.php?Season={year}&GameWeek={week}&PosID={pos_id}&LeagueID=107644\"\n# driver.get(url_start_pos)\n \n# #each page only gets 50 results, so cycle through next button until next button no longer exists\n# while True:\n# #read in table - no classes for tables so just need to find the right table in the list of tables from the page - 5th index\n# proj_ppr_fft_table_page = pd.read_html(driver.page_source, header=[1])[5]\n \n# proj_ppr_fft_table_page['POS'] = pos\n \n \n# #need to rename columns for different positions before concat because of differing column conventions\n# if pos == 'QB':\n# proj_ppr_fft_table_page.rename(columns={'Player Sort First: Last:':'PLAYER',\n# 'Comp':'PASS_COMP', 'Att': 'PASS_ATT', 'Yard':'PASS_YD',\n# 'TD':'PASS_TD', 'INT':'PASS_INT',\n# 'Att.1':'RUSH_ATT', 'Yard.1':'RUSH_YD', 'TD.1':'RUSH_TD'},\n# inplace=True)\n# elif pos == 'RB':\n# proj_ppr_fft_table_page.rename(columns={'Player Sort First: Last:':'PLAYER',\n# 'Att': 'RUSH_ATT', 'Yard':'RUSH_YD', 'TD':'RUSH_TD',\n# 'Rec':'RECV_RECPT', 'Yard.1':'RECV_YD', 'TD.1':'RECV_TD'},\n# inplace=True)\n \n# elif pos == 'WR':\n# proj_ppr_fft_table_page.rename(columns={'Player Sort First: Last:':'PLAYER',\n# 'Rec':'RECV_RECPT', 'Yard':'RECV_YD', 'TD':'RECV_TD',\n# 'Att':'RUSH_ATT', 'Yard.1':'RUSH_YD', 'TD.1':'RUSH_TD'},\n# inplace=True)\n \n# elif pos == 'TE':\n# proj_ppr_fft_table_page.rename(columns={'Player Sort First: Last:':'PLAYER',\n# 'Rec':'RECV_RECPT', 'Yard':'RECV_YD', 'TD':'RECV_TD'},\n# inplace=True)\n \n# elif pos == 'K':\n# proj_ppr_fft_table_page.rename(columns={'Player Sort First: Last:':'PLAYER',\n# 'FGM':'KICK_FG', 'FGA':'KICK_FGAtt', 'FG%':'KICK_FG%',\n# 'EPM':'KICK_XP', 'EPA':'KICK_XPAtt'},\n# inplace=True)\n \n# elif pos == 'DEF':\n# proj_ppr_fft_table_page['PLAYER'] = proj_ppr_fft_table_page['Team'] #+ ' D/ST' #add player name with team name plus D/ST tag\n# proj_ppr_fft_table_page.rename(columns={'Sack':'D/ST_Sack', 'FR':'D/ST_FR', 'DefTD':'D/ST_TD', 'INT':'D/ST_INT',\n# 'PA':'D/ST_PtsAll', 'PaYd/G':'D/ST_PaYd/G', 'RuYd/G':'D/ST_RuYd/G',\n# 'Safety':'D/ST_Sty', 'KickTD':'D/ST_RET_TD'},\n# inplace=True)\n \n \n# #add the position/page data to overall df\n# proj_ppr_fft = pd.concat([proj_ppr_fft, proj_ppr_fft_table_page],\n# ignore_index=True,\n# sort=False)\n \n \n# #click to next page to get next 50 results, but check that next button exists\n# try:\n# next_button = driver.find_element_by_link_text(\"Next Page\")\n# next_button.click()\n# except EC.NoSuchElementException:\n# break\n \n \n# driver.quit()\n \n# #add columns that give week/season\n# proj_ppr_fft['WEEK'] = week\n# proj_ppr_fft['SEASON'] = year\n \n \n# return proj_ppr_fft",
"_____no_output_____"
],
[
"# ###FORMAT/EXTRACT ACTUAL PLAYER PPR DATA###\n# #(you could make this more complex if want to extract some of the subdata)\n\n# def format_extract_PPR_player_points_FFtoday(df_scraped_ppr_fft):\n# # #optional data formatting for additional info\n# # #calculate completion percentage\n# # df_scraped_ppr_fft['PASS_COMP_PCT'] = df_scraped_ppr_fft.PASS_COMP/df_scraped_ppr_fft.PASS_ATT\n\n\n# # #calculate total PaYd and RuYd for season\n# # df_scraped_ppr_fft['D/ST_PaYdA'] = df_scraped_ppr_fft['D/ST_PaYd/G'] * 16\n# # df_scraped_ppr_fft['D/ST_RuYdA'] = df_scraped_ppr_fft['D/ST_RuYd/G'] * 16\n# # df_scraped_ppr_fft['D/ST_ToYd/G'] = df_scraped_ppr_fft['D/ST_PaYd/G'] + df_scraped_ppr_fft['D/ST_RuYd/G']\n# # df_scraped_ppr_fft['D/ST_ToYdA'] = df_scraped_ppr_fft['D/ST_ToYd/G'] * 16\n\n\n# #rename some of outstanding columns to match other dfs\n# df_scraped_ppr_fft.rename(columns={'Team':'TEAM', 'FPts':'FPTS_PPR_FFTODAY'},\n# inplace=True)\n\n# #remove any possible name suffixes to merge with other data better\n# df_scraped_ppr_fft['PLAYER'] = df_scraped_ppr_fft['PLAYER'].map(remove_suffixes_periods)\n \n \n# #for this function only extract 'PLAYER', 'POS', 'TEAM', 'PTS'\n# df_scraped_ppr_fft = df_scraped_ppr_fft[['PLAYER', 'POS', 'TEAM', 'FPTS_PPR_FFTODAY', 'WEEK']].sort_values('FPTS_PPR_FFTODAY', ascending=False)\n\n# return df_scraped_ppr_fft",
"_____no_output_____"
]
],
[
[
"#### Initial Database Stuff",
"_____no_output_____"
]
],
[
[
"# actual_ppr_df = pd.read_pickle('pickle_archive/Week1_Player_Actual_PPR_2018-9-13-6-41.pkl')\n# espn_final_df = pd.read_pickle('pickle_archive/Week1_PPR_Projections_ESPN_2018-9-13-6-46.pkl')\n# cbs_final_df = pd.read_pickle('pickle_archive/Week1_PPR_Projections_CBS_2018-9-13-17-45.pkl')",
"_____no_output_____"
],
[
"# cbs_final_df.head()",
"_____no_output_____"
],
[
"# from sqlalchemy import create_engine\n\n# disk_engine = create_engine('sqlite:///my_lite_store.db')\n# actual_ppr_df.to_sql('actual_ppr', disk_engine, if_exists='append')",
"_____no_output_____"
],
[
"# espn_final_df.to_sql('espn_final_df', disk_engine, if_exists='append')\n# cbs_final_df.to_sql('cbs_final_df', disk_engine, if_exists='append')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e78aff76a9dc0191625ecbe2ed96990a6a443e98 | 63,106 | ipynb | Jupyter Notebook | code-basics.ipynb | lukestein/coding-for-economists | 4466021d0003bbf804f3cc4f318765eb0ce3485d | [
"MIT"
] | null | null | null | code-basics.ipynb | lukestein/coding-for-economists | 4466021d0003bbf804f3cc4f318765eb0ce3485d | [
"MIT"
] | null | null | null | code-basics.ipynb | lukestein/coding-for-economists | 4466021d0003bbf804f3cc4f318765eb0ce3485d | [
"MIT"
] | 1 | 2021-09-29T07:08:34.000Z | 2021-09-29T07:08:34.000Z | 32.461934 | 729 | 0.57882 | [
[
[
"# Basics of Coding\n\nIn this chapter, you'll learn about the basics of objects, types, operations, conditions, loops, functions, and imports. These are the basic building blocks of almost all programming languages.\n\nThis chapter has benefited from the excellent [*Python Programming for Data Science*](https://www.tomasbeuzen.com/python-programming-for-data-science/README.html) book by Tomas Beuzen.\n\n```{tip}\nRemember, you can launch this page interactively by using the 'Colab' or 'Binder' buttons under the rocket symbol at the top of the page. You can also download this page as a Jupyter Notebook to run on your own computer: use the 'download .ipynb' button under the download symbol the top of the page.\n```\n\n## If you get stuck\n\nIt's worth saying at the outset that, *no-one*, and I mean no-one, memorises half of the stuff you'll see in this book. 80% or more of time spent programming is actually time spent looking up how to do this or that online, 'debugging' a code for errors, or testing code. This applies to all programmers, regardless of level. You are here to learn the skills and concepts of programming, not the precise syntax (which is easy to look up later).\n\n\n\nKnowing how to Google is one of the most important skills of any coder. No-one remembers every function from every library. Here are some useful coding resources:\n\n- when you have an error, look on Stack Overflow to see if anyone else had the same error (they probably did) and how they overcame it.\n\n- if you're having trouble navigating a new package or library, look up the documentation online. The best libraries put as much effort into documentation as they do the code base.\n\n- use cheat sheets to get on top of a range of functionality quickly. For instance, this excellent (mostly) base Python [Cheat Sheet](https://gto76.github.io/python-cheatsheet/).\n\n- if you're having a coding issue, take a walk to think about the problem, or explain your problem to an animal toy on your desk ([traditionally](https://en.wikipedia.org/wiki/Rubber_duck_debugging) a rubber duck, but other animals are available).\n\n## Values, variables, and types\n\nA value is datum such as a number or text. There are different types of values: 352.3 is known as a float or double, 22 is an integer, and \"Hello World!\" is a string. A variable is a name that refers to a value: you can think of a variable as a box that has a value, or multiple values, packed inside it. \n\nAlmost any word can be a variable name as long as it starts with a letter or an underscore, although there are some special keywords that can't be used because they already have a role in the Python language: these include `if`, `while`, `class`, and `lambda`.\n\nCreating a variable in Python is achieved via an assignment (putting a value in the box), and this assignment is done via the `=` operator. The box, or variable, goes on the left while the value we wish to store appears on the right. It's simpler than it sounds:",
"_____no_output_____"
]
],
[
[
"a = 10\nprint(a)",
"_____no_output_____"
]
],
[
[
"This creates a variable `a`, assigns the value 10 to it, and prints it. Sometimes you will hear variables referred to as *objects*. Everything that is not a literal value, such as `10`, is an object. In the above example, `a` is an object that has been assigned the value `10`.\n\nHow about this:",
"_____no_output_____"
]
],
[
[
"b = \"This is a string\"\nprint(b)",
"_____no_output_____"
]
],
[
[
"It's the same thing but with a different **type** of data, a string instead of an integer. Python is *dynamically typed*, which means it will guess what type of variable you're creating as you create it. This has pros and cons, with the main pro being that it makes for more concise code.\n\n```{admonition} Important\nEverything is an object, and every object has a type.\n```\n\nThe most basic built-in data types that you'll need to know about are: integers `10`, floats `1.23`, strings `like this`, booleans `True`, and nothing `None`. Python also has a built-in type called a list `[10, 15, 20]` that can contain anything, even *different* types. So",
"_____no_output_____"
]
],
[
[
"list_example = [10, 1.23, \"like this\", True, None]\nprint(list_example)",
"_____no_output_____"
]
],
[
[
"is completely valid code. `None` is a special type of nothingness, and represents an object with no value. It has type `NoneType` and is more useful than you might think! \n\nAs well as the built-in types, packages can define their own custom types. If you ever want to check the type of a Python variable, you can call the `type` function on it like so:",
"_____no_output_____"
]
],
[
[
"type(list_example)",
"_____no_output_____"
]
],
[
[
"This is especially useful for debugging `ValueError` messages.\n\nBelow is a table of common data types in Python:\n\n| Name | Type name | Type Category | Description | Example |\n| :-------------------- | :--------- | :------------- | :-------------------------------------------- | :----------------------------------------- |\n| integer | `int` | Numeric Type | positive/negative whole numbers | `22` |\n| floating point number | `float` | Numeric Type | real number in decimal form | `3.14159` |\n| boolean | `bool` | Boolean Values | true or false | `True` |\n| string | `str` | Sequence Type | text | `\"Hello World!\"` |\n| list | `list` | Sequence Type | a collection of objects - mutable & ordered | `['text entry', True, 16]` |\n| tuple | `tuple` | Sequence Type | a collection of objects - immutable & ordered | `(51.02, -0.98)` |\n| dictionary | `dict` | Mapping Type | mapping of key-value pairs | `{'name':'Ada', 'subject':'computer science'}` |\n| none | `NoneType` | Null Object | represents no value | `None` |\n| function | `function` | Function | Represents a function | `def add_one(x): return x+1` |\n\n### Brackets\n\nYou may notice that there are several kinds of brackets that appear in the code we've seen so far, including `[]`, `{}`, and `()`. These can play different roles depending on the context, but the most common uses are:\n\n- `[]` is used to denote a list, eg `['a', 'b']`, or to signify accessing a position using an index, eg `vector[0]` to get the first entry of a variable called vector.\n\n- `{}` is used to denote a set, eg `{'a', 'b'}`, or a dictionary (with pairs of terms), eg `{'first_letter': 'a', 'second_letter': 'b'}`.\n\n- `()` is used to denote a tuple, eg `('a', 'b')`, or the arguments to a function, eg `function(x)` where `x` is the input passed to the function, *or* to indicate the order operations are carried out.\n\n## Lists and slicing\n\nLists are a really useful way to work with lots of data at once. They're defined with square brackets, with entries separated by commas. You can also construct them by appending entries:",
"_____no_output_____"
]
],
[
[
"list_example.append(\"one more entry\")\nprint(list_example)",
"_____no_output_____"
]
],
[
[
"And you can access earlier entries using an index, which begins at 0 and ends at one less than the length of the list (this is the convention in many programming languages). For instance, to print specific entries at the start, using `0`, and end, using `-1`:",
"_____no_output_____"
]
],
[
[
"print(list_example[0])\nprint(list_example[-1])",
"_____no_output_____"
]
],
[
[
"As well as accessing positions in lists using indexing, you can use *slices* on lists. This uses the colon character, `:`, to stand in for 'from the beginning' or 'until the end' (when only appearing once). For instance, to print just the last two entries, we would use the index `-2:` to mean from the second-to-last onwards. Here are two distinct examples: getting the first three and last three entries to be successively printed:",
"_____no_output_____"
]
],
[
[
"print(list_example[:3])\nprint(list_example[-3:])",
"_____no_output_____"
]
],
[
[
"Slicing can be even more elaborate than that because we can jump entries using a second colon. Here's a full example that begins at the second entry (remember the index starts at 0), runs up until the second-to-last entry (exclusive), and jumps every other entry inbetween (range just produces a list of integers from the value to one less than the last):",
"_____no_output_____"
]
],
[
[
"list_of_numbers = list(range(1, 11))\nstart = 1\nstop = -1\nstep = 2\nprint(list_of_numbers[start:stop:step])",
"_____no_output_____"
]
],
[
[
"A handy trick is that you can print a reversed list entirely using double colons:",
"_____no_output_____"
]
],
[
[
"print(list_of_numbers[::-1])",
"_____no_output_____"
]
],
[
[
"What's amazing about lists is that they can hold any type, including other lists! Here's a valid example of a list that's got a lot going on:",
"_____no_output_____"
]
],
[
[
"wacky_list = [\n 3.1415,\n 16,\n [\"five\", 4, 3],\n \"Hello World!\",\n True,\n None,\n {\"key\": \"value\", \"key2\": \"value2\"},\n]\nwacky_list",
"_____no_output_____"
]
],
[
[
"Can you identify the types of each of the entries (and entries of entries)?\n\n## Operators\n\nAll of the basic operators you see in mathematics are available to use: `+` for addition, `-` for subtraction, `*` for multiplication, `**` for powers, `/` for division, and `%` for modulo. These work as you'd expect on numbers. But these operators are sometimes defined for other built-in data types too. For instance, we can 'sum' strings (which really concatenates them):",
"_____no_output_____"
]
],
[
[
"string_one = \"This is an example \"\nstring_two = \"of string concatenation\"\nstring_full = string_one + string_two\nprint(string_full)",
"_____no_output_____"
]
],
[
[
"It works for lists too:",
"_____no_output_____"
]
],
[
[
"list_one = [\"apples\", \"oranges\"]\nlist_two = [\"pears\", \"satsumas\"]\nlist_full = list_one + list_two\nprint(list_full)",
"_____no_output_____"
]
],
[
[
"Perhaps more surprisingly, you can multiply strings!",
"_____no_output_____"
]
],
[
[
"string = \"apples, \"\nprint(string * 3)",
"_____no_output_____"
]
],
[
[
"Below is a table of the basic arithmetic operations.\n\n| Operator | Description |\n| :------: | :--------------: |\n| `+` | addition |\n| `-` | subtraction |\n| `*` | multiplication |\n| `/` | division |\n| `**` | exponentiation |\n| `//` | integer division / floor division |\n| `%` | modulo |\n| `@` | matrix multiplication |\n\nAs well as the usual operators, Python supports *assignment operators*. An example of one is `x+=3`, which is equivalent to running `x = x + 3`. Pretty much all of the operators can be used in this way.\n\n\n## Strings\n\nIn some ways, strings are treated a bit like lists, meaning you can access the individual characters via slicing and indexing. For example:",
"_____no_output_____"
]
],
[
[
"string = \"cheesecake\"\nprint(string[-4:])",
"_____no_output_____"
]
],
[
[
"Both lists and strings will also allow you to use the `len` command to get their length:",
"_____no_output_____"
]
],
[
[
"string = \"cheesecake\"\nprint(\"String has length:\")\nprint(len(string))\nlist_of_numbers = range(1, 20)\nprint(\"List of numbers has length:\")\nprint(len(list_of_numbers))",
"_____no_output_____"
]
],
[
[
"Strings have type `string` and can be defined by single or double quotes, eg `string = \"cheesecake\"` would have been equally valid above.\n\nThere are various functions built into Python to help you work with strings that are particularly useful for cleaning messy data. For example, imagine you have a variable name like 'This Is /A Variable '. (You may think this is implausibly bad; I only wish that were true). Let's see if we can clean this up:",
"_____no_output_____"
]
],
[
[
"string = \"This Is /A Variable \"\nstring = string.replace(\"/\", \"\").rstrip().lower()\nprint(string)",
"_____no_output_____"
]
],
[
[
"The steps above replace the character '/', strip out whitespace on the right hand-side of the string, and put everything in lower case. The brackets after the words signify that a function has been applied; we'll see more of functions later.\n\nYou'll often want to output one type of data as another, and Python generally knows what you're trying to achieve if you, for example, `print` a boolean value. For numbers, there are more options and you can see a big list of advice on string formatting of all kinds of things [here](https://pyformat.info/). For now, let's just see a simple example of something called an f-string, a string that combines a number and a string (these begin with an `f` for formatting):",
"_____no_output_____"
]
],
[
[
"value = 20\nsqrt_val = 20 ** 0.5\nprint(f\"The square root of {value:d} is {sqrt_val:.2f}\")",
"_____no_output_____"
]
],
[
[
"The formatting command `:d` is an instruction to treat `value` like an integer, while `:.2f` is an instruction to print it like a float with 2 decimal places.\n\n```{note}\nf-strings are only available in Python 3.6+\n```\n\n## Booleans and conditions\n\nSome of the most important operations you will perform are with `True` and `False` values, also known as boolean data types. There are two types of operation that are associated with booleans: boolean operations, in which existing booleans are combined, and condition operations, which create a boolean when executed.\n\nBoolean operators that return booleans are as follows:\n\n| Operator | Description |\n| :---: | :--- |\n|`x and y`| are `x` and `y` both True? |\n|`x or y` | is at least one of `x` and `y` True? |\n| `not x` | is `x` False? | \n\nThese behave as you'd expect: `True and False` evaluates to `False`, while `True or False` evaluates to `True`. There's also the `not` keyword. For example",
"_____no_output_____"
]
],
[
[
"not True",
"_____no_output_____"
]
],
[
[
"as you would expect.\n\nConditions are expressions that evaluate as booleans. A simple example is `10 == 20`. The `==` is an operator that compares the objects on either side and returns `True` if they have the same *values*--though be careful using it with different data types.\n\nHere's a table of conditions that return booleans:\n\n| Operator | Description |\n| :-------- | :----------------------------------- |\n| `x == y ` | is `x` equal to `y`? |\n| `x != y` | is `x` not equal to `y`? |\n| `x > y` | is `x` greater than `y`? |\n| `x >= y` | is `x` greater than or equal to `y`? |\n| `x < y` | is `x` less than `y`? |\n| `x <= y` | is `x` less than or equal to `y`? |\n| `x is y` | is `x` the same object as `y`? |\n\n\nAs you can see from the table, the opposite of `==` is `!=`, which you can read as 'not equal to the value of'. Here's an example of `==`:",
"_____no_output_____"
]
],
[
[
"boolean_condition = 10 == 20\nprint(boolean_condition)",
"_____no_output_____"
]
],
[
[
"The real power of conditions comes when we start to use them in more complex examples. Some of the keywords that evaluate conditions are `if`, `else`, `and`, `or`, `in`, `not`, and `is`. Here's an example showing how some of these conditional keywords work:",
"_____no_output_____"
]
],
[
[
"name = \"Ada\"\nscore = 99\n\nif name == \"Ada\" and score > 90:\n print(\"Ada, you achieved a high score.\")\n\nif name == \"Smith\" or score > 90:\n print(\"You could be called Smith or have a high score\")\n\nif name != \"Smith\" and score > 90:\n print(\"You are not called Smith and you have a high score\")",
"_____no_output_____"
]
],
[
[
"All three of these conditions evaluate as True, and so all three messages get printed. Given that `==` and `!=` test for equality and not equal, respectively, you may be wondering what the keywords `is` and `not` are for. Remember that everything in Python is an object, and that values can be assigned to objects. `==` and `!=` compare *values*, while `is` and `not` compare *objects*. For example,",
"_____no_output_____"
]
],
[
[
"name_list = [\"Ada\", \"Adam\"]\nname_list_two = [\"Ada\", \"Adam\"]\n\n# Compare values\nprint(name_list == name_list_two)\n\n# Compare objects\nprint(name_list is name_list_two)",
"_____no_output_____"
]
],
[
[
"One of the most useful conditional keywords is `in`. I must use this one ten times a day to pick out a variable or make sure something is where it's supposed to be.",
"_____no_output_____"
]
],
[
[
"name_list = [\"Lovelace\", \"Smith\", \"Hopper\", \"Babbage\"]\n\nprint(\"Lovelace\" in name_list)\n\nprint(\"Bob\" in name_list)",
"_____no_output_____"
]
],
[
[
"The opposite is `not in`.\n\nFinally, one conditional construct you're bound to use at *some* point, is the `if`...`else` structure:",
"_____no_output_____"
]
],
[
[
"score = 98\n\nif score == 100:\n print(\"Top marks!\")\nelif score > 90 and score < 100:\n print(\"High score!\")\nelif score > 10 and score <= 90:\n pass\nelse:\n print(\"Better luck next time.\")",
"_____no_output_____"
]
],
[
[
"Note that this does nothing if the score is between 11 and 90, and prints a message otherwise.\n\nOne nice feature of Python is that you can make multiple boolean comparisons in a single line.",
"_____no_output_____"
]
],
[
[
"a, b = 3, 6\n\n1 < a < b < 20",
"_____no_output_____"
]
],
[
[
"## Casting variables\n\nSometimes we need to explicitly cast a value from one type to another. We can do this using functions like `str()`, `int()`, and `float()`. If you try these, Python will do its best to interpret the input and convert it to the output type you'd like and, if they can't, the code will throw a great big error.\n\nHere's an example of casting a `float` as an `int`:",
"_____no_output_____"
]
],
[
[
"orig_number = 4.39898498\ntype(orig_number)",
"_____no_output_____"
]
],
[
[
"Now we cast it to an int:",
"_____no_output_____"
]
],
[
[
"mod_number = int(orig_number)\nmod_number",
"_____no_output_____"
]
],
[
[
"which looks like it became an integer, but we can double check that:",
"_____no_output_____"
]
],
[
[
"type(mod_number)",
"_____no_output_____"
]
],
[
[
"## Tuples and (im)mutability\n\nA tuple is an object that is defined by parentheses and entries that are separated by commas, for example `(15, 20, 32)`. (They are of type `tuple`.) As such, they have a lot in common with lists-but there's a big and important difference.\n\nTuples are immutable, while lists are mutable. This means that, once defined, we can always modify a list using slicing and indexing, e.g. to change the first entry of a list called `listy` we would use `listy[0] = 5`. But trying to do this with a tuple will result in an error.\n\n*Immutable* objects, such as tuples, can't have their elements changed, appended, extended, or removed. Lists can do all of these things. Tuples aren't the only immutable objects in Python; strings are immutable too.\n\nYou may wonder why both are needed given lists seem to provide a superset of functionality: sometimes in coding, lack of flexibility is a *good* thing because it restricts the number of ways a process can go awry. I dare say there are other reasons too, but you don't need to worry about them and using lists is a good default most of the time.\n\n## Indentation\n\nYou'll have seen that certain parts of the code examples are indented. Code that is part of a function, a conditional clause, or loop is indented. This isn't a code style choice, it's actually what tells the language that some code is to be executed as part of, say, a loop and not to executed after the loop is finished.\n\nHere's a basic example of indentation as part of an `if` loop. The `print` statement that is indented only executes if the condition evaluates to true.",
"_____no_output_____"
]
],
[
[
"x = 10\n\nif x > 2:\n print(\"x is greater than 2\")",
"_____no_output_____"
]
],
[
[
"When functions, conditional clauses, or loops are combined together, they each cause an *increase* in the level of indentation. Here's a double indent.",
"_____no_output_____"
]
],
[
[
"if x > 2:\n print(\"outer conditional cause\")\n for i in range(4):\n print(\"inner loop\")",
"_____no_output_____"
]
],
[
[
"The standard practice for indentation is that each sub-statement should be indented by 4 spaces. It can be hard to keep track of these but, as usual, Visual Studio Code has you covered. Go to Settings (the cog in the bottom left-hand corner, then click Settings) and type 'Whitespace' into the search bar. Under 'Editor: Render Whitespace', select 'boundary'. This will show any whitespace that is more than one character long using faint grey dots. Each level of indentation in your Python code should now begin with four grey dots showing that it consists of four spaces. To make it even easier, you can install the 'indent-rainbow' extension in VS Code-this shows different levels of indentation in different colours.\n\n## Loops and list comprehensions\n\nA loop is a way of executing a similar piece of code over and over in a similar way. The most useful loops are `for` loops and list comprehensions.\n\nA `for` loop does something *for* the time that the condition is satisfied. For example,",
"_____no_output_____"
]
],
[
[
"name_list = [\"Lovelace\", \"Smith\", \"Pigou\", \"Babbage\"]\n\nfor name in name_list:\n print(name)",
"_____no_output_____"
]
],
[
[
"prints out a name until all names have been printed out. A useful trick with for loops is the `enumerate` keyword, which runs through an index that keeps track of the items in a list:",
"_____no_output_____"
]
],
[
[
"name_list = [\"Lovelace\", \"Smith\", \"Hopper\", \"Babbage\"]\n\nfor i, name in enumerate(name_list):\n print(f\"The name in position {i} is {name}\")",
"_____no_output_____"
]
],
[
[
"Remember, Python indexes from 0 so the first entry of `i` will be zero. But, if you'd like to index from a different number, you can:",
"_____no_output_____"
]
],
[
[
"for i, name in enumerate(name_list, start=1):\n print(f\"The name in position {i} is {name}\")",
"_____no_output_____"
]
],
[
[
"High-level languages like Python and R do not get *compiled* into highly performant machine code ahead of being run, unlike C++ and FORTRAN. What this means is that although they are much less unwieldy to use, some types of operation can be very slow--and `for` loops are particularly cumbersome. (Although you may not notice this unless you're working on a bigger computation.)\n\nBut there is a way around this, and it's with something called a *list comprehension*. These can combine what a `for` loop and a `condition` do in a single line of efficiently executable code. Say we had a list of numbers and wanted to filter it according to whether the numbers divided by 3 or not:",
"_____no_output_____"
]
],
[
[
"number_list = range(1, 40)\ndivide_list = [x for x in number_list if x % 3 == 0]\nprint(divide_list)",
"_____no_output_____"
]
],
[
[
"Or if we only wanted to pick out names that end in 'Smith':",
"_____no_output_____"
]
],
[
[
"names_list = [\"Joe Bloggs\", \"Adam Smith\", \"Sandra Noone\", \"leonara smith\"]\nsmith_list = [x for x in names_list if \"smith\" in x.lower()]\nprint(smith_list)",
"_____no_output_____"
]
],
[
[
"Note how we used 'smith' rather than 'Smith' and then used `lower()` to ensure we matched names regardless of the case they are written in. We can even do a whole `if` ... `else` construct *inside* a list comprehension:",
"_____no_output_____"
]
],
[
[
"names_list = [\"Joe Bloggs\", \"Adam Smith\", \"Sandra Noone\", \"leonara smith\"]\nsmith_list = [x if \"smith\" in x.lower() else \"Not Smith!\" for x in names_list]\nprint(smith_list)",
"_____no_output_____"
]
],
[
[
"Many of the constructs we've seen can be combined. For instance, there is no reason why we can't have a nested or repeated list comprehension, and, perhaps more surprisingly, sometimes these are useful!",
"_____no_output_____"
]
],
[
[
"first_names = [\"Ada\", \"Adam\", \"Grace\", \"Charles\"]\nlast_names = [\"Lovelace\", \"Smith\", \"Hopper\", \"Babbage\"]\nnames_list = [x + \" \" + y for x, y in zip(first_names, last_names)]\nprint(names_list)",
"_____no_output_____"
]
],
[
[
"The `zip` keyword is doing this magic; think of it like a zipper, bringing an element of each list together in turn. It can also be used directly in a for loop:",
"_____no_output_____"
]
],
[
[
"for first_nm, last_nm in zip(first_names, last_names):\n print(first_nm, last_nm)",
"_____no_output_____"
]
],
[
[
"Finally, an even more extreme use of list comprehensions can deliver nested structures:",
"_____no_output_____"
]
],
[
[
"first_names = [\"Ada\", \"Adam\"]\nlast_names = [\"Lovelace\", \"Smith\"]\nnames_list = [[x + \" \" + y for x in first_names] for y in last_names]\nprint(names_list)",
"_____no_output_____"
]
],
[
[
"This gives a nested structure that (in this case) iterates over `first_names` first, and then `last_names`. If you'd like to learn more about list comprehensions, check out these [short video tutorials](https://calmcode.io/comprehensions/introduction.html).\n\n## While loops\n\n`while` loops continue to execute code until their conditional expression evaluates to `False`. (Of course, if it evaluates to `True` forever, your code will just continue to execute...)",
"_____no_output_____"
]
],
[
[
"n = 10\nwhile n > 0:\n print(n)\n n -= 1\n\nprint(\"execution complete\")",
"_____no_output_____"
]
],
[
[
"NB: in case you're wondering what `-=` does, it's a compound assignment that sets the left-hand side equal to the left-hand side minus the right-hand side.\n\nYou can use the keyword `break` to break out of a while loop, for example if it's reached a certain number of iterations without converging.\n\n## Dictionaries\n\nAnother built-in Python type that is enormously useful is the *dictionary*. This provides a mapping one set of variables to another (either one-to-one or many-to-one). Let's see an example of defining a dictionary and using it:",
"_____no_output_____"
]
],
[
[
"fruit_dict = {\n \"Jazz\": \"Apple\",\n \"Owari\": \"Satsuma\",\n \"Seto\": \"Satsuma\",\n \"Pink Lady\": \"Apple\",\n}\n\n# Add an entry\nfruit_dict.update({\"Cox\": \"Apple\"})\n\nvariety_list = [\"Jazz\", \"Jazz\", \"Seto\", \"Cox\"]\n\nfruit_list = [fruit_dict[x] for x in variety_list]\nprint(fruit_list)",
"_____no_output_____"
]
],
[
[
"From an input list of varieties, we get an output list of their associated fruits. Another good trick to know with dictionaries is that you can iterate through their keys and values:",
"_____no_output_____"
]
],
[
[
"for key, value in fruit_dict.items():\n print(key + \" maps into \" + value)",
"_____no_output_____"
]
],
[
[
"## Running on empty\n\nBeing able to create empty containers is sometimes useful. The commands to create empty lists, tuples, dictionaries, and sets are `lst = []`, `tup=()`, `dic={}`, and `st = set()` respectively.\n\n## Functions\n\nIf you're an economist, I hardly need to tell you what a function is. In coding, it's much the same as in mathematics: a function has inputs, it performs its function, and it returns any outputs. Functions begin with a `def` keyword for 'define a function'. It then has a name, followed by brackets, `()`, which may contain *function arguments* and *function keyword arguments*. The body of the function is then indented relative to the left-most text. Function arguments are defined in brackets following the name, with different inputs separated by commas. Any outputs are given with the `return` keyword, again with different variables separated by commas. Let's see a very simple example:",
"_____no_output_____"
]
],
[
[
"def welcome_message(name):\n return f\"Hello {name}, and welcome!\"\n\n\n# Without indentation, this code is not part of function\nname = \"Ada\"\noutput_string = welcome_message(name)\nprint(output_string)",
"_____no_output_____"
]
],
[
[
"One powerful feature of functions is that we can define defaults for the input arguments. Let's see that in action by defining a default value for `name`, along with multiple outputs--a hello message and a score.",
"_____no_output_____"
]
],
[
[
"def score_message(score, name=\"student\"):\n \"\"\"This is a doc-string, a string describing a function.\n Args:\n score (float): Raw score\n name (str): Name of student\n Returns:\n str: A hello message.\n float: A normalised score.\n \"\"\"\n norm_score = (score - 50) / 10\n return f\"Hello {name}\", norm_score\n\n\n# Without indentation, this code is not part of function\nname = \"Ada\"\nscore = 98\n# No name entered\nprint(score_message(score))\n# Name entered\nprint(score_message(score, name=name))",
"_____no_output_____"
]
],
[
[
"In that last example, you'll notice that I added some text to the function. This is a doc-string. It's there to help users (and, most likely, future you) to understand what the function does. Let's see how this works in action by calling `help` on the `score_message` function:",
"_____no_output_____"
]
],
[
[
"help(score_message)",
"_____no_output_____"
]
],
[
[
"## Scope\n\nScope refers to what parts of your code can see what other parts. If you define a variable inside a function, the rest of your code won't be able to 'see' it or use it. For example, here's a function that creates a variable and then an example of calling that variable:\n\n```python\ndef var_func():\n str_variable = 'Hello World!'\n\nvar_func()\nprint(str_variable)\n```\n\nThis would raise an error, because as far as your general code is concerned `str_variable` doesn't exist outside of the function. If you want to create variables inside a function and have them persist, you need to explicitly pass them out using, for example `return str_variable` like this:",
"_____no_output_____"
]
],
[
[
"def var_func():\n str_variable = \"Hello World!\"\n return str_variable\n\n\nreturned_var = var_func()\nprint(returned_var)",
"_____no_output_____"
]
],
[
[
"Or, if you only want to modify a variable, you can declare the variable before the function is run, pass it into the function, and then return it.\n\n\n## Using packages and modules\n\nWe already saw how to install packages in the previous chapter: using `pip install packagename` or `conda install packagename` on the command line. What about using a package that you've installed? That's what we'll look at now.\n\n```{note}\nIf you want to install packages into a dedicated conda environment, remember to `conda activate environmentname` before using the package install command(s).\n```\n\nLet's see an example of using the powerful numerical library **numpy**. There are different ways to import packages, you can import the entire package in one go or just import the functions you need. When an entire package is imported, you can give it any name you like and the convention for **numpy** is to import it as the shortened 'np'. All of the functions and methods of the package can be accessed by typing `np` followed by `.` and then typing the function name. As well as demonstrating importing the whole package, the example below shows importing just one specific function.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom numpy.linalg import inv\n\nmatrix = np.array([[4.0, 2.0, 4.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])\n\nprint(\"Matrix:\")\nprint(matrix)\n\ninv_mat = inv(matrix)\nprint(\"Inverse:\")\nprint(inv_mat)",
"_____no_output_____"
]
],
[
[
"We could have imported all of **numpy** using `from numpy import *` but this is considered bad practice as it fills our 'namespace' with function names that might clash with other packages and it's less easy to parse which package's function is doing what. R also relies heavily on imported libraries but uses a different convention for namespaces: in that case, everything is imported but the *order* of package imports matters for what functions are default.\n\n```{note}\nIf you want to check what packages you have installed in your Python environment, run `conda list` on the command line.\n```\n\n### Modules\n\nSometimes, you will want to call in some code from a different script. Imagine you have several code scripts (a, b, and c), all of which use the same underlying function that *you* have written. A central tenet of good coding is that you *do not repeat yourself*. Therefore, a bad solution to this problem would be to copy and paste the same code into all three of the scripts. A *good* solution is to write the code that's need just once in a separate 'utility' script and have the other scripts import that one function:",
"_____no_output_____"
]
],
[
[
"import networkx as nx\nimport matplotlib.pyplot as plt\n\ngraph = nx.DiGraph()\ngraph.add_edges_from(\n [\n (\"Utility script\", \"code file a\"),\n (\"Utility script\", \"code file b\"),\n (\"code file a\", \"code file c\"),\n (\"code file b\", \"code file c\"),\n (\"Utility script\", \"code file c\"),\n ]\n)\ncolour_node = \"#AFCBFF\"\nfixed_pos = nx.spring_layout(graph, seed=100)\nnx.draw(graph, pos=fixed_pos, with_labels=True, node_size=5000, node_color=colour_node)\nplt.xlim(-1.3, 1.3)\nplt.ylim(-1.3, 1.3)\nplt.show();",
"_____no_output_____"
]
],
[
[
"How would this work in practice? We would define a file 'utilities.py' that had the following:\n\n```python\n# Contents of utilities.py file\ndef really_useful_func(number):\n return number*10\n```\n\nThen, in 'code_script_a.py':",
"_____no_output_____"
]
],
[
[
"import utilities as utils\n\nprint(utils.really_useful_func(20))",
"_____no_output_____"
]
],
[
[
"An alternative is to *just* import the function we want, with the name we want:",
"_____no_output_____"
]
],
[
[
"from utilities import really_useful_func as ru_fn\n\nprint(ru_fn(30))",
"_____no_output_____"
]
],
[
[
"Another important example is the case where you want to run 'utilities.py' as a script, but still want to borrow functions from it to run in other scripts. There's a way to do this. Let's change utilities.py to\n\n```python\n# Contents of utilities.py file\ndef really_useful_func(number):\n return number*10\n\n\ndef default_func():\n print('Script has run')\n\n\nif __name__ == '__main__':\n default_func()\n```\n\nWhat this says is that if we call 'utilities.py' from the command line, eg\n\n```bash\npython utilities.py\n```\n\nIt will return `Script has run` because, by executing the script alone, we are asking for anything in the `main` block defined at the end of the file to be run. But we can still import anything from utilities into other scripts as before--and in that case it is not the main script, but an import, and so the `main` block will *not* be executed.\n\nYou can important several functions at once from a module (aka another script file) like this:\n\n```python\nfrom utilities import really_useful_func, default_func\n```\n\n## Lambda functions\n\nLambda functions are a very old idea in programming, and part of the functional programming paradigm. Coding languages tend to be more object-oriented or functional, though high-level languages often mix both. For example, R leans slightly more toward being a functional language, while Python is slightly more object oriented. However, Python does have lambda functions, for example:",
"_____no_output_____"
]
],
[
[
"plus_one = lambda x: x + 1\nplus_one(3)",
"_____no_output_____"
]
],
[
[
"For a one-liner function that has a name it's actually better practice here to use `def plus_one(x): return x + 1`, so you shouldn't see this form of lambda function too much in the wild. However, you are likely to see lambda functions being used with dataframes and other objects. For example, if you had a dataframe with a column of string called 'strings' that you want to change to “Title Case” and replace one phrase with another, you could use lambda functions to do that (there are better ways of doing this but this is useful as a simple example):",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\ndf = pd.DataFrame(\n data=[[\"hello my blah is Ada\"], [\"hElLo mY blah IS Adam\"]],\n columns=[\"strings\"],\n dtype=\"string\",\n)\ndf[\"strings\"].apply(lambda x: x.title().replace(\"Blah\", \"Name\"))",
"_____no_output_____"
]
],
[
[
"More complex lambda functions can be constructed, eg `lambda x, y, z: x + y + z`. One of the best use cases of lambdas is when you *don't* want to go to the trouble of declaring a function. For example, let's say you want to compose a series of functions and you want to specify those functions in a list, one after the other. Using functions alone, you'd have to define a new function for each operation. With lambdas, it would look like this (again, there are easier ways to do this operation, but we'll use simple functions to demonstrate the principle):",
"_____no_output_____"
]
],
[
[
"number = 1\nfor func in [lambda x: x + 1, lambda x: x * 2, lambda x: x ** 2]:\n number = func(number)\n print(number)",
"_____no_output_____"
]
],
[
[
"Note that people often use `x` by convention, but there's nothing to stop you writing `lambda horses: horses**2` (except the looks your co-authors will give you). If you want to learn more about lambda functions, check out these [short video tutorials](https://calmcode.io/lambda/introduction.html).\n\n## Splat and splatty-splat\n\nYou read those right, yes. These are also known as unpacking operators for, respectively, arguments and dictionaries. For instance, if I have a function that takes two arguments I can send variables to it in different ways:",
"_____no_output_____"
]
],
[
[
"def add(a, b):\n return a + b\n\n\nprint(add(5, 10))\n\nfunc_args = (6, 11)\n\nprint(add(*func_args))",
"_____no_output_____"
]
],
[
[
"The splat operator, `*`, unpacks the variable `func_args` into two different function arguments. Splatty-splat unpacks dictionaries into keyword arguments (aka kwargs):",
"_____no_output_____"
]
],
[
[
"def function_with_kwargs(a, x=0, y=0, z=0):\n return a + x + y + z\n\n\nprint(function_with_kwargs(5))\n\nkwargs = {\"x\": 3, \"y\": 4, \"z\": 5}\n\nprint(function_with_kwargs(5, **kwargs))",
"_____no_output_____"
]
],
[
[
"Perhaps most surprisingly of all, we can use the splat operator *in the definition of a function*. For example:",
"_____no_output_____"
]
],
[
[
"def sum_elements(*elements):\n return sum(*elements)\n\n\nnums = (1, 2, 3)\n\nprint(sum_elements(nums))\n\nmore_nums = (1, 2, 3, 4, 5)\n\nprint(sum_elements(more_nums))",
"_____no_output_____"
]
],
[
[
"To learn more about args and kwargs, check out these [short video tutorials](https://calmcode.io/args-kwargs/introduction.html).\n\n## Time\n\nLet's do a quick dive into how to deal with dates and times. This is only going to scratch the surface, but should give a sense of what's possible.\n\nThe built-in library that deals with datetimes is called `datetime`. Let's import it and ask it to give us a very precise account of the datetime (when the code is executed):",
"_____no_output_____"
]
],
[
[
"from datetime import datetime\n\nnow = datetime.now()\nprint(now)",
"_____no_output_____"
]
],
[
[
"You can pick out bits of the datetime that you need:",
"_____no_output_____"
]
],
[
[
"day = now.day\nmonth = now.month\nyear = now.year\nhour = now.hour\nminute = now.minute\nprint(f\"{year}/{month}/{day}, {hour}:{minute}\")",
"_____no_output_____"
]
],
[
[
"To add or subtract time to a datetime, use `timedelta`:",
"_____no_output_____"
]
],
[
[
"from datetime import timedelta\n\nnew_time = now + timedelta(days=365, hours=5)\nprint(new_time)",
"_____no_output_____"
]
],
[
[
"To take the difference of two dates:",
"_____no_output_____"
]
],
[
[
"from datetime import date\n\nnew_year = date(year=2022, month=1, day=1)\ntime_till_ny = new_year - date.today()\nprint(f\"{time_till_ny.days} days until New Year\")",
"_____no_output_____"
]
],
[
[
"Note that date and datetime are two different types of objects-a datetime includes information on the date and time, whereas a date does not.\n\n## Reading and writing files\n\nAlthough most applications in economics will probably use the **pandas** package to read and write tabular data, it's sometimes useful to know how to read and write arbitrary files using the built-in Python libraries too. To open a file\n\n```python\nopen('filename', mode)\n```\n\nwhere `mode` could be `r` for read, `a` for append, `w` for write, and `x` to create a file. Create a file called `text_example.txt` and write a single line in it, 'hello world'. To open the file and print the text, use:\n\n```python\nwith open('text_example.txt') as f:\n text_in = f.read()\n\nprint(text_in)\n```\n\n```python\n'hello world!\\n'\n```\n\n`\\n` is the new line character. Now let's try adding a line to the file:\n\n```python\nwith open('text_example.txt', 'a') as f:\n f.write('this is another line\\n')\n```\n\nWriting and reading files using the `with` command is a quick and convenient shorthand for the less concise open, action, close pattern. For example, the above example can also be written as:\n\n```python\nf = open('text_example.txt', 'a')\nf.write('this is another line\\n')\nf.close()\n```\n\nAlthough this short example shows opening and writing a text file, this approach can be used to edit a wide range of file extensions including .json, .xml, .csv, .tsv, and many more, including binary files in addition to plain text files.\n\n## Miscellaneous fun\n\nHere are some other bits of basic coding that might be useful. They really show why Python is such a delightful language.\n\nYou can use unicode characters for variables",
"_____no_output_____"
]
],
[
[
"α = 15\nβ = 30\n\nprint(α / β)",
"_____no_output_____"
]
],
[
[
"You can swap variables in a single assignment:",
"_____no_output_____"
]
],
[
[
"a = 10\nb = \"This is a string\"\n\na, b = b, a\n\nprint(a)",
"_____no_output_____"
]
],
[
[
"**iterools** offers counting, repeating, cycling, chaining, and slicing. Here's a cycling example that uses the `next` keyword to get the next iteraction:",
"_____no_output_____"
]
],
[
[
"from itertools import cycle\n\nlorrys = [\"red lorry\", \"yellow lorry\"]\nlorry_iter = cycle(lorrys)\n\nprint(next(lorry_iter))\nprint(next(lorry_iter))\nprint(next(lorry_iter))",
"_____no_output_____"
]
],
[
[
"**iterools** also offers products, combinations, combinations with replacement, and permutations. Here are the combinations of 'abc' of length 2:",
"_____no_output_____"
]
],
[
[
"from itertools import combinations\n\nprint(list(combinations(\"abc\", 2)))",
"_____no_output_____"
]
],
[
[
"Find out what the date is! (Can pass a timezone as an argument.)",
"_____no_output_____"
]
],
[
[
"from datetime import date\n\nprint(date.today())",
"_____no_output_____"
]
],
[
[
"Because functions are just objects, you can iterate over them just like any other object:",
"_____no_output_____"
]
],
[
[
"functions = [str.isdigit, str.islower, str.isupper]\n\nraw_str = \"asdfaa3fa\"\n\nfor str_func in functions:\n print(f\"Function name: {str_func.__name__}, value is:\")\n print(str_func(raw_str))",
"_____no_output_____"
]
],
[
[
"Functions can be defined recursively. For instance, the Fibonacci sequence is defined such that $ a_n = a_{n-1} + a_{n-2} $ for $ n>1 $.",
"_____no_output_____"
]
],
[
[
"def fibonacci(n):\n if n < 0:\n print(\"Please enter n>0\")\n return 0\n elif n <= 1:\n return n\n else:\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n\n[fibonacci(i) for i in range(10)]",
"_____no_output_____"
]
],
[
[
"This is just a taster of what can be done using 'batteries included' base Python; for more see the Advanced Coding Chapter.\n\n## Review\n\nIf you now understand a bit about what objects, types, operators, conditional statements, loops, functions, and imports are, and *how* to use them, you are well on your way to becoming a coder. What you've seen in this chapter are the building blocks and you need to know a bit about them. But bricks by themselves do not a house make. In subsequent chapters, we'll see how to combine the elements here to do productive analysis in economics.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e78b060f33165d7534c645f3fc7e8fe3ab8e35a6 | 81,480 | ipynb | Jupyter Notebook | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation | 5074229cd6fa33aa1884eded792be5c78ba9fb4c | [
"MIT"
] | 5 | 2021-05-01T17:20:08.000Z | 2021-05-03T09:13:28.000Z | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation | 5074229cd6fa33aa1884eded792be5c78ba9fb4c | [
"MIT"
] | 9 | 2021-02-14T11:45:44.000Z | 2021-06-07T09:37:33.000Z | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation | 5074229cd6fa33aa1884eded792be5c78ba9fb4c | [
"MIT"
] | 2 | 2021-02-14T10:31:21.000Z | 2022-03-29T12:37:52.000Z | 373.761468 | 58,936 | 0.929983 | [
[
[
"# Animate samples from a Gaussian distribution\n\nThis notebook demonstrates how to use the functionality in `ProbNum-Evaluation` to animate samples from a Gaussian distribution.",
"_____no_output_____"
]
],
[
[
"from probnumeval import visual\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(42)",
"_____no_output_____"
]
],
[
[
"As a toy example, let us consider animate a sample from a Gaussian process on 15 grid points with `N =5` frames. \nThe number of grid points determines the dimension of the underlying Normal distribution, therefore this variable is called `dim` in `ProbNum-Evaluation`.",
"_____no_output_____"
]
],
[
[
"dim = 15\nnum_frames = 5",
"_____no_output_____"
]
],
[
[
"For didactic reasons, let us set `endpoint` to `True`, which means that the final sample is the first sample.",
"_____no_output_____"
]
],
[
[
"states_gp = visual.animate_with_periodic_gp(dim, num_frames, endpoint=True)\nstates_sphere = visual.animate_with_great_circle_of_unitsphere(dim, num_frames, endpoint=True)",
"_____no_output_____"
]
],
[
[
"The output of the `animate_with*` function is a sequence of (pseudo-) samples from a standard Normal distribution.",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(dpi=150, ncols=num_frames, nrows=2, sharey=True, sharex=True, figsize=(num_frames*2, 2), constrained_layout=True)\n\nfor ax in axes.flatten():\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n \nfor state_sphere, state_gp, ax in zip(states_sphere, states_gp, axes.T):\n ax[0].vlines(np.arange(dim), ymin=np.minimum(0., state_gp), ymax=np.maximum(0., state_gp), linewidth=4, color=\"darksalmon\")\n ax[1].vlines(np.arange(dim), ymin=np.minimum(0., state_sphere), ymax=np.maximum(0., state_sphere), linewidth=4, color=\"darksalmon\")\n\naxes[0][0].set_ylabel('GP')\naxes[1][0].set_ylabel('Sphere')\nfor idx, ax in enumerate(axes.T):\n ax[0].set_title(f\"Frame {idx+1}\", fontsize=\"medium\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"These can be turned into samples from a multivariate Normal distribution $N(m, K)$ via the formula $u \\mapsto m + \\sqrt{K} u$",
"_____no_output_____"
]
],
[
[
"def k(s, t):\n return np.exp(-(s - t)**2/0.1)\n\nlocations = np.linspace(0, 1, dim)\ncov = k(locations[:, None], locations[None, :])\ncov_cholesky = np.linalg.cholesky(cov + 1e-12 * np.eye(dim))\n\n# From the \"right\", because the states have shape (N, d).\nsamples_sphere = states_sphere @ cov_cholesky.T\nsamples_gp = states_gp @ cov_cholesky.T\n",
"_____no_output_____"
]
],
[
[
"The resulting (pseudo-)samples \"move through the sample space\" in a continuous way for both, the periodic GP and the sphere. ",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(dpi=150, ncols=num_frames, nrows=2, sharey=True, sharex=True, figsize=(num_frames*2, 2), constrained_layout=True)\n\nfor ax in axes.flatten():\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n \nfor sample_sphere, sample_gp, ax in zip(samples_sphere, samples_gp, axes.T):\n ax[0].plot(locations, sample_gp, color=\"darksalmon\")\n ax[1].plot(locations, sample_sphere, color=\"darksalmon\")\n\naxes[0][0].set_ylabel('GP')\naxes[1][0].set_ylabel('Sphere')\nfor idx, ax in enumerate(axes.T):\n ax[0].set_title(f\"Frame {idx+1}\", fontsize=\"medium\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"The difference between the spherical version and the GP version is that path that each sample takes: for the spherical sample, the paths are a lot more symmetric than for the GP sample.",
"_____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"
],
[
"markdown"
]
] |
e78b165b7c13adcac5efc47de2ba2abe186ed4b1 | 19,872 | ipynb | Jupyter Notebook | Admissions.ipynb | frodre/UWAdmissions | dba81c3239a9ce3f33294ded0a0089a6df3b0997 | [
"CC0-1.0"
] | null | null | null | Admissions.ipynb | frodre/UWAdmissions | dba81c3239a9ce3f33294ded0a0089a6df3b0997 | [
"CC0-1.0"
] | null | null | null | Admissions.ipynb | frodre/UWAdmissions | dba81c3239a9ce3f33294ded0a0089a6df3b0997 | [
"CC0-1.0"
] | null | null | null | 36.596685 | 91 | 0.270733 | [
[
[
"import tabula",
"_____no_output_____"
],
[
"pdf = 'data/admissions05-by-ethnicity.pdf'",
"_____no_output_____"
],
[
"tabula.read_pdf(pdf, pages='1')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
e78b1da695f58af4c6cd25d7283436a2bc24051e | 8,036 | ipynb | Jupyter Notebook | 3 Custom components.ipynb | MichaMucha/odsc2019-voila-jupyter-web-app | adab4a28d76eca085490282cd090cc5b5b855d38 | [
"BSD-3-Clause"
] | 3 | 2019-11-13T08:52:51.000Z | 2019-11-22T18:54:46.000Z | 3 Custom components.ipynb | MichaMucha/odsc2019-voila-jupyter-web-app | adab4a28d76eca085490282cd090cc5b5b855d38 | [
"BSD-3-Clause"
] | null | null | null | 3 Custom components.ipynb | MichaMucha/odsc2019-voila-jupyter-web-app | adab4a28d76eca085490282cd090cc5b5b855d38 | [
"BSD-3-Clause"
] | 6 | 2019-11-18T14:59:14.000Z | 2019-11-20T18:19:46.000Z | 28.295775 | 97 | 0.426954 | [
[
[
"import ipyvuetify as v\nimport traitlets\nfrom traitlets import Int, Unicode, List, Dict, Bool",
"_____no_output_____"
]
],
[
[
"# URL text box\n\nhttps://vuetifyjs.com/en/components/text-fields",
"_____no_output_____"
]
],
[
[
"v.Col(cols=6, children=[\n v.TextField(outlined=True, class_='ma-2', label='URL', placeholder='https://')\n])",
"_____no_output_____"
],
[
"# home listing\n# https://www.rightmove.co.uk/property-for-sale/property-72921928.html\n\n# all listing data: property of Rightmove.co.uk",
"_____no_output_____"
],
[
"from download_listing import get_listing\nfrom pprint import pprint\n\nclass URLTextField(v.VuetifyTemplate):\n url = Unicode('').tag(sync=True, allow_null=True)\n loading = Bool(False).tag(sync=True)\n template = Unicode('''\n <v-text-field\n class=\"ma-2\"\n v-model=\"url\"\n :disabled=\"loading\"\n :loading=\"loading\"\n label=\"URL\"\n placeholder=\"https:// ...\"\n outlined\n clearable\n @change=get_properties(url)\n ></v-text-field>\n ''').tag(sync=True)\n \n def vue_get_properties(self, data):\n self.loading = True\n pprint(get_listing(data))\n self.loading = False\n\nURLTextField()",
"_____no_output_____"
]
],
[
[
"# Card\nhttps://vuetifyjs.com/en/components/cards",
"_____no_output_____"
]
],
[
[
"from download_listing import get_listing\n\nclass URLTextField(v.VuetifyTemplate):\n url = Unicode('').tag(sync=True, allow_null=True)\n loading = Bool(False).tag(sync=True)\n props = List(get_listing('')).tag(sync=True)\n show = Bool(False).tag(sync=True)\n price_string = Unicode('£1,000,000').tag(sync=True)\n template = Unicode('''\n <template>\n <v-col cols=\"8\">\n <v-text-field\n class=\"ma-2\"\n v-model=\"url\"\n :disabled=\"loading\"\n :loading=\"loading\"\n label=\"URL\"\n placeholder=\"https:// ...\"\n outlined\n clearable\n @change=get_properties(url)\n ></v-text-field>\n\n <v-card\n class=\"mx-auto\"\n max-width=\"444\"\n >\n <v-img\n v-bind:src=\"props[3]\"\"\n height=\"200px\"\n ></v-img>\n <v-card-title>\n {{ props[1] }}\n </v-card-title>\n <v-card-subtitle class=\"ma-4\">\n {{ price_string }} - {{ props[2] }}\n </v-card-subtitle>\n <v-card-actions>\n <v-btn text v-bind:href=\"url\">View on Rightmove</v-btn>\n <v-spacer></v-spacer>\n <v-btn\n icon\n @click=\"show = !show\"\n >\n <v-icon>{{ show ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>\n </v-btn>\n </v-card-actions>\n\n <v-expand-transition>\n <div v-show=\"show\">\n <v-divider></v-divider>\n <v-card-text>\n More information ...\n </v-card-text>\n </div>\n </v-expand-transition>\n </v-card>\n </v-col>\n </template>\n ''').tag(sync=True)\n \n def vue_get_properties(self, data):\n self.disabled = True\n self.loading = True\n self.props = list(get_listing(data))\n self.price_string = f'£{self.props[0]:,.0f}'\n self.disabled = False\n self.loading = False\n\nu = URLTextField()\nu",
"_____no_output_____"
]
],
[
[
"# Sparkline\nhttps://vuetifyjs.com/en/components/sparklines",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\n\nstrange_walk = np.random.beta(2, 3, 10) * 100 * np.random.normal(size=10)\nstrange_walk = pd.Series(strange_walk, name='Strange Walk').cumsum().round(2)\n\nstrange_walk.plot()",
"_____no_output_____"
],
[
"class SeriesSparkline(v.VuetifyTemplate):\n name = Unicode('').tag(sync=True)\n value = List([1,2,3]).tag(sync=True)\n template = Unicode(\"\"\"\n <template>\n <v-card\n class=\"mx-auto text-center\"\n color=\"green\"\n dark\n max-width=\"600\"\n >\n <v-card-text>\n <v-sheet color=\"rgba(0, 0, 0, .12)\">\n <v-sparkline\n :value=\"value\"\n color=\"rgba(255, 255, 255, .7)\"\n height=\"100\"\n padding=\"24\"\n stroke-linecap=\"round\"\n smooth\n >\n <template v-slot:label=\"item\">\n {{ item.value }}\n </template>\n </v-sparkline>\n </v-sheet>\n </v-card-text>\n\n <v-card-text>\n <div class=\"display-1 font-weight-thin\">{{ name }}</div>\n </v-card-text>\n </v-card>\n </template>\n \"\"\").tag(sync=True)\n \n def __init__(self, *args, \n data=pd.Series(),\n **kwargs):\n super().__init__(*args, **kwargs)\n self.name = data.name\n self.value = data.tolist()\n \ns = SeriesSparkline(data=strange_walk)\n\ns",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e78b1e53f17308d1f867b4281971f56ad1f98af4 | 64,488 | ipynb | Jupyter Notebook | Germeval2019-Task2.ipynb | rother/germeval2019 | 95c366124ae2e94a89d7732de6f53e2d7a6b0cb2 | [
"MIT"
] | null | null | null | Germeval2019-Task2.ipynb | rother/germeval2019 | 95c366124ae2e94a89d7732de6f53e2d7a6b0cb2 | [
"MIT"
] | null | null | null | Germeval2019-Task2.ipynb | rother/germeval2019 | 95c366124ae2e94a89d7732de6f53e2d7a6b0cb2 | [
"MIT"
] | null | null | null | 34.504013 | 326 | 0.470739 | [
[
[
"import pandas as pd, numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer",
"//anaconda/envs/python3/lib/python3.5/site-packages/sklearn/utils/fixes.py:313: FutureWarning: numpy not_equal will not check object identity in the future. The comparison did not return the same result as suggested by the identity (`is`)) and will change.\n _nan_object_mask = _nan_object_array != _nan_object_array\n"
],
[
"# Uncomment to get complete text output and not truncated text from data frames\npd.set_option('display.max_colwidth', -1)",
"_____no_output_____"
],
[
"# 2018 Files\n# Train: 5009 labeled\n# Test: 3532 labeled\n\n#file_head = 'germeval2018_training.csv' # 5009 labeled\n#file_testset = 'germeval2018_test.csv'\n\n# For submission\n#file_head = 'germeval2019_training_subtask12.csv' \nfile_train18 = 'germeval2018.training.txt' # 5009 labeled\nfile_test18 = 'germeval2018.test_.txt' # 3532 labeled\nfile_train19 = 'germeval2019_training_subtask12.txt' # 3995 labeled (removed one problem-tweet -> 3994)\nfile_list = [file_train18, file_test18, file_train19] # should be length 12.536\n\nfile_testset = 'germeval2019_Testdata_Subtask12.txt' # 3031 unlabeled",
"_____no_output_____"
],
[
"# Dev\n#df_tweets_tsh = pd.read_csv(file_head, delimiter='\\t', header=None)\n\n# Submission\ndf_tweets_tsh = pd.concat([pd.read_csv(f, delimiter='\\t', header=None) for f in file_list ])\ntest = pd.read_csv(file_testset, sep='\\r\\n', encoding='utf-8-sig', header=None, names=['text', 'label', 'fine'])",
"//anaconda/envs/python3/lib/python3.5/site-packages/ipykernel/__main__.py:6: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.\n"
],
[
"#f0 = pd.read_csv(file_testset, delimiter='\\t', header=None)\n#f1 = pd.read_csv(file_train18, delimiter='\\t', header=None)\n#f2 = pd.read_csv(file_test18, delimiter='\\t', header=None)\n#f3 = pd.read_csv(file_train19, delimiter='\\t', encoding='utf-8-sig', header=None)\n#len(f0), len(f1), len(f2), len(f3) # (3031, 5009, 3398, 3994)\n#f3[3780:3820] # +1 # 3780 ok -> 3820 falsch -> 3789/3790 = problem",
"_____no_output_____"
],
[
"len(df_tweets_tsh), len(test)",
"_____no_output_____"
]
],
[
[
"### Fix the Seed for Reproducible Results",
"_____no_output_____"
]
],
[
[
"import random\n\nseed = 23\n#torch.manual_seed(seed)\n#torch.cuda.manual_seed_all(seed)\nnp.random.seed(seed)\nrandom.seed(seed)",
"_____no_output_____"
],
[
"import re\ndef my_preprocess_text(in_text):\n username_re = re.compile(r'(^|[^@\\w])@(\\w{1,15})\\b') # @username\n url_re = re.compile(r'http\\S+') # urls\n in_text = re.sub('RT', '', in_text.rstrip()) # remove \"RT\"\n in_text = re.sub('\\:', '', in_text.rstrip()) # remove \":\"\n in_text = re.sub('\\'s', '', in_text.rstrip()) # remove \"'s\" -> try without this\n in_text = re.sub('#', '', in_text.rstrip()) # remove \"#\"\n in_text = re.sub(url_re, 'xx_url', in_text.rstrip()) # replace urls with xx_url\n return re.sub(username_re, ' xx_username', in_text.rstrip()).lstrip() # replace @username with xx_username\n # TODO: replace multiple usernames in a row ?! ",
"_____no_output_____"
],
[
"df_tweets_tsh[0] = df_tweets_tsh[0].apply(my_preprocess_text)\ndf_tweets_tsh.head()",
"_____no_output_____"
],
[
"test['text'] = test['text'].apply(my_preprocess_text)\ntest.head()",
"_____no_output_____"
],
[
"# Transform from the format text, binary, fine to\n# text, other, offense for binary classification\n# 1) Copy\ndf_tweets_tsh_new = df_tweets_tsh.copy()\n# 2) Remove 3rd column\ndel(df_tweets_tsh_new[2])\n# 3) Add 'other', 'offense' and use column names\ndf_tweets_tsh_new.columns = ['text', 'labels']\ndf_tweets_tsh_new['other'] = 0\ndf_tweets_tsh_new['offense'] = 0\n# 4) Fill 'other' and 'offense'\nmask_other = df_tweets_tsh_new.labels == 'OTHER'\nmask_offense = df_tweets_tsh_new.labels == 'OFFENSE'\n\ndf_tweets_tsh_new.loc[mask_other, 'other'] = 1\ndf_tweets_tsh_new.loc[mask_offense, 'offense'] = 1\ndf_tweets_tsh_new.head()",
"_____no_output_____"
],
[
"# Use all tweets for training\ntrain_df_tweets_tsh = df_tweets_tsh_new.copy()",
"_____no_output_____"
],
[
"train_df_tweets_tsh.head()",
"_____no_output_____"
],
[
"train_df_tweets_tsh.text[0]",
"_____no_output_____"
],
[
"lens = train_df_tweets_tsh.text.str.len()\nlens.mean(), lens.std(), lens.max()",
"_____no_output_____"
],
[
"lens.hist();",
"_____no_output_____"
],
[
"# long_tweets = train_df_tweets_tsh.text.str.len() > 500 # ok, da diverse tokens verwendet werden\n# train_df_tweets_tsh[long_tweets]",
"_____no_output_____"
],
[
"label_cols = ['other', 'offense']\ntrain_df_tweets_tsh['none'] = 1-train_df_tweets_tsh[label_cols].max(axis=1)\ntrain_df_tweets_tsh.describe()",
"_____no_output_____"
],
[
"# None-Tokenizer works surprisingly well :o\ndef tokenize_dummy(s):\n return s.split(' ')",
"_____no_output_____"
],
[
"#from fastai import *\n#from fastai.text import *\n\n#tokenizer_fastai = Tokenizer(lang='de', n_cpus=8)",
"_____no_output_____"
],
[
"LEMMATIZE = False\n\nimport spacy\nnlp = spacy.load('de')\n\ndef tokenize_spacy(corpus, lemma=LEMMATIZE):\n doc = nlp(corpus)\n if lemma:\n return list(str(x.lemma_) for x in doc) # lemma_ to get string instead of hash\n else:\n return list(str(x) for x in doc)",
"_____no_output_____"
],
[
"COMMENT = 'text'\n#n = train_df_tweets_tsh.shape[0]\nvec = TfidfVectorizer(analyzer='char', ngram_range=(3,6), tokenizer=tokenize_spacy,\n min_df=4, max_df=0.4, strip_accents='unicode', use_idf=True,\n smooth_idf=False, sublinear_tf=True, lowercase=True, binary=False)\ntrn_term_doc = vec.fit_transform(train_df_tweets_tsh[COMMENT])\ntest_term_doc = vec.transform(test[COMMENT])",
"_____no_output_____"
],
[
"trn_term_doc, test_term_doc",
"_____no_output_____"
],
[
"#vec.vocabulary_\n#vec",
"_____no_output_____"
],
[
"def pr(y_i, y):\n p = x[y==y_i].sum(0)\n return (p+1) / ((y==y_i).sum()+1)",
"_____no_output_____"
],
[
"x = trn_term_doc\ntest_x = test_term_doc",
"_____no_output_____"
],
[
"# other, offense\nclass_weight = {0: 2, 1: 1}\n\ndef get_mdl(y):\n y = y.values\n r = np.log(pr(1,y) / pr(0,y))\n m = LogisticRegression(C=14.0, dual=False, solver='saga', multi_class='auto', penalty='l2', \n class_weight='balanced', max_iter=500) # class_weight='balanced'\n x_nb = x.multiply(r)\n return m.fit(x_nb, y), r",
"_____no_output_____"
],
[
"preds = np.zeros((len(test), len(label_cols)))\n\nfor i, j in enumerate(label_cols):\n print('fit', j)\n m,r = get_mdl(train_df_tweets_tsh[j])\n preds[:,i] = m.predict_proba(test_x.multiply(r))[:,1]",
"fit other\nfit offense\n"
],
[
"# All predictions for the testset file\npredictions = pd.DataFrame(preds, columns = label_cols)\n#predictions",
"_____no_output_____"
],
[
"submission = test.copy()\ndel(submission['fine'])\nsubmission['text'][21]",
"_____no_output_____"
],
[
"submission = test.copy()\nsubmission['fine'] = 'OTHER' # dummy label for binary classification\nfor index,row in submission.iterrows():\n if( preds[index][1] >=0.485):\n #print('OFFENSE')\n submission['label'][index] = 'OFFENSE'\n else:\n #print('OTHER')\n submission['label'][index] = 'OTHER'\nsubmission.head()",
"//anaconda/envs/python3/lib/python3.5/site-packages/ipykernel/__main__.py:9: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n//anaconda/envs/python3/lib/python3.5/site-packages/pandas/core/indexing.py:189: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self._setitem_with_indexer(indexer, value)\n"
],
[
"# 1,1 ngrams -> 62.95 (C=40.0); lowercase=False\n# 1,2 ngrams -> 62.88 (C=40.0); lowercase=False\n\n# 1,1 ngrams -> 64.47 (C=1.0); lowercase=False\n\n# 1,1 ngrams -> 66.41 (C=1.0); lowercase=True\n# 1,2 ngrams -> 65.88 (C=1.0); lowercase=True\n# 1,3 ngrams -> 65.80 (C=1.0); lowercase=True\n# 1,4 ngrams -> 66.02 (C=1.0); lowercase=True\n# 1,5 ngrams -> 65.87 (C=1.0); lowercase=True\n# 1,6 ngrams -> 65.87 (C=1.0); lowercase=True\n\n# 1,4 ngrams -> 65.79 (C=1.0); lowercase=True; class_weight='balanced'\n\n# 3,3 ngrams -> 58.07\n\n# 1,4 ngrams -> 66.02 (C=1.0); lowercase=True; 4/1.0\n# 1,4 ngrams -> 64.07(C=1.0); lowercase=True; 2/0.8\n\n# 1,1 ngrams -> 66.41 (C=1.0); lowercase=True; 4/0.8\n# 1,1 ngrams -> 66.99 (C=4.0); lowercase=True; 4/0.8\n# 1,1 ngrams -> 67.69 (C=4.0); lowercase=True; 3/0.8\n# 1,1 ngrams -> 67.97 (C=4.0); lowercase=True; 2/0.8\n# 1,1 ngrams -> 61.61 (C=4.0); lowercase=True; 1/0.8\n\n# 1,1 ngrams -> 63.06 (C=8.0); lowercase=True; 2/0.8\n# 1,1 ngrams -> 66.26 (C=1.0); lowercase=True; 2/0.8\n# 1,1 ngrams -> 67.47 (C=2.0); lowercase=True; 2/0.8\n# 1,1 ngrams -> 68.05 (C=3.0); lowercase=True; 2/0.8*\n\n# 1,1 ngrams -> 61.88 (C=3.0); lowercase=True; 3/0.8\n# 1,1 ngrams -> 68.00 (C=3.5); lowercase=True; 2/0.8\n\n# 1,2 ngrams -> 66.16 (C=3.0); lowercase=True; 2/0.8\n# 1,3 ngrams -> 65.93 (C=3.0); lowercase=True; 2/0.8\n# 1,4 ngrams -> 65.95 (C=3.0); lowercase=True; 2/0.8\n\n# 2,3 ngrams -> 59.88 (C=3.0); lowercase=True; 2/0.8\n\n# character level\n# 3,6 ngrams -> 70.71 (c=4.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 69.03 (c=4.0); lowercase=False; 4/1.0\n\n# 3,6 ngrams -> 71.03 (c=8.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 69.17 (c=2.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 70.79 (c=6.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.56 (c=16.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.11 (c=32.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.04 (c=24.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.29 (c=20.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.39 (c=18.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.38 (c=12.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.71* (c=14.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.57 (c=15.0); lowercase=True; 4/1.0\n# 3,6 ngrams -> 71.45 (c=17.0); lowercase=True; 4/1.0\n\n# 3,6 ngrams -> 71.14 (c=14.0); lowercase=True; 5/1.0\n# 3,6 ngrams -> 71.23 (c=14.0); lowercase=True; 3/1.0\n# 3,6 ngrams -> 71.21 (c=14.0); lowercase=True; 3/0.5\n# 3,6 ngrams -> 71.57 (c=14.0); lowercase=True; 4/0.5\n\n# 3,6 ngrams -> 69.32 (c=14.0); lowercase=True; 4/1.0; l1 regularization\n\n# 3,10 ngrams -> 70.89 (c=14.0); lowercase=True; 4/1.0\n# 3,8 ngrams -> 70.92 (c=14.0); lowercase=True; 4/1.0\n# 2,6 ngrams -> 71.07 (c=14.0); lowercase=True; 4/1.0\n# 2,5 ngrams -> 71.15 (c=14.0); lowercase=True; 4/1.0\n# 4,7 ngrams -> 71.34 (c=14.0); lowercase=True; 4/1.0\n# 5,8 ngrams -> 69.84 (c=14.0); lowercase=True; 4/1.0\n\n# 3,6 ngrams -> 71.61 (c=14.0); lowercase=True; 4/0.4\n\n# 1,10 ngrams -> 70.70\n# 1,6 ngrams -> 70.99\n# 1,40 ngrams -> 69.71\n\n# Class labels (strangely balanced works best)\n# 2/1: 70.3\n# 1/2: 71.95\n# balanced: 72.28*\n\n# Cutoff (note that this should be 0.5)\n# 0.5 -> 72.28\n# 0.51 -> 72.14\n# 0.55 -> 71.76\n# 0.6 -> 71.59\n# 0.4 -> 71.20\n\n# 0.495 -> 72.47\n# 0.49 -> 72.47\n# 0.485 -> 72.62* (lemmatized: 72.58)\n# 0.48 -> 72.44\n\n# 0.47 -> 72.24\n\nsubmission.to_csv('naive.csv', sep='\\t', line_terminator='\\n', header=None, index=False, encoding='utf-8-sig')",
"_____no_output_____"
]
],
[
[
"### Fine grained task",
"_____no_output_____"
]
],
[
[
"# Transform from the format text, binary, fine to\n# text, 'other', 'offense', 'abuse', 'insult', 'profanity' for finegrained classification\n# 1) Copy\n#df_tweets_tsh_fine = pd.read_csv(file_head, delimiter='\\t', header=None)\ndf_tweets_tsh_fine = pd.concat([pd.read_csv(f, delimiter='\\t', header=None) for f in file_list ])\n\n# 2) Remove 2rd column\ndel(df_tweets_tsh_fine[1])\n# 3) Add 'other', 'offense', 'abuse', 'insult', 'profanity' and use column names\ndf_tweets_tsh_fine.columns = ['text', 'labels']\ndf_tweets_tsh_fine['other'] = 0\ndf_tweets_tsh_fine['offense'] = 0\ndf_tweets_tsh_fine['abuse'] = 0\ndf_tweets_tsh_fine['insult'] = 0\ndf_tweets_tsh_fine['profanity'] = 0\n\n# 4) Fill 'other' and 'offense'\nmask_other = df_tweets_tsh_fine.labels == 'OTHER'\nmask_offense = df_tweets_tsh_fine.labels == 'OFFENSE'\nmask_abuse = df_tweets_tsh_fine.labels == 'ABUSE'\nmask_insult = df_tweets_tsh_fine.labels == 'INSULT'\nmask_profanity = df_tweets_tsh_fine.labels == 'PROFANITY'\n\ndf_tweets_tsh_fine.loc[mask_other, 'other'] = 1\ndf_tweets_tsh_fine.loc[mask_offense, 'offense'] = 1\ndf_tweets_tsh_fine.loc[mask_abuse, 'abuse'] = 1\ndf_tweets_tsh_fine.loc[mask_insult, 'insult'] = 1\ndf_tweets_tsh_fine.loc[mask_profanity, 'profanity'] = 1\n\ndf_tweets_tsh_fine.head()",
"_____no_output_____"
],
[
"train_df_tweets_tsh_fine = df_tweets_tsh_fine.copy()",
"_____no_output_____"
],
[
"train_df_tweets_tsh_fine.head()",
"_____no_output_____"
],
[
"label_cols_fine = ['other', 'abuse', 'insult', 'profanity']\ntrain_df_tweets_tsh_fine['none'] = 1-train_df_tweets_tsh_fine[label_cols_fine].max(axis=1)\ntrain_df_tweets_tsh_fine.describe()",
"_____no_output_____"
],
[
"COMMENT = 'text'\n#n = train_df_tweets_tsh_fine.shape[0]\nvec = TfidfVectorizer(analyzer='char', ngram_range=(3,6), tokenizer=tokenize_spacy,\n min_df=4, max_df=1.0, strip_accents='unicode', use_idf=True,\n smooth_idf=False, sublinear_tf=True, lowercase=True, binary=False)\ntrn_term_doc_fine = vec.fit_transform(train_df_tweets_tsh_fine[COMMENT])\ntest_term_doc_fine = vec.transform(test[COMMENT])",
"_____no_output_____"
],
[
"trn_term_doc_fine, test_term_doc_fine",
"_____no_output_____"
],
[
"x = trn_term_doc_fine\ntest_x = test_term_doc_fine",
"_____no_output_____"
],
[
"# other, abuse, insult, profanity\n# class_weight = {}\n\ndef get_mdl(y):\n y = y.values\n r = np.log(pr(1,y) / pr(0,y))\n m = LogisticRegression(C=14.0, dual=False, solver='saga', multi_class='auto', penalty='l2', max_iter=500, class_weight='balanced') # class_weight='balanced'\n x_nb = x.multiply(r)\n return m.fit(x_nb, y), r",
"_____no_output_____"
],
[
"preds = np.zeros((len(test), len(label_cols_fine)))\n\nfor i, j in enumerate(label_cols_fine):\n print('fit', j)\n m,r = get_mdl(train_df_tweets_tsh_fine[j])\n preds[:,i] = m.predict_proba(test_x.multiply(r))[:,1]",
"fit other\nfit abuse\nfit insult\nfit profanity\n"
],
[
"# All predictions for the testset file\npredictions = pd.DataFrame(preds, columns = label_cols_fine)\n#predictions",
"_____no_output_____"
],
[
"submission = test.copy()\n#del(submission['fine'])\nsubmission['text'][21]",
"_____no_output_____"
],
[
"def max_from_labels(pred, labels):\n return labels[np.argmax(pred)].upper()",
"_____no_output_____"
],
[
"#submission['label'] = 'OTHER' # dummy label for fine classification\nfor index,row in submission.iterrows():\n submission['label'][index] = max_from_labels(preds[index], label_cols_fine)\n submission['fine'][index] = max_from_labels(preds[index], label_cols_fine)",
"//anaconda/envs/python3/lib/python3.5/site-packages/ipykernel/__main__.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n app.launch_new_instance()\n//anaconda/envs/python3/lib/python3.5/site-packages/pandas/core/indexing.py:189: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self._setitem_with_indexer(indexer, value)\n//anaconda/envs/python3/lib/python3.5/site-packages/ipykernel/__main__.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n"
],
[
"# 3,6c -> 45.67\n# 3,7c -> 43.8\n# 3,6c -> 44.41 (1/2 classes)\n# 3,6c -> 45.71* (2/1 classes)\n# 3,6c -> 45.43 (3/1 classes)\n\n# Balanced\n# 4/1.0; 3,6c -> 45.72* (balanced) -> same lemmatized\nsubmission.to_csv('naive2.csv', sep='\\t', line_terminator='\\n', header=None, index=False, encoding='utf-8-sig')",
"_____no_output_____"
],
[
"#for index,row in submission.iterrows():\n# print(preds[index])",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.