hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
list
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
list
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
list
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
list
cell_types
list
cell_type_groups
list
cb09664ca14775788d924d54dcb552e1009e7eeb
47,924
ipynb
Jupyter Notebook
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
a0aaec13785266fd7b5f476796b47b6fb94f7f0a
[ "MIT" ]
null
null
null
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
a0aaec13785266fd7b5f476796b47b6fb94f7f0a
[ "MIT" ]
null
null
null
Lesson_2_Introduction/1.9 Putting It All Together.ipynb
ReemAlattas/DSND
a0aaec13785266fd7b5f476796b47b6fb94f7f0a
[ "MIT" ]
null
null
null
55.920653
15,064
0.630728
[ [ [ "#### Putting It All Together\n\nAs you might have guessed from the last notebook, using all of the variables was allowing you to drastically overfit the training data. This was great for looking good in terms of your Rsquared on these points. However, this was not great in terms of how well you were able to predict on the test data.\n\nWe will start where we left off in the last notebook. First read in the dataset.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, mean_squared_error\nimport AllTogether as t\nimport seaborn as sns\n%matplotlib inline\n\ndf = pd.read_csv('./survey_results_public.csv')\ndf.head()", "_____no_output_____" ] ], [ [ "#### Question 1\n\n**1.** To begin fill in the format function below with the correct variable. Notice each **{ }** holds a space where one of your variables will be added to the string. This will give you something to do while the the function does all the steps you did throughout this lesson.", "_____no_output_____" ] ], [ [ "a = 'test_score'\nb = 'train_score'\nc = 'linear model (lm_model)'\nd = 'X_train and y_train'\ne = 'X_test'\nf = 'y_test'\ng = 'train and test data sets'\nh = 'overfitting'\n\nq1_piat = '''In order to understand how well our {} fit the dataset, \n we first needed to split our data into {}. \n Then we were able to fit our {} on the {}. \n We could then predict using our {} by providing \n the linear model the {} for it to make predictions. \n These predictions were for {}. \n\n By looking at the {}, it looked like we were doing awesome because \n it was 1! However, looking at the {} suggested our model was not \n extending well. The purpose of this notebook will be to see how \n well we can get our model to extend to new data.\n \n This problem where our data fits the training data well, but does\n not perform well on test data is commonly known as \n {}.'''.format(c, g, c, d, c, e, f, b, a, h)\n\nprint(q1_piat)", "In order to understand how well our linear model (lm_model) fit the dataset, \n we first needed to split our data into train and test data sets. \n Then we were able to fit our linear model (lm_model) on the X_train and y_train. \n We could then predict using our linear model (lm_model) by providing \n the linear model the X_test for it to make predictions. \n These predictions were for y_test. \n\n By looking at the train_score, it looked like we were doing awesome because \n it was 1! However, looking at the test_score suggested our model was not \n extending well. The purpose of this notebook will be to see how \n well we can get our model to extend to new data.\n \n This problem where our data fits the training data well, but does\n not perform well on test data is commonly known as \n overfitting.\n" ], [ "# Print the solution order of the letters in the format\nt.q1_piat_answer()", "This one is tricky - here is the order of the letters for the solution we had in mind:\n c, g, c, d, c, e, f, b, a, h\n" ] ], [ [ "#### Question 2\n\n**2.** Now, we need to improve the model . Use the dictionary below to provide the true statements about improving **this model**. **Also consider each statement as a stand alone**. Though, it might be a good idea after other steps, which would you consider a useful **next step**?", "_____no_output_____" ] ], [ [ "a = 'yes'\nb = 'no'\n\nq2_piat = {'add interactions, quadratics, cubics, and other higher order terms': b, \n 'fit the model many times with different rows, then average the responses': a,\n 'subset the features used for fitting the model each time': a,\n 'this model is hopeless, we should start over': b}", "_____no_output_____" ], [ "#Check your solution\nt.q2_piat_check(q2_piat)", "Nice job! That looks right! These two techniques are really common in Machine Learning algorithms to combat overfitting. Though the first technique could be useful, it is not likely to help us right away with our current model. These additional features would likely continue to worsen the nature of overfitting we are seeing here.\n" ] ], [ [ "##### Question 3\n\n**3.** Before we get too far along, follow the steps in the function below to create the X (explanatory matrix) and y (response vector) to be used in the model. If your solution is correct, you should see a plot similar to the one shown in the Screencast.", "_____no_output_____" ] ], [ [ "def clean_data(df):\n '''\n INPUT\n df - pandas dataframe \n \n OUTPUT\n X - A matrix holding all of the variables you want to consider when predicting the response\n y - the corresponding response vector\n \n This function cleans df using the following steps to produce X and y:\n 1. Drop all the rows with no salaries\n 2. Create X as all the columns that are not the Salary column\n 3. Create y as the Salary column\n 4. Drop the Salary, Respondent, and the ExpectedSalary columns from X\n 5. For each numeric variable in X, fill the column with the mean value of the column.\n 6. Create dummy columns for all the categorical variables in X, drop the original columns\n '''\n # Drop rows with missing salary values\n df = df.dropna(subset=['Salary'], axis=0)\n y = df['Salary']\n \n #Drop respondent and expected salary columns\n df = df.drop(['Respondent', 'ExpectedSalary', 'Salary'], axis=1)\n \n # Fill numeric columns with the mean\n num_vars = df.select_dtypes(include=['float', 'int']).columns\n for col in num_vars:\n df[col].fillna((df[col].mean()), inplace=True)\n \n # Dummy the categorical variables\n cat_vars = df.select_dtypes(include=['object']).copy().columns\n for var in cat_vars:\n # for each cat add dummy var, drop original column\n df = pd.concat([df.drop(var, axis=1), pd.get_dummies(df[var], prefix=var, prefix_sep='_', drop_first=True)], axis=1)\n \n X = df\n return X, y\n \n#Use the function to create X and y\nX, y = clean_data(df) ", "_____no_output_____" ], [ "#cutoffs here pertains to the number of missing values allowed in the used columns.\n#Therefore, lower values for the cutoff provides more predictors in the model.\ncutoffs = [5000, 3500, 2500, 1000, 100, 50, 30, 25]\n\nr2_scores_test, r2_scores_train, lm_model, X_train, X_test, y_train, y_test = t.find_optimal_lm_mod(X, y, cutoffs)", "_____no_output_____" ] ], [ [ "#### Question 4\n\n**4.** Use the output and above plot to correctly fill in the keys of the **q4_piat** dictionary with the correct variable. Notice that only the optimal model results are given back in the above - they are stored in **lm_model**, **X_train**, **X_test**, **y_train**, and **y_test**. If more than one answer holds, provide a tuple holding all the correct variables in the order of first variable alphabetically to last variable alphabetically.", "_____no_output_____" ] ], [ [ "print(X_train.shape[1]) #Number of columns\nprint(r2_scores_test[np.argmax(r2_scores_test)]) # The model we should implement test_r2\nprint(r2_scores_train[np.argmax(r2_scores_test)]) # The model we should implement train_r2\n", "690\n0.684855663033\n0.787915206279\n" ], [ "a = 'we would likely have a better rsquared for the test data.'\nb = 1000\nc = 872\nd = 0.69\ne = 0.82\nf = 0.88\ng = 0.72\nh = 'we would likely have a better rsquared for the training data.'\n\nq4_piat = {'The optimal number of features based on the results is': c, \n 'The model we should implement in practice has a train rsquared of': e, \n 'The model we should implement in practice has a test rsquared of': d,\n 'If we were to allow the number of features to continue to increase': h\n}", "_____no_output_____" ], [ "#Check against your solution\nt.q4_piat_check(q4_piat)", "Nice job! That looks right! We can see that the model we should impement was the 6th model using 1088 features. It is the model that has the best test rsquared value.\n" ] ], [ [ "#### Question 5\n\n**5.** The default penalty on coefficients using linear regression in sklearn is a ridge (also known as an L2) penalty. Because of this penalty, and that all the variables were normalized, we can look at the size of the coefficients in the model as an indication of the impact of each variable on the salary. The larger the coefficient, the larger the expected impact on salary. \n\nUse the space below to take a look at the coefficients. Then use the results to provide the **True** or **False** statements based on the data.", "_____no_output_____" ] ], [ [ "def coef_weights(coefficients, X_train):\n '''\n INPUT:\n coefficients - the coefficients of the linear model \n X_train - the training data, so the column names can be used\n OUTPUT:\n coefs_df - a dataframe holding the coefficient, estimate, and abs(estimate)\n \n Provides a dataframe that can be used to understand the most influential coefficients\n in a linear model by providing the coefficient estimates along with the name of the \n variable attached to the coefficient.\n '''\n coefs_df = pd.DataFrame()\n coefs_df['est_int'] = X_train.columns\n coefs_df['coefs'] = lm_model.coef_\n coefs_df['abs_coefs'] = np.abs(lm_model.coef_)\n coefs_df = coefs_df.sort_values('abs_coefs', ascending=False)\n return coefs_df\n\n#Use the function\ncoef_df = coef_weights(lm_model.coef_, X_train)\n\n#A quick look at the top results\ncoef_df.head(20)", "_____no_output_____" ], [ "a = True\nb = False\n\n#According to the data...\nq5_piat = {'Country appears to be one of the top indicators for salary': a,\n 'Gender appears to be one of the indicators for salary': b, \n 'How long an individual has been programming appears to be one of the top indicators for salary': a,\n 'The longer an individual has been programming the more they are likely to earn': b}", "_____no_output_____" ], [ "t.q5_piat_check(q5_piat)", "Nice job! That looks right! The country and years of experience both seem to have a significant impact on the salary of individuals.\n" ] ], [ [ "#### Congrats of some kind\n\nCongrats! Hopefully this was a great review, or an eye opening experience about how to put the steps together for an analysis. List the steps. In the next lesson, you will look at how take this and show it off to others so they can act on it.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
cb0979df1329f84a5d36814d816ff1c529ad7fc9
48,129
ipynb
Jupyter Notebook
src/exploring_s&p_500/LSTM_approach_Pytorch.ipynb
angelomenezes/Data_Science_for_Finance
20d9771fea44aab6c177975bf9db79d0bc7dbc86
[ "MIT" ]
2
2021-09-07T03:11:08.000Z
2021-11-10T16:32:19.000Z
src/exploring_s&p_500/LSTM_approach_Pytorch.ipynb
angelomenezes/Data_Science_for_Finance
20d9771fea44aab6c177975bf9db79d0bc7dbc86
[ "MIT" ]
3
2019-05-28T06:05:27.000Z
2019-05-28T06:17:39.000Z
src/exploring_s&p_500/LSTM_approach_Pytorch.ipynb
angelomenezes/Data_Science_for_Finance
20d9771fea44aab6c177975bf9db79d0bc7dbc86
[ "MIT" ]
1
2020-03-10T07:36:36.000Z
2020-03-10T07:36:36.000Z
48.615152
17,556
0.635376
[ [ [ "import pandas as pd #pandas does things with matrixes\nimport numpy as np #used for sorting a matrix\nimport matplotlib.pyplot as plt #matplotlib is used for plotting data\nimport matplotlib.ticker as ticker #used for changing tick spacing\nimport datetime as dt #used for dates\nimport matplotlib.dates as mdates #used for dates, in a different way\nimport os #used for changes of directory\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.preprocessing import MinMaxScaler # It scales the data between 0 and 1\nimport sys\nsys.path.append('../')\nfrom utils import simple_plot, simple_plot_by_date, hit_count\n\nimport torch\nimport torch.nn as nn\nfrom torchvision.transforms import ToTensor\nfrom torch.utils.data.dataloader import DataLoader\nimport torch.nn.functional as F", "_____no_output_____" ], [ "# Device configuration\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')", "_____no_output_____" ], [ "dataset_1yr = pd.read_csv(\"../../Data/all_stocks_5yr.csv\")\ndataset_1yr.head()\n\n# Changing the date column to the datetime format (best format to work with time series)\ndataset_1yr['Date'] = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dataset_1yr['Date']]\n\ndataset_1yr.head()", "_____no_output_____" ], [ "# Assigning a mid price column with the mean of the Highest and Lowest values\n\ndataset_1yr['Mid'] = (dataset_1yr['High'] + dataset_1yr['Low'])/2\ndataset_1yr.head()", "_____no_output_____" ], [ "# Getting rid of null columns\n\nmissing_data = pd.DataFrame(dataset_1yr.isnull().sum()).T\nprint(missing_data)\n\nfor index, column in enumerate(missing_data.columns):\n if missing_data.loc[0][index] != 0:\n dataset_1yr = dataset_1yr.drop(dataset_1yr.loc[dataset_1yr[column].isnull()].index)\n \nmissing_data = pd.DataFrame(dataset_1yr.isnull().sum()).T\nprint(missing_data)", " Date Open High Low Close Volume Name Mid\n0 0 384 208 227 0 406 0 358\n Date Open High Low Close Volume Name Mid\n0 0 0 0 0 0 0 0 0\n" ], [ "# Let's analyze 3M stocks a bit deeper\n\nMMM_stocks = dataset_1yr[dataset_1yr['Name'] == 'MMM']\n\nMMM_stocks.head()", "_____no_output_____" ], [ "# Creating a percent change column related to the closing price\n\npercent_change_closing_price = MMM_stocks['Close'].pct_change()\npercent_change_closing_price.fillna(0, inplace=True)\nMMM_stocks['PC_change'] = pd.DataFrame(percent_change_closing_price)\n\n# As we want to predict the closing price, let's add the target column as the close price shifted by 1\n\nMMM_stocks['Target'] = MMM_stocks['Close'].shift(-1)\n\nMMM_stocks = MMM_stocks.drop(0, axis = 0)\nMMM_stocks = MMM_stocks.drop('Name', axis = 1)\nMMM_stocks = MMM_stocks.drop('Date', axis = 1)\n\nMMM_stocks.head()", "_____no_output_____" ], [ "# Separating as Training and Testing\n\ntrain_data = MMM_stocks.iloc[:1000,:]\ntrain_data = train_data.drop('Target',axis=1)\ntest_data = MMM_stocks.iloc[1000:,:]\ntest_data = test_data.drop('Target',axis=1)\n\ny_train = MMM_stocks.iloc[:1000,-1]\ny_test = MMM_stocks.iloc[1000:,-1]\n\nprint(train_data.shape)\nprint(test_data.shape)\nprint(y_train.shape)\nprint(y_test.shape)", "(1000, 7)\n(256, 7)\n(1000,)\n(256,)\n" ], [ "# Data still needs to be scaled.\n\n\n# Training Data\nscaler_closing_price = MinMaxScaler(feature_range = (0, 1))\nscaler_closing_price.fit(np.array(train_data['Close']).reshape(-1,1))\n\nscaler_dataframe = MinMaxScaler(feature_range = (0, 1))\ntraining_set_scaled = pd.DataFrame(scaler_dataframe.fit_transform(train_data))\ntraining_set_scaled.head()\n\ny_set_scaled = pd.DataFrame(scaler_closing_price.transform(np.array(y_train).reshape(-1,1)))\n\n# Testing Data\ntesting_set_scaled = pd.DataFrame(scaler_dataframe.fit_transform(test_data))\n\ny_test_scaled = pd.DataFrame(scaler_closing_price.transform(np.array(y_test).reshape(-1,1)))", "_____no_output_____" ], [ "# Preparing data for the experiment with an univariate model \n# Getting Closing Price and arranging lists for training/testing based on the sequence\n\ndef split_sequence(sequence, n_steps):\n X, y = list(), list()\n for i in range(len(sequence)):\n # find the end of this pattern\n end_ix = i + n_steps\n # check if we are beyond the sequence\n if end_ix > len(sequence)-1:\n break\n # gather input and output parts of the pattern\n seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]\n X.append(seq_x)\n y.append(seq_y) \n return np.array(X), np.array(y)\n\ntrain_univariate, y_train_univariate = split_sequence(training_set_scaled[3], 5)\ntest_univariate, y_test_univariate = split_sequence(testing_set_scaled[3], 5)", "_____no_output_____" ], [ "def reshape_pandas_data(x, y, input_size):\n x = torch.from_numpy(np.array(x)).type(torch.Tensor).view([-1, input_size])\n y = torch.from_numpy(np.array(y)).type(torch.Tensor).view(-1)\n return (x, y)", "_____no_output_____" ], [ "train_tensor, target = reshape_pandas_data(train_univariate, y_train_univariate, train_univariate.shape[1])\n#train_tensor, target = reshape_pandas_data(train_data, y_train, train_data.shape[1])\nprint(train_tensor.shape)\n\n#train_tensor = DataLoader(train_tensor, batch_size)", "torch.Size([995, 5])\n" ], [ "# Creating a device data loader in order to pass batches to device memory\n\ndef to_device(data, device):\n ''' Move tensor to chosen device'''\n if isinstance(data, (list,tuple)):\n return [to_device(x, device) for x in data]\n return data.to(device, non_blocking=True)\n\nclass DeviceDataLoader():\n \n def __init__(self, data, device):\n self.data = data\n self.device = device\n \n def __iter__(self):\n \"Yield a batch of data after moving it to device\"\n for item in self.data:\n yield to_device(item, self.device)\n\n def __len__(self):\n \"Number of batches\"\n return len(self.data)", "_____no_output_____" ], [ "train_tensor = DeviceDataLoader(train_tensor, device)\n#target = DeviceDataLoader(target, device)", "_____no_output_____" ], [ "# Recurrent neural network (many-to-one)\nclass RNN(nn.Module):\n def __init__(self, input_size, hidden_size, num_layers=1, num_classes=1):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)\n self.fc = nn.Linear(hidden_size, num_classes)\n self.input_size = input_size\n \n def forward(self, x):\n \n print(x)\n #x = x.reshape(-1, len(x), self.input_size)\n \n # Set initial hidden and cell states \n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)\n \n # Forward propagate LSTM\n out, self.hidden = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size)\n \n # Decode the hidden state of the last time step\n out = self.fc(out[:, -1, :])\n return out", "_____no_output_____" ], [ "# Recurrent neural network (many-to-one)\nclass RNN(nn.Module):\n def __init__(self, input_size, hidden_size, num_layers=1, num_classes=1):\n super(RNN, self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)\n self.fc = nn.Linear(hidden_size, num_classes)\n self.input_size = input_size\n \n def forward(self, x):\n \n #x = x.reshape(-1, len(x), self.input_size)\n \n # Set initial hidden and cell states \n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)\n \n # Forward propagate LSTM\n out, self.hidden = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size)\n \n # Decode the hidden state of the last time step\n out = self.fc(out[:, -1, :])\n return out", "_____no_output_____" ], [ "# Hyper-parameters\nepochs = 50\ninput_size = 5\nhidden_size = 128\nnum_layers = 2\nnum_classes = 1\nlearning_rate = 1e-3\nmodel = RNN(input_size, hidden_size, num_layers, num_classes).to(device)\n\nfor t in model.parameters():\n print(t.shape)", "torch.Size([512, 5])\ntorch.Size([512, 128])\ntorch.Size([512])\ntorch.Size([512])\ntorch.Size([512, 128])\ntorch.Size([512, 128])\ntorch.Size([512])\ntorch.Size([512])\ntorch.Size([1, 128])\ntorch.Size([1])\n" ], [ "for index, tensor in enumerate(train_tensor):\n y_pred = model(tensor)\n loss += loss_fn(y_pred, target[index])\n\nloss", "_____no_output_____" ], [ "hist = []\nloss_fn = torch.nn.MSELoss(size_average=False)\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\nfor epoch in range(epochs):\n\n #model.zero_grad()\n \n loss = []\n \n for tensor, real_output in train_tensor, target:\n y_pred = model(tensor)\n loss += loss_fn(y_pred, real_output)\n \n y_pred = model(train_tensor)\n loss += loss_fn(y_pred, target.to(device))\n\n hist.append(loss.mean())\n\n loss.backward()\n\n optimizer.step()\n \n optimizer.zero_grad()\n \n #if epoch+1 % 10 == 0: \n print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))", "_____no_output_____" ], [ "plt.plot(hist, '-x')\nplt.xlabel('epoch')\nplt.ylabel('accuracy')\nplt.title('Accuracy vs Epoch');", "_____no_output_____" ], [ "class TimeSeriesRNNModel(nn.Module):\n def __init__(self):\n super(TimeSeriesRNNModel, self).__init__()\n self.lstm1 = nn.LSTM(input_size=5, hidden_size=50, num_layers=1)\n self.lstm2 = nn.LSTM(input_size=50, hidden_size=25, num_layers=1)\n self.linear = nn.Linear(in_features=25, out_features=1)\n\n self.h_t1 = None\n self.c_t1 = None\n self.h_t2 = None\n self.c_t2 = None\n\n def initialize_model(self, input_data):\n self.h_t1 = torch.rand(1, 1, 50, dtype=torch.double).to(device) \n self.c_t1 = torch.rand(1, 1, 50, dtype=torch.double).to(device) \n self.h_t2 = torch.rand(1, 1, 25, dtype=torch.double).to(device) \n self.c_t2 = torch.rand(1, 1, 25, dtype=torch.double).to(device) \n\n def forward(self, input_data):\n outputs = []\n self.initialize_model(input_data)\n \n input_data = input_data.reshape(-1, len(input_data), 5)\n\n output = None\n \n for _, input_t in enumerate(input_data.chunk(input_data.size(1), dim=1)):\n self.h_t1, self.c_t1 = self.lstm1(input_t, (self.h_t1, self.c_t1))\n self.h_t2, self.c_t2 = self.lstm2(self.h_t1, (self.h_t2, self.c_t2))\n output = self.linear(self.h_t2)\n outputs += [output]\n\n outputs = torch.stack(outputs, 1).squeeze(2)\n return outputs", "_____no_output_____" ], [ "# Hyper-parameters\nepochs = 20\nlearning_rate = 1e-3\nmodel = TimeSeriesRNNModel().to(device)\n\nfor t in model.parameters():\n print(t.shape)", "_____no_output_____" ], [ "hist = []\nloss_fn = torch.nn.MSELoss(size_average=False)\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\nfor epoch in range(epochs):\n\n #model.zero_grad()\n\n y_pred = model(train_tensor.to(device))\n\n loss = loss_fn(y_pred, target.to(device))\n \n hist.append(loss.item())\n\n loss.backward()\n\n optimizer.step()\n \n optimizer.zero_grad()\n \n #if epoch+1 % 10 == 0: \n print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))", "_____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" ] ]
cb097b95b91ece95b4d6d61c31365db3b617fc88
23,221
ipynb
Jupyter Notebook
SRC/Main_Notebook.ipynb
Geno16/Rural_Development_Study_No2
9502c65ac38b8c8e703d959a98b4f3d096f26899
[ "MIT" ]
null
null
null
SRC/Main_Notebook.ipynb
Geno16/Rural_Development_Study_No2
9502c65ac38b8c8e703d959a98b4f3d096f26899
[ "MIT" ]
null
null
null
SRC/Main_Notebook.ipynb
Geno16/Rural_Development_Study_No2
9502c65ac38b8c8e703d959a98b4f3d096f26899
[ "MIT" ]
null
null
null
41.915162
191
0.549201
[ [ [ "#Created 2021-09-08\n#Copyright Spencer W. Leifeld", "_____no_output_____" ], [ "from pyspark.sql import SparkSession as Session\nfrom pyspark import SparkConf as Conf\nfrom pyspark import SparkContext as Context", "_____no_output_____" ], [ "import os\nos.environ['SPARK_LOCAL_IP']='192.168.1.2'\nos.environ['HADOOP_HOME']='/home/geno1664/Developments/Github_Samples/RDS-ENV/hadoop'\nos.environ['LD_LIBRARY_PATH']='$LD_LIBRARY_PATH:$HADOOP_HOME/lib/native'\nos.environ['PYSPARK_DRIVER_PYTHON']='jupyter'\nos.environ['PYSPARK_DRIVER_PYTHON_OPTS']='notebook'\nos.environ['PYSPARK_PYTHON']='python3'\nos.environ['PYARROW_IGNORE_TIMEZONE']='1'", "_____no_output_____" ], [ "configuration = Conf().setAppName('RDS_2').setMaster('spark://GenoMachine:7077')\nconfiguration.set('spark.executor.memory','10G').set('spark.driver.memory', '2G').set('spark.cores.max', '8')", "_____no_output_____" ], [ "context = Context(conf=configuration)", "21/09/10 09:07:37 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable\nUsing Spark's default log4j profile: org/apache/spark/log4j-defaults.properties\nSetting default log level to \"WARN\".\nTo adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).\n" ], [ "session = Session(context)", "_____no_output_____" ], [ "from Functions.IO import CSV_File", "_____no_output_____" ], [ "csvDF = CSV_File(session, r'/home/geno1664/Developments/Github_Samples/RDS-ENV/Rural_Development_Study_No2/IO/Jobs.csv')\nemploymentByJob = csvDF.GetSparkDF().select('State', 'County', 'PctEmpAgriculture', 'PctEmpConstruction', 'PctEmpMining', 'PctEmpTrade', 'PctEmpTrans', \\\n 'PctEmpInformation', 'PctEmpFIRE', 'PctEmpServices', 'PctEmpGovt', 'PctEmpManufacturing')", "Now Reading: /home/geno1664/Developments/Github_Samples/RDS-ENV/Rural_Development_Study_No2/IO/Jobs.csv\n" ], [ "employmentByJob = employmentByJob.withColumnRenamed('PctEmpAgriculture', 'Farmers').withColumnRenamed('PctEmpConstruction', 'Builders').withColumnRenamed('PctEmpMining', 'Miners') \\\n .withColumnRenamed('PctEmpTrade', 'Retail_Associates').withColumnRenamed('PctEmpFIRE', 'Businessmen').withColumnRenamed('PctEmpServices', 'Hospitality_Associates') \\\n .withColumnRenamed('PctEmpGovt', 'Civil_Servants').withColumnRenamed('PctEmpManufacturing', 'Craftsmen').withColumnRenamed('PctEmpInformation', 'Technologists') \\\n .withColumnRenamed('PctEmpTrans', 'Teamsters')", "_____no_output_____" ], [ "employmentByJob = employmentByJob.where(employmentByJob.State != 'US')\nemploymentByJob = employmentByJob.repartition('State')", "_____no_output_____" ], [ "employmentByJob.show()", "" ], [ "csvDF = CSV_File(session, r'/home/geno1664/Developments/Github_Samples/RDS-ENV/Rural_Development_Study_No2/IO/People.csv')\neducationRate = csvDF.GetSparkDF().select('State', 'County', 'Ed1LessThanHSPct', 'Ed2HSDiplomaOnlyPct', 'Ed3SomeCollegePct', 'Ed4AssocDegreePct', 'Ed5CollegePlusPct')", "Now Reading: /home/geno1664/Developments/Github_Samples/RDS-ENV/Rural_Development_Study_No2/IO/People.csv\n" ], [ "educationRate = educationRate.withColumnRenamed('Ed1LessThanHSPct', 'Some_High_School').withColumnRenamed('Ed2HSDiplomaOnlyPct', 'High_School_Degree') \\\n .withColumnRenamed('Ed3SomeCollegePct', 'Some_College').withColumnRenamed('Ed4AssocDegreePct', 'Associates_Degree').withColumnRenamed('Ed5CollegePlusPct', 'College_Graduate')", "_____no_output_____" ], [ "educationRate = educationRate.where(educationRate.State != 'US')\neducationRate = educationRate.repartition('State')", "_____no_output_____" ], [ "educationRate.show()", "+-----+--------------+----------------+------------------+-------------+-----------------+----------------+\n|State| County|Some_High_School|High_School_Degree| Some_College|Associates_Degree|College_Graduate|\n+-----+--------------+----------------+------------------+-------------+-----------------+----------------+\n| AZ| Arizona| 12.8607054321| 23.8588772353|25.1858413213| 8.6277705042| 29.4668055071|\n| AZ| Apache| 19.5977663574| 32.238759483| 28.234221006| 7.6286457986| 12.300607355|\n| AZ| Cochise| 12.6165291708| 24.1034242746|28.7691552847| 11.4013167654| 23.1095745045|\n| AZ| Coconino| 9.4800192585| 22.0389985556|23.8854116514| 8.4352431391| 36.1603273953|\n| AZ| Gila| 13.6740401729| 27.8540554284|30.8619374523| 8.8761759471| 18.7337909992|\n| AZ| Graham| 14.7431030119| 28.7226862398|30.8529486206| 10.5289800051| 15.1522821227|\n| AZ| Greenlee| 11.9405534677| 34.711308507|30.7311240178| 9.1048855483| 13.5121284592|\n| AZ| La Paz| 23.0611100729| 31.1468261384|27.3033077929| 6.4785398368| 12.010216159|\n| AZ| Maricopa| 12.2741475225| 22.3936237653| 24.116624375| 8.5175323875| 32.6980719497|\n| AZ| Mohave| 13.9326098074| 35.3441799092|29.4511683113| 8.326230657| 12.945811315|\n| AZ| Navajo| 16.6182204892| 30.3197447714| 29.94966324| 7.8582063098| 15.2541651896|\n| AZ| Pima| 11.6155183744| 22.2479078342|25.0945036667| 8.6588621177| 32.3832080069|\n| AZ| Pinal| 14.233029233| 29.2657832058|27.6249110582| 9.3441522216| 19.5321242814|\n| AZ| Santa Cruz| 23.4011330285| 28.6601597161|21.3432530203| 6.1634018156| 20.4320524196|\n| AZ| Yavapai| 8.9507176897| 25.8408241304|29.7434580373| 9.5876494592| 25.8773506834|\n| AZ| Yuma| 26.7469588578| 25.7078390534|24.7796492499| 7.7394427843| 15.0261100546|\n| SC|South Carolina| 12.4889649492| 29.1031459214|20.5041179633| 9.7840393783| 28.1197317877|\n| SC| Abbeville| 18.349106204| 34.0285080033|18.9332865989| 13.1090080617| 15.5800911321|\n| SC| Aiken| 12.0274768556| 32.7587813286|20.3188128372| 8.4776771724| 26.4172518062|\n| SC| Allendale| 20.2017018594| 45.8556571068|18.0586196029| 6.6656161361| 9.2184052947|\n+-----+--------------+----------------+------------------+-------------+-----------------+----------------+\nonly showing top 20 rows\n\n" ], [ "from databricks import koalas as ks", "_____no_output_____" ], [ "employmentByJob = employmentByJob.to_koalas().melt(id_vars=['State', 'County'], var_name='Employment_Catagory', value_name='Employment_Rate').to_spark()\neducationRate = educationRate.to_koalas().melt(id_vars=['State', 'County'], var_name='Education_Catagory', value_name='Education_Rate').to_spark()", "_____no_output_____" ], [ "mainDF = employmentByJob.join(educationRate, on=['State', 'County'], how='cross') \\\n .fillna(0, subset=['Employment_Rate', 'Education_Rate']).fillna('NONE', subset=['Employment_Catagory', 'Education_Catagory'])", "_____no_output_____" ], [ "mainDF = mainDF.to_koalas()\nmainDF['Hueristic'] = (mainDF['Employment_Rate'] / 100) * (mainDF['Education_Rate'] / 100) * 100\nmainDF = mainDF.to_spark().select('Employment_Catagory', 'Education_Catagory', 'Hueristic')", "_____no_output_____" ], [ "degreeDF = mainDF.groupBy('Employment_Catagory').pivot('Education_Catagory').mean()", "" ], [ "degreeDF.show()", "" ], [ "degreeDF = degreeDF.to_koalas()\ndegreeDF['No_Post_Secondary_Degree'] = degreeDF['Some_High_School'] + degreeDF['High_School_Degree'] + degreeDF['Some_College']\ndegreeDF['Post_Secondary_Degree'] = degreeDF['College_Graduate'] + degreeDF['Associates_Degree']\ndegreeDF = degreeDF.drop(labels=['Some_High_School', 'High_School_Degree', 'College_Graduate', 'Some_College', 'Associates_Degree']).to_spark()", "_____no_output_____" ], [ "degreeDF.show()", "" ], [ "print('Workplace Population Correlation between Degree and Non-Degree Holders: ' + str(degreeDF.corr('No_Post_Secondary_Degree', 'Post_Secondary_Degree')))", "" ], [ "degreeDF.agg({'No_Post_Secondary_Degree':'sum', 'Post_Secondary_Degree':'sum'}).show()", "" ], [ "employmentDF = mainDF.groupBy('Education_Catagory').pivot('Employment_Catagory').mean()", "_____no_output_____" ], [ "employmentDF = ks.melt(employmentDF.to_koalas(), id_vars='Education_Catagory', var_name='Employment_Catagory', value_name='Employment_Percentage').to_spark()", "_____no_output_____" ], [ "employmentDF.drop('Education_Catagory').groupBy('Employment_Catagory').sum().show()", "" ] ] ]
[ "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" ] ]
cb098272ea546b11ace47c81fd588efff403760b
56,559
ipynb
Jupyter Notebook
models/RL_Course_Aalto/Torch testing _introduction.ipynb
maxmax1992/Deep_RL
8b2b8491d6f94b94b2fce608b93cdc31b418c5b0
[ "MIT" ]
null
null
null
models/RL_Course_Aalto/Torch testing _introduction.ipynb
maxmax1992/Deep_RL
8b2b8491d6f94b94b2fce608b93cdc31b418c5b0
[ "MIT" ]
null
null
null
models/RL_Course_Aalto/Torch testing _introduction.ipynb
maxmax1992/Deep_RL
8b2b8491d6f94b94b2fce608b93cdc31b418c5b0
[ "MIT" ]
null
null
null
29.581067
1,298
0.432769
[ [ [ "from __future__ import print_function\nimport torch\nimport numpy as np\nfrom PIL import Image", "_____no_output_____" ], [ "x = torch.empty(5, 3)\nprint(x)", "tensor([[0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000]])\n" ], [ "x = torch.rand(5, 3)\nprint(x)", "tensor([[0.9738, 0.1549, 0.7427],\n [0.3109, 0.3026, 0.2183],\n [0.7190, 0.0869, 0.9434],\n [0.5827, 0.6285, 0.4375],\n [0.0023, 0.5938, 0.1499]])\n" ], [ "x = torch.zeros(5, 3, dtype=torch.long)\nprint(x)", "tensor([[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]])\n" ], [ "x = torch.tensor([5.5, 3])\nprint(x)", "tensor([5.5000, 3.0000])\n" ], [ "x = x.new_ones(5, 3, dtype=torch.double)\nprint(x)\nprint(x.dtype)", "tensor([[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]], dtype=torch.float64)\ntorch.float64\n" ], [ "x = torch.randn_like(x, dtype=torch.float)\nprint(x.dtype)\nprint(x)", "torch.float32\ntensor([[-0.6534, -0.2158, -0.6944],\n [-2.0448, -0.7748, -0.1905],\n [ 0.4455, 0.6352, 2.0486],\n [ 0.5485, -0.2452, -0.4419],\n [-1.0188, 0.1026, 0.3128]])\n" ], [ "print(x.shape)\nprint(x)\nprint('\\n')\ny = torch.rand(5, 3)\nprint(x + y)", "torch.Size([5, 3])\ntensor([[-0.6534, -0.2158, -0.6944],\n [-2.0448, -0.7748, -0.1905],\n [ 0.4455, 0.6352, 2.0486],\n [ 0.5485, -0.2452, -0.4419],\n [-1.0188, 0.1026, 0.3128]])\n\n\ntensor([[-0.1572, -0.1515, -0.0567],\n [-1.3043, -0.4949, 0.1734],\n [ 0.9092, 0.7685, 2.2040],\n [ 0.6632, 0.2583, 0.0094],\n [-0.8203, 0.3181, 1.2291]])\n" ], [ "print(torch.add(x, y))", "tensor([[-0.1572, -0.1515, -0.0567],\n [-1.3043, -0.4949, 0.1734],\n [ 0.9092, 0.7685, 2.2040],\n [ 0.6632, 0.2583, 0.0094],\n [-0.8203, 0.3181, 1.2291]])\n" ], [ "result = torch.empty(5, 3)\ntorch.add(x, y, out=result)\nprint(result)", "tensor([[-0.1572, -0.1515, -0.0567],\n [-1.3043, -0.4949, 0.1734],\n [ 0.9092, 0.7685, 2.2040],\n [ 0.6632, 0.2583, 0.0094],\n [-0.8203, 0.3181, 1.2291]])\n" ], [ "x = torch.randn(4, 4)\ny = x.view(16)\nz = x.view(-1, 8) # the size -1 is inferred from other dimensions\nprint(x.size(), y.size(), z.size())\n\nx = torch.randn(1)\nprint(x)\nprint(x.item())\nx[0].item()\n", "torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])\ntensor([-0.4582])\n-0.45823556184768677\n" ], [ "a = torch.ones(5)\nprint(a)\nb = a.numpy()\nprint(b)\na.add_(1)\nprint(b)\nprint(a)", "tensor([1., 1., 1., 1., 1.])\n[1. 1. 1. 1. 1.]\n[2. 2. 2. 2. 2.]\ntensor([2., 2., 2., 2., 2.])\n" ], [ "if torch.cuda.is_available():\n device = torch.device(\"cuda\") # a CUDA device object\n y = torch.ones_like(x, device=device) # directly create a tensor on GPU\n x = x.to(device) # or just use strings ``.to(\"cuda\")``\n z = x + y\n print(z)\n print(z.to(\"cpu\", torch.double)) # ``.to`` can also change dtype together!", "tensor([0.5418], device='cuda:0')\ntensor([0.5418], dtype=torch.float64)\n" ] ], [ [ "### Automatic gradient derivation", "_____no_output_____" ] ], [ [ "x = torch.ones(2, 2, requires_grad=True)\nprint(x)\ny = x + 2\nprint(y)", "tensor([[1., 1.],\n [1., 1.]], requires_grad=True)\ntensor([[3., 3.],\n [3., 3.]], grad_fn=<AddBackward>)\n" ], [ "print(y.grad_fn)", "<AddBackward object at 0x7f67a59fb128>\n" ], [ "z = y*y*3 \nout = z.mean()\nprint(z)\nprint(out)", "tensor([[27., 27.],\n [27., 27.]], grad_fn=<MulBackward>)\ntensor(27., grad_fn=<MeanBackward1>)\n" ], [ "# gradients\nout.backward()", "_____no_output_____" ], [ "print(x.grad)\nprint(x)", "tensor([[4.5000, 4.5000],\n [4.5000, 4.5000]])\ntensor([[1., 1.],\n [1., 1.]], requires_grad=True)\n" ], [ "c = torch.ones(2, 2, requires_grad=True)\nd = c.sum()\nd.backward()\nprint(c.grad)", "tensor([[1., 1.],\n [1., 1.]])\n" ], [ "x = torch.randn(3, requires_grad=True)\n\ny = x * 2\nwhile y.data.norm() < 1000:\n y = y * 2\n\nprint(y)", "tensor([-681.1754, -755.3866, 1.7198], grad_fn=<MulBackward>)\n" ], [ "x = torch.ones(1, 1, requires_grad=True)\nc = x.add(3)\ny = c**2", "_____no_output_____" ], [ "y.backward()", "_____no_output_____" ], [ "c.backward()", "_____no_output_____" ], [ "in_ = torch.tensor(np.arange(5, dtype='float32'))\nW1 = torch.rand(5, 5, requires_grad=True)\n\nlayer2 = in_.matmul(W1)\nW2 = torch.rand(5, 5, requires_grad=True)\n\nlayer3 = layer2.matmul(W2)\nW3 = torch.rand(5, requires_grad=True)\n\nd = layer3.dot(W3)\nloss = d.sum()\n# print(loss.backward())\nloss.backward()\nprint(W1.grad)", "tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],\n [2.0494, 1.9833, 1.0673, 1.3994, 2.4251],\n [4.0988, 3.9666, 2.1346, 2.7987, 4.8503],\n [6.1483, 5.9499, 3.2020, 4.1981, 7.2754],\n [8.1977, 7.9332, 4.2693, 5.5974, 9.7005]])\n" ] ], [ [ "### Simple full layer neural network Example", "_____no_output_____" ] ], [ [ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport math\nimport torch\nfrom torch.optim import Optimizer\n\n\nclass Adam(Optimizer):\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(Adam, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(Adam, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def step(self, closure=None, score=1):\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n grad.add_(group['weight_decay'], p.data)\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n \n p.data.addcdiv_(step_size*score, exp_avg, denom)\n\n return loss\n\n\nclass PolicyNetwork(nn.Module):\n def __init__(self, input_dim, learning_rate):\n super(PolicyNetwork, self).__init__() \n \n drop = 0.5\n \n self.classifier = nn.Sequential(\n nn.BatchNorm1d(num_features=input_dim),\n nn.Linear(input_dim, 512),\n nn.BatchNorm1d(512),\n nn.LeakyReLU(),\n nn.Dropout(drop),\n nn.Linear(512, 256),\n nn.BatchNorm1d(256),\n nn.LeakyReLU(),\n nn.Dropout(drop),\n nn.Linear(256, 128),\n nn.BatchNorm1d(128),\n nn.LeakyReLU(),\n nn.Dropout(drop),\n nn.Linear(128, 10),\n nn.BatchNorm1d(10),\n nn.LeakyReLU(),\n nn.Linear(10, 1),\n nn.Sigmoid()\n )\n \n self.optimizer = Adam(self.parameters(), lr=learning_rate)\n self.loss_fn = torch.nn.MSELoss()\n \n def forward(self, x):\n print(x.size())\n x = self.classifier(x)\n return x\n \n# def __init__(self, input_dim, learning_rate):\n# super(PolicyNetwork, self).__init__() \n# self.h1 = nn.Linear(input_dim, 20)\n# self.h2 = nn.Linear(20, 10)\n# self.out = nn.Linear(10, 1)\n \n# self.optimizer = optim.Adam(self.parameters(), lr=learning_rate)\n# self.loss_fn = torch.nn.MSELoss()\n \n# def forward(self, x):\n# x = F.leaky_relu(self.h1(x))\n# x = F.leaky_relu(self.h2(x))\n# x = F.leaky_relu(self.out(x))\n# return x\n \n def train(self, X, y, n_steps, batch_size=64):\n \n N = X.shape[0]\n batch_size=min(batch_size, N)\n \n for t in range(n_steps):\n \n batch_indices = np.random.randint(0, N, batch_size)\n \n y_pred = self.forward(X[batch_indices])\n \n\n # Compute and print loss.\n loss = self.loss_fn(y_pred, y[batch_indices])\n# print(loss.item())\n\n # Before the backward pass, use the optimizer object to zero all of the\n # gradients for the variables it will update (which are the learnable\n # weights of the model). This is because by default, gradients are\n # accumulated in buffers( i.e, not overwritten) whenever .backward()\n # is called. Checkout docs of torch.autograd.backward for more details.\n self.optimizer.zero_grad()\n\n # Backward pass: compute gradient of the loss with respect to model\n # parameters\n loss.backward()\n\n # Calling the step function on an Optimizer makes an update to its\n # parameters\n self.optimizer.step()\n\nnet = PolicyNetwork(4, 0.01)", "_____no_output_____" ], [ "inputs = np.array(\n [[1,2,3,4],\n [1,2,3,4],\n [1,2,3,4],\n [1,2,3,4]], dtype='float64'\n)\ntargets = np.array([\n 1,\n 1,\n 1,\n 1\n], dtype='float64')\nprint(net(torch.from_numpy(inputs).float()))\nnet.train(torch.from_numpy(inputs).float(), torch.from_numpy(targets).float().view(-1, 1), n_steps=1000, batch_size=2)\nprint(net(torch.from_numpy(inputs).float()))\n", "torch.Size([4, 4])\ntensor([[0.4908],\n [0.4908],\n [0.4908],\n [0.4908]], grad_fn=<SigmoidBackward>)\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\ntorch.Size([2, 4])\n" ], [ "arr = np.array([[1, 2],[3, 4]])\nar2 = np.array([[1, 2],[3, 4]])\n\ntensor = torch.from_numpy(arr).float()\ntensor2 = torch.from_numpy(ar2).float()\n# print(tensor.size())\n# batchNorm = nn.LayerNorm(4)\n# batchNorm(tensor)\n\ntorch.cat([tensor, tensor2], 0)", "_____no_output_____" ], [ "net(torch.from_numpy(inputs).float())", "_____no_output_____" ], [ "print(net.h1.bias.grad)\nloss.backward()", "tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0.])\n" ], [ "print(net.h1.bias.grad)", "_____no_output_____" ], [ "# create your optimizer\noptimizer = optim.SGD(net.parameters(), lr=0.01)\n\n# in your training loop:\noptimizer.zero_grad() # zero the gradient buffers\noutput = net(input)\nloss = criterion(outputs, targets)\nloss.backward()\noptimizer.step() ", "_____no_output_____" ], [ "print(loss.backward())", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb09a197b7ad1c414947ccab4944062ba0703c46
262,843
ipynb
Jupyter Notebook
FourierTransforms.ipynb
nbasu1/capstone-physics
b2e248bd55a297238fcae9b56ee24dd539fd63de
[ "MIT" ]
null
null
null
FourierTransforms.ipynb
nbasu1/capstone-physics
b2e248bd55a297238fcae9b56ee24dd539fd63de
[ "MIT" ]
null
null
null
FourierTransforms.ipynb
nbasu1/capstone-physics
b2e248bd55a297238fcae9b56ee24dd539fd63de
[ "MIT" ]
null
null
null
292.047778
112,256
0.918385
[ [ [ "# Fourier Transforms", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom scipy.integrate import quad\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## Part 1: The Discrete Fourier Transform", "_____no_output_____" ], [ "We’re about to make the transition from Fourier series to the Fourier transform. “Transition” is the\nappropriate word, for in the approach we’ll take the Fourier transform emerges as we pass from periodic\nto nonperiodic functions. To make the trip we’ll view a nonperiodic function (which can be just about\nanything) as a limiting case of a periodic function as the period becomes longer and longer.", "_____no_output_____" ], [ "We're going to start by creating a pulse function. Let's start with the following pulse function:", "_____no_output_____" ] ], [ [ "def pulseFunction(x):\n return 1/(3 + (x-20)**2)", "_____no_output_____" ], [ "x = np.linspace(-10, 50, 200)\nplt.plot(x, pulseFunction(x))\nplt.plot(np.zeros(100), np.linspace(0, 0.5, 100), \"--\")\nplt.plot(np.ones(100) *40, np.linspace(0, 0.5, 100), \"--\")\nplt.show()", "_____no_output_____" ] ], [ [ "### Step 1: Periodic Pulse Function", "_____no_output_____" ], [ "Take the `pulseFunction` above and make it periodic. Give it a variable period length (we will eventually make this 40 as shown by the vertical dotted lines above). ", "_____no_output_____" ] ], [ [ "def periodicPulseFunction(x, period):\n \"\"\"\n x : the x values to consider\n period : the period of the function\n \"\"\"\n n = x // period\n x = x - n*period\n return pulseFunction(x)", "_____no_output_____" ] ], [ [ "Plot your `periodicPulseFunction` with a period of $40$ from $-100$ to $100$ and check that it is correctly ", "_____no_output_____" ] ], [ [ "## TO DO: Plot your periodicPulseFunction with a period of 40 from x = -100 to x = 100\nx = np.linspace(-100,100,1000)\nplt.plot(x,periodicPulseFunction(x, 40))", "_____no_output_____" ] ], [ [ "### Step 2: Define the Fourier Series ", "_____no_output_____" ], [ "This function is neither odd nor even, so we're going to have to take into account both the the even coefficients $a_k$ and the odd coefficients $b_k$.", "_____no_output_____" ], [ "$$ f(x) = \\sum\\limits_{k=0}^{\\infty} a_k cos\\left(\\frac{2\\pi k x}{T}\\right) + b_k sin\\left(\\frac{2\\pi k x}{T}\\right) $$", "_____no_output_____" ], [ "Complete the `fourierSeriesSum` that calculates the summation described above. ", "_____no_output_____" ] ], [ [ "def fourierSeriesSum(k, ak, bk, x, period):\n \"\"\"\n Parameters:\n k : the maximum k value to include in the summation above\n ak : an array of length 'k' containing the even coefficients (from a_0 to a_(k-1))\n bk : an array of length 'k' containing the odd coefficients (from b_0 to b_(k-1))\n x : an array of the x values to consider\n period : the period of the function\n \"\"\"\n sum = 0\n for i in range(k+1):\n sum = sum + ak[i]*np.cos(2*np.pi*i*x/period) + bk[i]*np.sin(2*np.pi*i*x/period)\n return sum", "_____no_output_____" ] ], [ [ "### Step 3: Define the Integrands", "_____no_output_____" ], [ "Because we have both even and odd terms, we're going to have two separate integrals:\n\nThe integral to solve for the even terms:\n$$ a_k = \\frac{1}{T} \\int\\limits_{0}^{T} f(x, \\text{period}) \\cos\\left(\\frac{2\\pi k x}{T} \\right) dx$$\n\n\n\nThe integral to solve for the odd terms:\n$$ b_k = \\frac{1}{T} \\int\\limits_{0}^{T} f(x, \\text{period}) \\sin\\left(\\frac{2\\pi k x}{T} \\right) dx$$", "_____no_output_____" ] ], [ [ "def odd_integrand(x, f, k, period):\n \"\"\"\n Parameters:\n x: the x values to consider\n f: the function f(x, period) used in the integral\n k: the k value to use\n period: the period of f\n \"\"\"\n integrand = (1/period)*f(x,period)*np.sin(2*np.pi*k*x/period)\n return integrand", "_____no_output_____" ], [ "def even_integrand(x, f, k, period):\n \"\"\"\n Parameters:\n x: the x values to consider\n f: the function f(x, period) used in the integral\n k: the k value to use\n period: the period of f\n \"\"\"\n integrand = (1/period)*f(x,period)*np.cos(2*np.pi*k*x/period)\n return integrand", "_____no_output_____" ] ], [ [ "### Step 4: Find the Fourier Coefficients", "_____no_output_____" ], [ "Ok! Now it's time to find the coefficients. This is the same process as last time:\n1. Initialize an $a_k$ and $b_k$ array\n2. Loop through all the $k$ values\n3. Find $a_k[i]$ and $b_k[i]$ where i $\\in [0, k]$\n4. Return $a_k$ and $b_k$\n\n(At the end of your quad function, add \"limit = 100\" as an argument)", "_____no_output_____" ] ], [ [ "def findFourierCoefficients(f, k, period):\n \"\"\"\n Parameters:\n f: the function to evaluate\n k: the maximum k value to consider\n period: the period of f\n \n \"\"\"\n ak = np.array([])\n for i in range(k+1):\n temp = quad(even_integrand, 0, period, args=(f,i,period,), limit = 100)\n ak = np.append(ak, temp[0])\n bk = np.array([])\n for i in range(k+1):\n temp = quad(odd_integrand, 0, period, args=(f,i,period,), limit = 100)\n bk = np.append(bk, temp[0])\n return ak, bk", "_____no_output_____" ] ], [ [ "### Step 5: Putting it all Together", "_____no_output_____" ], [ "Let's test it out! ", "_____no_output_____" ] ], [ [ "k = 100\nperiod = 40\n\n[ak, bk] = findFourierCoefficients(periodicPulseFunction, k, period)\ny = fourierSeriesSum(k, ak, bk, x, period)\nplt.plot(x, y)\nplt.title(\"Pulse Function Constructed from Fourier Series\")\nplt.show()", "_____no_output_____" ] ], [ [ "### Step 6: Analyzing the Signal", "_____no_output_____" ], [ "Let's visualize what the coeffcients look like.", "_____no_output_____" ], [ "Plot the even coefficients ($a_k$ versus $k$).", "_____no_output_____" ] ], [ [ "# TO DO: Plot ak versus k\nk = 100\nperiod = 40\n\nx = np.linspace(0,100,101)\nplt.plot(x, findFourierCoefficients(periodicPulseFunction, k, period)[0])\n# print(findFourierCoefficients(periodicPulseFunction, k, period)[0])", "_____no_output_____" ] ], [ [ "Plot the odd coefficients ($b_k$ versus $k$).", "_____no_output_____" ] ], [ [ "# TO DO: Plot bk versus k\nk = 100\nperiod = 40\n\nx = np.linspace(0,100,101)\nplt.plot(x, findFourierCoefficients(periodicPulseFunction, k, period)[1])", "_____no_output_____" ] ], [ [ "## Part 2: Application", "_____no_output_____" ], [ "### Option 1", "_____no_output_____" ], [ "Below I've imported and plotted a signal for you. Break down this signal into sines and cosines, and plot the coefficients ($a_k$ versus $k$ and $b_k$ versus $k$)", "_____no_output_____" ] ], [ [ "x, y = np.loadtxt(\"signal.txt\", unpack=True)", "_____no_output_____" ], [ "plt.figure(figsize=(15, 5))\nplt.plot(x, y)\nplt.show()\nprint(len(x))\nprint(x)", "_____no_output_____" ], [ "period = 15.70796327\n\ndef periodicFunction(inp):\n \"\"\"\n inp : point to find value for\n \"\"\"\n while inp > period:\n inp = inp - period\n for i in range(1000):\n if (abs(inp - x[i]) < 0.0079):\n return y[i]\n\ndef odd_integrand(x, f, k, period):\n \"\"\"\n Parameters:\n x: the x values to consider\n f: the function f(x, period) used in the integral\n k: the k value to use\n period: the period of f\n \"\"\"\n integrand = (1/period)*f(x)*np.sin(2*np.pi*k*x/period)\n return integrand \n\ndef even_integrand(x, f, k, period):\n \"\"\"\n Parameters:\n x: the x values to consider\n f: the function f(x, period) used in the integral\n k: the k value to use\n period: the period of f\n \"\"\"\n integrand = (1/period)*f(x)*np.cos(2*np.pi*k*x/period)\n return integrand\n \ndef findFourierCoefficients2(f, k, period):\n \"\"\"\n Parameters:\n f: the function to evaluate\n k: the maximum k value to consider\n period: the period of f\n \n \"\"\"\n ak = np.array([])\n for i in range(k+1):\n temp = quad(even_integrand, 0, period, args=(f,i,period), limit = 100)\n ak = np.append(ak, temp[0])\n bk = np.array([])\n for i in range(k+1):\n temp = quad(odd_integrand, 0, period, args=(f,i,period), limit = 100)\n bk = np.append(bk, temp[0])\n return ak, bk\n\n\n\nt = np.linspace(0,100,101)\nplt.plot(t, findFourierCoefficients(periodicFunction, 100, period)[0])\nplt.plot(t, findFourierCoefficients(periodicFunction, 100, period)[1])", "<ipython-input-93-3ee181dc2d3b>:11: IntegrationWarning: The integral is probably divergent, or slowly convergent.\n temp = quad(even_integrand, 0, period, args=(f,i,period,), limit = 100)\n<ipython-input-93-3ee181dc2d3b>:11: IntegrationWarning: The maximum number of subdivisions (100) has been achieved.\n If increasing the limit yields no improvement it is advised to analyze \n the integrand in order to determine the difficulties. If the position of a \n local difficulty can be determined (singularity, discontinuity) one will \n probably gain from splitting up the interval and calling the integrator \n on the subranges. Perhaps a special-purpose integrator should be used.\n temp = quad(even_integrand, 0, period, args=(f,i,period,), limit = 100)\n<ipython-input-93-3ee181dc2d3b>:15: IntegrationWarning: The integral is probably divergent, or slowly convergent.\n temp = quad(odd_integrand, 0, period, args=(f,i,period,), limit = 100)\n<ipython-input-93-3ee181dc2d3b>:15: IntegrationWarning: The maximum number of subdivisions (100) has been achieved.\n If increasing the limit yields no improvement it is advised to analyze \n the integrand in order to determine the difficulties. If the position of a \n local difficulty can be determined (singularity, discontinuity) one will \n probably gain from splitting up the interval and calling the integrator \n on the subranges. Perhaps a special-purpose integrator should be used.\n temp = quad(odd_integrand, 0, period, args=(f,i,period,), limit = 100)\n<ipython-input-93-3ee181dc2d3b>:11: IntegrationWarning: The integral is probably divergent, or slowly convergent.\n temp = quad(even_integrand, 0, period, args=(f,i,period,), limit = 100)\n<ipython-input-93-3ee181dc2d3b>:11: IntegrationWarning: The maximum number of subdivisions (100) has been achieved.\n If increasing the limit yields no improvement it is advised to analyze \n the integrand in order to determine the difficulties. If the position of a \n local difficulty can be determined (singularity, discontinuity) one will \n probably gain from splitting up the interval and calling the integrator \n on the subranges. Perhaps a special-purpose integrator should be used.\n temp = quad(even_integrand, 0, period, args=(f,i,period,), limit = 100)\n<ipython-input-93-3ee181dc2d3b>:15: IntegrationWarning: The integral is probably divergent, or slowly convergent.\n temp = quad(odd_integrand, 0, period, args=(f,i,period,), limit = 100)\n<ipython-input-93-3ee181dc2d3b>:15: IntegrationWarning: The maximum number of subdivisions (100) has been achieved.\n If increasing the limit yields no improvement it is advised to analyze \n the integrand in order to determine the difficulties. If the position of a \n local difficulty can be determined (singularity, discontinuity) one will \n probably gain from splitting up the interval and calling the integrator \n on the subranges. Perhaps a special-purpose integrator should be used.\n temp = quad(odd_integrand, 0, period, args=(f,i,period,), limit = 100)\n" ] ], [ [ "### Option 2", "_____no_output_____" ], [ "Find a signal from real data, and find the cosines and sines values that comprise that signal. ", "_____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", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ] ]
cb09aed90d39a25f10039171d100f5c420bb5777
216,598
ipynb
Jupyter Notebook
P2_Image_Captioning/.ipynb_checkpoints/0_Dataset-checkpoint.ipynb
arvcode/computer_vision_DNN
327f7fa43593865d62c96b83bdde8d8ee954ed51
[ "MIT" ]
null
null
null
P2_Image_Captioning/.ipynb_checkpoints/0_Dataset-checkpoint.ipynb
arvcode/computer_vision_DNN
327f7fa43593865d62c96b83bdde8d8ee954ed51
[ "MIT" ]
null
null
null
P2_Image_Captioning/.ipynb_checkpoints/0_Dataset-checkpoint.ipynb
arvcode/computer_vision_DNN
327f7fa43593865d62c96b83bdde8d8ee954ed51
[ "MIT" ]
null
null
null
1,203.322222
211,404
0.956574
[ [ [ "# Computer Vision Nanodegree\n\n## Project: Image Captioning\n\n---\n\nThe Microsoft **C**ommon **O**bjects in **CO**ntext (MS COCO) dataset is a large-scale dataset for scene understanding. The dataset is commonly used to train and benchmark object detection, segmentation, and captioning algorithms. \n\n![Sample Dog Output](images/coco-examples.jpg)\n\nYou can read more about the dataset on the [website](http://cocodataset.org/#home) or in the [research paper](https://arxiv.org/pdf/1405.0312.pdf).\n\nIn this notebook, you will explore this dataset, in preparation for the project.\n\n## Step 1: Initialize the COCO API\n\nWe begin by initializing the [COCO API](https://github.com/cocodataset/cocoapi) that you will use to obtain the data.", "_____no_output_____" ] ], [ [ "import os\nimport sys\nsys.path.append('/opt/cocoapi/PythonAPI')\nfrom pycocotools.coco import COCO\n\n# initialize COCO API for instance annotations\ndataDir = '/opt/cocoapi'\ndataType = 'val2014'\ninstances_annFile = os.path.join(dataDir, 'annotations/instances_{}.json'.format(dataType))\ncoco = COCO(instances_annFile)\n\n# initialize COCO API for caption annotations\ncaptions_annFile = os.path.join(dataDir, 'annotations/captions_{}.json'.format(dataType))\ncoco_caps = COCO(captions_annFile)\n\n# get image ids \nids = list(coco.anns.keys())", "loading annotations into memory...\nDone (t=6.51s)\ncreating index...\nindex created!\nloading annotations into memory...\nDone (t=0.47s)\ncreating index...\nindex created!\n" ] ], [ [ "## Step 2: Plot a Sample Image\n\nNext, we plot a random image from the dataset, along with its five corresponding captions. Each time you run the code cell below, a different image is selected. \n\nIn the project, you will use this dataset to train your own model to generate captions from images!", "_____no_output_____" ] ], [ [ "import numpy as np\nimport skimage.io as io\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# pick a random image and obtain the corresponding URL\nann_id = np.random.choice(ids)\nimg_id = coco.anns[ann_id]['image_id']\nimg = coco.loadImgs(img_id)[0]\nurl = img['coco_url']\n\n# print URL and visualize corresponding image\nprint(url)\nI = io.imread(url)\nplt.axis('off')\nplt.imshow(I)\nplt.show()\n\n# load and display captions\nannIds = coco_caps.getAnnIds(imgIds=img['id']);\nanns = coco_caps.loadAnns(annIds)\ncoco_caps.showAnns(anns)", "http://images.cocodataset.org/val2014/COCO_val2014_000000524456.jpg\n" ] ], [ [ "## Step 3: What's to Come!\n\nIn this project, you will use the dataset of image-caption pairs to train a CNN-RNN model to automatically generate images from captions. You'll learn more about how to design the architecture in the next notebook in the sequence (**1_Preliminaries.ipynb**).\n\n![Image Captioning CNN-RNN model](images/encoder-decoder.png)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb09b0cbab1e3646b5196d06d38eeed2d1540277
25,966
ipynb
Jupyter Notebook
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
c976ee52598afa9d54892abc076c60fe8a18818a
[ "MIT" ]
null
null
null
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
c976ee52598afa9d54892abc076c60fe8a18818a
[ "MIT" ]
null
null
null
Module_4/Assignment+2.ipynb
AustinChase/Applied_Data_Science
c976ee52598afa9d54892abc076c60fe8a18818a
[ "MIT" ]
null
null
null
29.94925
294
0.530771
[ [ [ "---\n\n_You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._\n\n---", "_____no_output_____" ], [ "# Assignment 2 - Introduction to NLTK\n\nIn part 1 of this assignment you will use nltk to explore the Herman Melville novel Moby Dick. Then in part 2 you will create a spelling recommender function that uses nltk to find words similar to the misspelling. ", "_____no_output_____" ], [ "## Part 1 - Analyzing Moby Dick", "_____no_output_____" ] ], [ [ "import nltk\nimport pandas as pd\nimport numpy as np\n\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('averaged_perceptron_tagger')\n\n# If you would like to work with the raw text you can use 'moby_raw'\nwith open('moby.txt', 'r') as f:\n moby_raw = f.read()\n \n# If you would like to work with the novel in nltk.Text format you can use 'text1'\nmoby_tokens = nltk.word_tokenize(moby_raw)\ntext1 = nltk.Text(moby_tokens)\n", "[nltk_data] Downloading package punkt to /home/austin/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n[nltk_data] Downloading package wordnet to /home/austin/nltk_data...\n[nltk_data] Package wordnet is already up-to-date!\n[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] /home/austin/nltk_data...\n[nltk_data] Package averaged_perceptron_tagger is already up-to-\n[nltk_data] date!\n" ] ], [ [ "### Example 1\n\nHow many tokens (words and punctuation symbols) are in text1?\n\n*This function should return an integer.*", "_____no_output_____" ] ], [ [ "def example_one():\n \n return len(nltk.word_tokenize(moby_raw)) # or alternatively len(text1)\n", "_____no_output_____" ] ], [ [ "### Example 2\n\nHow many unique tokens (unique words and punctuation) does text1 have?\n\n*This function should return an integer.*", "_____no_output_____" ] ], [ [ "def example_two():\n \n return len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1))\n", "_____no_output_____" ] ], [ [ "### Example 3\n\nAfter lemmatizing the verbs, how many unique tokens does text1 have?\n\n*This function should return an integer.*", "_____no_output_____" ] ], [ [ "from nltk.stem import WordNetLemmatizer\n\ndef example_three():\n\n lemmatizer = WordNetLemmatizer()\n lemmatized = [lemmatizer.lemmatize(w,'v') for w in text1]\n\n return len(set(lemmatized))\n", "_____no_output_____" ] ], [ [ "### Question 1\n\nWhat is the lexical diversity of the given text input? (i.e. ratio of unique tokens to the total number of tokens)\n\n*This function should return a float.*", "_____no_output_____" ] ], [ [ "from nltk.stem import WordNetLemmatizer\n\ndef answer_one():\n \n lemmatizer = WordNetLemmatizer() #instantiate WordNetLemmatizer\n lemmatized = [lemmatizer.lemmatize(w) for w in text1] # use list comprehension to lemmatize each work in text1\n \n total = len(lemmatized) #calculate the total lemmas\n unique = len(set(lemmatized)) #calclulate the number of unique lemmas\n\n lexical_diversity = unique/total #calculate the ratio of unique lemmas to total lemmas \n \n return lexical_diversity\n\nanswer_one()", "_____no_output_____" ] ], [ [ "### Question 2\n\nWhat percentage of tokens is 'whale'or 'Whale'?\n\n*This function should return a float.*", "_____no_output_____" ] ], [ [ "from nltk.stem import WordNetLemmatizer\n\ndef answer_two():\n\n tokens = nltk.word_tokenize(moby_raw) #tokenize moby_raw\n dist = nltk.FreqDist(tokens) #calculate the distribution of tokens\n \n whale_freq = dist.freq(\"whale\")\n Whale_freq = dist.freq(\"Whale\")\n #access the frequency distributions for 'whale' and 'Whale'\n \n total_freq = (whale_freq + Whale_freq)*100 \n #add the distributions, multiply by 100 for a percentage\n \n return total_freq\n\nanswer_two()", "_____no_output_____" ] ], [ [ "### Question 3\n\nWhat are the 20 most frequently occurring (unique) tokens in the text? What is their frequency?\n\n*This function should return a list of 20 tuples where each tuple is of the form `(token, frequency)`. The list should be sorted in descending order of frequency.*", "_____no_output_____" ] ], [ [ "def answer_three():\n \n tokens = nltk.word_tokenize(moby_raw) #tokenize moby_raw\n \n# top_20 = dist.pformat(maxlen=20)\n \n# top_20_split = top_20.split(',')\n \n# word = []\n# count = []\n \n# for i,value in enumerate(top_20_split):\n# word.append(top_20_split[i].split(':')[0].replace(\"'\",\"\").lstrip().rstrip())\n \n# word.pop(0)\n# word.insert(0,',')\n# word.pop(21)\n# word.pop(1)\n# #word.pop(19)\n# #word.insert(19,\"''\")\n \n# for i in range(len(top_20_split)-2):\n# count.append(int(top_20_split[i+1].split(':')[1].lstrip().rstrip()))\n \n# merged_list= list(zip(word,count))\n\n## Took the scenic route the first go around\n \n top_20 = (nltk.FreqDist(tokens)\n .most_common(20)) #calculate the distribution of tokens and return the top 20\n \n return top_20\n\nanswer_three()", "_____no_output_____" ] ], [ [ "### Question 4\n\nWhat tokens have a length of greater than 5 and frequency of more than 150?\n\n*This function should return an alphabetically sorted list of the tokens that match the above constraints. To sort your list, use `sorted()`*", "_____no_output_____" ] ], [ [ "def answer_four():\n \n tokens = nltk.word_tokenize(moby_raw) #tokenize moby_raw\n \n dist = nltk.FreqDist(tokens) #calculate the distribution of tokens\n \n fivechars_onefiftytimes = [w for w in dist if len(w) > 5 and dist[w] > 150]\n # use list comprehension to return tokens greater than length 5 that have a frequency greater than 150\n \n fivechars_onefiftytimes.sort()\n \n return fivechars_onefiftytimes\n", "_____no_output_____" ] ], [ [ "### Question 5\n\nFind the longest word in text1 and that word's length.\n\n*This function should return a tuple `(longest_word, length)`.*", "_____no_output_____" ] ], [ [ "def answer_five():\n \n lemmatizer = nltk.WordNetLemmatizer() #instantiate WordNetLemmatizer\n lemmatized = [lemmatizer.lemmatize(w) for w in text1] #create a list of lemmas using the lemmatizer instance\n \n dist = nltk.FreqDist(lemmatized) #calculate the distribution of lemmas\n \n# first_answer = ([w for w in lemmatized if len(w) > 22][0],\n# len([w for w in lemmatized if len(w) > 22][0]))\n# #guess and check method using a list comprehension\n \n longest_word_length = 0\n longest_word = \"\"\n \n for i, word in enumerate(lemmatized):\n if len(word) > longest_word_length:\n longest_word_length = len(word)\n longest_word = word\n else:\n pass\n #loop over list of lemmas and store the running longest word length along with the actual word\n\n answer = (longest_word, longest_word_length) \n \n return answer\nanswer_five()", "_____no_output_____" ] ], [ [ "### Question 6\n\nWhat unique words have a frequency of more than 2000? What is their frequency?\n\n\"Hint: you may want to use `isalpha()` to check if the token is a word and not punctuation.\"\n\n*This function should return a list of tuples of the form `(frequency, word)` sorted in descending order of frequency.*", "_____no_output_____" ] ], [ [ "def answer_six():\n \n tokens = nltk.word_tokenize(moby_raw) #instantiate WordNetLemmatizer\n dist = nltk.FreqDist(tokens) #calculate the distribution of lemmas\n \n token = [w for w in dist if w.isalpha() and dist[w] > 2000] \n #use list comprehension to return tokens that are words and have a frequency greater than 2000\n count = [dist[w] for w in dist if w.isalpha() and dist[w] > 2000]\n #use list comprehension to return the count for the tokens returned in the above list comprehension\n \n combined = list(zip(count, token)) #combine the two lists\n combined.sort(reverse = True, key = lambda x: x[0]) #sort the list by the first entry in the tuple\n \n return combined\nanswer_six()", "_____no_output_____" ] ], [ [ "### Question 7\n\nWhat is the average number of tokens per sentence?\n\n*This function should return a float.*", "_____no_output_____" ] ], [ [ "def answer_seven():\n \n sentences = nltk.sent_tokenize(moby_raw) #instantiate a sentence tokenizer instance\n text_sentences = nltk.Text(sentences) \n\n counter = 0\n sum_total = 0\n for i,sentence in enumerate(sentences):\n sum_total += len(nltk.word_tokenize(sentence)) \n #loop through sentences and calculate a running total of sentence lengths\n counter += 1\n \n average = sum_total/counter \n #return sum of sentences lengths over count of sentences; average sentence length\n\n return average\n\nanswer_seven()", "_____no_output_____" ] ], [ [ "### Question 8\n\nWhat are the 5 most frequent parts of speech in this text? What is their frequency?\n\n*This function should return a list of tuples of the form `(part_of_speech, frequency)` sorted in descending order of frequency.*", "_____no_output_____" ] ], [ [ "def answer_eight():\n \n tokens = nltk.word_tokenize(moby_raw) #instantiate a sentence tokenizer instance\n tags = nltk.pos_tag(tokens) #create list of tokens with their respective parts of speech\n \n pos_tag = []\n for i,tag in enumerate(tags):\n pos_tag.append(tag[1])\n #create a list of all parts of speech in moby raw \n \n dist = nltk.FreqDist(pos_tag) #calculate the frequency distribution of the pos tags\n freq = [dist[w] for w in dist] #create a list of frequency counts from dist\n pos_tag_consolidated = [w for w in dist] #create a list of parts of speech from dist \n zipped = list(zip(pos_tag_consolidated,freq)) \n \n zipped.sort(reverse = True, key = lambda x:x[1])\n top_5 = zipped[:5]\n \n return top_5\n\nanswer_eight()", "_____no_output_____" ] ], [ [ "## Part 2 - Spelling Recommender\n\nFor this part of the assignment you will create three different spelling recommenders, that each take a list of misspelled words and recommends a correctly spelled word for every word in the list.\n\nFor every misspelled word, the recommender should find find the word in `correct_spellings` that has the shortest distance*, and starts with the same letter as the misspelled word, and return that word as a recommendation.\n\n*Each of the three different recommenders will use a different distance measure (outlined below).\n\nEach of the recommenders should provide recommendations for the three default words provided: `['cormulent', 'incendenece', 'validrate']`.", "_____no_output_____" ] ], [ [ "from nltk.corpus import words\nnltk.download('words')\ncorrect_spellings = words.words() # list of correctly spelled words", "[nltk_data] Downloading package words to /home/austin/nltk_data...\n[nltk_data] Package words is already up-to-date!\n" ] ], [ [ "### Question 9\n\nFor this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n\n**[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the trigrams of the two words.**\n\n*This function should return a list of length three:\n`['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*", "_____no_output_____" ] ], [ [ "def answer_nine(entries=['cormulent', 'incendenece', 'validrate']):\n \n entries = entries \n jaccard_list = []\n for i in range(len(entries)):\n jaccard_dict = {}\n for j,word in enumerate(correct_spellings):\n jaccard_dict[word] = nltk.jaccard_distance(set(nltk.ngrams(word,n=3)),\n set(nltk.ngrams(entries[i],n=3)))\n\n jaccard_list.append(jaccard_dict)\n #put dictionaries in a list\n \n for i in range(len(jaccard_list)):\n jaccard_list[i] = {k: v for k, v in sorted(jaccard_list[i].items(), key = lambda item: item[1])}\n #sort each dictionary in jaccard list by the jaccard distance\n \n answer = [] \n for i in range(len(jaccard_list)):\n for key in jaccard_list[i]:\n if key.startswith(entries[i][0]):\n print(\"{0}: {1:.2f}\".format(key,jaccard_list[i][key]))\n answer.append(key)\n break\n #return the word with the smallest jaccard distance that starts with the same letter as the misspelled word \n \n return answer\nanswer_nine()", "corpulent: 0.60\nindecence: 0.67\nvalidate: 0.56\n" ] ], [ [ "### Question 10\n\nFor this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n\n**[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the 4-grams of the two words.**\n\n*This function should return a list of length three:\n`['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*", "_____no_output_____" ] ], [ [ "def answer_ten(entries=['cormulent', 'incendenece', 'validrate']):\n #same as above, but for 4-grams instead of 3-grams \n entries = entries\n \n jaccard_list = []\n for i in range(len(entries)):\n jaccard_dict = {}\n for j,word in enumerate(correct_spellings):\n jaccard_dict[word] = nltk.jaccard_distance(set(nltk.ngrams(word,n=4)),\n set(nltk.ngrams(entries[i],n=4)))\n jaccard_list.append(jaccard_dict)\n #put dictionaries in list\n \n for i in range(len(jaccard_list)):\n jaccard_list[i] = {k: v for k, v in sorted(jaccard_list[i].items(), key = lambda item: item[1])}\n #sort each dictionary in jaccard list by the jaccard distance\n \n answer = [] \n for i in range(len(jaccard_list)):\n for key in jaccard_list[i]:\n if key.startswith(entries[i][0]):\n print(\"{0}: {1:.2f}\".format(key,jaccard_list[i][key]))\n answer.append(key)\n break\n #return the word with the smallest jaccard distance that starts with the same letter as the misspelled word\n #same as above\n \n return answer\n\nanswer_ten()", "cormus: 0.71\nincendiary: 0.75\nvalid: 0.67\n" ] ], [ [ "### Question 11\n\nFor this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n\n**[Edit distance on the two words with transpositions.](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)**\n\n*This function should return a list of length three:\n`['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*", "_____no_output_____" ] ], [ [ "def answer_eleven(entries=['cormulent', 'incendenece', 'validrate']):\n \n #use edit distance instead of Jaccard distance to recommend correct spelling\n edit_list = []\n for i in range(len(entries)):\n edit_dict = {}\n for j,word in enumerate(correct_spellings):\n edit_dict[word] = nltk.edit_distance(word,entries[i])\n edit_list.append(edit_dict)\n #put dictionaries in list\n \n for i in range(len(edit_list)):\n edit_list[i] = {k: v for k, v in sorted(edit_list[i].items(), key = lambda item: item[1])}\n #sort each dictionary in jaccard list by the edit distance\n \n answer = [] \n for i in range(len(edit_list)):\n for key in edit_list[i]:\n if key.startswith(entries[i][0]):\n print(\"{0}: {1:.1f}\".format(key,edit_list[i][key]))\n answer.append(key)\n break\n #return the word with the smallest edit distance that starts with the same letter as the misspelled word\n \n return answer\nanswer_eleven()\n", "corpulent: 1.0\nintendence: 2.0\nvalidate: 1.0\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb09b44036e01b1c1cc75ee0dcf87a29227604b2
465,781
ipynb
Jupyter Notebook
_graph_polt_gallery/matplotlib-gallery/ipynb/3dplots.ipynb
OpenBookProjects/ipynb
72a28109e8e30aea0b9c6713e78821e4affa2e33
[ "MIT" ]
6
2015-06-08T12:50:14.000Z
2018-11-20T10:05:01.000Z
_graph_polt_gallery/matplotlib-gallery/ipynb/3dplots.ipynb
OpenBookProjects/ipynb
72a28109e8e30aea0b9c6713e78821e4affa2e33
[ "MIT" ]
null
null
null
_graph_polt_gallery/matplotlib-gallery/ipynb/3dplots.ipynb
OpenBookProjects/ipynb
72a28109e8e30aea0b9c6713e78821e4affa2e33
[ "MIT" ]
8
2016-01-26T14:12:50.000Z
2021-02-20T14:24:09.000Z
1,003.838362
173,633
0.943834
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb09b85df26adf08fabf6d6fe056177b6a8b1be2
293,688
ipynb
Jupyter Notebook
code/evo_tune_201023/generate_embedding_transformer.ipynb
steveyu323/motor_embedding
65b05e024ca5a0aa339330eff6b63927af5ce4aa
[ "MIT" ]
null
null
null
code/evo_tune_201023/generate_embedding_transformer.ipynb
steveyu323/motor_embedding
65b05e024ca5a0aa339330eff6b63927af5ce4aa
[ "MIT" ]
null
null
null
code/evo_tune_201023/generate_embedding_transformer.ipynb
steveyu323/motor_embedding
65b05e024ca5a0aa339330eff6b63927af5ce4aa
[ "MIT" ]
null
null
null
114.677079
1,067
0.87692
[ [ [ "# Documentation\n> 201025: This notebook generate embedding vectors for pfam_motors, df_dev, and motor_toolkit from the models that currently finished training:\n - lstm5 \n - evotune_lstm_5_balanced.pt \n - evotune_lstm_5_balanced_target.pt \n - mini_lstm_5_balanced.pt \n - mini_lstm_5_balanced_target.pt \n - transformer_encoder \n - evotune_seq2seq_encoder_balanced.pt \n - evotune_seq2seq_encoder_balanced_target.pt \n - mini_seq2seq_encoder_balanced.pt \n - mini_seq2seq_encoder_balanced_target.pt \n - seq2seq_attention_mini \n - transformer_encoder_201025.pt \n - evotune_transformerencoder_balanced.pt \n - evotune_transformerencoder_balanced_target.pt \n - mini_evotune_transformerencoder_balanced.pt \n - mini_evotune_transformerencoder_balanced_target.pt \n \n\n- output for motor_toolkit,pfamA_random, and pfamA_motors\n", "_____no_output_____" ] ], [ [ "import math\nimport torch.nn as nn\nimport argparse\nimport random\nimport warnings\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch import optim\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\nfrom torch.autograd import Variable\nimport itertools\nimport pandas as pd\nfrom torch.nn import TransformerEncoder, TransformerEncoderLayer\nimport math\n\nseed = 7\ntorch.manual_seed(seed)\nnp.random.seed(seed)", "_____no_output_____" ], [ "pfamA_motors = pd.read_csv(\"../../data/pfamA_motors.csv\")\npfamA_random = pd.read_csv(\"../../data/pfamA_random_201027.csv\")\nmotor_toolkit = pd.read_csv(\"../../data/motor_tookits.csv\")\n\npfamA_motors_balanced = pfamA_motors.groupby('clan').apply(lambda _df: _df.sample(4500,random_state=1))\npfamA_motors_balanced = pfamA_motors_balanced.apply(lambda x: x.reset_index(drop = True))\n\npfamA_target_name = [\"PF00349\",\"PF00022\",\"PF03727\",\"PF06723\",\\\n \"PF14450\",\"PF03953\",\"PF12327\",\"PF00091\",\"PF10644\",\\\n \"PF13809\",\"PF14881\",\"PF00063\",\"PF00225\",\"PF03028\"]\n\npfamA_target = pfamA_motors.loc[pfamA_motors[\"pfamA_acc\"].isin(pfamA_target_name),:]\n\n\naminoacid_list = [\n 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L',\n 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'\n]\nclan_list = [\"actin_like\",\"tubulin_c\",\"tubulin_binding\",\"p_loop_gtpase\"]\n \naa_to_ix = dict(zip(aminoacid_list, np.arange(1, 21)))\nclan_to_ix = dict(zip(clan_list, np.arange(0, 4)))\n\ndef word_to_index(seq,to_ix):\n \"Returns a list of indices (integers) from a list of words.\"\n return [to_ix.get(word, 0) for word in seq]\n\nix_to_aa = dict(zip(np.arange(1, 21), aminoacid_list))\nix_to_clan = dict(zip(np.arange(0, 4), clan_list))\n\ndef index_to_word(ixs,ix_to): \n \"Returns a list of words, given a list of their corresponding indices.\"\n return [ix_to.get(ix, 'X') for ix in ixs]\n\ndef prepare_sequence(seq):\n idxs = word_to_index(seq[0:-1],aa_to_ix)\n return torch.tensor(idxs, dtype=torch.long)\n\ndef prepare_labels(seq):\n idxs = word_to_index(seq[1:],aa_to_ix)\n return torch.tensor(idxs, dtype=torch.long)\n\ndef prepare_eval(seq):\n idxs = word_to_index(seq[:],aa_to_ix)\n return torch.tensor(idxs, dtype=torch.long)\n\nprepare_labels('YCHXXXXX')\n\n# set device\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndevice", "_____no_output_____" ], [ "class PositionalEncoding(nn.Module):\n \"\"\"\n PositionalEncoding module injects some information about the relative or absolute position of\n the tokens in the sequence. The positional encodings have the same dimension as the embeddings \n so that the two can be summed. Here, we use sine and cosine functions of different frequencies.\n \"\"\"\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n # print(\"self.pe.size() :\", self.pe[:x.size(0),:,:].size())\n \n# pe[:, 0::2] = torch.sin(position * div_term)\n# pe[:, 1::2] = torch.cos(position * div_term)\n# pe = pe.unsqueeze(0)\n \n self.register_buffer('pe', pe)\n\n def forward(self, x):\n \n# x = x + self.pe[:x.size(0), :]\n x = x.unsqueeze(0).transpose(0, 1)\n # print(\"x.size() : \", x.size())\n # print(\"self.pe.size() :\", self.pe[:x.size(0),:,:].size())\n x = torch.add(x ,Variable(self.pe[:x.size(0),:,:], requires_grad=False))\n return self.dropout(x)\n\nclass TransformerModel(nn.Module):\n\n def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):\n super(TransformerModel, self).__init__()\n from torch.nn import TransformerEncoder, TransformerEncoderLayer\n self.model_type = 'Transformer'\n self.src_mask = None\n self.pos_encoder = PositionalEncoding(ninp)\n encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)\n self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n self.decoder = nn.Linear(ninp, ntoken)\n\n self.init_weights()\n\n def _generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src):\n # if self.src_mask is None or self.src_mask.size(0) != src.size(0):\n # device = src.device\n # mask = self._generate_square_subsequent_mask(src.size(0)).to(device)\n # self.src_mask = mask\n# print(\"src.device: \", src.device)\n src = self.encoder(src) * math.sqrt(self.ninp)\n # print(\"self.encoder(src) size: \", src.size())\n src = self.pos_encoder(src)\n # print(\"elf.pos_encoder(src) size: \", src.size())\n output_encoded = self.transformer_encoder(src, self.src_mask)\n output_encoded = self.transformer_encoder(src)\n # print(\"output_encoded size: \", output_encoded.size())\n output = self.decoder(output_encoded)\n return output,output_encoded", "_____no_output_____" ], [ "ntokens = len(aminoacid_list) + 1 # the size of vocabulary\nemsize = 12 # embedding dimension\nnhid = 100 # the dimension of the feedforward network model in nn.TransformerEncoder\nnlayers = 6 # the number of nn.TransformerEncoderLayer in nn.TransformerEncoder\nnhead = 12 # the number of heads in the multiheadattention models\ndropout = 0.1 # the dropout value\nmodel = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to(device)\nmodel.eval()", "_____no_output_____" ], [ "def generate_embedding_transformer(model,dict_file,dat,dat_name,out_path,out_dir,seq_col):\n # initialize network\n \n model.load_state_dict(torch.load(dict_file))\n\n print(\"loaded dict file for weights \" + dict_file)\n print(\"output embedding for \" + dat_name)\n \n hn_vector = []\n print_every = 1000\n for epoch in np.arange(0, dat.shape[0]): \n with torch.no_grad():\n seq = dat.iloc[epoch, seq_col]\n if len(seq) > 5000:\n continue\n sentence_in = prepare_eval(seq)\n sentence_in = sentence_in.to(device = device)\n _,hn = model(sentence_in)\n hn = hn.sum(dim = 0).cpu().detach().numpy()\n hn_vector.append(hn)\n \n if epoch % print_every == 0:\n print(f\"At Epoch: %.2f\"% epoch)\n print(seq)\n hn_vector = np.array(hn_vector)\n hn_vector = np.squeeze(hn_vector, axis=1)\n\n print(hn_vector.shape)\n print(out_dir+dat_name+\"_\"+out_path)\n np.save(out_dir+dat_name+\"_\"+out_path, hn_vector)\n return \n\n", "_____no_output_____" ], [ "dict_files = [\"evotune_transformer_encoder_mlm_balanced_target.pt\",\"evotune_transformer_encoder_mlm_balanced.pt\",\"evotune_transformerencoder_balanced_target.pt\",\\\n \"evotune_transformerencoder_balanced.pt\",\"mini_transformer_encoder_mlm_balanced_target.pt\",\"mini_transformer_encoder_mlm_balanced.pt\",\\\n \"mini_transformerencoder_balanced_target.pt\",\"mini_transformerencoder_balanced.pt\",\"transformer_encoder_201025.pt\",\"transformer_encoder_mlm_201025.pt\"]\ndict_files = [\"../../data/201025/\"+dict_file for dict_file in dict_files]\ndict_files\n# \"../data/hn_lstm5_motortoolkit.npy\"\n", "_____no_output_____" ], [ "out_paths = [\"mlm_evotune_balanced_target.npy\",\"mlm_evotune_balanced.npy\",\"evotune_balanced_target.npy\",\\\n \"evotune_balanced.npy\", \"mlm_mini_balanced_target.npy\",\"mlm_mini_balanced.npy\",\\\n \"mini_balanced_target.npy\", \"mini_balanced.npy\", \"raw.npy\",\"mlm_raw.npy\"]", "_____no_output_____" ], [ "out_dir = \"../../out/201027/embedding/transformer_encoder/\"\nout_paths", "_____no_output_____" ], [ "len(dict_files)==len(out_paths)", "_____no_output_____" ], [ "pfamA_target.iloc[1,3]", "_____no_output_____" ], [ "data = [pfamA_motors_balanced,pfamA_target,pfamA_random,motor_toolkit]\ndata_names = [\"pfamA_motors_balanced\", \"pfamA_target\" , \"pfamA_random\", \"motor_toolkit\"]\nseq_cols = [3,3,2,7]", "_____no_output_____" ], [ "for i in range(len(dict_files)):\n dict_file = dict_files[i]\n out_path = out_paths[i]\n for i in range(len(data)):\n dat = data[i]\n dat_name = data_names[i]\n seq_col = seq_cols[i]\n generate_embedding_transformer(model,dict_file,dat,dat_name,out_path,out_dir,seq_col)", "loaded dict file for weights ../../data/201025/evotune_transformer_encoder_mlm_balanced_target.pt\noutput embedding for pfamA_motors_balanced\nAt Epoch: 0.00\nHQDNVHARSLMGLVRNVFEQAGLEKTALDAVAVSSGPGSYTGLRIGVSVAKGLAYALDKPVIGVGTLEALAFRAIPFSDSTDTIIPMLDARRMEVYALVMDGLGDTLISPQPFILEDNPFMEYLEKGKVFFLGDGVPKSKEILSHPNSRFVPLFNSSQSIGELAYKKFLKADFESLAYFEPNYIKEFRI\nAt Epoch: 1000.00\nLAAEARGDRAEAARILGAGAANLVGLLDIDRVVLGGRTVAADEDAYVRGVRAVIADRAARGAGGAHVTVTVADGGDRPVAEGAAQLVLA\nAt Epoch: 2000.00\nARKIGIDLGTTNLLICVDNKGILVDEPSIITVDATTKKCIAAGLDARDMLGRTPKNMICIRPLKDGVVADFEATDMMLNYFLKKCDLKGMFKKNVILICHPTKITSVEKNAIRDCAYRAGAKKVYLEEEPKIAALGAGLDIGKASGNMVLDIGGGTSDIAVLSLGDIVCSTSIKTAGNKITQDILENVRIQKKMYIGEQTADEIKRRIANALVVKEPETITISGRDVETGLPHSIDINSNEVESYIRSSLQEIVHATKTILEVTPPELAADIVQHGLVLTGGGALLKNLDQLMRNELQIPVYVAENALKCVVDGCTIMLQNL\nAt Epoch: 3000.00\nNSLPSGDQHKAQQLTADYLGALKRHLIDSLKNQLGEHHAKATPLQFILTVPAVWSDAAKEKTLQAAETAGLGQHAPILMISEPEAAATYVLFRKELGGLSTGDTFVVCDAGGGTVDLISYTIEQLEPALQVKEAAPGSGGLCGSTYLNRRFQEFLVTKLGQEEGFDNETVGDAMKKFDEEIKREYSPNVPNPNYWVPVPGLATNPRLGIRRNKMTLPPDDVREILKPVIDEVVQLVRKQIQSTEREVKAVLLVGGFGGSQYLLERLKETVTKATVILQ\nAt Epoch: 4000.00\nHIAVDIGGSLAKLVYFSRDPTSKELGGRLNFLKFETARIDECIDFLRKLKLKYEIINGSRPSDLCVMATGGGAFKYYDEIKGALEVEVVREDEMECLIIGLDFFITEIPHEVFTYSQEEPMRFIAARPNIYPYLLVNIGSGVSMVKVSGPRQYERVGGTSLGGGTLWGLLSLLTGARTFEDMLSLAERGDNTAVDMLVGDIYGSGYGKIGLKSTTIASSFGKVYKMKRQAEQEAEDTGNLKEDSSQEHGRSFKSEDISKSLLYAVSNNIGQIAYLHAEKHNLEHIYFGGSFIGGHPQTMHTLSYAIKFWSKGEKQAYFLRHEGYLGSVGAFLK\nAt Epoch: 5000.00\nQPLGSFLFLGPTGVGKTELAKALAYELFDDEKHMVRIDMSEFMEQHSVARLIGAPPGYVGYDEGGQLSEAVRRKPYSVVLFDEVEKAHPQVWNVLLQVLDDGRLTDGKGKTVDFSNVVIIMTSNLGSQYLLAEAQLETISQHVKDSVMGEVRKHFRPEFLNRLDDM\nAt Epoch: 6000.00\nVNGVSFSVEAGETLAIVGESGCGKSVTSLSIMGLIASPGTITGGEITFQGRDLVKLSRKELRKLRGNEMSMIFQEPMTSLNPVFTIGNQLAEVFRVHQGTSKAEAKQKSIDMLQRVGIANASKLVRQFPHQLSGGMRQRVMIAMALACEPKLLIADEPTT\nAt Epoch: 7000.00\nYQHEGLDWLAKLYANQTNGILADEMGLGKTIQTIALLAHLAEEHHIWGPHLIVVPTSVILNWEMEFKKFLPGFKVLSYYGSVEERAQKRKGWSNPDIWNVVITSYQLILKDLPAIRVPEWHYMILDEAHNIKNFNSQRYQAMIRLKTHARLLLTGTPLQNSIIELWSLLTFLTAGQDGQGMGDLEEFTEWFRRPVDEIFVDGKSKLGNEAQDIVNKLHHSLRPYLLRRLKSSVEKQLPGKYEHTVICRLSKRQRQLYDAFMGLSDTKAKLTSGNMISVSQALMSLRKVCNHPDLF\nAt Epoch: 8000.00\nKQKNFRQFCFPKKYEFQIPQKFLAEFINPKTPYTGILVYHRIGAGKTCTAINIAENFKNKKRIMVVLPASLKGNFRSELRSLCADNNYLSANDRQKLKELEPSSQEYREIIQKSDKLIEKYYTIYSYNKFVDLIKNNLLNLTNTLLIIDEVHNMISETGTYYESLYKIIHSSPDDLRLVIMTATPIF\nAt Epoch: 9000.00\nFVIGIGKNGVDCVLRCMHLTEKRFGKDPKKVRFLCIGEETPLGERSYEGSAPGDGFTLPIDPEEAIYKYLNNPAKLPESAQIWFDSGLKNYSPAAPTYGLTKRQCGRIALFHYLKQIMKLTGEAMADFSGSDRSLEIVITGNLGDVFCGGMFIDLPYILAKLFSDAPYPVKFTGYFFAADTASLVETDQRDVGCYQANTIVAKAELDKFQLHRKRFTQKYSRTFEVDSDKPPYSACFLIPAADSYGLTMSRTAEKILNRMEIIFSKDDDAERIISYNMLRPEAAHDFRYLAFNVMACEIPTGKIMSYLAIKLFERLNR\nAt Epoch: 10000.00\nIIKVIGVGGGGSNAVTHMYKQGIVGVDFAICNTDAQAMEMSPVPTRIHLGPDLTEGRGAGSKPNIGKLACEESIDEVRKYLENNCRMLFITAGMGGGTGTGAAPIIAKAAKEMDVLTVGIVTLPFTFEGRRRTNQGMEGLLELKKHVDTLIVISNDKLRQIHG\nAt Epoch: 11000.00\nCQAGQTGNVFWELYCLEHGIQPNGPMPSDKTIGGDDSFNTFFSVMAVDKHVPVFVDPAPMIIDGVCTGTYCQHSHPEQSNTGKEDAADNDQRHYTLDKRIINLILKPVHKSSGFLVFHSFGGGIGSRFTSLLIEWKSKLEFSINVPPPRFPQLYLSPKNIFTTQTILEHPDFAFMLNYEAS\nAt Epoch: 12000.00\nLVIGMGSTGTEILEALADRIDWEVGGLQRAPWLEFLAVETDVAKPNRFNGTDDFKTLGIPATAWRDILHRPEIHEASIALNTWADAETLAQLPAQSIDSGAGHIRMVGRLALLYPPNYSEIKNAITQRVARLRNLTDAQAKAALNVNNAGLEMDVQFAVNASTGQTGVRVIVVGTLCGGTCSGTASDIGILLRTVLEDEEKTLAMFTLPHPNLSISQKSDAEIWKTNAYHALAELNQYHLHTDTERYKTIKFPDKPEGSPVLPHDAMPYDLVYLLRPNSTENVDLMRLTQAIADRMFLNVFVPETDPMAYMVNAGPVTVQQGRAFAFSTFGLSTIEYPMRRILEALKYRTLVHAVD\nAt Epoch: 13000.00\nEVISIHVGQCGVQVGNAVWELYCAEHAVKTDGSLYEHPHDQEWVETFFNLSEKGRYVPRCLFIDLEPSVIDEIRVGPWRSLFHPDKLITGYEDAANNFARGYFTVGKVLLSPILNEVRRTIEQCDGLQGLLFFRSLGGGTGAGLTAAILDVLGDYRKYTKVEIPIYPAPSLSPAVVEPYNCIFGEHFAMEDFNMGLLMDNEALYDVCS\nAt Epoch: 14000.00\nGVAIMSTGYGEGENRVKHAIDEALHSPLLNNDDIFNSKKVLLSITFCAKDQDQLTMEEMNEINDFMTKFGEDVETKWGVATDDTLEKKVKITVLATGFG\nAt Epoch: 15000.00\nPRIHFPLATYSPLFSADKAHHEQNSVMEMTFACFENGNQMVKCDPKEGKYMACCLLYRGDVAPKETSGAVAAIKTKRTIQFVDWCPTGFKLGVCNEPAACVPGGDLAKVTRSLCMLSNTTSIASAWNRLDH\nAt Epoch: 16000.00\nGMAMMGSGFAQGIDRARLATEQAISSPFLDDVTLDGARGILVNITTAPGCLKMSEYREIMKAVNANAHPDAECKVGTAEDDSMSEDAIRVTIIATGLK\nAt Epoch: 17000.00\nGVAHMGIGVGKGENAAQDAVRAAIESPLLETSIEGAENVLLNITGGSEFSLVDMGEVSSIVRDLVSEEANIIVGTAMDDNLKDEIKVTLIATGLD\n(18000, 12)\n../../out/201027/embedding/transformer_encoder/pfamA_motors_balanced_mlm_evotune_balanced_target.npy\nloaded dict file for weights ../../data/201025/evotune_transformer_encoder_mlm_balanced_target.pt\noutput embedding for pfamA_target\nAt Epoch: 0.00\nPDSAPIVIDNGASTFRIGWAGEAEPRVSFRNIVQRPRHRSSGETVTVVGDTDPALMKYFDCTRTSIRSAFDDDVVYQFEYMEYILDYAFDRLGATSEVGHPILMTECECNPSFSRARMSELLFETYGVPSVAFGIDDVFSYKYNQKLGNCGEDGLAISCEFGTCHVVPFLKGQPVLGACCRTNVGGSHITDFLRQLLSLKYPYHVANFSWEKAEELKKEHCYIAADYMSELQIFKNNKEEAEEKTRYWQLPWVPPPRDEPPSEEELARKAAYKEKAGQRLRDMAAAKKSQKIADLEEKLSGLEDLMDHLDGADEQEATSILGRSGYLSQQEIKSDILKATQSLRKAKGESNGNEENADASGADKYPLVSVPDDMLTPEQLKEKKKQILLKTTTEGKLRAKQKRAEE\nAt Epoch: 1000.00\nFRPVIIDNGSGRIKAGFASDERPRFICPNVVGEVKHKKFFSFSESQQCYVGNDALAHRAILKLSYPIKHGVISDWNGMEKVWSSVITGLGVSLKHHPVLLTEAPLNPKAKREEVCERFFEGFDCPAFYIGIQAVMSLYSTGKITGVVVESGQGVSCSVPIYQGYAIWHAIKRLNLAGHELTEYLSKLLRERGYCFKSSAEYEIVRDMKEKHCFVALDYEEALNKAAMSDELHVSYEMPDGQIVLIGSERFRCLEALFRPSLLGLEDVGIHWMVYNSIMKSDLDIRKDLYANIVLSGGTTMHEGFQERLQAEVVALAPRTVKVRVIAKPEVWTFGSVL\nAt Epoch: 2000.00\nMKEKHCYVALDFEQESNHNIKHSYELPDGQIIEIGAEIFRAPEVLFQPMMIGLEQSGIHEMAFNSIFKSDLEIRRDLYGNVVLSGGTSMLPGIADRLQKELMHLIPPNMMAMVVAPSERKNSTWTGGSMLASLSTFQERWIPKEAYDETGPGIVHRYCF\nAt Epoch: 3000.00\nLGIQRRSVLEHGLVADWDVMEEYWCHLFNRRVCVEPQDVGVLLTEPAVTPYEQRERTAEILFESFGVPKLFIGSQALFLLHSVGDRCDTAVVVESGAGVTQVVPIVAGYAVAAAARRFPVAGLDVTQYVLNNLREHEQGIEMEQALEVAEQVKVRYGCMAKDFARECAEAESKLPSYAIRNTELHTRAGAPYSIDVDYEQLLVPETLFQPDSLAAPSTVTASLFGGLPAVIDAVVWSCPMDCRRSLYANVIVSGGNTRLPYFAKRLHGALRHALDERATGVIAASGGPLGRQVEYEVNVRDYSQAMHAVWRGASAFAASPEYETSAVTRAAYMECGAAVMHQHH\nAt Epoch: 4000.00\nARLAPLVIDNGTGYSSQETQILRSSFRTAIATRGTSGGGSASGPSITGRPSIPSKPGALSASSNIATKRGIDDLDFFIGDEAIANSKTYNVSYPIRHGQIEDWDLMERYWQQTIFKYLRAEPEDHHVLLTEPPMNAPENREQTAEIMFEGLNIQGLYIAVQAVLALAASWSSNKVTDRTLTGTVIDSGDGVTHVIPVAEGYVIGSSIKHIPIAGRDITYFVQQLLRDRNESLNIPVDESLRIAEKIKEDYGYVCGDMVKEFRKYDSEPEKYIIKHEGFDTRTNKAYTIDVGYERFLAAEVFFNPEIYSSDFLTPLPEVVDNVIQTSPIDVRRGLYKNIVLSGGSTMYDHFGRRLQRDLKTIVDDRLYASEVASGGLIKSSGMDVNVITHKRQRYAVWFGGSLMASTPEFYSHCHSKADYMEYGPSICRRYQ\nAt Epoch: 5000.00\nSQDRKVVVCDNGTGFVKCGCAGPNFPEHIFPALVRRTVIRSTTKDLMVGDEASELRLMLEVNYPVGNGIVRNWNDMKHLWDYTFGAEKLIPKFVYVAIQTVL\nAt Epoch: 6000.00\nMMKLVQNKAAYVALNIQQELELAKKIPSPVNEEYELPCGHFMNFRSQKFRNPEALFQPSSARFVKDRENVGVRKMIFNSIMKCDIGIRNYLFKNIMLTVGSTLFPGFVEGITKEILELGSSTLAFKFSDLIAREINHKFANKMFRNVAPPNRMYNAGVGGPALALLNTFEQASPFKTQFY\nAt Epoch: 7000.00\nMTEQHNIHLNTSYQLPDGHVIRIGSERFRCPEALFQPLLLRCLWSHVEMFVVSIMKCDLDMRRKLYENIILSGGSTMFPGMGQRMTKELRVLVVWSRPVPLYSSWL\nAt Epoch: 8000.00\nVGLDIGTTKICAIVGRKNEFGKLEVLGMGKAESEGVVKGIVFNIDKTVYAIEKAIKDAGDQAGIDIGVVNVGIAGQHIRSFIQHGGITRTSKEDEITIADVERLTQDMYRMVVPPGSQIIHVMPQDYMVDYEEGIKEPVGMSGVRLEADFHIITAQTNAINNINKCVRRTGLEIDDLILEPLASSLAV\nAt Epoch: 9000.00\nALIDVGAGTSDICVTRDGSIIAYGMIPMAGDELTEVLVHEFLVDFATAEQIKRASTEGGNITYEDIMGISHTIKSEDVYKLTDPVMKKISGEVASKIKELNGDKSVSAAFVVGGGGKIHGFTEALSKDLDIVSERVALRGEEVMKNIVFEQNDIQKDSLLVTPIG\nAt Epoch: 10000.00\nTVIDLGYNSSRTIIFKDGIPKLFYSFPYGIKYILKDISNVLKVSEKEAHRLLTEEGACLRDTRTIKKVEFQPITGTGYSYTSLGLLNKIIYARVREIISRLNGELSRISYEKTYEIGALQGGIVLTGGGSKIRNIDQTIRELMGENYRKSSLVSLDYFRDVPEEIKKDSTYLSVFG\nAt Epoch: 11000.00\nACIDMGGGVTGVSLFLKKHMLFADAVRMGGDLVTRDISQGLRVPLPVAEWLKTRHGGLEATGRDDREMIDVTGEPGEDWDGERRFVSRADLIGIMRPRVEEILDGVREILEAAGFDQMPSRQVVLTGGASQIPGLDTLAMRILGYNVRIGRPLRIQGLAQQHTASCHAATVGLA\nAt Epoch: 12000.00\nEAKRVAAQFAFSSDDVRRATKEFINQMEEGLQKDHTDLSQIPTYVTAVPNGTEKGLYMAVDLGGTNFRVCSIMLHGNSTFTLTQTKVAIPRELMVAKTSKELFSFLAKQIELFLKAHHNEHYQGHIRRRKTTSLEEGYRDEEIFNLGFTFSFPVHQIGINKGVLMRWTKGFDIPDAVGKDVCALLQAEIDELHLPVRVAALVNDTVGTLMARSY\nAt Epoch: 13000.00\nKVENMLSGIHLSEEVVSRVKSVFLSEIELGINEEPSSLQMENTYVPELPDGTEEGLFLALDVGGTNFRVLLLELMEGRLVREEVKHYHITDELRLGPGIDLFDFLATCIADFVKEFNIADQTLPLGFTFSFPMHQRSMDCGCLVTWTKSFKCAGVQGEDVVEMLREAIRRRGDIKVDVVAVLNDTTGTLMQGAL\nAt Epoch: 14000.00\nAGLLKKFEAPLADVPGIARAFEVIYHSLALTASNQFLPTPIRALPTGEEKGRFLALDLGGTNLRVAVVRLYGGDGLKVCTQRSWSIPEHFKSGAAEVLFRWVADRIGDVVGEYLGDVGSEERERILSEGMELGITFSFPMEQTTHDSALLMPMGKGFTFTTTNDLSSLLKMAYDDLLSTTTPAHPLPKLDIVSITNDSISTLLSAAY\nAt Epoch: 15000.00\nVMGLLLGAGCNATVPMLIDDLHESKVRHIRLADPKAVETLVTTEWTLRAASEPLSNLNLITSWDSQLNASGDRPGFQPLEYMIAGRYLGELVRIIVHDYFHRILAISKEDLPDKLMKPYALTTEFLSLVVAPSQSGEELLADLERELPSPPLSGWKWTPSLADIVRATTTKIQRRAASLIAAASVGLLACTREIKLADLKEGKSVAETPVVCPSAVPTADPIALPHRSPGSNSPPKVKGQNNPEELVIAFSGGLIQHWPGFRESIQWHIDRLVLRGGPQELGKSIFLREVSDGGLVGVGVLAGT\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb09c8b61017a3c136ece496995c8df271f6f1f8
9,798
ipynb
Jupyter Notebook
eunice012716/Week3/ch8/8.3/example_ch8_3.ipynb
Sinica-SLAM/Intern-Training
da12b20890114efed7a1d37f867ba43e66837572
[ "MIT" ]
1
2021-08-24T12:14:46.000Z
2021-08-24T12:14:46.000Z
eunice012716/Week3/ch8/8.3/example_ch8_3.ipynb
Sinica-SLAM/Intern-Training
da12b20890114efed7a1d37f867ba43e66837572
[ "MIT" ]
14
2021-07-09T07:48:35.000Z
2021-08-19T03:06:31.000Z
eunice012716/Week3/ch8/8.3/example_ch8_3.ipynb
Sinica-SLAM/Intern-Training
da12b20890114efed7a1d37f867ba43e66837572
[ "MIT" ]
11
2021-07-09T07:35:24.000Z
2021-08-15T07:19:43.000Z
31.203822
92
0.494182
[ [ [ "# 8.3.3. Natural Language Statistics\nimport random\nimport torch\nfrom d2l import torch as d2l\n\ntokens = d2l.tokenize(d2l.read_time_machine())\n# Since each text line is not necessarily a sentence or a paragraph, we\n# concatenate all text lines\ncorpus = [token for line in tokens for token in line]\nvocab = d2l.Vocab(corpus)\nvocab.token_freqs[:10]", "_____no_output_____" ], [ "freqs = [freq for token, freq in vocab.token_freqs]\nd2l.plot(freqs, xlabel='token: x', ylabel='frequency: n(x)', xscale='log',\n yscale='log')", "_____no_output_____" ], [ "bigram_tokens = [pair for pair in zip(corpus[:-1], corpus[1:])]\nbigram_vocab = d2l.Vocab(bigram_tokens)\nbigram_vocab.token_freqs[:10]", "_____no_output_____" ], [ "trigram_tokens = [\n triple for triple in zip(corpus[:-2], corpus[1:-1], corpus[2:])]\ntrigram_vocab = d2l.Vocab(trigram_tokens)\ntrigram_vocab.token_freqs[:10]", "_____no_output_____" ], [ "bigram_freqs = [freq for token, freq in bigram_vocab.token_freqs]\ntrigram_freqs = [freq for token, freq in trigram_vocab.token_freqs]\nd2l.plot([freqs, bigram_freqs, trigram_freqs], xlabel='token: x',\n ylabel='frequency: n(x)', xscale='log', yscale='log',\n legend=['unigram', 'bigram', 'trigram'])", "_____no_output_____" ], [ "# 8.3.4. Reading Long Sequence Data\n# 8.3.4.1. Random Sampling\ndef seq_data_iter_random(corpus, batch_size, num_steps): #@save\n \"\"\"Generate a minibatch of subsequences using random sampling.\"\"\"\n # Start with a random offset (inclusive of `num_steps - 1`) to partition a\n # sequence\n corpus = corpus[random.randint(0, num_steps - 1):]\n # Subtract 1 since we need to account for labels\n num_subseqs = (len(corpus) - 1) // num_steps\n # The starting indices for subsequences of length `num_steps`\n initial_indices = list(range(0, num_subseqs * num_steps, num_steps))\n # In random sampling, the subsequences from two adjacent random\n # minibatches during iteration are not necessarily adjacent on the\n # original sequence\n random.shuffle(initial_indices)\n\n def data(pos):\n # Return a sequence of length `num_steps` starting from `pos`\n return corpus[pos:pos + num_steps]\n\n num_batches = num_subseqs // batch_size\n for i in range(0, batch_size * num_batches, batch_size):\n # Here, `initial_indices` contains randomized starting indices for\n # subsequences\n initial_indices_per_batch = initial_indices[i:i + batch_size]\n X = [data(j) for j in initial_indices_per_batch]\n Y = [data(j + 1) for j in initial_indices_per_batch]\n yield torch.tensor(X), torch.tensor(Y)", "_____no_output_____" ], [ "my_seq = list(range(35))\nfor X, Y in seq_data_iter_random(my_seq, batch_size=2, num_steps=5):\n print('X: ', X, '\\nY:', Y)", "X: tensor([[20, 21, 22, 23, 24],\n [25, 26, 27, 28, 29]]) \nY: tensor([[21, 22, 23, 24, 25],\n [26, 27, 28, 29, 30]])\nX: tensor([[15, 16, 17, 18, 19],\n [10, 11, 12, 13, 14]]) \nY: tensor([[16, 17, 18, 19, 20],\n [11, 12, 13, 14, 15]])\nX: tensor([[5, 6, 7, 8, 9],\n [0, 1, 2, 3, 4]]) \nY: tensor([[ 6, 7, 8, 9, 10],\n [ 1, 2, 3, 4, 5]])\n" ], [ "# 8.3.4.2. Sequential Partitioning\ndef seq_data_iter_sequential(corpus, batch_size, num_steps): #@save\n \"\"\"Generate a minibatch of subsequences using sequential partitioning.\"\"\"\n # Start with a random offset to partition a sequence\n offset = random.randint(0, num_steps)\n num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size\n Xs = torch.tensor(corpus[offset:offset + num_tokens])\n Ys = torch.tensor(corpus[offset + 1:offset + 1 + num_tokens])\n Xs, Ys = Xs.reshape(batch_size, -1), Ys.reshape(batch_size, -1)\n num_batches = Xs.shape[1] // num_steps\n for i in range(0, num_steps * num_batches, num_steps):\n X = Xs[:, i:i + num_steps]\n Y = Ys[:, i:i + num_steps]\n yield X, Y", "_____no_output_____" ], [ "for X, Y in seq_data_iter_sequential(my_seq, batch_size=2, num_steps=5):\n print('X: ', X, '\\nY:', Y)", "X: tensor([[ 4, 5, 6, 7, 8],\n [19, 20, 21, 22, 23]]) \nY: tensor([[ 5, 6, 7, 8, 9],\n [20, 21, 22, 23, 24]])\nX: tensor([[ 9, 10, 11, 12, 13],\n [24, 25, 26, 27, 28]]) \nY: tensor([[10, 11, 12, 13, 14],\n [25, 26, 27, 28, 29]])\nX: tensor([[14, 15, 16, 17, 18],\n [29, 30, 31, 32, 33]]) \nY: tensor([[15, 16, 17, 18, 19],\n [30, 31, 32, 33, 34]])\n" ], [ "class SeqDataLoader: #@save\n \"\"\"An iterator to load sequence data.\"\"\"\n def __init__(self, batch_size, num_steps, use_random_iter, max_tokens):\n if use_random_iter:\n self.data_iter_fn = d2l.seq_data_iter_random\n else:\n self.data_iter_fn = d2l.seq_data_iter_sequential\n self.corpus, self.vocab = d2l.load_corpus_time_machine(max_tokens)\n self.batch_size, self.num_steps = batch_size, num_steps\n\n def __iter__(self):\n return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps)", "_____no_output_____" ], [ "def load_data_time_machine(batch_size, num_steps, #@save\n use_random_iter=False, max_tokens=10000):\n \"\"\"Return the iterator and the vocabulary of the time machine dataset.\"\"\"\n data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter,\n max_tokens)\n return data_iter, data_iter.vocab", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb09dd0926397c700a832a7de82964b35021513b
259,424
ipynb
Jupyter Notebook
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
fdaebe0c14232bd9ad3a2dba0de7dcf499cd2cf1
[ "BSD-3-Clause" ]
180
2019-02-02T13:00:19.000Z
2022-03-31T07:06:22.000Z
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
fdaebe0c14232bd9ad3a2dba0de7dcf499cd2cf1
[ "BSD-3-Clause" ]
25
2019-01-20T05:12:26.000Z
2021-05-17T04:26:08.000Z
notebooks/7.3_application_of_HHL_algorithm.ipynb
Hiroya-W/quantum-native-dojo
fdaebe0c14232bd9ad3a2dba0de7dcf499cd2cf1
[ "BSD-3-Clause" ]
64
2019-02-04T05:10:15.000Z
2022-03-07T01:52:17.000Z
184.380952
80,892
0.88422
[ [ [ "## 7-3. HHLアルゴリズムを用いたポートフォリオ最適化\nこの節では論文[1]を参考に、過去の株価変動のデータから、最適なポートフォリオ(資産配分)を計算してみよう。\nポートフォリオ最適化は、[7-1節](7.1_quantum_phase_estimation_detailed.ipynb)で学んだHHLアルゴリズムを用いることで、従来より高速に解けることが期待されている問題の一つである。\n今回は具体的に、GAFA (Google, Apple, Facebook, Amazon) の4社の株式に投資する際、どのような資産配分を行えば最も低いリスクで高いリターンを得られるかという問題を考える。", "_____no_output_____" ], [ "### 株価データ取得\nまずは各社の株価データを取得する。\n\n* GAFA 4社の日次データを用いる\n* 株価データ取得のためにpandas_datareaderを用いてYahoo! Financeのデータベースから取得\n* 株価はドル建ての調整後終値(Adj. Close)を用いる", "_____no_output_____" ] ], [ [ "# データ取得に必要なpandas, pandas_datareaderのインストール\n# !pip install pandas pandas_datareader", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport pandas_datareader.data as web\nimport datetime\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "# 銘柄選択\ncodes = ['GOOG', 'AAPL', 'FB', 'AMZN'] # GAFA\n\n# 2017年の1年間のデータを使用\nstart = datetime.datetime(2017, 1, 1)\nend = datetime.datetime(2017, 12, 31)\n\n# Yahoo! Financeから日次の株価データを取得\ndata = web.DataReader(codes, 'yahoo', start, end)\n\ndf = data['Adj Close'] \n\n## 直近のデータの表示\ndisplay(df.tail())", "_____no_output_____" ], [ "## 株価をプロットしてみる\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))\ndf.loc[:,['AAPL', 'FB']].plot(ax=axes[0])\ndf.loc[:,['GOOG', 'AMZN']].plot(ax=axes[1])", "_____no_output_____" ] ], [ [ "※ここで、4つの銘柄を2つのグループに分けているのは、株価の値がそれぞれ近くプロット時に見やすいからであり、深い意味はない。\n\n### データの前処理\n次に、取得した株価を日次リターンに変換し、いくつかの統計量を求めておく。\n\n#### 日次リターンへの変換\n個別銘柄の日次リターン(変化率) $y_t$ ($t$は日付)は以下で定義される。 \n\n$$\ny_t = \\frac{P_t - P_{t-1}}{P_{t-1}}\n$$\n\nこれは `pandas DataFrame` の `pct_change()` メソッドで得られる。", "_____no_output_____" ] ], [ [ "daily_return = df.pct_change()\ndisplay(daily_return.tail())", "_____no_output_____" ] ], [ [ "#### 期待リターン\n銘柄ごとの期待リターン$\\vec R$を求める。ここでは過去のリターンの算術平均を用いる:\n\n$$\n\\vec R = \\frac{1}{T} \\sum_{t= 1}^{T} \\vec y_t\n$$", "_____no_output_____" ] ], [ [ "expected_return = daily_return.dropna(how='all').mean() * 252 # 年率換算のため年間の営業日数252を掛ける\nprint(expected_return)", "Symbols\nGOOG 0.300215\nAAPL 0.411192\nFB 0.430156\nAMZN 0.464567\ndtype: float64\n" ] ], [ [ "#### 分散・共分散行列\nリターンの標本不偏分散・共分散行列$\\Sigma$は以下で定義される。\n\n$$\n\\Sigma = \\frac{1}{T-1} \\sum_{t=1}^{T} ( \\vec y_t -\\vec R ) (\\vec y_t -\\vec R )^T\n$$", "_____no_output_____" ] ], [ [ "cov = daily_return.dropna(how='all').cov() * 252 # 年率換算のため\ndisplay(cov)", "_____no_output_____" ] ], [ [ "### ポートフォリオ最適化\n準備が整ったところで、ポートフォリオ最適化に取り組もう。\n\nまず、ポートフォリオ(i.e., 資産配分)を4成分のベクトル $\\vec{w} = (w_0,w_1,w_2,w_3)^T$ で表す。\nこれは各銘柄を持つ割合(ウェイト)を表しており、例えば $\\vec{w}=(1,0,0,0)$ であれば Google 株に全資産の100%を投入しするポートフォリオを意味する。\n\n以下の式を満たすようなポートフォリオを考えてみよう。\n\n$$\n\\min_{\\vec{w}} \\frac{1}{2} \\vec{w}^T \\Sigma \\vec{w} \\:\\:\\: \\text{s.t.} \\:\\: \\vec R^T \\vec w = \\mu , \\: \\vec 1^T \\vec w =1\n$$\n\nこの式は\n\n* 「ポートフォリオの期待リターン(リターンの平均値)が$\\mu$ 」\n* 「ポートフォリオに投資するウェイトの合計が1」($\\vec 1 = (1,1,1,1)^T$)\n\nという条件の下で、\n\n* 「ポートフォリオのリターンの分散の最小化」\n\nを行うことを意味している。つまり、将来的に $\\mu$ だけのリターンを望む時に、なるべくその変動(リスク)を小さくするようなポートフォリオが最善だというわけである。このような問題設定は、[Markowitzの平均分散アプローチ](https://ja.wikipedia.org/wiki/現代ポートフォリオ理論)と呼ばれ、現代の金融工学の基礎となる考えの一つである。\n\nラグランジュの未定乗数法を用いると、上記の条件を満たす$\\vec{w}$は、線形方程式\n\n$$\n\\begin{gather}\nW\n\\left( \n\\begin{array}{c}\n\\eta \\\\\n\\theta \\\\\n\\vec w\n\\end{array}\n\\right)\n=\n\\left( \n\\begin{array}{c}\n \\mu \\\\\n 1 \\\\\n\\vec 0\n\\end{array}\n\\right), \\tag{1}\\\\\nW =\n\\left( \n\\begin{array}{ccc}\n0 & 0 & \\vec R^T \\\\\n0 & 0 & \\vec 1^T \\\\\n\\vec{R} &\\vec 1 & \\Sigma \n\\end{array}\n\\right) \n\\end{gather}\n$$\n\nを解くことで得られる事がわかる。\nここで $\\eta, \\theta$ はラグランジュの未定乗数法のパラメータである。\nしたがって、最適なポートフォリオ $\\vec w$ を求めるためには、連立方程式(1)を $\\vec w$ について解けば良いことになる。\nこれで、ポートフォリオ最適化問題をHHLアルゴリズムが使える線形一次方程式に帰着できた。\n\n#### 行列Wの作成", "_____no_output_____" ] ], [ [ "R = expected_return.values\nPi = np.ones(4)\nS = cov.values\n\nrow1 = np.append(np.zeros(2), R).reshape(1,-1)\nrow2 = np.append(np.zeros(2), Pi).reshape(1,-1)\nrow3 = np.concatenate([R.reshape(-1,1), Pi.reshape(-1,1), S], axis=1)\nW = np.concatenate([row1, row2, row3])\n\nnp.set_printoptions(linewidth=200)\nprint(W)", "[[0. 0. 0.30021458 0.41119151 0.43015563 0.46456748]\n [0. 0. 1. 1. 1. 1. ]\n [0.30021458 1. 0.02369003 0.01330333 0.01838175 0.0216144 ]\n [0.41119151 1. 0.01330333 0.03111917 0.01629131 0.01887668]\n [0.43015563 1. 0.01838175 0.01629131 0.02885482 0.02333747]\n [0.46456748 1. 0.0216144 0.01887668 0.02333747 0.04412049]]\n" ], [ "## Wの固有値を確認 -> [-pi, pi] に収まっている\nprint(np.linalg.eigh(W)[0])", "[-2.11207187 -0.10947986 0.01121933 0.01864265 0.11919724 2.20027702]\n" ] ], [ [ "#### 右辺ベクトルの作成\n以下でポートフォリオの期待リターン $\\mu$ を指定すると、そのようなリターンをもたらす最もリスクの小さいポートフォリオを計算できる。$\\mu$ は自由に設定できる。一般に期待リターンが大きいほどリスクも大きくなるが、ここでは例として10%としておく(GAFA株がガンガン上がっている時期なので、これはかなり弱気な方である)。", "_____no_output_____" ] ], [ [ "mu = 0.1 # ポートフォリオのリターン(手で入れるパラメータ)\nxi = 1.0 \nmu_xi_0 = np.append(np.array([mu, xi]), np.zeros_like(R)) ## (1)式の右辺のベクトル\nprint(mu_xi_0)", "[0.1 1. 0. 0. 0. 0. ]\n" ] ], [ [ "#### 量子系で扱えるように行列を拡張する\n$W$ は6次元なので、3量子ビットあれば量子系で計算可能である ($2^3 = 8$)。\nそこで、拡張した2次元分を0で埋めた行列とベクトルも作っておく。", "_____no_output_____" ] ], [ [ "nbit = 3 ## 状態に使うビット数\nN = 2**nbit\n\nW_enl = np.zeros((N, N)) ## enl は enlarged の略\nW_enl[:W.shape[0], :W.shape[1]] = W.copy()\nmu_xi_0_enl = np.zeros(N)\nmu_xi_0_enl[:len(mu_xi_0)] = mu_xi_0.copy()", "_____no_output_____" ] ], [ [ "以上で、連立方程式(1)を解く準備が整った。\n\n### HHLアルゴリズムを用いた最小分散ポートフォリオ算出\nそれでは、HHL アルゴリズムを用いて、連立一次方程式(1)を解いていこう。\n先ずはその下準備として、\n\n* 古典データ $\\mathbf{x}$ に応じて、量子状態を $|0\\cdots0\\rangle \\to \\sum_i x_i |i \\rangle$ と変換する量子回路を返す関数 `input_state_gate` (本来は qRAM の考え方を利用して作るべきだが、シミュレータを使っているので今回は non-unitary なゲートとして実装してしまう。また、規格化は無視している)\n* 制御位相ゲートを返す関数 `CPhaseGate`\n* 量子フーリエ変換を行うゲートを返す関数 `QFT_gate` \n\nを用意する。", "_____no_output_____" ] ], [ [ "# Qulacs のインストール\n# !pip install qulacs\n\n## Google Colaboratory / (Linux or Mac)のjupyter notebook 環境の場合にのみ実行してください。\n## Qulacsのエラーが正常に出力されるようになります。\n!pip3 install wurlitzer\n%load_ext wurlitzer", "_____no_output_____" ], [ "import numpy as np\nfrom qulacs import QuantumCircuit, QuantumState, gate\nfrom qulacs.gate import merge, Identity, H, SWAP\n\ndef input_state_gate(start_bit, end_bit, vec):\n \"\"\" \n Making a quantum gate which transform |0> to \\sum_i x[i]|i>m where x[i] is input vector.\n !!! this uses 2**n times 2**n matrix, so it is quite memory-cosuming.\n !!! this gate is not unitary (we assume that the input state is |0>)\n Args:\n int start_bit: first index of qubit which the gate applies \n int end_bit: last index of qubit which the gate applies\n np.ndarray vec: input vector.\n Returns:\n qulacs.QuantumGate \n \"\"\"\n nbit = end_bit - start_bit + 1\n assert vec.size == 2**nbit\n mat_0tox = np.eye(vec.size, dtype=complex)\n mat_0tox[:,0] = vec\n return gate.DenseMatrix(np.arange(start_bit, end_bit+1), mat_0tox)\n\n\ndef CPhaseGate(target, control, angle):\n \"\"\" \n Create controlled phase gate diag(1,e^{i*angle}) with controll. (Qulacs.gate is requried)\n\n Args:\n int target: index of target qubit.\n int control: index of control qubit.\n float64 angle: angle of phase gate.\n Returns:\n QuantumGateBase.DenseMatrix: diag(1, exp(i*angle)).\n \"\"\"\n CPhaseGate = gate.DenseMatrix(target, np.array( [[1,0], [0,np.cos(angle)+1.j*np.sin(angle)]]) )\n CPhaseGate.add_control_qubit(control, 1)\n return CPhaseGate\n\ndef QFT_gate(start_bit, end_bit, Inverse = False):\n \"\"\" \n Making a gate which performs quantum Fourier transfromation between start_bit to end_bit.\n (Definition below is the case when start_bit = 0 and end_bit=n-1)\n We associate an integer j = j_{n-1}...j_0 to quantum state |j_{n-1}...j_0>.\n We define QFT as\n |k> = |k_{n-1}...k_0> = 1/sqrt(2^n) sum_{j=0}^{2^n-1} exp(2pi*i*(k/2^n)*j) |j>.\n then, |k_m > = 1/sqrt(2)*(|0> + exp(i*2pi*0.j_{n-1-m}...j_0)|1> )\n When Inverse=True, the gate represents Inverse QFT,\n |k> = |k_{n-1}...k_0> = 1/sqrt(2^n) sum_{j=0}^{2^n-1} exp(-2pi*i*(k/2^n)*j) |j>.\n\n Args:\n int start_bit: first index of qubits where we apply QFT.\n int end_bit: last index of qubits where we apply QFT.\n bool Inverse: When True, the gate perform inverse-QFT ( = QFT^{\\dagger}).\n Returns:\n qulacs.QuantumGate: QFT gate which acts on a region between start_bit and end_bit.\n \"\"\"\n\n gate = Identity(start_bit) ## make empty gate\n n = end_bit - start_bit + 1 ## size of QFT\n\n ## loop from j_{n-1} \n for target in range(end_bit, start_bit-1, -1):\n gate = merge(gate, H(target)) ## 1/sqrt(2)(|0> + exp(i*2pi*0.j_{target})|1>)\n for control in range(start_bit, target):\n gate = merge( gate, CPhaseGate(target, control, (-1)**Inverse * 2.*np.pi/2**(target-control+1)) )\n ## perform SWAP between (start_bit + s)-th bit and (end_bit - s)-th bit\n for s in range(n//2): ## s runs 0 to n//2-1\n gate = merge(gate, SWAP(start_bit + s, end_bit - s))\n ## return final circuit\n return gate", "_____no_output_____" ] ], [ [ "まずはHHLアルゴリズムに必要なパラメータを設定する。\nクロックレジスタ量子ビット数 `reg_nbit`を `7` とし、行列 $W$ のスケーリングに使う係数 `scale_fac` を`1` とする(つまり、スケールさせない)。\nまた、制御回転ゲートに使う係数 $c$ は、`reg_nbit` ビットで表せる非ゼロの最も小さい数の半分にとっておく。", "_____no_output_____" ] ], [ [ "# 位相推定に使うレジスタの数\nreg_nbit = 7\n\n## W_enl をスケールする係数\nscale_fac = 1.\nW_enl_scaled = scale_fac * W_enl\n\n## W_enl_scaledの固有値として想定する最小の値\n## 今回は射影が100%成功するので, レジスタで表せる最小値の定数倍でとっておく\nC = 0.5*(2 * np.pi * (1. / 2**(reg_nbit) ))", "_____no_output_____" ] ], [ [ "HHLアルゴリズムの核心部分を書いていく。今回は、シミュレータ qulacs を使うので様々な簡略化を行なっている。\nHHLアルゴリズムがどのように動作するのかについての感覚を知る実装と思っていただきたい。\n\n* 入力状態 $|\\mathbf{b}\\rangle$ を用意する部分は簡略化\n* 量子位相推定アルゴリズムで使う $e^{iA}$ の部分は、 $A$ を古典計算機で対角化したものを使う\n* 逆数をとる制御回転ゲートも、古典的に行列を用意して実装\n* 補助ビット $|0 \\rangle{}_{S}$ への射影測定を行い、測定結果 `0` が得られた状態のみを扱う\n(実装の都合上、制御回転ゲートの作用の定義を[7-1節](7.1_quantum_phase_estimation_detailed.ipynb)と逆にした)", "_____no_output_____" ] ], [ [ "from functools import reduce\n\n## 対角化. AP = PD <-> A = P*D*P^dag \nD, P = np.linalg.eigh(W_enl_scaled)\n\n#####################################\n### HHL量子回路を作る. 0番目のビットから順に、Aの作用する空間のbit達 (0番目 ~ nbit-1番目), \n### register bit達 (nbit番目 ~ nbit+reg_nbit-1番目), conditional回転用のbit (nbit+reg_nbit番目)\n### とする.\n#####################################\ntotal_qubits = nbit + reg_nbit + 1\ntotal_circuit = QuantumCircuit(total_qubits)\n\n## ------ 0番目~(nbit-1)番目のbitに入力するベクトルbの準備 ------\n## 本来はqRAMのアルゴリズムを用いるべきだが, ここでは自作の入力ゲートを用いている. \n## qulacsではstate.load(b_enl)でも実装可能.\nstate = QuantumState(total_qubits)\nstate.set_zero_state() \nb_gate = input_state_gate(0, nbit-1, mu_xi_0_enl)\ntotal_circuit.add_gate(b_gate)\n\n## ------- レジスターbit に Hadamard gate をかける -------\nfor register in range(nbit, nbit+reg_nbit): ## from nbit to nbit+reg_nbit-1\n total_circuit.add_H_gate(register)\n\n## ------- 位相推定を実装 -------\n## U := e^{i*A*t), その固有値をdiag( {e^{i*2pi*phi_k}}_{k=0, ..., N-1) )とおく.\n## Implement \\sum_j |j><j| exp(i*A*t*j) to register bits\nfor register in range(nbit, nbit+reg_nbit):\n ## U^{2^{register-nbit}} を実装.\n ## 対角化した結果を使ってしまう\n U_mat = reduce(np.dot, [P, np.diag(np.exp( 1.j * D * (2**(register-nbit)) )), P.T.conj()] )\n U_gate = gate.DenseMatrix(np.arange(nbit), U_mat)\n U_gate.add_control_qubit(register, 1) ## control bitの追加\n total_circuit.add_gate(U_gate)\n\n## ------- Perform inverse QFT to register bits -------\ntotal_circuit.add_gate(QFT_gate(nbit, nbit+reg_nbit-1, Inverse=True))\n\n## ------- conditional rotation を掛ける -------\n## レジスター |phi> に対応するA*tの固有値は l = 2pi * 0.phi = 2pi * (phi / 2**reg_nbit).\n## conditional rotationの定義は (本文と逆)\n## |phi>|0> -> C/(lambda)|phi>|0> + sqrt(1 - C^2/(lambda)^2)|phi>|1>.\n## 古典シミュレーションなのでゲートをあらわに作ってしまう.\ncondrot_mat = np.zeros( (2**(reg_nbit+1), (2**(reg_nbit+1))), dtype=complex)\nfor index in range(2**reg_nbit):\n lam = 2 * np.pi * (float(index) / 2**(reg_nbit) )\n index_0 = index ## integer which represents |index>|0>\n index_1 = index + 2**reg_nbit ## integer which represents |index>|1>\n if lam >= C:\n if lam >= np.pi: ## あらかじめ[-pi, pi]内に固有値をスケールしているので、[pi, 2pi] は 負の固有値に対応\n lam = lam - 2*np.pi\n condrot_mat[index_0, index_0] = C / lam\n condrot_mat[index_1, index_0] = np.sqrt( 1 - C**2/lam**2 )\n condrot_mat[index_0, index_1] = - np.sqrt( 1 - C**2/lam**2 )\n condrot_mat[index_1, index_1] = C / lam\n\n else:\n condrot_mat[index_0, index_0] = 1.\n condrot_mat[index_1, index_1] = 1.\n## DenseGateに変換して実装\ncondrot_gate = gate.DenseMatrix(np.arange(nbit, nbit+reg_nbit+1), condrot_mat) \ntotal_circuit.add_gate(condrot_gate)\n\n## ------- Perform QFT to register bits -------\ntotal_circuit.add_gate(QFT_gate(nbit, nbit+reg_nbit-1, Inverse=False))\n\n## ------- 位相推定の逆を実装(U^\\dagger = e^{-iAt}) -------\nfor register in range(nbit, nbit+reg_nbit): ## from nbit to nbit+reg_nbit-1\n ## {U^{\\dagger}}^{2^{register-nbit}} を実装.\n ## 対角化した結果を使ってしまう\n U_mat = reduce(np.dot, [P, np.diag(np.exp( -1.j* D * (2**(register-nbit)) )), P.T.conj()] )\n U_gate = gate.DenseMatrix(np.arange(nbit), U_mat)\n U_gate.add_control_qubit(register, 1) ## control bitの追加\n total_circuit.add_gate(U_gate)\n\n## ------- レジスターbit に Hadamard gate をかける -------\nfor register in range(nbit, nbit+reg_nbit): \n total_circuit.add_H_gate(register)\n\n## ------- 補助ビットを0に射影する. qulacsでは非ユニタリゲートとして実装されている -------\ntotal_circuit.add_P0_gate(nbit+reg_nbit)\n\n#####################################\n### HHL量子回路を実行し, 結果を取り出す\n#####################################\ntotal_circuit.update_quantum_state(state)\n\n## 0番目から(nbit-1)番目の bit が計算結果 |x>に対応\nresult = state.get_vector()[:2**nbit].real\nx_HHL = result/C * scale_fac", "_____no_output_____" ] ], [ [ "HHL アルゴリズムによる解 `x_HHL` と、通常の古典計算の対角化による解 `x_exact` を比べると、概ね一致していることが分かる。(HHLアルゴリズムの精度を決めるパラメータはいくつかある(例えば`reg_nbit`)ので、それらを変えて色々試してみて頂きたい。)", "_____no_output_____" ] ], [ [ "## 厳密解\nx_exact = np.linalg.lstsq(W_enl, mu_xi_0_enl, rcond=0)[0]\n\nprint(\"HHL: \", x_HHL)\nprint(\"exact:\", x_exact)\nrel_error = np.linalg.norm(x_HHL- x_exact) / np.linalg.norm(x_exact)\nprint(\"rel_error\", rel_error)", "HHL: [ 0.09580738 -0.04980738 2.36660125 0.09900883 -0.47774813 -0.98438791 0. 0. ]\nexact: [ 0.15426894 -0.07338059 2.29996915 0.17711988 -0.66526695 -0.81182208 0. 0. ]\nrel_error 0.11097291393510306\n" ] ], [ [ "実際のウェイトの部分だけ取り出すと", "_____no_output_____" ] ], [ [ "w_opt_HHL = x_HHL[2:6] \nw_opt_exact = x_exact[2:6] \nw_opt = pd.DataFrame(np.vstack([w_opt_exact, w_opt_HHL]).T, index=df.columns, columns=['exact', 'HHL'])\nw_opt", "_____no_output_____" ], [ "w_opt.plot.bar()", "_____no_output_____" ] ], [ [ "※重みが負になっている銘柄は、「空売り」(株を借りてきて売ること。株価が下がる局面で利益が得られる手法)を表す。今回は目標リターンが10%と、GAFA株(単独で30〜40%の期待リターン)にしてはかなり小さい値を設定したため、空売りを行って全体の期待リターンを下げていると思われる。\n\n### Appendix: バックテスト\n過去のデータから得られた投資ルールを、それ以降のデータを用いて検証することを「バックテスト」と呼び、その投資ルールの有効性を測るために重要である。\nここでは以上のように2017年のデータから構築したポートフォリオに投資した場合に、翌年の2018年にどの程度資産価値が変化するかを観察する。", "_____no_output_____" ] ], [ [ "# 2018年の1年間のデータを使用\nstart = datetime.datetime(2017, 12, 30)\nend = datetime.datetime(2018, 12, 31)\n\n# Yahoo! Financeから日次の株価データを取得\ndata = web.DataReader(codes, 'yahoo', start, end)\n\ndf2018 = data['Adj Close'] \n\ndisplay(df2018.tail())", "_____no_output_____" ], [ "## 株価をプロットしてみる\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))\ndf2018.loc[:,['AAPL', 'FB']].plot(ax=axes[0])\ndf2018.loc[:,['GOOG', 'AMZN']].plot(ax=axes[1])", "_____no_output_____" ], [ "# ポートフォリオの資産価値の推移\npf_value = df2018.dot(w_opt)\npf_value.head()", "_____no_output_____" ], [ "# exact と HHLで初期金額が異なることがありうるので、期初の値で規格化したリターンをみる。\npf_value.exact = pf_value.exact / pf_value.exact[0] \npf_value.HHL = pf_value.HHL / pf_value.HHL[0] \nprint(pf_value.tail())", " exact HHL\nDate \n2018-12-24 0.801548 0.749625\n2018-12-26 0.828918 0.766234\n2018-12-27 0.841539 0.781597\n2018-12-28 0.821053 0.756478\n2018-12-31 0.805599 0.735876\n" ], [ "pf_value.plot(figsize=(9, 6))", "_____no_output_____" ] ], [ [ "2018年はAmazon以外のGAFA各社の株式が軟調だったので、およそ-20%もの損が出ているが、exact解の方は多少マシであるようだ。。\nちなみに、元々行ったのはリスク最小化なので、この一年間のリスクも計算してみると、exact解の方が小さい結果となった。", "_____no_output_____" ] ], [ [ "pf_value.pct_change().std() * np.sqrt(252) ## 年率換算", "_____no_output_____" ] ], [ [ "### 参考文献\n[1] P. Rebentrost and S. Lloyd, “Quantum computational finance: quantum algorithm for portfolio optimization“, https://arxiv.org/abs/1811.03975", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb09e66195324b2e2d0b848bbc1a204e7a6a188c
73,321
ipynb
Jupyter Notebook
docs/workshops/GeoPython_2021.ipynb
Jack-ee/geemap
921f18fc853dbaffa3273905c8d86f5600548938
[ "MIT" ]
null
null
null
docs/workshops/GeoPython_2021.ipynb
Jack-ee/geemap
921f18fc853dbaffa3273905c8d86f5600548938
[ "MIT" ]
null
null
null
docs/workshops/GeoPython_2021.ipynb
Jack-ee/geemap
921f18fc853dbaffa3273905c8d86f5600548938
[ "MIT" ]
null
null
null
26.065055
479
0.534076
[ [ [ "**Interactive mapping and analysis of geospatial big data using geemap and Google Earth Engine**\n\nThis notebook was developed for the geemap workshop at the [GeoPython 2021 Conference](https://2021.geopython.net).\n\nAuthors: [Qiusheng Wu](https://github.com/giswqs), [Kel Markert](https://github.com/KMarkert)\n\nLink to this notebook: https://gishub.org/geopython\n\nRecorded video: https://www.youtube.com/watch?v=wGjpjh9IQ5I\n\n[![geemap workship](https://img.youtube.com/vi/wGjpjh9IQ5I/0.jpg)](https://www.youtube.com/watch?v=wGjpjh9IQ5I)\n\n\n## Introduction\n\n### Description\n\nGoogle Earth Engine (GEE) is a cloud computing platform with a multi-petabyte catalog of satellite imagery and geospatial datasets. It enables scientists, researchers, and developers to analyze and visualize changes on the Earth’s surface. The geemap Python package provides GEE users with an intuitive interface to manipulate, analyze, and visualize geospatial big data interactively in a Jupyter-based environment. The topics will be covered in this workshop include: \n\n1. Introducing geemap and the Earth Engine Python API\n2. Creating interactive maps\n3. Searching GEE data catalog\n4. Displaying GEE datasets\n5. Classifying images using machine learning algorithms\n6. Computing statistics and exporting results \n7. Producing publication-quality maps\n8. Building and deploying interactive web apps, among others\n\nThis workshop is intended for scientific programmers, data scientists, geospatial analysts, and concerned citizens of Earth. The attendees are expected to have a basic understanding of Python and the Jupyter ecosystem. Familiarity with Earth science and geospatial datasets is useful but not required.\n\n### Useful links\n- [GeoPython 2021 Conference website](https://2021.geopython.net)\n- [Google Earth Engine](https://earthengine.google.com)\n- [geemap.org](https://geemap.org)\n- [Google Earth Engine and geemap Python Tutorials](https://www.youtube.com/playlist?list=PLAxJ4-o7ZoPccOFv1dCwvGI6TYnirRTg3) (55 videos with a total length of 15 hours)\n- [Spatial Data Management with Google Earth Engine](https://www.youtube.com/playlist?list=PLAxJ4-o7ZoPdz9LHIJIxHlZe3t-MRCn61) (19 videos with a total length of 9 hours)\n- [Ask geemap questions on GitHub](https://github.com/giswqs/geemap/discussions)\n\n### Prerequisite\n- A Google Earth Engine account. Sign up [here](https://earthengine.google.com) if needed. \n- [Miniconda](https://docs.conda.io/en/latest/miniconda.html) or [Anaconda](https://www.anaconda.com/products/individual)\n\n\n### Set up a conda environment\n\n```\nconda create -n geo python=3.8\nconda activate geo\nconda install geemap -c conda-forge\nconda install jupyter_contrib_nbextensions -c conda-forge\njupyter contrib nbextension install --user\n```\n", "_____no_output_____" ], [ "## geemap basics\n\n### Import libraries", "_____no_output_____" ] ], [ [ "import os\nimport ee\nimport geemap", "_____no_output_____" ] ], [ [ "### Create an interactive map", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap", "_____no_output_____" ] ], [ [ "### Customize the default map\n\nYou can specify the center(lat, lon) and zoom for the default map. The lite mode will only show the zoom in/out tool. ", "_____no_output_____" ] ], [ [ "Map = geemap.Map(center=(40, -100), zoom=4, lite_mode=True)\nMap", "_____no_output_____" ] ], [ [ "### Add basemaps", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap.add_basemap('HYBRID')\nMap", "_____no_output_____" ], [ "from geemap.basemaps import basemaps", "_____no_output_____" ], [ "Map.add_basemap(basemaps.OpenTopoMap)", "_____no_output_____" ] ], [ [ "### Change basemaps without coding", "_____no_output_____" ], [ "![](https://i.imgur.com/PXURCSP.png)", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap", "_____no_output_____" ] ], [ [ "### Add WMS and XYZ tile layers\n\nExamples: https://viewer.nationalmap.gov/services/\n", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\nurl = 'https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}'\nMap.add_tile_layer(url, name='Google Terrain', attribution='Google')\nMap", "_____no_output_____" ], [ "naip_url = 'https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer?'\nMap.add_wms_layer(\n url=naip_url, layers='0', name='NAIP Imagery', format='image/png', shown=True\n)", "_____no_output_____" ] ], [ [ "### Use drawing tools", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap", "_____no_output_____" ], [ "# Map.user_roi.getInfo()", "_____no_output_____" ], [ "# Map.user_rois.getInfo()", "_____no_output_____" ] ], [ [ "### Convert GEE JavaScript to Python\n\nhttps://developers.google.com/earth-engine/guides/image_visualization", "_____no_output_____" ] ], [ [ "js_snippet = \"\"\"\n// Load an image.\nvar image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318');\n\n// Define the visualization parameters.\nvar vizParams = {\n bands: ['B5', 'B4', 'B3'],\n min: 0,\n max: 0.5,\n gamma: [0.95, 1.1, 1]\n};\n\n// Center the map and display the image.\nMap.setCenter(-122.1899, 37.5010, 10); // San Francisco Bay\nMap.addLayer(image, vizParams, 'false color composite');\n\n\"\"\"", "_____no_output_____" ], [ "geemap.js_snippet_to_py(\n js_snippet, add_new_cell=True, import_ee=True, import_geemap=True, show_map=True\n)", "_____no_output_____" ] ], [ [ "You can also convert GEE JavaScript to Python without coding.\n\n![](https://i.imgur.com/VnnrJwe.png)", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap", "_____no_output_____" ] ], [ [ "## Earth Engine datasets\n\n### Load Earth Engine datasets", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\n# Add Earth Engine datasets\ndem = ee.Image('USGS/SRTMGL1_003')\nlandcover = ee.Image(\"ESA/GLOBCOVER_L4_200901_200912_V2_3\").select('landcover')\nlandsat7 = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003')\nstates = ee.FeatureCollection(\"TIGER/2018/States\")\n\n# Set visualization parameters.\nvis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\n# Add Earth Eninge layers to Map\nMap.addLayer(dem, vis_params, 'SRTM DEM', True, 0.5)\nMap.addLayer(landcover, {}, 'Land cover')\nMap.addLayer(\n landsat7,\n {'bands': ['B4', 'B3', 'B2'], 'min': 20, 'max': 200, 'gamma': 1.5},\n 'Landsat 7',\n)\nMap.addLayer(states, {}, \"US States\")\n\nMap", "_____no_output_____" ] ], [ [ "### Search the Earth Engine Data Catalog", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap", "_____no_output_____" ], [ "dem = ee.Image('CGIAR/SRTM90_V4')\nMap.addLayer(dem, {}, \"CGIAR/SRTM90_V4\")", "_____no_output_____" ], [ "vis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\nMap.addLayer(dem, vis_params, \"DEM\")", "_____no_output_____" ] ], [ [ "### Use the datasets module", "_____no_output_____" ] ], [ [ "from geemap.datasets import DATA", "_____no_output_____" ], [ "Map = geemap.Map()\n\ndem = ee.Image(DATA.USGS_SRTMGL1_003)\n\nvis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\nMap.addLayer(dem, vis_params, 'SRTM DEM')\nMap", "_____no_output_____" ] ], [ [ "### Use the Inspector tool", "_____no_output_____" ], [ "![](https://i.imgur.com/drnfJ6N.png)", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\n# Add Earth Engine datasets\ndem = ee.Image('USGS/SRTMGL1_003')\nlandcover = ee.Image(\"ESA/GLOBCOVER_L4_200901_200912_V2_3\").select('landcover')\nlandsat7 = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003').select(\n ['B1', 'B2', 'B3', 'B4', 'B5', 'B7']\n)\nstates = ee.FeatureCollection(\"TIGER/2018/States\")\n\n# Set visualization parameters.\nvis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\n# Add Earth Eninge layers to Map\nMap.addLayer(dem, vis_params, 'SRTM DEM', True, 0.5)\nMap.addLayer(landcover, {}, 'Land cover')\nMap.addLayer(\n landsat7,\n {'bands': ['B4', 'B3', 'B2'], 'min': 20, 'max': 200, 'gamma': 1.5},\n 'Landsat 7',\n)\nMap.addLayer(states, {}, \"US States\")\n\nMap", "_____no_output_____" ] ], [ [ "## Data visualization \n\n### Use the Plotting tool", "_____no_output_____" ], [ "![](https://i.imgur.com/t4jKsNo.png)", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\nlandsat7 = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003').select(\n ['B1', 'B2', 'B3', 'B4', 'B5', 'B7']\n)\n\nlandsat_vis = {'bands': ['B4', 'B3', 'B2'], 'gamma': 1.4}\nMap.addLayer(landsat7, landsat_vis, \"Landsat\")\n\nhyperion = ee.ImageCollection('EO1/HYPERION').filter(\n ee.Filter.date('2016-01-01', '2017-03-01')\n)\n\nhyperion_vis = {\n 'min': 1000.0,\n 'max': 14000.0,\n 'gamma': 2.5,\n}\nMap.addLayer(hyperion, hyperion_vis, 'Hyperion')\n\nMap", "_____no_output_____" ] ], [ [ "### Change layer opacity", "_____no_output_____" ] ], [ [ "Map = geemap.Map(center=(40, -100), zoom=4)\n\ndem = ee.Image('USGS/SRTMGL1_003')\nstates = ee.FeatureCollection(\"TIGER/2018/States\")\n\nvis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\nMap.addLayer(dem, vis_params, 'SRTM DEM', True, 1)\nMap.addLayer(states, {}, \"US States\", True)\n\nMap", "_____no_output_____" ] ], [ [ "### Visualize raster data", "_____no_output_____" ] ], [ [ "Map = geemap.Map(center=(40, -100), zoom=4)\n\n# Add Earth Engine dataset\ndem = ee.Image('USGS/SRTMGL1_003')\nlandsat7 = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003').select(\n ['B1', 'B2', 'B3', 'B4', 'B5', 'B7']\n)\n\nvis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\nMap.addLayer(dem, vis_params, 'SRTM DEM', True, 1)\nMap.addLayer(\n landsat7,\n {'bands': ['B4', 'B3', 'B2'], 'min': 20, 'max': 200, 'gamma': 2},\n 'Landsat 7',\n)\nMap", "_____no_output_____" ] ], [ [ "### Visualize vector data", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\nstates = ee.FeatureCollection(\"TIGER/2018/States\")\nMap.addLayer(states, {}, \"US States\")\nMap", "_____no_output_____" ], [ "vis_params = {\n 'color': '000000',\n 'colorOpacity': 1,\n 'pointSize': 3,\n 'pointShape': 'circle',\n 'width': 2,\n 'lineType': 'solid',\n 'fillColorOpacity': 0.66,\n}\n\npalette = ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']\n\nMap.add_styled_vector(\n states, column=\"NAME\", palette=palette, layer_name=\"Styled vector\", **vis_params\n)", "_____no_output_____" ] ], [ [ "### Add a legend", "_____no_output_____" ] ], [ [ "legends = geemap.builtin_legends\nfor legend in legends:\n print(legend)", "_____no_output_____" ], [ "Map = geemap.Map()\nMap.add_basemap('HYBRID')\nlandcover = ee.Image('USGS/NLCD/NLCD2016').select('landcover')\nMap.addLayer(landcover, {}, 'NLCD Land Cover')\nMap.add_legend(builtin_legend='NLCD')\nMap", "_____no_output_____" ], [ "Map = geemap.Map()\n\nlegend_dict = {\n '11 Open Water': '466b9f',\n '12 Perennial Ice/Snow': 'd1def8',\n '21 Developed, Open Space': 'dec5c5',\n '22 Developed, Low Intensity': 'd99282',\n '23 Developed, Medium Intensity': 'eb0000',\n '24 Developed High Intensity': 'ab0000',\n '31 Barren Land (Rock/Sand/Clay)': 'b3ac9f',\n '41 Deciduous Forest': '68ab5f',\n '42 Evergreen Forest': '1c5f2c',\n '43 Mixed Forest': 'b5c58f',\n '51 Dwarf Scrub': 'af963c',\n '52 Shrub/Scrub': 'ccb879',\n '71 Grassland/Herbaceous': 'dfdfc2',\n '72 Sedge/Herbaceous': 'd1d182',\n '73 Lichens': 'a3cc51',\n '74 Moss': '82ba9e',\n '81 Pasture/Hay': 'dcd939',\n '82 Cultivated Crops': 'ab6c28',\n '90 Woody Wetlands': 'b8d9eb',\n '95 Emergent Herbaceous Wetlands': '6c9fb8',\n}\n\nlandcover = ee.Image('USGS/NLCD/NLCD2016').select('landcover')\nMap.addLayer(landcover, {}, 'NLCD Land Cover')\n\nMap.add_legend(legend_title=\"NLCD Land Cover Classification\", legend_dict=legend_dict)\nMap", "_____no_output_____" ] ], [ [ "### Add a colorbar", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\ndem = ee.Image('USGS/SRTMGL1_003')\nvis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\nMap.addLayer(dem, vis_params, 'SRTM DEM')\n\ncolors = vis_params['palette']\nvmin = vis_params['min']\nvmax = vis_params['max']\n\nMap.add_colorbar(vis_params, label=\"Elevation (m)\", layer_name=\"SRTM DEM\")\nMap", "_____no_output_____" ], [ "Map.add_colorbar(\n vis_params, label=\"Elevation (m)\", layer_name=\"SRTM DEM\", orientation=\"vertical\"\n)", "_____no_output_____" ], [ "Map.add_colorbar(\n vis_params,\n label=\"Elevation (m)\",\n layer_name=\"SRTM DEM\",\n orientation=\"vertical\",\n transparent_bg=True,\n)", "_____no_output_____" ], [ "Map.add_colorbar(\n vis_params,\n label=\"Elevation (m)\",\n layer_name=\"SRTM DEM\",\n orientation=\"vertical\",\n transparent_bg=True,\n discrete=True,\n)", "_____no_output_____" ] ], [ [ "### Create a split-panel map", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap.split_map(left_layer='HYBRID', right_layer='TERRAIN')\nMap", "_____no_output_____" ], [ "Map = geemap.Map()\nMap.split_map(\n left_layer='NLCD 2016 CONUS Land Cover', right_layer='NLCD 2001 CONUS Land Cover'\n)\nMap", "_____no_output_____" ], [ "nlcd_2001 = ee.Image('USGS/NLCD/NLCD2001').select('landcover')\nnlcd_2016 = ee.Image('USGS/NLCD/NLCD2016').select('landcover')\n\nleft_layer = geemap.ee_tile_layer(nlcd_2001, {}, 'NLCD 2001')\nright_layer = geemap.ee_tile_layer(nlcd_2016, {}, 'NLCD 2016')\n\nMap = geemap.Map()\nMap.split_map(left_layer, right_layer)\nMap", "_____no_output_____" ] ], [ [ "### Create linked maps", "_____no_output_____" ] ], [ [ "image = (\n ee.ImageCollection('COPERNICUS/S2')\n .filterDate('2018-09-01', '2018-09-30')\n .map(lambda img: img.divide(10000))\n .median()\n)\n\nvis_params = [\n {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 0.3, 'gamma': 1.3},\n {'bands': ['B8', 'B11', 'B4'], 'min': 0, 'max': 0.3, 'gamma': 1.3},\n {'bands': ['B8', 'B4', 'B3'], 'min': 0, 'max': 0.3, 'gamma': 1.3},\n {'bands': ['B12', 'B12', 'B4'], 'min': 0, 'max': 0.3, 'gamma': 1.3},\n]\n\nlabels = [\n 'Natural Color (B4/B3/B2)',\n 'Land/Water (B8/B11/B4)',\n 'Color Infrared (B8/B4/B3)',\n 'Vegetation (B12/B11/B4)',\n]\n\ngeemap.linked_maps(\n rows=2,\n cols=2,\n height=\"400px\",\n center=[38.4151, 21.2712],\n zoom=12,\n ee_objects=[image],\n vis_params=vis_params,\n labels=labels,\n label_position=\"topright\",\n)", "_____no_output_____" ] ], [ [ "### Create timelapse animations", "_____no_output_____" ] ], [ [ "geemap.show_youtube('https://youtu.be/mA21Us_3m28')", "_____no_output_____" ] ], [ [ "### Create time-series composites", "_____no_output_____" ] ], [ [ "geemap.show_youtube('https://youtu.be/kEltQkNia6o')", "_____no_output_____" ] ], [ [ "## Data analysis", "_____no_output_____" ], [ "### Descriptive statistics", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\ncentroid = ee.Geometry.Point([-122.4439, 37.7538])\n\nimage = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR').filterBounds(centroid).first()\n\nvis = {'min': 0, 'max': 3000, 'bands': ['B5', 'B4', 'B3']}\n\nMap.centerObject(centroid, 8)\nMap.addLayer(image, vis, \"Landsat-8\")\nMap", "_____no_output_____" ], [ "image.propertyNames().getInfo()", "_____no_output_____" ], [ "image.get('CLOUD_COVER').getInfo()", "_____no_output_____" ], [ "props = geemap.image_props(image)\nprops.getInfo()", "_____no_output_____" ], [ "stats = geemap.image_stats(image, scale=90)\nstats.getInfo()", "_____no_output_____" ] ], [ [ "### Zonal statistics", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\n# Add Earth Engine dataset\ndem = ee.Image('USGS/SRTMGL1_003')\n\n# Set visualization parameters.\ndem_vis = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\n# Add Earth Engine DEM to map\nMap.addLayer(dem, dem_vis, 'SRTM DEM')\n\n# Add Landsat data to map\nlandsat = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003')\n\nlandsat_vis = {'bands': ['B4', 'B3', 'B2'], 'gamma': 1.4}\nMap.addLayer(landsat, landsat_vis, \"LE7_TOA_5YEAR/1999_2003\")\n\nstates = ee.FeatureCollection(\"TIGER/2018/States\")\nMap.addLayer(states, {}, 'US States')\nMap", "_____no_output_____" ], [ "out_dir = os.path.expanduser('~/Downloads')\nout_dem_stats = os.path.join(out_dir, 'dem_stats.csv')\n\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n# Allowed output formats: csv, shp, json, kml, kmz\n# Allowed statistics type: MEAN, MAXIMUM, MINIMUM, MEDIAN, STD, MIN_MAX, VARIANCE, SUM\ngeemap.zonal_statistics(dem, states, out_dem_stats, statistics_type='MEAN', scale=1000)", "_____no_output_____" ], [ "out_landsat_stats = os.path.join(out_dir, 'landsat_stats.csv')\ngeemap.zonal_statistics(\n landsat, states, out_landsat_stats, statistics_type='SUM', scale=1000\n)", "_____no_output_____" ] ], [ [ "### Zonal statistics by group", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\ndataset = ee.Image('USGS/NLCD/NLCD2016')\nlandcover = ee.Image(dataset.select('landcover'))\nMap.addLayer(landcover, {}, 'NLCD 2016')\n\nstates = ee.FeatureCollection(\"TIGER/2018/States\")\nMap.addLayer(states, {}, 'US States')\nMap.add_legend(builtin_legend='NLCD')\nMap", "_____no_output_____" ], [ "out_dir = os.path.expanduser('~/Downloads')\nnlcd_stats = os.path.join(out_dir, 'nlcd_stats.csv')\n\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n# statistics_type can be either 'SUM' or 'PERCENTAGE'\n# denominator can be used to convert square meters to other areal units, such as square kilimeters\ngeemap.zonal_statistics_by_group(\n landcover,\n states,\n nlcd_stats,\n statistics_type='SUM',\n denominator=1000000,\n decimal_places=2,\n)", "_____no_output_____" ] ], [ [ "### Unsupervised classification\n\nSource: https://developers.google.com/earth-engine/guides/clustering\n\nThe `ee.Clusterer` package handles unsupervised classification (or clustering) in Earth Engine. These algorithms are currently based on the algorithms with the same name in [Weka](http://www.cs.waikato.ac.nz/ml/weka/). More details about each Clusterer are available in the reference docs in the Code Editor.\n\nClusterers are used in the same manner as classifiers in Earth Engine. The general workflow for clustering is:\n\n1. Assemble features with numeric properties in which to find clusters.\n2. Instantiate a clusterer. Set its parameters if necessary.\n3. Train the clusterer using the training data.\n4. Apply the clusterer to an image or feature collection.\n5. Label the clusters.\n\nThe training data is a `FeatureCollection` with properties that will be input to the clusterer. Unlike classifiers, there is no input class value for an `Clusterer`. Like classifiers, the data for the train and apply steps are expected to have the same number of values. When a trained clusterer is applied to an image or table, it assigns an integer cluster ID to each pixel or feature.\n\nHere is a simple example of building and using an ee.Clusterer:\n\n![](https://i.imgur.com/IcBapEx.png)", "_____no_output_____" ], [ "**Add data to the map**", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\npoint = ee.Geometry.Point([-87.7719, 41.8799])\n\nimage = (\n ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')\n .filterBounds(point)\n .filterDate('2019-01-01', '2019-12-31')\n .sort('CLOUD_COVER')\n .first()\n .select('B[1-7]')\n)\n\nvis_params = {'min': 0, 'max': 3000, 'bands': ['B5', 'B4', 'B3']}\n\nMap.centerObject(point, 8)\nMap.addLayer(image, vis_params, \"Landsat-8\")\n\nMap", "_____no_output_____" ] ], [ [ "**Make training dataset**\n\nThere are several ways you can create a region for generating the training dataset.\n\n- Draw a shape (e.g., rectangle) on the map and the use `region = Map.user_roi`\n- Define a geometry, such as `region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])`\n- Create a buffer zone around a point, such as `region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)`\n- If you don't define a region, it will use the image footprint by default", "_____no_output_____" ] ], [ [ "training = image.sample(\n **{\n # 'region': region,\n 'scale': 30,\n 'numPixels': 5000,\n 'seed': 0,\n 'geometries': True, # Set this to False to ignore geometries\n }\n)\n\nMap.addLayer(training, {}, 'training', False)", "_____no_output_____" ] ], [ [ "**Train the clusterer**", "_____no_output_____" ] ], [ [ "# Instantiate the clusterer and train it.\nn_clusters = 5\nclusterer = ee.Clusterer.wekaKMeans(n_clusters).train(training)", "_____no_output_____" ] ], [ [ "**Classify the image**", "_____no_output_____" ] ], [ [ "# Cluster the input using the trained clusterer.\nresult = image.cluster(clusterer)\n\n# # Display the clusters with random colors.\nMap.addLayer(result.randomVisualizer(), {}, 'clusters')\nMap", "_____no_output_____" ] ], [ [ "**Label the clusters**", "_____no_output_____" ] ], [ [ "legend_keys = ['One', 'Two', 'Three', 'Four', 'ect']\nlegend_colors = ['#8DD3C7', '#FFFFB3', '#BEBADA', '#FB8072', '#80B1D3']\n\n# Reclassify the map\nresult = result.remap([0, 1, 2, 3, 4], [1, 2, 3, 4, 5])\n\nMap.addLayer(\n result, {'min': 1, 'max': 5, 'palette': legend_colors}, 'Labelled clusters'\n)\nMap.add_legend(\n legend_keys=legend_keys, legend_colors=legend_colors, position='bottomright'\n)", "_____no_output_____" ] ], [ [ "**Visualize the result**", "_____no_output_____" ] ], [ [ "print('Change layer opacity:')\ncluster_layer = Map.layers[-1]\ncluster_layer.interact(opacity=(0, 1, 0.1))", "_____no_output_____" ], [ "Map", "_____no_output_____" ] ], [ [ "**Export the result**", "_____no_output_____" ] ], [ [ "out_dir = os.path.expanduser('~/Downloads')\nout_file = os.path.join(out_dir, 'cluster.tif')\ngeemap.ee_export_image(result, filename=out_file, scale=90)", "_____no_output_____" ], [ "# geemap.ee_export_image_to_drive(result, description='clusters', folder='export', scale=90)", "_____no_output_____" ] ], [ [ "### Supervised classification", "_____no_output_____" ], [ "Source: https://developers.google.com/earth-engine/guides/classification\n\nThe `Classifier` package handles supervised classification by traditional ML algorithms running in Earth Engine. These classifiers include CART, RandomForest, NaiveBayes and SVM. The general workflow for classification is:\n\n1. Collect training data. Assemble features which have a property that stores the known class label and properties storing numeric values for the predictors.\n2. Instantiate a classifier. Set its parameters if necessary.\n3. Train the classifier using the training data.\n4. Classify an image or feature collection.\n5. Estimate classification error with independent validation data.\n\nThe training data is a `FeatureCollection` with a property storing the class label and properties storing predictor variables. Class labels should be consecutive, integers starting from 0. If necessary, use remap() to convert class values to consecutive integers. The predictors should be numeric.\n\n![](https://i.imgur.com/vROsEiq.png)", "_____no_output_____" ], [ "**Add data to the map**", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\npoint = ee.Geometry.Point([-122.4439, 37.7538])\n\nimage = (\n ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')\n .filterBounds(point)\n .filterDate('2016-01-01', '2016-12-31')\n .sort('CLOUD_COVER')\n .first()\n .select('B[1-7]')\n)\n\nvis_params = {'min': 0, 'max': 3000, 'bands': ['B5', 'B4', 'B3']}\n\nMap.centerObject(point, 8)\nMap.addLayer(image, vis_params, \"Landsat-8\")\n\nMap", "_____no_output_____" ] ], [ [ "**Make training dataset**\n\nThere are several ways you can create a region for generating the training dataset.\n\n- Draw a shape (e.g., rectangle) on the map and the use `region = Map.user_roi`\n- Define a geometry, such as `region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])`\n- Create a buffer zone around a point, such as `region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)`\n- If you don't define a region, it will use the image footprint by default", "_____no_output_____" ] ], [ [ "# region = Map.user_roi\n# region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])\n# region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)", "_____no_output_____" ] ], [ [ "In this example, we are going to use the [USGS National Land Cover Database (NLCD)](https://developers.google.com/earth-engine/datasets/catalog/USGS_NLCD) to create label dataset for training\n\n\n![](https://i.imgur.com/7QoRXxu.png)", "_____no_output_____" ] ], [ [ "nlcd = ee.Image('USGS/NLCD/NLCD2016').select('landcover').clip(image.geometry())\nMap.addLayer(nlcd, {}, 'NLCD')\nMap", "_____no_output_____" ], [ "# Make the training dataset.\npoints = nlcd.sample(\n **{\n 'region': image.geometry(),\n 'scale': 30,\n 'numPixels': 5000,\n 'seed': 0,\n 'geometries': True, # Set this to False to ignore geometries\n }\n)\n\nMap.addLayer(points, {}, 'training', False)", "_____no_output_____" ] ], [ [ "**Train the classifier**", "_____no_output_____" ] ], [ [ "# Use these bands for prediction.\nbands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7']\n\n\n# This property of the table stores the land cover labels.\nlabel = 'landcover'\n\n# Overlay the points on the imagery to get training.\ntraining = image.select(bands).sampleRegions(\n **{'collection': points, 'properties': [label], 'scale': 30}\n)\n\n# Train a CART classifier with default parameters.\ntrained = ee.Classifier.smileCart().train(training, label, bands)", "_____no_output_____" ] ], [ [ "**Classify the image**", "_____no_output_____" ] ], [ [ "# Classify the image with the same bands used for training.\nresult = image.select(bands).classify(trained)\n\n# # Display the clusters with random colors.\nMap.addLayer(result.randomVisualizer(), {}, 'classfied')\nMap", "_____no_output_____" ] ], [ [ "**Render categorical map**\n\nTo render a categorical map, we can set two image properties: `landcover_class_values` and `landcover_class_palette`. We can use the same style as the NLCD so that it is easy to compare the two maps. ", "_____no_output_____" ] ], [ [ "class_values = nlcd.get('landcover_class_values').getInfo()\nclass_palette = nlcd.get('landcover_class_palette').getInfo()", "_____no_output_____" ], [ "landcover = result.set('classification_class_values', class_values)\nlandcover = landcover.set('classification_class_palette', class_palette)", "_____no_output_____" ], [ "Map.addLayer(landcover, {}, 'Land cover')\nMap.add_legend(builtin_legend='NLCD')\nMap", "_____no_output_____" ] ], [ [ "**Visualize the result**", "_____no_output_____" ] ], [ [ "print('Change layer opacity:')\ncluster_layer = Map.layers[-1]\ncluster_layer.interact(opacity=(0, 1, 0.1))", "_____no_output_____" ] ], [ [ "**Export the result**", "_____no_output_____" ] ], [ [ "out_dir = os.path.expanduser('~/Downloads')\nout_file = os.path.join(out_dir, 'landcover.tif')", "_____no_output_____" ], [ "geemap.ee_export_image(landcover, filename=out_file, scale=900)", "_____no_output_____" ], [ "# geemap.ee_export_image_to_drive(landcover, description='landcover', folder='export', scale=900)", "_____no_output_____" ] ], [ [ "### Training sample creation\n\n![](https://i.imgur.com/QQDjcPt.png)", "_____no_output_____" ] ], [ [ "geemap.show_youtube('https://youtu.be/VWh5PxXPZw0')", "_____no_output_____" ], [ "Map = geemap.Map()\nMap", "_____no_output_____" ] ], [ [ "### WhiteboxTools", "_____no_output_____" ] ], [ [ "import whiteboxgui", "_____no_output_____" ], [ "whiteboxgui.show()", "_____no_output_____" ], [ "whiteboxgui.show(tree=True)", "_____no_output_____" ] ], [ [ "![](https://i.imgur.com/aNRfUIf.png)", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\nMap", "_____no_output_____" ] ], [ [ "## Map making", "_____no_output_____" ], [ "### Plot a single band image", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nfrom geemap import cartoee", "_____no_output_____" ], [ "geemap.ee_initialize()", "_____no_output_____" ], [ "srtm = ee.Image(\"CGIAR/SRTM90_V4\")\nregion = [-180, -60, 180, 85] # define bounding box to request data\nvis = {'min': 0, 'max': 3000} # define visualization parameters for image", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\ncmap = \"gist_earth\" # colormap we want to use\n# cmap = \"terrain\"\n\n# use cartoee to get a map\nax = cartoee.get_map(srtm, region=region, vis_params=vis, cmap=cmap)\n\n# add a colorbar to the map using the visualization params we passed to the map\ncartoee.add_colorbar(\n ax, vis, cmap=cmap, loc=\"right\", label=\"Elevation\", orientation=\"vertical\"\n)\n\n# add gridlines to the map at a specified interval\ncartoee.add_gridlines(ax, interval=[60, 30], linestyle=\"--\")\n\n# add coastlines using the cartopy api\nax.coastlines(color=\"red\")\n\nax.set_title(label='Global Elevation Map', fontsize=15)\n\nplt.show()", "_____no_output_____" ] ], [ [ "### Plot an RGB image", "_____no_output_____" ] ], [ [ "# get a landsat image to visualize\nimage = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318')\n\n# define the visualization parameters to view\nvis = {\"bands\": ['B5', 'B4', 'B3'], \"min\": 0, \"max\": 5000, \"gamma\": 1.3}", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# here is the bounding box of the map extent we want to use\n# formatted a [W,S,E,N]\nzoom_region = [-122.6265, 37.3458, -121.8025, 37.9178]\n\n# plot the map over the region of interest\nax = cartoee.get_map(image, vis_params=vis, region=zoom_region)\n\n# add the gridlines and specify that the xtick labels be rotated 45 degrees\ncartoee.add_gridlines(ax, interval=0.15, xtick_rotation=45, linestyle=\":\")\n\n# add coastline\nax.coastlines(color=\"yellow\")\n\n# add north arrow\ncartoee.add_north_arrow(\n ax, text=\"N\", xy=(0.05, 0.25), text_color=\"white\", arrow_color=\"white\", fontsize=20\n)\n\n# add scale bar\ncartoee.add_scale_bar_lite(\n ax, length=10, xy=(0.1, 0.05), fontsize=20, color=\"white\", unit=\"km\"\n)\n\nax.set_title(label='Landsat False Color Composite (Band 5/4/3)', fontsize=15)\n\nplt.show()", "_____no_output_____" ] ], [ [ "### Add map elements", "_____no_output_____" ] ], [ [ "from matplotlib.lines import Line2D", "_____no_output_____" ], [ "# get a landsat image to visualize\nimage = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318')\n\n# define the visualization parameters to view\nvis = {\"bands\": ['B5', 'B4', 'B3'], \"min\": 0, \"max\": 5000, \"gamma\": 1.3}", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# here is the bounding box of the map extent we want to use\n# formatted a [W,S,E,N]\nzoom_region = [-122.6265, 37.3458, -121.8025, 37.9178]\n\n# plot the map over the region of interest\nax = cartoee.get_map(image, vis_params=vis, region=zoom_region)\n\n# add the gridlines and specify that the xtick labels be rotated 45 degrees\ncartoee.add_gridlines(ax, interval=0.15, xtick_rotation=0, linestyle=\":\")\n\n# add coastline\nax.coastlines(color=\"cyan\")\n\n# add north arrow\ncartoee.add_north_arrow(\n ax, text=\"N\", xy=(0.05, 0.25), text_color=\"white\", arrow_color=\"white\", fontsize=20\n)\n\n# add scale bar\ncartoee.add_scale_bar_lite(\n ax, length=10, xy=(0.1, 0.05), fontsize=20, color=\"white\", unit=\"km\"\n)\n\nax.set_title(label='Landsat False Color Composite (Band 5/4/3)', fontsize=15)\n\n# add legend\nlegend_elements = [\n Line2D([], [], color='#00ffff', lw=2, label='Coastline'),\n Line2D(\n [],\n [],\n marker='o',\n color='#A8321D',\n label='City',\n markerfacecolor='#A8321D',\n markersize=10,\n ls='',\n ),\n]\n\ncartoee.add_legend(ax, legend_elements, loc='lower right')\n\nplt.show()", "_____no_output_____" ] ], [ [ "### Plot multiple layers", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\nimage = (\n ee.ImageCollection('MODIS/MCD43A4_006_NDVI')\n .filter(ee.Filter.date('2018-04-01', '2018-05-01'))\n .select(\"NDVI\")\n .first()\n)\n\nvis_params = {\n 'min': 0.0,\n 'max': 1.0,\n 'palette': [\n 'FFFFFF',\n 'CE7E45',\n 'DF923D',\n 'F1B555',\n 'FCD163',\n '99B718',\n '74A901',\n '66A000',\n '529400',\n '3E8601',\n '207401',\n '056201',\n '004C00',\n '023B01',\n '012E01',\n '011D01',\n '011301',\n ],\n}\nMap.setCenter(-7.03125, 31.0529339857, 2)\nMap.addLayer(image, vis_params, 'MODIS NDVI')\n\ncountries = geemap.shp_to_ee(\"../data/countries.shp\")\nstyle = {\"color\": \"00000088\", \"width\": 1, \"fillColor\": \"00000000\"}\nMap.addLayer(countries.style(**style), {}, \"Countries\")\n\nndvi = image.visualize(**vis_params)\nblend = ndvi.blend(countries.style(**style))\n\nMap.addLayer(blend, {}, \"Blend\")\n\nMap", "_____no_output_____" ], [ "# specify region to focus on\nbbox = [-180, -88, 180, 88]", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# plot the result with cartoee using a PlateCarre projection (default)\nax = cartoee.get_map(blend, region=bbox)\ncb = cartoee.add_colorbar(ax, vis_params=vis_params, loc='right')\n\nax.set_title(label='MODIS NDVI', fontsize=15)\n\n# ax.coastlines()\nplt.show()", "_____no_output_____" ], [ "import cartopy.crs as ccrs", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\nprojection = ccrs.EqualEarth(central_longitude=-180)\n\n# plot the result with cartoee using a PlateCarre projection (default)\nax = cartoee.get_map(blend, region=bbox, proj=projection)\ncb = cartoee.add_colorbar(ax, vis_params=vis_params, loc='right')\n\nax.set_title(label='MODIS NDVI', fontsize=15)\n\n# ax.coastlines()\nplt.show()", "_____no_output_____" ] ], [ [ "### Use custom projections", "_____no_output_____" ] ], [ [ "import cartopy.crs as ccrs", "_____no_output_____" ], [ "# get an earth engine image of ocean data for Jan-Mar 2018\nocean = (\n ee.ImageCollection('NASA/OCEANDATA/MODIS-Terra/L3SMI')\n .filter(ee.Filter.date('2018-01-01', '2018-03-01'))\n .median()\n .select([\"sst\"], [\"SST\"])\n)", "_____no_output_____" ], [ "# set parameters for plotting\n# will plot the Sea Surface Temp with specific range and colormap\nvisualization = {'bands': \"SST\", 'min': -2, 'max': 30}\n# specify region to focus on\nbbox = [-180, -88, 180, 88]", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# plot the result with cartoee using a PlateCarre projection (default)\nax = cartoee.get_map(ocean, cmap='plasma', vis_params=visualization, region=bbox)\ncb = cartoee.add_colorbar(ax, vis_params=visualization, loc='right', cmap='plasma')\n\nax.set_title(label='Sea Surface Temperature', fontsize=15)\n\nax.coastlines()\nplt.show()", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# create a new Mollweide projection centered on the Pacific\nprojection = ccrs.Mollweide(central_longitude=-180)\n\n# plot the result with cartoee using the Mollweide projection\nax = cartoee.get_map(\n ocean, vis_params=visualization, region=bbox, cmap='plasma', proj=projection\n)\ncb = cartoee.add_colorbar(\n ax, vis_params=visualization, loc='bottom', cmap='plasma', orientation='horizontal'\n)\n\nax.set_title(\"Mollweide projection\")\n\nax.coastlines()\nplt.show()", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# create a new Robinson projection centered on the Pacific\nprojection = ccrs.Robinson(central_longitude=-180)\n\n# plot the result with cartoee using the Goode homolosine projection\nax = cartoee.get_map(\n ocean, vis_params=visualization, region=bbox, cmap='plasma', proj=projection\n)\ncb = cartoee.add_colorbar(\n ax, vis_params=visualization, loc='bottom', cmap='plasma', orientation='horizontal'\n)\n\nax.set_title(\"Robinson projection\")\n\nax.coastlines()\nplt.show()", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# create a new equal Earth projection focused on the Pacific\nprojection = ccrs.EqualEarth(central_longitude=-180)\n\n# plot the result with cartoee using the orographic projection\nax = cartoee.get_map(\n ocean, vis_params=visualization, region=bbox, cmap='plasma', proj=projection\n)\ncb = cartoee.add_colorbar(\n ax, vis_params=visualization, loc='right', cmap='plasma', orientation='vertical'\n)\n\nax.set_title(\"Equal Earth projection\")\n\nax.coastlines()\nplt.show()", "_____no_output_____" ], [ "fig = plt.figure(figsize=(15, 10))\n\n# create a new orographic projection focused on the Pacific\nprojection = ccrs.Orthographic(-130, -10)\n\n# plot the result with cartoee using the orographic projection\nax = cartoee.get_map(\n ocean, vis_params=visualization, region=bbox, cmap='plasma', proj=projection\n)\ncb = cartoee.add_colorbar(\n ax, vis_params=visualization, loc='right', cmap='plasma', orientation='vertical'\n)\n\nax.set_title(\"Orographic projection\")\n\nax.coastlines()\nplt.show()", "_____no_output_____" ] ], [ [ "### Create timelapse animations", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\nlon = -115.1585\nlat = 36.1500\nstart_year = 1984\nend_year = 2000\n\npoint = ee.Geometry.Point(lon, lat)\nyears = ee.List.sequence(start_year, end_year)\n\n\ndef get_best_image(year):\n\n start_date = ee.Date.fromYMD(year, 1, 1)\n end_date = ee.Date.fromYMD(year, 12, 31)\n image = (\n ee.ImageCollection(\"LANDSAT/LT05/C01/T1_SR\")\n .filterBounds(point)\n .filterDate(start_date, end_date)\n .sort(\"CLOUD_COVER\")\n .first()\n )\n return ee.Image(image)\n\n\ncollection = ee.ImageCollection(years.map(get_best_image))\n\nvis_params = {\"bands\": ['B4', 'B3', 'B2'], \"min\": 0, \"max\": 5000}\n\nimage = ee.Image(collection.first())\nMap.addLayer(image, vis_params, 'First image')\nMap.setCenter(lon, lat, 8)\nMap", "_____no_output_____" ], [ "w = 0.4\nh = 0.3\n\nregion = [lon - w, lat - h, lon + w, lat + h]\n\nfig = plt.figure(figsize=(10, 8))\n\n# use cartoee to get a map\nax = cartoee.get_map(image, region=region, vis_params=vis_params)\n\n# add gridlines to the map at a specified interval\ncartoee.add_gridlines(ax, interval=[0.2, 0.2], linestyle=\":\")\n\n# add north arrow\nnorth_arrow_dict = {\n \"text\": \"N\",\n \"xy\": (0.1, 0.3),\n \"arrow_length\": 0.15,\n \"text_color\": \"white\",\n \"arrow_color\": \"white\",\n \"fontsize\": 20,\n \"width\": 5,\n \"headwidth\": 15,\n \"ha\": \"center\",\n \"va\": \"center\",\n}\ncartoee.add_north_arrow(ax, **north_arrow_dict)\n\n# add scale bar\nscale_bar_dict = {\n \"length\": 10,\n \"xy\": (0.1, 0.05),\n \"linewidth\": 3,\n \"fontsize\": 20,\n \"color\": \"white\",\n \"unit\": \"km\",\n \"ha\": \"center\",\n \"va\": \"bottom\",\n}\ncartoee.add_scale_bar_lite(ax, **scale_bar_dict)\n\nax.set_title(label='Las Vegas, NV', fontsize=15)\n\nplt.show()", "_____no_output_____" ], [ "cartoee.get_image_collection_gif(\n ee_ic=collection,\n out_dir=os.path.expanduser(\"~/Downloads/timelapse\"),\n out_gif=\"animation.gif\",\n vis_params=vis_params,\n region=region,\n fps=5,\n mp4=True,\n grid_interval=(0.2, 0.2),\n plot_title=\"Las Vegas, NV\",\n date_format='YYYY-MM-dd',\n fig_size=(10, 8),\n dpi_plot=100,\n file_format=\"png\",\n north_arrow_dict=north_arrow_dict,\n scale_bar_dict=scale_bar_dict,\n verbose=True,\n)", "_____no_output_____" ] ], [ [ "## Data export", "_____no_output_____" ], [ "### Export ee.Image", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\nimage = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003')\n\nlandsat_vis = {'bands': ['B4', 'B3', 'B2'], 'gamma': 1.4}\nMap.addLayer(image, landsat_vis, \"LE7_TOA_5YEAR/1999_2003\", True, 1)\n\nMap", "_____no_output_____" ], [ "# Draw any shapes on the map using the Drawing tools before executing this code block\nroi = Map.user_roi\n\nif roi is None:\n roi = ee.Geometry.Polygon(\n [\n [\n [-115.413031, 35.889467],\n [-115.413031, 36.543157],\n [-114.034328, 36.543157],\n [-114.034328, 35.889467],\n [-115.413031, 35.889467],\n ]\n ]\n )", "_____no_output_____" ], [ "# Set output directory\nout_dir = os.path.expanduser('~/Downloads')\n\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\nfilename = os.path.join(out_dir, 'landsat.tif')", "_____no_output_____" ] ], [ [ "Exporting all bands as one single image", "_____no_output_____" ] ], [ [ "image = image.clip(roi).unmask()\ngeemap.ee_export_image(\n image, filename=filename, scale=90, region=roi, file_per_band=False\n)", "_____no_output_____" ] ], [ [ "Exporting each band as one image", "_____no_output_____" ] ], [ [ "geemap.ee_export_image(\n image, filename=filename, scale=90, region=roi, file_per_band=True\n)", "_____no_output_____" ] ], [ [ "Export an image to Google Drive¶", "_____no_output_____" ] ], [ [ "# geemap.ee_export_image_to_drive(image, description='landsat', folder='export', region=roi, scale=30)", "_____no_output_____" ] ], [ [ "### Export ee.ImageCollection", "_____no_output_____" ] ], [ [ "loc = ee.Geometry.Point(-99.2222, 46.7816)\ncollection = (\n ee.ImageCollection('USDA/NAIP/DOQQ')\n .filterBounds(loc)\n .filterDate('2008-01-01', '2020-01-01')\n .filter(ee.Filter.listContains(\"system:band_names\", \"N\"))\n)", "_____no_output_____" ], [ "collection.aggregate_array('system:index').getInfo()", "_____no_output_____" ], [ "geemap.ee_export_image_collection(collection, out_dir=out_dir)", "_____no_output_____" ], [ "# geemap.ee_export_image_collection_to_drive(collection, folder='export', scale=10)", "_____no_output_____" ] ], [ [ "### Extract pixels as a numpy array", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\nimg = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_038029_20180810').select(['B4', 'B5', 'B6'])\n\naoi = ee.Geometry.Polygon(\n [[[-110.8, 44.7], [-110.8, 44.6], [-110.6, 44.6], [-110.6, 44.7]]], None, False\n)\n\nrgb_img = geemap.ee_to_numpy(img, region=aoi)\nprint(rgb_img.shape)", "_____no_output_____" ], [ "rgb_img_test = (255 * ((rgb_img[:, :, 0:3] - 100) / 3500)).astype('uint8')\nplt.imshow(rgb_img_test)\nplt.show()", "_____no_output_____" ] ], [ [ "### Export pixel values to points", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\n# Add Earth Engine dataset\ndem = ee.Image('USGS/SRTMGL1_003')\nlandsat7 = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003')\n\n# Set visualization parameters.\nvis_params = {\n 'min': 0,\n 'max': 4000,\n 'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],\n}\n\n# Add Earth Eninge layers to Map\nMap.addLayer(\n landsat7, {'bands': ['B4', 'B3', 'B2'], 'min': 20, 'max': 200}, 'Landsat 7'\n)\nMap.addLayer(dem, vis_params, 'SRTM DEM', True, 1)\nMap", "_____no_output_____" ] ], [ [ "**Download sample data**", "_____no_output_____" ] ], [ [ "work_dir = os.path.expanduser('~/Downloads')\nin_shp = os.path.join(work_dir, 'us_cities.shp')\nif not os.path.exists(in_shp):\n data_url = 'https://github.com/giswqs/data/raw/main/us/us_cities.zip'\n geemap.download_from_url(data_url, out_dir=work_dir)", "_____no_output_____" ], [ "in_fc = geemap.shp_to_ee(in_shp)\nMap.addLayer(in_fc, {}, 'Cities')", "_____no_output_____" ] ], [ [ "**Export pixel values as a shapefile**", "_____no_output_____" ] ], [ [ "out_shp = os.path.join(work_dir, 'dem.shp')\ngeemap.extract_values_to_points(in_fc, dem, out_shp)", "_____no_output_____" ] ], [ [ "**Export pixel values as a csv**", "_____no_output_____" ] ], [ [ "out_csv = os.path.join(work_dir, 'landsat.csv')\ngeemap.extract_values_to_points(in_fc, landsat7, out_csv)", "_____no_output_____" ] ], [ [ "### Export ee.FeatureCollection", "_____no_output_____" ] ], [ [ "Map = geemap.Map()\n\nfc = ee.FeatureCollection('users/giswqs/public/countries')\nMap.addLayer(fc, {}, \"Countries\")\nMap", "_____no_output_____" ], [ "out_dir = os.path.expanduser('~/Downloads')\nout_shp = os.path.join(out_dir, 'countries.shp')", "_____no_output_____" ], [ "geemap.ee_to_shp(fc, filename=out_shp)", "_____no_output_____" ], [ "out_csv = os.path.join(out_dir, 'countries.csv')\ngeemap.ee_export_vector(fc, filename=out_csv)", "_____no_output_____" ], [ "out_kml = os.path.join(out_dir, 'countries.kml')\ngeemap.ee_export_vector(fc, filename=out_kml)", "_____no_output_____" ], [ "# geemap.ee_export_vector_to_drive(fc, description=\"countries\", folder=\"export\", file_format=\"shp\")", "_____no_output_____" ] ], [ [ "## Web apps", "_____no_output_____" ], [ "### Deploy web apps using ngrok", "_____no_output_____" ], [ "**Steps to deploy an Earth Engine App:**\n1. Install ngrok by following the [instruction](https://ngrok.com/download)\n3. Download the notebook [71_timelapse.ipynb](https://geemap.org/notebooks/71_timelapse/71_timelapse.ipynb) \n4. Run this from the command line: `voila --no-browser 71_timelapse.ipynb`\n5. Run this from the command line: `ngrok http 8866`\n6. Copy the link from the ngrok terminal window. The links looks like the following: https://randomstring.ngrok.io\n7. Share the link with anyone. \n\n**Optional steps:**\n* To show code cells from you app, run this from the command line: `voila --no-browser --strip_sources=False 71_timelapse.ipynb`\n* To protect your app with a password, run this: `ngrok http -auth=\"username:password\" 8866`\n* To run python simple http server in the directory, run this:`sudo python -m http.server 80` ", "_____no_output_____" ] ], [ [ "geemap.show_youtube(\"https://youtu.be/eRDZBVJcNCk\")", "_____no_output_____" ] ], [ [ "### Deploy web apps using Heroku", "_____no_output_____" ], [ "**Steps to deploy an Earth Engine App:**\n\n- [Sign up](https://signup.heroku.com/) for a free heroku account.\n- Follow the [instructions](https://devcenter.heroku.com/articles/getting-started-with-python#set-up) to install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and Heroku Command Line Interface (CLI).\n- Authenticate heroku using the `heroku login` command.\n- Clone this repository: <https://github.com/giswqs/geemap-heroku>\n- Create your own Earth Engine notebook and put it under the `notebooks` directory.\n- Add Python dependencies in the `requirements.txt` file if needed.\n- Edit the `Procfile` file by replacing `notebooks/geemap.ipynb` with the path to your own notebook.\n- Commit changes to the repository by using `git add . && git commit -am \"message\"`.\n- Create a heroku app: `heroku create`\n- Run the `config_vars.py` script to extract Earth Engine token from your computer and set it as an environment variable on heroku: `python config_vars.py`\n- Deploy your code to heroku: `git push heroku master`\n- Open your heroku app: `heroku open`\n\n**Optional steps:**\n\n- To specify a name for your app, use `heroku apps:create example`\n- To preview your app locally, use `heroku local web`\n- To hide code cells from your app, you can edit the `Procfile` file and set `--strip_sources=True`\n- To periodically check for idle kernels, you can edit the `Procfile` file and set `--MappingKernelManager.cull_interval=60 --MappingKernelManager.cull_idle_timeout=120`\n- To view information about your running app, use `heroku logs --tail`\n- To set an environment variable on heroku, use `heroku config:set NAME=VALUE`\n- To view environment variables for your app, use `heroku config`", "_____no_output_____" ] ], [ [ "geemap.show_youtube(\"https://youtu.be/nsIjfD83ggA\")", "_____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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb09e8d2c9df1dbebaef7cbfb518c23605e982e5
8,282
ipynb
Jupyter Notebook
wandb/run-20210519_231711-2p8s2bdn/tmp/code/_session_history.ipynb
Programmer-RD-AI/Heart-Disease-UCI
b077f8496fba3fe1a9a073c80d0a5df73c720f29
[ "Apache-2.0" ]
null
null
null
wandb/run-20210519_231711-2p8s2bdn/tmp/code/_session_history.ipynb
Programmer-RD-AI/Heart-Disease-UCI
b077f8496fba3fe1a9a073c80d0a5df73c720f29
[ "Apache-2.0" ]
null
null
null
wandb/run-20210519_231711-2p8s2bdn/tmp/code/_session_history.ipynb
Programmer-RD-AI/Heart-Disease-UCI
b077f8496fba3fe1a9a073c80d0a5df73c720f29
[ "Apache-2.0" ]
null
null
null
24.145773
265
0.497464
[ [ [ "import pandas as pd", "_____no_output_____" ], [ "data = pd.read_csv('./data.csv')", "_____no_output_____" ], [ "X,y = data.drop('target',axis=1),data['target']", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.25)", "_____no_output_____" ], [ "import torch\nimport torch.nn as nn", "_____no_output_____" ], [ "import numpy as np", "_____no_output_____" ], [ "X_train = torch.from_numpy(np.array(X_train).astype(np.float32))\ny_train = torch.from_numpy(np.array(y_train).astype(np.float32))\nX_test = torch.from_numpy(np.array(X_test).astype(np.float32))\ny_test = torch.from_numpy(np.array(y_test).astype(np.float32))", "_____no_output_____" ], [ "X_train.shape", "torch.Size([227, 13])" ], [ "X_test.shape", "torch.Size([76, 13])" ], [ "y_train.shape", "torch.Size([227])" ], [ "y_test.shape", "torch.Size([76])" ], [ "import torch.nn.functional as F", "_____no_output_____" ], [ "class Test_Model(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(13,32)\n self.fc2 = nn.Linear(32,64)\n self.fc3 = nn.Linear(64,128)\n self.fc4 = nn.Linear(128,256)\n self.fc5 = nn.Linear(256,512)\n self.fc6 = nn.Linear(512,256)\n self.fc7 = nn.Linear(256,1)\n \n def forward(self,X):\n preds = self.fc1(X)\n preds = F.relu(preds)\n preds = self.fc2(preds)\n preds = F.relu(preds)\n preds = self.fc3(preds)\n preds = F.relu(preds)\n preds = self.fc4(preds)\n preds = F.relu(preds)\n preds = self.fc5(preds)\n preds = F.relu(preds)\n preds = self.fc6(preds)\n preds = F.relu(preds)\n preds = self.fc7(preds)\n return F.sigmoid(preds)", "_____no_output_____" ], [ "device = torch.device('cuda')", "_____no_output_____" ], [ "X_train = X_train.to(device)\ny_train = y_train.to(device)\nX_test = X_test.to(device)\ny_test = y_test.to(device)", "_____no_output_____" ], [ "PROJECT_NAME = 'Heart-Disease-UCI'", "_____no_output_____" ], [ "def get_loss(criterion,X,y,model):\n model.eval()\n with torch.no_grad():\n preds = model(X.float().to(device))\n preds = preds.to(device)\n y = y.to(device)\n loss = criterion(preds,y)\n model.train()\n return loss.item()\ndef get_accuracy(X,y,model):\n model.eval()\n with torch.no_grad():\n correct = 0\n total = 0\n for i in range(len(X)):\n pred = model(X[i].float().to(device))\n pred.to(device)\n if round(int(pred[0])) == round(int(y[i])):\n correct += 1\n total += 1\n if correct == 0:\n correct += 1\n model.train()\n return round(correct/total,3)", "_____no_output_____" ], [ "import wandb", "_____no_output_____" ], [ "from tqdm import tqdm", "_____no_output_____" ], [ "EPOCHS = 100", "_____no_output_____" ], [ "model = Test_Model().to(device)\noptimizer = torch.optim.SGD(model.parameters(),lr=0.25)\ncriterion = nn.L1Loss()\nwandb.init(project=PROJECT_NAME,name='baseline')\nfor _ in tqdm(range(EPOCHS)):\n preds = model(X_train.float().to(device))\n preds = preds.view(len(preds),)\n preds.to(device)\n loss = criterion(preds,y_train)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n wandb.log({'loss':loss.item(),'val_loss':get_loss(criterion,X_test,y_test,model),'accuracy':get_accuracy(X_train,y_train,model),'val_accuracy':get_accuracy(X_test,y_test,model)})\nwandb.finish()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb09ea892258303c95a79934854eaee1e325285a
78,587
ipynb
Jupyter Notebook
module3/assignment_regression_classification_3.ipynb
AdrianduPlessis/DS-Unit-2-Regression-Classification
c32cc9cdcac7458950882ed14a584c2a48aec1ea
[ "MIT" ]
null
null
null
module3/assignment_regression_classification_3.ipynb
AdrianduPlessis/DS-Unit-2-Regression-Classification
c32cc9cdcac7458950882ed14a584c2a48aec1ea
[ "MIT" ]
null
null
null
module3/assignment_regression_classification_3.ipynb
AdrianduPlessis/DS-Unit-2-Regression-Classification
c32cc9cdcac7458950882ed14a584c2a48aec1ea
[ "MIT" ]
null
null
null
85.327904
18,052
0.681041
[ [ [ "<a href=\"https://colab.research.google.com/github/AdrianduPlessis/DS-Unit-2-Regression-Classification/blob/master/module3/assignment_regression_classification_3.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "Lambda School Data Science, Unit 2: Predictive Modeling\n\n# Regression & Classification, Module 3\n\n## Assignment\n\nWe're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices.\n\nBut not just for condos in Tribeca...\n\nInstead, predict property sales prices for **One Family Dwellings** (`BUILDING_CLASS_CATEGORY` == `'01 ONE FAMILY DWELLINGS'`) using a subset of the data where the **sale price was more than \\\\$100 thousand and less than $2 million.** \n\nThe [NYC Department of Finance](https://www1.nyc.gov/site/finance/taxes/property-rolling-sales-data.page) has a glossary of property sales terms and NYC Building Class Code Descriptions. The data comes from the [NYC OpenData](https://data.cityofnewyork.us/browse?q=NYC%20calendar%20sales) portal.\n\n\n- [ ] Do train/test split. Use data from January — March 2019 to train. Use data from April 2019 to test.\n- [ ] Do exploratory visualizations with Seaborn.\n- [ ] Do one-hot encoding of categorical features.\n- [ ] Do feature selection with `SelectKBest`.\n- [ ] Fit a linear regression model with multiple features.\n- [ ] Get mean absolute error for the test set.\n- [ ] As always, commit your notebook to your fork of the GitHub repo.\n\n\n## Stretch Goals\n- [ ] Add your own stretch goal(s) !\n- [ ] Do [feature scaling](https://scikit-learn.org/stable/modules/preprocessing.html).\n- [ ] Learn more about feature selection:\n - [\"Permutation importance\"](https://www.kaggle.com/dansbecker/permutation-importance)\n - [scikit-learn's User Guide for Feature Selection](https://scikit-learn.org/stable/modules/feature_selection.html)\n - [mlxtend](http://rasbt.github.io/mlxtend/) library\n - scikit-learn-contrib libraries: [boruta_py](https://github.com/scikit-learn-contrib/boruta_py) & [stability-selection](https://github.com/scikit-learn-contrib/stability-selection)\n - [_Feature Engineering and Selection_](http://www.feat.engineering/) by Kuhn & Johnson.\n- [ ] Try [statsmodels](https://www.statsmodels.org/stable/index.html) if you’re interested in more inferential statistical approach to linear regression and feature selection, looking at p values and 95% confidence intervals for the coefficients.\n- [ ] Read [_An Introduction to Statistical Learning_](http://faculty.marshall.usc.edu/gareth-james/ISL/ISLR%20Seventh%20Printing.pdf), Chapters 1-3, for more math & theory, but in an accessible, readable way (without an excessive amount of formulas or academic pre-requisites).\n(That book is good regardless of whether your cultural worldview is inferential statistics or predictive machine learning)\n- [ ] Read Leo Breiman's paper, [\"Statistical Modeling: The Two Cultures\"](https://projecteuclid.org/download/pdf_1/euclid.ss/1009213726)\n- [ ] Try [scikit-learn pipelines](https://scikit-learn.org/stable/modules/compose.html):\n\n> Pipeline can be used to chain multiple estimators into one. This is useful as there is often a fixed sequence of steps in processing the data, for example feature selection, normalization and classification. Pipeline serves multiple purposes here:\n\n> - **Convenience and encapsulation.** You only have to call fit and predict once on your data to fit a whole sequence of estimators.\n> - **Joint parameter selection.** You can grid search over parameters of all estimators in the pipeline at once.\n> - **Safety.** Pipelines help avoid leaking statistics from your test data into the trained model in cross-validation, by ensuring that the same samples are used to train the transformers and predictors.", "_____no_output_____" ] ], [ [ "# If you're in Colab...\nimport os, sys\nin_colab = 'google.colab' in sys.modules\n\nif in_colab:\n # Install required python packages:\n # category_encoders, version >= 2.0\n # pandas-profiling, version >= 2.0\n # plotly, version >= 4.0\n !pip install --upgrade category_encoders pandas-profiling plotly\n \n # Pull files from Github repo\n os.chdir('/content')\n !git init .\n !git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Regression-Classification.git\n !git pull origin master\n \n # Change into directory for module\n os.chdir('module3')", "Requirement already up-to-date: category_encoders in /usr/local/lib/python3.6/dist-packages (2.0.0)\nRequirement already up-to-date: pandas-profiling in /usr/local/lib/python3.6/dist-packages (2.3.0)\nRequirement already up-to-date: plotly in /usr/local/lib/python3.6/dist-packages (4.1.1)\nRequirement already satisfied, skipping upgrade: patsy>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.5.1)\nRequirement already satisfied, skipping upgrade: scipy>=0.19.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (1.3.1)\nRequirement already satisfied, skipping upgrade: statsmodels>=0.6.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.10.1)\nRequirement already satisfied, skipping upgrade: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.21.3)\nRequirement already satisfied, skipping upgrade: numpy>=1.11.3 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (1.16.5)\nRequirement already satisfied, skipping upgrade: pandas>=0.21.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.24.2)\nRequirement already satisfied, skipping upgrade: missingno>=0.4.2 in /usr/local/lib/python3.6/dist-packages (from pandas-profiling) (0.4.2)\nRequirement already satisfied, skipping upgrade: jinja2>=2.8 in /usr/local/lib/python3.6/dist-packages (from pandas-profiling) (2.10.1)\nRequirement already satisfied, skipping upgrade: phik>=0.9.8 in /usr/local/lib/python3.6/dist-packages (from pandas-profiling) (0.9.8)\nRequirement already satisfied, skipping upgrade: htmlmin>=0.1.12 in /usr/local/lib/python3.6/dist-packages (from pandas-profiling) (0.1.12)\nRequirement already satisfied, skipping upgrade: confuse>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from pandas-profiling) (1.0.0)\nRequirement already satisfied, skipping upgrade: matplotlib>=1.4 in /usr/local/lib/python3.6/dist-packages (from pandas-profiling) (3.0.3)\nRequirement already satisfied, skipping upgrade: astropy in /usr/local/lib/python3.6/dist-packages (from pandas-profiling) (3.0.5)\nRequirement already satisfied, skipping upgrade: retrying>=1.3.3 in /usr/local/lib/python3.6/dist-packages (from plotly) (1.3.3)\nRequirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from plotly) (1.12.0)\nRequirement already satisfied, skipping upgrade: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.20.0->category_encoders) (0.13.2)\nRequirement already satisfied, skipping upgrade: python-dateutil>=2.5.0 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.21.1->category_encoders) (2.5.3)\nRequirement already satisfied, skipping upgrade: pytz>=2011k in /usr/local/lib/python3.6/dist-packages (from pandas>=0.21.1->category_encoders) (2018.9)\nRequirement already satisfied, skipping upgrade: seaborn in /usr/local/lib/python3.6/dist-packages (from missingno>=0.4.2->pandas-profiling) (0.9.0)\nRequirement already satisfied, skipping upgrade: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from jinja2>=2.8->pandas-profiling) (1.1.1)\nRequirement already satisfied, skipping upgrade: jupyter-client>=5.2.3 in /usr/local/lib/python3.6/dist-packages (from phik>=0.9.8->pandas-profiling) (5.3.1)\nRequirement already satisfied, skipping upgrade: pytest>=4.0.2 in /usr/local/lib/python3.6/dist-packages (from phik>=0.9.8->pandas-profiling) (5.1.2)\nRequirement already satisfied, skipping upgrade: numba>=0.38.1 in /usr/local/lib/python3.6/dist-packages (from phik>=0.9.8->pandas-profiling) (0.40.1)\nRequirement already satisfied, skipping upgrade: nbconvert>=5.3.1 in /usr/local/lib/python3.6/dist-packages (from phik>=0.9.8->pandas-profiling) (5.6.0)\nRequirement already satisfied, skipping upgrade: pytest-pylint>=0.13.0 in /usr/local/lib/python3.6/dist-packages (from phik>=0.9.8->pandas-profiling) (0.14.1)\nRequirement already satisfied, skipping upgrade: pyyaml in /usr/local/lib/python3.6/dist-packages (from confuse>=1.0.0->pandas-profiling) (3.13)\nRequirement already satisfied, skipping upgrade: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.4->pandas-profiling) (0.10.0)\nRequirement already satisfied, skipping upgrade: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.4->pandas-profiling) (1.1.0)\nRequirement already satisfied, skipping upgrade: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.4->pandas-profiling) (2.4.2)\nRequirement already satisfied, skipping upgrade: traitlets in /usr/local/lib/python3.6/dist-packages (from jupyter-client>=5.2.3->phik>=0.9.8->pandas-profiling) (4.3.2)\nRequirement already satisfied, skipping upgrade: pyzmq>=13 in /usr/local/lib/python3.6/dist-packages (from jupyter-client>=5.2.3->phik>=0.9.8->pandas-profiling) (17.0.0)\nRequirement already satisfied, skipping upgrade: tornado>=4.1 in /usr/local/lib/python3.6/dist-packages (from jupyter-client>=5.2.3->phik>=0.9.8->pandas-profiling) (4.5.3)\nRequirement already satisfied, skipping upgrade: jupyter-core in /usr/local/lib/python3.6/dist-packages (from jupyter-client>=5.2.3->phik>=0.9.8->pandas-profiling) (4.5.0)\nRequirement already satisfied, skipping upgrade: packaging in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (19.1)\nRequirement already satisfied, skipping upgrade: atomicwrites>=1.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (1.3.0)\nRequirement already satisfied, skipping upgrade: importlib-metadata>=0.12; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (0.20)\nRequirement already satisfied, skipping upgrade: pluggy<1.0,>=0.12 in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (0.13.0)\nRequirement already satisfied, skipping upgrade: more-itertools>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (7.2.0)\nRequirement already satisfied, skipping upgrade: attrs>=17.4.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (19.1.0)\nRequirement already satisfied, skipping upgrade: wcwidth in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (0.1.7)\nRequirement already satisfied, skipping upgrade: py>=1.5.0 in /usr/local/lib/python3.6/dist-packages (from pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (1.8.0)\nRequirement already satisfied, skipping upgrade: llvmlite>=0.25.0dev0 in /usr/local/lib/python3.6/dist-packages (from numba>=0.38.1->phik>=0.9.8->pandas-profiling) (0.29.0)\nRequirement already satisfied, skipping upgrade: nbformat>=4.4 in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (4.4.0)\nRequirement already satisfied, skipping upgrade: pandocfilters>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (1.4.2)\nRequirement already satisfied, skipping upgrade: mistune<2,>=0.8.1 in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (0.8.4)\nRequirement already satisfied, skipping upgrade: entrypoints>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (0.3)\nRequirement already satisfied, skipping upgrade: pygments in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (2.1.3)\nRequirement already satisfied, skipping upgrade: bleach in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (3.1.0)\nRequirement already satisfied, skipping upgrade: testpath in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (0.4.2)\nRequirement already satisfied, skipping upgrade: defusedxml in /usr/local/lib/python3.6/dist-packages (from nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (0.6.0)\nRequirement already satisfied, skipping upgrade: pylint>=1.4.5 in /usr/local/lib/python3.6/dist-packages (from pytest-pylint>=0.13.0->phik>=0.9.8->pandas-profiling) (2.3.1)\nRequirement already satisfied, skipping upgrade: setuptools in /usr/local/lib/python3.6/dist-packages (from kiwisolver>=1.0.1->matplotlib>=1.4->pandas-profiling) (41.2.0)\nRequirement already satisfied, skipping upgrade: decorator in /usr/local/lib/python3.6/dist-packages (from traitlets->jupyter-client>=5.2.3->phik>=0.9.8->pandas-profiling) (4.4.0)\nRequirement already satisfied, skipping upgrade: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets->jupyter-client>=5.2.3->phik>=0.9.8->pandas-profiling) (0.2.0)\nRequirement already satisfied, skipping upgrade: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.12; python_version < \"3.8\"->pytest>=4.0.2->phik>=0.9.8->pandas-profiling) (0.6.0)\nRequirement already satisfied, skipping upgrade: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.6/dist-packages (from nbformat>=4.4->nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (2.6.0)\nRequirement already satisfied, skipping upgrade: webencodings in /usr/local/lib/python3.6/dist-packages (from bleach->nbconvert>=5.3.1->phik>=0.9.8->pandas-profiling) (0.5.1)\nRequirement already satisfied, skipping upgrade: isort<5,>=4.2.5 in /usr/local/lib/python3.6/dist-packages (from pylint>=1.4.5->pytest-pylint>=0.13.0->phik>=0.9.8->pandas-profiling) (4.3.21)\nRequirement already satisfied, skipping upgrade: mccabe<0.7,>=0.6 in /usr/local/lib/python3.6/dist-packages (from pylint>=1.4.5->pytest-pylint>=0.13.0->phik>=0.9.8->pandas-profiling) (0.6.1)\nRequirement already satisfied, skipping upgrade: astroid<3,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from pylint>=1.4.5->pytest-pylint>=0.13.0->phik>=0.9.8->pandas-profiling) (2.2.5)\nRequirement already satisfied, skipping upgrade: lazy-object-proxy in /usr/local/lib/python3.6/dist-packages (from astroid<3,>=2.2.0->pylint>=1.4.5->pytest-pylint>=0.13.0->phik>=0.9.8->pandas-profiling) (1.4.2)\nRequirement already satisfied, skipping upgrade: typed-ast>=1.3.0; implementation_name == \"cpython\" in /usr/local/lib/python3.6/dist-packages (from astroid<3,>=2.2.0->pylint>=1.4.5->pytest-pylint>=0.13.0->phik>=0.9.8->pandas-profiling) (1.4.0)\nRequirement already satisfied, skipping upgrade: wrapt in /usr/local/lib/python3.6/dist-packages (from astroid<3,>=2.2.0->pylint>=1.4.5->pytest-pylint>=0.13.0->phik>=0.9.8->pandas-profiling) (1.11.2)\nReinitialized existing Git repository in /content/.git/\nfatal: remote origin already exists.\nFrom https://github.com/LambdaSchool/DS-Unit-2-Regression-Classification\n * branch master -> FETCH_HEAD\nAlready up to date.\n" ], [ "# Ignore this Numpy warning when using Plotly Express:\n# FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.\nimport warnings\nwarnings.filterwarnings(action='ignore', category=FutureWarning, module='numpy')", "_____no_output_____" ], [ "import pandas as pd\nimport pandas_profiling\n\n# Read New York City property sales data\ndf = pd.read_csv('../data/NYC_Citywide_Rolling_Calendar_Sales.csv')\n\n# Change column names: replace spaces with underscores\ndf.columns = [col.replace(' ', '_') for col in df]\n\n# SALE_PRICE was read as strings.\n# Remove symbols, convert to integer\ndf['SALE_PRICE'] = (\n df['SALE_PRICE']\n .str.replace('$','')\n .str.replace('-','')\n .str.replace(',','')\n .astype(int)\n)", "_____no_output_____" ], [ "'''\nDo train/test split. Use data from January — March 2019 to train. Use data from April 2019 to test.\nDo exploratory visualizations with Seaborn.\nDo one-hot encoding of categorical features.\nDo feature selection with SelectKBest.\nFit a linear regression model with multiple features.\nGet mean absolute error for the test set.\nAs always, commit your notebook to your fork of the GitHub repo.\n'''", "_____no_output_____" ], [ "##Do train/test split. Use data from January — March 2019 to train. Use data from April 2019 to test.\n#Convert to datetime to facilitate split\ndf['SALE_DATE'] = pd.to_datetime(df['SALE_DATE'], infer_datetime_format=True)\n#Define split location\ntest_start_barrier = pd.to_datetime('04-01-2019')\n#Split data based on barrier\ntrain = df[df.SALE_DATE < test_start_barrier]\ntest = df[df.SALE_DATE >= test_start_barrier]\n\n", "_____no_output_____" ], [ "#Sanity check\ndf.shape, train.shape, test.shape", "_____no_output_____" ], [ "numeric_cols.head()", "_____no_output_____" ], [ "##Do exploratory visualizations with Seaborn.\nimport seaborn as sns\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "sns.catplot(x=\"BOROUGH\", y='SALE_PRICE', data = train, kind = 'bar', color = 'grey');", "_____no_output_____" ], [ "sns.catplot(x=\"TAX_CLASS_AT_TIME_OF_SALE\", y='SALE_PRICE', data = train, kind = 'bar', color = 'grey');", "_____no_output_____" ], [ "##Do one-hot encoding of categorical features.", "_____no_output_____" ], [ "#Identify binary encoded columns\n#good piece to have fuction prepped for sprint\ntrain.head()\n#no binaries", "_____no_output_____" ], [ "train.describe(exclude='number')", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0a0695421a7859a1504a41f0c9d4449fd170ae
4,304
ipynb
Jupyter Notebook
Houses data cleaning.ipynb
DiegoHueltes/aml-bigdataspain
d778272a8286a70f69c612f3bb456d3693d3c729
[ "MIT" ]
1
2019-05-19T02:48:48.000Z
2019-05-19T02:48:48.000Z
Houses data cleaning.ipynb
DiegoHueltes/aml-bigdataspain
d778272a8286a70f69c612f3bb456d3693d3c729
[ "MIT" ]
null
null
null
Houses data cleaning.ipynb
DiegoHueltes/aml-bigdataspain
d778272a8286a70f69c612f3bb456d3693d3c729
[ "MIT" ]
null
null
null
32.606061
136
0.587361
[ [ [ "import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder", "_____no_output_____" ], [ "train = pd.read_csv('houses/train.csv')\ntest = pd.read_csv('houses/test.csv')", "_____no_output_____" ], [ "sales_price = train['SalePrice']", "_____no_output_____" ], [ "train = train.drop(train[(train['GrLivArea'] > 4000) & (train['SalePrice'] < 300000)].index)\nntrain = train.shape[0]\nall_data = pd.concat((train, test)).reset_index(drop=True)\nall_data.drop(['SalePrice'], axis=1, inplace=True)\nall_data[\"LotFrontage\"] = all_data.groupby(\"Neighborhood\")[\"LotFrontage\"].transform(lambda x: x.fillna(x.median()))\nfor col in (\n'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond', 'PoolQC', 'MiscFeature', 'Alley', 'Fence', 'FireplaceQu',\n'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'MasVnrType', 'MSSubClass'):\n all_data[col] = all_data[col].fillna('None')\nfor col in (\n'GarageYrBlt', 'GarageArea', 'GarageCars', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath',\n'BsmtHalfBath', 'MasVnrArea'):\n all_data[col] = all_data[col].fillna(0)\nfor col in ('MSZoning', 'Electrical', 'KitchenQual', 'Exterior1st', 'Exterior2nd', 'SaleType'):\n all_data[col] = all_data[col].fillna(all_data[col].mode()[0])\nall_data = all_data.drop(['Utilities'], axis=1)\nall_data[\"Functional\"] = all_data[\"Functional\"].fillna(\"Typ\")\nfor col in ('OverallCond', 'YrSold', 'MoSold'):\n all_data[col] = all_data[col].astype(str)\nall_data['MSSubClass'] = all_data['MSSubClass'].apply(str)\ncols = (\n'FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual', 'GarageCond', 'ExterQual', 'ExterCond', 'HeatingQC', 'PoolQC',\n'KitchenQual', 'BsmtFinType1', 'BsmtFinType2', 'Functional', 'Fence', 'BsmtExposure', 'GarageFinish', 'LandSlope',\n'LotShape', 'PavedDrive', 'Street', 'Alley', 'CentralAir', 'MSSubClass', 'OverallCond', 'YrSold', 'MoSold')\nfor c in cols:\n lbl = LabelEncoder()\n lbl.fit(list(all_data[c].values))\n all_data[c] = lbl.transform(list(all_data[c].values))\nall_data = pd.get_dummies(all_data)\ntrain = all_data[:ntrain]\ntest = all_data[ntrain:]", "_____no_output_____" ], [ "train['SalePrice'] = sales_price\ntrain.to_csv('houses/clean_train.csv', index=False)\ntest.to_csv('houses/clean_test.csv', index=False)", "/Users/diegohueltes/anaconda3/envs/tpot-xgboost/lib/python3.5/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n \"\"\"Entry point for launching an IPython kernel.\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
cb0a2eca7a667fe0b4581e2030125e8f2bc93720
80,326
ipynb
Jupyter Notebook
4_CNN_Models.ipynb
seanlaidlaw/land-use-tensorflow-project
ff0f94ffafee663eb496daaca242ddd1dc1e80b6
[ "MIT" ]
null
null
null
4_CNN_Models.ipynb
seanlaidlaw/land-use-tensorflow-project
ff0f94ffafee663eb496daaca242ddd1dc1e80b6
[ "MIT" ]
null
null
null
4_CNN_Models.ipynb
seanlaidlaw/land-use-tensorflow-project
ff0f94ffafee663eb496daaca242ddd1dc1e80b6
[ "MIT" ]
null
null
null
80,326
80,326
0.835334
[ [ [ "import pickle\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Reshape\nfrom tensorflow.keras.layers import Conv1D\nfrom tensorflow.keras.layers import MaxPooling1D\nfrom tensorflow.keras.layers import GlobalAveragePooling1D\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv1D, Flatten, MaxPooling1D\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.datasets import load_iris", "_____no_output_____" ], [ "from google.colab import drive\ndrive.mount('/content/drive')\nimport os\nos.chdir('/content/drive/My Drive/University/ProjetML/')\nos.chdir('Data/Donnees_ENT/')", "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], [ "# load in data with 80:20 split for training:test\nwith open('Final_Data_sets80.pickle', \"rb\") as f:\n x_train, y_train, x_test, y_test = pickle.load(f)", "_____no_output_____" ], [ "# convert (498700, 32) to (498700, 32, 1) so fits in Conv1D input layer\nx_train = x_train.reshape(x_train.shape[0], x_train.shape[1], 1)\nx_test = x_test.reshape(x_test.shape[0], x_test.shape[1], 1)", "_____no_output_____" ] ], [ [ "## CNN Architectures", "_____no_output_____" ], [ "1D CNN are often use for sensor data, or for time series data. \n![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAArwAAADSCAYAAACo2xNAAAAgAElEQVR4AexdB3gV1db1PX1P/6egiCAdFEGqIr0XAekQSCAQeu+9i9KLSEda6FVAVDoIEpAagoIkoEiRolIEaaGIdf3f2uFcJjcJhNyZa27Y8307M3cyc+bMOmdm1t5nn70fgy6KgCKgCCgCioAioAgoAopAEkbgsSR8b3prioAioAgoAoqAIqAIKAKKAJTwaidQBBQBRUARUAQUAUVAEUjSCCjhTdLNqzenCCgCioAioAgoAoqAIqCEV/tAokDgr7/+wtWrV3H58mX8+eefiaJOTlTi5s2buHTpEi5evOiSW7du4e+//3biclqmIqAIKAKKgCKgCADq0qC9IHEgcP36dYwaNQq9evXCzz//nDgq5UAtVqxYgWbNmqF+/foiDRo0wNq1a/Hbb785cDUtUhFQBBQBRUARUASIgFp4tR8kCgRIcsuXL49XX30VJ0+eTBR1cqISixYtgp+fH6pUqYJs2bLhscceE6J/+/ZtJy6nZSoCioAioAgoAoqAEl7tA4kFAQ7xV65cGXnz5sWpU6cSS7Vsr8evv/4KWrNp0R09ejRSpEiB999/H0p4bYdaC1QEFAFFQBFQBFwIqIXXBYVu/JMIeEJ46f/6xx9/iO/vw/jC8lj6DvPc+53H/9Gv+EHHET8ey+Mo7ov7NSZPnoyUKVMq4XUHSn8rAoqAIqAIKAI2I6CE12ZAtbiEIRAX4SVJvHLlCr799lt8//334AQv68KJbocOHcLmzZsREhIix924ccN6iGyTgPJ8Crd5DLf37Nkj5x4+fNhVNi2wR44ckUllvD7dLfbu3YvPP/8c4eHhYqF1vwCPu3btGr755hts2rRJ6sIyIyMj4yTTkyZNUsLrDqT+VgQUAUVAEVAEHEBACa8DoGqRD49AbISX1teffvoJAwcORI4cOdC+fXshqab0c+fOYciQIciSJQuSJ08ukjNnTkyZMkUiPpjjuCZppctEtWrV8N1332HGjBkoXbo0nn/+efGjLVCgAMLCwuQUTiKjL/H48eNx7NgxuS5dD/71r38hbdq0mDhxYgzSy/rTRSF79uzipvDss8/ipZdewoQJE+Ta7tZdXkgJr7WFdFsRUAQUAUVAEXAOASW8zmGrJT8EAu6ElwSRFtiePXsiffr0aNy4MY4ePeoqkcf37t0bmTJlQpMmTcDJYHPnzpWJb3QTmDNnTjS3ApLjokWLgoS4a9euKFasGFq0aIERI0agcOHCIrT2cmEkhRdeeEGuGRQUJMf27dsXQ4cORZ48eZAqVSqsX7/eZbmlZXfkyJFSF0ZdWLhwIRYsWIAaNWogTZo0mDZtGui76056lfC6mlM3FAFFQBFQBBQBRxFQwusovFp4fBGwEl4SXboUtG3bFhkzZkSHDh2iWXZ///13zJs3D+nSpUPr1q2jhTFbuXIlMmfOjKpVq+L06dOuy5PwlixZUqy0JL7z588XEsq4uLxO2bJlXRbejz/+WIgqrcaMpkBXCbPQisv97733nssF4sMPP5R6BgYGRrtmaGgoXn75ZbEqM/KEEl6Doq4VAUVAEVAEFAHvIqCE17t469XiQMAQ3ty5c2PdunVo2LAhXnzxRXTr1g1nzpyJdhaTU9C9gZbfDz74QEjmiRMnZL1lyxYUL15c3BwOHDjgOo+Et0SJEkiWLJm4JJioCPSxpQX23XffFfcFklISXlp46UaxceNGVxncWLx4MTJkyIB+/fqJfy73sS7//e9/XS4QJOysD69fpEgR5MuXD7t371bCGw1J/aEIKAKKgCKgCHgPASW83sNar3QfBEh4aU2lj2z16tXx+OOPgxbTH374IcZZ3FexYkU899xzKFSoECpUqOCScuXKieWX5ezcudN1Lgkv3Rh4PAmpu7XVHMhoDCS89NkdMGAAaE22LsuWLRPXhR49egjhPX/+vLgu0L+XZbNepj6sC+tBf2ASZ/drqkuDFVndVgQUAUVAEVAEnENACa9z2GrJD4GAIby0njZt2lSsu3RL2LdvXzRfXBZJ6+kbb7yB1KlTo169eujcuTM6derkki5dughZZWQHsxgfXlp/SVLjWgzhpR8w/Xu5WImqIbzdu3eXSA90vShTpgyeeuqpWOvCug0aNEiiO1jLYblKeONqBd2vCCgCioAioAjYi4ASXnvx1NISiIBxaSCR3b9/vxBWElpaexk9wRrX9scff0SlSpVA94ft27ff94qGZBoLLwkvt+NaYiO81mOthJfhy1jv2rVri6vEtm3brIc+cFsJ7wMh0gMUAUVAEVAEFAFbEFDCawuMWoinCBjCy0xrdFng7z59+oil19/fH19//bUkf+B1GEN32LBhYuF9++23Y4QgoxvCpUuXcOfOHVe1nCC8jAHMhREa6AJBf2MrmSbZZkY1xhHWKA2uptANRUARUAQUAUXA6wgo4fU65HrB2BCwEl6TWpjkkREaGCuXoceOHz/uOpXJJhhTlzF4x40bByZ5oKsD16tXrxY3AuvxThJe+gQHBARIpAaSX5Jz1oV1ZF0Yz5fbxtpsboIWXt4bXTB27dol7huM5kCSrIsioAgoAoqAIqAI2IeAEl77sNSSPECAhJc+u4xoYAgviyNppZ8uEzlwotiFCxdcV6E7A/1nOXmNiSNq1aolUREYm5cTx5hgwiwkvIzSUKpUqWhWWPN/s6ZLwyeffCLWY5JX92X58uWSUILxgY2Fl8fQDYNuFqxnwYIF4efnJ9dj6DTWiyTYnfAytTCjQVCyZs0qhJmxhZkkQxdFQBFQBBQBRUARsA8BJbz2YakleYAA4+EyWQPDjNEFwLrQakvyydi3nCRmXb788ksJKcYwZkz6QIvw1KlTERERES3CAsOPzZw5U4TbcS3M7mau98UXX8Q4jOWOHTsWGzZsgAltZojswYMHxdWiUaNGqF+/voQrI6nlflptzXGmUCa64MQ4umVQSHaZ9OJ+9TPn6loRUAQUAUVAEVAE4o+AEt74Y6VHOoSAOxHkZbgvtv1x/Y8TyGhxJWG1LnGVE1fZ1nPdt2M7J7Z9zLzGulgn2sWnLOsxsZVr/b9uKwKKgCKgCCgCikD8EVDCG3+s9MhEiEBcxDCu/U7dwv2ud7//OVUfLVcRUAQUAUVAEVAE7iGghPceFrqlCCgCioAioAgoAoqAIpAEEVDCmwQbVW9JEVAEFAFFQBFQBBQBReAeAkp472GhW4qAIqAIKAKKgCKgCCgCSRABJbxJsFH1lhQBRUARUAQUAUVAEVAE7iGghPceFrqlCCgCioAioAgoAoqAIpAEEVDCmwQbVW9JEVAEFAFFQBFQBBQBReAeAkp472GhW48YAgwXxsxqTCDx+++/xxn39xGDRW9XEVAEFAFFQBFIcggo4U1yTao3FF8ESHjPnj2LD5cskexqd+7cie+pepwioAgoAoqAIqAI+BACSnh9qLG0qvYiQOvugQMH0LZ1G6xauRJXr1y19wJamiKgCCgCioAioAgkCgSU8CaKZtBK/BMIkOCuXbMWlSq+hfFjxuHUyVP/RDX0moqAIqAIKAKKgCLgMAJKeB0GWItPXAjQjcGk+j154ntMGDceJYoURaf27bH/q68SV2W1NoqAIqAIKAKKgCJgCwJKeG2BUQvxFQSshHdvaCgCavohc/oMyJ41KzasX+8rt6H1VAQUAUVAEVAEFIGHQEAJ70OApYf6NgLGsvvX33/h2tVrmDkjGKUKF8XCefPxep7XMGLYMPz0448SucG371RrrwgoAoqAIqAIKAJWBJTwWtHQ7UcCgevXrmHtqjVo37othgwchGtXr2LWjJloHNQQU6dMwYULFx4JHPQmFQFFQBFQBBSBRwUBJbyPSkvrfQoCDD329f4DqOdfF107d0bY3r0Sg/fEiRMYN2YsChcogI3rN+D69euKmCKgCCgCioAioAgkEQSU8CaRhvynb8P4xibW9V9//YWffvoJq1euxNv9+qF54yb4fPNm3Lp1S6D7448/sP+r/RjQ7220b9se8+fNw4njx8HzEus9mXr9022v11cEFAFFQBFQBBI7Akp4E3sL+Uj9SL6YrYxZy27evPmPS2RkJK5cuYLz58/j5PffIyI8AtOmTEGDuoFo27q1TFDj/7n8/XcUyLdu3sK+sDD07d0bftWqY+Tw4QgLC8PxY8clQcXlXy6L5Zf3d+sfvkcS9d9++80VccJHuolWUxFQBBQBRUAR+EcQUML7j8Du+xclwaV7AIf+f/nlFyGWR44cEcK4a8cO7N6585+RXbuwc8cObA0JwepPV2Lm9Ono37cvmjdpipbNmmP8mLGIiIgQYs57sC7mnk6ePIk5s2ahVfPmcl73Ll0xeeJEfLJiBT7f/Dl2bt+OPbt2/TP3t3MniC8jTBwKP4SffvwJly5dkkl4VDZokdZFEVAEFAFFQBFQBKIjoIQ3Oh76K54I/PH77zLkv+zDD9GnVy8E1a+PyhUr4s3SZVDhn5QyZVChTDlUKl8BftVqICigHnp374Hg6dNx8OuvcfXqVbGMmts0pNesuZ/3duNGJI58ewRLFi0RN4cmDYJQu0ZNVClfERXLlEUFXucfu8+yKF+qtNxnPf8A8UUmQWfWOJJeXRQBRUARUAQUAUUgOgJKeKPjob8egACJIaMY0P91zOjRaNGkKdq1ao2JEybgk48/wfp167B+3XqsX7s+as1tb8radVi/fj02bNiAzzdtwhfbtklCiTOnT0cjug+4Tfn3n3/9ifPnziP8YDh2bN8u97xxw0a5x3W8jjfvy1zL4Lp+PVatWoUZ06ajR+euaNKgIQb074/Vq1bhhx9+0NBq8WlgPUYRUAQUAUXgkUFACe8j09Se3yjJLofP58yajRKFC6NGtWoYP3Ycdu/ahV8uXfL8Al4owWrJvd/l4nvc/crwxv8ir0fi6wMHMCt4loRVy5EmE94f9R7OnDkjPtXeqINeQxFQBBQBRUARSOwIKOFN7C2USOr3559/4uLFixg5YjhKFi6CUSNG4vTp04i8cUN8efl/XyGJiQRSj6tBvOmz+9tvd3Dzxk1RRoKnTUfxfPnRr3dvnDp1SkmvxyhrAYqAIqAIKAJJAQElvEmhFb1wDz9fuACSqdLFSmD0e6MlxBdJri6JCwFOIJwVHIzi+Qtg8LsDcer06cRVQa2NIqAIKAKKgCLwDyCghPcfAN2XLmmsiHRbqFC6LN4bMUosh9yvFt3E1ZKmPeh2Mm/uXKR/+mmsXrUav97+VaM3JK6m0tooAoqAIqAIeBkBJbxeBtzXLkcrLkNfBU8PRokiRXH06DFXMgZfu5ekXt+/cU8JIeltFNQQ/Xr1xtcHvlbXhqTe+Hp/ioAioAgoAvdFQAnvfeHRfzID2caNG9GuZWsMevdd8RNVVBIpApawwky8MW/OXDRt2AhzZ8/GnV9/TaSV1mopAoqAIqAIKALOI6CE13mMffoKf/z5JyZNnIBGgfXx+abNuHHzhk/fz6NS+d/u3MG3h7+RrHHdOncGs8jpoggoAoqAIqAIPKoIKOF9VFs+nvfNdMG9evREj27dILFsf/89nmfqYf8kAn//9Rfu3P4VU6dMQfnSZcQy//df91we/sm66bUVAUVAEVAEFAFvI6CE19uI+9j1bt2+jS6dO2PM++9HZfGyDJv72K08UtU1zfTRRx+hWuUqOH70KH7/7XedaPhI9QK9WUVAEVAEFAGDgBJeg4SuY0Xg1s2bWLH8I2zZ/LmLLJloALGeoDsTFQJfffkVli5ZirM//gT6Y2vbJarm0cooAoqAIqAIeAkBJbxeAtpXL0OXhh9/+BE/n78gt6CEybda8srlK/jxxx9x+9Ztja7hW02ntVUEFAFFQBGwEQElvDaCmZSKMsSWa2bz+uvvv5LS7T0y90K/Xbafac9H5sb1RhUBRUARUAQUAQsCSngtYOhmdATcSZL77+hH66/EhkBs7RXbvsRWb62PIqAIKAKKgCJgNwJKeO1GVMtTBBQBRUARUAQUAUVAEUhUCCjhTVTNoZVRBBQBRUARUAQUAUVAEbAbASW8diMaV3l/Q/woxR+WPrEqioH2Ae0D2ge0D2gfsK0PqMtWXARE9xMBJbxe6Ad8CBkD9ebNm7h+/bqKYqB9QPuA9gHtA9oHbOwDN27cwJ07d4Q8e+GzrpfwQQSU8Hqh0X69cwdf7fsSn6z4GHPnzkXwjBmYMX26rLmdUJkxYwZmz5qFhQsXYsmSJZg1c6Yt5Zr6zJ41G0uWLMbCBQswd84czLFDZs+WshYvXgzKgvnz7Sn3bt0Ei8VLsGjRIsHarjrPnzdP6kucpc6zZ3te79lzpI7El+Wy7nPsKHfOHMF43ty5UmdiMTM4GDOmJ7yvmT7BPse+y7JZZ65nBs8E95tjErpm/WbNmoXFixZL+7HteC1Pyzb3vWDBAixm+y1YgODgYM/rSyxmzBCsFy1cKFiz/nY922yzefPm4cMlSzB3zlxMnz7N4zq72iY4WDBmvfnesAuP6dOnY/78+dI3+MxIv/Owb0T1uRnyvPGdwf7M54Tt6nHfmDEDM2fOlD4h/XnePPAe7CiXWPO9uXjRIhDn4BnBHpfrar8ZM+72jQ/vYuH594Rls+/OmjkLSxYvwcIFC+V5lP02tCH7WNT7eTHYN+wql3WePXs2li1dim1btyIyMtILX3W9hC8ioITXC63GB3DShAl4KW1aJE+eHLVr1ULdgAAE1PFPuPhHnfvWm+XxzNNP47HHHkPVSpXRILA+/GvXSXi5dfxR199f6le4UCEp94VnU6BwgYIoVrgwihUu4pGULFZcymJ9KWlTpUbRQoVQvEhRj8otUbQYihcpgieffFLKfeLxx/Fajlzg9TytM8vOmD69lMs6Z0qdBqVLlvS4XNbtjddeR7J//1fKTpEsOUoUK+ZxuYJlocLIn/d1KZf9o1b1GqjrH4CAu/3Gk74X1KABXkqdRsrO9Uo21KxWzeP+7F/HH4F166FM8eL4192+UaxQYdQLCJD+yP8npM58Flhu7Vp+SP1sCqlz+jRpUbtmLSk7oeWyLsSzbh1/FCsY9Zw88fgTqFC2HOrXq5egulrvj89gzerVkTZNFM6F8xdAwwYNPC5X6h0QIP0h2f/9Dy+keB6V36ok7wzpHwnF+S4eDQIDkfHFqDqnT5dO7qFeQF2P610/sB4K5H1d+sa///1vlCxWTNrVitnDbvvXZp+rK+/NF55PKX0jW5aXpf2IRUL7Bs/jPdf280PRgoWl3BTPPouaNWp43OfMPbJfZ38pq5RdXJ6TurY82/XrBeLNMmXx+L8fxxOPPYbKFSpK23naN/gc87uXOuULUudXX8kmzyTxT+j3ijizXnzeXn05q/SNxvXq4cKFqJjxXvi06yV8DAElvF5oMA61zJg2Dc0bN8b8uXNx6dIlGcq6evUqPJWj332HMe+9B3+/2jh9+jRu37rlcZms0/Vr1/D111/LC2/s2LHYuXMnQkNDRfbs2YOEypdffomdu3aiXZs2qB8QgGVLl2H37t3Yu3dvgstkXcLCwhAWthej33sP1StXxuCBA/H5559j37592BMa6lHZLGPFRx+hQ5s2qOtXB8uXLcf+AwdswSJkSwg++GAKqlepipHDh4P4EOeE4svzQu9iuTVkK7p07IxmjZvg4s8/29Lnrl27JimmN2/ejML53sBnGzfip59+wvVr1z3ud1QMjx49iratWuOd/m8jdM8eqTOv6clzwufv4qWLmD1zFpoGNcSs4GBcvHjRYzyuXY+6Z9Zz0Lvvor5/XRw9egw3bt70qL68V94zcV2/dh1ez5lLnr9ff/3V43Ll2b5+HT///DNaNGmKXt174NTp07hy5Ypc0xOc6a5169YtsXRXLFMW69aswVn2jbs4JbRsYnHz5i15TzQOCpK+sf+r/WC7eto32Of43gyeNh2Btf3x8YqPXa5nCa2vwfiXX36RZ7lbpy7o2qmTYO4pFqZOl69cxtp165Dp+VQIj4hApIcYm3Lpdnf8+DEUy19ArL18Hvk/T3Hms3Lp4kW8N3wkWjZthlUrV8p3kPibaydkzffOjcgbCAkJEYzf7tsX58+f98JXXS/hiwgo4fVCq0WS8E6fjrYtWuLjjz7Cb7/9Zs9V//5biMyUyZPRqEGQvJTsKTiqlFMnT4pWPn3aNISHh+Pbb78V+eabb5BQOX78OCIiItCtS1c0a9wYa9euxeHDh3HkyJEEl8m6fPfddzjy3XeYPGkS/GvVxuiRo4RE84XNeie0vjyPZWzYsAHdu3RB4/oNsH7dOnz//fe2lEsyPWf2HLEUTpwwAceOHfO4XLnfw9+AaYV79+yNju3a486vv9rZNYSMlileArt37ZIsbnYVTiLWrXMXDB8yVNrMrnL/+vMvLF3yIdq0aCUuArY9gwC+OXwYo0aMQPPGTWy1Lt2+fRvbt20DLd0R4eF2QSHlkDx37dIFQwcPtv29sWrVKtSoXAVfhGzDr7ft63eHDx1Cm5YtMWLIMHx//IRteERej8TC+QvQpEFDbPrsM9vK5dyNb7/5Fv1698GAfv1EUbStcABffLEdeXLkFMJuZ7kXLpxHhTJlsXD+fPm+2FU2n7kPJk5Cx7btEbJli62+tl/u+xK9e/QQZUgJr10tlvTKUcLrhTYl4Q2ePh2tmzXH8qXLwI+NHcuff/6Jc+fOYfLEiQgKrI/Lly/bUayU8Tf+xonjJ+BXoyamTpmCAwcO4NChQyIkrAkVEltajrt27oymDRti9apV8jEn6U1omTzPEFqSxto1amLk8BHYs3u3kEfW25OySSDXrV0rFoSG9QKxZs0aIaYel3vkCPaG7hWfuQC/2hg/dpwQf0/LNeeH7Q1Dzx490b5tW7H829Y5AOzatQulihXHzu3bccNGnzn25y4dO2HooEE4FBFhW5U5aXTJosVo1awFFi9aaNszyGgr7Fsjhg1Dk4aNcPbsWVvqTLJEC+bWLVtQtEAheWZsKfhuIbTEdunUCYMHDpL3Bu/DruXTTz5B9UqVEPL5FrkHu2bOk/S3btECQwcNwbGjR22pLut29coVzJ8zD40CG2DD+g22lMtC/vjjDxyKOIQ+PXuhX58+Yjm2o3DWme9+juDkzv4qTp48KcXahfPZc2dRvlRpGY08f+6cbcSU371J4yegfZu22LxpE5i23q6F79Ge3brjnf791cJrF6hJsBwlvF5oVF8kvITlxAkS3hqxEl6SqocVEgMX4e10j/DSemwI78OWacgdCS/LsBJeukqQrCakTOs5DyK81mPju22woCvHrOCZiEZ4I6IIenzLsh7Hcvk7IjwCYaFh6NndQcJbvDh2+Arh/d1CeBfaTHjDw4XwNrWb8EZG3iW8BZ0hvB1JeAc6Rni3bLaX8IYfPBhFeAcPkVEXO17dJIl055g/Z+5dwrvejmKlDMcJ79bohNeuip89e+4u4Z0HuwnvRBLe1lGE185Rlr2hoUp47eoASbgcJbxeaFwlvPcsw9EIb1CUhZeEV0jaXbJmJXDx2SbJ82nCO3NWdMJ71yIdn3t3P0YI72ElvO6PNa1JLguv3YT3roU3ivCec790gn6TiImFN4QWXmcJ75XLl22z4vFmXRZeuwmvsfA6QniNhVcJr4vwznOI8N618NpLeNXCm6AXzSN2khJeLzS4El4lvLERU5L/KAuvG+H1GQtvMZ+y8DLcmbg02E141cIb7S1qCK/tFl4lvIKzy6VBLbyufqcWXhcUunEfBJTw3gccu/6lhFcJ730Jr1p4XY+aYz68PmvhDREL78Gvv3ZhZMeG+PDedWm4cvmKYxbemzduSIZJO+rMkSDx4VULb5QPr9OEVy28dnRbr5dBhYgTXhlZgyNb/K1LFAJKeL3QE5TwKuFNmoS3hE9ZeNWl4d7LTglvFBYkA1E+vOrSYHqHujQYJHxzTd9xJrjq2LEj9u/fr4TX0oxKeC1gOLWphFcJ7/0JbyyT1g5FTT5zP+9Bv707aU0Jr0RpcMqlgVEavODDy+gujkRp2LwF9lp4nZy0poTXfP9chHfuPJw7d9a2vsEoDTJpTX14DdSOrIlzQEAAXnzxRcl6yIgeukQhoITXCz1BCW8SJLzHj3k80c7lw6suDa6nUF0aoqCg5TEpTFpTwutgWDKnXRrm6qQ114vJhzZIcJkYaOLEiRIvXl0a7jWeEt57WDi2pYQ3CRLeY4mY8GpYshjPsqNRGsKj4vDaH5ZMLbzWhlQf3ig0SGAkDq8SXlf30Di8LigStGH6FEd6kjJBVsKboO7xcCcp4VXC6+6KQNcDxyy8SnhjPKAkvBql4R4sxod3kC/F4XV00prG4TW9w+rS4Egc3kTq0kCyx/TGP/74I5gW2uoKQBLIERem++YxnrgAsSy+jy5duoQzZ86IFZbprbnNLHF37tyRpuCkM2tdrESUdeH/6I7EevJ/5vgffvgBFI6WcfKa9TzTxlxzP90feBxjzTNiEGPZsx6mXOvxSWFbCa8XWtFRwnvWmUxrhMXxxBMah/duWDJf9eHVxBP88EVEWBNP2BiH18cTT4TYHYfX0cQT6sNrPoVWwksy5Am5M2Vy7fLhTaSJJ0hC58+fj9KlS6NLly5CRE39Wffg4GBUqlQJM2fOdJFS8/+HWTP+8Pbt29GqVSvkzp0bmTJlQrZs2ZA3b14EBgZKVlOWt2zZMrz55pvo0KEDTp065SKuPH/27NkoU6YMpk6dKkScpHfKlCkoWrQoChUqhDfeeAM1a9aUjJhxtR+V3o8//hgVKlRAhgwZkDlzZpE8efJgwIABtmWNfBhsnD5WCa/TCANwlPA6lFqYsCjhjbJMO59pLXocXlp/I3xi0ppvEV7HLLw+THidsPB+cje1sO1xeB0lvGrhNZ/CR5HwGisov3l16tTBM888gxEjRog1l7iEhIQIIS1fvrwkOeLx5hyDW3zWPOeLL76Qsp5//nkh10FBQahevTr4m6SXZJjHXbx4UQhwsvCvcnoAACAASURBVGTJMGTIELHgcv/WrVvluFKlSklac17XRGZgOSTlJLBZs2bFunXr4lRYdu7ciZdffhlp0qSRSW4DBw4Ucs1y27dv70pZHZ/78pVjlPB6oaWU8KpLw0O5NDDxhCeEVzOtxXiqHfXhjUZ4z8a4dkJ28MMmk9a2RGVaczIOr91RGgzhtd3C66hLgzcsvLcS0hVinMO+4S0f3nNnHbDwtmmDzZs2IbFlWiOuXHbt2iWWUlpeP/zwQwntRRKZK1curF+/PhqB5Dm0oMYlpkzTiPRDp2WWFt1Zs2ZFw6BRo0ZimSXhNVZZhhUrUaIE0qdPL6HGaAzx8/NDjhw5sGHDBinW/Rrc2bNnT7Eer1271lWWqYNZDx06FMmTJ0f//v2juW/w/5GRkdHqZs7x9bUSXi+0oKOEV10aRMv16dTCwerSYB5DJ6M0OGbhdSosmY+6NDhGeNXCK48JCY7XCK8jLg1OEN5Q9OzWHe/07y9+sOZ98rBrQx4/+ugjvPrqq8ifPz/Kli0rQ/10GTD+teY4knZahd0NGvxNcktfYLPQn7Zr1654+umnMXr06GiEki4T9evXj0F4SXw//fRTIch0NahatSpeeeUVTJo0CTdv3pSiTV3MdVinzp07C0G/H+El4U6bNq24PtBqfOHCBfH5NeVw7V629X++uK2E1wut5ijhVZcG3ye8GpbM9RQ6SXi9k3jCGQvv1w5mWrPbwmtSC9PCq2HJNCyZebhdPryJdNIa62kIHkdXRo4cieeeew6PPfaYDPFzkpn1GG5zElvLli1RpEiRGPL6669jxYoVcg7/0DpbsmRJIaz79u1z7ec1YyO8pi4cnaJ7Bevy+OOPo0mTJi7/WnOMqzBAiHR8CC8nypFkp0uXTgh1w4YNsXDhQhw7dgz0742tbOt1fHFbCa8XWk0Jr7o0uFsAHI3S4DWXBk08QQsM23LEsGGICktm46Q1S+IJJ10aNLXwFcyf4w2XhiiLnKefHBIRr1h4H+HUwvSJ5aQxkkESXhJIQ3it7Udlcdq0aejXr5+4BtA9wAjdCvbs2eM6nFZUujKUK1cOR48elf2GVJLw1q1bF/ny5RMfXuPSYE5mXbJkySKElwSbRNuca44x6/haeHk+DQzjx48XNwu6TdD6XLx4cXHluH79uikyyayV8HqhKR0lvOrS4PsWXneXBoYVi7Aj09pe9OzeE+3btsXtW/b4D5rHhX5upYoX09TCThJei0vDAbXwIjzcyUxrOmnNPNvWSWuOhCVrnXhdGoiBUWIrVqwoE7/oQsAJZYyIQLcEs8RFOM3/zdoc99lnn4lrBN0Svv/+e/NvWXNidLFixVyT1qyEl6HCGEmBhJeEmW4IdGmIi5A+DOE1lSCZZ4QKf39/pEqVCqlTp8bKlStj+Paa4311rYTXCy3nKOFVl4YkQHijR2mgNdgewhvmMOEtjp3bt+NGZKRtT5FPujRESzxho4U38ga23p20pi4NEJ/I1i1aYOjgIS4Lmacdj2TkyhW18FpxdJ7wtk2Uk9YMBoxv27p1ayG7M2bMwPLly8UflpPWVq9e7fLjNcfHdx0aGioWXIYiCwsLk9PY/+hawOs9+eSTMtGMURxIePk/vg/btm0rURdIuHl9hhzjpLVVq1ZF8wM29YgP4WXZdNvgsdw2C10Zhg0bJlbtPn36xEmqzfG+tlbC64UWU8KrLg33dWkI9l3Cu0MJLyKiTVqzk/BGKuG1vJ8101oUGCQoXnFpcCy1sBMW3r22TFpjdAISPkZo6NWrl0w6ow/t9OnTZR8trSSrxP9hF7oh1KtXD//73//AEGDfffcdvvzyS3GXoG8vSSzDktESTMLLuowZM0aswnSPoBWWbT937lxkzJhRQprRZcJKWFknQ3izZ8+OOXPmuBJb0G3CLJx8R1cMWnFpbWbCC5bPOo4aNQpPPfWU+A2biXHmPF9fK+H1Qgs6SnjVpcH3Lbwz3aI0eGrhdfnwOu3S4FtxeB2btOYY4dXUwtbXsxLeKDS8SXhpYbQOr1vb42G3XZPWHHFp8JzwksQuWrRILLu1atUSQmruke4DtHjStYE+tLQCJ2RhmDNGf0iZMiUKFy4sBJdkl5FNWD5JL/116UNMa27OnDkligJdHgyxZaY3JobgJLYGDRrEcI8g4WU0iBQpUuC1114Tn2HG52UkI7OwLWrXro2XXnpJklswCUbv3r3B0GiMzctJeIzTm9QWJbxeaFFHCa+6NCQBwuurFl6dtEYy4I1Ja066NPjOpDUnfXh10pr5FD6qLg0My8XYtPRj3bZtm4FD1iSbtIQy6xlJJmPlJmShtXjevHmSHKJAgQKS5GLLli1ilaW1tXHjxlizZo34CjMyAzOvbdq0SQiw9XqMpNCtWzfUqFFDkmJYLc4ky3TFIGmvXLkyqlSpIvdE0mwWvrcYsowJJpjNjdnZWB9OWCPp5QQ7Euektijh9UKLKuFVl4ak6dKgk9ZiEl4bw5JZJq05SXg1LJk3fHh7u+KmevrJ8X0LrxM+vJ7F4TXWU2vbcF9s+80x9/ufOca6th5PVwG6D5Ccxncx55u1+3lx7bcex2Pcj6N7ww8//CDxhK1xg3me+7HWsnxxWwmvF1pNCa8S3vsSXrvj8NIlIjwCYaHOT1pTH15aeMMtYclsJLwSliwERQsUhBJenbRmPlUkIb7tw+sE4fXcpcHg+6isH0RmH/R/X8RJCa8XWk0JrxJeJbzxe9B8M0qDlfDaPWnNdwnvls1bZCa4XR9OZ314NSyZeUIdd2lIxIknDAa6TpoIKOH1Qrs6Snh10prv+/A6FodXLbzm8abvnGOT1pyy8IpLQxTh9dU4vAx9ZB/hVR9e9mfi6dMW3tZOWHg9c2kw7wldJ20ElPB6oX0dJbw6ac33Ca/dLg2uKA1OE16dtBbTh9dGC69mWov2dnbWwquT1gzYLgvvI5xpzWCh66SFgBJeL7SnEl51aXgol4aIQ4g45EGmNSW8MZ5q71l4nSG8Tvrw+k6UhnBo4gkvWniV8MZ4j+gO30ZACa8X2k8JrxLehyK8tsXhVQuvebydJbwRlklrSng//eQTVK9UCSGbt+CmrS4NSnjZn73m0qCE17w+dJ1EEFDC64WGVMKrhFcJb/weNJ+ctBahhNfaukp4o9BgyKlDEYfQp2cv9OvTx/fCkinhtXZr3U4CCCjh9UIjKuFVwntfwuuWWpiJDCju58TntzlPw5JFf7AdtfA6mWltyxYNS3a3KcMP6qQ1QuE1C+/cefCdTGs6aS36G09/xYaAEt7YULF5H2cqT5s6FS0aN8HihYvA1IAM9sz0fhRuU5jZxCr8SMcmtBxQeCxTHE6aMAEN6gXi4sWL8jLkRBojfDnGJvG5xRMnTsCvRg1MnTIFBw4ccBEwQ6riQ8Csx/C8I0eOSEzRrp06o2lQQ6xetQqcjMLjPCmXaRMPHz6MiRMmoHaNmhg5fAR2794NZpex1iEh2yxj3dq16NqpExrWC5RMOMx042mdicXevXsxy2cnrWlqYZ20FvNNohbeKEzUwhu9b7hSC2tYsujA6C+vIaCE1wtQ37p1CwP690ehAgVQL6AuBg4ciOHDh4OpA0eNGoX33nsPo0ePxpgxYzB27FiMGzcOEyZMwMSJEzF58mR88MEHmDJlCqZNm4bp06cjODgYM2fOFBk/fjyCGjRA0cJFMHXqVMkFznzgS5YsAfN2L126FMuXL8dHH32Ejz/+WHJ2f/rpp2Aaw1WrVokwZzeFKQ0pTDm4bt06zJ49G8WKFJF0iqwDr82UhUZYD2tdZs2aBQrPo8yZM0dk7ty5MMK6cX9AHX9UrlgRo0aOxPz586XeCxcudNV/8eLFoPA+zL3wfsw98b6Yc5zC+1uxYoVI75498WaZsujcsRMWzF8g98k85RTetxHr/ROH2DAwOGzcuFGwbta4MWpWrYaZM4OxJSQE3E/57LPPRJgCkrJ582aRzz//HBSmjjQSEhIiaRuZunHHjh1Yv349xo0dh+pVqmLo4MFC0rnfCPOZU3bt2uUSEvk9e/a4JDQ0FBSSZ0rYvjBZb9+2HV07d0Hrli1x+ZdfXAqWu5JllCqjSDHkUWwKk/VRYX1KFVfC6y3C6+SkNd/JtKY+vHwGvWbhdcyloQ02b9pka+ravaGaeML6ftbt2BFQwhs7LrbuvX37Njp36oQsmTLjtddeQ/ny5VGhQgVZM491uXLlULZsWZQpUwalSpVCyZIlRUqUKIFixYqJFC1aFIULFxYpWLCg5L1+4403kCdPHmRInx4pnnsOuXLlQt68eZE7d24R/s6ZMydy5MiBV199FdmyZcMrr7yCrFmzuuTll19GXJIxY0Y8/b//IWXKlEifPn28JF26dKDw+Li206ZNi2TJkuHpp59G6lSpwN/xEWt5GTJkAIV1zJQpEzJnzozMWbIgderUeOaZZ5AqVSpkyZJF7pf3TOH9Z8+eXbAgHsSF+FCIFXEjnsSQwrZ6/fXXkS9fPjkmXdq0SPVCKuTOlUtyj7MdmIOcwrYpUqSICNvKtBvbkMI2ZdtSSpcuLW3NdufvfK/nQ7o06ZA3Tx5UrFgxmrz11luSd93kRGde9KpVq6JatWoi1atXl3zqzKles2ZNyZ/u5+cHSs0aNeR+cubIgRbNm6NNmzZo27Yt2rVrJ8K88JSOHTuiU6dO6Ny5M7p06YKuXbtKnvbu3bujR48eIj179kSvXr3Qu3dv9O/fX/KtZ0yfHo0bNZL977zzDijvvvuuKHSDBg3C4MGDMWTIEMlPP2zYMJeSN3LkyGiK3vvvv+9S9nheqZIlUaVyZfF7pMJnVfqo1BnFj4qXUbiMokVlisoV89VTkVqwYAGoSHG7Q/sOKFe6DDq2by/7jLJEZZAKU2wKoVEEjfJDBWXDhg3RFB3WoUWzZqhYvoIoll988QW2bdsGrrdv3y7Ki1FajLJiFJSwsDDs27dP5KuvvsL+/ftlNIUEN3TPHsyeNQuv5cqNj1eskNEKjmRwxIGjA9999x2OHj0KjjZQOCJDOXnyJE6dOoXTp0+LMG0ohalMKRym5jGtWrQAFUSW8fPPP4NpRUl+r1y5IqNQ165dw/Xr10UiIyMliQSVd4oZnTIjUlSaqDBxUQtv1OdDLbzRP6Nq4Y2Oh/7yPgJKeL2AOV0aJk+cKMPh06ZMxfHjx+UDdObMGddHiR8nfqQo/BhRvv/+e5fwHCPmA8eP3u5du/DOgAFiIaR1jx8vfhCN8ANphvs55G+G9Ok+QKE7gZGDBw+KuwE/tnRhoLW3bOnS6Ne3r1hZaUmlkCjQwuouxhrLtbHQck2rLoXEg/8jGanrf8/Ca8gJ10aMRdhYiY3VmJZtEgySHVqcSX4MCaIVnB/xooUKoWGDIIwYPkIs5bSa03pOKzqt6bSqk3TRwk5LO8kYiRkJGgkXLfAkbiRwAwYMkDWJYpnSpVAg3xto2bIl+vXrB5JAEsJu3boJSSRZJGkkeSSJJJls3769kEySzdatW6NVq1ZyfosWLWTdsGFDIbjZsr4iRLhx48YICgpCgwYNUL9+fdSrVw9169ZFQEAA/P39UadOHdSuXTuK0NasKWSXpJcEmESYQlJcqVIllH+zPLK9kg0vvfSSiwyTFFuPJ5HmsSTWRgkzChiJuVHASNqLFy/uIvJUEJI984woDfnz5xcFrECBAuA2FTEqCVQWqDRQqEBQmaBS4a6IUQmhUCGhkvJs8uRIkSKFKE2sO/dRqaFQwTHKFxUgKkpp0qTBiy++KMoOFR4qOy+88EI04b7kyZLjqaeeQvLkyeVYnsNz3ZUto7DxOkaxsipXpi6iZGXOLIodFc5nnn5a6mgUSKtiaRQu3qNRvNyVLypgRgkjRtzOkjkz/u+pp/BK1qwuRcxdISPORjEj7sSfwrYwwrahgmaEv19MnVqw5HZsyhqVNrY5xaq4GYXcKG/sJ0bYd9jOKVOkwBv58okiz37lrrixv7IfWpU09m32cfZ39vvAwEB5Dvg88Lng8dleeUXK9a/jL88Pnyc+V0aZ4/PmrsDx+TTKG59ZKm19+vSRZ5jKG/fVrF4DeXPnRsOgIAwZOtSlqPH9EJuC5j4SN2nSpBgjcXw38X1S+a1KqFqliryvzLvOjGaZUSwzYmVVvsxInFG6OOpmFC4qXVQUs2TIiEWLF4uCxVEjq5LFURgqWO7Klbtixfc/vwX8Phz57gh2bN+BYgUL4b1Ro0Tp4nfHqkRReaIrHZWns2fPigJ14cIFcam7dOmSS3Gi6x6VJqMsUZka+/77aNuyFTasWyeKE5UCjijRau3JohZeT9B7dM5VwuuFttZJa/ZNWjMk3RB289v4004YNw5+1WtgxNBh2LFjpxB8EnlD5knkSeiN8LexqnHb/DYfBf6P59Jq1aldO9QPqCvWNl73yy+/FMsc12bbarGj5Y6/xc0gLEy2zW9+hHgNujh8MGkyalWvIX7HLCd0Tyj2hEa5LBiLoHFh4G/zIeO2+W0siMb1gS4Rmz/bjI7tO6BZ0yaiYF365Rfwg0RrHv29jfC3Vfjxssr58+flo8Y1hWXwI1ykQAGs/PRTHD92TD58/PhR+CE0H0Rumw8k91GMxdGsjeLH9Zf79qF5k6bo0a0bNn32mRxrlECrQkhl0KoY0rJpFERj6eSHmgogLaFsr/ffGw1/v9oYNWKEtBv7ANvXtB3biTgTU+JJDGmhJZFgO9Ethe4qdFsh4SD5oFL4weQP0CgoCGXLlMGc2XPEbYbExSiGdMMxih8tziQ9VOioxNEyTQXOqrzRfYgEigpah/btkTlDRiFsVNqosBlljYra0KFDRVEzShoVtLffflvIXN++fYXYuStmVMqowJE4kwA3a9ZMSCMVOSpizZs3R9OmTYVkNmrUKJoCZpQvd8XLKFEksiTbL6RMiQL5C6BsubIykmVGsKxKlFGgzOgVR0rclSYqSyTQFCoSzz77LF5I+YIoQVQYzIgVFSMqIEYpooLirhAZJej5558Xheq5554T5YejTU8++SSeeOIJPPXkkzJCxFEiCkehuOYxZk2FyQj3c5v1MmuWa8SUTUXL7OP1jVCx4wiaEe7ntqmr2abCZhQ5s83yHn/8cTmWypsRKnFGuM+q0BkFz4yW8X9WBY9KHo958r//RYrnUsi5RtmjsmlG1IzSZ9ZG+eNvblNJpZhto7jy/pInSybX4D6jHHJNBdEog1T2qPRRzGibUeaoxFlH1diPXsubV67XqX0HeUd54bOul/BBBJTweqHRlPDaR3iNhdp9LVbsb74BJ63VqVnL1klrtKRz0lo3TloLDMTaNWtkCNm9Dg/7m0SMJIvD1gG164BknfsOH7pniX/YMnn84W8OSzikfXv3oVePXmjfri1+vX3b1p5OUli6eAns3LEDt27etK1sEm1OaBw2eDC+OXzYtnJpSfpw8RK0bt4CixctlEmi9yvcOtHT6s9strmmZYpD+QcPfo3hQ4eicVBDIfQ8l9czYob7+dv4S5u1cQmwrs0k1su/XMamjRtRJH8B7AsLk/KMKwHXdJUyv7ltFeN6wH1mm+ubN2+KUGnp0LYdBvTrL3U2VjiORlmF+61idXEw22ZNax7LX7xoESqVL481q1aLAkRLnxHjLsHf3DZC619cQlcLHk8FpHHDhujfpy/C9obJubwPI0aBs66tihy3rYqc2aZSNGnCRATU8sOSRYuEMBnFzIy8UZmiIsXRNaNEcRSN7x0+c7SSGqWaShSVWSq1Hy75EI2CGqJxw0aiNFkVKbq9GEWKvv5UpDgfgPMCqEzRjYYKFecYcM4BLb50uzHKFEehMqRNi0kTJ8rcBlqNKUah4ugYFSozKkaliqNhHAkzShXniXC+COeNmDkkVJqyZnkJAf7+ojhRqXJXrDj6RcWKFnKOdtFiTpcnd+WKo14c8eJoF63wJYqXQK4cOWUUiooVFSwqXFSwmjRpEquSFdsoF122atWqJSMEdOdiudmzZUfnjh2V8N7vxfaI/08Jrxc6gKOE9+w5cZcICqwvHww7b4cveI3ScEjcQxyN0hA8EwF+tTF+7DjxzeQHlBbJhJBdOc9rmdaKYcf27bgRGWlbt7MzDq91mJQEc8mixWjVrAUWL1woRNGOSsuktfB7cXhZf7uWmzduYltIiIQlO/j113YVK+VQAaJiMWTQICGOVqw8vdCqlStRvVJlbN2yFbdv3fK0ONf5hw5FoE3Llhg+ZCiOHz/h2u/pBgn7wnkL0Lh+kIwqeFqeOZ8K0aHwQ+gtcXh7izJgVaS4bVWgYttmGRSjYHGbihMVJJLk3NlfxYnjx+WSRsEyipVZG+XKurYqWGabihbPIckvV7IUZgfPwpnTp0WR4v+McnW/tVXpct+m0jJm9Gi0adES69asEXcHo4SZtVHIrGurAmbdNooYz922dSs6d+iEAf36KeE1HVDXMRBQwhsDEvt3OEp4zynhJckzfso+GZbMLQ4vg9V7lFqYhDk8AmGcudy9J9q3bWsr8eAT4otRGhY7RXgjwi2Z1s7a8gIhGaIisVXj8LrwDA/37Ti8JGZ2LIYo09WGhPfUyZN2FOsq49y58yhfugzmz52H8+fOe+xfawomaaYlvUObtvh882Yh1+Z/nq737d2LXt26453+byvh9RTMJHy+El4vNK4SXmddGnye8LrH4fWU8HrNwqthycTC6/OZ1i6LBdGuV6FGaYhCktZSn860JoT3nG19g5bhieMnoL3G4bXrUdNyHhIBJbyxAMZhI/qBcXjSCH/zBZaQRQmvEl539wSSdN9PPFEiUbs0WJ9VR10aohFeGy28N25ga4jzmdauXL5iG6kh5kp4o3qezxNex+LwttU4vNaXk257DQElvLFAzckMnMVsQjYxrA4d6hPqn6eEVwmvEt5YHrRYdvEZ69KxE4YOGoRDERGxHJGwXd4jvPb48IpLgxLeaI3NiWGtW7TA0MFDZOJYtH8m8Adx5sS5+XPmoVFgA2xYvz6BJcU8TQlvdEzUwhsdD/3lfQSU8MaCOWcLM1YrZ5gyVA9D3zDcCmfqJmRRwquE16uE1+XDG6Y+vHcfWGcJr9WH10bCqz680V63Snij4CBJ5yik8eFleD47l7Nnz6F8qdJ3fXjVpcFObLWsfxYBJbyx4M8XipmVyhmrTA7AeIIJfbEo4VXCe1/C67NRGtSHV3x4LVEaGIfYjkUsvJE3dNKaBUwlvFFgKOG1dIq7m3tDQ9FTJq3110lrMeHRPXcRSFKElx8fWnL4QnjQYo7l2iw8z/1cBtqnO4MS3gOuMFkS+upQFIl1J3L3+238VhnwnyGRmgY1xOpVqySGJc/zpFzfjtLgFpaMk9Y8CUumFl7zSLvWvmvhjQpLxmfGzoURA+g6MmjgQAlnaH0Penod53x4fTtKA0Nt2bH4POFt3cYBH14lvKZvsX8wJBzD7dGtxp3TmOMexXWiI7xsHMbXY5pDBhpnYG5mO2Kgewb0Zhw+s/BYvqjpg8X/MfsRsxoxvSIzZjF4OId+rAsttwwczoxJPJZBvhnsn7EIY1uU8NbA1ClTBE9DZj0hY5yopYQ3itA6NmnNa4S3BHYm4ji81ufZe4TXRgsvfXi9EJbsymVfidKghJd9mt89r7g06KQ16yvEZ7b5rmOWRqaZJ3eyU5n1GRDiqGiiIrx8kEkwR4wYAaYRZNpFpk/k+n//+5/klieRNQsfepJVZnqhny2P45ppCplbnllgmP3HLHSaZ0pUprdkikOmNmTqReaMZwab2DqGEl4lvMyo5GjiCfewZB5auw9pWDLzyLvWzhLee4kn6P9ox8J3IZX7rVuctfAO9ikLr05aY9/yGuHVsGR2PMpeL4NGvVatWglfWr58eay8xuuVSiQXTDSElw8xLbWDBg0S4krthPnnaYllKkXm1ObEMea9N8tPP/2EwMBAyWPOyWXr1q2T/9PCy/SKzFVPsz4XfvCYmYZ53kuUKCEEd9++fVi6dCly584t5XNY3H1RwquE1+cIr9csvOrDSyU5IlriCRsJr/jwKuE172T14Y1CQgmv6RH31nuZZEd9eAUQvpOOHz8uo+KcgM/+oksUAomG8JKQknymTp0a/v7+0RzPaZmtWLEismTJ4iK8dEFgHvAnn3wSDRo0APOkWxc2Ms8zVltOJgkKCpLySYjNQm2IluDkyZNLbnCz36yV8Crh9TnC6zULr8bhjSK8Dlp4NQ6veRWLr7+GJfOihVddGlx9L6lv8D1Gf1/Dl5Lq/SYawkvCyslhdF2g765VK6GzP2PhWgkvLbelSpUSl4Rly5Y9sH3o40s3h+LFi+Orr77CiRMnRI4dO4Zp06bJdWvVqhWjHCW8SniV8MZ4LO6mFlbCq4Q3Zt9wbtKaujQQba9ZeB8xwksjGmPwk4vENaeHRjQaz+gqaeUoMZ+CuPfwPBr4fvnlF/zwww84deoUGA2K27w+jXBcyHE4ik0rLd03rdcjJ+L/OCpu/sc6cR+F85fIXTh5zXqetVbcz/vhcZwztW3bNlEqz5w54yrXenxS2E40hJcTouhaUKhQoWjWXYJMX7by5ctHI7zsGPS/ffXVV2VG+4MaY9OmTfi///s/pEuXTkhvyZIlYaRgwYLiFlGlSpUYxSR6wnv2HCZPnIigwPryYMS4AQ92UCnwq6GE13HC6x6WzLYoDXsdjsNbTDOt0aUh3Mk4vL7r0rBl8xZ5d8f1wX3YV1P4QScnrc3VxBN3G8Qah5eJYOyy+pFcSWrhRBqlgfOBaPQiHyD5c19ILOkTmz17dkyaNCnBuHBS/ooVK/DWW2/JHKX//Oc/YnBLliyZcJI9e/bIpRctWiSuljVq1BAiatqBfGjYsGEyX2ns2LHyjLFunPvEaFLkOJyjRPdN8h5znvv9XL16FZMnT5b7efzxx2WUmxyJc6GYeIvEN6ktiYbw0jc3TZo0qFatGi5duhQNZ6b15cQyCbW9yQAAIABJREFUWnhpneVCLYYNkyNHDknRGu2EWH5wstpjjz0mVuExY8ZIh2WnpbDRp0yZgk8++SRG+uBET3jPKeFl1AivhyU7fkzCtHkasWLv3r2YFTwLAX61MX7sOOnLnoZok/PDIxAWqoknzKvAJyetWRJPHHQoLJlvTVpzkvBqpjXzrFgJ73lHCK8TqYU9D0tGYjh+/Hg8/fTT6NatWwwDEi2/9evXF6Pczp07Ba6HVeZovZ07dy4yZsyIvHnzonfv3vjggw+ErJLLcB9dLlkuiW3fvn3FGNe8eXOxAvP8BQsWyIR75gegJZcLCS8TkTBh1tChQ1G4cGEhxGvXro2T8H766ad44YUXkD9/frz//vsyr4l1o4vnhAkTEpxZ1vSjxLhONISXLgfp06cX1wWrPy5N8mwEaixWlwZqJ2wo+vxSE3rQwvAc1Hxq1qwpHel+x1s7sRJetfA6buHVKA2ux1FTC0dBYT543ghLxiHTuKxAroZ5iA11aYgCy+dTCz9CURrMN5+hIuk+yUhPW7ZscbkD8P8klDlz5kTnzp0ldCpbmftJNuMS9+dqzZo1MirNSFF03bQuJLC0ylpDidHVgXOPnn32WQwcOFAm5nMUvFy5chIq1NTBWg63u3fvLiPm9yO8JkAAy6X13brQpYP3lNSWREN4OZzAhsyQIYM0JDsStRlGaeD+p556SqI0hIaGShvwf++9957sJ4ml/4vptKYTkiybDseOw8lwtCIzXq/Zz8J4PIcZSG7dFyW8SniV8Lo/FVAf3ruQ8D1CK/+IYcPQtGEj2BqWjFEadNKaq/NplIYoKMz3TVMLu7oG7IzSMG7cOKRKlQpdu3Z1WXlJAPv06SMkkiPBhgySKB48eBC0+O7atSuakLhSgTcLjXTNmjUT18qFCxe6yuD/WQ6tx+6El/8j5+EIN41+jFRF10/WgaNWXAzvkR+A+B+TlDOy1f0IL8tImzatzG1iTgK6MNA32FqedduU78vrREN4aWXo0qWLuB2wU7ADcTIaozOQ0L755ptioSUBNgs7U506dUDfF57DsGOM0xsWFob169dj1apVLmsuOyi1K8bp5eQ1+rbQUZtkhh2Vbg5vv/22Kdq1NoSXlmTG6mUCDA5Dx0aOXSe5bWhqYU0tbJJ2mDVJUpyJJzz14dUoDW5PYFRYwiWLFqNVsxZYvHBhDItGjBPiuSOK8Drkw8s4vEp4XS2hhDcKCq8RXpm0djaaccjVGAnYuOfD64RLg31hyfhepgWWLgbGwHby5Enxr6XfrXEjIASccEZu8swzz8QQ+sXOnDnThRTdNmm8o9sC+zIXQyjvR3h53IwZM5AyZUo88cQTYmG25hdwXeDuBsl5fAgvXUfbtWsnRsB///vfUje6MvDbRHcKUzf38n35d6IgvAZYxsWlqZ4+NLT00sWBZn7GlKOTNhNFMDavdWHna9y4sXQG+qMwYUWePHnER4axeTmL0SwkvfPnz5f/81hGeeDwBTs2hyro++K+0L2CnYJ14vWzZs0q14iPG4UpSwlvEiS8dvrw+qxLg0ZpcNTCq4TXvEJl7fOE95aPpRZ+xKI0sJMZLkJfWI4G04eWVk/O8eG3n6FQSU7NwpFhzg+aNWtWDJk+fbrMLTHH0iDHMmjEI6exLiSYNN6Rv1hdGngMLbkkznTpZBjWevXqiaHOOkptLSs+hNfcJ4+lLy8NhrQccwId3Tl4/4xGkdSWREF4DahsQL7U6MRNvxKa/Q3otMTS4ksLGRfTYNxmxAYmpxg5cqRYaTkRjeZ6airG7G+uwd/sUBy2YIY2+rEwQQU1udi0JrpFcNYkHcVZH64ZL5guGPFdlPAmQcJ7zMZJa0p4XY+S+vBGQcH3Gz+CauF1dQ35Nmgc3qhvH403jrs0PKKEl88e+QZDmDJiAwkhySjdDei+YBYrBzH7Ylub40h4SSZpZGM4VLOQ93DEmYY3GuushJf/++yzz/Daa6+JgY6RpOhuQR9dvitN2aYsruNDeHmc9Vyew5FxTl7jfdKFlCSe+5PSkmgIrxV8PsxWLcodcHOsWZv/k8zGFneOxxkxx/Iat27dcsW8M/utZVq3zf+t6wf93xyrhFcJr3FlMOuk4dLgW5nWFnvFpcEeqwjfLTck09oWFC1QEF9rlAYlvHc/KOwbXiG8Tk1acyQsmX0uDYSZPMJYeUkAObpLA5nJ3Brfb7/hAFwzwlSRIkXEUmvCnpHQ0tWhcuXK4q5Awsv/cT+vwehDzDrLEWj649LdwpBeWp3JYdyX+BBelk+XBnefXfYrEl26TvTo0QP0O05KS6IhvAQ1tk4U2z5rA9zv/7H9L7Z91vKc2FbCq4TXEF2zvi/hZWrgiAgZzTDHx3dtzovwUliyndu340ZkpG2PjVp4o6Dke8p7Fl6N0jB/joYlMw+xKyyZUxbe1onbh9fgwPlAtPAynCldLGmh9WQhwaTrAMlkmzZtwMhUjATBUKxly5aViWm05G7cuFEIL90xSTrpWsFwacaYx3lMzD/A+UjuE/BZP0N4s2XLJr6/JMm0KPN8s5Aos2z6BnMuk0lUQVcLhkqjawOveT/DoynLl9ZeIbx8eVvFABTbPvO/pLRWwquE152wRie8M6PH4fWZSWu+ZeH1uUlrPhqlge5k1StVQsjmLbhp4+QXn/fhvemMD+/3J0/a+rm0El4qoLQG2rGQPCXmxBPmHslLuNCaSx9eTj5jHFwzUd383xwfn7U5h2SWJJq+uEycxcgLJLt0qWTiCPrR0mWSIe0YOYGJJEiSmXfALCS09CXmJDZahmkFti78P8ks8xQwFKuZd0QCbxa2Re3atWWiHYkzrcicL8UJeHSZqFSpkst9w9TdnOvLa+cJ799Rlls+NEYIGEGkcF9SAjS2zqCENwkSXgcmrU3wucQTOmmN7y8qL46EJfNRH96VSnjlMxAjDq9OWrtLeH3DwssRlgEDBogLApU4uxb66JKQNmrUCO+++64rcRZJL31oOWeIYVc5wZ4kmO8Xw5HMmsm46HrAJBF0iaArglm4zShVnJ/E/9MVY/DgwZK4whzD9xYJ8NSpUyU6FmP9BgQECLFnuFfOUeK1zPXMeb6+dpzwCmBRCpMLq9iATGrAum4WgBLeJEh4E/OkNbpEeMmlYYe6NAjW9wivnT68kdDEE/fepOHhmmmNaPBb6dM+vG0SN+ElvlRW6G5A/126H5hkWJ7wFOu5bD8S6odZzPlm7X5uXPutx/EY9+P4m9Em6EJBom1d3I+1/s8Xtx0nvC5Q3Egv9yc1MF336rahhFcJ731dGoLdXBp8yIdXCe9fiAi3xuG1k/DeUMJreZeqS0MUGPxu+jThTYST1ogpCSijQjGJFdP70re2QIECEiXB0g2TzOaD+NeD/u+LQHiP8PoiOjbVWQmvEt6HIrz04T3kG5PWfInweidKw73MSp68PuQDHEkLb4jPRmnYsnmLkAi7Ppy+beHtLTPiPekT5lziaSW8jvnwzp0noa84/G3Hcs+H1wkLbyh6duuOd/r3d/naPkydiSkng7Vo0UKG9unXSt9Xhkh1t3o+TLl6bOJCQAmvF9pDCa8S3vsT3lkyac348NJni+J+Tnx+m/PUpSH6g82QhT45aW2LhiUzLRl+UF0aiIU74WUWMDsX16Q1x8KSJT7CS/wYhaFGjRpgNrWmTZtKLH8T2cAupc3OdtKyHh4BJbwPj9lDn6GEVwmvO1klMY0ztbC6NGDooEE4FBHx0M9aXCc4S3itk9bsdGm4Z+E96ENxeHXSWlQvjDFpzaEoDUp4gb2hnsfh5TuCocN++eWXuF4jut/HEVDC64UGVMKrhPehCK+6NDhCeB1zaXDMh9f5SWuDBg7E5cvOxOG136UhHJppzbsW3nNnnQhL5oSFN+GEl9bbuCy4ce33Am3QSziAgBJeB0B1L1IJrxLehyK8nlp4D2uUBvdn0HsWXht9eL0Ulswpwss4vJwIZBdp0ElrUb2aeFp9eH3OwpvIozS4vzv0d9JBQAmvF9qShHfGtGlo3aw5ln24VNIB8qXFyQDxER4bm/Cld+7sWUyeOBFBgfVdQzGxHeu+Lz63feLECfjVqIGpU6ZIzD5D2oyfqPkd37UZxmea1K6dOqNpUEOsXrVKUoayDE/KZfBtZoyZOGECateoiZHDR2D37t2SEz2+9YvrOOZVX7d2Lbp26oSG9QKxZs0ayVzjaZ0dc2nwGuHVOLx8ftlvHQlLlgQIryaeOIQ+PXuhX58+jk1ac4zwOpVpTQlvfD6/eowDCCjhdQBU9yKZr3rUiBGo8tZb6Nenr5C8zz77TMKdcGYoneUZ8y8kJARbt24VYVgUBqjesWMHdu7cKeSNAakZnHrv3r0ICwsTYTm9e/VC5bfewhfbtwt5pCXEkEeSQBI2kisGk6YcPXpUCBvTCFqFBNcq27ZuRcXy5TFkyBDJ423q7L7etGkT3IX3ZRXeI38zTzjPb9GsOQJq18bcOXPk/nnvBgNuGzF4WNcsw12IE2X40KGoWqkyBvTrj3Xr1mPXrl2Co8HSHGdwJbZW4fHuQryXLV2Kdq1bo27tOli69EN8tf8rCRDONjHtwraxCs+zimkzs2bgb97H1ClT4VejJkaPGgUqAwwk7i7Mw+4uTE1pFZZHYRncv3vXbnTv2h1tW7dG5PXrYhWiX6ERKkxG3BWvBylIxKhUcc20FpPw2mzh9eEoDWrh/QOHInyY8Do1aU0JrztF0N9eQkAJrxeA5kzPzh07InOmTGCu7AoVKshMUM4GpVSsWDFW4XHuUr58ednHNaVUyZLInj070rz4IkqXLi37mB7QXcqVKwd34TEsw6zNtUx9SpYsidSpUiFnzpwoXrw4+NtIqVKlYITXpZQpU0bSJJq19XqmPrwGtxnyJXPGjJI/nPvMNQ0mTG1ohOkTKVWqVJEUiIyPSKlevTpq1qwp4ufnJ6kSixQpjCyZMqFQwYKoWaMm6tatK1KvXj1QAgMDUb9+fTRo0ADMLkNhxhtK48aN0aRJE5mhy3SOFKaUbNWqlYSqKVSgAHLnzIl6deuiQ4cOaNu2Ldq1a4f27dvLb+7r2LEjOnXqhM6dO0sGm65du4LSrVs3dO/eXTLs9OzZE7169ZK0lfxfYL16eP2111Dbzw/vDBiAt99+W4RZft555x3JxjNw4EBQmD2HWXMoQ4cOxbBhw0SGDx8uWXlGjhyJUaNGYdTIURg2ZBiqVa0mSsvChQvx0UcfiaxYsQIff/yxzEL+9NNPsXLlSqxatQqrV68W6/XatWuxbt06ydbDXO1Mh0klxSg1IVu3YsKECcibKxcmjB+PtWvWiLJiFBZ35YTKm1HgqHgY5cNd0aBFntbzuv4BaN2yJRYvXixKnbvSsG/fPlCMUmAUAXfyT+JPOXjwoCgLo0aMQp1afqJ88hyrUkjFkKMEFCqIRkl0VxSNssjc9FQWuWZWo57du0vZVHhOnz4NWt1OnTolwt+UM2fOSIxPxvmkMH89hWlDKYwBSmE6V8qJ4yfw8YoVKPD66wjZskVGcBgAn1mWKJxgYybZcKINXRMoDCBPuXr1qsi1a9dAYapUCoPMs5z2bdri7X79pQ50Pbh165YI31cUhpGiMCwThSlL6RpihIqTUZi4Jvnn8qkl05q6NCjhNZ9YV1gyJbwGEl17GQElvF4AnBbeEcOH463y5dGjWzcsWbIEy5cvx7JlyyRvNnNmcx8/8IsWLQLJCYWpBSnz5s3DnDlzRGbPno2ZM2eKzJgxA++PHi1ErlCBghgzZgymTZsmsQMnT56MSZMmSc5tkhPKuHHjMHbsWBEeyzSGFKYSpJAokTBRmNKQ6Q9z5sghxJKkjmSOQmLH3xSSPiPMSNO6dWsRksSWLVuKMLYhheSRa5LK/G/kR64cOVCrZk0X2TTEkzm9DRklMaUYosq1Ia+GzJo1UyMWK1oUWTJnlnzlJMT+/v5ChJk3nKSYUqtWLRFDlrlmOBoKz6EYUm3WZUqXxqvZsonSQqJftVpVVK5U2UXKDVE3xN0oD1wb5YRE3ygBzJ/O3yzr9ddfR9o0aZArVy5RGIwCYRQKKhklSpQQoeJhpFixYqIwFC1aFEaKFCkCSuHChVGwQEFkzJhR8qmzLCoiFJZvyubalG/K5ZplmzLd1/wfc74neyaZrHktUxdrGe7b5h7M2ihPXJt6sO7p0qaVHPIM+m6wMGtzD7GtialViDUxNvjnzZMH6dOlx2t584qi6a5Esd3ZB9gf2EeMElWnTh3pR+xfpq8Z5Yn9kYoYFZaXsrwkx7F/uytO5hngM8Fng88Jnxd3pcmqMPH54rXTpH5R8txTUeIzaRSm3r17o0+fPqI4MX0o04hSWaKiRGHaUndFiaM1VJS4n89K+XJv4t133pFnnu+A0aNHi/D9QOH7gu+N8ePHyztk4sSJ8k7h+4UxSqdMmSLpSZmilO8evpuoBObNlRs9u/eQ/zMFKt9bfIfNnTtXhO80vtsWLFggwvcd3318B1L4PuR7cenSpSJU1viuKl+uHALr1sPkSZNFYTOKG1O/GuXNqsC5K3HuihyVOZ7bq0dPlC9bDiNHjJDRJaO8mVE3jsRYFTczUkSljaMdVNYoZrSHShq3P1yyFI0bNkLTJk1kJImKllHMzGgMFTKKGZkzihhdpowiZlXCOEpHRYyYvZLlJRklooLF0bnvv/9exChcRtEyypZVybIqWOfPn8eFCxdEgYqIOITSRYtJ+377zTe4dPFiDEXKKFBUnihUbPido1BxsipNRmHicePHjpWRss82bhRlyowscUTJk8WOKA2eXF/P9Q0ElPB6oZ2MD2+rpvTh/VBeCHzQrdaRhGzT0kLL0KQJE9CgXqBYffjiYFlm2NqTNa1ZtapXBz9utKaZF7OxnCVkzZc4y+rcoSMaN2gg1iB+AFi2tTwzPG9dmw8FPxrGumfcA2jx4/Z7I0eiRpWqGDjgHbFK0uLGjxI/UMa6yA8XP2C0RBrXCX7gjNsFXS9ozaRVkx9E/uZHu1njxqhRtSqoaGzavEmskfyg0jrKjyyFH11+QPkhptCayo+1UXCsSg63SQL69+uPcqXLoEunTvKhtyo7hiDwOJIGq8ITHBwsdZk+fTooJBwkHhSSkXFjxsKvph8qV6qE5cuWSf1M3VgviqmXIRZG8bIqXyQlRvFiffibBCt71lfQu09v6R/Wuph6kAxRWBcqX1YFjASKQkJlyBUJDYlaiWLFUKF8eXTt0kWIGK3XFBI1EjZj4aa1m6SOQks4zzXWcdaP0rdvXyGFJInVq1XDa3nyoGqVKmJ1p8Wdlndjhe/SpYtY5mmhj025I5EjSTWKHYkriSyVqQL58+OVl7MisF6gjAwY0stRAypyRokzChxHGUiWjQJHIk1CTQWNJJdC8l2yRAmkeO45lC1TRoi4UcqoiFWtWlXEjIBwRMQ6YmSULXdFi8pCiZIlkT5dOmTKmBFFixSNpkQZBYeKDKVQoUKiQBYsWFAyT+XPn19SrubLl0+UNSpsHLnKmzevSKZMmfDMM8+I4pkjZ05RiqggPUjy5Mkjx3DtLiybyQBSpEiB1KlTI3u27K7rmeveb23qx7VVeA7rlTFDRjz37HN4+eWXwftiSlneJ5Uu3jcxIBZUyIgPFTwqdFblzaqUGcWL52TOmEmwYDuwfawjV1SWjFJtFC6jkN9P4WJ/oUKXPFky6RcN7/ax2EaqjKHBGCCMsmUULmO8oCGDfZ/HZ0iXXkYSW7dq7RqhorLlrnDx+aK4K1xmZIrPphmV4r6qlaugcMFC8ozwWaZhxYxKWRUuvgtiU7houKHSxXeJUbr4vundqzfeqlBRkk+QvOuiCMSGgBLe2FCxeZ9GafA8SoPV6hHb5DIzHM1Ja3Vq1sIombS256EnrdGi4i60pqxftw7dOndCw8D6MoHt+InjMY5zPy+236ae/B8VChL1ObPnIKB2HUwcP16GyM0xCV1/e+RbfHP4G3y17yv07tkbHdq3k+FoO7v13tBQlClREnt278adX3+1rWgO0Xfv0gUjhg7Fd0eO2FYuFcGliz9E6+YtsGTRIhmi5z6jeBrFkEokLVIcfjVWKlqsaLmiFYtWKroFGDcBuhDQwjegf38EBtTFocOHxRpGlwFazPjxNS4KtKhRQTVWNlrdaIGj6wMtchRa6Gipo6sEEy0sXLAA+fLkxaqVK2UfLX3sF+w/ZtIkLYNGYTQKIpVDoxgaZZBWR+NjTmWvrr8/WjRvjg3rN7hcTqzKoFEIqQgaZdCqCFIZpMsLraZ0g6E7Ct07aGku+MYbGDp4iFhnrUqWcauhokUli1bc2Ea43JUsKlxUdOjCxVGhYUOHuUa5YlOw3Ee4qFzRUk0hkSKhojWbJIuELMA/APnyvi7uTCRgVK6MgkVixmNoFbcqV1SweK8UEj5a22l1p9BliQoVFZ+Cd0kzCaW7UsV9FCpTZqSMhJTKlBklM6NjdLFiQgSWSWJboWJFPJssuYxGcESMShTFOgJGBcooUWaUi4TajGqZ0SyjPJGAk6w/nyIF8uTOHcNNjiTbjK6YkSLrCJF1ZMgoS1QWqDhQiciQPgNeSJkSWV9+2aV4UOmwKjtUQIzC464kWfdbz6GikjZtWnRo1z5BmdZse9FoQYkaASW8XmgeJbyeE97YSK7ZRzJsSEBSiNLA+3kQwTf37r6W8zRKQ4xQWCSykmmteQssXrhQSK1djz7bYOTw4WjaqDHOn79gV7H49fZtbN+2DcUKFrI1CQcrSDy6demCYYOH4EbkDdvqzILo012zShXs2LZdrmNX4RzK58RRKrNnTp+xq1jpCx8uWoJmQY3FVzohBVuVJzPCRqXpwP4D6NmtB3r37Cl+1UaRsipRVKTclSn6XxtfbCpV9NGmUCGk/zYVKSoSr76cVZRm7qNiZdwUjGJFX3EqVlblyihYRrmigmX80bm9c+cu6XOjRo7Ezh07XG4VRslifzfvKKuyxRE6KlxG2bIqXFS6ONLWo1t3+Pv5YfKkSTLqZlxBqDQ+aCSOo3DWkTgzp4AjcBMnTERAbX+JiKEW3oT04EfjHCW8XmhnJbxKeGMjprQc0+o2a2ZUauHxY8eJb575oLifE5/fSnhjf6BdhLdZFOEl8bBjoYU4IiLcEpbM5igNIc6nFr5y+YprwpkdmFgnrT3KYclIfA8fOow+PXujf5++MmJgB74sgwR72xdfIHf2V2WUwK5yWc7PF35GhdJlZHTh4s8/21Y08fhg0mR0bNceW0NCYiilnlxo/1f70adHT7zT/2218HoCZBI/VwmvFxpYCa8SXneySmLqIrzBboTX00xrauGN8VQ7S3itcXh9j/DSgkjibtfiHOE9qJnW7pJdkke6nJDw0hXGzuXs2XMoX6o05s+dJ1Zju/oGlcyJ4yegfWsnMq2Fiv/uO/37+yThpQJjxM621LKiI6CENzoejvxSwquE976E1zEL71707N4T7du2xe1bt2zt21FxeDXxRJSF1yHCG3kDW71g4fUdwuvLqYV7+2biCSdSCzsSlsyHCa9nASpsfa8n9cKU8HqhhZXwKuG9P+GdiQC/2nC5NNDCGxEhk5Lcz3vQb3VpiP2BdtbC66BLwxbnXRqU8F7B/Dnz0CiwATasXx97B0rAXk6E9OnEEz6Vac1HCa8hu2adgH6mp8QfASW88ccqwUcq4U2ChPf4Mdcs+QeR0Nj+H82lwTELb5haeO8+tc4SXocsvJJaOARFCxSUkH0JfgHFciInTXXp2AmDBw6UqBJ2DVvzUs65NPiyhbcPbt66GUtLPPwuDn17xaXBpwjvXp92aXj4XqBnJAQBJbwJQe0hz1HCmwQJ77FETHg5izo8AmGhzhPendu340Zk5EM+EXEfzpnmJGJDBw2yNTKBo4Q33EELr7o0uDoLIwK0btFCwp0xpJ8dC8kjoyGohfcemlYf3vPnztnm3+2sD68S3nstqFtxIaCENy5kbNyvhFcJr7uVVy28sT9gPkl4I5y08Drv0nDFZyatKeHlU+M1C+/ceXCE8Driw6uEN/Y3qu61IqCE14qGQ9tKeJXwJk3CWxw71MIr/tYjhg1D04aNQOuYHQtJDWOzemPSmhJetfBa+6zLwqsuDVZYfGab7w76j3NUi65K/K1LFAJKeL3QE5TwKuG9L+GNLSyZJ5PWvObS4FuEd/GixWjlS3F4IyOxVSetud7QzDznnEvDXJ20dhdpF+F1ysKrYclcfdqJDZJdpoBnmmgm/7DTP9+J+nqzTCW8XkBbCa8S3vsSXp205noKfdOlwUkf3qhJawe//tqFkR0b1klrmnhCLbzWPuUivGrhtcLiM9u//fYb2rdvD6ZlZjY+Jbz3mk4J7z0sHNtSwquEVwlv/B4v3yS8vu7Dq5nWdNLavedTCe89LHxxiwT3yy+/xMqVK8EU0+rScK8VlfDew8KxLSW8SnjvS3iDbY7Dqy4NMZ5lR6M0OJVamIknfNClgVal6pUqYcvmLeKHbNcHV10aoro18fRKWDLHMq21weZNm0BLpF3L3lAfjcNrFwCWctg/KMZ/167nz3IJn91UwuuFplPCq4T3/oQ3ltTCnvjwamrhGE+1TxJer01aUwuvWnjvPTJWCy9HXOwaEneFJUvEURpIwq9duyah6q5evQqrMHwdf/M+PCGRPJcKy82bN+U6v/zyi8TCZvnXr1+XCWdsjdu3b8v1eJwhr6aV7ty5I/+ja5L5nzmedTRl8b0XV125n//n/f74448y+fbMmTNyrinXXC+prJXweqEllfAq4b0v4VUfXtdTqC4NUVDwY+S9KA1KeJXwuh5BiTRSvlRpzH8EfXi3bNmC6tWro2jRoihevLhLihUrhsKFC6NMmTKYP3++i5TeQy3+WyTMn332GZo3b4433ngDOXPmRN68eZE/f340bNjQlWRm9erVqFKlivjjHjt2zEVcSWynT5+OihUrYs6rICqnAAAgAElEQVScOSA5JYGeNm0aSpUqJXVmXevUqYPdu3fHqbDw/bJ48WIpJ1u2bOLzmytXLqnTO++8g7Nnz8b/pnzkSCW8XmgoJbxKeJXwxu9B803C69CkNR91adBMa1F93edTC9Ol4eyjZeFlfPSRI0eiX79+6N+/v8iAAQPg5+eHZ555BmnSpMHChQsTTHipyNLl57XXXkOePHnQrl07DB06FH379gVJJ/dv375dyO358+eF7KZMmRI9evTAhQsXhLyuWrVKyCnr9O2330pnI+EliWZd+/TpI+Q5e/bsWLduXZyEd+PGjeAxr7/+utzvjBkzMGbMGInuMHr0aPH/jd9b23eOUsLrhbZSwquE976E1y0sGV+6FPdz4vPbnOedTGu+FZZsiVNhyZzKtKZhyaK9ncPDfTksWW8Zwo52Qwn8QdLk2z68bROtDy9xpVsDXQYoVFqY1S8oKAjPPfccunXr5tFEsC+++EKsx7Tmfvrpp+KWwOvRlaFu3brIly+fEF7jpsDsgpUrV8YLL7yADz74QCajvfnmmyhUqBBCQkKkH7AbsU+wriyLltsOHTqA1tq1a9fGSXgHDx6M559/HgMHDhS3Bp5PFweef/nyZdlOYBdNtKcp4fVC0yjhVcLrTlZJTI8cOYK9e/diVmyT1g55QHi95sPrW4TXsTi8jhFe3560FrJ5C27euOEaivX0VauphaMQdCe835886Sm00c53+fDKpLWzcRKmaCfF44fLh7e170xaoz8sLaa07pKQkvwSf7OQINNfltZXys8//+wS/qb7gVm43aVLFzz55JOYMGFCtP8Rm/r164s7AS28xm+a16JrA62/WbJkQZEiRWQ9depUcWUwZVvXJL2dO3d+IOGlO0SKFClAAr1v3z4XebaWldS2lfB6oUWV8CZBwnv8mFhgjUXVndA+6Hc0wnvXh3fC2HFCgnmuJ+XK+eERCAvdi57de6J927a4feuWrT19165dKFXctwivcxZe3w5LRmuO+cDa0UnUpSEKxaTg0uBMamHfILyRkZF4//33xbpavnx57N+/3/V4GNL7ww8/CBGma4C7ZMqUCUuWLHGdQ4WtRIkSchzDhlmX2AivuQafzVGjRomF+YknnkCLFi2EXPN8c4y1rPgSXk5QCwgIkPtLly6dbC9duhS8J1q3Yyvbeh1f3FbC64VWU8KbBAnvMfsJ73jbCW+YEt67z7ezURocIrzq0hDt7awW3ig4SES85dLgCOF1JNPaXvTs1h3v9O8P+r56shBfTgSbOXMmMmfOjJIlS2LHjh2uIq1EkNbdefPmYdiwYTGErgJWYksXBFpqaVHlJDQupixaf91dGlwXBCRzWvr06fHvf/9bJradOnXKda71OG7Hh/DyuhTG6aXvbs2aNfHKK6+IxZcT9oKDg8HoEUltUcLrhRZVwquE193iG5uFVwkvoJPWol5I/BjdkElrUZnWvnYo09qggQPFX88JC6/tcXjDwx1MLTxPUwvf/RZaXRocIbyJOCwZIaAysWzZMuTIkQMFCxbEpk2bXMP9hqAa2sDfxveVSrW7WJ8rlvPSSy+hUqVKOHHihClC1qGhoTJ5jBPZrC4N/Cfd3hglgn6/dGngxDkSbLpbxLbEl/Cac3m/fO9yEhsn67366qtIlSqVWKd5b0lpUcLrhdZ0lPCePYfJEyciKLC+fLjsvB0+lH41amDqlCk4cOCAaxKVJ8Pt9Fvlx7trp85oGtQQq1etAi03ng7jf/PNNzh8+DAmTpiA2jVqYuTwERKShbNY3cnmw/5mGevWrkXXTp3QsF4g1qxZIxq6p3V2+fDaHZbMlXhCXRrM8+CohTfcKQuvb/rwWl0aOAHGnSSYNnnYtVp4oxAjnt6y8JIIWUnbw7aZ9Xhf8eH9/PPPhVzS4rl8+XKJu8v7cO/H7r+t92rdNseR1HJSGgnlV1995TrEuEU89thjErmBE9sM5gwNxlBlGTJkkHBoe/bskfBo/P3RRx+5jnMVFk8LL4839TLbvCafV4Y3++9//yuRIeIi1dbr+dK2El4vtJajhPecEl4ScJ8mvG5RGg5FqA/v0EGDcCgiwrank4TXsUlr0TKt2RO7kh+jG+LS4KyFd7ADFl6Tac3+SWtORmlQC6952KwWXmcIb+KN0nDw4EFUqFAByZMnB0NzXbx4USaX0eWAQlcHWlCtZNHg9qA1kzswNu5//vMfCUVGMkk/2pYtW0ocXhJhhiWjJZjkkwoCw4TR2sqJczyeig5j59LKy1i7VuJsrm8svIzvy0gQrDd9cg2J5nHcN3bsWDDuMBNbGMs072/cuHF4/PHHpY78nZQWJbxeaE0lvOrS4G5Vjs2lwf5Ja0778JbAju3bhZjZ9Rj5pkuDQxZeH820tvJuamH7Ca+PuzTcumnLY0Ky5RULr1OJJxKxDy+jH3Bi2L/+9S/xZ33xxRdhFYYmY0xcksqELJzERstxsmTJhNxym8SVsXXpTkA3CrpTsH0ZUoz/p3/t/7d3HtBRFV0c1+M59t57wYKKggiCFEEFRaQjCojSeyo1oWgogvQkFFFQQLGgovipiEhTRKUFaQoWFGygFMsH53x60Pud383O+rJZQpItZDf3nTN5m7cz9838Z96+/9z5z8zWrVv9t2MyHRtDYKNly5aybds2/3d8IG8pKSk6yQ17bKDBJhW8g9wB4W3QoIGWje/ZBKNPnz66UgTeY5Y9Y2JyvB1GeKNQo0Z4jfAWhvCahjdWNbwRIrxR0PBGwsPrlTTYsmSbpH+fvpLev39MrsNb2jS8y5Yt040XEhISdC1bNobwhs6dO8vs2bOLvPGE8wjjaZ03b54SzEaNGum9IJaQ1KVLlyqRRcNLPCbDsSEF3wdqaZm0hgeadYGZGOf13hJ37ty5+h3r8RIgs994lq9zHSY2vWjfvr00a9ZMiTVLo3FP5BeO1Lu8R4EqRfwWRngjDrGIEV4jvFElvLYOb76nOqIa3o0RIrx4eBfHnqTBCG9u84N4IE8ywpuLh1/DW4InrUEcqbeCAmSxOCTQpeEeyBPQ53o17u7enInLfciHSweK7rP3exff/ejxnbPlLYdL6+zwP9+z6QWrNWzfvl0lHNSTi+vOznasn43wRqEGjfAa4Y1PwmuSBl4syFNGDB8u7do8JOgfw3HwouFluHTJYrm1UmWd6BkOu84G2rzkhETBw7tv7748HiIXp7hnI7y5yEEmYprwRkrSUEIJb6TJndc+n10o6nPmteNNe6jrgXEC47l8eM8uTWBcdz1Wz0Z4o1BzRniN8BaJ8IY6ac08vPme6uh5eMM4ac0Ib556tFUacuGAhLgh6XLXlM0zVJ0HsGL+E/FJa11jY+OJYsJnyUowAkZ4o1A5RnjjkPBGYKe1sGl4o0Z4zcNrHt78P6Dm4c3FxDy8edtGLEga8ubY/os3BIzwRqFGjfDGIeG1ndZsa2ERlQJs3LAhMpIGm7SW59c5sh7eGbbxhA9tr4e3tE1ay9Pg7J+4Q8AIbxSqNKKE98cfbeOJmF+Hd5q0aNpM/B7eUCUNtvFEvqc6dtfhjbyGd+/evRHR8IZ9p7X1kVyHN3YJ7zbP7Pt8Db8YF7yENzLr8JqkoRjVYknCgIAR3jCAeDgTESW8tvGEThqK6Y0nwr3Tmkka8j2S0dPw2qQ1kzTkNj+TNOR9DE3SkBcP+y/6CBjhjQLmEN4np06Vrh06yitz2Krwf2G5K/rBXTt3yqTsbN1a+Nd9+8Ji1xlhQeumjRsLi3GzHTBb94YSmLjFAtrsZpOSlKyz2t/8z3+UsLJ9byi2SU/IzsqS5o2byOOPjdC1BLlfKHZJyxbA899+W1LZWrhlK10QnG2XQ7HrsFi1apU8Pf1padGsuWSOH6/4hGKXtJB/7K9etVr69ukrPbp10511XL2G4/zRio+kVvUasmL5cmGt1XAdO3fu1G2nhw0ZIps9C6WHah/y8eLzL0iXDh3lhdmz/duFhmqXZ5B8ulUa8IiF42BiEjsgLVu6VFdpWL9+QzjM+m3oKg2JSTIkI0OXSKIc4Trmvf66NKxXT5YuWhK2tWfJG6thdOnYUYYPGSpffvFlWLL7j4iW/9kZs1TSsOCdd8JiFyNMLNu8abP079tPBqSl6S5d4TBO26C+WDOWSWusyRrOgzZcp1ZteXbmTNm1a5d/iapQ7wHhnZiZJT27dpNF772nS2KFatOlX7VylfRN7SWDBwwQfkPsMASCIWCENxgqYb7G8kJTp0yRTm3byfPPPac/sPv/u1/YMaW4gW1Hsbtj+3aZMG6cPNCihT7o7KBSXJsuHXYJEMgG9etLVmaWrFy5SnJycmTdunV65nNRA9sg8tKCiCV076Ekfe6rr8raNWtCsks+IOSEcWPHSON7G8iwjKHy/rL3lVwXNZ+B8TesXy+8xBO6d5eW97UQtk6FWAbGK+r/aBI/XL5cpk55Qpo2aiKjR40W9KA5IWBMHtbl5MjaNWtlxfIPJTU5Rbp06iT79u5V8kG7cfVcnDPtgkXRlyxZItVvqSJLFy+W3bt3a3spjj1vGkjYN9u2Sc9uPeSRQYMlZ+1aJQnc0xuvqJ8hjqSZNWOmdHi4rcyaMUMYxg/VLukP7D+g+RyakaGdIRZ3D9czuGf3Hlm4YIFUvqmi0DEC96KWPVh88r1nzx4lHoN8BIF44cADUvPynDlSv05deXf+Atn9yy9hs7t69Wrp0LadZAx6RDZt2Kg4h5pn2gYEb/pT06R1i/vlzTfeCI9dX5vNWZsjvVNSpW/v3rInTM8Jz/CBA/tl4bsLpewVZeTzLVvC8pzQBmi7tOHa1WrI9GnT9P1ChzZUnEnPMzd+zFjp2rGTzJ8/X9d/dc9msHZamGvYJc/8jqYmJsnA9HQjvGHmL/FkzghvFGqTh/KJKZOlft26+qM6Yew4mZiVLVkTMosdsn1p8XY0b9JUKpa7QUaOGCFTJk8utk2Xn+zMTNUFDxo4UK69ooza7+fbLSi9f5qk9etf7MALloXYa95aTSpXqCBdOnWUtH79ZECIdgekpasXpVnjJlLhunLSqP69Svb4AQwlv6QdmJYuXTt1lto1akil8uWVQA4eOEh3TwrFNnnjZdjq/pZSvuz10qRBQxmYPkBCxdil753aS26veZtUqVhRxvvanGs3rq6Les7OzJIpkybrGq5lzr9Iz2NGjRKuZ2UWvz2Tj0nZEwXPbu0aNaVhvXskvV9/fU7UdgjPCnYpf9sHH5IaVarKww+20U5iqM8g3irwTOvbTxrWry9Vb6okw4cOk8kTJ4X8DGJ79OOjJLFHT7n07POkb+8+2jEqan0Fiz8xK0vxqFn5Fql3x50ycsRIyRw/IbcOQ8AZu1MmTZIObdtL+avKSmL3HjJm1OjQf+sysxRTPKU1qlbRtsHvCPXKb1WwMhb22sTsiToa1KZVa62/7p276L1CbXO0LTT5af3TpG7tO+Su2rf7nsGskPLrnrEJ4ydIz+7d5ZwTT9LOIfcLFQswo+3Shq++8BJp07K1DB8yTPMbLjzua9xEalWrLj2795Dx48YJ+Be2roLFI1+0g6SeCVLvzjqSmpSkXukovNbtFjGIgBHeKFQaniuGyoZlZKhnMzkhQZITE0MLCYlKNlKTkqVXcopwTklKkiSue227/93Z+92hPvviYi8lMVGJY6+UFL0P9wolpCb78pucLKnJSZJrl8+518Nhu1dysvT25zdMdrGXkiKpKf/mP5S8klbL7Owm5WIQDhw0X5pX7pGidZiSmJTbLorSDgpoH9o2knLrj89sYpCn3ZGWa8GuB7Pri4stcM6tv+TC2yjoPgkJKpOgc0EAH8WjMPnz2nWf3dlXDuz1Ts21ywu3UGUOsJEHO75LSNQ89kpJ1TPtQn83gqULdi0Yxp46ofwafO2O5zxovr22vZ+D2ef7hETplcRvRLLWY7624Wz44uYp96Fs+vLmnhfaRi4eQdpcMBsFXfPhnNs2cn/bFAdv/lyeC7Lj/c6XFnx5/vR3Izn53zbnjcvnItpP0Tzzu5zbJhTjQDvOpi8virP3c2AeXHofHnhLaXu8V4Lmz9l3dgL/d9fdWb9P0nahz7avXQe17dJw9uY52D183yf26KGOAmQY+8Is7YsCRbBbRAkBI7xRAJoJM9/t2CErP/lEFi1cKIsXL5YlFgwDawPWBqwNWBuwNhByG0ATjKxh65YtYdPnR4Ea2C2ijIAR3igA/s/ff8tff/6lWiM0SxYih8GB/fvFhUjgjG2zm4tBpLCIBL6RthlpLCJtP9z4RDK/kbCNzUjYDTeugfYsz//+HjOSis6dCX3xtiVuFGhKqbiFEd4IV7M9eBEG2MwbAoaAIWAIGAKGgCFwGASM8B4GIPvaEDAEDAFDwBAwBAwBQyC2ETDCG9v1Z7k3BApEgBEGHWVgwVE7DAFDwBAwBAyBUoqAEd5SWvFW7NKBAJo2tG1svOAnv6Wj6FZKQ8AQMAQMAUPAj4ARXj8U9sEQiD8EWJSdBd/ZEMAmc8Rf/VqJDAFDwBAwBAqHgBHewuFksQyBmEPAJkzGXJVZhg0BQ8AQMAQihIAR3ggBa2YNAUOg9CKwadMmmTJlirz//vvy559/ll4grOSGgCFgCJQQBIzwlpCKsGwYAoZA/CAwY8YMOf/88yUtLU3YWtwOQ8AQMAQMgSOLgBHeI4u/3d0QMATiEAEjvHFYqVakwyLABNnff/9dJ8keNrJFMASijIAR3igDbrczBEobAkVZHcLFLYr+2KUpDK5FievsFSUvLk1hCG9x8uLs29kQKIkIvPDCC9K3b19588035euvv7ZtfktiJZXiPBnhLcWVb0U3BCKFAGSOpdBYJeKnn37SgPfnr7/+0tUigt334MGDum0z8X/77bcC42Kf+Ohjf/nlF9m9e7e+XA9ln7gs0UY8Vq0gHde8BzZJT+Azq1qQhvz88ccf/qXdvGn47M0L8TmmT58u5513Xj5JA3HBhS1iv//++3z55ns7DIFYReDll1+WVq1aSfXq1aVp06aqY9+8ebN5fGO1QuMs30Z446xCrTiGQElAAJL46KOPynXXXada1gsuuEDKli0rTZo0kY8++ihfFiHGTzzxhNx0000a/9JLL5XOnTurlyhfZBEl0niT7rjjDrn44ovloosukipVqki7du1k1apVuZtt+BJCYJ966impUaOGxrvkkkukTp06smjRojwTyiDDXbp0kbZt28qePXvkww8/lHr16ml+rr32Whk3bpwS8UBSCnl99tlnNW6ZMmXkqquuEu5x7LHHSnp6eh4N71dffSU9e/aUK664QgkxuJQvX166du0qTHSDZNthCMQqAnTm8OzOnj1bunXrpm27fv36+vzxTNlhCBxJBIzwHkn07d6GQBwiwCStHj16yHHHHScXXnih3HfffdKmTRt9+Z1zzjmCFyjwGDJkiJx++ukCsYS0QmSPP/54qVmzpnzzzTd5ouP97d+/v5xyyily5plnyt13363k+Pbbb5cTTjhBnnzySb/3Fs9samqqnHzyyXL55ZdLy5YtlXTjfT3ppJP0Rey8sj/88IPccsstUq5cOYFMV6pUScgv57POOktOPfVUeeaZZ/J4q0ibkJCg5Jb8Q14rV66s8Y855hgZMGCAn/Du27dPateuLUcffbRcffXVikmLFi2UIJNu8eLF/nznKbD9YwjECALeziAdyDfeeENat24tV155pXbqNm7caJ26GKnLeMymEd54rFUrkyFwBBGAoOKhvfnmm+Wzzz7LkxMIaOCqBZDIc889VyB/u3bt8seHSEJKMzMz/VpAPKB4ayG799xzj3z55Zf++HzYsWOHQFx58RLwvJ5xxhnSoEEDlRC4yB9//LGSUzzDzuP8448/qpcY23ijIenbt2/XJEuXLlVyzTW81xyQXby+kOKGDRvmKetLL70keG+9qzQ8//zz6i2GmP/6668uK3pmog+eYi9hyBPB/jEEYhQBnpfnnntOR1h4DnmWGHWxwxCINgJGeKONuN3PEIhzBCCJFSpUUDnDnDlzBM+m29rYFd0RO3SsjRo10uF91qyF0Lp1a19//XUlzrwk3XAoZLZixYrqMfrggw+cuaBEEfIMicabu2TJknxxR48erSS2V69eKpGA8OLhPeqoo1R/uG3bNn8a8oku8d577xVkCRyffPKJeo1vu+22fNKLYJPW3nrrLY3PPcgPxB9cAg+HTeD1wP+J99133+lav8uWLdPz8uXLhbBixQol8hB78rly5UpZvXq1hrVr10pOTo6sW7dOPv30U1m/fr3geUNSQaCT8vnnn8uWLVtk69at2qmgzAxVgwkdmm+//VY7A3QwyAP1An6Qm507d2rH5eeff/brq9FN0w4g+njoIfiu84O2G0kLuwHSiaD+IURgQ3ugnIXFJBAj+//IIeCtM+qRdvfAAw/IXXfdpe2Oa3YYAtFEwAhvNNG2exkCcY4ALzmIy2OPPaZeW7yceD+RGUCUIDTeFx16W4bzkRugY0XzileUM3ras88+W2699VYlU0D37rvvqmYXbS2T1Ti8L1YvvHh/b7zxRsGjCoFzcV18CPNll12mnmJImCO86G8hit4DwnvnnXdK3bp1lQhCxvDuIrvAA+08Vs52MMILwUWugQeZ8j744IMq74AYBnYIvPc+1Gcm3T399NPqjUYTzLAx+mECkolrrrlGv0MmQkBPTUCyQbjhhhsUH/Cng0JAQ03AO09AzoFEg4BGmlC1alWtE+qlWrVq2hFAH01AgkIHoFatWirfQMIB/khUwI+AfhrSQ0COQqA+8dij96RTQaCjQ9uhQ0RA/92sWTOVyNx///1KnpggBY4PPfSQaq/Bt3379tKxY0dtP7Sp7t27q26aEYOkpCRJSUlRmUvv3r2lX79+/vaG/GTQoEHyyCOPSEZGhiCzGTZsmLblkSNHyqhRo4RO0tixY2X8+PFa71lZWTJx4kSZPHmyatBp54xAMGmRkQvawaxZs9TDiYf/xRdfFDqByHpeeeUVmTt3rtCxY+iflQ3efvtteeedd2TBggWycOFC1ZkjdcErSoeQzgzackYl6Mjw/KxZs0bJJB0YOi8bNmzwd1zotHzxxRfaSXMdFjordFRo07R510HheaJjSeeEjgmdEtqs65Dw7NLOaXeuI3Kotum97p4JrtHBok2BMyMadhgC0UTACG800bZ7GQKlBAFekq+99poSoNNOO02JISQPosCL1b0E58+fr5IA9LEQNkiaNzAJDLLjdLzTpk1Tjy0T2nghF3QwOxzCDVHiJR944MnknpA2PJOO8EIG8Vh6D8gBRA3CRjpIPTplCDnyBcrjykQ6yE6wjScgEOzABsmE+KJzhpRDivB4FuXgfnix8dxC0CFBkCGIEQQJogRpgjyBM4QKYgXBevXVV5VwQb4gYUwyIg8QNMgaOEPeyOukSZMkOztbJkyYoCR/zJgx8vjjj8uIESNk+PDhMnToUCWIEEWIDB0WiGSfPn0E7zkEE6LJZD3IJyS0U6dO0qFDB+0AQFYhrZBXPIB45SG21BuEF/ILGYYY0+GgDiDQkGkINp53yDdkHGIOUYe0gzHYXn/99Ur4aVd0BmhTtEVkN27CI3WFNIX6RBeOHps2ifb7xBNPVG04nRsCOnEC170B+U2wgA3qOljgHt7As0Lg/sEC8hzyFyygMw8MlIdyBQvIiFxgFMQbwCNYQJPvDeBHp9FN1gRjOldgDvZ0ohiRoV6YxMrBZDbqzHVYi9LmLa4hEAoCRnhDQc/SGgKGQD4EvMSPL/HK4pHjRYlcACLE8DYHpIwXLUTHyRbyGfRcwCsGiYUEH+6FiYcXLyYEyXl4PabUW8bLGu+i18NLmsMRXobg0fPywodEBpYZzyDExbtKgzcO6SGZEDjICwQKjzHXvfG8+bXPRxYB6gXvJl5OvJ106ujA0PGiPdN+aZN4TOk80UlC3kNnDe8qnlY8rrRFJCR4Y/HK4qHFU4vHFikKXlxGH5C9sJKI67Tg/XWdFjqTeIfxFNNhwXuMTnbmzJna2aLTQodl6tSp6n2mw8JIBB1OOix4q/Fa02GhreLRpsMycOBAbbPeDktycnKeDgsjL67DwoomDz/8sL/DwnPOJFWWJGvcuLF2WPDa02HBO85BR4fOCpPa7DAEoomAEd5oom33MgRKAQIMzwcbosfLyJA6JBNNKQcvf15+DMl7NbkOJoZOvbbQlOK5w1MHWeY770F8J5mAePDyxZv33nvveaPpZzyWkG1WcYBoOg9vYQgvhId0kFrIhVvTl/zMmzdPvdSQe+8qDU6XGkhoISt4/yC/kKPA7/Nl3HehsPEOld6uGwLRRoBnFs8vnTtGSewwBKKJgBHeaKJt9zIESgECeKjwRuHhwgMGmYQg4s1i6BnSywQWDggiOkiGT1m+CEJLfAJpkQ/g4cKbxgHJwzPFUCxD3XjFnNaQ+Hh1GeYnHiSUIXqGefFE8Z3LCzIAhsAh2m5CW1EIL6QaossQdvPmzZW4o3tkYhraVIZ1Gcr2enjxyFEWPIFOF8lLH/JP+SkPHkEjslrVMfXH6qzg6qKd453m2UC6wuRHw6xgzOzb8CNghDf8mJpFQ6BUIwCBhfChjUWvB0FF54kHExLIGrpMjHEH5I8hVEgsE1rQfKL3QzKAt5VhUq/cgbRoRYkPYUXniS4U4okml6Fd53FliBntKHHRe6IvRVeKthDvLhOQ3OSZohBe8s4QNS9wSC8rL/CZ+7O1KsPEkFju5+wzkQoJBFpghokZVh48eLCWmbyYpMG1CDvHEwKM4jABEC0vkwqRcrjn00hvPNV0yS+LEd6SX0eWQ0MgphDghQahY/IXelsmzEDoIIN4PFnGKvDAO4uGkMkvLj7SByY04YF1qyC4dGgmmTgFIcY2AfLLCgHoHr0vUrxLrBoBCSceRJRhVfTAbgk07OIZZqIUk6P47D2Y1MbEKrzQblkyvqrfEYYAAAIoSURBVGeSGEQem6zuQLnRJmIbEgypdYQXLTM2wIH4lJMz+YLsoiO2wxCIBwR4/lh9hN0TeZ54rtEJe5f6i4dyWhliCwEjvLFVX5ZbQ6BEI+AlmmQUHS0TdCCJXs2eN573s5MxED+Q5Lp47ox9CCtSBSYFOe2uA4h43rhcZzkmyKv3CBaP711adz5UGr4nv7zgD3V4beDdIh/gwtmbb+J54x7Knl03BEoiAjy/rOVMR4/JanR6mdSGht7Jksi3tfGSWHvxnycjvPFfx1ZCQyCqCByOtBX1ZRcsfkH3OFT8SIAQznsFsxWJPJtNQyBSCLAGMesuszIKqzmgaafT646CnlsXx86GQKQQMMIbKWTNriFgCBgChoAhUIoQQLbD8mdMJmUSZ+DoRSmCwopaAhEwwlsCK8WyZAgYAoaAIWAIxBoCrLqCzMhLdCmDjV7EWk3GZ36N8MZnvVqpDAFDwBAwBAwBQ8AQMAR8CBjhtaZgCBgChoAhYAgYAoaAIRDXCBjhjevqtcIZAoaAIWAIGAKGgCFgCBjhtTZgCBgChoAhYAgYAoaAIRDXCBjhjevqtcIZAoaAIWAIGAKGgCFgCBjhtTZgCBgChoAhYAgYAoaAIRDXCBjhjevqtcIZAoaAIWAIGAKGgCFgCBjhtTZgCBgChoAhYAgYAoZAKUXg74MH5Z+//4n70hvhjfsqtgIaAoaAIWAIGAKGgCGQH4GDBw/Kgf37hXO8H/8HJ9nzSMa1lFMAAAAASUVORK5CYII=)", "_____no_output_____" ], [ "![A 1D Global max pooling](https://peltarion.com/static/1d_global_max_pooling.png) A 1D Global max pooling", "_____no_output_____" ], [ "The difference here versus the previous models which consisted only of Dense layers is the presence of convolution layers for which this type of network is named. A convolution layer passes over one set of values to the next calculating a dot product as it goes, creating one value from multiple values. We can determine the quantity of kernels (the functions that iterate over the array to calculate the dot product) as well as the size of its window it uses to calculate the dot product, and the size of its stride. As it creates a new value from multiple, we would lose dimensionality each time we have a Conv layer so we use padding. ", "_____no_output_____" ], [ "After the first Conv1D we add a pooling layer. This is to reduce the spatial size of the convolved features and also helps reduce overfitting which is a probelm with CNNs.Here we use max pooling instead of average pooling because taking the maximum instead of the average value from our kernel reduces noise by discarding noisy activations and so is better than average pooling.", "_____no_output_____" ], [ "### Basic Convolutional Neural Network", "_____no_output_____" ] ], [ [ "# Basic CNN\nmodel = Sequential()\nmodel.add(Conv1D(64, 2, activation=\"relu\", input_shape=(32,1)))\nmodel.add(Flatten())\nmodel.add(Dense(5, activation = 'softmax'))\n\nmodel.compile(loss = 'sparse_categorical_crossentropy', \n optimizer = \"adam\", \n metrics = ['accuracy'])\nmodel.summary()", "Model: \"sequential_20\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv1d_69 (Conv1D) (None, 31, 64) 192 \n_________________________________________________________________\nflatten_6 (Flatten) (None, 1984) 0 \n_________________________________________________________________\ndense_31 (Dense) (None, 5) 9925 \n=================================================================\nTotal params: 10,117\nTrainable params: 10,117\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(loss = 'sparse_categorical_crossentropy',\noptimizer = \"adam\",\nmetrics = ['accuracy'])\nmodel.fit(x_train, y_train, batch_size=32,epochs=30, verbose=2, validation_split=0.2, callbacks=[tf.keras.callbacks.EarlyStopping('loss', patience=3)])\nacc = model.evaluate(x_test, y_test)\nprint(\"Loss:\", acc[0], \" Accuracy:\", acc[1])", "Epoch 1/30\n12468/12468 - 44s - loss: 0.2602 - accuracy: 0.9065 - val_loss: 0.4388 - val_accuracy: 0.8419\nEpoch 2/30\n12468/12468 - 44s - loss: 0.2596 - accuracy: 0.9064 - val_loss: 0.3199 - val_accuracy: 0.8983\nEpoch 3/30\n12468/12468 - 45s - loss: 0.2592 - accuracy: 0.9069 - val_loss: 0.4657 - val_accuracy: 0.8281\nEpoch 4/30\n12468/12468 - 44s - loss: 0.2582 - accuracy: 0.9075 - val_loss: 0.5101 - val_accuracy: 0.8149\nEpoch 5/30\n12468/12468 - 44s - loss: 0.2578 - accuracy: 0.9074 - val_loss: 0.4511 - val_accuracy: 0.8448\nEpoch 6/30\n12468/12468 - 46s - loss: 0.2562 - accuracy: 0.9075 - val_loss: 0.4868 - val_accuracy: 0.8307\nEpoch 7/30\n12468/12468 - 45s - loss: 0.2571 - accuracy: 0.9077 - val_loss: 0.4163 - val_accuracy: 0.8631\nEpoch 8/30\n12468/12468 - 45s - loss: 0.2565 - accuracy: 0.9081 - val_loss: 0.3188 - val_accuracy: 0.8960\nEpoch 9/30\n12468/12468 - 44s - loss: 0.2550 - accuracy: 0.9083 - val_loss: 0.3496 - val_accuracy: 0.8855\nEpoch 10/30\n12468/12468 - 44s - loss: 0.2556 - accuracy: 0.9087 - val_loss: 0.4460 - val_accuracy: 0.8469\nEpoch 11/30\n12468/12468 - 44s - loss: 0.2552 - accuracy: 0.9082 - val_loss: 0.4242 - val_accuracy: 0.8454\nEpoch 12/30\n12468/12468 - 41s - loss: 0.2550 - accuracy: 0.9086 - val_loss: 0.5040 - val_accuracy: 0.8152\nEpoch 13/30\n12468/12468 - 44s - loss: 0.2533 - accuracy: 0.9091 - val_loss: 0.3997 - val_accuracy: 0.8715\nEpoch 14/30\n12468/12468 - 42s - loss: 0.2543 - accuracy: 0.9083 - val_loss: 0.4553 - val_accuracy: 0.8406\nEpoch 15/30\n12468/12468 - 41s - loss: 0.2541 - accuracy: 0.9088 - val_loss: 0.4146 - val_accuracy: 0.8561\nEpoch 16/30\n12468/12468 - 41s - loss: 0.2529 - accuracy: 0.9093 - val_loss: 0.4829 - val_accuracy: 0.8210\nEpoch 17/30\n12468/12468 - 41s - loss: 0.2531 - accuracy: 0.9090 - val_loss: 0.5622 - val_accuracy: 0.7948\nEpoch 18/30\n12468/12468 - 41s - loss: 0.2527 - accuracy: 0.9089 - val_loss: 0.4645 - val_accuracy: 0.8405\nEpoch 19/30\n12468/12468 - 41s - loss: 0.2524 - accuracy: 0.9097 - val_loss: 0.3727 - val_accuracy: 0.8783\nEpoch 20/30\n12468/12468 - 42s - loss: 0.2517 - accuracy: 0.9097 - val_loss: 0.4128 - val_accuracy: 0.8522\nEpoch 21/30\n12468/12468 - 41s - loss: 0.2524 - accuracy: 0.9095 - val_loss: 0.4914 - val_accuracy: 0.8215\nEpoch 22/30\n12468/12468 - 41s - loss: 0.2515 - accuracy: 0.9098 - val_loss: 0.3208 - val_accuracy: 0.8994\nEpoch 23/30\n12468/12468 - 41s - loss: 0.2506 - accuracy: 0.9098 - val_loss: 0.3103 - val_accuracy: 0.8994\nEpoch 24/30\n12468/12468 - 41s - loss: 0.2499 - accuracy: 0.9102 - val_loss: 0.4341 - val_accuracy: 0.8530\nEpoch 25/30\n12468/12468 - 41s - loss: 0.2502 - accuracy: 0.9102 - val_loss: 0.4011 - val_accuracy: 0.8704\nEpoch 26/30\n12468/12468 - 41s - loss: 0.2495 - accuracy: 0.9104 - val_loss: 0.3579 - val_accuracy: 0.8822\nEpoch 27/30\n12468/12468 - 41s - loss: 0.2498 - accuracy: 0.9104 - val_loss: 0.4215 - val_accuracy: 0.8811\nEpoch 28/30\n12468/12468 - 42s - loss: 0.2490 - accuracy: 0.9103 - val_loss: 0.5404 - val_accuracy: 0.8238\nEpoch 29/30\n12468/12468 - 41s - loss: 0.2489 - accuracy: 0.9100 - val_loss: 0.4299 - val_accuracy: 0.8854\nEpoch 30/30\n12468/12468 - 41s - loss: 0.2499 - accuracy: 0.9102 - val_loss: 0.8272 - val_accuracy: 0.8591\n3336/3336 [==============================] - 6s 2ms/step - loss: 0.6286 - accuracy: 0.8745\nLoss: 0.628559410572052 Accuracy: 0.874478816986084\n" ] ], [ [ "## Intermediate Convolutional Neural Network", "_____no_output_____" ] ], [ [ "model = Sequential()\nmodel.add(Conv1D(28, 2, activation=\"relu\", input_shape=(32,1)))\nmodel.add(Conv1D(28, 2, activation=\"relu\"))\nmodel.add(MaxPooling1D(2))\n\nmodel.add(Conv1D(64, 2, activation=\"relu\"))\nmodel.add(Conv1D(64, 2,activation=\"relu\"))\nmodel.add(MaxPooling1D(2))\n\n\nmodel.add(BatchNormalization())\nmodel.add(Flatten())\nmodel.add(Dropout(0.3))\nmodel.add(Dense(6, activation = 'softmax'))", "_____no_output_____" ], [ "model.compile(loss = 'sparse_categorical_crossentropy',\noptimizer = \"adam\",\nmetrics = ['accuracy'])\nmodel.fit(x_train, y_train, batch_size=32,epochs=30, verbose=2, validation_split=0.2, callbacks=[tf.keras.callbacks.EarlyStopping('loss', patience=3)])", "Epoch 1/30\n12468/12468 - 45s - loss: 0.3953 - accuracy: 0.8625 - val_loss: 0.5836 - val_accuracy: 0.8055\nEpoch 2/30\n12468/12468 - 45s - loss: 0.3399 - accuracy: 0.8789 - val_loss: 0.4322 - val_accuracy: 0.8588\nEpoch 3/30\n12468/12468 - 48s - loss: 0.3204 - accuracy: 0.8857 - val_loss: 0.3981 - val_accuracy: 0.8706\nEpoch 4/30\n12468/12468 - 45s - loss: 0.3092 - accuracy: 0.8898 - val_loss: 0.3501 - val_accuracy: 0.8727\nEpoch 5/30\n12468/12468 - 45s - loss: 0.3011 - accuracy: 0.8924 - val_loss: 0.4589 - val_accuracy: 0.8500\nEpoch 6/30\n12468/12468 - 45s - loss: 0.2950 - accuracy: 0.8943 - val_loss: 0.5422 - val_accuracy: 0.7972\nEpoch 7/30\n12468/12468 - 47s - loss: 0.2918 - accuracy: 0.8956 - val_loss: 0.5803 - val_accuracy: 0.7993\nEpoch 8/30\n12468/12468 - 45s - loss: 0.2884 - accuracy: 0.8968 - val_loss: 0.2744 - val_accuracy: 0.9124\nEpoch 9/30\n12468/12468 - 46s - loss: 0.2845 - accuracy: 0.8978 - val_loss: 0.3422 - val_accuracy: 0.8835\nEpoch 10/30\n12468/12468 - 47s - loss: 0.2836 - accuracy: 0.8986 - val_loss: 0.4292 - val_accuracy: 0.8538\nEpoch 11/30\n12468/12468 - 45s - loss: 0.2809 - accuracy: 0.8997 - val_loss: 0.3192 - val_accuracy: 0.8977\nEpoch 12/30\n12468/12468 - 46s - loss: 0.2792 - accuracy: 0.8999 - val_loss: 0.3849 - val_accuracy: 0.8693\nEpoch 13/30\n12468/12468 - 45s - loss: 0.2760 - accuracy: 0.9013 - val_loss: 0.4643 - val_accuracy: 0.8372\nEpoch 14/30\n12468/12468 - 45s - loss: 0.2756 - accuracy: 0.9015 - val_loss: 0.4731 - val_accuracy: 0.8193\nEpoch 15/30\n12468/12468 - 45s - loss: 0.2743 - accuracy: 0.9017 - val_loss: 0.3542 - val_accuracy: 0.8812\nEpoch 16/30\n12468/12468 - 45s - loss: 0.2721 - accuracy: 0.9023 - val_loss: 0.4624 - val_accuracy: 0.8368\nEpoch 17/30\n12468/12468 - 46s - loss: 0.2713 - accuracy: 0.9029 - val_loss: 0.5419 - val_accuracy: 0.8073\nEpoch 18/30\n12468/12468 - 45s - loss: 0.2709 - accuracy: 0.9026 - val_loss: 0.5212 - val_accuracy: 0.8168\nEpoch 19/30\n12468/12468 - 45s - loss: 0.2695 - accuracy: 0.9034 - val_loss: 0.3915 - val_accuracy: 0.8734\nEpoch 20/30\n12468/12468 - 45s - loss: 0.2678 - accuracy: 0.9038 - val_loss: 0.3500 - val_accuracy: 0.8836\nEpoch 21/30\n12468/12468 - 45s - loss: 0.2676 - accuracy: 0.9042 - val_loss: 0.4343 - val_accuracy: 0.8468\nEpoch 22/30\n12468/12468 - 45s - loss: 0.2663 - accuracy: 0.9050 - val_loss: 0.2942 - val_accuracy: 0.9066\nEpoch 23/30\n12468/12468 - 44s - loss: 0.2649 - accuracy: 0.9047 - val_loss: 0.2771 - val_accuracy: 0.9095\nEpoch 24/30\n12468/12468 - 45s - loss: 0.2636 - accuracy: 0.9054 - val_loss: 0.4135 - val_accuracy: 0.8552\nEpoch 25/30\n12468/12468 - 44s - loss: 0.2636 - accuracy: 0.9056 - val_loss: 0.3852 - val_accuracy: 0.8707\nEpoch 26/30\n12468/12468 - 44s - loss: 0.2621 - accuracy: 0.9056 - val_loss: 0.3276 - val_accuracy: 0.8940\nEpoch 27/30\n12468/12468 - 45s - loss: 0.2623 - accuracy: 0.9059 - val_loss: 0.3420 - val_accuracy: 0.8913\nEpoch 28/30\n12468/12468 - 45s - loss: 0.2610 - accuracy: 0.9061 - val_loss: 0.4162 - val_accuracy: 0.8599\nEpoch 29/30\n12468/12468 - 44s - loss: 0.2606 - accuracy: 0.9059 - val_loss: 0.3032 - val_accuracy: 0.9027\nEpoch 30/30\n12468/12468 - 44s - loss: 0.2610 - accuracy: 0.9060 - val_loss: 0.3797 - val_accuracy: 0.8688\n" ], [ " acc = model.evaluate(x_test, y_test)\n print(\"Loss:\", acc[0], \" Accuracy:\", acc[1])", "3336/3336 [==============================] - 7s 2ms/step - loss: 0.3265 - accuracy: 0.8874\nLoss: 0.32654300332069397 Accuracy: 0.8874179124832153\n" ] ], [ [ "Principles of CNN Design:\n- by convention channel size stays the same throughout network\n- number of filters should start low and increase throughout the network\n- keep adding layers until we over-fit then regularize using l1/l2 regularisation, droput, batch norm\n- be inspired by patterns in classic networks such as Conv-Pool-Conv-Pool or Conv-Conv-Pool", "_____no_output_____" ] ], [ [ "callbacks_list = [\n keras.callbacks.ModelCheckpoint(\n filepath='best_model.{epoch:02d}-{val_loss:.2f}.h5',\n monitor='val_loss', save_best_only=True),\n keras.callbacks.EarlyStopping(monitor='accuracy', patience=1)]", "_____no_output_____" ], [ "model.fit(x_train, y_train, batch_size=32,epochs=50, verbose=2, callbacks=callbacks_list, validation_split=0.2)\nacc = model.evaluate(x_test, y_test)\nprint(\"Loss:\", acc[0], \" Accuracy:\", acc[1])", "Epoch 1/50\n12468/12468 - 76s - loss: 0.6468 - accuracy: 0.7868 - val_loss: 1.0875 - val_accuracy: 0.6388\nEpoch 2/50\n12468/12468 - 75s - loss: 0.5467 - accuracy: 0.8131 - val_loss: 0.9476 - val_accuracy: 0.6218\nEpoch 3/50\n12468/12468 - 73s - loss: 0.5072 - accuracy: 0.8234 - val_loss: 0.7243 - val_accuracy: 0.7591\nEpoch 4/50\n12468/12468 - 73s - loss: 0.4831 - accuracy: 0.8310 - val_loss: 0.6739 - val_accuracy: 0.7576\nEpoch 5/50\n12468/12468 - 71s - loss: 0.4592 - accuracy: 0.8397 - val_loss: 0.7894 - val_accuracy: 0.7042\nEpoch 6/50\n12468/12468 - 71s - loss: 0.4422 - accuracy: 0.8469 - val_loss: 0.5264 - val_accuracy: 0.8227\nEpoch 7/50\n12468/12468 - 71s - loss: 0.4280 - accuracy: 0.8519 - val_loss: 0.4253 - val_accuracy: 0.8596\nEpoch 8/50\n12468/12468 - 71s - loss: 0.4155 - accuracy: 0.8565 - val_loss: 0.4739 - val_accuracy: 0.8465\nEpoch 9/50\n12468/12468 - 71s - loss: 0.4066 - accuracy: 0.8608 - val_loss: 0.4494 - val_accuracy: 0.8576\nEpoch 10/50\n12468/12468 - 71s - loss: 0.3984 - accuracy: 0.8639 - val_loss: 0.4990 - val_accuracy: 0.8191\nEpoch 11/50\n12468/12468 - 71s - loss: 0.3900 - accuracy: 0.8664 - val_loss: 0.5870 - val_accuracy: 0.7818\nEpoch 12/50\n12468/12468 - 71s - loss: 0.3836 - accuracy: 0.8680 - val_loss: 0.4228 - val_accuracy: 0.8774\nEpoch 13/50\n12468/12468 - 72s - loss: 0.3793 - accuracy: 0.8694 - val_loss: 0.5026 - val_accuracy: 0.8340\nEpoch 14/50\n12468/12468 - 70s - loss: 0.3704 - accuracy: 0.8727 - val_loss: 0.5475 - val_accuracy: 0.8243\nEpoch 15/50\n12468/12468 - 73s - loss: 0.3660 - accuracy: 0.8742 - val_loss: 0.5309 - val_accuracy: 0.8160\nEpoch 16/50\n12468/12468 - 72s - loss: 0.3606 - accuracy: 0.8753 - val_loss: 0.4574 - val_accuracy: 0.8452\nEpoch 17/50\n12468/12468 - 72s - loss: 0.3583 - accuracy: 0.8765 - val_loss: 0.5544 - val_accuracy: 0.8196\nEpoch 18/50\n12468/12468 - 71s - loss: 0.3551 - accuracy: 0.8777 - val_loss: 0.4008 - val_accuracy: 0.8783\nEpoch 19/50\n12468/12468 - 70s - loss: 0.3484 - accuracy: 0.8800 - val_loss: 0.5710 - val_accuracy: 0.8087\nEpoch 20/50\n12468/12468 - 70s - loss: 0.3478 - accuracy: 0.8797 - val_loss: 0.6133 - val_accuracy: 0.7725\n3336/3336 [==============================] - 9s 3ms/step - loss: 0.6559 - accuracy: 0.7836\nLoss: 0.6558953523635864 Accuracy: 0.7836055159568787\n" ], [ "def build_model(hp):\n model = Sequential()\n model.add(Conv1D(hp.Int('n_filt_1', 4, 32, 4), 2, activation=\"relu\", input_shape=(32,1)))\n model.add(Conv1D(hp.Int('n_filt_1', 4, 32, 4), 2, activation=\"relu\"))\n model.add(MaxPooling1D())\n\n for i in range(hp.Int('n_layers', 1, 12)):\n filt_nb = hp.Int(f'conv_{i}_units', min_value=4, max_value=32, step=4)\n model.add(Conv1D(filt_nb, hp.Int(f'kernal_{i}_size', 1, 4), activation=\"relu\"))\n model.add(Conv1D(filt_nb, hp.Int(f'kernal_{i}_size', 1, 4), activation=\"relu\"))\n model.add(MaxPooling1D())\n\n\n model.add(Flatten())\n model.add(BatchNormalization())\n\n model.add(Dense(6, activation = 'softmax'))\n\n adam=keras.optimizers.Adam(hp.Choice('learning_rate', [1e-2, 1e-3, 1e-4]))\n model.compile(loss = 'sparse_categorical_crossentropy',\n optimizer = adam,\n metrics = ['accuracy'])\n return model\n\nfrom kerastuner import Hyperband\ntuner = Hyperband(build_model, max_epochs=150, objective=\"val_accuracy\",project_name=\"cnn\", executions_per_trial=2)\n# Display search space summary\ntuner.search_space_summary()\n\n\ntuner.search(x=x_train,y=y_train, validation_data=(x_test,y_test), callbacks=[tf.keras.callbacks.EarlyStopping('val_loss', patience=3)] )\ntuner.results_summary()\n\ntuner.get_best_hyperparameters(num_trials=1)\n", "_____no_output_____" ] ], [ [ "## Auto-Optimised Models", "_____no_output_____" ], [ "Here, before attempting to use more appropriate CNN and RNNs, we are going to attempt one last time to get the best performance using only dense/fully-connected layers, by using the keras-tuner package to tune the hyperparameters of our model. Usually in machine learning we manually change each of these through trial and error, but with this package we can automate the combinatory process of optimising each hyperparameter. Here we have decided to auto-optimise the hyperperameters controlling the number of hidden layers, and the nb of neurons in each of those hidden layers", "_____no_output_____" ] ], [ [ "!pip install keras-tuner\nfrom kerastuner import RandomSearch", "_____no_output_____" ], [ "def build_model(hp):\n d1 = hp.Int(\"d1_units\", min_value=6, max_value=256, step=16)\n\n model = keras.models.Sequential()\n model.add(tf.keras.layers.Dense(d1, activation='relu', input_dim=32))\n\n for i in range(hp.Int('n_layers', 1, 8)): # adding variation of layers.\n model.add(Dense(hp.Int(f'conv_{i}_units',\n min_value=6,\n max_value=256,\n step=16), activation='relu'))\n \n \n model.add(Dense(6, activation='softmax'))\n \n model.compile(optimizer=\"adam\",loss=\"sparse_categorical_crossentropy\",metrics=[\"accuracy\"])\n return model", "_____no_output_____" ], [ "tuner = RandomSearch(build_model, objective=\"val_accuracy\", max_trials=5,executions_per_trial=5)\ntuner.search(x=x_train,y=y_train,epochs=15,validation_data=(x_test,y_test))", "Trial 5 Complete [00h 50m 10s]\nval_accuracy: 0.917763352394104\n\nBest val_accuracy So Far: 0.9192193508148193\nTotal elapsed time: 04h 20m 50s\nINFO:tensorflow:Oracle triggered exit\n" ] ], [ [ "### Construire le Modele", "_____no_output_____" ] ], [ [ "model = Sequential()\nmodel.add(Conv1D(64, 2, activation=\"relu\", input_shape=(4,1)))\nmodel.add(Conv1D(64, 2, activation=\"relu\"))\nmodel.add(Dense(16, activation=\"relu\"))\nmodel.add(MaxPooling1D())\nmodel.add(Flatten())\nmodel.add(Dense(3, activation = 'softmax'))\nmodel.compile(loss = 'sparse_categorical_crossentropy', \n optimizer = \"adam\", \n metrics = ['accuracy'])\nmodel.summary()", "_____no_output_____" ], [ "model.fit(xtrain, ytrain, batch_size=16,epochs=100, verbose=2, validation_split=0.2)", "Epoch 1/100\n7/7 - 0s - loss: 1.0363 - accuracy: 0.3465 - val_loss: 0.9948 - val_accuracy: 0.2692\nEpoch 2/100\n7/7 - 0s - loss: 0.9452 - accuracy: 0.3465 - val_loss: 0.9041 - val_accuracy: 0.5769\nEpoch 3/100\n7/7 - 0s - loss: 0.8996 - accuracy: 0.6238 - val_loss: 0.8725 - val_accuracy: 0.3846\nEpoch 4/100\n7/7 - 0s - loss: 0.8596 - accuracy: 0.6337 - val_loss: 0.8560 - val_accuracy: 0.4231\nEpoch 5/100\n7/7 - 0s - loss: 0.8324 - accuracy: 0.6436 - val_loss: 0.8400 - val_accuracy: 0.4231\nEpoch 6/100\n7/7 - 0s - loss: 0.8110 - accuracy: 0.6337 - val_loss: 0.7942 - val_accuracy: 0.5385\nEpoch 7/100\n7/7 - 0s - loss: 0.7920 - accuracy: 0.7525 - val_loss: 0.8010 - val_accuracy: 0.5000\nEpoch 8/100\n7/7 - 0s - loss: 0.7828 - accuracy: 0.6832 - val_loss: 0.8196 - val_accuracy: 0.5000\nEpoch 9/100\n7/7 - 0s - loss: 0.7653 - accuracy: 0.7624 - val_loss: 0.7344 - val_accuracy: 0.9231\nEpoch 10/100\n7/7 - 0s - loss: 0.7511 - accuracy: 0.9208 - val_loss: 0.7240 - val_accuracy: 0.8077\nEpoch 11/100\n7/7 - 0s - loss: 0.7274 - accuracy: 0.8119 - val_loss: 0.7438 - val_accuracy: 0.5769\nEpoch 12/100\n7/7 - 0s - loss: 0.7222 - accuracy: 0.7327 - val_loss: 0.6955 - val_accuracy: 0.9231\nEpoch 13/100\n7/7 - 0s - loss: 0.7156 - accuracy: 0.9604 - val_loss: 0.6561 - val_accuracy: 0.8462\nEpoch 14/100\n7/7 - 0s - loss: 0.6935 - accuracy: 0.9109 - val_loss: 0.7185 - val_accuracy: 0.5769\nEpoch 15/100\n7/7 - 0s - loss: 0.6885 - accuracy: 0.8119 - val_loss: 0.6627 - val_accuracy: 0.9231\nEpoch 16/100\n7/7 - 0s - loss: 0.6679 - accuracy: 0.9307 - val_loss: 0.6453 - val_accuracy: 0.9231\nEpoch 17/100\n7/7 - 0s - loss: 0.6547 - accuracy: 0.9307 - val_loss: 0.6344 - val_accuracy: 0.9231\nEpoch 18/100\n7/7 - 0s - loss: 0.6432 - accuracy: 0.9505 - val_loss: 0.6097 - val_accuracy: 0.9231\nEpoch 19/100\n7/7 - 0s - loss: 0.6302 - accuracy: 0.9505 - val_loss: 0.6261 - val_accuracy: 0.9231\nEpoch 20/100\n7/7 - 0s - loss: 0.6214 - accuracy: 0.9604 - val_loss: 0.5838 - val_accuracy: 0.9231\nEpoch 21/100\n7/7 - 0s - loss: 0.6040 - accuracy: 0.9604 - val_loss: 0.5773 - val_accuracy: 0.9231\nEpoch 22/100\n7/7 - 0s - loss: 0.5907 - accuracy: 0.9703 - val_loss: 0.5497 - val_accuracy: 0.9231\nEpoch 23/100\n7/7 - 0s - loss: 0.5783 - accuracy: 0.9604 - val_loss: 0.5503 - val_accuracy: 0.9231\nEpoch 24/100\n7/7 - 0s - loss: 0.5667 - accuracy: 0.9604 - val_loss: 0.5473 - val_accuracy: 0.9231\nEpoch 25/100\n7/7 - 0s - loss: 0.5555 - accuracy: 0.9604 - val_loss: 0.5178 - val_accuracy: 0.9231\nEpoch 26/100\n7/7 - 0s - loss: 0.5470 - accuracy: 0.9604 - val_loss: 0.5071 - val_accuracy: 0.9231\nEpoch 27/100\n7/7 - 0s - loss: 0.5308 - accuracy: 0.9703 - val_loss: 0.4907 - val_accuracy: 0.9231\nEpoch 28/100\n7/7 - 0s - loss: 0.5433 - accuracy: 0.9208 - val_loss: 0.4991 - val_accuracy: 0.9231\nEpoch 29/100\n7/7 - 0s - loss: 0.4719 - accuracy: 0.9703 - val_loss: 0.3896 - val_accuracy: 0.9231\nEpoch 30/100\n7/7 - 0s - loss: 0.3675 - accuracy: 0.9703 - val_loss: 0.3352 - val_accuracy: 0.8846\nEpoch 31/100\n7/7 - 0s - loss: 0.3060 - accuracy: 0.9505 - val_loss: 0.3216 - val_accuracy: 0.9231\nEpoch 32/100\n7/7 - 0s - loss: 0.2476 - accuracy: 0.9802 - val_loss: 0.3027 - val_accuracy: 0.9231\nEpoch 33/100\n7/7 - 0s - loss: 0.2090 - accuracy: 0.9604 - val_loss: 0.2417 - val_accuracy: 0.8846\nEpoch 34/100\n7/7 - 0s - loss: 0.1709 - accuracy: 0.9901 - val_loss: 0.2407 - val_accuracy: 0.9231\nEpoch 35/100\n7/7 - 0s - loss: 0.1594 - accuracy: 0.9802 - val_loss: 0.2367 - val_accuracy: 0.9231\nEpoch 36/100\n7/7 - 0s - loss: 0.1301 - accuracy: 0.9802 - val_loss: 0.2167 - val_accuracy: 0.9231\nEpoch 37/100\n7/7 - 0s - loss: 0.1192 - accuracy: 0.9703 - val_loss: 0.2397 - val_accuracy: 0.9231\nEpoch 38/100\n7/7 - 0s - loss: 0.1272 - accuracy: 0.9604 - val_loss: 0.1928 - val_accuracy: 0.9231\nEpoch 39/100\n7/7 - 0s - loss: 0.1016 - accuracy: 0.9802 - val_loss: 0.2145 - val_accuracy: 0.9231\nEpoch 40/100\n7/7 - 0s - loss: 0.0967 - accuracy: 0.9901 - val_loss: 0.1808 - val_accuracy: 0.8846\nEpoch 41/100\n7/7 - 0s - loss: 0.0953 - accuracy: 0.9802 - val_loss: 0.1772 - val_accuracy: 0.8846\nEpoch 42/100\n7/7 - 0s - loss: 0.1127 - accuracy: 0.9406 - val_loss: 0.1994 - val_accuracy: 0.9231\nEpoch 43/100\n7/7 - 0s - loss: 0.1013 - accuracy: 0.9703 - val_loss: 0.1984 - val_accuracy: 0.9231\nEpoch 44/100\n7/7 - 0s - loss: 0.0926 - accuracy: 0.9802 - val_loss: 0.1710 - val_accuracy: 0.8846\nEpoch 45/100\n7/7 - 0s - loss: 0.0999 - accuracy: 0.9604 - val_loss: 0.2173 - val_accuracy: 0.9231\nEpoch 46/100\n7/7 - 0s - loss: 0.0872 - accuracy: 0.9802 - val_loss: 0.1706 - val_accuracy: 0.9231\nEpoch 47/100\n7/7 - 0s - loss: 0.0885 - accuracy: 0.9802 - val_loss: 0.1757 - val_accuracy: 0.9231\nEpoch 48/100\n7/7 - 0s - loss: 0.0759 - accuracy: 0.9703 - val_loss: 0.1669 - val_accuracy: 0.9231\nEpoch 49/100\n7/7 - 0s - loss: 0.0704 - accuracy: 0.9802 - val_loss: 0.2044 - val_accuracy: 0.9231\nEpoch 50/100\n7/7 - 0s - loss: 0.0757 - accuracy: 0.9802 - val_loss: 0.1604 - val_accuracy: 0.8846\nEpoch 51/100\n7/7 - 0s - loss: 0.0903 - accuracy: 0.9802 - val_loss: 0.2126 - val_accuracy: 0.9231\nEpoch 52/100\n7/7 - 0s - loss: 0.0692 - accuracy: 0.9802 - val_loss: 0.1575 - val_accuracy: 0.8846\nEpoch 53/100\n7/7 - 0s - loss: 0.0692 - accuracy: 0.9802 - val_loss: 0.1759 - val_accuracy: 0.9231\nEpoch 54/100\n7/7 - 0s - loss: 0.0635 - accuracy: 0.9901 - val_loss: 0.1640 - val_accuracy: 0.9231\nEpoch 55/100\n7/7 - 0s - loss: 0.0721 - accuracy: 0.9802 - val_loss: 0.1530 - val_accuracy: 0.8846\nEpoch 56/100\n7/7 - 0s - loss: 0.0680 - accuracy: 0.9802 - val_loss: 0.1694 - val_accuracy: 0.9231\nEpoch 57/100\n7/7 - 0s - loss: 0.0624 - accuracy: 0.9901 - val_loss: 0.1701 - val_accuracy: 0.9231\nEpoch 58/100\n7/7 - 0s - loss: 0.0695 - accuracy: 0.9802 - val_loss: 0.1546 - val_accuracy: 0.9231\nEpoch 59/100\n7/7 - 0s - loss: 0.0860 - accuracy: 0.9505 - val_loss: 0.2552 - val_accuracy: 0.9231\nEpoch 60/100\n7/7 - 0s - loss: 0.1031 - accuracy: 0.9703 - val_loss: 0.1484 - val_accuracy: 0.8846\nEpoch 61/100\n7/7 - 0s - loss: 0.0639 - accuracy: 0.9703 - val_loss: 0.1820 - val_accuracy: 0.9231\nEpoch 62/100\n7/7 - 0s - loss: 0.0643 - accuracy: 0.9802 - val_loss: 0.1536 - val_accuracy: 0.9231\nEpoch 63/100\n7/7 - 0s - loss: 0.0577 - accuracy: 0.9802 - val_loss: 0.1710 - val_accuracy: 0.9231\nEpoch 64/100\n7/7 - 0s - loss: 0.0549 - accuracy: 0.9901 - val_loss: 0.1784 - val_accuracy: 0.9231\nEpoch 65/100\n7/7 - 0s - loss: 0.0624 - accuracy: 0.9703 - val_loss: 0.1706 - val_accuracy: 0.9231\nEpoch 66/100\n7/7 - 0s - loss: 0.0567 - accuracy: 0.9901 - val_loss: 0.1539 - val_accuracy: 0.9231\nEpoch 67/100\n7/7 - 0s - loss: 0.0521 - accuracy: 0.9802 - val_loss: 0.1726 - val_accuracy: 0.9231\nEpoch 68/100\n7/7 - 0s - loss: 0.0518 - accuracy: 0.9901 - val_loss: 0.1468 - val_accuracy: 0.9231\nEpoch 69/100\n7/7 - 0s - loss: 0.0510 - accuracy: 0.9901 - val_loss: 0.1644 - val_accuracy: 0.9231\nEpoch 70/100\n7/7 - 0s - loss: 0.0533 - accuracy: 0.9802 - val_loss: 0.1409 - val_accuracy: 0.9231\nEpoch 71/100\n7/7 - 0s - loss: 0.0736 - accuracy: 0.9802 - val_loss: 0.1797 - val_accuracy: 0.9231\nEpoch 72/100\n7/7 - 0s - loss: 0.0528 - accuracy: 0.9802 - val_loss: 0.1489 - val_accuracy: 0.9231\nEpoch 73/100\n7/7 - 0s - loss: 0.0564 - accuracy: 0.9703 - val_loss: 0.1535 - val_accuracy: 0.9231\nEpoch 74/100\n7/7 - 0s - loss: 0.0606 - accuracy: 0.9802 - val_loss: 0.1638 - val_accuracy: 0.9231\nEpoch 75/100\n7/7 - 0s - loss: 0.0587 - accuracy: 0.9802 - val_loss: 0.1423 - val_accuracy: 0.9231\nEpoch 76/100\n7/7 - 0s - loss: 0.0570 - accuracy: 0.9703 - val_loss: 0.1464 - val_accuracy: 0.9231\nEpoch 77/100\n7/7 - 0s - loss: 0.0461 - accuracy: 0.9802 - val_loss: 0.1655 - val_accuracy: 0.9231\nEpoch 78/100\n7/7 - 0s - loss: 0.0517 - accuracy: 0.9703 - val_loss: 0.1440 - val_accuracy: 0.9231\nEpoch 79/100\n7/7 - 0s - loss: 0.0518 - accuracy: 0.9703 - val_loss: 0.1537 - val_accuracy: 0.9231\nEpoch 80/100\n7/7 - 0s - loss: 0.0463 - accuracy: 0.9802 - val_loss: 0.1394 - val_accuracy: 0.9231\nEpoch 81/100\n7/7 - 0s - loss: 0.0451 - accuracy: 0.9802 - val_loss: 0.1634 - val_accuracy: 0.9231\nEpoch 82/100\n7/7 - 0s - loss: 0.0470 - accuracy: 0.9802 - val_loss: 0.1454 - val_accuracy: 0.9231\nEpoch 83/100\n7/7 - 0s - loss: 0.0490 - accuracy: 0.9802 - val_loss: 0.1549 - val_accuracy: 0.9231\nEpoch 84/100\n7/7 - 0s - loss: 0.0520 - accuracy: 0.9901 - val_loss: 0.1731 - val_accuracy: 0.9231\nEpoch 85/100\n7/7 - 0s - loss: 0.0747 - accuracy: 0.9802 - val_loss: 0.1302 - val_accuracy: 0.9231\nEpoch 86/100\n7/7 - 0s - loss: 0.0674 - accuracy: 0.9901 - val_loss: 0.2171 - val_accuracy: 0.9231\nEpoch 87/100\n7/7 - 0s - loss: 0.0900 - accuracy: 0.9703 - val_loss: 0.1348 - val_accuracy: 0.9231\nEpoch 88/100\n7/7 - 0s - loss: 0.1275 - accuracy: 0.9406 - val_loss: 0.2374 - val_accuracy: 0.9231\nEpoch 89/100\n7/7 - 0s - loss: 0.1293 - accuracy: 0.9505 - val_loss: 0.1342 - val_accuracy: 0.9231\nEpoch 90/100\n7/7 - 0s - loss: 0.0464 - accuracy: 0.9802 - val_loss: 0.1349 - val_accuracy: 0.9231\nEpoch 91/100\n7/7 - 0s - loss: 0.0429 - accuracy: 0.9802 - val_loss: 0.1683 - val_accuracy: 0.9231\nEpoch 92/100\n7/7 - 0s - loss: 0.0513 - accuracy: 0.9802 - val_loss: 0.1451 - val_accuracy: 0.9231\nEpoch 93/100\n7/7 - 0s - loss: 0.0455 - accuracy: 0.9802 - val_loss: 0.1722 - val_accuracy: 0.9231\nEpoch 94/100\n7/7 - 0s - loss: 0.0490 - accuracy: 0.9802 - val_loss: 0.1311 - val_accuracy: 0.9231\nEpoch 95/100\n7/7 - 0s - loss: 0.0427 - accuracy: 0.9802 - val_loss: 0.1487 - val_accuracy: 0.9231\nEpoch 96/100\n7/7 - 0s - loss: 0.0403 - accuracy: 0.9802 - val_loss: 0.1325 - val_accuracy: 0.9231\nEpoch 97/100\n7/7 - 0s - loss: 0.0459 - accuracy: 0.9802 - val_loss: 0.1734 - val_accuracy: 0.9231\nEpoch 98/100\n7/7 - 0s - loss: 0.0497 - accuracy: 0.9802 - val_loss: 0.1210 - val_accuracy: 0.9615\nEpoch 99/100\n7/7 - 0s - loss: 0.0560 - accuracy: 0.9703 - val_loss: 0.1830 - val_accuracy: 0.9231\nEpoch 100/100\n7/7 - 0s - loss: 0.0505 - accuracy: 0.9802 - val_loss: 0.1284 - val_accuracy: 0.9231\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0a3a4421177d4d7b97a42d504be132043ad9bf
9,565
ipynb
Jupyter Notebook
notebooks/senzing-examples/Windows/senzing-create-redo-records.ipynb
Senzing/docker-jupyter
33ea9d51fdbc2e16c4ca0e0ed51116da42eed5f9
[ "Apache-2.0" ]
1
2021-09-28T04:13:48.000Z
2021-09-28T04:13:48.000Z
notebooks/senzing-examples/Windows/senzing-create-redo-records.ipynb
Senzing/docker-jupyter
33ea9d51fdbc2e16c4ca0e0ed51116da42eed5f9
[ "Apache-2.0" ]
88
2019-01-07T15:16:04.000Z
2022-03-24T18:56:17.000Z
notebooks/senzing-examples/Windows/senzing-create-redo-records.ipynb
Senzing/docker-jupyter
33ea9d51fdbc2e16c4ca0e0ed51116da42eed5f9
[ "Apache-2.0" ]
4
2019-02-04T18:04:58.000Z
2020-07-09T01:37:34.000Z
26.349862
118
0.567486
[ [ [ "# Create redo records\n\nThis Jupyter notebook shows how to create a Senzing \"redo record\".\nIt assumes a G2 database that is empty.\n\nEssentially the steps are to create very similar records under different data sources,\nthen delete one of the records. This produces a \"redo record\".", "_____no_output_____" ], [ "## G2Engine", "_____no_output_____" ], [ "### Senzing initialization\n\nCreate an instance of G2Engine, G2ConfigMgr, and G2Config.", "_____no_output_____" ] ], [ [ "from G2Engine import G2Engine\nfrom G2ConfigMgr import G2ConfigMgr\nfrom G2Config import G2Config", "_____no_output_____" ], [ "g2_engine = G2Engine()\ntry:\n g2_engine_flags = G2Engine.G2_EXPORT_DEFAULT_FLAGS\n g2_engine.initV2(\n \"pyG2EngineForRedoRecords\",\n senzing_config_json,\n verbose_logging)\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_engine.getLastException())", "_____no_output_____" ], [ "g2_configuration_manager = G2ConfigMgr()\ntry:\n g2_configuration_manager.initV2(\n \"pyG2ConfigMgrForRedoRecords\",\n senzing_config_json,\n verbose_logging)\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_configuration_manager.getLastException())", "_____no_output_____" ], [ "g2_config = G2Config()\ntry:\n g2_config.initV2(\n \"pyG2ConfigForRedoRecords\",\n senzing_config_json,\n verbose_logging)\n config_handle = g2_config.create()\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_config.getLastException())", "_____no_output_____" ] ], [ [ "### primeEngine", "_____no_output_____" ] ], [ [ "try:\n g2_engine.primeEngine()\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_engine.getLastException())", "_____no_output_____" ] ], [ [ "### Variable initialization", "_____no_output_____" ] ], [ [ "load_id = None", "_____no_output_____" ] ], [ [ "### Create add data source function\n\nCreate a data source with a name having the form `TEST_DATA_SOURCE_nnn`.", "_____no_output_____" ] ], [ [ "def add_data_source(datasource_suffix):\n datasource_prefix = \"TEST_DATA_SOURCE_\"\n datasource_id = \"{0}{1}\".format(datasource_prefix, datasource_suffix)\n configuration_comment = \"Added {}\".format(datasource_id)\n g2_config.addDataSource(config_handle, datasource_id)\n configuration_bytearray = bytearray()\n return_code = g2_config.save(config_handle, configuration_bytearray)\n configuration_json = configuration_bytearray.decode()\n configuration_id_bytearray = bytearray()\n g2_configuration_manager.addConfig(configuration_json, configuration_comment, configuration_id_bytearray)\n g2_configuration_manager.setDefaultConfigID(configuration_id_bytearray)\n g2_engine.reinitV2(configuration_id_bytearray)", "_____no_output_____" ] ], [ [ "### Create add record function\n\nCreate a record with the id having the form `RECORD_nnn`.\n**Note:** this is essentially the same record with only the `DRIVERS_LICENSE_NUMBER` modified slightly.", "_____no_output_____" ] ], [ [ "def add_record(record_id_suffix, datasource_suffix):\n datasource_prefix = \"TEST_DATA_SOURCE_\"\n record_id_prefix = \"RECORD_\"\n datasource_id = \"{0}{1}\".format(datasource_prefix, datasource_suffix)\n record_id = \"{0}{1}\".format(record_id_prefix, record_id_suffix)\n data = {\n \"NAMES\": [{\n \"NAME_TYPE\": \"PRIMARY\",\n \"NAME_LAST\": \"Smith\",\n \"NAME_FIRST\": \"John\",\n \"NAME_MIDDLE\": \"M\"\n }],\n \"PASSPORT_NUMBER\": \"PP11111\",\n \"PASSPORT_COUNTRY\": \"US\",\n \"DRIVERS_LICENSE_NUMBER\": \"DL1{:04d}\".format(record_id_suffix),\n \"SSN_NUMBER\": \"111-11-1111\"\n }\n data_as_json = json.dumps(data)\n g2_engine.addRecord(\n datasource_id,\n record_id,\n data_as_json,\n load_id)", "_____no_output_____" ] ], [ [ "## Redo record", "_____no_output_____" ], [ "### Print data sources\n\nPrint the list of currently defined data sources.", "_____no_output_____" ] ], [ [ "try:\n datasources_bytearray = bytearray()\n g2_config.listDataSources(config_handle, datasources_bytearray)\n datasources_dictionary = json.loads(datasources_bytearray.decode())\n print(datasources_dictionary)\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_config.getLastException())", "_____no_output_____" ] ], [ [ "### Add data sources and records", "_____no_output_____" ] ], [ [ "try:\n add_data_source(1)\n add_record(1,1)\n add_record(2,1)\n add_data_source(2)\n add_record(3,2)\n add_record(4,2)\n add_data_source(3)\n add_record(5,3)\n add_record(6,3)\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_engine.getLastException())", "_____no_output_____" ] ], [ [ "### Delete record\n\nDeleting a record will create a \"redo record\".", "_____no_output_____" ] ], [ [ "try:\n g2_engine.deleteRecord(\"TEST_DATA_SOURCE_3\", \"RECORD_5\", load_id)\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_engine.getLastException())", "_____no_output_____" ] ], [ [ "### Count redo records\n\nThe `count_of_redo_records` will show how many redo records are in Senzing's queue of redo records. ", "_____no_output_____" ] ], [ [ "try:\n count_of_redo_records = g2_engine.countRedoRecords()\n print(\"Number of redo records: {0}\".format(count_of_redo_records))\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_engine.getLastException())", "_____no_output_____" ] ], [ [ "### Print data sources again\n\nPrint the list of currently defined data sources.", "_____no_output_____" ] ], [ [ "try:\n datasources_bytearray = bytearray()\n g2_config.listDataSources(config_handle, datasources_bytearray)\n datasources_dictionary = json.loads(datasources_bytearray.decode())\n print(datasources_dictionary)\nexcept G2Exception.G2ModuleGenericException as err:\n print(g2_config.getLastException())", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb0a3ab7ad09bdcfc5230e575aa99ff5bfe5e9bd
17,110
ipynb
Jupyter Notebook
notebooks/pipeline/pipeline_02.ipynb
HimariO/keras-js
e914a21733ea3a1ed49e3e71331b1c5e860a9eb7
[ "MIT" ]
5,330
2016-10-01T02:04:36.000Z
2022-03-28T18:32:10.000Z
notebooks/pipeline/pipeline_02.ipynb
HimariO/keras-js
e914a21733ea3a1ed49e3e71331b1c5e860a9eb7
[ "MIT" ]
126
2016-10-14T04:49:22.000Z
2022-02-23T14:24:47.000Z
notebooks/pipeline/pipeline_02.ipynb
HimariO/keras-js
e914a21733ea3a1ed49e3e71331b1c5e860a9eb7
[ "MIT" ]
615
2016-10-14T00:48:57.000Z
2021-12-31T05:43:54.000Z
95.055556
12,375
0.619287
[ [ [ "import numpy as np\nimport json\nfrom keras.models import Model\nfrom keras.layers import Input\nfrom keras.layers.convolutional import Conv2D\nfrom keras import backend as K\nfrom collections import OrderedDict", "Using TensorFlow backend.\n" ], [ "def format_decimal(arr, places=6):\n return [round(x * 10**places) / 10**places for x in arr]", "_____no_output_____" ], [ "DATA = OrderedDict()", "_____no_output_____" ] ], [ [ "### pipeline 2", "_____no_output_____" ] ], [ [ "random_seed = 1002\ndata_in_shape = (16, 16, 2)\n\nlayers = [\n Conv2D(5, (3,3), activation='relu', padding='same', strides=(2,2), data_format='channels_last', use_bias=True),\n Conv2D(4, (3,3), activation='linear', padding='valid', strides=(1,1), data_format='channels_last', use_bias=True),\n Conv2D(2, (1,1), activation='relu', padding='valid', strides=(1,1), data_format='channels_last', use_bias=True),\n Conv2D(3, (5,5), activation='relu', padding='same', strides=(1,1), data_format='channels_last', use_bias=True),\n Conv2D(2, (3,3), activation='linear', padding='same', strides=(1,1), data_format='channels_last', use_bias=True),\n Conv2D(4, (1,1), activation='relu', padding='valid', strides=(1,1), data_format='channels_last', use_bias=True),\n Conv2D(2, (3,3), activation='linear', padding='valid', strides=(1,1), data_format='channels_last', use_bias=True)\n]\n\ninput_layer = Input(shape=data_in_shape)\nx = layers[0](input_layer)\nfor layer in layers[1:-1]:\n x = layer(x)\noutput_layer = layers[-1](x)\nmodel = Model(inputs=input_layer, outputs=output_layer)\n\nnp.random.seed(random_seed)\ndata_in = 2 * np.random.random(data_in_shape) - 1\n\n# set weights to random (use seed for reproducibility)\nweights = []\nfor i, w in enumerate(model.get_weights()):\n np.random.seed(random_seed + i)\n weights.append(2 * np.random.random(w.shape) - 1)\nmodel.set_weights(weights)\n\nresult = model.predict(np.array([data_in]))\ndata_out_shape = result[0].shape\ndata_in_formatted = format_decimal(data_in.ravel().tolist())\ndata_out_formatted = format_decimal(result[0].ravel().tolist())\n\nDATA['pipeline_02'] = {\n 'input': {'data': data_in_formatted, 'shape': data_in_shape},\n 'weights': [{'data': format_decimal(w.ravel().tolist()), 'shape': w.shape} for w in weights],\n 'expected': {'data': data_out_formatted, 'shape': data_out_shape}\n}", "_____no_output_____" ] ], [ [ "### export for Keras.js tests", "_____no_output_____" ] ], [ [ "import os\n\nfilename = '../../test/data/pipeline/02.json'\nif not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\nwith open(filename, 'w') as f:\n json.dump(DATA, f)", "_____no_output_____" ], [ "print(json.dumps(DATA))", "{\"pipeline_02\": {\"input\": {\"data\": [-0.742023, -0.077688, -0.167692, 0.205448, -0.633864, -0.164175, -0.731823, 0.313236, 0.613465, -0.723716, -0.299231, 0.229032, 0.102561, 0.384949, -0.90948, -0.294898, -0.916217, -0.699031, -0.323329, -0.673445, 0.521949, -0.306796, -0.476018, -0.628623, 0.808028, -0.585043, -0.307429, -0.234868, -0.897584, 0.741743, 0.320785, 0.709132, -0.978084, 0.601894, -0.228816, -0.069558, -0.522066, -0.399597, -0.916222, 0.161549, -0.211915, 0.823372, -0.6549, -0.30403, 0.677588, -0.431259, 0.219659, -0.091937, -0.101636, -0.595218, -0.815428, 0.502932, 0.775249, 0.624226, 0.622601, -0.091075, 0.763603, 0.472659, 0.621131, -0.504549, -0.270214, 0.492749, 0.643055, -0.290058, -0.752162, 0.758918, 0.011832, -0.183967, 0.768298, 0.764241, 0.906398, 0.872853, -0.292238, 0.16788, -0.447741, 0.679196, 0.566614, 0.867549, -0.011606, -0.252108, 0.165669, -0.509362, 0.620632, -0.32465, -0.071143, -0.823613, 0.331067, -0.016903, -0.76138, -0.491146, 0.106088, -0.641492, 0.234893, 0.658853, -0.475623, 0.269103, 0.935505, -0.577134, 0.985015, -0.405957, -0.325882, 0.849518, -0.589155, 0.378331, -0.753075, 0.711411, 0.04547, 0.398327, -0.665657, 0.531142, -0.410293, -0.526649, 0.860648, 0.32795, -0.197082, -0.095526, -0.391361, 0.785465, -0.267269, -0.020154, -0.95189, -0.580742, 0.788104, -0.092433, 0.320354, 0.070651, 0.045416, 0.99799, 0.583116, -0.708131, -0.104784, -0.838947, -0.598224, 0.209105, 0.824956, 0.10438, 0.692046, -0.091308, 0.884896, 0.730617, 0.244486, -0.415624, -0.397714, -0.647236, -0.816162, 0.001325, 0.593873, -0.243723, 0.168275, 0.192345, -0.522916, 0.458154, -0.333828, -0.014549, -0.744552, -0.203297, 0.771256, -0.703928, 0.998892, -0.947633, 0.566086, -0.274437, -0.218108, -0.800599, 0.504541, 0.233776, -0.111802, -0.03089, 0.761595, 0.537963, 0.217941, -0.910822, 0.531235, -0.018533, -0.161811, -0.200401, -0.742618, -0.35126, -0.954474, -0.071092, -0.817604, 0.355039, -0.71623, -0.174142, -0.097041, -0.630172, -0.998405, 0.830425, -0.54058, 0.091193, -0.128435, -0.698893, -0.238618, 0.090807, -0.544714, 0.529065, 0.016035, 0.031572, -0.112153, -0.267803, 0.750932, -0.1755, -0.056039, -0.819933, 0.144761, 0.729724, -0.415998, 0.708302, -0.462218, -0.147249, 0.436382, -0.027364, 0.920436, 0.982113, -0.719826, -0.39192, 0.687992, 0.67207, 0.806184, -0.848625, -0.328676, 0.483859, 0.121646, -0.563886, -0.489969, 0.149126, 0.572393, -0.179969, 0.261244, 0.685893, 0.708577, 0.583762, 0.611609, 0.451507, 0.734521, 0.783842, 0.910886, 0.094794, -0.7603, -0.571009, 0.766552, -0.005378, 0.441925, -0.405844, -0.44351, -0.02502, 0.532842, -0.605724, 0.489149, -0.030616, 0.618367, -0.507044, 0.921095, 0.277124, 0.277796, 0.517938, -0.097656, -0.718449, -0.64776, -0.523526, -0.587764, -0.917412, -0.377526, -0.137101, -0.441038, -0.818358, -0.337538, -0.092447, -0.099825, 0.452412, -0.245787, -0.318709, 0.262443, 0.243089, -0.81751, 0.151959, -0.712124, -0.568058, 0.851689, 0.578001, 0.5535, -0.968162, 0.907764, -0.33327, 0.719366, 0.166725, 0.739587, -0.285609, -0.75929, 0.003963, 0.333512, 0.274331, 0.284225, 0.108992, -0.07236, 0.421666, 0.778074, -0.418525, -0.082178, 0.316198, -0.881106, 0.525714, -0.461855, 0.216712, 0.779531, 0.662279, 0.262508, 0.877733, 0.568056, 0.342805, -0.463299, -0.378632, 0.381052, 0.99444, -0.720164, -0.687681, -0.088427, 0.999846, 0.998652, 0.738574, 0.845422, 0.081389, -0.387621, 0.425191, -0.649076, -0.206885, 0.01809, -0.383956, 0.499222, -0.311785, 0.802452, -0.51268, 0.917756, 0.561026, -0.142752, 0.819264, -0.86242, -0.900524, -0.91049, -0.086446, -0.423479, 0.315488, -0.194078, 0.02387, -0.084516, -0.993568, -0.076955, 0.860088, -0.810888, -0.690519, 0.006994, -0.252601, 0.058697, 0.895512, -0.232657, -0.107581, -0.619655, -0.835333, 0.236688, -0.832395, -0.418488, 0.12863, 0.52645, 0.056954, 0.301947, -0.733774, -0.738797, 0.377858, -0.300689, 0.195755, 0.485844, 0.233366, -0.49798, 0.738907, 0.964552, 0.014276, -0.92375, 0.161384, -0.380637, 0.942824, -0.712071, 0.493943, -0.613403, 0.761721, 0.268988, 0.133175, -0.904693, -0.072221, -0.38943, -0.628801, -0.872558, 0.22282, 0.124402, 0.975161, -0.753868, -0.12336, -0.014669, -0.377103, 0.103176, -0.996724, 0.734126, -0.418102, 0.404471, -0.901678, -0.08642, 0.242373, -0.155506, 0.844976, -0.35723, 0.598496, -0.757695, 0.846844, 0.416975, -0.193873, -0.170191, 0.725291, 0.486349, -0.195375, 0.504815, 0.087869, 0.430875, 0.630802, 0.328853, 0.729598, -0.42338, 0.826289, 0.830184, -0.382228, 0.251766, -0.483812, -0.498886, -0.498876, 0.743145, -0.122468, 0.19787, 0.426367, -0.319919, 0.577979, 0.045291, -0.577872, -0.890138, -0.904327, 0.39408, 0.936017, 0.699018, -0.95137, 0.739907, -0.820321, 0.298268, 0.425665, -0.57465, -0.45691, -0.207231, 0.577525, 0.383161, 0.779462, 0.43675, -0.322722, 0.899672, -0.605107, -0.251538, -0.402769, -0.852449, 0.602925, 0.209488, -0.170528, -0.491783, -0.266771, -0.946184, -0.347622, -0.165897, -0.394488, -0.496513, 0.261219, -0.900065, -0.430779, -0.779167, -0.089611, -0.010344, 0.381565, 0.888566, -0.799082, -0.282598, -0.993037, 0.171011, 0.591692, -0.474342, -0.184681, 0.403464, -0.61967, -0.178805, 0.435739, -0.719391, -0.722968, 0.462124, -0.268135, -0.63873, -0.061148, 0.014527, -0.605344, -0.178504, -0.863282, -0.033531, -0.1711, -0.729127, 0.002226, 0.474697, 0.376, 0.234174, -0.900878, 0.779224, 0.188183], \"shape\": [16, 16, 2]}, \"weights\": [{\"data\": [-0.742023, -0.077688, -0.167692, 0.205448, -0.633864, -0.164175, -0.731823, 0.313236, 0.613465, -0.723716, -0.299231, 0.229032, 0.102561, 0.384949, -0.90948, -0.294898, -0.916217, -0.699031, -0.323329, -0.673445, 0.521949, -0.306796, -0.476018, -0.628623, 0.808028, -0.585043, -0.307429, -0.234868, -0.897584, 0.741743, 0.320785, 0.709132, -0.978084, 0.601894, -0.228816, -0.069558, -0.522066, -0.399597, -0.916222, 0.161549, -0.211915, 0.823372, -0.6549, -0.30403, 0.677588, -0.431259, 0.219659, -0.091937, -0.101636, -0.595218, -0.815428, 0.502932, 0.775249, 0.624226, 0.622601, -0.091075, 0.763603, 0.472659, 0.621131, -0.504549, -0.270214, 0.492749, 0.643055, -0.290058, -0.752162, 0.758918, 0.011832, -0.183967, 0.768298, 0.764241, 0.906398, 0.872853, -0.292238, 0.16788, -0.447741, 0.679196, 0.566614, 0.867549, -0.011606, -0.252108, 0.165669, -0.509362, 0.620632, -0.32465, -0.071143, -0.823613, 0.331067, -0.016903, -0.76138, -0.491146], \"shape\": [3, 3, 2, 5]}, {\"data\": [0.195612, -0.128132, -0.96626, 0.193375, 0.789956], \"shape\": [5]}, {\"data\": [-0.922097, 0.712992, 0.493001, 0.727856, 0.119969, -0.839034, -0.536727, -0.515472, 0.231, 0.214218, -0.791636, -0.148304, 0.309846, 0.742779, -0.123022, 0.427583, -0.882276, 0.818571, 0.043634, 0.454859, -0.007311, -0.744895, -0.368229, 0.324805, -0.388758, -0.556215, -0.542859, 0.685655, 0.350785, -0.312753, 0.591401, 0.95999, 0.136369, -0.58844, -0.506667, -0.208736, 0.548969, 0.653173, 0.128943, 0.180094, -0.16098, 0.208798, 0.666245, 0.347307, -0.384733, -0.88354, -0.328468, -0.515324, 0.479247, -0.360647, 0.09069, -0.221424, 0.091284, 0.202631, 0.208087, 0.582248, -0.164064, -0.925036, -0.678806, -0.212846, 0.960861, 0.536089, -0.038634, -0.473456, -0.409408, 0.620315, -0.873085, -0.695405, -0.024465, 0.762843, -0.928228, 0.557106, -0.65499, -0.918356, 0.815491, 0.996431, 0.115769, -0.751652, 0.075229, 0.969983, -0.80409, -0.080661, -0.644088, 0.160702, -0.486518, -0.09818, -0.191651, -0.961566, -0.238209, 0.260427, 0.085307, -0.664437, 0.458517, -0.824692, 0.312768, -0.253698, 0.761718, 0.551215, 0.566009, -0.85706, 0.687904, -0.283819, 0.5816, 0.820087, -0.028474, 0.588153, -0.221145, 0.049173, 0.529328, -0.359074, -0.463161, 0.493967, -0.852793, -0.552675, -0.695748, -0.178157, 0.477995, 0.858725, 0.120384, -0.515209, 0.204484, -0.025025, -0.654961, 0.239585, -0.654691, -0.651696, -0.699951, -0.054626, -0.232999, 0.464974, 0.285499, -0.311165, 0.18009, -0.100505, 0.303943, 0.265535, -0.960747, -0.542418, 0.195178, -0.848394, 0.0774, 0.250615, -0.690541, -0.106589, -0.587335, 0.52418, -0.750735, 0.906333, -0.185252, 0.091099, -0.516456, -0.314899, -0.398607, 0.555608, 0.741523, -0.454881, 0.5701, 0.205032, -0.772784, 0.733803, -0.669988, -0.872516, -0.124316, -0.664428, -0.363449, -0.511484, -0.192889, -0.91777, 0.017015, 0.158025, -0.407377, 0.62727, -0.121838, -0.930295, -0.139409, 0.758526, 0.711386, -0.371721, 0.833163, 0.179111], \"shape\": [3, 3, 5, 4]}, {\"data\": [0.318429, -0.858397, -0.059042, 0.68597], \"shape\": [4]}, {\"data\": [0.486255, -0.547151, 0.285068, 0.764711, 0.481398, 0.442527, -0.409304, 0.051033], \"shape\": [1, 1, 4, 2]}, {\"data\": [0.0965, 0.594443], \"shape\": [2]}, {\"data\": [0.228005, 0.859479, -0.49018, 0.232871, -0.303968, -0.799141, 0.621228, 0.850429, 0.029476, -0.583346, 0.889636, -0.128896, 0.067108, -0.1059, -0.788773, -0.559347, 0.674802, 0.513275, -0.95495, -0.230976, -0.430566, 0.607782, -0.292593, -0.362274, -0.825576, 0.904458, 0.531651, 0.139053, -0.797761, 0.905804, -0.875903, 0.04377, -0.704592, 0.203555, -0.083031, 0.321316, 0.334565, 0.965166, 0.31912, 0.987618, 0.11275, 0.755438, 0.133156, -0.271605, -0.739053, 0.930942, 0.723852, -0.399546, 0.365907, 0.680404, 0.302211, 0.481088, -0.254831, -0.719056, -0.13153, 0.195489, -0.457555, -0.825431, -0.866045, -0.010333, -0.168299, 0.986557, -0.410139, 0.607414, 0.897455, -0.503628, -0.125592, -0.216501, 0.854905, 0.862831, 0.911679, 0.451035, -0.208763, -0.0935, -0.482974, -0.552539, -0.348091, -0.720601, -0.234177, -0.522557, -0.128204, 0.992609, -0.112888, -0.806388, 0.223532, -0.205692, -0.772152, 0.989159, -0.277926, -0.544355, -0.707034, -0.598198, 0.555265, -0.382095, -0.372491, 0.631353, 0.784895, -0.373885, -0.368449, 0.898173, 0.252309, 0.912245, -0.033641, -0.896843, 0.914818, -0.598634, -0.389127, 0.116656, -0.476051, -0.595, 0.076412, -0.998532, -0.469193, -0.993491, 0.503043, 0.698487, 0.538773, -0.763721, 0.048814, -0.996688, -0.13339, 0.032822, 0.777114, -0.102801, -0.866702, -0.544717, -0.870035, -0.645622, -0.235138, 0.178248, 0.593266, 0.562264, -0.042026, -0.019967, -0.330309, 0.349891, 0.858278, 0.350973, -0.639028, -0.779616, 0.548236, 0.011033, -0.678063, 0.361407, 0.625538, -0.380135, -0.531038, 0.255256, -0.552471, 0.188966], \"shape\": [5, 5, 2, 3]}, {\"data\": [0.229761, -0.670851, -0.398017], \"shape\": [3]}, {\"data\": [-0.211487, -0.648815, -0.854588, -0.616238, -0.200391, -0.163753, 0.525164, 0.04282, -0.178234, 0.074889, -0.458875, -0.133347, 0.654533, -0.456294, 0.454776, -0.799519, -0.004428, 0.160632, 0.153349, -0.585922, -0.407693, 0.794725, -0.535387, 0.408942, -0.182012, 0.741361, 0.045939, -0.156736, -0.156846, -0.357358, 0.539258, 0.948017, -0.307682, -0.715505, 0.740323, 0.616044, -0.79421, 0.478351, -0.40107, 0.597915, -0.251741, -0.56835, -0.30559, 0.943538, -0.121007, -0.5726, 0.63163, -0.4633, -0.466873, -0.269675, 0.939682, -0.088032, -0.686666, -0.763883], \"shape\": [3, 3, 3, 2]}, {\"data\": [0.311362, -0.228519], \"shape\": [2]}, {\"data\": [-0.946541, 0.585593, -0.49527, 0.594532, -0.38557, 0.124664, 0.290608, 0.016082], \"shape\": [1, 1, 2, 4]}, {\"data\": [0.114077, -0.889658, -0.472025, 0.718808], \"shape\": [4]}, {\"data\": [-0.536401, 0.404425, -0.338344, -0.818131, 0.441566, 0.867769, 0.505219, 0.689963, 0.598858, 0.268687, -0.728914, 0.878801, -0.318668, -0.305686, -0.80848, 0.195743, 0.821773, 0.716334, -0.41629, 0.169864, -0.799399, -0.27582, 0.312052, -0.021639, 0.822725, -0.417215, 0.246061, -0.188668, -0.632463, 0.781629, -0.462136, -0.881432, -0.024391, 0.94485, -0.300768, 0.615408, 0.12297, 0.540219, 0.335681, -0.355003, 0.194186, 0.922101, -0.592691, -0.345502, 0.812393, 0.922283, 0.520438, 0.878666, -0.380913, 0.41579, -0.541346, -0.72511, -0.276467, 0.539221, 0.09016, 0.344573, 0.564725, 0.392841, -0.250152, -0.200319, 0.615438, 0.658222, -0.706144, 0.066833, -0.346988, 0.490674, 0.566333, -0.210763, -0.292341, 0.583961, 0.007116, -0.958503], \"shape\": [3, 3, 4, 2]}, {\"data\": [0.255023, -0.721247], \"shape\": [2]}], \"expected\": {\"data\": [-3.226907, 2.897466, 4.614365, 3.29115, 2.999473, 6.406079, -0.957869, 13.266747, 1.091891, 3.802161, -1.217917, 8.808489, 5.691413, 2.603114, -1.765725, 10.413739, 7.91112, 7.984789, 5.843855, 11.019684, -1.760968, 11.507448, -3.58255, 24.304056, -5.537182, -0.779647, -5.423543, -0.766776, -2.797846, 8.630902, 3.297426, 30.247473], \"shape\": [4, 4, 2]}}}\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0a3ce9b220abbccf12d7f045bd915cdf92c96d
390,606
ipynb
Jupyter Notebook
DC2B_Sheng_Pei_Wang.ipynb
ShengpeiWang/Paneled_bubbles_R2D3_template
fa3e815600287d7ff68c5c651d34e6ecf93f9916
[ "MIT" ]
null
null
null
DC2B_Sheng_Pei_Wang.ipynb
ShengpeiWang/Paneled_bubbles_R2D3_template
fa3e815600287d7ff68c5c651d34e6ecf93f9916
[ "MIT" ]
null
null
null
DC2B_Sheng_Pei_Wang.ipynb
ShengpeiWang/Paneled_bubbles_R2D3_template
fa3e815600287d7ff68c5c651d34e6ecf93f9916
[ "MIT" ]
null
null
null
152.461358
102,156
0.818559
[ [ [ "# Load packages and data", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport seaborn as sns; sns.set(style=\"ticks\", color_codes=True)\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "data = pd.read_csv('breast-cancer-wisconsin.txt', sep=\",\", header=0, index_col = 0)\ndata.dtypes\n# some of the columns have bad data, since all columns contain numeric data", "_____no_output_____" ] ], [ [ "## Data cleaning", "_____no_output_____" ] ], [ [ "# check the categories present in the data\nfor column in list(data.columns[1:]):\n print(column, data[column].unique())\n# nas are represented in different ways as nan, '#', '?', and 'No idea' \n# and some entreis have class value as 20 or 40, while expected 2 or 4", "Clump Thickness [ 7 6 8 5 10 3 4 1 70 80 100 2 9 50 30 40 60]\nUniformity of Cell Size ['8' '10' '6' '5' '4' '9' '3' '1' 'No idea' '2' '7' '50' '100' '30' nan\n '#' '?' '80' '40' '60' '90' '20']\nUniformity of Cell Shape ['3' '5' '4' '6' '10' '7' '1' 'No idea' '2' '60' '100' '40' nan '#' '9'\n '8' '?' '30' '50' '70']\nMarginal Adhesion ['7' '5' '10' '3' '6' '4' '1' '2' 'No idea' '30' '40' nan '#' '8' '?' '70'\n '60' '100' '50' '9' '20']\nSingle Epithelial Cell Size ['4' '10' '3' '6' '2' '8' 'No idea' '1' '30' nan '5' '#' '?' '40' '20' '7'\n '60' '80' '100' '9']\nBare Nuclei ['5' '10' '1' '8' '2' '3' '6' 'No idea' '?' '80' '60' '30' nan '100' '#'\n '9' '50' '7' '4' '20']\nBland Chromatin ['7' '6' '3' '2' '4' 'No idea' '1' '5' '70' '30' nan '40' '#' '10' '8' '?'\n '20' '9' '60' '50']\nNormal Nucleoli ['8' '10' '5' '4' '3' '7' '2' '6' '9' '1' 'No idea' '40' '90' '20' nan\n '30' '#' '?' '80' '60' '50' '100' '70']\nMitoses ['2' '1' '7' 'No idea' '3' '10' '70' '8' nan '20' '#' '6' '?' '4' '5']\nClass ['4' '2' 'No idea' '40' nan '#' '?' '20']\n" ] ], [ [ "### Coerce all data to be numeric\nThis will make the wrong entires NAs", "_____no_output_____" ] ], [ [ "data_n = data.apply(pd.to_numeric, errors='coerce')", "_____no_output_____" ] ], [ [ "### Handel rows with values that are 10 times as large", "_____no_output_____" ] ], [ [ "dat_10 = data_n[data_n.Class > 4]\ndat_d10 = dat_10.iloc[:,1:]/10\ndat_d10.insert(0, 'ID', dat_10['ID'])\n# all values seem to be 10 times larger", "_____no_output_____" ], [ "dat = data_n[data_n.Class <= 4].append(dat_d10)", "_____no_output_____" ] ], [ [ "## Check number of unique IDs:", "_____no_output_____" ] ], [ [ "print(dat.ID.unique().shape)\n# there are only 665 unique IDs\nprint(dat.shape)\n# But there are 15776 rows of data?", "(665,)\n(15776, 11)\n" ], [ "# look at how IDs repeated:\ndat.groupby('ID').count().sort_values(by = 'Class', ascending=False).head(20).plot(y = \"Class\", kind = \"barh\")\nplt.xlabel(\"Count\")\nplt.ylabel(\"ID\")\nplt.show", "_____no_output_____" ], [ "# look at the unique rows for these super-duplicated IDs:\nid_dups = data.groupby('ID').count().sort_values(by = 'Class', ascending=False).head(15).reset_index().ID\ndata[data.ID.isin(id_dups)].drop_duplicates().sort_values('ID')\n# each ID with lots of duplicates has only one or two unique rows with valid data\n# also when there is missing value, clump thickness is the only column with full data", "_____no_output_____" ], [ "data_cleaned = dat.drop_duplicates()\nprint(data_cleaned.shape)\n\ndata_dups = data_cleaned.groupby('ID').count().\\\n sort_values(by = 'Class', ascending=False).reset_index()[['ID', 'Class']]\\\n .rename(columns={\"Class\": \"ct\"})\n\ndatac = data_cleaned.merge(data_dups, left_on='ID', right_on='ID')\n\ndatacc = datac[datac.ct == 1]\nprint(datacc.shape)\n# there are 627 samples with only one row", "(710, 11)\n(627, 12)\n" ] ], [ [ "- I am not sure whether a sample can have multiple rows\n- But having multiple data points from a sample will violate the assumption of independence\n- So I filtered the data down to the samples with only one entry", "_____no_output_____" ], [ "## Handling missing values", "_____no_output_____" ] ], [ [ "datacc[datacc.isnull().any(axis=1)]\n# not a lot of NAs, and only in the Bare Nulei column\n# will remove these", "_____no_output_____" ], [ "dataf = datacc.dropna()\ndataf.groupby('Class').count()\n# The two classes are fairly balanced", "_____no_output_____" ] ], [ [ "## Visualize the relationship between the different factors and cancer class:", "_____no_output_____" ] ], [ [ "# Transform data into the long format for vis\ndat_long_for_vis = pd.melt(dataf.iloc[:, 1:11], id_vars=['Class'])\n\n# Make histograms faceted by class\nbins = np.linspace(0, 9, 10)\ng = sns.FacetGrid(dat_long_for_vis, row = \"variable\", col=\"Class\", margin_titles=True, sharey= False)\ng.map(plt.hist, \"value\", color=\"steelblue\", bins = bins)\n\n# All of the features have some importance", "_____no_output_____" ], [ "corr = dataf.iloc[:, 1:11].corr()\ncorr", "_____no_output_____" ] ], [ [ "## Check correlations between features:", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(8,8))\n\ncorr = dataf.iloc[:, 1:11].corr()\n\nmask = np.triu(np.ones_like(corr))\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr, mask = mask, cmap='Blues', annot=True, fmt='.2f', center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n\n# The correlations aren't super high", "_____no_output_____" ] ], [ [ "# Compare feature importance using modeling", "_____no_output_____" ] ], [ [ "# import libraries\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nlogi = LogisticRegression()\nlogib = LogisticRegression(class_weight='balanced')\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import roc_curve", "_____no_output_____" ], [ "X = dataf.iloc[:, 1:10]\ny = dataf['Class']/2 -1\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=55, stratify = y)", "_____no_output_____" ], [ "cross_validate(logi, X_train, y_train, cv=5, scoring = 'recall_weighted')", "_____no_output_____" ], [ "scores = cross_validate(logib, X_train, y_train, cv=5, scoring = 'recall_weighted')\nprint(scores)\nprint(scores['test_score'].mean())\n# balanced weight is better", "{'fit_time': array([0.03479075, 0.0444684 , 0.02959847, 0.0309279 , 0.03213739]), 'score_time': array([0.00870395, 0.00566697, 0.00517964, 0.00572872, 0.00926089]), 'test_score': array([0.97560976, 0.97560976, 0.97560976, 0.93902439, 1. ])}\n0.9731707317073169\n" ], [ "model = logib.fit(X_train, y_train)\ny_pred = model.predict(X_test)", "_____no_output_____" ], [ "# ROC curve:\nfrom sklearn import metrics\n\nfpr, tpr, thresholds = roc_curve(y_test, y_pred)\nroc_auc = metrics.auc(fpr, tpr)\ndisplay = metrics.RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc, estimator_name='example estimator')\ndisplay.plot() \nplt.show() ", "_____no_output_____" ] ], [ [ "## Look at feature importance\nUsing coefficients from the logistic regression model", "_____no_output_____" ] ], [ [ "features = pd.DataFrame(data = {'feature': list(X.columns), 'importance': model.coef_.tolist()[0]})\\\n .sort_values(by = 'importance')\nfeatures", "_____no_output_____" ] ], [ [ "## Look at alternative feature importance\nSince collecting these data could be expensive, can we collect less data?\nWhat if we only collect one type of the data?", "_____no_output_____" ] ], [ [ "# Function to test feature importance using just that feature\ndef feature_test(name):\n scores = cross_validate(logib, X_train[name][:, np.newaxis], y_train, cv=5, scoring = 'recall_weighted')\n return(scores['test_score'].mean())", "_____no_output_____" ], [ "s = []\nfor name in list(X.columns):\n s.append([name, feature_test(name)])", "_____no_output_____" ], [ "features2 = features.merge(pd.DataFrame(s, columns = [\"feature\", \"single_importance\"]), \n left_on='feature', right_on='feature')\n\nsns.barplot(x=\"importance\", y=\"feature\", data=features2,\n color=\"b\")\nplt.title(\"Feature importance for full model\")", "_____no_output_____" ], [ "sns.set_color_codes(\"muted\")\nsns.barplot(x=\"single_importance\", y=\"feature\", data=features2,\n color=\"dodgerblue\")\nplt.title(\"Recall for models with a single feature\")", "_____no_output_____" ] ], [ [ "## Feature selection using recursive elimination", "_____no_output_____" ] ], [ [ "from sklearn.feature_selection import RFECV\nselector = RFECV(logib, step=1, cv=5, scoring = 'recall_weighted')\nselector.fit(X_train, y_train)\nselector.ranking_", "_____no_output_____" ], [ "reduced_features = [x for x, y in zip(list(X_train.columns),list(selector.ranking_)) if y == 1]\n\nscores = cross_validate(logib, X_train[reduced_features], y_train, cv=5, scoring = 'recall_weighted')\nprint(scores['test_score'].mean())", "0.9707317073170731\n" ], [ "model_r = logib.fit(X_train[reduced_features], y_train)\n\nr_features = pd.DataFrame(data = {'feature': reduced_features, 'importance_r': model_r.coef_.tolist()[0]})\\\n .sort_values(by = 'importance_r')\n\nsns.barplot(x=\"importance_r\", y=\"feature\", data=r_features,\n color=\"b\")\nplt.title(\"Feature importance for reduced model\")", "_____no_output_____" ] ], [ [ "## Exporting all feature importance measures for bubble charts", "_____no_output_____" ] ], [ [ "features_all = features2.merge(r_features, how = 'outer',\n left_on='feature', right_on='feature')\nfeatures_all.to_csv(\"feature_importance.csv\")", "_____no_output_____" ] ], [ [ "# Conclusion\n\nThe three most importance features that predict the cancer status of a sample are: \n- the number of Bare Nuclei\n- the Uniformaty of cell size\n- Mitoses\n\nIf data is available on all nine features, the logistic regression model has a 97% recall.\n\nHowever, if resources is extremely limited, uniformity of cell size is the most informative feature on its own.", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb0a44cdc6e81398801c9a4133846b1941e45c67
55,317
ipynb
Jupyter Notebook
Gaussian Mixture Model Assignment/Gaussian Mixture Model.ipynb
tusharsaxena250/AIML_Course
a4c90462be7fa07a31e001e9506d43caf133742d
[ "MIT" ]
null
null
null
Gaussian Mixture Model Assignment/Gaussian Mixture Model.ipynb
tusharsaxena250/AIML_Course
a4c90462be7fa07a31e001e9506d43caf133742d
[ "MIT" ]
null
null
null
Gaussian Mixture Model Assignment/Gaussian Mixture Model.ipynb
tusharsaxena250/AIML_Course
a4c90462be7fa07a31e001e9506d43caf133742d
[ "MIT" ]
null
null
null
208.743396
32,356
0.922664
[ [ [ "## Imports", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt \nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.datasets import make_blobs", "_____no_output_____" ] ], [ [ "## Dataset", "_____no_output_____" ] ], [ [ "data = pd.read_csv('Clustering_gmm.csv')\nplt.figure(figsize=(7,7))\nplt.scatter(data[\"Weight\"],data[\"Height\"])\nplt.xlabel('Weight')\nplt.ylabel('Height')\nplt.title('Data Distribution')\nplt.show()", "_____no_output_____" ], [ "kmeans = KMeans(n_clusters=4)\nkmeans.fit(data)", "_____no_output_____" ], [ "pred = kmeans.predict(data)\nframe = pd.DataFrame(data)\nframe['cluster'] = pred\nframe.columns = ['Weight', 'Height', 'cluster']", "_____no_output_____" ], [ "color=['blue','green','cyan', 'black']\nfor k in range(0,4):\n data = frame[frame[\"cluster\"]==k]\n plt.scatter(data[\"Weight\"],data[\"Height\"],c=color[k])\nplt.show()", "_____no_output_____" ] ], [ [ "## GMM", "_____no_output_____" ] ], [ [ "data = pd.read_csv('Clustering_gmm.csv')", "_____no_output_____" ], [ "gmm = GaussianMixture(n_components=4)\ngmm.fit(data)", "_____no_output_____" ], [ "labels = gmm.predict(data)\nframe = pd.DataFrame(data)\nframe['cluster'] = labels\nframe.columns = ['Weight', 'Height', 'cluster']", "_____no_output_____" ], [ "color=['blue','green','cyan', 'black']\nfor k in range(0,4):\n data = frame[frame[\"cluster\"]==k]\n plt.scatter(data[\"Weight\"],data[\"Height\"],c=color[k])\nplt.show()", "_____no_output_____" ] ], [ [ "## Blobs and GMM", "_____no_output_____" ] ], [ [ "X, y = make_blobs(n_samples=10000, n_features=2, centers=4, random_state=2)", "_____no_output_____" ], [ "plt.figure(figsize=(7,7))\nplt.scatter(X[:, 0],X[:, 1])\nplt.xlabel('Weight')\nplt.ylabel('Height')\nplt.title('Data Distribution')\nplt.show()", "_____no_output_____" ], [ "gmm = GaussianMixture(n_components=4)\ngmm.fit(X, y)", "_____no_output_____" ], [ "labels = gmm.predict(X)\nframe = pd.DataFrame(X, y)\nframe['cluster'] = labels\nframe.columns = ['Weight', 'Height', 'cluster']", "_____no_output_____" ], [ "color=['blue','green','cyan', 'black']\nfor k in range(0,4):\n d = frame[frame[\"cluster\"]==k]\n plt.scatter(d['Weight'],d['Height'] ,c=color[k])\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb0a477a1444cf6b07f4f3d09e843828a17fc567
345,346
ipynb
Jupyter Notebook
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
b574b7e55c3d737e477f47316812d1d227763b7e
[ "Apache-2.0" ]
null
null
null
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
b574b7e55c3d737e477f47316812d1d227763b7e
[ "Apache-2.0" ]
null
null
null
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
b574b7e55c3d737e477f47316812d1d227763b7e
[ "Apache-2.0" ]
1
2022-02-23T02:43:58.000Z
2022-02-23T02:43:58.000Z
43.05523
3,971
0.502977
[ [ [ "# Deutsch-Jozsa Algorithm", "_____no_output_____" ], [ "In this section, we first introduce the Deutsch-Jozsa problem, and classical and quantum algorithms to solve it. We then implement the quantum algorithm using Qiskit, and run it on a simulator and device.", "_____no_output_____" ], [ "## Contents\n\n1. [Introduction](#introduction) \n 1.1 [Deutsch-Jozsa Problem](#djproblem) \n 1.2 [Deutsch-Jozsa Algorithm](#classical-solution) \n 1.3 [The Quantum Solution](#quantum-solution) \n 1.4 [Why Does This Work?](#why-does-this-work) \n2. [Worked Example](#example)\n3. [Creating Quantum Oracles](#creating-quantum-oracles) \n4. [Qiskit Implementation](#implementation) \n 4.1 [Constant Oracle](#const_oracle) \n 4.2 [Balanced Oracle](#balanced_oracle) \n 4.3 [The Full Algorithm](#full_alg) \n 4.4 [Generalised Circuit](#general_circs) \n5. [Running on Real Devices](#device) \n6. [Problems](#problems)\n7. [References](#references)", "_____no_output_____" ], [ "## 1. Introduction <a id='introduction'></a>", "_____no_output_____" ], [ "The Deutsch-Jozsa algorithm, first introduced in Reference [1], was the first example of a quantum algorithm that performs better than the best classical algorithm. It showed that there can be advantages to using a quantum computer as a computational tool for a specific problem.", "_____no_output_____" ], [ "### 1.1 Deutsch-Jozsa Problem <a id='djproblem'> </a>\n\nWe are given a hidden Boolean function $f$, which takes as input a string of bits, and returns either $0$ or $1$, that is:\n\n$$\nf(\\{x_0,x_1,x_2,...\\}) \\rightarrow 0 \\textrm{ or } 1 \\textrm{ , where } x_n \\textrm{ is } 0 \\textrm{ or } 1$$\n\nThe property of the given Boolean function is that it is guaranteed to either be balanced or constant. A constant function returns all $0$'s or all $1$'s for any input, while a balanced function returns $0$'s for exactly half of all inputs and $1$'s for the other half. Our task is to determine whether the given function is balanced or constant. \n\nNote that the Deutsch-Jozsa problem is an $n$-bit extension of the single bit Deutsch problem. \n\n### 1.2 The Classical Solution <a id='classical-solution'> </a>\n\nClassically, in the best case, two queries to the oracle can determine if the hidden Boolean function, $f(x)$, is balanced: \ne.g. if we get both $f(0,0,0,...)\\rightarrow 0$ and $f(1,0,0,...) \\rightarrow 1$, then we know the function is balanced as we have obtained the two different outputs. \n\nIn the worst case, if we continue to see the same output for each input we try, we will have to check exactly half of all possible inputs plus one in order to be certain that $f(x)$ is constant. Since the total number of possible inputs is $2^n$, this implies that we need $2^{n-1}+1$ trial inputs to be certain that $f(x)$ is constant in the worst case. For example, for a $4$-bit string, if we checked $8$ out of the $16$ possible combinations, getting all $0$'s, it is still possible that the $9^\\textrm{th}$ input returns a $1$ and $f(x)$ is balanced. Probabilistically, this is a very unlikely event. In fact, if we get the same result continually in succession, we can express the probability that the function is constant as a function of $k$ inputs as:\n\n\n\n$$ P_\\textrm{constant}(k) = 1 - \\frac{1}{2^{k-1}} \\qquad \\textrm{for } k \\leq 2^{n-1}$$\n\n\n\nRealistically, we could opt to truncate our classical algorithm early, say if we were over x% confident. But if we want to be 100% confident, we would need to check $2^{n-1}+1$ inputs.", "_____no_output_____" ], [ "### 1.3 Quantum Solution <a id='quantum-solution'> </a>\n\nUsing a quantum computer, we can solve this problem with 100% confidence after only one call to the function $f(x)$, provided we have the function $f$ implemented as a quantum oracle, which maps the state $\\vert x\\rangle \\vert y\\rangle $ to $ \\vert x\\rangle \\vert y \\oplus f(x)\\rangle$, where $\\oplus$ is addition modulo $2$. Below is the generic circuit for the Deutsh-Jozsa algorithm.\n\n![image1](images/deutsch_steps.png)\n\nNow, let's go through the steps of the algorithm:\n\n<ol>\n <li>\n Prepare two quantum registers. The first is an $n$-qubit register initialised to $|0\\rangle$, and the second is a one-qubit register initialised to $|1\\rangle$:\n \n\n$$\\vert \\psi_0 \\rangle = \\vert0\\rangle^{\\otimes n} \\vert 1\\rangle$$\n\n\n </li>\n \n <li>\n Apply a Hadamard gate to each qubit:\n \n\n$$\\vert \\psi_1 \\rangle = \\frac{1}{\\sqrt{2^{n+1}}}\\sum_{x=0}^{2^n-1} \\vert x\\rangle \\left(|0\\rangle - |1 \\rangle \\right)$$\n\n\n </li>\n \n <li>\n Apply the quantum oracle $\\vert x\\rangle \\vert y\\rangle$ to $\\vert x\\rangle \\vert y \\oplus f(x)\\rangle$:\n $$\n \\begin{aligned}\n \\lvert \\psi_2 \\rangle \n & = \\frac{1}{\\sqrt{2^{n+1}}}\\sum_{x=0}^{2^n-1} \\vert x\\rangle (\\vert f(x)\\rangle - \\vert 1 \\oplus f(x)\\rangle) \\\\ \n & = \\frac{1}{\\sqrt{2^{n+1}}}\\sum_{x=0}^{2^n-1}(-1)^{f(x)}|x\\rangle ( |0\\rangle - |1\\rangle ) \n \\end{aligned}\n $$\n \nsince for each $x,f(x)$ is either $0$ or $1$.\n </li>\n\n <li>\n At this point the second single qubit register may be ignored. Apply a Hadamard gate to each qubit in the first register:\n $$\n \\begin{aligned}\n \\lvert \\psi_3 \\rangle \n & = \\frac{1}{2^n}\\sum_{x=0}^{2^n-1}(-1)^{f(x)}\n \\left[ \\sum_{y=0}^{2^n-1}(-1)^{x \\cdot y} \n \\vert y \\rangle \\right] \\\\\n & = \\frac{1}{2^n}\\sum_{y=0}^{2^n-1}\n \\left[ \\sum_{x=0}^{2^n-1}(-1)^{f(x)}(-1)^{x \\cdot y} \\right]\n \\vert y \\rangle\n \\end{aligned}\n $$\n \nwhere $x \\cdot y = x_0y_0 \\oplus x_1y_1 \\oplus \\ldots \\oplus x_{n-1}y_{n-1}$ is the sum of the bitwise product.\n </li>\n\n <li>\n Measure the first register. Notice that the probability of measuring $\\vert 0 \\rangle ^{\\otimes n} = \\lvert \\frac{1}{2^n}\\sum_{x=0}^{2^n-1}(-1)^{f(x)} \\rvert^2$, which evaluates to $1$ if $f(x)$ is constant and $0$ if $f(x)$ is balanced. \n </li>\n\n</ol>\n\n### 1.4 Why Does This Work? <a id='why-does-this-work'> </a>\n\n- **Constant Oracle**\n\nWhen the oracle is *constant*, it has no effect (up to a global phase) on the input qubits, and the quantum states before and after querying the oracle are the same. Since the H-gate is its own inverse, in Step 4 we reverse Step 2 to obtain the initial quantum state of $|00\\dots 0\\rangle$ in the first register.\n\n$$\nH^{\\otimes n}\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ \\vdots \\\\ 0 \\end{bmatrix} \n= \n\\tfrac{1}{\\sqrt{2^n}}\\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ \\vdots \\\\ 1 \\end{bmatrix}\n\\quad \\xrightarrow{\\text{after } U_f} \\quad\nH^{\\otimes n}\\tfrac{1}{\\sqrt{2^n}}\\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ \\vdots \\\\ 1 \\end{bmatrix}\n= \n\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ \\vdots \\\\ 0 \\end{bmatrix} \n$$\n\n- **Balanced Oracle**\n\nAfter step 2, our input register is an equal superposition of all the states in the computational basis. When the oracle is *balanced*, phase kickback adds a negative phase to exactly half these states:\n\n$$\nU_f \\tfrac{1}{\\sqrt{2^n}}\\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ \\vdots \\\\ 1 \\end{bmatrix} \n= \n\\tfrac{1}{\\sqrt{2^n}}\\begin{bmatrix} -1 \\\\ 1 \\\\ -1 \\\\ \\vdots \\\\ 1 \\end{bmatrix}\n$$\n\n\nThe quantum state after querying the oracle is orthogonal to the quantum state before querying the oracle. Thus, in Step 4, when applying the H-gates, we must end up with a quantum state that is orthogonal to $|00\\dots 0\\rangle$. This means we should never measure the all-zero state. \n", "_____no_output_____" ], [ "## 2. Worked Example <a id='example'></a>\n\nLet's go through a specfic example for a two bit balanced function, where we apply X-gates before both CNOTs.\n\n<ol>\n <li> The first register of two qubits is initialized to $|00\\rangle$ and the second register qubit to $|1\\rangle$ \n \n\n$$\\lvert \\psi_0 \\rangle = \\lvert 0 0 \\rangle_1 \\lvert 1 \\rangle_2 $$\n\n \n </li>\n \n <li> Apply Hadamard on all qubits\n \n\n$$\\lvert \\psi_1 \\rangle = \\frac{1}{2} \\left( \\lvert 0 0 \\rangle_1 + \\lvert 0 1 \\rangle_1 + \\lvert 1 0 \\rangle_1 + \\lvert 1 1 \\rangle_1 \\right) \\frac{1}{\\sqrt{2}} \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right) $$\n\n \n </li>\n \n <li> The oracle function can be implemented as $\\text{Q}_f = CX_{1a}CX_{2a}$, \n $$\n \\begin{align*}\n \\lvert \\psi_2 \\rangle = \\frac{1}{2\\sqrt{2}} \\left[ \\lvert 0 0 \\rangle_1 \\left( \\lvert 0 \\oplus 0 \\oplus 0 \\rangle_2 - \\lvert 1 \\oplus 0 \\oplus 0 \\rangle_2 \\right) \\\\\n + \\lvert 0 1 \\rangle_1 \\left( \\lvert 0 \\oplus 0 \\oplus 1 \\rangle_2 - \\lvert 1 \\oplus 0 \\oplus 1 \\rangle_2 \\right) \\\\\n + \\lvert 1 0 \\rangle_1 \\left( \\lvert 0 \\oplus 1 \\oplus 0 \\rangle_2 - \\lvert 1 \\oplus 1 \\oplus 0 \\rangle_2 \\right) \\\\\n + \\lvert 1 1 \\rangle_1 \\left( \\lvert 0 \\oplus 1 \\oplus 1 \\rangle_2 - \\lvert 1 \\oplus 1 \\oplus 1 \\rangle_2 \\right) \\right]\n \\end{align*}\n $$\n </li>\n \n <li>Thus\n $$\n \\begin{aligned}\n \\lvert \\psi_2 \\rangle & = \\frac{1}{2\\sqrt{2}} \\left[ \\lvert 0 0 \\rangle_1 \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right) - \\lvert 0 1 \\rangle_1 \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right) - \\lvert 1 0 \\rangle_1 \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right) + \\lvert 1 1 \\rangle_1 \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right) \\right] \\\\\n & = \\frac{1}{2} \\left( \\lvert 0 0 \\rangle_1 - \\lvert 0 1 \\rangle_1 - \\lvert 1 0 \\rangle_1 + \\lvert 1 1 \\rangle_1 \\right) \\frac{1}{\\sqrt{2}} \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right) \\\\\n & = \\frac{1}{\\sqrt{2}} \\left( \\lvert 0 \\rangle_{10} - \\lvert 1 \\rangle_{10} \\right)\\frac{1}{\\sqrt{2}} \\left( \\lvert 0 \\rangle_{11} - \\lvert 1 \\rangle_{11} \\right)\\frac{1}{\\sqrt{2}} \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right)\n \\end{aligned}\n $$\n </li>\n \n <li> Apply Hadamard on the first register\n \n\n$$ \\lvert \\psi_3\\rangle = \\lvert 1 \\rangle_{10} \\lvert 1 \\rangle_{11} \\left( \\lvert 0 \\rangle_2 - \\lvert 1 \\rangle_2 \\right) $$\n\n\n </li>\n \n <li> Measuring the first two qubits will give the non-zero $11$, indicating a balanced function.\n </li>\n</ol>\n\nYou can try out similar examples using the widget below. Press the buttons to add H-gates and oracles, re-run the cell and/or set `case=\"constant\"` to try out different oracles.", "_____no_output_____" ] ], [ [ "from qiskit_textbook.widgets import dj_widget\ndj_widget(size=\"small\", case=\"balanced\")", "_____no_output_____" ] ], [ [ "## 3. Creating Quantum Oracles <a id='creating-quantum-oracles'> </a>\n\nLet's see some different ways we can create a quantum oracle. \n\nFor a constant function, it is simple:\n\n$\\qquad$ 1. if f(x) = 0, then apply the $I$ gate to the qubit in register 2. \n$\\qquad$ 2. if f(x) = 1, then apply the $X$ gate to the qubit in register 2.\n\nFor a balanced function, there are many different circuits we can create. One of the ways we can guarantee our circuit is balanced is by performing a CNOT for each qubit in register 1, with the qubit in register 2 as the target. For example:\n\n![image2](images/deutsch_balanced1.svg)\n\nIn the image above, the top three qubits form the input register, and the bottom qubit is the output register. We can see which states give which output in the table below:\n\n| States that output 0 | States that output 1 |\n|:--------------------:|:--------------------:|\n| 000 | 001 |\n| 011 | 100 |\n| 101 | 010 |\n| 110 | 111 |\n\n\nWe can change the results while keeping them balanced by wrapping selected controls in X-gates. For example, see the circuit and its results table below:\n\n![other_balanced_circuit](images/deutsch_balanced2.svg)\n\n| States that output 0 | States that output 1 |\n|:--------------------:|:--------------------:|\n| 001 | 000 |\n| 010 | 011 |\n| 100 | 101 |\n| 111 | 110 |", "_____no_output_____" ], [ "## 4. Qiskit Implementation <a id='implementation'></a>\n\nWe now implement the Deutsch-Jozsa algorithm for the example of a three-bit function, with both constant and balanced oracles. First let's do our imports:", "_____no_output_____" ] ], [ [ "# initialization\nimport numpy as np\n\n# importing Qiskit\nfrom qiskit import IBMQ, BasicAer\nfrom qiskit.providers.ibmq import least_busy\nfrom qiskit import QuantumCircuit, execute\n\n# import basic plot tools\nfrom qiskit.visualization import plot_histogram", "_____no_output_____" ] ], [ [ "Next, we set the size of the input register for our oracle:", "_____no_output_____" ] ], [ [ "# set the length of the n-bit input string. \nn = 3", "_____no_output_____" ] ], [ [ "### 4.1 Constant Oracle <a id='const_oracle'></a>\nLet's start by creating a constant oracle, in this case the input has no effect on the ouput so we just randomly set the output qubit to be 0 or 1:", "_____no_output_____" ] ], [ [ "# set the length of the n-bit input string. \nn = 3\n\nconst_oracle = QuantumCircuit(n+1)\n\noutput = np.random.randint(2)\nif output == 1:\n const_oracle.x(n)\n\nconst_oracle.draw()", "_____no_output_____" ] ], [ [ "### 4.2 Balanced Oracle <a id='balanced_oracle'></a>", "_____no_output_____" ] ], [ [ "balanced_oracle = QuantumCircuit(n+1)", "_____no_output_____" ] ], [ [ "Next, we create a balanced oracle. As we saw in section 1b, we can create a balanced oracle by performing CNOTs with each input qubit as a control and the output bit as the target. We can vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. Let's first choose a binary string of length `n` that dictates which controls to wrap:", "_____no_output_____" ] ], [ [ "b_str = \"101\"", "_____no_output_____" ] ], [ [ "Now we have this string, we can use it as a key to place our X-gates. For each qubit in our circuit, we place an X-gate if the corresponding digit in `b_str` is `1`, or do nothing if the digit is `0`.", "_____no_output_____" ] ], [ [ "balanced_oracle = QuantumCircuit(n+1)\nb_str = \"101\"\n\n# Place X-gates\nfor qubit in range(len(b_str)):\n if b_str[qubit] == '1':\n balanced_oracle.x(qubit)\nbalanced_oracle.draw()", "_____no_output_____" ] ], [ [ "Next, we do our controlled-NOT gates, using each input qubit as a control, and the output qubit as a target:", "_____no_output_____" ] ], [ [ "balanced_oracle = QuantumCircuit(n+1)\nb_str = \"101\"\n\n# Place X-gates\nfor qubit in range(len(b_str)):\n if b_str[qubit] == '1':\n balanced_oracle.x(qubit)\n\n# Use barrier as divider\nbalanced_oracle.barrier()\n\n# Controlled-NOT gates\nfor qubit in range(n):\n balanced_oracle.cx(qubit, n)\n\nbalanced_oracle.barrier()\nbalanced_oracle.draw()", "_____no_output_____" ] ], [ [ "Finally, we repeat the code from two cells up to finish wrapping the controls in X-gates:", "_____no_output_____" ] ], [ [ "balanced_oracle = QuantumCircuit(n+1)\nb_str = \"101\"\n\n# Place X-gates\nfor qubit in range(len(b_str)):\n if b_str[qubit] == '1':\n balanced_oracle.x(qubit)\n\n# Use barrier as divider\nbalanced_oracle.barrier()\n\n# Controlled-NOT gates\nfor qubit in range(n):\n balanced_oracle.cx(qubit, n)\n\nbalanced_oracle.barrier()\n\n# Place X-gates\nfor qubit in range(len(b_str)):\n if b_str[qubit] == '1':\n balanced_oracle.x(qubit)\n\n# Show oracle\nbalanced_oracle.draw()", "_____no_output_____" ] ], [ [ "We have just created a balanced oracle! All that's left to do is see if the Deutsch-Joza algorithm can solve it.\n\n### 4.3 The Full Algorithm <a id='full_alg'></a>\n\nLet's now put everything together. This first step in the algorithm is to initialise the input qubits in the state $|{+}\\rangle$ and the output qubit in the state $|{-}\\rangle$:", "_____no_output_____" ] ], [ [ "dj_circuit = QuantumCircuit(n+1, n)\n\n# Apply H-gates\nfor qubit in range(n):\n dj_circuit.h(qubit)\n\n# Put qubit in state |->\ndj_circuit.x(n)\ndj_circuit.h(n)\ndj_circuit.draw()", "_____no_output_____" ] ], [ [ "Next, let's apply the oracle. Here we apply the `balanced_oracle` we created above:", "_____no_output_____" ] ], [ [ "dj_circuit = QuantumCircuit(n+1, n)\n\n# Apply H-gates\nfor qubit in range(n):\n dj_circuit.h(qubit)\n\n# Put qubit in state |->\ndj_circuit.x(n)\ndj_circuit.h(n)\n\n# Add oracle\ndj_circuit += balanced_oracle\ndj_circuit.draw()", "_____no_output_____" ] ], [ [ "Finally, we perform H-gates on the $n$-input qubits, and measure our input register:", "_____no_output_____" ] ], [ [ "dj_circuit = QuantumCircuit(n+1, n)\n\n# Apply H-gates\nfor qubit in range(n):\n dj_circuit.h(qubit)\n\n# Put qubit in state |->\ndj_circuit.x(n)\ndj_circuit.h(n)\n\n# Add oracle\ndj_circuit += balanced_oracle\n\n# Repeat H-gates\nfor qubit in range(n):\n dj_circuit.h(qubit)\ndj_circuit.barrier()\n\n# Measure\nfor i in range(n):\n dj_circuit.measure(i, i)\n\n# Display circuit\ndj_circuit.draw()", "_____no_output_____" ] ], [ [ "Let's see the output:", "_____no_output_____" ] ], [ [ "# use local simulator\nbackend = BasicAer.get_backend('qasm_simulator')\nshots = 1024\nresults = execute(dj_circuit, backend=backend, shots=shots).result()\nanswer = results.get_counts()\n\nplot_histogram(answer)", "_____no_output_____" ] ], [ [ "We can see from the results above that we have a 0% chance of measuring `000`. This correctly predicts the function is balanced. \n\n### 4.4 Generalised Circuits <a id='general_circs'></a>\n\nBelow, we provide a generalised function that creates Deutsch-Joza oracles and turns them into quantum gates. It takes the `case`, (either `'balanced'` or '`constant`', and `n`, the size of the input register:", "_____no_output_____" ] ], [ [ "def dj_oracle(case, n):\n # We need to make a QuantumCircuit object to return\n # This circuit has n+1 qubits: the size of the input,\n # plus one output qubit\n oracle_qc = QuantumCircuit(n+1)\n \n # First, let's deal with the case in which oracle is balanced\n if case == \"balanced\":\n # First generate a random number that tells us which CNOTs to\n # wrap in X-gates:\n b = np.random.randint(1,2**n)\n # Next, format 'b' as a binary string of length 'n', padded with zeros:\n b_str = format(b, '0'+str(n)+'b')\n # Next, we place the first X-gates. Each digit in our binary string \n # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1\n # we apply an X-gate to that qubit:\n for qubit in range(len(b_str)):\n if b_str[qubit] == '1':\n oracle_qc.x(qubit)\n # Do the controlled-NOT gates for each qubit, using the output qubit \n # as the target:\n for qubit in range(n):\n oracle_qc.cx(qubit, n)\n # Next, place the final X-gates\n for qubit in range(len(b_str)):\n if b_str[qubit] == '1':\n oracle_qc.x(qubit)\n\n # Case in which oracle is constant\n if case == \"constant\":\n # First decide what the fixed output of the oracle will be\n # (either always 0 or always 1)\n output = np.random.randint(2)\n if output == 1:\n oracle_qc.x(n)\n \n oracle_gate = oracle_qc.to_gate()\n oracle_gate.name = \"Oracle\" # To show when we display the circuit\n return oracle_gate", "_____no_output_____" ] ], [ [ "Let's also create a function that takes this oracle gate and performs the Deutsch-Joza algorithm on it:", "_____no_output_____" ] ], [ [ "def dj_algorithm(oracle, n):\n dj_circuit = QuantumCircuit(n+1, n)\n # Set up the output qubit:\n dj_circuit.x(n)\n dj_circuit.h(n)\n # And set up the input register:\n for qubit in range(n):\n dj_circuit.h(qubit)\n # Let's append the oracle gate to our circuit:\n dj_circuit.append(oracle, range(n+1))\n # Finally, perform the H-gates again and measure:\n for qubit in range(n):\n dj_circuit.h(qubit)\n \n for i in range(n):\n dj_circuit.measure(i, i)\n \n return dj_circuit", "_____no_output_____" ] ], [ [ "Finally, let's use these functions to play around with the algorithm:", "_____no_output_____" ] ], [ [ "n = 4\noracle_gate = dj_oracle('balanced', n)\ndj_circuit = dj_algorithm(oracle_gate, n)\ndj_circuit.draw()", "_____no_output_____" ] ], [ [ "And see the results of running this circuit:", "_____no_output_____" ] ], [ [ "results = execute(dj_circuit, backend=backend, shots=1024).result()\nanswer = results.get_counts()\nplot_histogram(answer)", "_____no_output_____" ] ], [ [ "## 5. Experiment with Real Devices <a id='device'></a>\n\nWe can run the circuit on the real device as shown below. We first look for the least-busy device that can handle our circuit.", "_____no_output_____" ] ], [ [ "# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits\nIBMQ.load_account()\nprovider = IBMQ.get_provider(hub='ibm-q')\nbackend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and\n not x.configuration().simulator and x.status().operational==True))\nprint(\"least busy backend: \", backend)", "least busy backend: ibmq_burlington\n" ], [ "# Run our circuit on the least busy backend. Monitor the execution of the job in the queue\nfrom qiskit.tools.monitor import job_monitor\n\nshots = 1024\njob = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)\n\njob_monitor(job, interval = 2)", "Job Status: job has successfully run\n" ], [ "# Get the results of the computation\nresults = job.result()\nanswer = results.get_counts()\n\nplot_histogram(answer)", "_____no_output_____" ] ], [ [ "As we can see, the most likely result is `1111`. The other results are due to errors in the quantum computation. ", "_____no_output_____" ], [ "## 6. Problems <a id='problems'></a>\n\n1. Are you able to create a balanced or constant oracle of a different form?", "_____no_output_____" ] ], [ [ "from qiskit_textbook.problems import dj_problem_oracle\noracle = dj_problem_oracle(1)", "_____no_output_____" ] ], [ [ "2. The function `dj_problem_oracle` (shown above) returns a Deutsch-Joza oracle for `n = 4` in the form of a gate. The gate takes 5 qubits as input where the final qubit (`q_4`) is the output qubit (as with the example oracles above). You can get different oracles by giving `dj_problem_oracle` different integers between 1 and 5. Use the Deutsch-Joza algorithm to decide whether each oracle is balanced or constant (**Note:** It is highly recommended you try this example using the `qasm_simulator` instead of a real device).", "_____no_output_____" ], [ "## 7. References <a id='references'></a>\n\n1. David Deutsch and Richard Jozsa (1992). \"Rapid solutions of problems by quantum computation\". Proceedings of the Royal Society of London A. 439: 553–558. [doi:10.1098/rspa.1992.0167](https://doi.org/10.1098%2Frspa.1992.0167).\n2. R. Cleve; A. Ekert; C. Macchiavello; M. Mosca (1998). \"Quantum algorithms revisited\". Proceedings of the Royal Society of London A. 454: 339–354. [doi:10.1098/rspa.1998.0164](https://doi.org/10.1098%2Frspa.1998.0164).", "_____no_output_____" ] ], [ [ "import qiskit\nqiskit.__qiskit_version__", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "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", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb0a4e6782b05dd69cf953c419f0f053e8ab6dbc
13,248
ipynb
Jupyter Notebook
Personal_Projects/vector math calculus 2.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
Personal_Projects/vector math calculus 2.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
Personal_Projects/vector math calculus 2.ipynb
NSC9/Sample_of_Work
8f8160fbf0aa4fd514d4a5046668a194997aade6
[ "MIT" ]
null
null
null
39.311573
1,313
0.501283
[ [ [ "from IPython.display import Image\nfrom IPython.core.display import HTML \nImage(url= \"https://i.imgur.com/NLtIf3P.png\")", "_____no_output_____" ], [ "# Start with a coordinate system\nfrom sympy.vector import CoordSys3D, Del\ndelop = Del()\nC = CoordSys3D('C')", "_____no_output_____" ], [ "C", "_____no_output_____" ], [ "delop", "_____no_output_____" ], [ "from sympy import symbols, Function\nv1, v2, v3, f = symbols('v1 v2 v3 f', cls=Function)", "_____no_output_____" ], [ "# Define the vector field as vfield and the scalar field as sfield.\nvfield = v1(C.x, C.y, C.z)*C.i + v2(C.x, C.y, C.z)*C.j + v3(C.x, C.y, C.z)*C.k\nffield = f(C.x, C.y, C.z)", "_____no_output_____" ], [ "vfield", "_____no_output_____" ], [ "ffield", "_____no_output_____" ], [ "# Construct the expression for the LHS of the equation using Del()\nlhs = (delop.dot(ffield * vfield)).doit()", "_____no_output_____" ], [ "lhs", "_____no_output_____" ], [ "# Similarly, the RHS would be defined.\nrhs = ((vfield.dot(delop(ffield))) + (ffield * (delop.dot(vfield)))).doit()", "_____no_output_____" ], [ "rhs", "_____no_output_____" ], [ "# Now, to prove the product rule, we would just need to equate the expanded and simplified versions of the lhs and the rhs,\n# so that the SymPy expressions match.\nlhs.expand().simplify() == rhs.expand().doit().simplify()", "_____no_output_____" ], [ "lhs.expand().simplify()", "_____no_output_____" ], [ "rhs.expand().doit().simplify()", "_____no_output_____" ], [ "# Thus, the general form of the third product rule mentioned above can be proven using sympy.vector.\n\n# source: https://docs.sympy.org/latest/modules/vector/examples.html", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0a5003fff70c3c281597f6aca151212461d3a8
347,018
ipynb
Jupyter Notebook
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
0ab9869324a8f8a32d5ecfe0bfae71fc6fe0dde0
[ "MIT" ]
null
null
null
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
0ab9869324a8f8a32d5ecfe0bfae71fc6fe0dde0
[ "MIT" ]
null
null
null
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
0ab9869324a8f8a32d5ecfe0bfae71fc6fe0dde0
[ "MIT" ]
null
null
null
109.090852
110,302
0.706228
[ [ [ "# Residual Networks\n\nWelcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](https://arxiv.org/pdf/1512.03385.pdf), allow you to train much deeper networks than were previously practically feasible.\n\n**In this assignment, you will:**\n- Implement the basic building blocks of ResNets. \n- Put together these building blocks to implement and train a state-of-the-art neural network for image classification. \n\nThis assignment will be done in Keras. \n\nBefore jumping into the problem, let's run the cell below to load the required packages.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom keras import layers\nfrom keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D\nfrom keras.models import Model, load_model\nfrom keras.preprocessing import image\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.applications.imagenet_utils import preprocess_input\nimport pydot\nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom resnets_utils import *\nfrom keras.initializers import glorot_uniform\nimport scipy.misc\nfrom matplotlib.pyplot import imshow\n%matplotlib inline\n\nimport keras.backend as K\nK.set_image_data_format('channels_last')\nK.set_learning_phase(1)", "Using TensorFlow backend.\n" ] ], [ [ "## 1 - The problem of very deep neural networks\n\nLast week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers.\n\nThe main benefit of a very deep network is that it can represent very complex functions. It can also learn features at many different levels of abstraction, from edges (at the lower layers) to very complex features (at the deeper layers). However, using a deeper network doesn't always help. A huge barrier to training them is vanishing gradients: very deep networks often have a gradient signal that goes to zero quickly, thus making gradient descent unbearably slow. More specifically, during gradient descent, as you backprop from the final layer back to the first layer, you are multiplying by the weight matrix on each step, and thus the gradient can decrease exponentially quickly to zero (or, in rare cases, grow exponentially quickly and \"explode\" to take very large values). \n\nDuring training, you might therefore see the magnitude (or norm) of the gradient for the earlier layers descrease to zero very rapidly as training proceeds: ", "_____no_output_____" ], [ "<img src=\"images/vanishing_grad_kiank.png\" style=\"width:450px;height:220px;\">\n<caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'> : **Vanishing gradient** <br> The speed of learning decreases very rapidly for the early layers as the network trains </center></caption>\n\nYou are now going to solve this problem by building a Residual Network!", "_____no_output_____" ], [ "## 2 - Building a Residual Network\n\nIn ResNets, a \"shortcut\" or a \"skip connection\" allows the gradient to be directly backpropagated to earlier layers: \n\n<img src=\"images/skip_connection_kiank.png\" style=\"width:650px;height:200px;\">\n<caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'> : A ResNet block showing a **skip-connection** <br> </center></caption>\n\nThe image on the left shows the \"main path\" through the network. The image on the right adds a shortcut to the main path. By stacking these ResNet blocks on top of each other, you can form a very deep network. \n\nWe also saw in lecture that having ResNet blocks with the shortcut also makes it very easy for one of the blocks to learn an identity function. This means that you can stack on additional ResNet blocks with little risk of harming training set performance. (There is also some evidence that the ease of learning an identity function--even more than skip connections helping with vanishing gradients--accounts for ResNets' remarkable performance.)\n\nTwo main types of blocks are used in a ResNet, depending mainly on whether the input/output dimensions are same or different. You are going to implement both of them. ", "_____no_output_____" ], [ "### 2.1 - The identity block\n\nThe identity block is the standard block used in ResNets, and corresponds to the case where the input activation (say $a^{[l]}$) has the same dimension as the output activation (say $a^{[l+2]}$). To flesh out the different steps of what happens in a ResNet's identity block, here is an alternative diagram showing the individual steps:\n\n<img src=\"images/idblock2_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'> : **Identity block.** Skip connection \"skips over\" 2 layers. </center></caption>\n\nThe upper path is the \"shortcut path.\" The lower path is the \"main path.\" In this diagram, we have also made explicit the CONV2D and ReLU steps in each layer. To speed up training we have also added a BatchNorm step. Don't worry about this being complicated to implement--you'll see that BatchNorm is just one line of code in Keras! \n\nIn this exercise, you'll actually implement a slightly more powerful version of this identity block, in which the skip connection \"skips over\" 3 hidden layers rather than 2 layers. It looks like this: \n\n<img src=\"images/idblock3_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 4** </u><font color='purple'> : **Identity block.** Skip connection \"skips over\" 3 layers.</center></caption>\n\nHere're the individual steps.\n\nFirst component of main path: \n- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\" and its name should be `conv_name_base + '2a'`. Use 0 as the seed for the random initialization. \n- The first BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2a'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nSecond component of main path:\n- The second CONV2D has $F_2$ filters of shape $(f,f)$ and a stride of (1,1). Its padding is \"same\" and its name should be `conv_name_base + '2b'`. Use 0 as the seed for the random initialization. \n- The second BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2b'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nThird component of main path:\n- The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is \"valid\" and its name should be `conv_name_base + '2c'`. Use 0 as the seed for the random initialization. \n- The third BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. \n\nFinal step: \n- The shortcut and the input are added together.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\n**Exercise**: Implement the ResNet identity block. We have implemented the first component of the main path. Please read over this carefully to make sure you understand what it is doing. You should implement the rest. \n- To implement the Conv2D step: [See reference](https://keras.io/layers/convolutional/#conv2d)\n- To implement BatchNorm: [See reference](https://faroit.github.io/keras-docs/1.2.2/layers/normalization/) (axis: Integer, the axis that should be normalized (typically the channels axis))\n- For the activation, use: `Activation('relu')(X)`\n- To add the value passed forward by the shortcut: [See reference](https://keras.io/layers/merge/#add)", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: identity_block\n\ndef identity_block(X, f, filters, stage, block):\n \"\"\"\n Implementation of the identity block as defined in Figure 3\n\n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n stage -- integer, used to name the layers, depending on their position in the network\n block -- string/character, used to name the layers, depending on their position in the network\n\n Returns:\n X -- output of the identity block, tensor of shape (n_H, n_W, n_C)\n \"\"\"\n\n # defining name basis\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n # Retrieve Filters\n F1, F2, F3 = filters\n\n # Save the input value. You'll need this later to add back to the main path. \n X_shortcut = X\n\n # First component of main path\n X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2a', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)\n X = Activation('relu')(X)\n\n ### START CODE HERE ###\n\n # Second component of main path (≈3 lines)\n X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)\n X = Activation('relu')(X)\n\n # Third component of main path (≈2 lines)\n X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)\n\n # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n\n ### END CODE HERE ###\n\n return X", "_____no_output_____" ], [ "tf.reset_default_graph()\n\nwith tf.Session() as test:\n np.random.seed(1)\n A_prev = tf.placeholder(\"float\", [3, 4, 4, 6])\n X = np.random.randn(3, 4, 4, 6)\n A = identity_block(A_prev, f=2, filters=[2, 4, 6], stage=1, block='a')\n test.run(tf.global_variables_initializer())\n out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})\n print(\"out = \" + str(out[0][1][1][0]))\n", "out = [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003]\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **out**\n </td>\n <td>\n [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003]\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "## 2.2 - The convolutional block\n\nYou've implemented the ResNet identity block. Next, the ResNet \"convolutional block\" is the other type of block. You can use this type of block when the input and output dimensions don't match up. The difference with the identity block is that there is a CONV2D layer in the shortcut path: \n\n<img src=\"images/convblock_kiank.png\" style=\"width:650px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 4** </u><font color='purple'> : **Convolutional block** </center></caption>\n\nThe CONV2D layer in the shortcut path is used to resize the input $x$ to a different dimension, so that the dimensions match up in the final addition needed to add the shortcut value back to the main path. (This plays a similar role as the matrix $W_s$ discussed in lecture.) For example, to reduce the activation dimensions's height and width by a factor of 2, you can use a 1x1 convolution with a stride of 2. The CONV2D layer on the shortcut path does not use any non-linear activation function. Its main role is to just apply a (learned) linear function that reduces the dimension of the input, so that the dimensions match up for the later addition step. \n\nThe details of the convolutional block are as follows. \n\nFirst component of main path:\n- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\" and its name should be `conv_name_base + '2a'`. \n- The first BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2a'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nSecond component of main path:\n- The second CONV2D has $F_2$ filters of (f,f) and a stride of (1,1). Its padding is \"same\" and it's name should be `conv_name_base + '2b'`.\n- The second BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2b'`.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n\nThird component of main path:\n- The third CONV2D has $F_3$ filters of (1,1) and a stride of (1,1). Its padding is \"valid\" and it's name should be `conv_name_base + '2c'`.\n- The third BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. \n\nShortcut path:\n- The CONV2D has $F_3$ filters of shape (1,1) and a stride of (s,s). Its padding is \"valid\" and its name should be `conv_name_base + '1'`.\n- The BatchNorm is normalizing the channels axis. Its name should be `bn_name_base + '1'`. \n\nFinal step: \n- The shortcut and the main path values are added together.\n- Then apply the ReLU activation function. This has no name and no hyperparameters. \n \n**Exercise**: Implement the convolutional block. We have implemented the first component of the main path; you should implement the rest. As before, always use 0 as the seed for the random initialization, to ensure consistency with our grader.\n- [Conv Hint](https://keras.io/layers/convolutional/#conv2d)\n- [BatchNorm Hint](https://keras.io/layers/normalization/#batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))\n- For the activation, use: `Activation('relu')(X)`\n- [Addition Hint](https://keras.io/layers/merge/#add)", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: convolutional_block\n\ndef convolutional_block(X, f, filters, stage, block, s=2):\n \"\"\"\n Implementation of the convolutional block as defined in Figure 4\n\n Arguments:\n X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)\n f -- integer, specifying the shape of the middle CONV's window for the main path\n filters -- python list of integers, defining the number of filters in the CONV layers of the main path\n stage -- integer, used to name the layers, depending on their position in the network\n block -- string/character, used to name the layers, depending on their position in the network\n s -- Integer, specifying the stride to be used\n\n Returns:\n X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)\n \"\"\"\n\n # defining name basis\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n # Retrieve Filters\n F1, F2, F3 = filters\n\n # Save the input value\n X_shortcut = X\n\n ##### MAIN PATH #####\n # First component of main path \n X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '2a', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)\n X = Activation('relu')(X)\n\n ### START CODE HERE ###\n\n # Second component of main path (≈3 lines)\n X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)\n X = Activation('relu')(X)\n\n # Third component of main path (≈2 lines)\n X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)\n\n ##### SHORTCUT PATH #### (≈2 lines)\n X_shortcut = Conv2D(filters=F3, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '1', kernel_initializer=glorot_uniform(seed=0))(X_shortcut)\n X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1')(X_shortcut)\n\n # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n\n ### END CODE HERE ###\n return X\n", "_____no_output_____" ], [ "tf.reset_default_graph()\n\nwith tf.Session() as test:\n np.random.seed(1)\n A_prev = tf.placeholder(\"float\", [3, 4, 4, 6])\n X = np.random.randn(3, 4, 4, 6)\n A = convolutional_block(A_prev, f=2, filters=[2, 4, 6], stage=1, block='a')\n test.run(tf.global_variables_initializer())\n out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})\n print(\"out = \" + str(out[0][1][1][0]))\n", "out = [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603]\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **out**\n </td>\n <td>\n [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603]\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "## 3 - Building your first ResNet model (50 layers)\n\nYou now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the architecture of this neural network. \"ID BLOCK\" in the diagram stands for \"Identity block,\" and \"ID BLOCK x3\" means you should stack 3 identity blocks together.\n\n<img src=\"images/resnet_kiank.png\" style=\"width:850px;height:150px;\">\n<caption><center> <u> <font color='purple'> **Figure 5** </u><font color='purple'> : **ResNet-50 model** </center></caption>\n\nThe details of this ResNet-50 model are:\n- Zero-padding pads the input with a pad of (3,3)\n- Stage 1:\n - The 2D Convolution has 64 filters of shape (7,7) and uses a stride of (2,2). Its name is \"conv1\".\n - BatchNorm is applied to the channels axis of the input.\n - MaxPooling uses a (3,3) window and a (2,2) stride.\n- Stage 2:\n - The convolutional block uses three set of filters of size [64,64,256], \"f\" is 3, \"s\" is 1 and the block is \"a\".\n - The 2 identity blocks use three set of filters of size [64,64,256], \"f\" is 3 and the blocks are \"b\" and \"c\".\n- Stage 3:\n - The convolutional block uses three set of filters of size [128,128,512], \"f\" is 3, \"s\" is 2 and the block is \"a\".\n - The 3 identity blocks use three set of filters of size [128,128,512], \"f\" is 3 and the blocks are \"b\", \"c\" and \"d\".\n- Stage 4:\n - The convolutional block uses three set of filters of size [256, 256, 1024], \"f\" is 3, \"s\" is 2 and the block is \"a\".\n - The 5 identity blocks use three set of filters of size [256, 256, 1024], \"f\" is 3 and the blocks are \"b\", \"c\", \"d\", \"e\" and \"f\".\n- Stage 5:\n - The convolutional block uses three set of filters of size [512, 512, 2048], \"f\" is 3, \"s\" is 2 and the block is \"a\".\n - The 2 identity blocks use three set of filters of size [256, 256, 2048], \"f\" is 3 and the blocks are \"b\" and \"c\".\n- The 2D Average Pooling uses a window of shape (2,2) and its name is \"avg_pool\".\n- The flatten doesn't have any hyperparameters or name.\n- The Fully Connected (Dense) layer reduces its input to the number of classes using a softmax activation. Its name should be `'fc' + str(classes)`.\n\n**Exercise**: Implement the ResNet with 50 layers described in the figure above. We have implemented Stages 1 and 2. Please implement the rest. (The syntax for implementing Stages 3-5 should be quite similar to that of Stage 2.) Make sure you follow the naming convention in the text above. \n\nYou'll need to use this function: \n- Average pooling [see reference](https://keras.io/layers/pooling/#averagepooling2d)\n\nHere're some other functions we used in the code below:\n- Conv2D: [See reference](https://keras.io/layers/convolutional/#conv2d)\n- BatchNorm: [See reference](https://keras.io/layers/normalization/#batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))\n- Zero padding: [See reference](https://keras.io/layers/convolutional/#zeropadding2d)\n- Max pooling: [See reference](https://keras.io/layers/pooling/#maxpooling2d)\n- Fully conected layer: [See reference](https://keras.io/layers/core/#dense)\n- Addition: [See reference](https://keras.io/layers/merge/#add)", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: ResNet50\n\ndef ResNet50(input_shape=(64, 64, 3), classes=6):\n \"\"\"\n Implementation of the popular ResNet50 the following architecture:\n CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3\n -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER\n\n Arguments:\n input_shape -- shape of the images of the dataset\n classes -- integer, number of classes\n\n Returns:\n model -- a Model() instance in Keras\n \"\"\"\n\n # Define the input as a tensor with shape input_shape\n X_input = Input(input_shape)\n\n # Zero-Padding\n X = ZeroPadding2D((3, 3))(X_input)\n\n # Stage 1\n X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name='bn_conv1')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((3, 3), strides=(2, 2))(X)\n\n # Stage 2\n X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)\n X = identity_block(X, 3, [64, 64, 256], stage=2, block='b')\n X = identity_block(X, 3, [64, 64, 256], stage=2, block='c')\n\n ### START CODE HERE ###\n\n # Stage 3 (≈4 lines)\n X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)\n X = identity_block(X, 3, [128, 128, 512], stage=3, block='b')\n X = identity_block(X, 3, [128, 128, 512], stage=3, block='c')\n X = identity_block(X, 3, [128, 128, 512], stage=3, block='d')\n\n # Stage 4 (≈6 lines)\n X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='b')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='c')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='d')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='e')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='f')\n\n # Stage 5 (≈3 lines)\n X = X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)\n X = identity_block(X, 3, [512, 512, 2048], stage=5, block='b')\n X = identity_block(X, 3, [512, 512, 2048], stage=5, block='c')\n\n # AVGPOOL (≈1 line). Use \"X = AveragePooling2D(...)(X)\"\n X = AveragePooling2D(pool_size=(2, 2), padding='same')(X)\n\n ### END CODE HERE ###\n\n # output layer\n X = Flatten()(X)\n X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer=glorot_uniform(seed=0))(X)\n\n # Create model\n model = Model(inputs=X_input, outputs=X, name='ResNet50')\n\n return model", "_____no_output_____" ] ], [ [ "Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below.", "_____no_output_____" ] ], [ [ "model = ResNet50(input_shape=(64, 64, 3), classes=6)", "_____no_output_____" ] ], [ [ "As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model.", "_____no_output_____" ] ], [ [ "model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])", "_____no_output_____" ] ], [ [ "The model is now ready to be trained. The only thing you need is a dataset.", "_____no_output_____" ], [ "Let's load the SIGNS Dataset.\n\n<img src=\"images/signs_data_kiank.png\" style=\"width:450px;height:250px;\">\n<caption><center> <u> <font color='purple'> **Figure 6** </u><font color='purple'> : **SIGNS dataset** </center></caption>\n", "_____no_output_____" ] ], [ [ "X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\n\n# Normalize image vectors\nX_train = X_train_orig / 255.\nX_test = X_test_orig / 255.\n\n# Convert training and test labels to one hot matrices\nY_train = convert_to_one_hot(Y_train_orig, 6).T\nY_test = convert_to_one_hot(Y_test_orig, 6).T\n\nprint(\"number of training examples = \" + str(X_train.shape[0]))\nprint(\"number of test examples = \" + str(X_test.shape[0]))\nprint(\"X_train shape: \" + str(X_train.shape))\nprint(\"Y_train shape: \" + str(Y_train.shape))\nprint(\"X_test shape: \" + str(X_test.shape))\nprint(\"Y_test shape: \" + str(Y_test.shape))", "number of training examples = 1080\nnumber of test examples = 120\nX_train shape: (1080, 64, 64, 3)\nY_train shape: (1080, 6)\nX_test shape: (120, 64, 64, 3)\nY_test shape: (120, 6)\n" ] ], [ [ "Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch. ", "_____no_output_____" ] ], [ [ "model.fit(X_train, Y_train, epochs = 2, batch_size = 32)", "Epoch 1/2\n1080/1080 [==============================] - 313s - loss: 2.9895 - acc: 0.2426 \nEpoch 2/2\n1080/1080 [==============================] - 317s - loss: 2.1304 - acc: 0.3278 \n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n ** Epoch 1/2**\n </td>\n <td>\n loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours.\n </td>\n </tr>\n <tr>\n <td>\n ** Epoch 2/2**\n </td>\n <td>\n loss: between 1 and 5, acc: between 0.2 and 0.5, you should see your loss decreasing and the accuracy increasing.\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "Let's see how this model (trained on only two epochs) performs on the test set.", "_____no_output_____" ] ], [ [ "preds = model.evaluate(X_test, Y_test)\nprint(\"Loss = \" + str(preds[0]))\nprint(\"Test Accuracy = \" + str(preds[1]))", "120/120 [==============================] - 11s \nLoss = 2.15092230638\nTest Accuracy = 0.166666666667\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **Test Accuracy**\n </td>\n <td>\n between 0.16 and 0.25\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "For the purpose of this assignment, we've asked you to train the model only for two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check correctness, the online grader will run your code only for a small number of epochs as well.", "_____no_output_____" ], [ "After you have finished this official (graded) part of this assignment, you can also optionally train the ResNet for more iterations, if you want. We get a lot better performance when we train for ~20 epochs, but this will take more than an hour when training on a CPU. \n\nUsing a GPU, we've trained our own ResNet50 model's weights on the SIGNS dataset. You can load and run our trained model on the test set in the cells below. It may take ≈1min to load the model.", "_____no_output_____" ] ], [ [ "model = load_model('ResNet50.h5') ", "_____no_output_____" ], [ "preds = model.evaluate(X_test, Y_test)\nprint(\"Loss = \" + str(preds[0]))\nprint(\"Test Accuracy = \" + str(preds[1]))", "120/120 [==============================] - 13s \nLoss = 0.530178320408\nTest Accuracy = 0.866666662693\n" ] ], [ [ "ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy.\n\nCongratulations on finishing this assignment! You've now implemented a state-of-the-art image classification system! ", "_____no_output_____" ], [ "## 4 - Test on your own image (Optional/Ungraded)", "_____no_output_____" ], [ "If you wish, you can also take a picture of your own hand and see the output of the model. To do this:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Write your image's name in the following code\n 4. Run the code and check if the algorithm is right! ", "_____no_output_____" ] ], [ [ "img_path = 'images/my_image.jpg'\nimg = image.load_img(img_path, target_size=(64, 64))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = preprocess_input(x)\nprint('Input image shape:', x.shape)\nmy_image = scipy.misc.imread(img_path)\nimshow(my_image)\nprint(\"class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = \")\nprint(model.predict(x))", "Input image shape: (1, 64, 64, 3)\nclass prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = \n[[ 1. 0. 0. 0. 0. 0.]]\n" ] ], [ [ "You can also print a summary of your model by running the following code.", "_____no_output_____" ] ], [ [ "model.summary()", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\ninput_1 (InputLayer) (None, 64, 64, 3) 0 \n____________________________________________________________________________________________________\nzero_padding2d_1 (ZeroPadding2D) (None, 70, 70, 3) 0 input_1[0][0] \n____________________________________________________________________________________________________\nconv1 (Conv2D) (None, 32, 32, 64) 9472 zero_padding2d_1[0][0] \n____________________________________________________________________________________________________\nbn_conv1 (BatchNormalization) (None, 32, 32, 64) 256 conv1[0][0] \n____________________________________________________________________________________________________\nactivation_4 (Activation) (None, 32, 32, 64) 0 bn_conv1[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 15, 15, 64) 0 activation_4[0][0] \n____________________________________________________________________________________________________\nres2a_branch2a (Conv2D) (None, 15, 15, 64) 4160 max_pooling2d_1[0][0] \n____________________________________________________________________________________________________\nbn2a_branch2a (BatchNormalizatio (None, 15, 15, 64) 256 res2a_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_5 (Activation) (None, 15, 15, 64) 0 bn2a_branch2a[0][0] \n____________________________________________________________________________________________________\nres2a_branch2b (Conv2D) (None, 15, 15, 64) 36928 activation_5[0][0] \n____________________________________________________________________________________________________\nbn2a_branch2b (BatchNormalizatio (None, 15, 15, 64) 256 res2a_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_6 (Activation) (None, 15, 15, 64) 0 bn2a_branch2b[0][0] \n____________________________________________________________________________________________________\nres2a_branch2c (Conv2D) (None, 15, 15, 256) 16640 activation_6[0][0] \n____________________________________________________________________________________________________\nres2a_branch1 (Conv2D) (None, 15, 15, 256) 16640 max_pooling2d_1[0][0] \n____________________________________________________________________________________________________\nbn2a_branch2c (BatchNormalizatio (None, 15, 15, 256) 1024 res2a_branch2c[0][0] \n____________________________________________________________________________________________________\nbn2a_branch1 (BatchNormalization (None, 15, 15, 256) 1024 res2a_branch1[0][0] \n____________________________________________________________________________________________________\nadd_2 (Add) (None, 15, 15, 256) 0 bn2a_branch2c[0][0] \n bn2a_branch1[0][0] \n____________________________________________________________________________________________________\nactivation_7 (Activation) (None, 15, 15, 256) 0 add_2[0][0] \n____________________________________________________________________________________________________\nres2b_branch2a (Conv2D) (None, 15, 15, 64) 16448 activation_7[0][0] \n____________________________________________________________________________________________________\nbn2b_branch2a (BatchNormalizatio (None, 15, 15, 64) 256 res2b_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_8 (Activation) (None, 15, 15, 64) 0 bn2b_branch2a[0][0] \n____________________________________________________________________________________________________\nres2b_branch2b (Conv2D) (None, 15, 15, 64) 36928 activation_8[0][0] \n____________________________________________________________________________________________________\nbn2b_branch2b (BatchNormalizatio (None, 15, 15, 64) 256 res2b_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_9 (Activation) (None, 15, 15, 64) 0 bn2b_branch2b[0][0] \n____________________________________________________________________________________________________\nres2b_branch2c (Conv2D) (None, 15, 15, 256) 16640 activation_9[0][0] \n____________________________________________________________________________________________________\nbn2b_branch2c (BatchNormalizatio (None, 15, 15, 256) 1024 res2b_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_3 (Add) (None, 15, 15, 256) 0 bn2b_branch2c[0][0] \n activation_7[0][0] \n____________________________________________________________________________________________________\nactivation_10 (Activation) (None, 15, 15, 256) 0 add_3[0][0] \n____________________________________________________________________________________________________\nres2c_branch2a (Conv2D) (None, 15, 15, 64) 16448 activation_10[0][0] \n____________________________________________________________________________________________________\nbn2c_branch2a (BatchNormalizatio (None, 15, 15, 64) 256 res2c_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_11 (Activation) (None, 15, 15, 64) 0 bn2c_branch2a[0][0] \n____________________________________________________________________________________________________\nres2c_branch2b (Conv2D) (None, 15, 15, 64) 36928 activation_11[0][0] \n____________________________________________________________________________________________________\nbn2c_branch2b (BatchNormalizatio (None, 15, 15, 64) 256 res2c_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_12 (Activation) (None, 15, 15, 64) 0 bn2c_branch2b[0][0] \n____________________________________________________________________________________________________\nres2c_branch2c (Conv2D) (None, 15, 15, 256) 16640 activation_12[0][0] \n____________________________________________________________________________________________________\nbn2c_branch2c (BatchNormalizatio (None, 15, 15, 256) 1024 res2c_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_4 (Add) (None, 15, 15, 256) 0 bn2c_branch2c[0][0] \n activation_10[0][0] \n____________________________________________________________________________________________________\nactivation_13 (Activation) (None, 15, 15, 256) 0 add_4[0][0] \n____________________________________________________________________________________________________\nres3a_branch2a (Conv2D) (None, 8, 8, 128) 32896 activation_13[0][0] \n____________________________________________________________________________________________________\nbn3a_branch2a (BatchNormalizatio (None, 8, 8, 128) 512 res3a_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_14 (Activation) (None, 8, 8, 128) 0 bn3a_branch2a[0][0] \n____________________________________________________________________________________________________\nres3a_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_14[0][0] \n____________________________________________________________________________________________________\nbn3a_branch2b (BatchNormalizatio (None, 8, 8, 128) 512 res3a_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_15 (Activation) (None, 8, 8, 128) 0 bn3a_branch2b[0][0] \n____________________________________________________________________________________________________\nres3a_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_15[0][0] \n____________________________________________________________________________________________________\nres3a_branch1 (Conv2D) (None, 8, 8, 512) 131584 activation_13[0][0] \n____________________________________________________________________________________________________\nbn3a_branch2c (BatchNormalizatio (None, 8, 8, 512) 2048 res3a_branch2c[0][0] \n____________________________________________________________________________________________________\nbn3a_branch1 (BatchNormalization (None, 8, 8, 512) 2048 res3a_branch1[0][0] \n____________________________________________________________________________________________________\nadd_5 (Add) (None, 8, 8, 512) 0 bn3a_branch2c[0][0] \n bn3a_branch1[0][0] \n____________________________________________________________________________________________________\nactivation_16 (Activation) (None, 8, 8, 512) 0 add_5[0][0] \n____________________________________________________________________________________________________\nres3b_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_16[0][0] \n____________________________________________________________________________________________________\nbn3b_branch2a (BatchNormalizatio (None, 8, 8, 128) 512 res3b_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_17 (Activation) (None, 8, 8, 128) 0 bn3b_branch2a[0][0] \n____________________________________________________________________________________________________\nres3b_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_17[0][0] \n____________________________________________________________________________________________________\nbn3b_branch2b (BatchNormalizatio (None, 8, 8, 128) 512 res3b_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_18 (Activation) (None, 8, 8, 128) 0 bn3b_branch2b[0][0] \n____________________________________________________________________________________________________\nres3b_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_18[0][0] \n____________________________________________________________________________________________________\nbn3b_branch2c (BatchNormalizatio (None, 8, 8, 512) 2048 res3b_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_6 (Add) (None, 8, 8, 512) 0 bn3b_branch2c[0][0] \n activation_16[0][0] \n____________________________________________________________________________________________________\nactivation_19 (Activation) (None, 8, 8, 512) 0 add_6[0][0] \n____________________________________________________________________________________________________\nres3c_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_19[0][0] \n____________________________________________________________________________________________________\nbn3c_branch2a (BatchNormalizatio (None, 8, 8, 128) 512 res3c_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_20 (Activation) (None, 8, 8, 128) 0 bn3c_branch2a[0][0] \n____________________________________________________________________________________________________\nres3c_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_20[0][0] \n____________________________________________________________________________________________________\nbn3c_branch2b (BatchNormalizatio (None, 8, 8, 128) 512 res3c_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_21 (Activation) (None, 8, 8, 128) 0 bn3c_branch2b[0][0] \n____________________________________________________________________________________________________\nres3c_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_21[0][0] \n____________________________________________________________________________________________________\nbn3c_branch2c (BatchNormalizatio (None, 8, 8, 512) 2048 res3c_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_7 (Add) (None, 8, 8, 512) 0 bn3c_branch2c[0][0] \n activation_19[0][0] \n____________________________________________________________________________________________________\nactivation_22 (Activation) (None, 8, 8, 512) 0 add_7[0][0] \n____________________________________________________________________________________________________\nres3d_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_22[0][0] \n____________________________________________________________________________________________________\nbn3d_branch2a (BatchNormalizatio (None, 8, 8, 128) 512 res3d_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_23 (Activation) (None, 8, 8, 128) 0 bn3d_branch2a[0][0] \n____________________________________________________________________________________________________\nres3d_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_23[0][0] \n____________________________________________________________________________________________________\nbn3d_branch2b (BatchNormalizatio (None, 8, 8, 128) 512 res3d_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_24 (Activation) (None, 8, 8, 128) 0 bn3d_branch2b[0][0] \n____________________________________________________________________________________________________\nres3d_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_24[0][0] \n____________________________________________________________________________________________________\nbn3d_branch2c (BatchNormalizatio (None, 8, 8, 512) 2048 res3d_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_8 (Add) (None, 8, 8, 512) 0 bn3d_branch2c[0][0] \n activation_22[0][0] \n____________________________________________________________________________________________________\nactivation_25 (Activation) (None, 8, 8, 512) 0 add_8[0][0] \n____________________________________________________________________________________________________\nres4a_branch2a (Conv2D) (None, 4, 4, 256) 131328 activation_25[0][0] \n____________________________________________________________________________________________________\nbn4a_branch2a (BatchNormalizatio (None, 4, 4, 256) 1024 res4a_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_26 (Activation) (None, 4, 4, 256) 0 bn4a_branch2a[0][0] \n____________________________________________________________________________________________________\nres4a_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_26[0][0] \n____________________________________________________________________________________________________\nbn4a_branch2b (BatchNormalizatio (None, 4, 4, 256) 1024 res4a_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_27 (Activation) (None, 4, 4, 256) 0 bn4a_branch2b[0][0] \n____________________________________________________________________________________________________\nres4a_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_27[0][0] \n____________________________________________________________________________________________________\nres4a_branch1 (Conv2D) (None, 4, 4, 1024) 525312 activation_25[0][0] \n____________________________________________________________________________________________________\nbn4a_branch2c (BatchNormalizatio (None, 4, 4, 1024) 4096 res4a_branch2c[0][0] \n____________________________________________________________________________________________________\nbn4a_branch1 (BatchNormalization (None, 4, 4, 1024) 4096 res4a_branch1[0][0] \n____________________________________________________________________________________________________\nadd_9 (Add) (None, 4, 4, 1024) 0 bn4a_branch2c[0][0] \n bn4a_branch1[0][0] \n____________________________________________________________________________________________________\nactivation_28 (Activation) (None, 4, 4, 1024) 0 add_9[0][0] \n____________________________________________________________________________________________________\nres4b_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_28[0][0] \n____________________________________________________________________________________________________\nbn4b_branch2a (BatchNormalizatio (None, 4, 4, 256) 1024 res4b_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_29 (Activation) (None, 4, 4, 256) 0 bn4b_branch2a[0][0] \n____________________________________________________________________________________________________\nres4b_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_29[0][0] \n____________________________________________________________________________________________________\nbn4b_branch2b (BatchNormalizatio (None, 4, 4, 256) 1024 res4b_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_30 (Activation) (None, 4, 4, 256) 0 bn4b_branch2b[0][0] \n____________________________________________________________________________________________________\nres4b_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_30[0][0] \n____________________________________________________________________________________________________\nbn4b_branch2c (BatchNormalizatio (None, 4, 4, 1024) 4096 res4b_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_10 (Add) (None, 4, 4, 1024) 0 bn4b_branch2c[0][0] \n activation_28[0][0] \n____________________________________________________________________________________________________\nactivation_31 (Activation) (None, 4, 4, 1024) 0 add_10[0][0] \n____________________________________________________________________________________________________\nres4c_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_31[0][0] \n____________________________________________________________________________________________________\nbn4c_branch2a (BatchNormalizatio (None, 4, 4, 256) 1024 res4c_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_32 (Activation) (None, 4, 4, 256) 0 bn4c_branch2a[0][0] \n____________________________________________________________________________________________________\nres4c_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_32[0][0] \n____________________________________________________________________________________________________\nbn4c_branch2b (BatchNormalizatio (None, 4, 4, 256) 1024 res4c_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_33 (Activation) (None, 4, 4, 256) 0 bn4c_branch2b[0][0] \n____________________________________________________________________________________________________\nres4c_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_33[0][0] \n____________________________________________________________________________________________________\nbn4c_branch2c (BatchNormalizatio (None, 4, 4, 1024) 4096 res4c_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_11 (Add) (None, 4, 4, 1024) 0 bn4c_branch2c[0][0] \n activation_31[0][0] \n____________________________________________________________________________________________________\nactivation_34 (Activation) (None, 4, 4, 1024) 0 add_11[0][0] \n____________________________________________________________________________________________________\nres4d_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_34[0][0] \n____________________________________________________________________________________________________\nbn4d_branch2a (BatchNormalizatio (None, 4, 4, 256) 1024 res4d_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_35 (Activation) (None, 4, 4, 256) 0 bn4d_branch2a[0][0] \n____________________________________________________________________________________________________\nres4d_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_35[0][0] \n____________________________________________________________________________________________________\nbn4d_branch2b (BatchNormalizatio (None, 4, 4, 256) 1024 res4d_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_36 (Activation) (None, 4, 4, 256) 0 bn4d_branch2b[0][0] \n____________________________________________________________________________________________________\nres4d_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_36[0][0] \n____________________________________________________________________________________________________\nbn4d_branch2c (BatchNormalizatio (None, 4, 4, 1024) 4096 res4d_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_12 (Add) (None, 4, 4, 1024) 0 bn4d_branch2c[0][0] \n activation_34[0][0] \n____________________________________________________________________________________________________\nactivation_37 (Activation) (None, 4, 4, 1024) 0 add_12[0][0] \n____________________________________________________________________________________________________\nres4e_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_37[0][0] \n____________________________________________________________________________________________________\nbn4e_branch2a (BatchNormalizatio (None, 4, 4, 256) 1024 res4e_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_38 (Activation) (None, 4, 4, 256) 0 bn4e_branch2a[0][0] \n____________________________________________________________________________________________________\nres4e_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_38[0][0] \n____________________________________________________________________________________________________\nbn4e_branch2b (BatchNormalizatio (None, 4, 4, 256) 1024 res4e_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_39 (Activation) (None, 4, 4, 256) 0 bn4e_branch2b[0][0] \n____________________________________________________________________________________________________\nres4e_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_39[0][0] \n____________________________________________________________________________________________________\nbn4e_branch2c (BatchNormalizatio (None, 4, 4, 1024) 4096 res4e_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_13 (Add) (None, 4, 4, 1024) 0 bn4e_branch2c[0][0] \n activation_37[0][0] \n____________________________________________________________________________________________________\nactivation_40 (Activation) (None, 4, 4, 1024) 0 add_13[0][0] \n____________________________________________________________________________________________________\nres4f_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_40[0][0] \n____________________________________________________________________________________________________\nbn4f_branch2a (BatchNormalizatio (None, 4, 4, 256) 1024 res4f_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_41 (Activation) (None, 4, 4, 256) 0 bn4f_branch2a[0][0] \n____________________________________________________________________________________________________\nres4f_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_41[0][0] \n____________________________________________________________________________________________________\nbn4f_branch2b (BatchNormalizatio (None, 4, 4, 256) 1024 res4f_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_42 (Activation) (None, 4, 4, 256) 0 bn4f_branch2b[0][0] \n____________________________________________________________________________________________________\nres4f_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_42[0][0] \n____________________________________________________________________________________________________\nbn4f_branch2c (BatchNormalizatio (None, 4, 4, 1024) 4096 res4f_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_14 (Add) (None, 4, 4, 1024) 0 bn4f_branch2c[0][0] \n activation_40[0][0] \n____________________________________________________________________________________________________\nactivation_43 (Activation) (None, 4, 4, 1024) 0 add_14[0][0] \n____________________________________________________________________________________________________\nres5a_branch2a (Conv2D) (None, 2, 2, 512) 524800 activation_43[0][0] \n____________________________________________________________________________________________________\nbn5a_branch2a (BatchNormalizatio (None, 2, 2, 512) 2048 res5a_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_44 (Activation) (None, 2, 2, 512) 0 bn5a_branch2a[0][0] \n____________________________________________________________________________________________________\nres5a_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_44[0][0] \n____________________________________________________________________________________________________\nbn5a_branch2b (BatchNormalizatio (None, 2, 2, 512) 2048 res5a_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_45 (Activation) (None, 2, 2, 512) 0 bn5a_branch2b[0][0] \n____________________________________________________________________________________________________\nres5a_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_45[0][0] \n____________________________________________________________________________________________________\nres5a_branch1 (Conv2D) (None, 2, 2, 2048) 2099200 activation_43[0][0] \n____________________________________________________________________________________________________\nbn5a_branch2c (BatchNormalizatio (None, 2, 2, 2048) 8192 res5a_branch2c[0][0] \n____________________________________________________________________________________________________\nbn5a_branch1 (BatchNormalization (None, 2, 2, 2048) 8192 res5a_branch1[0][0] \n____________________________________________________________________________________________________\nadd_15 (Add) (None, 2, 2, 2048) 0 bn5a_branch2c[0][0] \n bn5a_branch1[0][0] \n____________________________________________________________________________________________________\nactivation_46 (Activation) (None, 2, 2, 2048) 0 add_15[0][0] \n____________________________________________________________________________________________________\nres5b_branch2a (Conv2D) (None, 2, 2, 512) 1049088 activation_46[0][0] \n____________________________________________________________________________________________________\nbn5b_branch2a (BatchNormalizatio (None, 2, 2, 512) 2048 res5b_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_47 (Activation) (None, 2, 2, 512) 0 bn5b_branch2a[0][0] \n____________________________________________________________________________________________________\nres5b_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_47[0][0] \n____________________________________________________________________________________________________\nbn5b_branch2b (BatchNormalizatio (None, 2, 2, 512) 2048 res5b_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_48 (Activation) (None, 2, 2, 512) 0 bn5b_branch2b[0][0] \n____________________________________________________________________________________________________\nres5b_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_48[0][0] \n____________________________________________________________________________________________________\nbn5b_branch2c (BatchNormalizatio (None, 2, 2, 2048) 8192 res5b_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_16 (Add) (None, 2, 2, 2048) 0 bn5b_branch2c[0][0] \n activation_46[0][0] \n____________________________________________________________________________________________________\nactivation_49 (Activation) (None, 2, 2, 2048) 0 add_16[0][0] \n____________________________________________________________________________________________________\nres5c_branch2a (Conv2D) (None, 2, 2, 512) 1049088 activation_49[0][0] \n____________________________________________________________________________________________________\nbn5c_branch2a (BatchNormalizatio (None, 2, 2, 512) 2048 res5c_branch2a[0][0] \n____________________________________________________________________________________________________\nactivation_50 (Activation) (None, 2, 2, 512) 0 bn5c_branch2a[0][0] \n____________________________________________________________________________________________________\nres5c_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_50[0][0] \n____________________________________________________________________________________________________\nbn5c_branch2b (BatchNormalizatio (None, 2, 2, 512) 2048 res5c_branch2b[0][0] \n____________________________________________________________________________________________________\nactivation_51 (Activation) (None, 2, 2, 512) 0 bn5c_branch2b[0][0] \n____________________________________________________________________________________________________\nres5c_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_51[0][0] \n____________________________________________________________________________________________________\nbn5c_branch2c (BatchNormalizatio (None, 2, 2, 2048) 8192 res5c_branch2c[0][0] \n____________________________________________________________________________________________________\nadd_17 (Add) (None, 2, 2, 2048) 0 bn5c_branch2c[0][0] \n activation_49[0][0] \n____________________________________________________________________________________________________\nactivation_52 (Activation) (None, 2, 2, 2048) 0 add_17[0][0] \n____________________________________________________________________________________________________\navg_pool (AveragePooling2D) (None, 1, 1, 2048) 0 activation_52[0][0] \n____________________________________________________________________________________________________\nflatten_1 (Flatten) (None, 2048) 0 avg_pool[0][0] \n____________________________________________________________________________________________________\nfc6 (Dense) (None, 6) 12294 flatten_1[0][0] \n====================================================================================================\nTotal params: 23,600,006\nTrainable params: 23,546,886\nNon-trainable params: 53,120\n____________________________________________________________________________________________________\n" ] ], [ [ "Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to \"File -> Open...-> model.png\".", "_____no_output_____" ] ], [ [ "plot_model(model, to_file='model.png')\nSVG(model_to_dot(model).create(prog='dot', format='svg'))", "_____no_output_____" ] ], [ [ "<font color='blue'>\n**What you should remember:**\n- Very deep \"plain\" networks don't work in practice because they are hard to train due to vanishing gradients. \n- The skip-connections help to address the Vanishing Gradient problem. They also make it easy for a ResNet block to learn an identity function. \n- There are two main type of blocks: The identity block and the convolutional block. \n- Very deep Residual Networks are built by stacking these blocks together.", "_____no_output_____" ], [ "### References \n\nThis notebook presents the ResNet algorithm due to He et al. (2015). The implementation here also took significant inspiration and follows the structure given in the github repository of Francois Chollet: \n\n- Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun - [Deep Residual Learning for Image Recognition (2015)](https://arxiv.org/abs/1512.03385)\n- Francois Chollet's github repository: https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb0a76cc783be2b53ec57498f9dbd1bbab879061
6,357
ipynb
Jupyter Notebook
eloi/prediction_pipeline.ipynb
phdinds-aim/resype
322f272d600ed6831fb90c5d05794d0e5dd3eca2
[ "MIT" ]
null
null
null
eloi/prediction_pipeline.ipynb
phdinds-aim/resype
322f272d600ed6831fb90c5d05794d0e5dd3eca2
[ "MIT" ]
null
null
null
eloi/prediction_pipeline.ipynb
phdinds-aim/resype
322f272d600ed6831fb90c5d05794d0e5dd3eca2
[ "MIT" ]
null
null
null
35.513966
563
0.656914
[ [ [ "# ReSyPE Training Pipeline", "_____no_output_____" ], [ "We introduce a framework for training arbitrary machine learning models to perform collaborative filtering on small and large datasets. Given the utility matrix as input, we outline two approaches for model training as discussed by C. Aggarwal in his book on *Recommender Systems*. We also propose an extension of these methodologies by applying clustering on the dataset before the model training. ", "_____no_output_____" ], [ "## Machine Learning + Collaborative Filtering (ML+CS) Recommender System", "_____no_output_____" ], [ "### Approach 1: ML-based Collaborative Filtering on Utility Matrix with Reduced Dimensions", "_____no_output_____" ], [ "1. Fill Utility Matrix with mean of matrix\n1. Choose column j to where missing ratings will be predicted. Column j will be the label in the model while the features will be the rest of the columns (not equal to j). \n1. Perform SVD on feature matrix. This will be the new feature table used to predict the ratings for item j.\n1. Train a model using the feature matrix as input and column j as output\n1. Repeat 2, 3, 4 for all items/columns.", "_____no_output_____" ], [ "### Approach 2: Iterative Approach to ML-based Item-wise Collaborative Filtering", "_____no_output_____" ], [ "1. Mean-center each row of the utility matrix to remove user bias. \n1. Replace missing values with zero after mean centering. \n1. Choose column j to where missing ratings will be predicted. Column j will be the label in the model while the features will be the rest of the columns (not equal to j). \n1. Train a model using the feature matrix as input and column j as output\n1. Predict missing ratings for column j. \n1. Use the predicted values to update the missing ratings in the utility matrix. \n1. Perform steps 3, 4, 5, 6 for all columns. \n1. Iterate steps 3 to 7 until the predicted ratings converge. ", "_____no_output_____" ], [ "### Approach 3: ML and Content-Based Collaborative Filtering ", "_____no_output_____" ], [ "1. Generate user features and item features\n1. Concatenate the user features and item features for every user-item pair wherein a user has rated an item.\n1. Perform a stratified splitting of the data into train and test sets where the test set is a fraction of the items a user has not rated. Each user must have a minimum number of items rated to be part of the training process.\n1. Train a model using the concatenated user-item feature table to predict the rating for each user-item pair in the training set.\n1. Use the trained model to predict the rating for all items a user has not rated.\n1. Select the items with the highest rating as the recommendations.", "_____no_output_____" ], [ "## Training on Large Datasets", "_____no_output_____" ], [ "The diagram below shows the flowchart of the proposed method for model training. If the dataset is small (left branch), we use the two approaches metioned above and apply them to the raw utility matrix. Since we are training one model per item, a limitation of these methods is that they are computationally expensive especially when the iterative approach is used. Hence we need a more scalable solution. One way to do this assigning users and/or items into clusters and deriving a new utility matrix that contains the representative ratings per cluster. ", "_____no_output_____" ], [ "After clustering, the cluster-based utility matrix contains the aggregate ratings of each cluster. The collaborative filtering problem is now reduced to prediction of ratings per user- or item-cluster instead of predicting the ratings for all users and items. ", "_____no_output_____" ], [ "![flowchart](../training_pipeline.png)", "_____no_output_____" ], [ "### Model training for clustered data", "_____no_output_____" ], [ "1. Generate multiple sets of synthetic data containing unknown/missing ratings. We do this by randomly setting elements of the cluster-based utility matrix to NaN. \n1. For each matrix of synthetic data, we apply the iterative and the SVD approach to predict the missing ratings. \n1. Get all predictions from each matrix of synthetic data and get the mean across all datasets. This will be the treated as the final cluster-based predictions of the RS. ", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb0a7ee85065d751d30b69f5ec1a97138c2621ba
4,094
ipynb
Jupyter Notebook
Vallisneri Courses/Python Statistics Essential Training/Exercise Files/chapter5/05_03/05_03_fitgoodness_begin.ipynb
samisaf/Learning-Data-Science
879f92a0b353f814ec6ebbf6bf2239c01e8f86b0
[ "MIT" ]
null
null
null
Vallisneri Courses/Python Statistics Essential Training/Exercise Files/chapter5/05_03/05_03_fitgoodness_begin.ipynb
samisaf/Learning-Data-Science
879f92a0b353f814ec6ebbf6bf2239c01e8f86b0
[ "MIT" ]
null
null
null
Vallisneri Courses/Python Statistics Essential Training/Exercise Files/chapter5/05_03/05_03_fitgoodness_begin.ipynb
samisaf/Learning-Data-Science
879f92a0b353f814ec6ebbf6bf2239c01e8f86b0
[ "MIT" ]
null
null
null
20.676768
116
0.5298
[ [ [ "## Python statistics essential training - 05_03_fitgoodness", "_____no_output_____" ], [ "Standard imports", "_____no_output_____" ] ], [ [ "import math", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "import matplotlib\nimport matplotlib.pyplot as pp", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ], [ "import statsmodels\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf", "_____no_output_____" ] ], [ [ "Loading gapminder data for year 1985 (Live Aid!) and setting up plot as in chapter 3", "_____no_output_____" ] ], [ [ "gapminder = pd.read_csv('gapminder.csv')", "_____no_output_____" ], [ "gdata = gapminder.query('year == 1985')", "_____no_output_____" ], [ "size = 1e-6 * gdata.population\n\ncolors = gdata.region.map({'Africa': 'skyblue', 'Europe': 'gold', 'America': 'palegreen', 'Asia': 'coral'})\n\ndef plotdata():\n gdata.plot.scatter('age5_surviving','babies_per_woman',\n c=colors,s=size,linewidths=0.5,edgecolor='k',alpha=0.5)", "_____no_output_____" ] ], [ [ "Setting up model plot", "_____no_output_____" ] ], [ [ "def plotfit(fit):\n plotdata()\n pp.scatter(gdata.age5_surviving,fit.predict(gdata),\n c=colors,s=30,linewidths=0.5,edgecolor='k',marker='D')", "_____no_output_____" ] ], [ [ "Three models from last video", "_____no_output_____" ] ], [ [ "groupmeans = smf.ols(formula='babies_per_woman ~ -1 + region', data=gdata).fit()", "_____no_output_____" ], [ "surviving = smf.ols(formula='babies_per_woman ~ -1 + region + age5_surviving', data=gdata).fit()", "_____no_output_____" ], [ "surviving_byregion_population = smf.ols(\n formula='babies_per_woman ~ -1 + region + age5_surviving'\n '+ age5_surviving:region - age5_surviving + population',\n data=gdata).fit()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb0a9b9139d1ecff9fe34a8af78f2c1daf107619
59,415
ipynb
Jupyter Notebook
notebooks/plot_data.ipynb
margiki/Improving-Interpretability-Medical-Imaging
428cf5af4e154dfcac734ba6150e5adcb583460c
[ "MIT-feh", "MIT" ]
1
2021-12-29T07:45:41.000Z
2021-12-29T07:45:41.000Z
notebooks/plot_data.ipynb
margiki/Interpretability-Adversarial
428cf5af4e154dfcac734ba6150e5adcb583460c
[ "MIT-feh", "MIT" ]
null
null
null
notebooks/plot_data.ipynb
margiki/Interpretability-Adversarial
428cf5af4e154dfcac734ba6150e5adcb583460c
[ "MIT-feh", "MIT" ]
1
2022-03-01T14:35:29.000Z
2022-03-01T14:35:29.000Z
861.086957
40,158
0.734882
[ [ [ "%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "plt.figure(figsize=(8, 4))\nxticks = [0, 1, 2, 3, 4, 5]\nplt.plot([0, 1, 2, 3, 4, 5], [72.55, 66.26, 64.92, 63.85, 61.17, 61.44], marker='o')\nplt.scatter([1], [66.26], marker='o', color='red')\nplt.xlabel(\"Model\")\nplt.ylabel(\"Weighted accuracy\")\nplt.ylim(60, 75)\nplt.xticks(xticks, ['Standard\\nmodel', 'Fine-tune\\ngroups 2-5', 'Fine-tune\\ngroups 3-5', 'Fine-tune\\ngroups 4-5', 'Fine-tune\\ngroup 5', 'Robust\\nmodel']);", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
cb0aa770b581a08a5f6ac1ed87e8e69177c3e4ef
14,530
ipynb
Jupyter Notebook
jupyter/distiller_jupyter_helpers.ipynb
HWT-WalterHu/distiller
556492a0a5434a6bcb21fb0301f8b68501ad2d21
[ "Apache-2.0" ]
null
null
null
jupyter/distiller_jupyter_helpers.ipynb
HWT-WalterHu/distiller
556492a0a5434a6bcb21fb0301f8b68501ad2d21
[ "Apache-2.0" ]
null
null
null
jupyter/distiller_jupyter_helpers.ipynb
HWT-WalterHu/distiller
556492a0a5434a6bcb21fb0301f8b68501ad2d21
[ "Apache-2.0" ]
null
null
null
40.361111
128
0.514935
[ [ [ "## Interpreting your pruning and regularization experiments\nThis notebook contains code to be included in your own notebooks by adding this line at the top of your notebook:<br>\n```%run distiller_jupyter_helpers.ipynb```", "_____no_output_____" ] ], [ [ "# Relative import of code from distiller, w/o installing the package\nimport os\nimport sys\nimport distiller.utils\nimport distiller\nimport distiller.apputils.checkpoint", "_____no_output_____" ], [ "import torch\nimport torchvision\nimport os\nimport collections\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef to_np(x):\n return x.cpu().numpy()\n\ndef flatten(weights):\n weights = weights.clone().view(weights.numel())\n weights = to_np(weights)\n return weights\n\n\nimport scipy.stats as stats\ndef plot_params_hist_single(name, weights_pytorch, remove_zeros=False, kmeans=None):\n weights = flatten(weights_pytorch)\n if remove_zeros:\n weights = weights[weights!=0]\n n, bins, patches = plt.hist(weights, bins=200)\n plt.title(name)\n \n if kmeans is not None:\n labels = kmeans.labels_\n centroids = kmeans.cluster_centers_\n cnt_coefficients = [len(labels[labels==i]) for i in range(16)]\n # Normalize the coefficients so they display in the same range as the float32 histogram\n cnt_coefficients = [cnt / 5 for cnt in cnt_coefficients] \n centroids, cnt_coefficients = zip(*sorted(zip(centroids, cnt_coefficients)))\n cnt_coefficients = list(cnt_coefficients)\n centroids = list(centroids)\n if remove_zeros:\n for i in range(len(centroids)):\n if abs(centroids[i]) < 0.0001: # almost zero\n centroids.remove(centroids[i])\n cnt_coefficients.remove(cnt_coefficients[i])\n break\n \n plt.plot(centroids, cnt_coefficients)\n zeros = [0] * len(centroids)\n plt.plot(centroids, zeros, 'r+', markersize=15)\n \n h = cnt_coefficients\n hmean = np.mean(h)\n hstd = np.std(h)\n pdf = stats.norm.pdf(h, hmean, hstd)\n #plt.plot(h, pdf)\n \n plt.show()\n print(\"mean: %f\\nstddev: %f\" % (weights.mean(), weights.std()))\n print(\"size=%s %d elements\" % distiller.size2str(weights_pytorch.size()))\n print(\"min: %.3f\\nmax:%.3f\" % (weights.min(), weights.max()))\n\n \ndef plot_params_hist(params, which='weight', remove_zeros=False): \n for name, weights_pytorch in params.items():\n if which not in name:\n continue\n plot_params_hist_single(name, weights_pytorch, remove_zeros)\n \ndef plot_params2d(classifier_weights, figsize, binary_mask=True, \n gmin=None, gmax=None,\n xlabel=\"\", ylabel=\"\", title=\"\"):\n if not isinstance(classifier_weights, list):\n classifier_weights = [classifier_weights]\n \n for weights in classifier_weights:\n assert weights.dim() in [2,4], \"something's wrong\"\n \n shape_str = distiller.size2str(weights.size())\n volume = distiller.volume(weights)\n \n # Clone because we are going to change the tensor values\n if binary_mask:\n weights2d = weights.clone()\n else:\n weights2d = weights\n \n if weights.dim() == 4:\n weights2d = weights2d.view(weights.size()[0] * weights.size()[1], -1)\n\n sparsity = len(weights2d[weights2d==0]) / volume\n \n # Move to CPU so we can plot it.\n if weights2d.is_cuda:\n weights2d = weights2d.cpu()\n \n cmap='seismic'\n # create a binary image (non-zero elements are black; zeros are white)\n if binary_mask:\n cmap='binary'\n weights2d[weights2d!=0] = 1\n \n fig = plt.figure(figsize=figsize)\n if (not binary_mask) and (gmin is not None) and (gmax is not None):\n if isinstance(gmin, torch.Tensor):\n gmin = gmin.item()\n gmax = gmax.item()\n plt.imshow(weights2d, cmap=cmap, vmin=gmin, vmax=gmax)\n else:\n plt.imshow(weights2d, cmap=cmap, vmin=0, vmax=1)\n #plt.figure(figsize=(20,40))\n \n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(title)\n plt.colorbar( pad=0.01, fraction=0.01)\n plt.show()\n print(\"sparsity = %.1f%% (nnz=black)\" % (sparsity*100))\n print(\"size=%s = %d elements\" % (shape_str, volume))\n \n \ndef printk(k):\n \"\"\"Print the values of the elements of a kernel as a list\"\"\"\n print(list(k.view(k.numel())))\n\n \ndef plot_param_kernels(weights, layout, size_ctrl, binary_mask=False, color_normalization='Model', \n gmin=None, gmax=None, interpolation=None, first_kernel=0):\n ofms, ifms = weights.size()[0], weights.size()[1]\n kw, kh = weights.size()[2], weights.size()[3]\n \n print(\"min=%.4f\\tmax=%.4f\" % (weights.min(), weights.max()))\n shape_str = distiller.size2str(weights.size())\n volume = distiller.volume(weights)\n print(\"size=%s = %d elements\" % (shape_str, volume))\n \n # Clone because we are going to change the tensor values\n weights = weights.clone()\n if binary_mask:\n weights[weights!=0] = 1\n # Take the inverse of the pixels, because we want zeros to appear white\n #weights = 1 - weights\n \n kernels = weights.view(ofms * ifms, kh, kw)\n nrow, ncol = layout[0], layout[1]\n \n # Move to CPU so we can plot it.\n if kernels.is_cuda:\n kernels = kernels.cpu()\n\n # Plot the graph\n plt.gray()\n #plt.tight_layout()\n fig = plt.figure( figsize=(layout[0]*size_ctrl, layout[1]*size_ctrl) );\n\n # We want to normalize the grayscale brightness levels for all of the images we display (group),\n # otherwise, each image is normalized separately and this causes distortion between the different\n # filters images we ddisplay.\n # We don't normalize across all of the filters images, because the outliers cause the image of each \n # filter to be very muted. This is because each group of filters we display usually has low variance\n # between the element values of that group.\n if color_normalization=='Tensor':\n gmin = weights.min()\n gmax = weights.max()\n elif color_normalization=='Group':\n gmin = weights[0:nrow, 0:ncol].min()\n gmax = weights[0:nrow, 0:ncol].max()\n print(\"gmin=%.4f\\tgmax=%.4f\" % (gmin, gmax))\n if isinstance(gmin, torch.Tensor):\n gmin = gmin.item()\n gmax = gmax.item()\n \n i = 0 \n for row in range(0, nrow):\n for col in range (0, ncol):\n ax = fig.add_subplot(layout[0], layout[1], i+1)\n if binary_mask:\n ax.matshow(kernels[first_kernel+i], cmap='binary', vmin=0, vmax=1);\n else:\n # Use siesmic so that colors around the center are lighter. Red and blue are used\n # to represent (and visually separate) negative and positive weights \n ax.matshow(kernels[first_kernel+i], cmap='seismic', vmin=gmin, vmax=gmax, interpolation=interpolation);\n ax.set(xticks=[], yticks=[])\n i += 1\n \n \ndef l1_norm_histogram(weights):\n \"\"\"Compute a histogram of the L1-norms of the kernels of a weights tensor.\n \n The L1-norm of a kernel is one way to quantify the \"magnitude\" of the total coeffiecients\n making up this kernel.\n \n Another interesting look at filters is to compute a histogram per filter.\n \"\"\"\n ofms, ifms = weights.size()[0], weights.size()[1]\n kw, kh = weights.size()[2], weights.size()[3]\n kernels = weights.view(ofms * ifms, kh, kw)\n \n if kernels.is_cuda:\n kernels = kernels.cpu()\n \n l1_hist = []\n for kernel in range(ofms*ifms):\n l1_hist.append(kernels[kernel].norm(1))\n return l1_hist\n\ndef plot_l1_norm_hist(weights): \n l1_hist = l1_norm_histogram(weights)\n n, bins, patches = plt.hist(l1_hist, bins=200)\n plt.title('Kernel L1-norm histograms')\n plt.ylabel('Frequency')\n plt.xlabel('Kernel L1-norm')\n plt.show()\n \n\ndef plot_layer_sizes(which, sparse_model, dense_model):\n dense = []\n sparse = []\n names = []\n for name, sparse_weights in sparse_model.state_dict().items():\n if ('weight' not in name) or (which!='*' and which not in name):\n continue \n sparse.append(len(sparse_weights[sparse_weights!=0]))\n names.append(name)\n\n for name, dense_weights in dense_model.state_dict().items():\n if ('weight' not in name) or (which!='*' and which not in name):\n continue\n dense.append(dense_weights.numel())\n\n N = len(sparse)\n ind = np.arange(N) # the x locations for the groups\n\n fig, ax = plt.subplots()\n width = .47\n p1 = plt.bar(ind, dense, width = .47, color = '#278DBC')\n p2 = plt.bar(ind, sparse, width = 0.35, color = '#000099')\n\n plt.ylabel('Size')\n plt.title('Layer sizes')\n plt.xticks(rotation='vertical')\n plt.xticks(ind, names)\n #plt.yticks(np.arange(0, 100, 150))\n plt.legend((p1[0], p2[0]), ('Dense', 'Sparse'))\n\n #Remove plot borders\n for location in ['right', 'left', 'top', 'bottom']:\n ax.spines[location].set_visible(False) \n\n #Fix grid to be horizontal lines only and behind the plots\n ax.yaxis.grid(color='gray', linestyle='solid')\n ax.set_axisbelow(True)\n plt.show()\n \n \ndef conv_param_names(model):\n return [param_name for param_name, p in model.state_dict().items() \n if (p.dim()>2) and (\"weight\" in param_name)]\n\ndef conv_fc_param_names(model):\n return [param_name for param_name, p in model.state_dict().items() \n if (p.dim()>1) and (\"weight\" in param_name)]\n\ndef conv_fc_params(model):\n return [(param_name,p) for (param_name, p) in model.state_dict()\n if (p.dim()>1) and (\"weight\" in param_name)]\n\ndef fc_param_names(model):\n return [param_name for param_name, p in model.state_dict().items() \n if (p.dim()==2) and (\"weight\" in param_name)]", "_____no_output_____" ], [ "def plot_bars(which, setA, setAName, setB, setBName, names, title):\n N = len(setA)\n ind = np.arange(N) # the x locations for the groups\n\n fig, ax = plt.subplots(figsize=(20,10))\n width = .47\n p1 = plt.bar(ind, setA, width = .47, color = '#278DBC')\n p2 = plt.bar(ind, setB, width = 0.35, color = '#000099')\n\n plt.ylabel('Size')\n plt.title(title)\n plt.xticks(rotation='vertical')\n plt.xticks(ind, names)\n #plt.yticks(np.arange(0, 100, 150))\n plt.legend((p1[0], p2[0]), (setAName, setBName))\n\n #Remove plot borders\n for location in ['right', 'left', 'top', 'bottom']:\n ax.spines[location].set_visible(False) \n\n #Fix grid to be horizontal lines only and behind the plots\n ax.yaxis.grid(color='gray', linestyle='solid')\n ax.set_axisbelow(True)\n plt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ] ]
cb0aa8500af8e9bd133424d0f84345a89b2cf991
92,766
ipynb
Jupyter Notebook
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
3132762197d343b0a4891499f9168dad4f925522
[ "MIT" ]
null
null
null
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
3132762197d343b0a4891499f9168dad4f925522
[ "MIT" ]
null
null
null
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
3132762197d343b0a4891499f9168dad4f925522
[ "MIT" ]
null
null
null
208.462921
41,616
0.892223
[ [ [ "# Confounding Example: Finding causal effects from observed data\n\nSuppose you are given some data with treatment and outcome. Can you determine whether the treatment causes the outcome, or is the correlation purely due to another common cause?", "_____no_output_____" ] ], [ [ "import os, sys\nsys.path.append(os.path.abspath(\"../../\"))", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\nimport datasets", "_____no_output_____" ] ], [ [ "# Let's create a mystery dataset. Need to find if there is a causal effect.\n\nCreating the dataset. It is generated from either of two models:\n* **Model 1**: Treatment does cause outcome. \n* **Model 2**: Treatment does not cause outcome. All observed correlation is due to a common cause.", "_____no_output_____" ] ], [ [ "rvar = 1 if np.random.uniform() >0.5 else 0\ndata_dict = datasets.xy_dataset(10000, effect=rvar, sd_error=0.2) \ndf = data_dict['df'] \nprint(df[[\"Treatment\", \"Outcome\", \"w0\"]].head()) \n ", "_____no_output_____" ], [ "dowhy.plotter.plot_treatment_outcome(df[data_dict[\"treatment_name\"]], df[data_dict[\"outcome_name\"]],\n df[data_dict[\"time_val\"]]) ", "_____no_output_____" ] ], [ [ "# Using DoWhy to resolve the mystery: *Does Treatment cause Outcome variable?*\n## STEP 1: Model the problem as a causal graph\nInitializing the causal model.", "_____no_output_____" ] ], [ [ "model= CausalModel( \n data=df, \n treatment=data_dict[\"treatment_name\"], \n outcome=data_dict[\"outcome_name\"], \n common_causes=data_dict[\"common_causes_names\"], \n instruments=data_dict[\"instrument_names\"]) \nmodel.view_model(layout=\"dot\") ", "WARNING:dowhy.do_why:WARN: Causal Graph not provided. DoWhy will construct a graph based on data inputs.\n" ] ], [ [ "<img src=\"causal_model.png\">", "_____no_output_____" ], [ "## STEP 2: Identify causal effect using properties of the formal causal graph\nIdentify the causal effect using properties of the causal graph.", "_____no_output_____" ] ], [ [ "identified_estimand = model.identify_effect()\nprint(identified_estimand)", "INFO:dowhy.causal_identifier:Common causes of treatment and outcome:{'w0', 'U'}\n" ] ], [ [ "## STEP 3: Estimate the causal effect\n\nOnce we have the identified estimand, can use any statistical method to estimate the causal effect. \n\nLet's use Linear Regression for simplicity.", "_____no_output_____" ] ], [ [ "estimate = model.estimate_effect(identified_estimand,\n method_name=\"backdoor.linear_regression\")\nprint(\"Causal Estimate is \" + str(estimate.value))\n\n# Plot Slope of line between treamtent and outcome =causal effect \ndowhy.plotter.plot_causal_effect(estimate, df[data_dict[\"treatment_name\"]], df[data_dict[\"outcome_name\"]])", "LinearRegressionEstimator\n" ] ], [ [ "### Checking if the estimate is correct", "_____no_output_____" ] ], [ [ "print(\"DoWhy estimate is \" + str(estimate.value)) \nprint (\"Actual true causal effect was {0}\".format(rvar))", "DoWhy estimate is 0.004553072035180647\nActual true causal effect was 0\n" ] ], [ [ "## Step 4: Refuting the estimate\n\nWe can also refute the estimate to check its robustness to assumptions (*aka* sensitivity analysis, but on steroids). ", "_____no_output_____" ], [ "### Adding a random common cause variable", "_____no_output_____" ] ], [ [ "res_random=model.refute_estimate(identified_estimand, estimate, method_name=\"random_common_cause\")\nprint(res_random)", "INFO:dowhy.causal_estimator:INFO: Using Linear Regression Estimator\nINFO:dowhy.causal_estimator:b: Outcome~Treatment+w0+w_random\n" ] ], [ [ "### Replacing treatment with a random (placebo) variable", "_____no_output_____" ] ], [ [ "res_placebo=model.refute_estimate(identified_estimand, estimate,\n method_name=\"placebo_treatment_refuter\", placebo_type=\"permute\")\nprint(res_placebo)", "INFO:dowhy.causal_estimator:INFO: Using Linear Regression Estimator\nINFO:dowhy.causal_estimator:b: Outcome~placebo+w0\n" ] ], [ [ "### Removing a random subset of the data", "_____no_output_____" ] ], [ [ "res_subset=model.refute_estimate(identified_estimand, estimate,\n method_name=\"data_subset_refuter\", subset_fraction=0.9)\nprint(res_subset)\n", "INFO:dowhy.causal_estimator:INFO: Using Linear Regression Estimator\nINFO:dowhy.causal_estimator:b: Outcome~Treatment+w0\n" ] ], [ [ "As you can see, our causal estimator is robust to simple refutations.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb0ab75094d5df8967b344d072b0fea62f7174ee
431,384
ipynb
Jupyter Notebook
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
7a76132f80287917a28d0422c09c32dac8926465
[ "MIT" ]
null
null
null
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
7a76132f80287917a28d0422c09c32dac8926465
[ "MIT" ]
null
null
null
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
7a76132f80287917a28d0422c09c32dac8926465
[ "MIT" ]
null
null
null
1,373.834395
107,748
0.957082
[ [ [ "# Identify calibration targets\n\nAttempt to automatically locate the calibration target in each scene. If this fails for any images then the target can be located manually. Note that the automated method only works for scenes containing a single target!\n\nCalibration spectra ( measured radiance vs known reflectance ) are then extracted from the targets and stored in the image .hdr files. ", "_____no_output_____" ] ], [ [ "import os\nimport glob\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nimport hylite\nimport hylite.io as io\nfrom hylite.correct import Panel ", "_____no_output_____" ] ], [ [ "## Define data directories", "_____no_output_____" ] ], [ [ "# input directory containing images to locate (these should all be captured from about the same location)\npath = '/Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc'\nimage_paths = glob.glob( os.path.join(path,\"*.hdr\"), recursive=True )", "_____no_output_____" ], [ "print(\"Found %d images:\" % len(image_paths))\nfor p in image_paths:\n print(p)", "Found 4 images:\n/Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc/0066ELC.hdr\n/Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc/0068ELC.hdr\n/Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc/0067ELC.hdr\n/Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc/0065ELC.hdr\n" ] ], [ [ "## Define calibration panel material", "_____no_output_____" ] ], [ [ "from hylite.reference.spectra import R90, R50, PVC_Red, PVC_White, PVC_Grey # load calibration material spectra\nM = R90 # define calibration panel material", "_____no_output_____" ] ], [ [ "## Attempt to automatically identify targets", "_____no_output_____" ] ], [ [ "for i,p in enumerate(tqdm(image_paths)):\n \n image = io.loadWithGDAL( p ) #load image\n image.set_as_nan(0) # set nans \n \n target = Panel(M,image,method='auto', bands=hylite.RGB) # look for panel\n\n #plot target\n fig,ax = target.quick_plot()\n fig.suptitle(\"%d: %s\" % (i,p))\n fig.show()\n\n #add to header\n image.header.add_panel(target)\n\n #save\n outpath = io.matchHeader(p)[0]\n io.saveHeader(outpath, image.header)", "_____no_output_____" ] ], [ [ "## If necessary, manually pick some targets", "_____no_output_____" ] ], [ [ "assert False, \"Pause here and turn your brain on! ツ\"", "_____no_output_____" ], [ "incorrect = [0,1,2,3] # choose incorrectly identified targets to manually select", "_____no_output_____" ] ], [ [ "First, clear incorrectly set targets from header file.", "_____no_output_____" ] ], [ [ "for i in incorrect:\n image = io.loadWithGDAL( image_paths[i] )\n image.header.remove_panel(None) # remove panels\n outpath = io.matchHeader(image_paths[i])[0]\n io.saveHeader(outpath, image.header)", "_____no_output_____" ] ], [ [ "If targets do exist in scene, manually select them. Skip this step if no targets exist.", "_____no_output_____" ] ], [ [ "targets = []\nfor i in incorrect:\n \n image = io.loadWithGDAL( image_paths[i] ) #load image\n target = Panel(M,image,method='manual',bands=hylite.RGB) # select panel\n \n #add to header\n image.header.add_panel(target)\n\n #save\n outpath = io.matchHeader(image_paths[i])[0]\n io.saveHeader(outpath, image.header)\n \n targets.append(target) # store for plotting", "_____no_output_____" ], [ "#plot targets\n%matplotlib inline\nfor i,t in enumerate(targets):\n #plot target\n fig,ax = t.quick_plot()\n fig.suptitle(\"%d: %s\" % (incorrect[i],image_paths[incorrect[i]]))\n fig.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0ac30c73ccae5762f597024d44006a3df3a9e6
1,002,820
ipynb
Jupyter Notebook
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
d4a52aad36899d25435c329db3041510b039888c
[ "Apache-2.0" ]
1
2018-12-15T20:12:29.000Z
2018-12-15T20:12:29.000Z
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
d4a52aad36899d25435c329db3041510b039888c
[ "Apache-2.0" ]
null
null
null
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
d4a52aad36899d25435c329db3041510b039888c
[ "Apache-2.0" ]
null
null
null
999.820538
284,240
0.939373
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\nNeural Transfer Using PyTorch\n=============================\n\n\n**Author**: `Alexis Jacq <https://alexis-jacq.github.io>`_\n \n**Edited by**: `Winston Herring <https://github.com/winston6>`_\n\n**Re-implemented by:** `Shubhajit Das <https://github.com/Shubhajitml>`\n\nIntroduction\n------------\n\nThis tutorial explains how to implement the `Neural-Style algorithm <https://arxiv.org/abs/1508.06576>`__\ndeveloped by Leon A. Gatys, Alexander S. Ecker and Matthias Bethge.\nNeural-Style, or Neural-Transfer, allows you to take an image and\nreproduce it with a new artistic style. The algorithm takes three images,\nan input image, a content-image, and a style-image, and changes the input \nto resemble the content of the content-image and the artistic style of the style-image.\n\n \n.. figure:: /_static/img/neural-style/neuralstyle.png\n :alt: content1\n\n", "_____no_output_____" ], [ "Underlying Principle\n--------------------\n\nThe principle is simple: we define two distances, one for the content\n($D_C$) and one for the style ($D_S$). $D_C$ measures how different the content\nis between two images while $D_S$ measures how different the style is\nbetween two images. Then, we take a third image, the input, and\ntransform it to minimize both its content-distance with the\ncontent-image and its style-distance with the style-image. Now we can\nimport the necessary packages and begin the neural transfer.\n\nImporting Packages and Selecting a Device\n-----------------------------------------\nBelow is a list of the packages needed to implement the neural transfer.\n\n- ``torch``, ``torch.nn``, ``numpy`` (indispensables packages for\n neural networks with PyTorch)\n- ``torch.optim`` (efficient gradient descents)\n- ``PIL``, ``PIL.Image``, ``matplotlib.pyplot`` (load and display\n images)\n- ``torchvision.transforms`` (transform PIL images into tensors)\n- ``torchvision.models`` (train or load pre-trained models)\n- ``copy`` (to deep copy the models; system package)\n\n", "_____no_output_____" ] ], [ [ "from google.colab import files\n\nuploaded = files.upload()\n\nfor fn in uploaded.keys():\n print('User uploaded file \"{name}\" with length {length} bytes'.format(\n name=fn, length=len(uploaded[fn])))", "_____no_output_____" ], [ "!ls", "colorful.jpg data\t models shubhajit.jpg\ncourse-v3 ml-100k.zip paint.jpg shubha.jpg\n" ], [ "from __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimport torchvision.transforms as transforms\nimport torchvision.models as models\n\nimport copy", "_____no_output_____" ] ], [ [ "Next, we need to choose which device to run the network on and import the\ncontent and style images. Running the neural transfer algorithm on large\nimages takes longer and will go much faster when running on a GPU. We can\nuse ``torch.cuda.is_available()`` to detect if there is a GPU available.\nNext, we set the ``torch.device`` for use throughout the tutorial. Also the ``.to(device)``\nmethod is used to move tensors or modules to a desired device. \n\n", "_____no_output_____" ] ], [ [ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")", "_____no_output_____" ] ], [ [ "Loading the Images\n------------------\n\nNow we will import the style and content images. The original PIL images have values between 0 and 255, but when\ntransformed into torch tensors, their values are converted to be between\n0 and 1. The images also need to be resized to have the same dimensions.\nAn important detail to note is that neural networks from the\ntorch library are trained with tensor values ranging from 0 to 1. If you\ntry to feed the networks with 0 to 255 tensor images, then the activated\nfeature maps will be unable sense the intended content and style.\nHowever, pre-trained networks from the Caffe library are trained with 0\nto 255 tensor images. \n\n\n.. Note::\n Here are links to download the images required to run the tutorial:\n `picasso.jpg <https://pytorch.org/tutorials/_static/img/neural-style/picasso.jpg>`__ and\n `dancing.jpg <https://pytorch.org/tutorials/_static/img/neural-style/dancing.jpg>`__.\n Download these two images and add them to a directory\n with name ``images`` in your current working directory.\n\n", "_____no_output_____" ] ], [ [ "# desired size of the output image\nimsize = 512 if torch.cuda.is_available() else 128 # use small size if no gpu\n\nloader = transforms.Compose([\n transforms.Resize(imsize), # scale imported image\n transforms.ToTensor()]) # transform it into a torch tensor\n\n\ndef image_loader(image_name):\n image = Image.open(image_name)\n # fake batch dimension required to fit network's input dimensions\n image = loader(image).unsqueeze(0)\n return image.to(device, torch.float)\n\n\nstyle_img = image_loader(\"colorful.jpg\")\ncontent_img = image_loader(\"shubha.jpg\")\n\nassert style_img.size() == content_img.size(), \\\n \"we need to import style and content images of the same size\"", "_____no_output_____" ] ], [ [ "Now, let's create a function that displays an image by reconverting a \ncopy of it to PIL format and displaying the copy using \n``plt.imshow``. We will try displaying the content and style images \nto ensure they were imported correctly.\n\n", "_____no_output_____" ] ], [ [ "unloader = transforms.ToPILImage() # reconvert into PIL image\n\nplt.ion()\n\ndef imshow(tensor, title=None):\n image = tensor.cpu().clone() # we clone the tensor to not do changes on it\n image = image.squeeze(0) # remove the fake batch dimension\n image = unloader(image)\n plt.imshow(image)\n if title is not None:\n plt.title(title)\n plt.pause(0.001) # pause a bit so that plots are updated\n\n\nplt.figure()\nimshow(style_img, title='Style Image')\n\nplt.figure()\nimshow(content_img, title='Content Image')", "_____no_output_____" ] ], [ [ "Loss Functions\n--------------\nContent Loss\n~~~~~~~~~~~~\n\nThe content loss is a function that represents a weighted version of the\ncontent distance for an individual layer. The function takes the feature\nmaps $F_{XL}$ of a layer $L$ in a network processing input $X$ and returns the\nweighted content distance $w_{CL}.D_C^L(X,C)$ between the image $X$ and the\ncontent image $C$. The feature maps of the content image($F_{CL}$) must be\nknown by the function in order to calculate the content distance. We\nimplement this function as a torch module with a constructor that takes\n$F_{CL}$ as an input. The distance $\\|F_{XL} - F_{CL}\\|^2$ is the mean square error\nbetween the two sets of feature maps, and can be computed using ``nn.MSELoss``.\n\nWe will add this content loss module directly after the convolution\nlayer(s) that are being used to compute the content distance. This way\neach time the network is fed an input image the content losses will be\ncomputed at the desired layers and because of auto grad, all the\ngradients will be computed. Now, in order to make the content loss layer\ntransparent we must define a ``forward`` method that computes the content\nloss and then returns the layer’s input. The computed loss is saved as a\nparameter of the module.\n\n\n", "_____no_output_____" ] ], [ [ "class ContentLoss(nn.Module):\n\n def __init__(self, target,):\n super(ContentLoss, self).__init__()\n # we 'detach' the target content from the tree used\n # to dynamically compute the gradient: this is a stated value,\n # not a variable. Otherwise the forward method of the criterion\n # will throw an error.\n self.target = target.detach()\n\n def forward(self, input):\n self.loss = F.mse_loss(input, self.target)\n return input", "_____no_output_____" ] ], [ [ ".. Note::\n **Important detail**: although this module is named ``ContentLoss``, it\n is not a true PyTorch Loss function. If you want to define your content\n loss as a PyTorch Loss function, you have to create a PyTorch autograd function \n to recompute/implement the gradient manually in the ``backward``\n method.\n\n", "_____no_output_____" ], [ "Style Loss\n~~~~~~~~~~\n\nThe style loss module is implemented similarly to the content loss\nmodule. It will act as a transparent layer in a\nnetwork that computes the style loss of that layer. In order to\ncalculate the style loss, we need to compute the gram matrix $G_{XL}$. A gram\nmatrix is the result of multiplying a given matrix by its transposed\nmatrix. In this application the given matrix is a reshaped version of\nthe feature maps $F_{XL}$ of a layer $L$. $F_{XL}$ is reshaped to form $\\hat{F}_{XL}$, a $K$\\ x\\ $N$\nmatrix, where $K$ is the number of feature maps at layer $L$ and $N$ is the\nlength of any vectorized feature map $F_{XL}^k$. For example, the first line\nof $\\hat{F}_{XL}$ corresponds to the first vectorized feature map $F_{XL}^1$.\n\nFinally, the gram matrix must be normalized by dividing each element by\nthe total number of elements in the matrix. This normalization is to\ncounteract the fact that $\\hat{F}_{XL}$ matrices with a large $N$ dimension yield\nlarger values in the Gram matrix. These larger values will cause the\nfirst layers (before pooling layers) to have a larger impact during the\ngradient descent. Style features tend to be in the deeper layers of the\nnetwork so this normalization step is crucial.\n\n\n", "_____no_output_____" ] ], [ [ "def gram_matrix(input):\n a, b, c, d = input.size() # a=batch size(=1)\n # b=number of feature maps\n # (c,d)=dimensions of a f. map (N=c*d)\n\n features = input.view(a * b, c * d) # resise F_XL into \\hat F_XL\n\n G = torch.mm(features, features.t()) # compute the gram product\n\n # we 'normalize' the values of the gram matrix\n # by dividing by the number of element in each feature maps.\n return G.div(a * b * c * d)", "_____no_output_____" ] ], [ [ "Now the style loss module looks almost exactly like the content loss\nmodule. The style distance is also computed using the mean square\nerror between $G_{XL}$ and $G_{SL}$.\n\n\n", "_____no_output_____" ] ], [ [ "class StyleLoss(nn.Module):\n\n def __init__(self, target_feature):\n super(StyleLoss, self).__init__()\n self.target = gram_matrix(target_feature).detach()\n\n def forward(self, input):\n G = gram_matrix(input)\n self.loss = F.mse_loss(G, self.target)\n return input", "_____no_output_____" ] ], [ [ "Importing the Model\n-------------------\n\nNow we need to import a pre-trained neural network. We will use a 19\nlayer VGG network like the one used in the paper.\n\nPyTorch’s implementation of VGG is a module divided into two child\n``Sequential`` modules: ``features`` (containing convolution and pooling layers),\nand ``classifier`` (containing fully connected layers). We will use the\n``features`` module because we need the output of the individual\nconvolution layers to measure content and style loss. Some layers have\ndifferent behavior during training than evaluation, so we must set the\nnetwork to evaluation mode using ``.eval()``.\n\n\n", "_____no_output_____" ] ], [ [ "cnn = models.vgg19(pretrained=True).features.to(device).eval()", "Downloading: \"https://download.pytorch.org/models/vgg19-dcbb9e9d.pth\" to /root/.torch/models/vgg19-dcbb9e9d.pth\n100%|██████████| 574673361/574673361 [00:08<00:00, 70914944.30it/s]\n" ] ], [ [ "Additionally, VGG networks are trained on images with each channel\nnormalized by mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225].\nWe will use them to normalize the image before sending it into the network.\n\n\n", "_____no_output_____" ] ], [ [ "cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)\ncnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)\n\n# create a module to normalize input image so we can easily put it in a\n# nn.Sequential\nclass Normalization(nn.Module):\n def __init__(self, mean, std):\n super(Normalization, self).__init__()\n # .view the mean and std to make them [C x 1 x 1] so that they can\n # directly work with image Tensor of shape [B x C x H x W].\n # B is batch size. C is number of channels. H is height and W is width.\n self.mean = torch.tensor(mean).view(-1, 1, 1)\n self.std = torch.tensor(std).view(-1, 1, 1)\n\n def forward(self, img):\n # normalize img\n return (img - self.mean) / self.std", "_____no_output_____" ] ], [ [ "A ``Sequential`` module contains an ordered list of child modules. For\ninstance, ``vgg19.features`` contains a sequence (Conv2d, ReLU, MaxPool2d,\nConv2d, ReLU…) aligned in the right order of depth. We need to add our\ncontent loss and style loss layers immediately after the convolution\nlayer they are detecting. To do this we must create a new ``Sequential``\nmodule that has content loss and style loss modules correctly inserted.\n\n\n", "_____no_output_____" ] ], [ [ "# desired depth layers to compute style/content losses :\ncontent_layers_default = ['conv_4']\nstyle_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']\n\ndef get_style_model_and_losses(cnn, normalization_mean, normalization_std,\n style_img, content_img,\n content_layers=content_layers_default,\n style_layers=style_layers_default):\n cnn = copy.deepcopy(cnn)\n\n # normalization module\n normalization = Normalization(normalization_mean, normalization_std).to(device)\n\n # just in order to have an iterable access to or list of content/syle\n # losses\n content_losses = []\n style_losses = []\n\n # assuming that cnn is a nn.Sequential, so we make a new nn.Sequential\n # to put in modules that are supposed to be activated sequentially\n model = nn.Sequential(normalization)\n\n i = 0 # increment every time we see a conv\n for layer in cnn.children():\n if isinstance(layer, nn.Conv2d):\n i += 1\n name = 'conv_{}'.format(i)\n elif isinstance(layer, nn.ReLU):\n name = 'relu_{}'.format(i)\n # The in-place version doesn't play very nicely with the ContentLoss\n # and StyleLoss we insert below. So we replace with out-of-place\n # ones here.\n layer = nn.ReLU(inplace=False)\n elif isinstance(layer, nn.MaxPool2d):\n name = 'pool_{}'.format(i)\n elif isinstance(layer, nn.BatchNorm2d):\n name = 'bn_{}'.format(i)\n else:\n raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))\n\n model.add_module(name, layer)\n\n if name in content_layers:\n # add content loss:\n target = model(content_img).detach()\n content_loss = ContentLoss(target)\n model.add_module(\"content_loss_{}\".format(i), content_loss)\n content_losses.append(content_loss)\n\n if name in style_layers:\n # add style loss:\n target_feature = model(style_img).detach()\n style_loss = StyleLoss(target_feature)\n model.add_module(\"style_loss_{}\".format(i), style_loss)\n style_losses.append(style_loss)\n\n # now we trim off the layers after the last content and style losses\n for i in range(len(model) - 1, -1, -1):\n if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):\n break\n\n model = model[:(i + 1)]\n\n return model, style_losses, content_losses", "_____no_output_____" ] ], [ [ "Next, we select the input image. You can use a copy of the content image\nor white noise.\n\n\n", "_____no_output_____" ] ], [ [ "input_img = content_img.clone()\n# if you want to use white noise instead uncomment the below line:\n# input_img = torch.randn(content_img.data.size(), device=device)\n\n# add the original input image to the figure:\nplt.figure()\nimshow(input_img, title='Input Image')", "_____no_output_____" ] ], [ [ "Gradient Descent\n----------------\n\nAs Leon Gatys, the author of the algorithm, suggested `here <https://discuss.pytorch.org/t/pytorch-tutorial-for-neural-transfert-of-artistic-style/336/20?u=alexis-jacq>`__, we will use\nL-BFGS algorithm to run our gradient descent. Unlike training a network,\nwe want to train the input image in order to minimise the content/style\nlosses. We will create a PyTorch L-BFGS optimizer ``optim.LBFGS`` and pass\nour image to it as the tensor to optimize.\n\n\n", "_____no_output_____" ] ], [ [ "def get_input_optimizer(input_img):\n # this line to show that input is a parameter that requires a gradient\n optimizer = optim.LBFGS([input_img.requires_grad_()])\n return optimizer", "_____no_output_____" ] ], [ [ "Finally, we must define a function that performs the neural transfer. For\neach iteration of the networks, it is fed an updated input and computes\nnew losses. We will run the ``backward`` methods of each loss module to\ndynamicaly compute their gradients. The optimizer requires a “closure”\nfunction, which reevaluates the modul and returns the loss.\n\nWe still have one final constraint to address. The network may try to\noptimize the input with values that exceed the 0 to 1 tensor range for\nthe image. We can address this by correcting the input values to be\nbetween 0 to 1 each time the network is run.\n\n\n", "_____no_output_____" ] ], [ [ "def run_style_transfer(cnn, normalization_mean, normalization_std,\n content_img, style_img, input_img, num_steps=500,\n style_weight=1000000, content_weight=1):\n \"\"\"Run the style transfer.\"\"\"\n print('Building the style transfer model..')\n model, style_losses, content_losses = get_style_model_and_losses(cnn,\n normalization_mean, normalization_std, style_img, content_img)\n optimizer = get_input_optimizer(input_img)\n\n print('Optimizing..')\n run = [0]\n while run[0] <= num_steps:\n\n def closure():\n # correct the values of updated input image\n input_img.data.clamp_(0, 1)\n\n optimizer.zero_grad()\n model(input_img)\n style_score = 0\n content_score = 0\n\n for sl in style_losses:\n style_score += sl.loss\n for cl in content_losses:\n content_score += cl.loss\n\n style_score *= style_weight\n content_score *= content_weight\n\n loss = style_score + content_score\n loss.backward()\n\n run[0] += 1\n if run[0] % 50 == 0:\n print(\"run {}:\".format(run))\n print('Style Loss : {:4f} Content Loss: {:4f}'.format(\n style_score.item(), content_score.item()))\n print()\n\n return style_score + content_score\n\n optimizer.step(closure)\n\n # a last correction...\n input_img.data.clamp_(0, 1)\n\n return input_img", "_____no_output_____" ] ], [ [ "Finally, we can run the algorithm.\n\n\n", "_____no_output_____" ] ], [ [ "output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,\n content_img, style_img, input_img)\n\nplt.figure()\nimshow(output, title='Output Image')\n\n# sphinx_gallery_thumbnail_number = 4\nplt.ioff()\nplt.show()\n", "Building the style transfer model..\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" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "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" ] ]
cb0acea0575a23ee3d6df7d1913b61e6d9cd4940
27,859
ipynb
Jupyter Notebook
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
6c7e369f4447808eb1ded1a709f3ca841f3fabd1
[ "MIT" ]
null
null
null
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
6c7e369f4447808eb1ded1a709f3ca841f3fabd1
[ "MIT" ]
null
null
null
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
6c7e369f4447808eb1ded1a709f3ca841f3fabd1
[ "MIT" ]
null
null
null
27,859
27,859
0.804264
[ [ [ "## Linear Regression\r\n\r\n### PyTorch Model Designing Steps\r\n\r\n1. **Design your model using class with Variables**\r\n2. **Construct loss and optimizer (select from PyTorch API)**\r\n3. **Training cycle (forward, backward, update)**", "_____no_output_____" ], [ "### Step #1 : Design your model using class with Variables", "_____no_output_____" ] ], [ [ "from torch import nn\r\nimport torch\r\nfrom torch import tensor\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nx_data = tensor([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]])\r\ny_data = tensor([[2.0], [4.0], [6.0], [8.0], [10.0], [12.0]])\r\n\r\n# Hyper-parameters\r\ninput_size = 1\r\noutput_size = 1\r\nnum_epochs = 100\r\nlearning_rate = 0.01", "_____no_output_____" ], [ "print(torch.__version__)\r\n\r\nprint(torch.cuda.get_device_name())", "1.7.0+cu101\nTesla T4\n" ] ], [ [ "### Using GPU for the PyTorch Models\r\n\r\nRemember always 2 things must be on GPU\r\n\r\n- model\r\n- tensors", "_____no_output_____" ] ], [ [ "class Model(nn.Module):\r\n def __init__(self):\r\n \"\"\"\r\n In the constructor we instantiate nn.Linear module\r\n \"\"\"\r\n super().__init__()\r\n self.linear = torch.nn.Linear(input_size, output_size) # One in and one out\r\n\r\n def forward(self, x):\r\n \"\"\"\r\n In the forward function we accept a Variable of input data and we must return\r\n a Variable of output data. We can use Modules defined in the constructor as\r\n well as arbitrary operators on Variables.\r\n \"\"\"\r\n y_pred = self.linear(x)\r\n return y_pred\r\n\r\n\r\n# our model\r\nmodel = Model()\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\nmodel.to(device)", "_____no_output_____" ] ], [ [ "### Explanations:- \r\n\r\n`torch.nn.Linear(in_features, out_features, bias=True)`\r\n\r\nApplies a linear transformation to the incoming data: $y = W^T * x + b$\r\n\r\n**Parameters:**\r\n\r\n- `in_features `– size of each input sample (i.e. size of x)\r\n- `out_features` – size of each output sample (i.e. size of y)\r\n- `bias` – If set to False, the layer will not learn an additive bias. **Default: True**\r\n", "_____no_output_____" ], [ "###Step #2 : Construct loss and optimizer (select from PyTorch API)", "_____no_output_____" ] ], [ [ "# Construct our loss function and an Optimizer. The call to model.parameters()\r\n# in the SGD constructor will contain the learnable parameters\r\ncriterion = torch.nn.MSELoss(reduction='sum')\r\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)", "_____no_output_____" ] ], [ [ "### Explanations:- \r\n\r\nMSE Loss: Mean Squared Error (**Default: 'mean'**)\r\n\r\n- $\\hat y$ : prediction\r\n- $y$ : true value\r\n\r\n$MSE \\ (sum) = \\sum_{i=1}^n(\\hat y_i - y_i)^2$\r\n\r\n$MSE \\ (mean) = \\frac{1}{n} \\sum_{i=1}^n(\\hat y_i - y_i)^2$", "_____no_output_____" ], [ "###Step #3 : Training: forward, loss, backward, step", "_____no_output_____" ] ], [ [ "# Credit: https://github.com/jcjohnson/pytorch-examples\r\n\r\n# Training loop\r\nfor epoch in range(num_epochs):\r\n # 1) Forward pass: Compute predicted y by passing x to the model\r\n y_pred = model(x_data.to(device))\r\n\r\n # 2) Compute and print loss\r\n loss = criterion(y_pred, y_data.to(device))\r\n print(f'Epoch: {epoch} | Loss: {loss.item()} ')\r\n\r\n # Zero gradients, perform a backward pass, and update the weights.\r\n optimizer.zero_grad()\r\n # Getting gradients w.r.t. parameters\r\n loss.backward()\r\n # Updating parameters\r\n optimizer.step()\r\n\r\n\r\n# After training\r\nhour_var = tensor([[7.0]]).to(device)\r\ny_pred = model(hour_var)\r\nprint(\"Prediction (after training)\", 7, model(hour_var).data[0][0].item())", "Epoch: 0 | Loss: 0.04414632171392441 \nEpoch: 1 | Loss: 0.037211932241916656 \nEpoch: 2 | Loss: 0.03136666119098663 \nEpoch: 3 | Loss: 0.02643958479166031 \nEpoch: 4 | Loss: 0.022286424413323402 \nEpoch: 5 | Loss: 0.01878545433282852 \nEpoch: 6 | Loss: 0.015834316611289978 \nEpoch: 7 | Loss: 0.013346947729587555 \nEpoch: 8 | Loss: 0.011250494979321957 \nEpoch: 9 | Loss: 0.00948311947286129 \nEpoch: 10 | Loss: 0.007993534207344055 \nEpoch: 11 | Loss: 0.006737751420587301 \nEpoch: 12 | Loss: 0.005679425783455372 \nEpoch: 13 | Loss: 0.00478725228458643 \nEpoch: 14 | Loss: 0.004035332705825567 \nEpoch: 15 | Loss: 0.0034015250857919455 \nEpoch: 16 | Loss: 0.0028671536128968 \nEpoch: 17 | Loss: 0.002416762989014387 \nEpoch: 18 | Loss: 0.002037121681496501 \nEpoch: 19 | Loss: 0.001717082574032247 \nEpoch: 20 | Loss: 0.0014473588671535254 \nEpoch: 21 | Loss: 0.0012200772762298584 \nEpoch: 22 | Loss: 0.0010285326279699802 \nEpoch: 23 | Loss: 0.0008669731905683875 \nEpoch: 24 | Loss: 0.0007308223284780979 \nEpoch: 25 | Loss: 0.0006160807679407299 \nEpoch: 26 | Loss: 0.0005193640245124698 \nEpoch: 27 | Loss: 0.0004377948062028736 \nEpoch: 28 | Loss: 0.00036905714659951627 \nEpoch: 29 | Loss: 0.00031109602423384786 \nEpoch: 30 | Loss: 0.0002622445463202894 \nEpoch: 31 | Loss: 0.00022103048104327172 \nEpoch: 32 | Loss: 0.00018631585408002138 \nEpoch: 33 | Loss: 0.00015708355931565166 \nEpoch: 34 | Loss: 0.00013243967259768397 \nEpoch: 35 | Loss: 0.0001116378916776739 \nEpoch: 36 | Loss: 9.413070802111179e-05 \nEpoch: 37 | Loss: 7.938130875118077e-05 \nEpoch: 38 | Loss: 6.693360774079338e-05 \nEpoch: 39 | Loss: 5.643032636726275e-05 \nEpoch: 40 | Loss: 4.7579771489836276e-05 \nEpoch: 41 | Loss: 4.012114368379116e-05 \nEpoch: 42 | Loss: 3.3833723136922345e-05 \nEpoch: 43 | Loss: 2.8520098567241803e-05 \nEpoch: 44 | Loss: 2.4056535039562732e-05 \nEpoch: 45 | Loss: 2.0292434783186764e-05 \nEpoch: 46 | Loss: 1.7130943888332695e-05 \nEpoch: 47 | Loss: 1.4457059478445444e-05 \nEpoch: 48 | Loss: 1.2199224329378922e-05 \nEpoch: 49 | Loss: 1.0295959327777382e-05 \nEpoch: 50 | Loss: 8.68849383550696e-06 \nEpoch: 51 | Loss: 7.3387905104027595e-06 \nEpoch: 52 | Loss: 6.202298209245782e-06 \nEpoch: 53 | Loss: 5.237749519437784e-06 \nEpoch: 54 | Loss: 4.4233556764083914e-06 \nEpoch: 55 | Loss: 3.7351574064814486e-06 \nEpoch: 56 | Loss: 3.1560714432998793e-06 \nEpoch: 57 | Loss: 2.668224851731793e-06 \nEpoch: 58 | Loss: 2.257534788441262e-06 \nEpoch: 59 | Loss: 1.913428150146501e-06 \nEpoch: 60 | Loss: 1.6214072502407362e-06 \nEpoch: 61 | Loss: 1.3771661997452611e-06 \nEpoch: 62 | Loss: 1.1682066087814746e-06 \nEpoch: 63 | Loss: 9.905502338369843e-07 \nEpoch: 64 | Loss: 8.425095643360692e-07 \nEpoch: 65 | Loss: 7.173612743827107e-07 \nEpoch: 66 | Loss: 6.105864258643123e-07 \nEpoch: 67 | Loss: 5.207971867093875e-07 \nEpoch: 68 | Loss: 4.4541320676216856e-07 \nEpoch: 69 | Loss: 3.8081543607404456e-07 \nEpoch: 70 | Loss: 3.2628258850309066e-07 \nEpoch: 71 | Loss: 2.807912551361369e-07 \nEpoch: 72 | Loss: 2.4094634909488377e-07 \nEpoch: 73 | Loss: 2.0819703649976873e-07 \nEpoch: 74 | Loss: 1.800950144570379e-07 \nEpoch: 75 | Loss: 1.5580013723592856e-07 \nEpoch: 76 | Loss: 1.3530416254070587e-07 \nEpoch: 77 | Loss: 1.1766678653657436e-07 \nEpoch: 78 | Loss: 1.0277517503709532e-07 \nEpoch: 79 | Loss: 9.065848871614435e-08 \nEpoch: 80 | Loss: 8.004781193449162e-08 \nEpoch: 81 | Loss: 7.053864692352363e-08 \nEpoch: 82 | Loss: 6.230408189367154e-08 \nEpoch: 83 | Loss: 5.544825398828834e-08 \nEpoch: 84 | Loss: 4.978483048034832e-08 \nEpoch: 85 | Loss: 4.4602586513065035e-08 \nEpoch: 86 | Loss: 4.0317047478310997e-08 \nEpoch: 87 | Loss: 3.653326530184131e-08 \nEpoch: 88 | Loss: 3.3295236789854243e-08 \nEpoch: 89 | Loss: 3.051195562875364e-08 \nEpoch: 90 | Loss: 2.799265530484263e-08 \nEpoch: 91 | Loss: 2.564371470725746e-08 \nEpoch: 92 | Loss: 2.373735696892254e-08 \nEpoch: 93 | Loss: 2.1766993540950352e-08 \nEpoch: 94 | Loss: 2.0134905298618833e-08 \nEpoch: 95 | Loss: 1.8830178305506706e-08 \nEpoch: 96 | Loss: 1.7476622815593146e-08 \nEpoch: 97 | Loss: 1.637459945413866e-08 \nEpoch: 98 | Loss: 1.544805172670749e-08 \nEpoch: 99 | Loss: 1.4453007679549046e-08 \nPrediction (after training) 7 13.99990463256836\n" ] ], [ [ "### Explanations:- \r\n\r\n- Calling `.backward()` mutiple times accumulates the gradient (**by addition**) for each parameter. \r\n\r\n- This is why you should call `optimizer.zero_grad()` after each .step() call. \r\n\r\n- Note that following the first `.backward` call, a second call is only possible after you have performed another **forward pass**.\r\n\r\n- `optimizer.step` performs a parameter update based on the current gradient (**stored in .grad attribute of a parameter**)\r\n\r\n### Simplified equation:-\r\n\r\n- `parameters = parameters - learning_rate * parameters_gradients`\r\n- parameters $W$ and $b$ in ($y = W^T * x + b$)\r\n- $\\theta = \\theta - \\eta \\cdot \\nabla_\\theta$ [ General parameter $\\theta$ ]\r\n * $\\theta$ : parameters (our variables)\r\n * $\\eta$ : learning rate (how fast we want to learn)\r\n * $\\nabla_\\theta$ : parameters' gradients\r\n\r\n ", "_____no_output_____" ], [ "### Plot of predicted and actual values", "_____no_output_____" ] ], [ [ "# Clear figure\r\nplt.clf()\r\n\r\n# Get predictions\r\npredictions = model(x_data.to(device)).cpu().detach().numpy()\r\n\r\n# Plot true data\r\nplt.plot(x_data, y_data, 'go', label='True data', alpha=0.5)\r\n\r\n# Plot predictions\r\nplt.plot(x_data, predictions, '--', label='Predictions', alpha=0.5)\r\n\r\n# Legend and plot\r\nplt.legend(loc='best')\r\nplt.show()", "_____no_output_____" ] ], [ [ "### Saving Model to Directory ", "_____no_output_____" ] ], [ [ "from google.colab import drive\r\n\r\ndrive.mount('/content/gdrive')\r\n\r\nroot_path = '/content/gdrive/My Drive/AUST Docs/AUST Teaching Docs/AUST Spring 2020/CSE 4238/Lab 02/'", "Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount(\"/content/gdrive\", force_remount=True).\n" ] ], [ [ "### Save Model", "_____no_output_____" ] ], [ [ "save_model = True\r\n\r\nif save_model is True:\r\n # Saves only parameters\r\n # wights & biases\r\n torch.save(model.state_dict(), root_path + 'linear_regression.pkl') \r\n\r\n# Save the model checkpoint \r\n# torch.save(model.state_dict(), root_path + 'linear_regression.ckpt')\r\n", "_____no_output_____" ] ], [ [ "### Load Model", "_____no_output_____" ] ], [ [ "load_model = True\r\n\r\nif load_model is True:\r\n model.load_state_dict(torch.load(root_path + 'linear_regression.pkl'))", "_____no_output_____" ] ], [ [ "### Try Other Optimizers\r\n\r\n- torch.optim.Adagrad\r\n- torch.optim.Adam\r\n- torch.optim.Adamax\r\n- torch.optim.ASGD\r\n- torch.optim.LBFGS\r\n- torch.optim.RMSprop\r\n- torch.optim.Rprop\r\n- torch.optim.SGD\r\n", "_____no_output_____" ], [ "### *** Official PyTorch Tutorials ***\r\n\r\nhttps://pytorch.org/tutorials/", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb0ad71df03eecf6afc26a23690e31b26c5b6f95
557,436
ipynb
Jupyter Notebook
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
2c37f146a9900340b686ba4d1bbb84980053e461
[ "MIT" ]
null
null
null
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
2c37f146a9900340b686ba4d1bbb84980053e461
[ "MIT" ]
null
null
null
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
2c37f146a9900340b686ba4d1bbb84980053e461
[ "MIT" ]
null
null
null
327.325895
456,572
0.911231
[ [ [ "# **Blockchain Analytics**\nAnalysis of Bitcoin blockchain data (transaction graph) to find potential indicators of incidents\n\n_by Dhruv Chopra and Siddhant Pathak_", "_____no_output_____" ], [ "## **Import all the necessary libraries**\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport networkx as nx\nimport time\nimport requests\nsb.set()", "_____no_output_____" ] ], [ [ "## **Query the data from the Blockchain API and organize it**\n", "_____no_output_____" ] ], [ [ "response = requests.get(\"https://blockchain.info/rawtx/0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098\")\njason = response.json()", "_____no_output_____" ], [ "#response = requests.get(\"https://blockchain.info/q/getreceivedbyaddress/12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\")", "_____no_output_____" ], [ "jason", "_____no_output_____" ], [ "new = jason['out'][0]['addr']", "_____no_output_____" ], [ "new", "_____no_output_____" ], [ "response = requests.get(\"https://blockchain.info/rawaddr/\"+new)", "_____no_output_____" ], [ "transactions = response.json()", "_____no_output_____" ], [ "transactions", "_____no_output_____" ], [ "rev = transactions['txs']\nrev.reverse()\nfor i in rev:\n print(i['block_height'])", "_____no_output_____" ] ], [ [ "## **Creating the graph**", "_____no_output_____" ] ], [ [ "stack1 = []\nstack2 = []\ng = nx.MultiDiGraph()\n\naddress='12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX'\nstack1\nstack1.append(address)\n\ncolor=[]\nedge_color=[]\ncompleted = []\nlevel = 0\nLEVEL = 10\n\nwhile(level < LEVEL):\n address = stack1.pop()\n response = requests.get(\"https://blockchain.info/rawaddr/\"+address)\n address_info = response.json()\n \n transactions = address_info['txs']\n transactions.reverse()\n\n for i in transactions:\n if(i['hash'] not in completed):\n completed.append(i['hash'])\n #g.add_edge(address,i['hash'],weight = i['weight'])\n for j in i[\"inputs\"]:\n \n if j['prev_out']['addr'] not in g:\n color.append('blue')\n if i['hash'] not in g:\n color.append('red')\n edge_color.append('purple') \n g.add_edge(j['prev_out'][\"addr\"],i['hash'], weight = j['prev_out']['value']*0.00000001)\n stack2.append(j['prev_out'][\"addr\"])\n \n for j in i[\"out\"]:\n \n if i['hash'] not in g:\n color.append('red')\n if j['addr'] not in g:\n color.append('blue')\n edge_color.append('green')\n g.add_edge(i['hash'],j[\"addr\"], weight = j['value']*0.00000001)\n stack2.append(j['addr'])\n \n break\n \n if(len(stack1)==0):\n stack1 = stack2\n level = level +1\n \n time.sleep(8.5)", "_____no_output_____" ] ], [ [ "## **Store the graph**", "_____no_output_____" ] ], [ [ "nx.write_edgelist(g, path = \"graph.csv\", delimiter=\":\")", "_____no_output_____" ], [ "plt.figure(4, figsize=(50,50))\npos = nx.spring_layout(g, center=None, dim=2)\nnx.draw_networkx(g,pos=pos, node_size=99, edge_color=edge_color, node_color=color, width=2.5, with_labels=False)\n#labels = nx.get_edge_attributes(g,'weight')\n#nx.draw_networkx_edge_labels(g,pos)\nplt.show()", "_____no_output_____" ], [ "plt.savefig(\"graph.png\")", "_____no_output_____" ] ], [ [ "# **Centrality**", "_____no_output_____" ], [ "## **VoteRank Algorithm**\nVoteRank computes a ranking of the nodes in a graph G based on a voting scheme. With VoteRank, all nodes vote for each of its in-neighbours and the node with the highest votes is elected iteratively. The voting ability of out-neighbors of elected nodes is decreased in subsequent turns.\n", "_____no_output_____" ] ], [ [ "node_voterank = nx.algorithms.centrality.voterank(g)\nnode_voterank", "_____no_output_____" ] ], [ [ "## **Percolation Centrality** (error)\nPercolation centrality of a node v, at a given time, is defined as the proportion of ‘percolated paths’ that go through that node. This measure quantifies relative impact of nodes based on their topological connectivity, as well as their percolation states. Percolation states of nodes are used to depict network percolation scenarios (such as during infection transmission in a social network of individuals, spreading of computer viruses on computer networks, or transmission of disease over a network of towns) over time. In this measure usually the percolation state is expressed as a decimal between 0.0 and 1.0.", "_____no_output_____" ] ], [ [ "node_percolation = nx.algorithms.centrality.percolation_centrality(g)\nnode_percolation", "_____no_output_____" ] ], [ [ "## **PageRank Algorithm** (error)\nPageRank is an algorithm used by Google Search to rank web pages in their search engine results. PageRank is a way of measuring the importance of website pages.", "_____no_output_____" ] ], [ [ "node_pagerank = nx.algorithms.link_analysis.pagerank_alg.pagerank(g)\nnode_pagerank ", "_____no_output_____" ] ], [ [ "## **Degree of Nodes**\n`degree_centrality(G)` : Compute the degree centrality for nodes.\n\n`in_degree_centrality(G)` : Compute the in-degree centrality for nodes.\n\n`out_degree_centrality(G)` : Compute the out-degree centrality for nodes.", "_____no_output_____" ] ], [ [ "node_degree = nx.degree_centrality(g)\nnode_deg_in = nx.in_degree_centrality(g)\nnode_deg_out = nx.out_degree_centrality(g)", "_____no_output_____" ], [ "node_degree", "_____no_output_____" ], [ "node_deg_in", "_____no_output_____" ], [ "node_deg_out", "_____no_output_____" ] ], [ [ "## **Eigenvector and Katz Centrality** (error)\nKatz centrality is a generalization of degree centrality. Degree centrality measures the number of direct neighbors, and Katz centrality measures the number of all nodes that can be connected through a path, while the contributions of distant nodes are penalized. ", "_____no_output_____" ] ], [ [ "node_eigen = nx.eigenvector_centrality(g)\nnode_eigen", "_____no_output_____" ], [ "node_katz = nx.katz_centrality(g)\nnode_katz", "_____no_output_____" ] ], [ [ "## **Closeness**\n`closeness_centrality(G[, u, distance, …])` : Compute closeness centrality for nodes.\n\n`incremental_closeness_centrality(G, edge[, …])`: Incremental closeness centrality for nodes.\n\nNotice that higher values of closeness indicate higher centrality.", "_____no_output_____" ] ], [ [ "node_close = nx.closeness_centrality(g)\nnode_close", "_____no_output_____" ], [ "node_close_inc = nx.incremental_closeness_centrality(g, edge = ('1Ep8AVZx89qmBzzeu1zPpKLF8pxHfkZaJc', '56484b549f42a4485fb79b2838c7829805d025a28a46248eec677aaba78e4b70') )", "_____no_output_____" ] ], [ [ "## **Current Flow Closeness** (error)\nCompute current-flow closeness centrality for nodes.\n", "_____no_output_____" ] ], [ [ "node_cur = nx.current_flow_closeness_centrality(g)", "_____no_output_____" ], [ "node_cur_info = nx.information_centrality(g)", "_____no_output_____" ] ], [ [ "## **Dispersion**\nCalculate dispersion between u and v in G.\n\nA link between two actors (u and v) has a high dispersion when their mutual ties (s and t) are not well connected with each other.\n\nIf u (v) is specified, returns a dictionary of nodes with dispersion score for all “target” (“source”) nodes. If neither u nor v is specified, returns a dictionary of dictionaries for all nodes ‘u’ in the graph with a dispersion score for each node ‘v’.", "_____no_output_____" ] ], [ [ "dispersion = nx.dispersion(g)\ndispersion", "_____no_output_____" ] ], [ [ "## **Harmonic Centrality**\nHarmonic centrality of a node u is the sum of the reciprocal of the shortest path distances from all other nodes to u.", "_____no_output_____" ] ], [ [ "harmonic = nx.harmonic_centrality(g)\nharmonic", "_____no_output_____" ] ], [ [ "## **Reaching**\n`local_reaching_centrality(G, v[, paths, …])` : Returns the local reaching centrality of a node in a directed graph. The local reaching centrality of a node in a directed graph is the proportion of other nodes reachable from that node\n\n`global_reaching_centrality(G[, weight, …]`) : Returns the global reaching centrality of a directed graph. The global reaching centrality of a weighted directed graph is the average over all nodes of the difference between the local reaching centrality of the node and the greatest local reaching centrality of any node in the graph.\n\n", "_____no_output_____" ] ], [ [ "global_reach = nx.global_reaching_centrality(g)\nglobal_reach", "_____no_output_____" ] ], [ [ "## **Second Order Centrality** (error)\nThe second order centrality of a given node is the standard deviation of the return times to that node of a perpetual random walk on G:\n\n", "_____no_output_____" ] ], [ [ "node_2nd_order = nx.second_order_centrality(g)\nnode_2nd_order", "_____no_output_____" ] ], [ [ "## **Trophic** (2 error)\n`trophic_levels(G[, weight])` : Compute the trophic levels of nodes.\n\n`trophic_differences(G[, weight])` : Compute the trophic differences of the edges of a directed graph.\n\n`trophic_incoherence_parameter(G[, weight, …])` : Compute the trophic incoherence parameter of a graph.\n", "_____no_output_____" ] ], [ [ "trophic = nx.trophic_levels(g)\ntrophic", "_____no_output_____" ], [ "trophic_differences = nx.trophic_differences(g)", "_____no_output_____" ], [ "incoherence = nx.trophic_incoherence_parameter(g)", "_____no_output_____" ] ], [ [ "## **Subgraph** (error)\n`subgraph_centrality(G)` : Returns subgraph centrality for each node in G.\n\n`subgraph_centrality_exp(G)` : Returns the subgraph centrality for each node of G.\n\n`estrada_index(G) `: Returns the Estrada index of a the graph G.\n", "_____no_output_____" ] ], [ [ "subgraph = nx.subgraph_centrality(g)\nsubgraph", "_____no_output_____" ], [ "sub_exp = nx.subgraph_centrality_exp(g)\nsub_exp", "_____no_output_____" ], [ "estrada = nx.estrada_index(g)", "_____no_output_____" ] ], [ [ "## **Load** \nThe load centrality of a node is the fraction of all shortest paths that pass through that node.\n", "_____no_output_____" ] ], [ [ "load = nx.load_centrality(g)\nload", "_____no_output_____" ], [ "edge_load = nx.edge_load_centrality(g)\nedge_load", "_____no_output_____" ] ], [ [ "## **Group Centrality** (error)\n`group_betweenness_centrality(G, C[, …])`: Compute the group betweenness centrality for a group of nodes.\n\n`group_closeness_centrality(G, S[, weight])`: Compute the group closeness centrality for a group of nodes.\n\n`group_degree_centrality(G, S)`: Compute the group degree centrality for a group of nodes.\n\n`group_in_degree_centrality(G, S)`: Compute the group in-degree centrality for a group of nodes.\n\n`group_out_degree_centrality(G, S)`: Compute the group out-degree centrality for a group of nodes.", "_____no_output_____" ] ], [ [ "gp_btw = nx.group_betweenness_centrality(g, C=g.nodes)\ngp_btw", "_____no_output_____" ], [ "gp_close = nx.group_closeness_centrality(g,S=g.nodes)\ngp_close", "_____no_output_____" ], [ "gp_deg = nx.group_degree_centrality(g, g.nodes)", "_____no_output_____" ], [ "gp_in = nx.group_in_degree_centrality(g, g.nodes)\ngp_in", "_____no_output_____" ], [ "gp_out = nx.group_out_degree_centrality(g, g.nodes)\ngp_out", "_____no_output_____" ] ], [ [ "## **Communicability Betweenness** (error)\nCommunicability betweenness measure makes use of the number of walks connecting every pair of nodes as the basis of a betweenness centrality measure.", "_____no_output_____" ] ], [ [ "comm_btw = nx.communicability_betweenness_centrality(g)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cb0ae7ba8c2569747bce0665db40f4f828be77f2
374,586
ipynb
Jupyter Notebook
Chapter11/chapter_11_02_erk2_graph_conv.ipynb
deepchem/DeepLearningLifeSciences
9020c18d97de5f5bdab85234a5f3aac191791f1e
[ "MIT" ]
256
2019-02-07T20:28:28.000Z
2022-03-29T15:22:39.000Z
Chapter11/chapter_11_02_erk2_graph_conv.ipynb
deepchem/DeepLearningLifeSciences
9020c18d97de5f5bdab85234a5f3aac191791f1e
[ "MIT" ]
24
2019-06-12T13:46:59.000Z
2022-03-31T18:51:00.000Z
Chapter11/chapter_11_02_erk2_graph_conv.ipynb
deepchem/DeepLearningLifeSciences
9020c18d97de5f5bdab85234a5f3aac191791f1e
[ "MIT" ]
116
2019-02-05T22:58:59.000Z
2022-03-30T08:09:45.000Z
160.973786
12,684
0.770408
[ [ [ "### Training a Graph Convolution Model\nNow that we have the data appropriately formatted, we can use this data to train a Graph Convolution model. First we need to import the necessary libraries. ", "_____no_output_____" ] ], [ [ "import deepchem as dc\nfrom deepchem.models import GraphConvModel\nimport numpy as np\nimport sys\nimport pandas as pd\nimport seaborn as sns\nfrom rdkit.Chem import PandasTools\nfrom tqdm.auto import tqdm", "_____no_output_____" ] ], [ [ "Now let's define a function to create a GraphConvModel. In this case we will be creating a classification model. Since we will be apply the model later on a different dataset, it's a good idea to create a directory in which to store the model. ", "_____no_output_____" ] ], [ [ "def generate_graph_conv_model():\n batch_size = 128\n model = GraphConvModel(1, batch_size=batch_size, mode='classification', model_dir=\"./model_dir\")\n return model", "_____no_output_____" ] ], [ [ "Now we will read in the dataset that we just created. ", "_____no_output_____" ] ], [ [ "dataset_file = \"dude_erk2_mk01.csv\"\ntasks = [\"is_active\"]\nfeaturizer = dc.feat.ConvMolFeaturizer()\nloader = dc.data.CSVLoader(tasks=tasks, feature_field=\"SMILES\", featurizer=featurizer)\ndataset = loader.create_dataset(dataset_file, shard_size=8192)", "_____no_output_____" ] ], [ [ "Now that we have the dataset loaded, let's build a model.\nWe will create training and test sets to evaluate the model's performance. In this case we will use the RandomSplitter(). DeepChem offers a number of other splitters such as the ScaffoldSplitter, which will divide the dataset by chemical scaffold or the ButinaSplitter which will first cluster the data then split the dataset so that different clusters will end up in the training and test sets. ", "_____no_output_____" ] ], [ [ "splitter = dc.splits.RandomSplitter()", "_____no_output_____" ] ], [ [ "With the dataset split, we can train a model on the training set and test that model on the validation set. \nAt this point we can define some metrics and evaluate the performance of our model. In this case our dataset is unbalanced, we have a small number of active compounds and a large number of inactive compounds. Given this difference, we need to use a metric that reflects the performance on unbalanced datasets. One metric that is apporpriate for datasets like this is the Matthews correlation coefficient (MCC). Put more info about MCC here.", "_____no_output_____" ] ], [ [ "metrics = [dc.metrics.Metric(dc.metrics.matthews_corrcoef, np.mean)]", "_____no_output_____" ] ], [ [ "In order to evaluate the performance of our moldel, we will perform 10 folds of cross valiation, where we train a model on the training set and validate on the validation set. ", "_____no_output_____" ] ], [ [ "training_score_list = []\nvalidation_score_list = []\ntransformers = []\ncv_folds = 10\nfor i in tqdm(range(0,cv_folds)):\n model = generate_graph_conv_model()\n train_dataset, valid_dataset, test_dataset = splitter.train_valid_test_split(dataset)\n model.fit(train_dataset)\n train_scores = model.evaluate(train_dataset, metrics, transformers)\n training_score_list.append(train_scores[\"mean-matthews_corrcoef\"])\n validation_scores = model.evaluate(valid_dataset, metrics, transformers)\n validation_score_list.append(validation_scores[\"mean-matthews_corrcoef\"])\nprint(training_score_list)\nprint(validation_score_list)", "_____no_output_____" ] ], [ [ "To visualize the preformance of our models on the training and test data, we can make boxplots of the models' performance.", "_____no_output_____" ] ], [ [ "sns.boxplot(x=[\"training\"]*cv_folds+[\"validation\"]*cv_folds,y=training_score_list+validation_score_list);", "_____no_output_____" ] ], [ [ "It is also useful to visualize the result of our model. In order to do this, we will generate a set of predictions for a validation set. ", "_____no_output_____" ] ], [ [ "pred = [x.flatten() for x in model.predict(valid_dataset)]", "_____no_output_____" ], [ "pred", "_____no_output_____" ] ], [ [ "**The results of predict on a GraphConv model are returned as a list of lists. Is this the intent? It doesn't seem consistent across models. RandomForest returns a list. For convenience, we will put our predicted results into a Pandas dataframe.**", "_____no_output_____" ] ], [ [ "pred_df = pd.DataFrame(pred,columns=[\"neg\",\"pos\"])", "_____no_output_____" ] ], [ [ "We can easily add the activity class (1 = active, 0 = inactive) and the SMILES string for our predicted moleculesto the dataframe. __Is the moleculed id retained as part of the DeepChem dataset? I can't find it__", "_____no_output_____" ] ], [ [ "pred_df[\"active\"] = [int(x) for x in valid_dataset.y]\npred_df[\"SMILES\"] = valid_dataset.ids", "_____no_output_____" ], [ "pred_df.head()", "_____no_output_____" ], [ "pred_df.sort_values(\"pos\",ascending=False).head(25)", "_____no_output_____" ], [ "sns.boxplot(x=pred_df.active,y=pred_df.pos)", "_____no_output_____" ] ], [ [ "The performance of our model is very good, we can see a clear separation between the active and inactive compounds. It appears that only one of our active compounds receieved a low positive score. Let's look more closely. ", "_____no_output_____" ] ], [ [ "false_negative_df = pred_df.query(\"active == 1 & pos < 0.5\").copy()", "_____no_output_____" ], [ "PandasTools.AddMoleculeColumnToFrame(false_negative_df,\"SMILES\",\"Mol\")", "_____no_output_____" ], [ "false_negative_df", "_____no_output_____" ], [ "false_positive_df = pred_df.query(\"active == 0 & pos > 0.5\").copy()\nPandasTools.AddMoleculeColumnToFrame(false_positive_df,\"SMILES\",\"Mol\")", "_____no_output_____" ], [ "false_positive_df", "_____no_output_____" ] ], [ [ "Now that we've evaluated our model's performance we can retrain the model on the entire dataset and save it. ", "_____no_output_____" ] ], [ [ "model.fit(dataset)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cb0aeaa8fe3a47934da42df79c2399679008b76b
9,625
ipynb
Jupyter Notebook
python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb
Quan030994/atom-assignments
ed5a23704a78c984fdb61b9c29fa39494e7d50e4
[ "MIT" ]
null
null
null
python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb
Quan030994/atom-assignments
ed5a23704a78c984fdb61b9c29fa39494e7d50e4
[ "MIT" ]
null
null
null
python-for-data/Ex01 - Syntax, Variables and Numbers.ipynb
Quan030994/atom-assignments
ed5a23704a78c984fdb61b9c29fa39494e7d50e4
[ "MIT" ]
null
null
null
28.143275
226
0.538597
[ [ [ "# Exercise 01 - Syntax, Variables and Numbers", "_____no_output_____" ], [ "Welcome to your first set of Python coding problems! \n\n**Notebooks** are composed of blocks (called \"cells\") of text and code. Each of these is editable, though you'll mainly be editing the code cells to answer some questions.\n\nTo get started, try running the code cell below (by pressing the `►| Run` button, or clicking on the cell and pressing `ctrl+Enter`/`shift+Enter` on your keyboard).", "_____no_output_____" ] ], [ [ "print(\"You've successfully run some Python code\")\nprint(\"Congratulations!\")", "_____no_output_____" ] ], [ [ "Try adding another line of code in the cell above and re-running it. \n\nNow let's get a little fancier: Add a new code cell by clicking on an existing code cell, hitting the `escape` key *(turn to command mode)*, and then hitting the `a` or `b` key. \n- The `a` key will add a cell above the current cell.\n- The `b` adds a cell below.\n\nGreat! Now you know how to use Notebooks.", "_____no_output_____" ], [ "## 0. Creating a Variable\n\n**What is your favorite color? **\n\nTo complete this question, create a variable called `color` in the cell below with an appropriate `string` value.", "_____no_output_____" ] ], [ [ "# Create a variable called color with an appropriate value on the line below\n# (Remember, strings in Python must be enclosed in 'single' or \"double\" quotes)\n\ncolor = 'blue'", "_____no_output_____" ] ], [ [ "<hr/>\n\n## 1. Simple Arithmetic Operation\n\nComplete the code below. In case it's helpful, here is the table of available arithmatic operations:\n\n\n\n| Operator | Name | Description |\n|--------------|----------------|--------------------------------------------------------|\n| ``a + b`` | Addition | Sum of ``a`` and ``b`` |\n| ``a - b`` | Subtraction | Difference of ``a`` and ``b`` |\n| ``a * b`` | Multiplication | Product of ``a`` and ``b`` |\n| ``a / b`` | True division | Quotient of ``a`` and ``b`` |\n| ``a // b`` | Floor division | Quotient of ``a`` and ``b``, removing fractional parts |\n| ``a % b`` | Modulus | Integer remainder after division of ``a`` by ``b`` |\n| ``a ** b`` | Exponentiation | ``a`` raised to the power of ``b`` |\n| ``-a`` | Negation | The negative of ``a`` |\n\n<span style=\"display:none\"></span>\n", "_____no_output_____" ] ], [ [ "pi = 3.14159 # approximate\ndiameter = 3\n\n# Create a variable called 'radius' equal to half the diameter\nradius = 3/2\n# Create a variable called 'area', using the formula for the area of a circle: pi times the radius squared\narea = pi * radius**2\narea", "_____no_output_____" ] ], [ [ "**Results**:\n- Area = 7.0685775", "_____no_output_____" ], [ "## 2. Variable Reassignment\n\nAdd code to the following cell to swap variables `a` and `b` (so that `a` refers to the object previously referred to by `b` and vice versa).", "_____no_output_____" ] ], [ [ "# If you're curious, these are examples of lists. We'll talk about \n# them in depth a few lessons from now. For now, just know that they're\n# yet another type of Python object, like int or float.\na = [1, 2, 3]\nb = [3, 2, 1]\n\n######################################################################\n\n# Your code goes here. Swap the values to which a and b refer.\n# Hint: Try using a third variable\nc = b\nb = a\na = c\nprint('a = ', a)\nprint('b = ', b)\n\n", "a = [3, 2, 1]\nb = [1, 2, 3]\n" ] ], [ [ "## 3. Order of Operations\n\n\na) Add parentheses to the following expression so that it evaluates to 1.\n\n*Hint*: Following its default \"**PEMDAS**\"-like rules for order of operations, Python will first divide 3 by 2, then subtract the result from 5. You need to add parentheses to force it to perform the subtraction first.", "_____no_output_____" ] ], [ [ "(5 - 3) // 2", "_____no_output_____" ] ], [ [ "<small>Questions, like this one, marked a spicy pepper are a bit harder. Don't feel bad if you can't get these.</small>\n\nb) <span title=\"A bit spicy\" style=\"color: darkgreen \">🌶️</span> Add parentheses to the following expression so that it evaluates to **0**.", "_____no_output_____" ] ], [ [ "8 - (3 * 2) - (1 + 1)", "_____no_output_____" ] ], [ [ "## 4. Your Turn\nAlice, Bob and Carol have agreed to pool their Halloween candies and split it evenly among themselves.\nFor the sake of their friendship, any candies left over will be smashed. For example, if they collectively\nbring home 91 candies, they'll take 30 each and smash 1.\n\nWrite an arithmetic expression below to calculate how many candies they must smash for a given haul.\n\n> *Hint*: You'll probably want to use the modulo operator, `%`, to obtain the remainder of division.", "_____no_output_____" ] ], [ [ "# Variables representing the number of candies collected by Alice, Bob, and Carol\nalice_candies = 121\nbob_candies = 77\ncarol_candies = 109\n\n# Your code goes here! Replace the right-hand side of this assignment with an expression\ncandies_smash = (alice_candies + bob_candies + carol_candies) % 3\ncandies_smash\n# involving alice_candies, bob_candies, and carol_candies\n#to_smash = -1", "_____no_output_____" ] ], [ [ "# Keep Going 💪", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb0aefc368f1824152e52e2130ccbfbbb051cd0e
25,363
ipynb
Jupyter Notebook
Day015_Cifar_HW.ipynb
semishen/DL-CVMarathon
6d4fb15cd8ccd84a3226342a13b2f89f09866611
[ "MIT" ]
null
null
null
Day015_Cifar_HW.ipynb
semishen/DL-CVMarathon
6d4fb15cd8ccd84a3226342a13b2f89f09866611
[ "MIT" ]
null
null
null
Day015_Cifar_HW.ipynb
semishen/DL-CVMarathon
6d4fb15cd8ccd84a3226342a13b2f89f09866611
[ "MIT" ]
null
null
null
46.968519
236
0.430746
[ [ [ "<a href=\"https://colab.research.google.com/github/semishen/DL-CVMarathon/blob/master/Day015_Cifar_HW.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "## 『本次練習內容』\n#### 運用這幾天所學觀念搭建一個CNN分類器", "_____no_output_____" ], [ "## 『本次練習目的』\n #### 熟悉CNN分類器搭建步驟與原理\n #### 學員們可以嘗試不同搭法,如使用不同的Maxpooling層,用GlobalAveragePooling取代Flatten等等", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras.layers import Convolution2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import BatchNormalization\nfrom keras.layers import Activation\n\nimport keras.utils\nfrom keras.datasets import cifar10\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n", "Using TensorFlow backend.\n" ], [ "(x_train, y_train), (x_test, y_test) = cifar10.load_data()", "Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n170500096/170498071 [==============================] - 6s 0us/step\n" ], [ "print(x_train.shape) #(50000, 32, 32, 3)\n\n## Normalize Data\ndef normalize(X_train,X_test):\n mean = np.mean(X_train,axis=(0,1,2,3))\n std = np.std(X_train, axis=(0,1,2,3))\n X_train = (X_train-mean)/(std+1e-7)\n X_test = (X_test-mean)/(std+1e-7) \n return X_train, X_test, mean, std\n \n \n## Normalize Training and Testset \nx_train, x_test, mean_train, std_train = normalize(x_train, x_test) ", "(50000, 32, 32, 3)\n" ], [ "# ## OneHot Label 由(None, 1)-(None, 10)\n# ## ex. label=2,變成[0,0,1,0,0,0,0,0,0,0]\n# one_hot=OneHotEncoder()\n# y_train=one_hot.fit_transform(y_train).toarray()\n# y_test=one_hot.transform(y_test).toarray()\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, 10)\ny_test = keras.utils.to_categorical(y_test, 10)", "_____no_output_____" ], [ "classifier=Sequential()\n\n#卷積組合\nclassifier.add(Convolution2D(kernel_size=(3,3), filters=16, input_shape=(32,32,3)))#32,3,3,input_shape=(32,32,3),activation='relu''\nclassifier.add(BatchNormalization())\nclassifier.add(Activation('relu'))\n'''自己決定MaxPooling2D放在哪裡'''\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\n\n#卷積組合\nclassifier.add(Convolution2D(kernel_size=(3,3), filters=32))\nclassifier.add(BatchNormalization())\nclassifier.add(Activation('relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\n\n#flatten\nclassifier.add(Flatten())\n\n#FC\nclassifier.add(Dense(100)) #output_dim=100,activation=relu\nclassifier.add(Activation('relu'))\n\n\n#輸出\nclassifier.add(Dense(units=10,activation='softmax'))\nclassifier.summary()\n\n#超過兩個就要選categorical_crossentrophy\nclassifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nclassifier.fit(x_train,y_train,batch_size=100,epochs=100)", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_1 (Conv2D) (None, 30, 30, 16) 448 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 30, 30, 16) 64 \n_________________________________________________________________\nactivation_1 (Activation) (None, 30, 30, 16) 0 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 15, 15, 16) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 13, 13, 32) 4640 \n_________________________________________________________________\nbatch_normalization_2 (Batch (None, 13, 13, 32) 128 \n_________________________________________________________________\nactivation_2 (Activation) (None, 13, 13, 32) 0 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 6, 6, 32) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 1152) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 100) 115300 \n_________________________________________________________________\nactivation_3 (Activation) (None, 100) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 1010 \n=================================================================\nTotal params: 121,590\nTrainable params: 121,494\nNon-trainable params: 96\n_________________________________________________________________\nEpoch 1/100\n50000/50000 [==============================] - 11s 223us/step - loss: 1.4265 - accuracy: 0.4910\nEpoch 2/100\n50000/50000 [==============================] - 4s 80us/step - loss: 1.0835 - accuracy: 0.6205\nEpoch 3/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.9604 - accuracy: 0.6636\nEpoch 4/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.8802 - accuracy: 0.6919\nEpoch 5/100\n50000/50000 [==============================] - 4s 85us/step - loss: 0.8160 - accuracy: 0.7158\nEpoch 6/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.7704 - accuracy: 0.7313\nEpoch 7/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.7336 - accuracy: 0.7429\nEpoch 8/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.6911 - accuracy: 0.7570\nEpoch 9/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.6601 - accuracy: 0.7682\nEpoch 10/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.6307 - accuracy: 0.7788\nEpoch 11/100\n50000/50000 [==============================] - 4s 83us/step - loss: 0.6029 - accuracy: 0.7895\nEpoch 12/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.5707 - accuracy: 0.8006\nEpoch 13/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.5503 - accuracy: 0.8072\nEpoch 14/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.5259 - accuracy: 0.8162\nEpoch 15/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.5003 - accuracy: 0.8247\nEpoch 16/100\n50000/50000 [==============================] - 4s 86us/step - loss: 0.4860 - accuracy: 0.8302\nEpoch 17/100\n50000/50000 [==============================] - 4s 86us/step - loss: 0.4629 - accuracy: 0.8381\nEpoch 18/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.4480 - accuracy: 0.8443\nEpoch 19/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.4348 - accuracy: 0.8473\nEpoch 20/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.4107 - accuracy: 0.8554\nEpoch 21/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.3921 - accuracy: 0.8621\nEpoch 22/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.3790 - accuracy: 0.8669\nEpoch 23/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.3635 - accuracy: 0.8727\nEpoch 24/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.3478 - accuracy: 0.8783\nEpoch 25/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.3304 - accuracy: 0.8851\nEpoch 26/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.3193 - accuracy: 0.8884\nEpoch 27/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.3084 - accuracy: 0.8918\nEpoch 28/100\n50000/50000 [==============================] - 4s 85us/step - loss: 0.2905 - accuracy: 0.8992\nEpoch 29/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.2829 - accuracy: 0.9004\nEpoch 30/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.2761 - accuracy: 0.9019\nEpoch 31/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.2526 - accuracy: 0.9119\nEpoch 32/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.2497 - accuracy: 0.9117\nEpoch 33/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.2336 - accuracy: 0.9181\nEpoch 34/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.2337 - accuracy: 0.9171\nEpoch 35/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.2184 - accuracy: 0.9233\nEpoch 36/100\n50000/50000 [==============================] - 4s 86us/step - loss: 0.2091 - accuracy: 0.9263\nEpoch 37/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.2047 - accuracy: 0.9279\nEpoch 38/100\n50000/50000 [==============================] - 4s 83us/step - loss: 0.1946 - accuracy: 0.9296\nEpoch 39/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.1876 - accuracy: 0.9339\nEpoch 40/100\n50000/50000 [==============================] - 4s 85us/step - loss: 0.1828 - accuracy: 0.9357\nEpoch 41/100\n50000/50000 [==============================] - 4s 85us/step - loss: 0.1712 - accuracy: 0.9394\nEpoch 42/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.1674 - accuracy: 0.9408\nEpoch 43/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.1647 - accuracy: 0.9410\nEpoch 44/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1582 - accuracy: 0.9437\nEpoch 45/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1488 - accuracy: 0.9470\nEpoch 46/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.1470 - accuracy: 0.9474\nEpoch 47/100\n50000/50000 [==============================] - 4s 83us/step - loss: 0.1360 - accuracy: 0.9530\nEpoch 48/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1365 - accuracy: 0.9515\nEpoch 49/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.1338 - accuracy: 0.9528\nEpoch 50/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.1305 - accuracy: 0.9534\nEpoch 51/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1197 - accuracy: 0.9581\nEpoch 52/100\n50000/50000 [==============================] - 4s 83us/step - loss: 0.1192 - accuracy: 0.9581\nEpoch 53/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.1183 - accuracy: 0.9579\nEpoch 54/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.1056 - accuracy: 0.9629\nEpoch 55/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1140 - accuracy: 0.9593\nEpoch 56/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1101 - accuracy: 0.9616\nEpoch 57/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1042 - accuracy: 0.9631\nEpoch 58/100\n50000/50000 [==============================] - 4s 83us/step - loss: 0.1006 - accuracy: 0.9647\nEpoch 59/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.1021 - accuracy: 0.9641\nEpoch 60/100\n50000/50000 [==============================] - 4s 86us/step - loss: 0.0998 - accuracy: 0.9636\nEpoch 61/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.0947 - accuracy: 0.9659\nEpoch 62/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0864 - accuracy: 0.9698\nEpoch 63/100\n50000/50000 [==============================] - 4s 86us/step - loss: 0.0921 - accuracy: 0.9670\nEpoch 64/100\n50000/50000 [==============================] - 4s 85us/step - loss: 0.0828 - accuracy: 0.9710\nEpoch 65/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0890 - accuracy: 0.9683\nEpoch 66/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.0820 - accuracy: 0.9723\nEpoch 67/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.0748 - accuracy: 0.9744\nEpoch 68/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0814 - accuracy: 0.9710\nEpoch 69/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0819 - accuracy: 0.9714\nEpoch 70/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0807 - accuracy: 0.9716\nEpoch 71/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0753 - accuracy: 0.9736\nEpoch 72/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.0722 - accuracy: 0.9748\nEpoch 73/100\n50000/50000 [==============================] - 4s 85us/step - loss: 0.0738 - accuracy: 0.9743\nEpoch 74/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.0762 - accuracy: 0.9736\nEpoch 75/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0763 - accuracy: 0.9732\nEpoch 76/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0703 - accuracy: 0.9759\nEpoch 77/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.0690 - accuracy: 0.9758\nEpoch 78/100\n50000/50000 [==============================] - 4s 88us/step - loss: 0.0623 - accuracy: 0.9781\nEpoch 79/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0732 - accuracy: 0.9738\nEpoch 80/100\n50000/50000 [==============================] - 4s 87us/step - loss: 0.0704 - accuracy: 0.9747\nEpoch 81/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0648 - accuracy: 0.9769\nEpoch 82/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.0619 - accuracy: 0.9778\nEpoch 83/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.0619 - accuracy: 0.9786\nEpoch 84/100\n50000/50000 [==============================] - 4s 84us/step - loss: 0.0584 - accuracy: 0.9796\nEpoch 85/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0676 - accuracy: 0.9766\nEpoch 86/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0599 - accuracy: 0.9787\nEpoch 87/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.0595 - accuracy: 0.9792\nEpoch 88/100\n50000/50000 [==============================] - 4s 83us/step - loss: 0.0558 - accuracy: 0.9801\nEpoch 89/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.0674 - accuracy: 0.9763\nEpoch 90/100\n50000/50000 [==============================] - 4s 82us/step - loss: 0.0548 - accuracy: 0.9813\nEpoch 91/100\n50000/50000 [==============================] - 4s 83us/step - loss: 0.0644 - accuracy: 0.9769\nEpoch 92/100\n50000/50000 [==============================] - 4s 87us/step - loss: 0.0506 - accuracy: 0.9825\nEpoch 93/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0600 - accuracy: 0.9789\nEpoch 94/100\n50000/50000 [==============================] - 4s 79us/step - loss: 0.0593 - accuracy: 0.9794\nEpoch 95/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0575 - accuracy: 0.9793\nEpoch 96/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0491 - accuracy: 0.9830\nEpoch 97/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0556 - accuracy: 0.9799\nEpoch 98/100\n50000/50000 [==============================] - 4s 81us/step - loss: 0.0508 - accuracy: 0.9818\nEpoch 99/100\n50000/50000 [==============================] - 4s 80us/step - loss: 0.0549 - accuracy: 0.9817\nEpoch 100/100\n50000/50000 [==============================] - 4s 85us/step - loss: 0.0508 - accuracy: 0.9819\n" ] ], [ [ "## 預測新圖片,輸入影像前處理要與訓練時相同\n#### ((X-mean)/(std+1e-7) ):這裡的mean跟std是訓練集的\n## 維度如下方示範", "_____no_output_____" ] ], [ [ "index = 50\ninput_example = x_test[index].reshape(1,32,32,3)\n# input_example.shape\ninput_example=(input_example-mean_train)/(std_train+1e-7) \nprint(classifier.predict(input_example))\nprint(y_test[index])", "[[9.8900187e-01 4.3648228e-18 1.9784315e-05 1.0233850e-02 6.6645944e-04\n 9.5122732e-10 1.2182406e-09 1.8907217e-06 7.6206437e-05 2.0525989e-18]]\n[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0af826432bf99989713769b29146099ab319fb
711,271
ipynb
Jupyter Notebook
research/Transmission.ipynb
goran-mahovlic/onebitbt
fe509bd8a300810439f267fe84b6899b2612b96b
[ "Apache-2.0" ]
150
2021-03-23T02:37:40.000Z
2022-03-20T18:06:55.000Z
research/Transmission.ipynb
goran-mahovlic/onebitbt
fe509bd8a300810439f267fe84b6899b2612b96b
[ "Apache-2.0" ]
2
2021-03-23T12:21:35.000Z
2021-12-07T20:47:29.000Z
research/Transmission.ipynb
goran-mahovlic/onebitbt
fe509bd8a300810439f267fe84b6899b2612b96b
[ "Apache-2.0" ]
9
2021-03-23T03:00:12.000Z
2021-12-09T14:15:31.000Z
421.61885
63,868
0.935801
[ [ [ "# Transmission", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nnp.seterr(divide='ignore') # Ignore divide by zero in log plots\nfrom scipy import signal\nimport scipy.signal\nfrom numpy.fft import fft, fftfreq\nimport matplotlib.pyplot as plt\n#import skrf as rf # pip install scikit-rf if you want to run this one", "_____no_output_____" ] ], [ [ "First, let's set up a traditional, full-precision modulator and plot the spectrum of that as a baseline", "_____no_output_____" ] ], [ [ "def prbs(n=0, taps=[]):\n state = [1]*n\n shift = lambda s: [sum([s[i] for i in taps]) % 2] + s[0:-1]\n out = []\n for i in range(2**n - 1):\n out.append(state[-1])\n state = shift(state)\n return out\nprbs9 = lambda: prbs(n=9, taps=[4,8])\n\ndef make_carrier(freq=None, sample_rate=None, samples=None, phase=0):\n t = (1/sample_rate)*np.arange(samples)\n return np.real(np.exp(1j*(2*np.pi*freq*t - phase)))\n\ndef modulate_gmsk(bits, carrier_freq=2.402e9, sample_rate=5e9, baseband=False, phase_offset=0, include_phase=False):\n symbol_rate = 1e6 # 1Mhz\n BT = 0.5\n bw = symbol_rate*BT/sample_rate\n\n samples_per_symbol = int(sample_rate/symbol_rate)\n \n # This looks scary but it's just a traditional gaussian distribution from wikipedia\n kernel = np.array([(np.sqrt(2*np.pi/np.log(2))*bw)*np.exp(-(2/np.log(2))*np.power(np.pi*t*bw, 2)) for t in range(-5000,5000)])\n kernel /= sum(kernel) # Normalize so things amplitude after convolution remains the same\n \n rotation = np.repeat(bits, sample_rate/symbol_rate)*2.0 - 1.0\n smoothed_rotation = np.convolve(rotation, kernel,mode='same')\n\n angle_per_sample = (np.pi/2.0)/(samples_per_symbol)\n current_angle = phase_offset\n modulated = np.zeros((len(smoothed_rotation),), dtype=np.complex64) # Represents I and Q as a complex number\n i = 0\n for bit in smoothed_rotation:\n current_angle += angle_per_sample*bit\n modulated[i] = np.exp(1j*current_angle)\n i += 1\n\n if baseband:\n return modulated\n \n I = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(modulated), phase=0)\n Q = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(modulated), phase=np.pi/2)\n\n if include_phase:\n return np.real(modulated)*I + np.imag(modulated)*Q, np.angle(modulated)\n return np.real(modulated)*I + np.imag(modulated)*Q", "_____no_output_____" ] ], [ [ "Now let's look at the FFT of this...", "_____no_output_____" ] ], [ [ "sample_rate = 6e9\nmodulated = modulate_gmsk(prbs9(), sample_rate=sample_rate)\n\nfftm = np.abs(fft(modulated))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(modulated), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.gca().set_ylim(-40, 0)", "_____no_output_____" ] ], [ [ "This is clean (as one would expect), now let's see what happens if we reduce things to 1-bit of precision by just rounding", "_____no_output_____" ], [ "# The Naive Approach (Rounding)", "_____no_output_____" ] ], [ [ "sample_rate=5e9\n\nmodulates_5g = modulated = np.sign(modulate_gmsk(prbs9(), sample_rate=sample_rate))\n\nfftm = np.abs(fft(modulated))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(modulated), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)", "_____no_output_____" ] ], [ [ "_Oof_ this is not pretty. What's happening here is that (I think) the aliases are mixing with each other to produce these interference paterns. In this case, it looks like the big subharmonics are spaced about 200Mhz which makes sense given the alias of 2.402ghz at 2.698ghz when sampling at 2.5ghz.", "_____no_output_____" ] ], [ [ "sample_rate = 6e9\n\nmodulated_6g = modulated = np.sign(modulate_gmsk(prbs9(), sample_rate=sample_rate))\n\nfftm = np.abs(fft(modulated))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(modulated), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)\nplt.title(\"Unfiltered\")", "_____no_output_____" ] ], [ [ "Ok, in this case, the alias is at `3 + (3 - 2.402) = 3.6ghz`. The difference between this and 2.402ghz is about 1.2ghz, which looking at the next big peak, looks to be about 1.2ghz, so this makes sense. From this math, we can intuit that it's a good idea for the sample rate to be a whole number multiple of the carrier frequency. In the ideal case, 4 times the carrier:", "_____no_output_____" ] ], [ [ "sample_rate = 2.402e9*4\n\nmodulated_4x = modulated = np.sign(modulate_gmsk(prbs9(), sample_rate=sample_rate))\n\nfftm = np.abs(fft(modulated))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(modulated), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)", "_____no_output_____" ] ], [ [ "There a couple of challenges here, however:\n\n1. In order to get the clean(ish) spectrum, we have to clock the output frequency at a rate relative to the carrier frequency. If we only intended to use one frequency, this would be fine but Bluetooth (as an example) hops around frequency constantly by design. This might be doable, but it's kind of painful (this might require various SERDES resets which aren't instantaneous)\n2. At 2.402ghz, 4x this would be... 9.6ghz, which is too fast for my (low-end-ish) SERDES which maxes out around 6ghz.", "_____no_output_____" ], [ "# Adding a Reconstruction Filter\n\nIn order to prevent a friendly visit from an unmarked FCC van, it's more or less mandatory that we filter noise outside of the band of interest. In our case, I have a tiny 2.4Ghz surface mount band pass filter that I've put onto a test board. This is the delightfully named \"DEA252450BT-2027A1\" which is a surface mount part which has a frequency response of:\n\n![image.png](attachment:f25e931a-f396-47b5-b852-d5363399e422.png)\n\nTo (more fully) characterize this filter, I hooked it up to a NanoVNA2 and saved its S parameters using a NanoVNA Saver:", "_____no_output_____" ] ], [ [ "# pip install scikit-rf if you want to run this one\n# Note: running this before we've plotted anything, borks matplotlib\nimport skrf as rf\nfilter2_4 = rf.Network('2_4ghzfilter.s2p')\nfilter2_4.s21.plot_s_db()", "_____no_output_____" ] ], [ [ "Hey that's not too far off from data sheet (at least up to 4.4Ghz). \n\nTo turn this into a filter, we can use the scipy-rf to compute an impulse response which we can then convolve with our input data to see what the filtered output would be:", "_____no_output_____" ] ], [ [ "ts, ms = filter2_4.s21.impulse_response()\nimpulse_response = ms[list(ts).index(0):]\nimpulse_response = impulse_response/np.max(impulse_response)\ntstep = ts[1] - ts[0]\nprint(\"Timestep {} seconds, frequency {:e} hz\".format(tstep, 1/tstep))\nplt.plot(impulse_response)\nplt.gca().set_xlim(0, 300)", "Timestep 3.2641464908425124e-11 seconds, frequency 3.063588e+10 hz\n" ] ], [ [ "This is great and all but the impulse response is sampled at north of 30ghz (!). Our output serdes runs at around 6ghz so let's resample this to that rate", "_____no_output_____" ] ], [ [ "# Truncate the impulse response so we can get relatively close to 6ghz\ntrunc = impulse_response[:-4]\nsize = int((tstep*(len(trunc) - 1))/(1/6e9) + 1)\nprint(size)\n\nimpulse_response_6g = scipy.signal.resample(impulse_response, size)\nplt.plot(impulse_response_6g)\nplt.gca().set_xlim(0, 50)", "274\n" ] ], [ [ "Not quite as pretty, but it's what we need. Let's verify that this does \"the thing\" by filtering our 6ghz signal:", "_____no_output_____" ] ], [ [ "sample_rate=6e9\n\nfftm = np.abs(fft(np.convolve(modulated_6g, impulse_response_6g, mode=\"same\")))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(fftm), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.grid(b=True)\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)", "_____no_output_____" ] ], [ [ "This looks better, but the passband for my filter is still super wide (hundreds of MHz, not surprising for a 50c filter, I should look at B39242B9413K610 which is a $1 surface acoustic wave filter). We see some nontrivial imaging up to -12db, which is... not great.\n\nWhat to do?", "_____no_output_____" ], [ "# Delta Sigma Modulation\n\nA way around this is to use something called Delta Sigma Modulation. The way to think about this conceptually is that we keep a running sum of values we've output (think of this as the error) and factor this into the value we decide to output (versus just blindly rounding the current value). Further, you can filter this feedback loop to \"shape\" the noise to different parts of the spectrum (that we can filter out elsewhere).\n\nA good place to read about this is [Wikipedia](https://en.wikipedia.org/wiki/Delta-sigma_modulation#Oversampling). In [Novel Architectures for Flexible and Wideband All-digital Transmitters](https://ria.ua.pt/bitstream/10773/23875/1/Documento.pdf) by Rui Fiel Cordeiro, Rui proposes using a filter that has a zero at the carrier of interest, which looks like the following", "_____no_output_____" ] ], [ [ "def pwm2(sig, k=1.0):\n z1 = 0.0\n z2 = 0.0\n out = np.zeros((len(sig,)))\n\n for i in range(len(sig)):\n v = sig[i] - (k*z1 + z2)\n out[i] = np.sign(v)\n z2 = z1\n z1 = v - out[i]\n\n return out", "_____no_output_____" ] ], [ [ "To be clear, `pwm2` is replacing `np.sign`", "_____no_output_____" ] ], [ [ "sample_rate = 6e9\n\nmodulated = modulate_gmsk(prbs9(), sample_rate=sample_rate)\nmodulatedsd5 = modulated = pwm2(modulated, k=-2.0*np.cos(2.0*np.pi*2.402e9/sample_rate))\n\nfftm = np.abs(fft(np.sign(modulated)))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(modulated), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)\nplt.title(\"Second order Delta Sigma Modulation\")", "_____no_output_____" ] ], [ [ "Now let's filter this with our output filter", "_____no_output_____" ] ], [ [ "fftm = np.abs(fft(np.convolve(modulatedsd5, impulse_response_6g, mode=\"same\")))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(fftm), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.grid(b=True)\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)\nplt.title(\"Filtered Second Order Delta Sigma Modulation\")", "_____no_output_____" ] ], [ [ "This is better in the immediate vicinity of our signal. \n\nYou'll notice on the wikipedia page that we can use increasing filter orders to increase the steepness of the valley around our signal of interest.\n\nOn one hand this is good, but because our filter is not very good (tm) this actually results in higher peaks than we'd like at around 2.2ghz.\n\nGiven that our filter is... not that good, can we design the filter in the modulator to compliment it?", "_____no_output_____" ], [ "# Filter-Aware Sigma Delta Modulator\n\nI lay no claim to this awesome work by the folks who wrote pydsm, but it's great -- feed it an impulse response for a reconstruction filter and it will optimize a noise transfer function that matches it:\n", "_____no_output_____" ] ], [ [ "from pydsm.ir import impulse_response\nfrom pydsm.delsig import synthesizeNTF, simulateDSM, evalTF\nfrom pydsm.delsig import dbv, dbp\nfrom pydsm.NTFdesign import quantization_noise_gain\nfrom pydsm.NTFdesign.legacy import q0_from_filter_ir\nfrom pydsm.NTFdesign.weighting import ntf_fir_from_q0", "_____no_output_____" ], [ "H_inf = 1.6 # This is out of band noise level in dB\nq0 = q0_from_filter_ir(51, impulse_response_6g) # 51 is the number of filter coefficients\nntf_opti = ntf_fir_from_q0(q0, H_inf=H_inf)", "\nCalling CVXOPT ...\n pcost dcost gap pres dres k/t\n 0: 1.3378e-17 -1.0000e+00 2e+02 8e+00 1e+01 1e+00\n 1: -3.2534e-02 4.5237e-02 1e+01 1e+00 2e+00 4e-01\n 2: 1.6301e-01 1.5136e-01 2e+00 3e-01 3e-01 5e-02\n 3: 1.3047e-01 1.2416e-01 5e-01 9e-02 1e-01 2e-02\n 4: 1.3111e-01 1.2758e-01 2e-01 5e-02 6e-02 8e-03\n 5: 1.2081e-01 1.1905e-01 5e-02 2e-02 2e-02 2e-03\n 6: 1.1941e-01 1.1808e-01 3e-02 1e-02 1e-02 1e-03\n 7: 1.1569e-01 1.1532e-01 7e-03 3e-03 3e-03 3e-04\n 8: 1.1457e-01 1.1448e-01 1e-03 6e-04 8e-04 6e-05\n 9: 1.1452e-01 1.1445e-01 1e-03 4e-04 5e-04 3e-05\n10: 1.1431e-01 1.1429e-01 2e-04 8e-05 1e-04 6e-06\n11: 1.1430e-01 1.1429e-01 1e-04 5e-05 6e-05 3e-06\n12: 1.1428e-01 1.1428e-01 3e-05 1e-05 1e-05 6e-07\n13: 1.1428e-01 1.1428e-01 1e-05 4e-06 5e-06 2e-07\n14: 1.1428e-01 1.1428e-01 4e-06 1e-06 2e-06 5e-08\n15: 1.1428e-01 1.1428e-01 2e-06 7e-07 9e-07 2e-08\n16: 1.1428e-01 1.1428e-01 5e-07 2e-07 2e-07 6e-09\n17: 1.1428e-01 1.1428e-01 1e-07 4e-08 5e-08 1e-09\nOptimal solution found.\n" ] ], [ [ "Let's see how well we did. Anecdotally, this is not a _great_ solution (likely constrained by the low oversampling) but I'd wager this is because the oversampling rate is super low.", "_____no_output_____" ] ], [ [ "# Take the frequency response\nsamples = filter2_4.s21.s_db[:,0,0]\n# Normalize the samples\nff = filter2_4.f/6e9\n\n# Compute frequency response data\nresp_opti = evalTF(ntf_opti, np.exp(1j*2*np.pi*ff))\n\n# Plot the output filter, \nplt.figure()\nplt.plot(ff*6e9, dbv(resp_opti), 'r', label=\"Optimal NTF\")\nplt.plot(ff*6e9, samples, 'b', label=\"External Filter\")\nplt.plot(ff*6e9, dbv(resp_opti) + samples, 'g', label=\"Resulting Noise Shape\")\nplt.gca().set_xlim(0, 3e9)\nplt.legend(loc=\"lower right\")\nplt.suptitle(\"Output filter and NTFs\")", "_____no_output_____" ] ], [ [ "Ok, so it's not amazing but definitely an improvement. But now that we've got this monstrous 49 coefficient NTF, how do we modulate with it?\n\nFortunately we have the pydsm to the rescue!", "_____no_output_____" ] ], [ [ "sample_rate = 6e9\nmodulated = modulate_gmsk(prbs9(), sample_rate=sample_rate)\nxx_opti = simulateDSM(modulated, ntf_opti)", "_____no_output_____" ], [ "fftm = np.abs(fft(np.convolve(xx_opti[0], impulse_response_6g, mode=\"same\")))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(fftm), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.grid(b=True)\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)", "_____no_output_____" ] ], [ [ "Ok, so we've basically \"filled in the valley\" with the peaks from eithe sides. We've cut the max spurs down by about 3db. Not amazing, but not bad!\n\nAfter looking around at SAW filters I realized how impressive they can be in this frequency rance, so I tried to order one (CBPFS-2441) and try with that. Unfortunately, the datasheets only show _drawing_ of parameters (and only phase) and actual s2p files are impossible to find. This seems dumb. Nevertheless, https://apps.automeris.io/wpd/ exists which allow you to extimate a graph from an image.", "_____no_output_____" ] ], [ [ "import csv\nfrom scipy.interpolate import interp1d\n\ntraced = np.array([(float(f), float(d)) for f,d in csv.reader(open('saw_filter_traced.csv'))])\n\n# Interpolate to 600 equally spaced points (this means 1200 total, so 1200 * 5MHz -> 6GHz sampling rate)\nx = traced[:,0]\ny = -1*traced[:,1]\nf = interp1d(x, y)\nx = np.array(np.linspace(5, 3000, 600))\ny = np.array(f(x))\n\nx = np.concatenate((np.flip(x)*-1, np.array([0]), x))\n\n# In FFT format\ny_orig = 10**(np.concatenate((np.array([-70]), y, np.flip(y)))/10)\ny = 10**(np.concatenate((np.flip(y), np.array([-70]), y))/10.0)\n\nplt.plot(x, 10*np.log10(y))", "_____no_output_____" ] ], [ [ "Let's look at the impulse respponse quickly", "_____no_output_____" ] ], [ [ "impulse = np.fft.ifft(y_orig)\nimpulse_trunc = impulse[:300]\n\nplt.plot(np.real(impulse_trunc))", "_____no_output_____" ] ], [ [ "**Update:** The filter finally arrived and I can characterize it, as shown below...\n\n(the remaining code uses the measured filter response rather than the one trace from the image)", "_____no_output_____" ] ], [ [ "sawfilter = rf.Network('crysteksawfilter.s2p')\nsawfilter.s21.plot_s_db()\nfilter2_4.s21.plot_s_db()", "_____no_output_____" ], [ "ts, ms = sawfilter.s21.impulse_response()\nimpulse_response = ms[list(ts).index(0):]\nimpulse_response = impulse_response/np.max(impulse_response)\ntstep = ts[1] - ts[0]\nprint(\"Timestep {} seconds, frequency {:e} hz\".format(tstep, 1/tstep))\nplt.plot(impulse_response)\nplt.gca().set_xlim(0, 600)\nplt.show()\n\ntrunc = impulse_response[:-2]\nsize = int((tstep*(len(trunc) - 1))/(1/6e9) + 1)\nprint(size)\n\nimpulse_response_6g = scipy.signal.resample(impulse_response, size)\nplt.plot(impulse_response_6g)\nplt.gca().set_xlim(0, 400)", "Timestep 4.283537554093063e-11 seconds, frequency 2.334519e+10 hz\n" ] ], [ [ "Wow that is a fair bit sharper.", "_____no_output_____" ] ], [ [ "H_inf = 1.5\nq0 = q0_from_filter_ir(49, np.real(impulse_response_6g))\nntf_opti = ntf_fir_from_q0(q0, H_inf=H_inf)", "\nCalling CVXOPT ...\n pcost dcost gap pres dres k/t\n 0: -8.1247e-17 -1.0000e+00 1e+02 7e+00 1e+01 1e+00\n 1: -1.3096e-01 -8.2158e-02 1e+01 1e+00 2e+00 4e-01\n 2: 1.4314e-02 5.1210e-03 2e+00 2e-01 3e-01 6e-02\n 3: 1.0809e-02 3.6882e-03 4e-01 7e-02 1e-01 1e-02\n 4: 2.1580e-02 1.7220e-02 2e-01 4e-02 6e-02 7e-03\n 5: 2.2150e-02 1.9725e-02 6e-02 2e-02 2e-02 2e-03\n 6: 2.3864e-02 2.3136e-02 2e-02 4e-03 6e-03 5e-04\n 7: 2.3036e-02 2.2576e-02 8e-03 2e-03 3e-03 2e-04\n 8: 2.2906e-02 2.2677e-02 4e-03 1e-03 2e-03 8e-05\n 9: 2.3006e-02 2.2782e-02 4e-03 1e-03 2e-03 7e-05\n10: 2.2753e-02 2.2704e-02 7e-04 2e-04 3e-04 1e-05\n11: 2.2693e-02 2.2669e-02 3e-04 9e-05 1e-04 4e-06\n12: 2.2636e-02 2.2632e-02 5e-05 2e-05 2e-05 6e-07\n13: 2.2630e-02 2.2628e-02 2e-05 6e-06 8e-06 2e-07\n14: 2.2628e-02 2.2628e-02 1e-05 4e-06 5e-06 1e-07\n15: 2.2626e-02 2.2626e-02 2e-06 6e-07 8e-07 2e-08\n16: 2.2626e-02 2.2626e-02 6e-07 2e-07 3e-07 6e-09\n17: 2.2626e-02 2.2626e-02 1e-07 3e-08 5e-08 1e-09\n18: 2.2626e-02 2.2626e-02 4e-08 1e-08 2e-08 4e-10\nOptimal solution found.\n" ], [ "# Take the frequency response\n#samples = 10*np.log10(y)\n# Normalize the samples\n#ff = x*1e6/6e9\n\n# Take the frequency response\nsamples = sawfilter.s21.s_db[:,0,0]\n# Normalize the samples\nff = sawfilter.f/6e9\n\n# Compute frequency response data\nresp_opti = evalTF(ntf_opti, np.exp(1j*2*np.pi*ff))\n\n# Plot the output filter, \nplt.figure()\nplt.plot(ff*6e9, dbv(resp_opti), 'r', label=\"Optimal NTF\")\nplt.plot(ff*6e9, samples, 'b', label=\"External Filter\")\nplt.plot(ff*6e9, dbv(resp_opti) + samples, 'g', label=\"Resulting Noise Shape\")\nplt.gca().set_xlim(0, 3e9)\nplt.legend(loc=\"lower left\")\nplt.suptitle(\"Output filter and NTFs\")", "_____no_output_____" ], [ "sample_rate = 6e9\nmodulated = modulate_gmsk(prbs9(), sample_rate=sample_rate)\nxx_opti = simulateDSM(modulated, ntf_opti)", "_____no_output_____" ], [ "fftm = np.abs(fft(np.convolve(xx_opti[0], impulse_response_6g, mode=\"same\")))\nfftm = fftm/np.max(fftm)\n\nfftbins = fftfreq(len(fftm), 1/sample_rate)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftbins, 10*np.log10(fftm))\nplt.grid(b=True)\nplt.gca().set_ylim(-40, 0)\nplt.gca().set_xlim(0, 3e9)\nplt.title(\"Optimized Filtered Output\")", "_____no_output_____" ] ], [ [ "Wow, the baseline noise level has dropped by almost 10db! Impressive!", "_____no_output_____" ], [ "# Symbol Dictionaries\n\nNow that we've figured out how much noise we can stifle with this setup, we can begin to design our transmitter.\n\nNow you may notice that the above noise transfer function filter is... quite expensive, clocking in at 51 coefficients. While we might be able to implement this on our FPGA, a better question is -- can we avoid it?\n\nGiven that we're transmitting digital data with a finite number of symbols, it turns out we can just pre-compute the symbols, store them in a dictionary and then play back the relevant pre-processed symbol when we need to transmit a given symbol. Simple!\n\nExcept, GMSK is not _quite_ that simple in this context because not only do we have to consider 1s and 0s but also where we currently are on a phase plot. If you think about GMSK visually on a constellation diagram, one symbols is recomended by a 90 degree arc on a unit circle that is either moving clockwise or counter clockwise. This is futher complicated by the fact that the gaussian smoothing, makes the velocity of the arc potentially slow down if the next bit is different from the current bit (because it needs to gradually change direction).\n\nThe result of this (if you enumerate out all the computations) is that we actually end up with a 32-symbol table. This is not the _only_ way to simplify these symbols, nor the most efficient, but it's simplest from an implementation perspective. I spent some time figuring out a train of bits that would iterate through each symbol. I'm sur ethere's a more optimal pattern, but efficiency is not hugely important when we only need to run this once when precomputing.", "_____no_output_____" ] ], [ [ "carrier_freq = 2.402e9\nsample_rate = 6e9\nsymbol_rate = 1e6\nsamples_per_symbol = int(sample_rate/symbol_rate)\n\n# Used to test that we've mapped things correctly.\n# Note that this returns the phase angle, not the output bits\ndef demodulate_gmsk(sig, phase_offset=0):\n I = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(sig), phase=0 + phase_offset)\n Q = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(sig), phase=np.pi/2 + phase_offset)\n\n # Mix down to (complex) baseband\n down = sig*I + 1j*sig*Q\n\n # Create a low pass filter at the symbol rate\n sos = signal.butter(5, symbol_rate, 'low', fs=sample_rate, output='sos')\n filtered_down = signal.sosfilt(sos, down)\n\n # Take the phase angle of the baseband\n return np.angle(filtered_down)\n\n\n# The sequence of bits to modulate\nseq = [0, 0, 0, 1, 1, 1, \n 0, 0, 1, 0, 1, 1,\n 0, 0,\n 1, 0, 1, 0, 1, 0,\n 0, 1,\n 1, 0, 1, 0, 0, 0]\n# The relevant samples to pull out and store in the dictionary\nsamples = np.array([1, 4, 7, 10, 14, 17, 22, 25])\n\nfig, axs = plt.subplots(4, 8, sharey=True, figsize=(24, 12))\ndictionary = np.zeros((4*8, samples_per_symbol))\n\nfor q in range(4):\n current_angle = [0, np.pi/2, np.pi, np.pi*3/2][q]\n\n # Modulate the symbol with out optimized delta-sigma-modulator\n modulated, angle = modulate_gmsk(seq, phase_offset=current_angle, sample_rate=sample_rate, include_phase=True)\n modulated = simulateDSM(modulated, ntf_opti)[0]\n demodulated = demodulate_gmsk(modulated, phase_offset=0)\n\n n = 0\n for i in samples:\n iqsymbol = modulated[samples_per_symbol*i:samples_per_symbol*(i+1)]\n dictionary[q*8 + n,:] = iqsymbol\n axs[q, n].plot(np.unwrap(angle[samples_per_symbol*i:samples_per_symbol*(i+1)]))\n n += 1", "_____no_output_____" ] ], [ [ "With these established, let's concatenate a few symbols together, demodulate to phase angle and make sure things look nice and smooth", "_____no_output_____" ] ], [ [ "def sim(out):\n carrier=2.402e9\n I = make_carrier(freq=carrier, sample_rate=sample_rate, samples=len(out), phase=0)\n Q = make_carrier(freq=carrier, sample_rate=sample_rate, samples=len(out), phase=np.pi/2)\n \n sos = signal.butter(2, symbol_rate, 'low', fs=sample_rate, output='sos')\n rx_baseband = signal.sosfilt(sos, out*I + 1j*out*Q)\n \n plt.plot(np.angle(rx_baseband))\n\nsim(np.concatenate((dictionary[4,:], dictionary[5,:], dictionary[4,:], dictionary[5,:])))\nsim(-1.0*np.concatenate((dictionary[13,:], dictionary[12,:], dictionary[13,:], dictionary[12,:])))\n\nsim(np.concatenate((dictionary[21,:], dictionary[20,:], dictionary[21,:], dictionary[20,:])))\nsim(-1.0*np.concatenate((dictionary[28,:], dictionary[29,:], dictionary[28,:], dictionary[29,:])))", "_____no_output_____" ] ], [ [ "Now, in order to synthesize this, we need a bit more logic to map between a bit stream and its respective symbols.\n\nNote that there is additional state (i.e. the current phase offset) that factors into the symbol encoding beyond just the symbol value itself, which makes things a bit more complicate than most other forms of simple modulation. The code below keeps track of the starting phase angle at a given symbol as well as the before and after symbols to then output the right symbol.", "_____no_output_____" ] ], [ [ "idx = {\n '000': 0,\n '111': 1,\n '001': 2,\n '011': 3,\n '010': 4,\n '101': 5,\n '110': 6,\n '100': 7\n}\n\nstart_q = [\n [3, 2, 3, 2, 2, 3, 2, 3],\n [0, 3, 0, 3, 3, 0, 3, 0],\n [1, 0, 1, 0, 0, 1, 0, 1],\n [2, 1, 2, 1, 1, 2, 1, 2]\n]\n\ndef encode(bitstream):\n out = np.zeros((len(bitstream)*samples_per_symbol,))\n q = 0\n prev = bitstream[0]\n bitstream = bitstream + [bitstream[-1]] # Pad at the end so we can do a lookup\n syms = []\n for i in range(len(bitstream) - 1):\n n = idx[str(prev) + str(bitstream[i]) + str(bitstream[i+1])]\n d = -1\n for j in range(4):\n if start_q[j][n] == q:\n d = j*8 + n\n assert d != -1\n syms.append(d)\n out[i*samples_per_symbol:(i+1)*samples_per_symbol] = dictionary[d]\n if bitstream[i]:\n q = (q + 1) % 4\n else:\n q = (q + 4 - 1) % 4\n prev = bitstream[i]\n \n return out, syms\n\n# Whitened bits from elsewhere\nwbits = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1]\nout, syms = encode([1 - b for b in wbits])\n\n# Let's look at the resulting symbol indexes\nprint(syms)", "[22, 21, 20, 21, 20, 21, 20, 21, 20, 23, 10, 12, 13, 12, 15, 2, 4, 7, 24, 16, 8, 2, 4, 7, 26, 27, 6, 5, 3, 9, 22, 21, 20, 23, 8, 2, 3, 9, 22, 23, 8, 0, 24, 18, 19, 25, 6, 7, 26, 28, 29, 27, 1, 14, 15, 2, 4, 7, 24, 18, 19, 30, 31, 16, 8, 2, 3, 14, 15, 2, 3, 9, 17, 30, 31, 18, 19, 25, 6, 5, 3, 14, 15, 2, 3, 14, 13, 12, 13, 11, 17, 30, 31, 18, 20, 21, 19, 25, 1, 9, 22, 21, 19, 30, 31, 16, 10, 12, 15, 0, 26, 27, 1, 9, 17, 30, 31, 18, 19, 25, 1, 14, 13, 12, 13, 11, 17, 30, 29, 28, 29, 27, 1, 14, 13, 11, 22, 23, 8, 0, 26, 27, 6, 5, 4, 7, 24, 16, 8, 2, 3, 9, 17, 25, 6, 7, 26, 28, 31, 16, 8, 0, 24, 18, 20, 21, 20, 23, 10, 11, 22, 21, 19, 25, 1, 14, 15, 0, 24, 16, 8, 2, 4, 5, 4, 7, 24, 18, 20, 23, 8, 2, 3, 9, 17, 30, 31, 16, 8, 0, 24, 18, 19, 30, 29, 28, 31, 18, 20, 21, 20, 23, 10, 11, 17, 30, 29, 28, 31, 16, 8, 0, 26, 27, 1, 14, 15, 0, 26, 27, 6, 7, 24, 18, 19, 25, 6, 7, 24, 16, 8, 0, 26, 28, 29, 27, 1, 9, 17, 25, 1, 9, 17, 30, 29, 28, 29, 27, 6, 5, 3, 14, 15, 0]\n" ] ], [ [ "As a reminder, the dictionary is really just one bit of precision:", "_____no_output_____" ] ], [ [ "dictionary[0][:100]", "_____no_output_____" ] ], [ [ "Let's demodulate the encoded bits to check that things make sense (note that the filtering will delay the output a bit in time, but it demodulates correctly)", "_____no_output_____" ] ], [ [ "def demodulate_gmsk(sig):\n carrier_freq=2.402e9\n I = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(sig), phase=0)\n Q = make_carrier(freq=carrier_freq, sample_rate=sample_rate, samples=len(sig), phase=np.pi/2)\n\n # Mix down to (complex) baseband\n down = sig*I + 1j*sig*Q\n\n # Create a low pass filter at the symbol rate\n sos = signal.butter(5, symbol_rate, 'low', fs=sample_rate, output='sos')\n filtered_down = signal.sosfilt(sos, down)\n\n # Take the phase angle of the baseband\n angle = np.unwrap(np.angle(filtered_down))\n\n # Take the derivative of the phase angle and hard limit it to 1:-1\n return -(np.sign(angle[1:] - angle[:-1]) + 1.0)/2.0\n\nplt.figure(figsize=(40,3))\nplt.plot(demodulate_gmsk(out))\nplt.plot(np.repeat(wbits, int(sample_rate/1e6)) + 1.5)\nplt.gca().set_xlim(0, 0.6e6)", "_____no_output_____" ], [ "fftout = np.abs(fft(out))\nfftout = fftout/np.max(fftout)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftfreq(len(out), d=1/sample_rate), 10*np.log(fftout))\nplt.gca().set_xlim(0, 3e9)\nplt.gca().set_ylim(-80, 0)\nplt.title(\"BLE Packet Before Reconstruction Filter\")\nplt.show()\n\nfftm = np.abs(fft(np.convolve(out, impulse_response_6g, mode=\"same\")))\nfftm = fftm/np.max(fftm)\n\nplt.figure(figsize=(10,6))\nplt.plot(fftfreq(len(out), d=1/sample_rate), 10*np.log(fftm))\nplt.gca().set_xlim(0, 3e9)\nplt.gca().set_ylim(-80, 0)\nplt.title(\"BLE Packet After Reconstruction Filter\")\nplt.show()\n\nplt.figure(figsize=(10,6))\nplt.plot(fftfreq(len(out), d=1/sample_rate), 10*np.log(fftm))\nplt.gca().set_xlim(2.402e9 - 5e6, 2.402e9 + 5e6)\nplt.gca().set_ylim(-80, 0)\nplt.title(\"BLE Packet After Reconstruction Filter (10MHz span)\")", "_____no_output_____" ] ], [ [ "The library used to generate the NTF filter uses a copyleft license, so rather than integrate that into the code, we save out the resulting symbol waveforms and use those directly.", "_____no_output_____" ] ], [ [ "np.save('../data/gmsk_2402e6_6e9.npy', dictionary)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb0afb929fbe17c57b34060e5169126493ef641c
46,599
ipynb
Jupyter Notebook
model-read.ipynb
jzmnd/RRAM_network_analysis_model
f05a62cca2e5c46a348b7dd45a6afd000a60ee6c
[ "MIT" ]
1
2017-12-19T14:52:24.000Z
2017-12-19T14:52:24.000Z
model-read.ipynb
jzmnd/RRAM_network_analysis_model
f05a62cca2e5c46a348b7dd45a6afd000a60ee6c
[ "MIT" ]
null
null
null
model-read.ipynb
jzmnd/RRAM_network_analysis_model
f05a62cca2e5c46a348b7dd45a6afd000a60ee6c
[ "MIT" ]
1
2019-09-10T13:54:30.000Z
2019-09-10T13:54:30.000Z
131.635593
18,086
0.870083
[ [ [ "%matplotlib inline", "_____no_output_____" ], [ "import numpy as np\nfrom scipy.sparse.linalg import spsolve\nfrom scipy.sparse import csr_matrix\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom condlib import conductance_matrix_READ\nfrom timeit import default_timer as timer", "_____no_output_____" ], [ "# Memory array parameters\nrL = 12\nrHRS = 1e6\nrPU = 1e3\nn = 16\nvRead = [0.5, 1.0, 1.6, 2.0, 2.5, 3.0, 4.0]", "_____no_output_____" ], [ "hubList = []\nlsbList = []\nWLvoltagesList = []\nBLvoltagesList = []\ncellVoltagesList = []\nmask = np.ones((n, n), dtype=bool)\nmask[n-1][n-1] = False", "_____no_output_____" ], [ "for v in vRead:\n # Voltages for BLs and WLs (read voltages, unselected floating)\n vBLsel = 0.0\n vWLsel = v\n\n start_t = timer()\n # Create conductance matrix\n conductancematrix, iinvector = conductance_matrix_READ(n, rL, rHRS, rPU,\n vWLsel, vBLsel,\n isel=n-1, jsel=n-1, verbose=False)\n # Convert to sparse matrix (CSR)\n conductancematrix = csr_matrix(conductancematrix)\n # Solve\n voltages = spsolve(conductancematrix, iinvector)\n stop_t = timer()\n\n # Separate WL and BL nodes and calculate cell voltages\n WLvoltages = voltages[:n*n].reshape((n, n))\n BLvoltages = voltages[n*n:].reshape((n, n))\n WLvoltagesList.append(WLvoltages)\n BLvoltagesList.append(BLvoltages)\n\n cellVoltages = abs(BLvoltages - WLvoltages)\n cellVoltagesList.append(cellVoltages)\n\n # Calculate Highest Unselected Bit and Lowest Selected Bit\n hub = np.max(cellVoltages[mask])\n lsb = cellVoltages[n-1][n-1]\n hubList.append(hub)\n lsbList.append(lsb)\n \n print \"{:.4f} sec\".format(stop_t - start_t)\n print \"Write voltage : {:.4f} V\".format(v)\n print \"Highest unselected bit : {:.4f} V\".format(hub)\n print \"Lowest selected bit : {:.4f} V\".format(lsb)", "0.0077 sec\nWrite voltage : 0.5000 V\nHighest unselected bit : 0.2380 V\nLowest selected bit : 0.4911 V\n0.0052 sec\nWrite voltage : 1.0000 V\nHighest unselected bit : 0.4760 V\nLowest selected bit : 0.9822 V\n0.0067 sec\nWrite voltage : 1.6000 V\nHighest unselected bit : 0.7615 V\nLowest selected bit : 1.5715 V\n0.0048 sec\nWrite voltage : 2.0000 V\nHighest unselected bit : 0.9519 V\nLowest selected bit : 1.9644 V\n0.0054 sec\nWrite voltage : 2.5000 V\nHighest unselected bit : 1.1899 V\nLowest selected bit : 2.4555 V\n0.0058 sec\nWrite voltage : 3.0000 V\nHighest unselected bit : 1.4279 V\nLowest selected bit : 2.9467 V\n0.0049 sec\nWrite voltage : 4.0000 V\nHighest unselected bit : 1.9038 V\nLowest selected bit : 3.9289 V\n" ], [ "if n < 9:\n sns.heatmap(WLvoltagesList[2], square=True)\nelse:\n sns.heatmap(WLvoltagesList[2], square=True, xticklabels=n/8, yticklabels=n/8)\nplt.savefig(\"figures/read_mapWL_{}.png\".format(n), dpi=300)", "_____no_output_____" ], [ "if n < 9:\n sns.heatmap(BLvoltagesList[2], square=True)\nelse:\n sns.heatmap(BLvoltagesList[2], square=True, xticklabels=n/8, yticklabels=n/8)\nplt.savefig(\"figures/read_mapBL_{}.png\".format(n), dpi=300, figsize=(10,10))", "_____no_output_____" ], [ "if n < 9:\n sns.heatmap(cellVoltagesList[2], square=True)\nelse:\n sns.heatmap(cellVoltagesList[2], square=True, xticklabels=n/8, yticklabels=n/8)\nplt.savefig(\"figures/read_mapCell_{}.png\".format(n), dpi=300, figsize=(10,10))", "_____no_output_____" ], [ "plt.plot(vRead, hubList, vRead, lsbList)\nplt.plot([0.5, 4], [1.1, 1.1], [0.5, 4], [2.2, 2.2], c='gray', ls='--')\nplt.plot([0.5, 4], [1.2, 1.2], c='gray', ls='--')\nplt.xlim([0,4.5])\nplt.ylim([0,4.5])\nplt.ylabel(\"Vcell\")\nplt.xlabel(\"Vread\")\nplt.savefig(\"figures/read_margin_{}.png\".format(n), dpi=300, figsize=(10,12))\nplt.show()", "_____no_output_____" ], [ "# Find window\nwindowlsb = np.interp([1.2, 2.2], lsbList, vRead)\nwindowhub = np.interp(1.1, hubList, vRead)\nprint windowlsb\nprint windowhub", "[ 1.22172479 2.23982878]\n2.31112066614\n" ], [ "# Output data to csv\nnp.savetxt(\"data/read_margin_{}.csv\".format(n),\n np.vstack((vRead, lsbList, hubList)).T,\n delimiter=',',\n header=\"Vread,VcellLSB,VcellHUB\",\n footer=\",WindowLSB = {} - {}, WindowHSB < {}\".format(windowlsb[0], windowlsb[1], windowhub),\n comments='')\nnp.savetxt(\"data/read_mapCell_{}.csv\".format(n),\n cellVoltagesList[2],\n delimiter=',')\nnp.savetxt(\"data/read_mapWL_{}.csv\".format(n),\n WLvoltagesList[2],\n delimiter=',')\nnp.savetxt(\"data/read_mapBL_{}.csv\".format(n),\n BLvoltagesList[2],\n delimiter=',')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0afebf3e247ed02461898483a5d83628a7f918
69,621
ipynb
Jupyter Notebook
notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb
zekearneodo/ceciestunepipe
7e771783769816f37de44077177152175aecc2b7
[ "MIT" ]
null
null
null
notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb
zekearneodo/ceciestunepipe
7e771783769816f37de44077177152175aecc2b7
[ "MIT" ]
null
null
null
notebooks/pipeline/z_w12m7_20/sglx_preprocess-z_w12m7_20-multisess-pouli.ipynb
zekearneodo/ceciestunepipe
7e771783769816f37de44077177152175aecc2b7
[ "MIT" ]
null
null
null
57.207067
1,593
0.651413
[ [ [ "# Pre-processing pipeline for spikeglx sessions, zebra finch\nBird z_w12m7_20\n\n- For every run in the session:\n - Load the recordings\n - Extract wav chan with micrhopohone and make a wav chan with the nidq syn signal\n - Get the sync events for the nidq sync channel\n \n - Do bout detection\n \nIn another notebook, bout detection is curated\n- Left to decide where to:\n - Sort spikes\n - Sync the spikes/lfp/nidq\n - make and plot 'bout rasters'", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport os\nimport glob\nimport logging\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom scipy.io import wavfile\nfrom scipy import signal\nimport traceback\nimport warnings\n\nfrom matplotlib import pyplot as plt\nfrom importlib import reload\n\nlogger = logging.getLogger()\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\n '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\nlogger.setLevel(logging.INFO)\n", "_____no_output_____" ], [ "from ceciestunepipe.file import bcistructure as et\nfrom ceciestunepipe.util import sglxutil as sglu\nfrom ceciestunepipe.util import rigutil as ru\nfrom ceciestunepipe.util import wavutil as wu\nfrom ceciestunepipe.util import syncutil as su\n\nfrom ceciestunepipe.util.sound import boutsearch as bs\n\nfrom ceciestunepipe.util.spikeextractors import preprocess as pre\nfrom ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor import readSGLX as rsgl\nfrom ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor import spikeglxrecordingextractor as sglex", "h5py version > 2.10.0. Some extractors might not work properly. It is recommended to downgrade to version 2.10.0: \n>>> pip install h5py==2.10.0\n" ], [ "import spikeinterface as si\nimport spikeinterface.extractors as se\nimport spikeinterface.toolkit as st\nimport spikeinterface.sorters as ss\nimport spikeinterface.comparison as sc\nimport spikeinterface.widgets as sw\nlogger.info('all modules loaded')", "2021-10-19 11:58:34,081 root INFO all modules loaded\n" ] ], [ [ "## Session parameters and raw files", "_____no_output_____" ], [ "#### list all the sessions for this bird", "_____no_output_____" ] ], [ [ "bird = 'z_w12m7_20'\nall_bird_sess = et.list_sessions(bird)\nlogger.info('all sessions for bird are {}'.format(all_bird_sess))", "2021-10-19 11:58:35,383 root INFO all sessions for bird are ['2020-11-04', '2020-11-05', '2020-11-06']\n" ] ], [ [ "### set up bird and sessions parameters\nthis will define:\n- locations of files (for the bird)\n- signals and channels to look for in the metadata of the files and in the rig.json parameter file: Note that this have to exist in all of the sessions that will be processed\n- 'sess' is unimportant here, but it comes handy if there is need to debug usin a single session", "_____no_output_____" ] ], [ [ "reload(et)\n# for one example session\n\nsess_par = {'bird': 'z_w12m7_20',\n 'sess': '2020-11-04',\n 'probes': ['probe_0'], #probes of interest\n 'mic_list': ['microphone_0'], #list of mics of interest, by signal name in rig.json\n 'sort': 4, #label for this sort instance\n }\n\nexp_struct = et.get_exp_struct(sess_par['bird'], sess_par['sess'], sort=sess_par['sort'])\n\nksort_folder = exp_struct['folders']['ksort']\nraw_folder = exp_struct['folders']['sglx']", "_____no_output_____" ] ], [ [ "list all the epochs in a session, to check that it is finding what it has to find", "_____no_output_____" ] ], [ [ "sess_epochs = et.list_sgl_epochs(sess_par)\nsess_epochs", "2021-10-19 11:58:37,438 ceciestunepipe.file.bcistructure INFO {'folders': {'bird': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20', 'raw': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04', 'sglx': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04/sglx', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04', 'processed': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx', 'derived': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx', 'tmp': '/experiment/tmp/tmp', 'msort': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-04', 'ksort': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-04'}, 'files': {'par': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-04/params.json', 'set': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04/sglx/settings.isf', 'rig': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04/sglx/rig.json', 'kwd': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04/stream.kwd', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04/sort_4/spikes.kwik', 'kwe': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04/events.kwe', 'dat_mic': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx/dat_mic.mat', 'dat_ap': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx/dat_ap.mat', 'allevents': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx/dat_all.pkl', 'wav_mic': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/wav_mic.wav', 'mda_raw': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-04/raw.mda', 'bin_raw': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-04/raw.bin'}}\n" ] ], [ [ "#### define pre-processing steps for each epoch and for the session", "_____no_output_____" ] ], [ [ "def preprocess_run(sess_par, exp_struct, epoch):\n # get the recordings\n logger.info('PREPROCESSING sess {} | epoch {}'.format(sess_par['sess'], epoch))\n logger.info('getting extractors')\n sgl_exp_struct = et.sgl_struct(sess_par, epoch)\n run_recs_dict, run_meta_files, files_pd, rig_dict = pre.load_sglx_recordings(sgl_exp_struct, epoch)\n \n # get the microphone to wav\n # get the chans\n mic_list = sess_par['mic_list']\n logger.info('Getting microphone channel(s) {}'.format(mic_list))\n mic_stream = pre.extract_nidq_channels(sess_par, run_recs_dict, rig_dict, mic_list, chan_type='adc')\n # get the sampling rate\n nidq_s_f = run_recs_dict['nidq'].get_sampling_frequency()\n \n mic_file_path = os.path.join(sgl_exp_struct['folders']['derived'], 'wav_mic.wav')\n wav_s_f = wu.save_wav(mic_stream, nidq_s_f, mic_file_path)\n \n \n # get the syn to wav\n # get the chans\n sync_list = ['sync']\n logger.info('Getting sync channel(s) {}'.format(sync_list))\n sync_stream = pre.extract_nidq_channels(sess_par, run_recs_dict, rig_dict, sync_list, chan_type='ttl')\n \n sync_file_path = os.path.join(sgl_exp_struct['folders']['derived'], 'wav_sync.wav')\n wav_s_f = wu.save_wav(sync_stream, nidq_s_f, sync_file_path)\n \n logger.info('Getting sync events from the wav sync channel')\n sync_ev_path = os.path.join(sgl_exp_struct['folders']['derived'], 'wav_sync_evt.npy')\n wav_s_f, x_d, ttl_arr = wu.wav_to_syn(sync_file_path)\n logger.info('saving sync events of the wav channel to {}'.format(sync_ev_path))\n np.save(sync_ev_path, ttl_arr)\n \n t_0_path = os.path.join(sgl_exp_struct['folders']['derived'], 'wav_t0.npy')\n logger.info('saving t0 for wav channel to {}'.format(t_0_path))\n np.save(t_0_path, np.arange(sync_stream.size)/wav_s_f)\n #make the sync dict\n syn_dict = {'s_f': wav_s_f,\n 't_0_path': t_0_path,\n 'evt_arr_path': sync_ev_path}\n \n syn_dict_path = os.path.join(sgl_exp_struct['folders']['derived'], '{}_sync_dict.pkl'.format('wav'))\n syn_dict['path'] = syn_dict_path\n logger.info('saving sync dict to ' + syn_dict_path)\n with open(syn_dict_path, 'wb') as pf:\n pickle.dump(syn_dict, pf)\n\n epoch_dict = {'epoch': epoch,\n 'files_pd': files_pd,\n 'recordings': run_recs_dict,\n 'meta': run_meta_files,\n 'rig': rig_dict}\n \n return epoch_dict\n\n \none_epoch_dict = preprocess_run(sess_par, exp_struct, sess_epochs[1])", "2021-10-19 11:58:39,204 root INFO PREPROCESSING sess 2020-11-04 | epoch 2500r250a_3500_dir_g1\n2021-10-19 11:58:39,205 root INFO getting extractors\n2021-10-19 11:58:39,244 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 11:58:39,245 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 11:58:39,246 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_mic.wav\n2021-10-19 11:58:39,823 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_mic.npy\n2021-10-19 11:58:41,129 root INFO Getting sync channel(s) ['sync']\n2021-10-19 11:58:41,130 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 11:58:41,686 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 11:58:41,686 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync.wav\n2021-10-19 11:58:42,154 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync.npy\n2021-10-19 11:58:42,618 root INFO Getting sync events from the wav sync channel\n2021-10-19 11:58:42,786 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync_evt.npy\n2021-10-19 11:58:42,792 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_t0.npy\n2021-10-19 11:58:44,779 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync_dict.pkl\n" ], [ "### sequentially process all runs of the sessions\ndef preprocess_session(sess_par: dict):\n logger.info('pre-process all runs of sess ' + sess_par['sess'])\n # get exp struct\n sess_struct = et.get_exp_struct(sess_par['bird'], sess_par['sess'], sort=sess_par['sort'])\n # list the epochs\n sess_epochs = et.list_sgl_epochs(sess_par)\n logger.info('found epochs: {}'.format(sess_epochs))\n # preprocess all epochs\n epoch_dict_list = []\n for i_ep, epoch in enumerate(sess_epochs):\n try:\n exp_struct = et.sgl_struct(sess_par, epoch)\n one_epoch_dict = preprocess_run(sess_par, exp_struct, epoch)\n epoch_dict_list.append(one_epoch_dict)\n except Exception as exc:\n warnings.warn('Error in epoch {}'.format(epoch), UserWarning)\n logger.info(traceback.format_exc)\n logger.info(exc)\n logger.info('Session {} epoch {} could not be preprocessed'.format(sess_par['sess'], epoch))\n \n return epoch_dict_list\n\nall_epoch_list = preprocess_session(sess_par)", "_____no_output_____" ] ], [ [ "## Process multiple sessions", "_____no_output_____" ] ], [ [ "sess_list = all_bird_sess\n# fist implant, right hemisphere\nsess_list = ['2020-11-04', '2020-11-05', '2020-11-06']", "_____no_output_____" ], [ "all_sess_dict = {}\n\nfor one_sess in sess_list[:]:\n sess_par['sess'] = one_sess\n preprocess_session(sess_par)", "2021-10-19 13:02:14,812 root INFO pre-process all runs of sess 2020-11-04\n2021-10-19 13:02:14,814 ceciestunepipe.file.bcistructure INFO {'folders': {'bird': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20', 'raw': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04', 'sglx': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04/sglx', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04', 'processed': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx', 'derived': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx', 'tmp': '/experiment/tmp/tmp', 'msort': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-04', 'ksort': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-04'}, 'files': {'par': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-04/params.json', 'set': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04/sglx/settings.isf', 'rig': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-04/sglx/rig.json', 'kwd': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04/stream.kwd', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04/sort_4/spikes.kwik', 'kwe': '/experiment/z_w12m7_20/sglx/kwik/2020-11-04/events.kwe', 'dat_mic': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx/dat_mic.mat', 'dat_ap': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx/dat_ap.mat', 'allevents': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-04/sglx/dat_all.pkl', 'wav_mic': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/wav_mic.wav', 'mda_raw': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-04/raw.mda', 'bin_raw': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-04/raw.bin'}}\n2021-10-19 13:02:14,830 root INFO found epochs: ['2500r250a_3500_dir_g0', '2500r250a_3500_dir_g1', '2500r250a_3500_dir_g2']\n2021-10-19 13:02:14,831 root INFO PREPROCESSING sess 2020-11-04 | epoch 2500r250a_3500_dir_g0\n2021-10-19 13:02:14,832 root INFO getting extractors\n2021-10-19 13:02:15,131 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 13:02:15,132 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:02:15,133 ceciestunepipe.util.wavutil INFO saving (1, 191052384)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_mic.wav\n2021-10-19 13:02:41,396 ceciestunepipe.util.wavutil INFO saving (1, 191052384)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_mic.npy\n2021-10-19 13:02:51,054 root INFO Getting sync channel(s) ['sync']\n2021-10-19 13:02:51,055 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 13:02:55,092 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:02:55,093 ceciestunepipe.util.wavutil INFO saving (1, 191052384)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_sync.wav\n2021-10-19 13:02:58,699 ceciestunepipe.util.wavutil INFO saving (1, 191052384)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_sync.npy\n2021-10-19 13:03:02,306 root INFO Getting sync events from the wav sync channel\n2021-10-19 13:03:03,621 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_sync_evt.npy\n2021-10-19 13:03:03,644 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_t0.npy\n2021-10-19 13:03:18,865 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_sync_dict.pkl\n2021-10-19 13:03:19,039 root INFO PREPROCESSING sess 2020-11-04 | epoch 2500r250a_3500_dir_g1\n2021-10-19 13:03:19,040 root INFO getting extractors\n2021-10-19 13:03:19,172 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 13:03:19,173 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:03:19,174 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_mic.wav\n2021-10-19 13:03:23,653 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_mic.npy\n2021-10-19 13:03:24,941 root INFO Getting sync channel(s) ['sync']\n2021-10-19 13:03:24,942 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 13:03:25,452 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:03:25,453 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync.wav\n2021-10-19 13:03:25,962 ceciestunepipe.util.wavutil INFO saving (1, 23393601)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync.npy\n2021-10-19 13:03:26,423 root INFO Getting sync events from the wav sync channel\n2021-10-19 13:03:26,671 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync_evt.npy\n2021-10-19 13:03:26,676 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_t0.npy\n2021-10-19 13:03:28,616 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g1/wav_sync_dict.pkl\n2021-10-19 13:03:28,636 root INFO PREPROCESSING sess 2020-11-04 | epoch 2500r250a_3500_dir_g2\n2021-10-19 13:03:28,637 root INFO getting extractors\n2021-10-19 13:03:28,734 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 13:03:28,735 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:03:28,735 ceciestunepipe.util.wavutil INFO saving (1, 3340000)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g2/wav_mic.wav\n2021-10-19 13:03:29,432 ceciestunepipe.util.wavutil INFO saving (1, 3340000)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g2/wav_mic.npy\n2021-10-19 13:03:29,660 root INFO Getting sync channel(s) ['sync']\n2021-10-19 13:03:29,661 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 13:03:29,743 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:03:29,744 ceciestunepipe.util.wavutil INFO saving (1, 3340000)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g2/wav_sync.wav\n2021-10-19 13:03:29,827 ceciestunepipe.util.wavutil INFO saving (1, 3340000)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g2/wav_sync.npy\n2021-10-19 13:03:29,920 root INFO Getting sync events from the wav sync channel\n2021-10-19 13:03:29,948 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g2/wav_sync_evt.npy\n2021-10-19 13:03:29,952 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g2/wav_t0.npy\n2021-10-19 13:03:30,252 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g2/wav_sync_dict.pkl\n2021-10-19 13:03:30,386 root INFO pre-process all runs of sess 2020-11-05\n2021-10-19 13:03:30,387 ceciestunepipe.file.bcistructure INFO {'folders': {'bird': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20', 'raw': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-05', 'sglx': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-05/sglx', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-05', 'processed': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-05/sglx', 'derived': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx', 'tmp': '/experiment/tmp/tmp', 'msort': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-05', 'ksort': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-05'}, 'files': {'par': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-05/params.json', 'set': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-05/sglx/settings.isf', 'rig': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-05/sglx/rig.json', 'kwd': '/experiment/z_w12m7_20/sglx/kwik/2020-11-05/stream.kwd', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-05/sort_4/spikes.kwik', 'kwe': '/experiment/z_w12m7_20/sglx/kwik/2020-11-05/events.kwe', 'dat_mic': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-05/sglx/dat_mic.mat', 'dat_ap': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-05/sglx/dat_ap.mat', 'allevents': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-05/sglx/dat_all.pkl', 'wav_mic': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/wav_mic.wav', 'mda_raw': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-05/raw.mda', 'bin_raw': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-05/raw.bin'}}\n2021-10-19 13:03:30,390 root INFO found epochs: ['dir_g0', 'dir_m101_extref_g0', 'dir_m101_g0']\n2021-10-19 13:03:30,391 root INFO PREPROCESSING sess 2020-11-05 | epoch dir_g0\n2021-10-19 13:03:30,391 root INFO getting extractors\n2021-10-19 13:03:30,499 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 13:03:30,500 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:03:30,501 ceciestunepipe.util.wavutil INFO saving (1, 141651680)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_g0/wav_mic.wav\n2021-10-19 13:03:58,467 ceciestunepipe.util.wavutil INFO saving (1, 141651680)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_g0/wav_mic.npy\n2021-10-19 13:04:05,663 root INFO Getting sync channel(s) ['sync']\n2021-10-19 13:04:05,664 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 13:04:08,696 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:04:08,697 ceciestunepipe.util.wavutil INFO saving (1, 141651680)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_g0/wav_sync.wav\n2021-10-19 13:04:11,368 ceciestunepipe.util.wavutil INFO saving (1, 141651680)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_g0/wav_sync.npy\n2021-10-19 13:04:14,017 root INFO Getting sync events from the wav sync channel\n2021-10-19 13:04:14,947 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_g0/wav_sync_evt.npy\n2021-10-19 13:04:14,954 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_g0/wav_t0.npy\n2021-10-19 13:04:26,068 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_g0/wav_sync_dict.pkl\n2021-10-19 13:04:26,092 root INFO PREPROCESSING sess 2020-11-05 | epoch dir_m101_extref_g0\n2021-10-19 13:04:26,093 root INFO getting extractors\n2021-10-19 13:04:26,213 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 13:04:26,214 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:04:26,215 ceciestunepipe.util.wavutil INFO saving (1, 10843457)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_extref_g0/wav_mic.wav\n2021-10-19 13:04:28,274 ceciestunepipe.util.wavutil INFO saving (1, 10843457)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_extref_g0/wav_mic.npy\n2021-10-19 13:04:28,873 root INFO Getting sync channel(s) ['sync']\n2021-10-19 13:04:28,874 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 13:04:29,116 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:04:29,117 ceciestunepipe.util.wavutil INFO saving (1, 10843457)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_extref_g0/wav_sync.wav\n2021-10-19 13:04:29,322 ceciestunepipe.util.wavutil INFO saving (1, 10843457)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_extref_g0/wav_sync.npy\n2021-10-19 13:04:29,531 root INFO Getting sync events from the wav sync channel\n2021-10-19 13:04:29,622 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_extref_g0/wav_sync_evt.npy\n2021-10-19 13:04:29,626 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_extref_g0/wav_t0.npy\n2021-10-19 13:04:30,510 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_extref_g0/wav_sync_dict.pkl\n2021-10-19 13:04:30,515 root INFO PREPROCESSING sess 2020-11-05 | epoch dir_m101_g0\n2021-10-19 13:04:30,516 root INFO getting extractors\n2021-10-19 13:04:30,610 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 13:04:30,611 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:04:30,612 ceciestunepipe.util.wavutil INFO saving (1, 13042785)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_g0/wav_mic.wav\n2021-10-19 13:04:33,028 ceciestunepipe.util.wavutil INFO saving (1, 13042785)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_g0/wav_mic.npy\n2021-10-19 13:04:33,752 root INFO Getting sync channel(s) ['sync']\n2021-10-19 13:04:33,753 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 13:04:34,039 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:04:34,040 ceciestunepipe.util.wavutil INFO saving (1, 13042785)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_g0/wav_sync.wav\n2021-10-19 13:04:34,284 ceciestunepipe.util.wavutil INFO saving (1, 13042785)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_g0/wav_sync.npy\n2021-10-19 13:04:34,537 root INFO Getting sync events from the wav sync channel\n2021-10-19 13:04:34,634 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_g0/wav_sync_evt.npy\n2021-10-19 13:04:34,638 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_g0/wav_t0.npy\n2021-10-19 13:04:35,675 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-05/sglx/dir_m101_g0/wav_sync_dict.pkl\n2021-10-19 13:04:35,750 root INFO pre-process all runs of sess 2020-11-06\n2021-10-19 13:04:35,751 ceciestunepipe.file.bcistructure INFO {'folders': {'bird': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20', 'raw': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-06', 'sglx': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-06/sglx', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-06', 'processed': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-06/sglx', 'derived': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx', 'tmp': '/experiment/tmp/tmp', 'msort': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-06', 'ksort': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-06'}, 'files': {'par': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-06/params.json', 'set': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-06/sglx/settings.isf', 'rig': '/mnt/sphere/speech_bci/raw_data/z_w12m7_20/2020-11-06/sglx/rig.json', 'kwd': '/experiment/z_w12m7_20/sglx/kwik/2020-11-06/stream.kwd', 'kwik': '/experiment/z_w12m7_20/sglx/kwik/2020-11-06/sort_4/spikes.kwik', 'kwe': '/experiment/z_w12m7_20/sglx/kwik/2020-11-06/events.kwe', 'dat_mic': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-06/sglx/dat_mic.mat', 'dat_ap': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-06/sglx/dat_ap.mat', 'allevents': '/mnt/sphere/speech_bci/processed_data/z_w12m7_20/2020-11-06/sglx/dat_all.pkl', 'wav_mic': '/mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/wav_mic.wav', 'mda_raw': '/experiment/tmp/z_w12m7_20/sglx/msort/2020-11-06/raw.mda', 'bin_raw': '/experiment/tmp/z_w12m7_20/sglx/ksort/2020-11-06/raw.bin'}}\n2021-10-19 13:04:35,755 root INFO found epochs: ['dir_g0']\n2021-10-19 13:04:35,756 root INFO PREPROCESSING sess 2020-11-06 | epoch dir_g0\n2021-10-19 13:04:35,756 root INFO getting extractors\n2021-10-19 13:04:35,913 root INFO Getting microphone channel(s) ['microphone_0']\n2021-10-19 13:04:35,914 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:04:35,915 ceciestunepipe.util.wavutil INFO saving (1, 349616384)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/dir_g0/wav_mic.wav\n2021-10-19 13:06:11,009 ceciestunepipe.util.wavutil INFO saving (1, 349616384)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/dir_g0/wav_mic.npy\n2021-10-19 13:06:28,862 root INFO Getting sync channel(s) ['sync']\n2021-10-19 13:06:28,863 ceciestunepipe.util.spikeextractors.extractors.spikeglxrecordingextractor.spikeglxrecordingextractor INFO getting ttl traces, chan range(0, 7)\n2021-10-19 13:06:43,417 ceciestunepipe.util.wavutil INFO sampling rate 25000\n2021-10-19 13:06:43,418 ceciestunepipe.util.wavutil INFO saving (1, 349616384)-shaped array as wav in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/dir_g0/wav_sync.wav\n2021-10-19 13:06:50,096 ceciestunepipe.util.wavutil INFO saving (1, 349616384)-shaped array as npy in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/dir_g0/wav_sync.npy\n2021-10-19 13:06:56,625 root INFO Getting sync events from the wav sync channel\n2021-10-19 13:07:00,034 root INFO saving sync events of the wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/dir_g0/wav_sync_evt.npy\n2021-10-19 13:07:00,047 root INFO saving t0 for wav channel to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/dir_g0/wav_t0.npy\n2021-10-19 13:07:34,819 root INFO saving sync dict to /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-06/sglx/dir_g0/wav_sync_dict.pkl\n" ], [ "sess_par", "_____no_output_____" ], [ "# Search bouts", "_____no_output_____" ] ], [ [ "## search bouts for those sessions", "_____no_output_____" ] ], [ [ "from ceciestunepipe.util.sound import boutsearch as bs\nfrom ceciestunepipe.util import wavutil as wu\n\nfrom joblib import Parallel, delayed\nimport pickle\nimport sys", "_____no_output_____" ], [ "reload(bs)", "_____no_output_____" ], [ "def sess_file_id(f_path):\n n = int(os.path.split(f_path)[1].split('-')[-1].split('.wav')[0])\n return n\n\n\ndef get_all_day_bouts(sess_par: dict, hparams:dict, n_jobs: int=12, ephys_software='sglx', \n parallel=True) -> pd.DataFrame:\n \n logger.info('Will search for bouts through all session {}, {}'.format(sess_par['bird'], sess_par['sess']))\n exp_struct = et.get_exp_struct(sess_par['bird'], sess_par['sess'], ephys_software=ephys_software)\n\n # get all the paths to the wav files of the epochs of the day \n source_folder = exp_struct['folders']['derived']\n logger.info('looking for mic wav files in {}'.format(source_folder))\n wav_path_list = et.get_sgl_files_epochs(source_folder, file_filter='*wav_mic.wav')\n wav_path_list.sort()\n logger.info('Found {} files'.format(len(wav_path_list)))\n print(wav_path_list)\n \n get_file_bouts = lambda path: bs.get_epoch_bouts(path, hparams)\n # Go parallel through all the paths in the day, get a list of all the pandas dataframes for each file\n if parallel:\n sess_pd_list = Parallel(n_jobs=n_jobs, verbose=100, prefer='threads')(delayed(get_file_bouts)(i) for i in wav_path_list)\n else:\n sess_pd_list = [get_file_bouts(i) for i in wav_path_list]\n \n #concatenate the file and return it, eventually write to a pickle\n sess_bout_pd = pd.concat(sess_pd_list)\n return sess_bout_pd\n\ndef save_auto_bouts(sess_bout_pd, sess_par, hparams):\n exp_struct = et.get_exp_struct(sess_par['bird'], sess_par['sess'], ephys_software='bouts_sglx')\n #sess_bouts_dir = os.path.join(exp_struct['folders']['derived'], 'bouts_ceciestunepipe')\n sess_bouts_dir = exp_struct['folders']['derived']\n\n sess_bouts_path = os.path.join(sess_bouts_dir, hparams['bout_auto_file'])\n hparams_pickle_path = os.path.join(sess_bouts_dir, 'bout_search_params.pickle')\n\n os.makedirs(sess_bouts_dir, exist_ok=True)\n logger.info('saving bouts pandas to ' + sess_bouts_path)\n sess_bout_pd.to_pickle(sess_bouts_path)\n\n logger.info('saving bout detect parameters dict to ' + hparams_pickle_path)\n with open(hparams_pickle_path, 'wb') as fh:\n pickle.dump(hparams, fh)", "_____no_output_____" ], [ "## need to enter 'sample_rate' from the file!\nhparams = {\n # spectrogram\n 'num_freq':1024, #1024# how many channels to use in a spectrogram #\n 'preemphasis':0.97, \n 'frame_shift_ms':5, # step size for fft\n 'frame_length_ms':10, #128 # frame length for fft FRAME SAMPLES < NUM_FREQ!!!\n 'min_level_db':-55, # minimum threshold db for computing spe \n 'ref_level_db':110, # reference db for computing spec\n #'sample_rate':None, # sample rate of your data\n \n # spectrograms\n 'mel_filter': False, # should a mel filter be used?\n 'num_mels':1024, # how many channels to use in the mel-spectrogram\n 'fmin': 500, # low frequency cutoff for mel filter\n 'fmax': 12000, # high frequency cutoff for mel filter\n \n # spectrogram inversion\n 'max_iters':200,\n 'griffin_lim_iters':20,\n 'power':1.5,\n\n # Added for the searching\n 'read_wav_fun': wu.read_wav_chan, # function for loading the wav_like_stream (has to returns fs, ndarray)\n 'file_order_fun': sess_file_id, # function for extracting the file id within the session\n 'min_segment': 10, # Minimum length of supra_threshold to consider a 'syllable' (ms)\n 'min_silence': 2000, # Minmum distance between groups of syllables to consider separate bouts (ms)\n 'min_bout': 200, # min bout duration (ms)\n 'peak_thresh_rms': 0.55, # threshold (rms) for peak acceptance,\n 'thresh_rms': 0.25, # threshold for detection of syllables\n 'mean_syl_rms_thresh': 0.3, #threshold for acceptance of mean rms across the syllable (relative to rms of the file)\n 'max_bout': 120000, #exclude bouts too long\n 'l_p_r_thresh': 100, # threshold for n of len_ms/peaks (typycally about 2-3 syllable spans\n \n 'waveform_edges': 1000, #get number of ms before and after the edges of the bout for the waveform sample\n \n 'bout_auto_file': 'bout_auto.pickle', # extension for saving the auto found files\n 'bout_curated_file': 'bout_checked.pickle', #extension for manually curated files (coming soon)\n }", "_____no_output_____" ], [ "all_sessions = sess_list[:]\n#all_sessions = ['2021-07-18']\n\nfor sess in all_sessions:\n sess_par['sess'] = sess\n sess_bout_pd = get_all_day_bouts(sess_par, hparams, parallel=False)\n save_auto_bouts(sess_bout_pd, sess_par, hparams)\n sess_bouts_folder = os.path.join(exp_struct['folders']['derived'], 'bouts')\n #bouts_to_wavs(sess_bout_pd, sess_par, hparams, sess_bouts_folder)", "2021-10-19 13:20:40,498 root INFO Will search for bouts through all session z_w12m7_20, 2020-11-04\n2021-10-19 13:20:40,500 root INFO looking for mic wav files in /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx\n2021-10-19 13:20:40,756 root INFO Found 3 files\n2021-10-19 13:20:40,758 ceciestunepipe.util.sound.boutsearch INFO Getting bouts for long file /mnt/sphere/speech_bci/derived_data/z_w12m7_20/2020-11-04/sglx/2500r250a_3500_dir_g0/wav_mic.wav\n" ], [ "get_all_day_bouts??", "_____no_output_____" ], [ "sess_bout_pd.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 103 entries, 0 to 37\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 start_ms 103 non-null int64 \n 1 end_ms 103 non-null int64 \n 2 start_sample 103 non-null int64 \n 3 end_sample 103 non-null int64 \n 4 p_step 103 non-null object \n 5 rms_p 103 non-null float64\n 6 peak_p 103 non-null float64\n 7 bout_check 103 non-null bool \n 8 file 103 non-null object \n 9 len_ms 103 non-null int64 \n 10 syl_in 103 non-null object \n 11 n_syl 103 non-null int64 \n 12 peaks_p 103 non-null object \n 13 n_peaks 103 non-null int64 \n 14 l_p_ratio 103 non-null float64\n 15 waveform 103 non-null object \n 16 confusing 103 non-null bool \ndtypes: bool(2), float64(3), int64(7), object(5)\nmemory usage: 13.1+ KB\n" ], [ "np.unique(sess_bout_pd['start_ms']).size", "_____no_output_____" ] ], [ [ "# debug", "_____no_output_____" ], [ "## debug search_bout", "_____no_output_____" ] ], [ [ "## look for a single file\nsess = sess_list[0]\n\nexp_struct = et.get_exp_struct(sess_par['bird'], sess, ephys_software='sglx')\nsource_folder = exp_struct['folders']['derived']\nwav_path_list = et.get_sgl_files_epochs(source_folder, file_filter='*wav_mic.wav')\nwav_path_list.sort()\nlogger.info('Found {} files'.format(len(wav_path_list)))\nprint(wav_path_list)", "2021-09-22 15:13:39,371 root INFO Found 4 files\n" ], [ "one_file = wav_path_list[0]", "_____no_output_____" ], [ "reload(bs)\nepoch_bout_pd, epoch_wav = bs.get_bouts_in_long_file(wav_path_list[0], hparams)", "2021-09-22 15:13:45,924 ceciestunepipe.util.sound.boutsearch INFO Getting bouts for long file /mnt/sphere/speech_bci/derived_data/s_b1253_21/2021-06-14/sglx/0712_g0/wav_mic.wav\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
cb0b135e145a60a6080bb6c1c1cd61bac05f76f3
3,448
ipynb
Jupyter Notebook
examples/voxel_callback.ipynb
LaGuer/K3D-jupyter
7be6f413c8a4787d3f3b83654cd5f311fd6d615d
[ "MIT" ]
null
null
null
examples/voxel_callback.ipynb
LaGuer/K3D-jupyter
7be6f413c8a4787d3f3b83654cd5f311fd6d615d
[ "MIT" ]
null
null
null
examples/voxel_callback.ipynb
LaGuer/K3D-jupyter
7be6f413c8a4787d3f3b83654cd5f311fd6d615d
[ "MIT" ]
null
null
null
29.220339
132
0.454756
[ [ [ "import k3d\nimport numpy as np\nfrom math import sqrt, sin, cos\nfrom skimage.measure import label\n\nwidth = height = length = 100\n\ndef r(x, y, z):\n r = sqrt((x - width / 2) * (x - width / 2) + (y - height / 2) * (y - height / 2) + (z - length / 2) * (z - length / 2))\n r += sin(x / 2) * 3\n r += cos(y / 10) * 5\n \n return r\n\ndef f(x, y, z):\n return 0 if r(x, y, z) > width / 2 else (1 if y + sin(x / 20) * 10 > height / 2 else 2)\n\ndef on_click(x, y, z):\n coords = [x, y, z]\n missing = None\n missing_count = 0\n \n for idx, v in enumerate([np.array([0,0,1]), np.array([0,1,0]), np.array([1,0,0])]):\n axis = coords[idx] \n \n if axis == 0 or (obj.voxels[tuple(np.array([z, y, x]) - v)] == 0):\n missing = -v\n missing_count += 1\n\n if axis == obj.voxels.shape[2 - idx] - 1 or obj.voxels[tuple(np.array([z, y, x]) + v)] == 0:\n missing = v\n missing_count += 1 \n \n if missing_count == 1: \n if missing[0] != 0:\n slice = obj.voxels[z, :, :]\n mask = label(slice, connectivity = 2) \n slice[mask == mask[y, x]] = plot.voxel_paint_color\n if missing[1] != 0:\n slice = obj.voxels[:, y, :]\n mask = label(slice, connectivity = 2)\n slice[mask == mask[z, x]] = plot.voxel_paint_color\n if missing[2] != 0:\n slice = obj.voxels[:, :, x]\n mask = label(slice, connectivity = 2)\n slice[mask == mask[z, y]] = plot.voxel_paint_color\n \n obj.push_data('voxels')\n \ncolor_map = (0xffff00, 0xff0000, 0x00ff00)\nvoxels = np.array([[[f(x, y, z) for x in range(width)] for y in range(height)] for z in range(length)])\n\nobj = k3d.voxels(voxels.astype(np.uint8), color_map)\nplot = k3d.plot()\nplot += obj\n\nobj.click_callback = on_click\nplot.voxel_paint_color = 3", "_____no_output_____" ], [ "# select Controls->Mode->Callback and click on object wall\nplot.display()", "_____no_output_____" ], [ "plot.camera_auto_fit = False", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cb0b1638ea8449e8d4e19b7f68ac8877e010355b
233,149
ipynb
Jupyter Notebook
docs/_static/notebooks/telescopes_tutorial_5.ipynb
LBJ-Wade/PsrSigSim
6b876005cd02c3d16254ef2368ddb7c140a90cfc
[ "MIT" ]
13
2020-03-06T16:41:05.000Z
2021-12-22T02:26:40.000Z
docs/_static/notebooks/telescopes_tutorial_5.ipynb
LBJ-Wade/PsrSigSim
6b876005cd02c3d16254ef2368ddb7c140a90cfc
[ "MIT" ]
80
2018-09-25T18:37:30.000Z
2021-09-16T13:39:43.000Z
docs/_static/notebooks/telescopes_tutorial_5.ipynb
LBJ-Wade/PsrSigSim
6b876005cd02c3d16254ef2368ddb7c140a90cfc
[ "MIT" ]
9
2018-10-29T14:31:40.000Z
2021-09-08T13:55:02.000Z
399.912521
71,224
0.936178
[ [ [ "# Telescopes: Tutorial 5\n\nThis notebook will build on the previous tutorials, showing more features of the `PsrSigSim`. Details will be given for new features, while other features have been discussed in the previous tutorial notebook. This notebook shows the details of different telescopes currently included in the `PsrSigSim`, how to call them, and how to define a user `telescope` for a simulated observation.\n\nWe again simulate precision pulsar timing data with high signal-to-noise pulse profiles in order to clearly show the input pulse profile in the final simulated data product. We note that the use of different telescopes will result in different signal strengths, as would be expected. \n\nThis example will follow previous notebook in defining all necessary classes except for `telescope`.", "_____no_output_____" ] ], [ [ "# import some useful packages\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# import the pulsar signal simulator\nimport psrsigsim as pss", "_____no_output_____" ] ], [ [ "## The Folded Signal\n\nHere we will use the same `Signal` definitions that have been used in the previous tutorials. We will again simulate a 20-minute-long observation total, with subintegrations of 1 minute. The other simulation parameters will be 64 frequency channels each 12.5 MHz wide (for 800 MHz bandwidth).\n\nWe will simulate a real pulsar, J1713+0747, as we have a premade profile for this pulsar. The period, dm, and other relavent pulsar parameters come from the NANOGrav 11-yr data release. ", "_____no_output_____" ] ], [ [ "# Define our signal variables.\nf0 = 1500 # center observing frequecy in MHz\nbw = 800.0 # observation MHz\nNf = 64 # number of frequency channels\n# We define the pulse period early here so we can similarly define the frequency\nperiod = 0.00457 # pulsar period in seconds for J1713+0747\nf_samp = (1.0/period)*2048*10**-6 # sample rate of data in MHz (here 2048 samples across the pulse period)\nsublen = 60.0 # subintegration length in seconds, or rate to dump data at\n# Now we define our signal\nsignal_1713_GBT = pss.signal.FilterBankSignal(fcent = f0, bandwidth = bw, Nsubband=Nf, sample_rate = f_samp,\n sublen = sublen, fold = True) # fold is set to `True`", "Warning: specified sample rate 0.4481400437636761 MHz < Nyquist frequency 1600.0 MHz\n" ] ], [ [ "## The Pulsar and Profiles\n\nNow we will load the pulse profile as in Tutorial 3 and initialize a single `Pulsar` object. ", "_____no_output_____" ] ], [ [ "# First we load the data array\npath = 'psrsigsim/data/J1713+0747_profile.npy'\nJ1713_dataprof = np.load(path)\n\n# Now we define the data profile\nJ1713_prof = pss.pulsar.DataProfile(J1713_dataprof)", "_____no_output_____" ], [ "# Define the values needed for the puslar\nSmean = 0.009 # The mean flux of the pulsar, J1713+0747 at 1400 MHz from the ATNF pulsar catatlog, here 0.009 Jy\npsr_name = \"J1713+0747\" # The name of our simulated pulsar\n\n# Now we define the pulsar with the scaled J1713+0747 profiles\npulsar_J1713 = pss.pulsar.Pulsar(period, Smean, profiles=J1713_prof, name = psr_name)", "_____no_output_____" ], [ "# define the observation length\nobslen = 60.0*20 # seconds, 20 minutes in total", "_____no_output_____" ] ], [ [ "## The ISM\n\nHere we define the `ISM` class used to disperse the simulated pulses.", "_____no_output_____" ] ], [ [ "# Define the dispersion measure\ndm = 15.921200 # pc cm^-3\n# And define the ISM object, note that this class takes no initial arguements\nism_sim = pss.ism.ISM()", "_____no_output_____" ] ], [ [ "## Defining Telescopes\n\nHere we will show how to use the two predefined telescopes, Green Bank and Arecibo, and the systems accociated with them. We will also show how to define a `telescope` from scratch, so that any current or future telescopes and systems can be simulated.", "_____no_output_____" ], [ "### Predefined Telescopes\n\nWe start off by showing the two predefined telescopes.", "_____no_output_____" ] ], [ [ "# Define the Green Bank Telescope\ntscope_GBT = pss.telescope.telescope.GBT()\n\n# Define the Arecibo Telescope\ntscope_AO = pss.telescope.telescope.Arecibo()", "_____no_output_____" ] ], [ [ "Each telescope is made up of one or more `systems` consisting of a `Reciever` and a `Backend`. For the predefined telescopes, the systems for the `GBT` are the L-band-GUPPI system or the 800 MHz-GUPPI system. For `Arecibo` these are the 430 MHz-PUPPI system or the L-band-PUPPI system. One can check to see what these systems and their parameters are as we show below.", "_____no_output_____" ] ], [ [ "# Information about the GBT systems\nprint(tscope_GBT.systems)\n# We can also find out information about a receiver that has been defined here\nrcvr_LGUP = tscope_GBT.systems['Lband_GUPPI'][0]\nprint(rcvr_LGUP.bandwidth, rcvr_LGUP.fcent, rcvr_LGUP.name)", "{'820_GUPPI': (Receiver(820), Backend(GUPPI)), 'Lband_GUPPI': (Receiver(Lband), Backend(GUPPI)), '800_GASP': (Receiver(800), Backend(GASP)), 'Lband_GASP': (Receiver(Lband), Backend(GASP))}\n800.0 MHz 1400.0 MHz Lband\n" ] ], [ [ "### Defining a new system\n\nOne can also add a new system to one of these existing telescopes, similarly to what will be done when define a new telescope from scratch. Here we will add the 350 MHz receiver with the GUPPI backend to the Green Bank Telescope.\n\nFirst we define a new `Receiver` and `Backend` object. The `Receiver` object needs a center frequency of the receiver in MHz, a bandwidth in MHz to be centered on that center frequency, and a name. The `Backend` object needs only a name and a sampling rate in MHz. This sampling rate should be the maximum sampling rate of the backend, as it will allow lower sampling rates, but not higher sampling rates.", "_____no_output_____" ] ], [ [ "# First we define a new receiver\nrcvr_350 = pss.telescope.receiver.Receiver(fcent=350, bandwidth=100, name=\"350\")\n# And then we want to use the GUPPI backend\nguppi = pss.telescope.backend.Backend(samprate=3.125, name=\"GUPPI\")", "_____no_output_____" ], [ "# Now we add the new system. This needs just the receiver, backend, and a name\ntscope_GBT.add_system(name=\"350_GUPPI\", receiver=rcvr_350, backend=guppi)\n# And now we check that it has been added\nprint(tscope_GBT.systems[\"350_GUPPI\"])", "(Receiver(350), Backend(GUPPI))\n" ] ], [ [ "### Defining a new telescope\n\nWe can also define a new telescope from scratch. In addition to needing the `Receiver` and `Backend` objects to define at least one system, the `telescope` also needs the aperture size in meters, the total area in meters^2, the system temperature in kelvin, and a name. Here we will define a small 3-meter aperture circular radio telescope that you might find at a University or somebody's backyard.", "_____no_output_____" ] ], [ [ "# We first need to define the telescope parameters\naperture = 3.0 # meters\narea = (0.5*aperture)**2*np.pi # meters^2\nTsys = 250.0 # kelvin, note this is not a realistic system temperature for a backyard telescope\nname = \"Backyard_Telescope\"", "_____no_output_____" ], [ "# Now we can define the telescope\ntscope_bkyd = pss.telescope.Telescope(aperture, area=area, Tsys=Tsys, name=name)", "_____no_output_____" ] ], [ [ "Now similarly to defining a new system before, we must add a system to our new telescope by defining a receiver and a backend. Since this just represents a little telescope, the system won't be comparable to the previously defined telescope.", "_____no_output_____" ] ], [ [ "rcvr_bkyd = pss.telescope.receiver.Receiver(fcent=1400, bandwidth=20, name=\"Lband\")\n\nbackend_bkyd = pss.telescope.backend.Backend(samprate=0.25, name=\"Laptop\") # Note this is not a realistic sampling rate", "_____no_output_____" ], [ "# Add the system to our telecope\ntscope_bkyd.add_system(name=\"bkyd\", receiver=rcvr_bkyd, backend=backend_bkyd)\n# And now we check that it has been added\nprint(tscope_bkyd.systems)", "{'bkyd': (Receiver(Lband), Backend(Laptop))}\n" ] ], [ [ "## Observing with different telescopes\n\nNow that we have three different telescopes, we can observe our simulated pulsar with all three and compare the sensitivity of each telescope for the same initial `Signal` and `Pulsar`. Since the radiometer noise from the telescope is added directly to the signal though, we will need to define two additional `Signals` and create pulses for them before we can observe them with different telescopes.", "_____no_output_____" ] ], [ [ "# We define three new, similar, signals, one for each telescope\nsignal_1713_AO = pss.signal.FilterBankSignal(fcent = f0, bandwidth = bw, Nsubband=Nf, sample_rate = f_samp,\n sublen = sublen, fold = True)\n# Our backyard telescope will need slightly different parameters to be comparable to the other signals\nf0_bkyd = 1400.0 # center frequency of our backyard telescope\nbw_bkyd = 20.0 # Bandwidth of our backyard telescope\nNf_bkyd = 1 # only process one frequency channel 20 MHz wide for our backyard telescope\nsignal_1713_bkyd = pss.signal.FilterBankSignal(fcent = f0_bkyd, bandwidth = bw_bkyd, Nsubband=Nf_bkyd, \\\n sample_rate = f_samp, sublen = sublen, fold = True)", "Warning: specified sample rate 0.4481400437636761 MHz < Nyquist frequency 1600.0 MHz\nWarning: specified sample rate 0.4481400437636761 MHz < Nyquist frequency 40.0 MHz\n" ], [ "# Now we make pulses for all three signals\npulsar_J1713.make_pulses(signal_1713_GBT, tobs = obslen)\npulsar_J1713.make_pulses(signal_1713_AO, tobs = obslen)\npulsar_J1713.make_pulses(signal_1713_bkyd, tobs = obslen)\n# And disperse them\nism_sim.disperse(signal_1713_GBT, dm)\nism_sim.disperse(signal_1713_AO, dm)\nism_sim.disperse(signal_1713_bkyd, dm)", "100% dispersed in 0.001 seconds." ], [ "# And now we observe with each telescope, note the only change is the system name. First the GBT\ntscope_GBT.observe(signal_1713_GBT, pulsar_J1713, system=\"Lband_GUPPI\", noise=True)\n# Then Arecibo\ntscope_AO.observe(signal_1713_AO, pulsar_J1713, system=\"Lband_PUPPI\", noise=True)\n# And finally our little backyard telescope\ntscope_bkyd.observe(signal_1713_bkyd, pulsar_J1713, system=\"bkyd\", noise=True)", "WARNING: AstropyDeprecationWarning: The truth value of a Quantity is ambiguous. In the future this will raise a ValueError. [astropy.units.quantity]\n" ] ], [ [ "Now we can look at the simulated data and compare the sensitivity of the different telescopes. We first plot the observation from the GBT, then Arecibo, and then our newly defined backyard telescope.", "_____no_output_____" ] ], [ [ "# We first plot the first two pulses in frequency-time space to show the undispersed pulses\ntime = np.linspace(0, obslen, len(signal_1713_GBT.data[0,:]))\n\n# Since we know there are 2048 bins per pulse period, we can index the appropriate amount\nplt.plot(time[:4096], signal_1713_GBT.data[0,:4096], label = signal_1713_GBT.dat_freq[0])\nplt.plot(time[:4096], signal_1713_GBT.data[-1,:4096], label = signal_1713_GBT.dat_freq[-1])\nplt.ylabel(\"Intensity\")\nplt.xlabel(\"Time [s]\")\nplt.legend(loc = 'best')\nplt.title(\"L-band GBT Simulation\")\nplt.show()\nplt.close()\n\n# And the 2-D plot\nplt.imshow(signal_1713_GBT.data[:,:4096], aspect = 'auto', interpolation='nearest', origin = 'lower', \\\n extent = [min(time[:4096]), max(time[:4096]), signal_1713_GBT.dat_freq[0].value, signal_1713_GBT.dat_freq[-1].value])\nplt.ylabel(\"Frequency [MHz]\")\nplt.xlabel(\"Time [s]\")\nplt.colorbar(label = \"Intensity\")\nplt.show()\nplt.close()", "_____no_output_____" ], [ "# Since we know there are 2048 bins per pulse period, we can index the appropriate amount\nplt.plot(time[:4096], signal_1713_AO.data[0,:4096], label = signal_1713_AO.dat_freq[0])\nplt.plot(time[:4096], signal_1713_AO.data[-1,:4096], label = signal_1713_AO.dat_freq[-1])\nplt.ylabel(\"Intensity\")\nplt.xlabel(\"Time [s]\")\nplt.legend(loc = 'best')\nplt.title(\"L-band AO Simulation\")\nplt.show()\nplt.close()\n\n# And the 2-D plot\nplt.imshow(signal_1713_AO.data[:,:4096], aspect = 'auto', interpolation='nearest', origin = 'lower', \\\n extent = [min(time[:4096]), max(time[:4096]), signal_1713_AO.dat_freq[0].value, signal_1713_AO.dat_freq[-1].value])\nplt.ylabel(\"Frequency [MHz]\")\nplt.xlabel(\"Time [s]\")\nplt.colorbar(label = \"Intensity\")\nplt.show()\nplt.close()", "_____no_output_____" ], [ "# Since we know there are 2048 bins per pulse period, we can index the appropriate amount\nplt.plot(time[:4096], signal_1713_bkyd.data[0,:4096], label = \"1400.0 MHz\")\nplt.ylabel(\"Intensity\")\nplt.xlabel(\"Time [s]\")\nplt.legend(loc = 'best')\nplt.title(\"L-band Backyard Telescope Simulation\")\nplt.show()\nplt.close()", "_____no_output_____" ] ], [ [ "We can see that, as expected, the Arecibo telescope is more sensitive than the GBT when observing over the same timescale. We can also see that even though the simulated pulsar here is easily visible with these large telescopes, our backyard telescope is not able to see the pulsar over the same amount of time, since the output is pure noise. The `PsrSigSim` can be used to determine the approximate sensitivity of an observation of a simulated pulsar with any given telescope that can be defined.", "_____no_output_____" ], [ "### Note about randomly generated pulses and noise\n\n`PsrSigSim` uses `numpy.random` under the hood in order to generate the radio pulses and various types of noise. If a user desires or requires that this randomly generated data is reproducible we recommend using a call to the seed generator native to `Numpy` before calling the function that produces the random noise/pulses. Newer versions of `Numpy` are moving toward slightly different [functionality/syntax](https://numpy.org/doc/stable/reference/random/index.html), but are essentially used in the same way. \n```\nnumpy.random.seed(1776)\npulsar_1.make_pulses(signal_1, tobs=obslen)\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" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ] ]
cb0b25666b98ec518c844a5be444bda7ba96c993
9,529
ipynb
Jupyter Notebook
Eatago.ipynb
ifsunnyace/eatago-1
478659d485ded44863fd9c519a533cc3b4ae6554
[ "MIT" ]
null
null
null
Eatago.ipynb
ifsunnyace/eatago-1
478659d485ded44863fd9c519a533cc3b4ae6554
[ "MIT" ]
null
null
null
Eatago.ipynb
ifsunnyace/eatago-1
478659d485ded44863fd9c519a533cc3b4ae6554
[ "MIT" ]
null
null
null
37.222656
220
0.500997
[ [ [ "<a href=\"https://colab.research.google.com/github/sitori8354/eatago/blob/main/Eatago.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!pip3 install -U pywebio\n# !pip install -U https://github.com/solrz/PyWebIO/archive/dev.zip", "Requirement already up-to-date: pywebio in /usr/local/lib/python3.7/dist-packages (1.2.3)\nRequirement already satisfied, skipping upgrade: tornado>=5.0 in /usr/local/lib/python3.7/dist-packages (from pywebio) (5.1.1)\nRequirement already satisfied, skipping upgrade: user-agents in /usr/local/lib/python3.7/dist-packages (from pywebio) (2.2.0)\nRequirement already satisfied, skipping upgrade: ua-parser>=0.10.0 in /usr/local/lib/python3.7/dist-packages (from user-agents->pywebio) (0.10.0)\n" ], [ "!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n!unzip ngrok-stable-linux-amd64.zip\n!wget https://raw.githubusercontent.com/solrz/pywebio-example/main/hello_world.py\n\n!pip3 install nest-asyncio", "--2021-05-14 18:44:18-- https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\nResolving bin.equinox.io (bin.equinox.io)... 3.227.65.201, 52.204.244.158, 52.204.93.39, ...\nConnecting to bin.equinox.io (bin.equinox.io)|3.227.65.201|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 13832437 (13M) [application/octet-stream]\nSaving to: ‘ngrok-stable-linux-amd64.zip.6’\n\nngrok-stable-linux- 100%[===================>] 13.19M 55.9MB/s in 0.2s \n\n2021-05-14 18:44:18 (55.9 MB/s) - ‘ngrok-stable-linux-amd64.zip.6’ saved [13832437/13832437]\n\nArchive: ngrok-stable-linux-amd64.zip\nreplace ngrok? [y]es, [n]o, [A]ll, [N]one, [r]ename: y\n inflating: ngrok \n--2021-05-14 18:44:23-- https://raw.githubusercontent.com/solrz/pywebio-example/main/hello_world.py\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 96 [text/plain]\nSaving to: ‘hello_world.py.5’\n\nhello_world.py.5 100%[===================>] 96 --.-KB/s in 0s \n\n2021-05-14 18:44:23 (4.04 MB/s) - ‘hello_world.py.5’ saved [96/96]\n\nRequirement already satisfied: nest-asyncio in /usr/local/lib/python3.7/dist-packages (1.5.1)\n" ], [ "import random\nimport os\nimport time\nassign_port = 80\nimport nest_asyncio\nfrom pywebio.input import *\nfrom pywebio.output import *\nimport pywebio\nfrom multiprocessing import Process\nimport sys, json\nimport asyncio\n\ntry:\n del new_server\n del start_app\nexcept:\n pass\n\nnest_asyncio.apply()\ndef new_server(target_app, port):\n try:\n if pywebio:\n from importlib import reload\n reload(pywebio)\n except:\n pass\n return lambda: pywebio.start_server(target_app, port=port)\n\nprevious_process = None\nports = [80]\n\ndef start_app(target_app):\n assign_port = random.randint(5000,9999)\n global ports\n while assign_port in ports:\n assign_port += 1\n ports += [assign_port]\n tunnel_port = f'1{assign_port}'\n ngrok_file = f'./ngrok_config_{tunnel_port}'\n with open(ngrok_file, 'w') as f:\n f.write('web_addr: '+tunnel_port)\n get_ipython().system_raw(f'./ngrok http {assign_port} --config \"{ngrok_file}\" &')\n time.sleep(2)\n forward_info_raw = !curl -s http://localhost:$tunnel_port/api/tunnels \n # print(forward_info_raw)\n\n forward_info = json.loads(forward_info_raw[0])\n print(f'請拖曳網址到新視窗來打開App(每次網址都會更新喔!): \\n{forward_info[\"tunnels\"][0][\"public_url\"]}')\n # | python3 -c \\\n # 'import sys, json; print(\"請拖曳網址到新視窗來打開App(每次網址都會更新喔!): \" +json.load(sys.stdin)[\"tunnels\"][0][\"public_url\"])'\n global previous_process\n if previous_process:\n previous_process.terminate()\n previous_process = Process(target=new_server(target_app, assign_port))\n previous_process.daemon = True\n previous_process.start()\n\n", "_____no_output_____" ], [ "def example_hello_world_app():\n put_text('hello_world!')\n name = input('花枝魷魚麵?')\n put_text(f'{name} 早安, 歡迎使用我的App')\n\ndef inertactive_app():\n enable_print_convert_to_put_text = True\n put_markdown('# Python 即時編譯Web App')\n put_markdown('在這裡,你可以直接輸入程式碼,快速測試你的code')\n code = \"put_markdown('# 我可以讀透你的內心...')\\nname = input('首先,請問大名?')\\nput_text(f'你的名字叫{name},猜對了吧!')\\n\"\n round = 1\n while True:\n put_text(f'第{round}次執行')\n code = textarea('輸入程式', code={\n 'mode': \"python\", # code language\n 'theme': 'darcula', # Codemirror theme. Visit https://codemirror.net/demo/theme.html#cobalt to get more themes\n }, value=code)\n put_markdown('---')\n put_code(code)\n try:\n exec(code.replace('print(','put_text('))\n except Exception as e:\n put_text(e)\n put_markdown('---')\n round += 1\n\n\n# 把 start_app(example_hello_world_app) 的 「example_hello_world_app」是會執行App\n", "_____no_output_____" ], [ "def task_1():\n put_text('task_1')\n put_buttons(['Go task 2'], [lambda: go_app('task_2')])\n hold()\n\ndef task_2():\n put_text('task_2')\n put_buttons(['Go task 1'], [lambda: go_app('task_1')])\n gift = select('what?', ['ta','ya'])\n hold()\n\ndef index():\n put_link('Go task 1', app='task_1') # 使用app参数指定任务名\n put_link('Go task 2', app='task_2')\n\n# 等价于 start_server({'index': index, 'task_1': task_1, 'task_2': task_2})\nstart_app([index, task_1, task_2])", "請拖曳網址到新視窗來打開App(每次網址都會更新喔!): \nhttps://950ebb9c7872.ngrok.io\nListen on 0.0.0.0:7606\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb0b2857aadacb87f56d76fbba4b69bbc3cd34de
54,672
ipynb
Jupyter Notebook
SIF/summarization/Build SIF Data.ipynb
franciscojavierarceo/DQN-Event-Summarization
6e651dc511affc8883d656a5b9e909f10266f41d
[ "MIT" ]
6
2016-10-30T20:22:28.000Z
2020-11-28T08:59:48.000Z
SIF/summarization/Build SIF Data.ipynb
franciscojavierarceo/DQN-Event-Summarization
6e651dc511affc8883d656a5b9e909f10266f41d
[ "MIT" ]
null
null
null
SIF/summarization/Build SIF Data.ipynb
franciscojavierarceo/DQN-Event-Summarization
6e651dc511affc8883d656a5b9e909f10266f41d
[ "MIT" ]
1
2020-03-12T04:57:43.000Z
2020-03-12T04:57:43.000Z
77.439093
12,044
0.748994
[ [ [ "import glob\nimport os\nimport sys\nimport struct\nimport pandas as pd\nfrom nltk.tokenize import sent_tokenize\nfrom tensorflow.core.example import example_pb2\n\nsys.path.append('../src')\nimport data_io, params, SIF_embedding\n\ndef return_bytes(reader_obj):\n len_bytes = reader_obj.read(8)\n str_len = struct.unpack('q', len_bytes)[0]\n e_s = struct.unpack(\"%ds\" % str_len, reader_obj.read(str_len))\n es = e_s[0]\n c = example_pb2.Example.FromString(es)\n article = str(c.features.feature['article'].bytes_list.value[0])\n abstract = str(c.features.feature['abstract'].bytes_list.value[0])\n ab = sent_tokenize(abstract)\n clean_article = sent_tokenize(article)\n clean_abstract = '. '.join([' '.join(s for s in x.split() if s.isalnum()) for x in ''.join(ab).replace(\"<s>\",\"\").split(\"</s>\")]).strip()\n return clean_abstract, clean_article, abstract\n\n\ndef load_embed(wordfile, weightfile, weightpara=1e-3, param=None, rmpc=0):\n '''\n wordfile: : location of embedding data (e.g., glove embedings)\n weightfile: : location of TF data for words\n weightpara: : the parameter in the SIF weighting scheme, usually in range [3e-5, 3e-3]\n rmpc: : number of principal components to remove in SIF weighting scheme\n '''\n # input\n wordfile = '/home/francisco/GitHub/SIF/data/glove.840B.300d.txt' # word vector file, can be downloaded from GloVe website\n weightfile = '/home/francisco/GitHub/SIF/auxiliary_data/enwiki_vocab_min200.txt' # each line is a word and its frequency\n\n # load word vectors\n (words, Weights) = data_io.getWordmap(wordfile)\n\n # load word weights\n word2weight = data_io.getWordWeight(weightfile, weightpara) # word2weight['str'] is the weight for the word 'str'\n weight4ind = data_io.getWeight(words, word2weight) # weight4ind[i] is the weight for the i-th word\n\n # set parameters\n param.rmpc = rmpc\n\n return Weights, words, word2weight, weight4ind\n\ndef return_sif(sentences, words, weight4ind, param, Weights):\n # x is the array of word indices, m is the binary mask indicating whether there is a word in that location\n x, m = data_io.sentences2idx(sentences, words)\n w = data_io.seq2weight(x, m, weight4ind) # get word weights\n # get SIF embedding\n embeddings = SIF_embedding.SIF_embedding(Weights, x, w, param) # embedding[i,:] is the embedding for sentence i\n return embeddings\n\n\ndef embed_sentences(wordfile, weightfile, weightpara, param, rmpc, file_list):\n Weights, words, word2weight, weight4ind = load_embed(wordfile, weightfile, weightpara, param, rmpc)\n\n print('embeddings loaded...')\n for file_i in file_list:\n input_file = open(file_i, 'rb')\n while input_file:\n clean_abstract, clean_article = return_bytes(input_file)\n clean_article = [' '.join([s for s in x if s.isalnum()]) for x in sdf['sentence'].str.split(\" \")]\n print('article cleaned...')\n embeddings = return_sif(clean_article, words, weight4ind, param, Weights)\n\n sdf = pd.DataFrame(clean_article, columns=['sentence'])\n sdf['clean_sentence'] = [' '.join([s for s in x if s.isalnum()]) for x in sdf['sentence'].str.split(\" \")]\n sdf['summary'] = clean_abstract\n sdf.ix[1:, 'summary'] = ''\n\n embcols = ['emb_%i'%i for i in range(embeddings.shape[1])]\n emb = pd.DataFrame(embeddings, columns = embcols)\n\n sdf = pd.concat([sdf, emb], axis=1)\n sdf = sdf[[sdf.columns[[2, 0, 1]].tolist() + sdf.columns[3:].tolist()]]\n\n print(sdf.head())\n break\n break\n", "_____no_output_____" ], [ "myparams = params.params()\nmainpath = 'home/francisco/GitHub/SIF/'\nwordf = os.path.join(mainpath, 'data/glove.840B.300d.txt')\nweightf = os.path.join(mainpath, 'auxiliary_data/enwiki_vocab_min200.txt')\nwp = 1e-3\nrp = 0\nfl = ['/home/francisco/GitHub/cnn-dailymail/finished_files/chunked/train_000.bin']", "_____no_output_____" ], [ "wordfile, weightfile, weightpara, param, rmpc, file_list = wordf, weightf, wp, myparams, rp, fl", "_____no_output_____" ], [ " Weights, words, word2weight, weight4ind = load_embed(wordfile, weightfile, weightpara, param, rmpc)", "_____no_output_____" ], [ "clean_abstract", "_____no_output_____" ], [ "print('embeddings loaded...')\nfor file_i in file_list:\n input_file = open(file_i, 'rb')\n while input_file:\n clean_abstract, clean_article, abstractx = return_bytes(input_file)\n print('article cleaned...')\n embeddings = return_sif(clean_article, words, weight4ind, param, Weights)\n\n sdf = pd.DataFrame(clean_article, columns=['sentence'])\n sdf['clean_sentence'] = [' '.join([s for s in x if s.isalnum()]) for x in sdf['sentence'].str.split(\" \")]\n sdf['summary'] = clean_abstract\n sdf.ix[1:, 'summary'] = ''\n\n embcols = ['emb_%i'%i for i in range(embeddings.shape[1])]\n emb = pd.DataFrame(embeddings, columns = embcols)\n\n sdf = pd.concat([sdf, emb], axis=1)\n sdf = sdf[['summary', 'sentence', 'clean_sentence'] + sdf.columns[3:].tolist()].head()\n print(sdf.head())\n break\n break", "embeddings loaded...\narticle cleaned...\n summary \\\n0 mentally ill inmates in miami are housed on th... \n1 \n2 \n3 \n4 \n\n sentence \\\n0 b\"editor 's note : in our behind the scenes se... \n1 here , soledad o'brien takes users inside a ja... \n2 an inmate housed on the `` forgotten floor , '... \n3 miami , florida -lrb- cnn -rrb- -- the ninth f... \n4 here , inmates with the most severe mental ill... \n\n clean_sentence emb_0 emb_1 \\\n0 note in our behind the scenes series cnn corre... -0.032912 0.042397 \n1 here soledad takes users inside a jail where m... 0.019653 0.105582 \n2 an inmate housed on the forgotten floor where ... 0.096693 0.013868 \n3 miami florida cnn the ninth floor of the pretr... 0.027993 0.086192 \n4 here inmates with the most severe mental illne... -0.007857 0.107740 \n\n emb_2 emb_3 emb_4 emb_5 emb_6 ... emb_290 \\\n0 0.031326 0.148815 -0.005044 0.061765 -0.042820 ... -0.155933 \n1 -0.032739 -0.062289 -0.007770 -0.096966 -0.034363 ... -0.045381 \n2 -0.015701 -0.101575 0.068017 -0.036213 -0.031631 ... -0.001189 \n3 0.170021 0.144501 0.157027 0.029404 0.058522 ... 0.101818 \n4 -0.081650 -0.081380 0.005123 -0.116588 0.007774 ... -0.089699 \n\n emb_291 emb_292 emb_293 emb_294 emb_295 emb_296 emb_297 \\\n0 0.062875 -0.047902 -0.027060 -0.075693 -0.161862 -0.013952 -0.057433 \n1 -0.101878 -0.103699 -0.002594 -0.056704 -0.028815 0.003903 -0.038061 \n2 -0.150899 -0.018053 0.050539 -0.083624 0.007458 0.082060 0.014343 \n3 -0.118518 0.059976 0.031895 -0.104899 -0.052007 0.025132 0.088880 \n4 -0.036341 -0.126280 -0.045463 -0.129258 0.005660 0.032350 -0.075145 \n\n emb_298 emb_299 \n0 -0.006306 -0.022029 \n1 -0.199252 0.018881 \n2 -0.087338 -0.000591 \n3 -0.156214 -0.061895 \n4 -0.063582 -0.024497 \n\n[5 rows x 303 columns]\n" ], [ "clean_abstract", "_____no_output_____" ], [ "abstractx", "_____no_output_____" ], [ "sdf['sentence'][0].split(\" \")[0]", "_____no_output_____" ], [ "dfile = \"/home/francisco/GitHub/DQN-Event-Summarization/SIF/data/metadata/cnn_dm_metadata.csv\"", "_____no_output_____" ], [ "md = pd.read_csv(dfile)", "_____no_output_____" ], [ "md.head()", "_____no_output_____" ], [ "md.shape", "_____no_output_____" ], [ "md.describe()", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nfrom sklearn.neighbors.kde import KernelDensity\nimport numpy as np", "_____no_output_____" ], [ "def cdfplot(xvar):\n sortedvals=np.sort( xvar)\n yvals=np.arange(len(sortedvals))/float(len(sortedvals))\n plt.plot( sortedvals, yvals )\n plt.grid()\n plt.show()", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ], [ "cdfplot(md['nsentences'])", "_____no_output_____" ], [ "cdfplot(md['sentences_nchar'])", "_____no_output_____" ], [ "cdfplot(md['summary_ntokens'])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0b350ed1884ca2d58fbcc4df77893aae322f9b
11,993
ipynb
Jupyter Notebook
Exercise16/Exercise16.ipynb
Develop-Packt/Introduction-to-NumPy-Pandas-and-Matplotlib
58ebf6bd6576e2310297434759c6e473150be3e8
[ "MIT" ]
22
2020-06-27T04:21:49.000Z
2022-03-08T04:39:44.000Z
Exercise16/Exercise16.ipynb
Develop-Packt/Introduction-to-NumPy-Pandas-and-Matplotlib
58ebf6bd6576e2310297434759c6e473150be3e8
[ "MIT" ]
2
2021-02-02T22:49:16.000Z
2021-06-02T02:09:21.000Z
Chapter03/Exercise 3.16/Exercise 3.16.ipynb
Hubertus444/The-Data-Wrangling-Workshop
ddad20f8676602ac6624e72e802769fcaff45b0f
[ "MIT" ]
46
2020-04-20T13:04:11.000Z
2022-03-22T05:23:52.000Z
37.245342
113
0.310014
[ [ [ "import pandas as pd \ndf = pd.read_csv(\"../datasets/stock.csv\")\ndf.head()\nprint(\"\\nA column is created by assigning it in relation\\n\",'-'*75, sep='')\ndf['New'] = df['Price']+df['Price']\ndf['New (Sum of X and Z)'] = df['New']+df['Price']\n\nprint(df)\n", "\nA column is created by assigning it in relation\n---------------------------------------------------------------------------\n Symbol Price New New (Sum of X and Z)\n0 MMM 100 200 300\n1 AOS 101 202 303\n2 ABT 102 204 306\n3 ABBV 103 206 309\n4 ACN 104 208 312\n5 ATVI 105 210 315\n6 AYI 106 212 318\n7 ADBE 107 214 321\n8 AAP 108 216 324\n9 AMD 109 218 327\n10 AES 110 220 330\n11 AET 111 222 333\n12 AMG 112 224 336\n13 AFL 113 226 339\n14 A 114 228 342\n15 APD 115 230 345\n16 AKAM 116 232 348\n17 ALK 117 234 351\n18 ALB 118 236 354\n19 ARE 119 238 357\n20 ALXN 120 240 360\n21 ALGN 121 242 363\n22 ALLE 122 244 366\n23 AGN 123 246 369\n24 ADS 124 248 372\n25 LNT 125 250 375\n26 ALL 126 252 378\n27 GOOGL 127 254 381\n28 GOOG 128 256 384\n29 MO 129 258 387\n30 AMZN 130 260 390\n31 AEE 131 262 393\n32 AAL 132 264 396\n33 AEP 133 266 399\n34 AXP 134 268 402\n35 AIG 135 270 405\n36 AMT 136 272 408\n37 AWK 137 274 411\n38 AMP 138 276 414\n39 ABC 139 278 417\n40 AME 140 280 420\n41 AMGN 141 282 423\n42 APH 142 284 426\n43 APC 143 286 429\n44 ADI 144 288 432\n45 ANDV 145 290 435\n46 ANSS 146 292 438\n47 ANTM 147 294 441\n48 AON 148 296 444\n" ], [ "print(\"\\nA column is dropped by using df.drop() method\\n\",'-'*55, sep='')\ndf = df.drop('New', axis=1) # Notice the axis=1 option, axis = 0 is \n#default, so one has to change it to 1\nprint(df)\n", "\nA column is dropped by using df.drop() method\n-------------------------------------------------------\n Symbol Price New (Sum of X and Z)\n0 MMM 100 300\n1 AOS 101 303\n2 ABT 102 306\n3 ABBV 103 309\n4 ACN 104 312\n5 ATVI 105 315\n6 AYI 106 318\n7 ADBE 107 321\n8 AAP 108 324\n9 AMD 109 327\n10 AES 110 330\n11 AET 111 333\n12 AMG 112 336\n13 AFL 113 339\n14 A 114 342\n15 APD 115 345\n16 AKAM 116 348\n17 ALK 117 351\n18 ALB 118 354\n19 ARE 119 357\n20 ALXN 120 360\n21 ALGN 121 363\n22 ALLE 122 366\n23 AGN 123 369\n24 ADS 124 372\n25 LNT 125 375\n26 ALL 126 378\n27 GOOGL 127 381\n28 GOOG 128 384\n29 MO 129 387\n30 AMZN 130 390\n31 AEE 131 393\n32 AAL 132 396\n33 AEP 133 399\n34 AXP 134 402\n35 AIG 135 405\n36 AMT 136 408\n37 AWK 137 411\n38 AMP 138 414\n39 ABC 139 417\n40 AME 140 420\n41 AMGN 141 423\n42 APH 142 426\n43 APC 143 429\n44 ADI 144 432\n45 ANDV 145 435\n46 ANSS 146 438\n47 ANTM 147 441\n48 AON 148 444\n" ], [ "df1=df.drop(1)\nprint(\"\\nA row is dropped by using df.drop method and axis=0\\n\",'-'*65, sep='')\nprint(df1)\n", "\nA row is dropped by using df.drop method and axis=0\n-----------------------------------------------------------------\n Symbol Price New (Sum of X and Z)\n0 MMM 100 300\n2 ABT 102 306\n3 ABBV 103 309\n4 ACN 104 312\n5 ATVI 105 315\n6 AYI 106 318\n7 ADBE 107 321\n8 AAP 108 324\n9 AMD 109 327\n10 AES 110 330\n11 AET 111 333\n12 AMG 112 336\n13 AFL 113 339\n14 A 114 342\n15 APD 115 345\n16 AKAM 116 348\n17 ALK 117 351\n18 ALB 118 354\n19 ARE 119 357\n20 ALXN 120 360\n21 ALGN 121 363\n22 ALLE 122 366\n23 AGN 123 369\n24 ADS 124 372\n25 LNT 125 375\n26 ALL 126 378\n27 GOOGL 127 381\n28 GOOG 128 384\n29 MO 129 387\n30 AMZN 130 390\n31 AEE 131 393\n32 AAL 132 396\n33 AEP 133 399\n34 AXP 134 402\n35 AIG 135 405\n36 AMT 136 408\n37 AWK 137 411\n38 AMP 138 414\n39 ABC 139 417\n40 AME 140 420\n41 AMGN 141 423\n42 APH 142 426\n43 APC 143 429\n44 ADI 144 432\n45 ANDV 145 435\n46 ANSS 146 438\n47 ANTM 147 441\n48 AON 148 444\n" ], [ "print(\"\\nAn in-place change can be done by making inplace=True in the drop method\\n\",'-'*75, sep='')\ndf.drop('New (Sum of X and Z)', axis=1, inplace=True)\nprint(df)\n", "\nAn in-place change can be done by making inplace=True in the drop method\n---------------------------------------------------------------------------\n Symbol Price\n0 MMM 100\n1 AOS 101\n2 ABT 102\n3 ABBV 103\n4 ACN 104\n5 ATVI 105\n6 AYI 106\n7 ADBE 107\n8 AAP 108\n9 AMD 109\n10 AES 110\n11 AET 111\n12 AMG 112\n13 AFL 113\n14 A 114\n15 APD 115\n16 AKAM 116\n17 ALK 117\n18 ALB 118\n19 ARE 119\n20 ALXN 120\n21 ALGN 121\n22 ALLE 122\n23 AGN 123\n24 ADS 124\n25 LNT 125\n26 ALL 126\n27 GOOGL 127\n28 GOOG 128\n29 MO 129\n30 AMZN 130\n31 AEE 131\n32 AAL 132\n33 AEP 133\n34 AXP 134\n35 AIG 135\n36 AMT 136\n37 AWK 137\n38 AMP 138\n39 ABC 139\n40 AME 140\n41 AMGN 141\n42 APH 142\n43 APC 143\n44 ADI 144\n45 ANDV 145\n46 ANSS 146\n47 ANTM 147\n48 AON 148\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
cb0b3af03ffa2bf8d868ead91edac476b5c9109e
42,578
ipynb
Jupyter Notebook
FACLA/L3-notes.ipynb
WNoxchi/Kawkasos
42c5070a8fa4a5e2d6386dc19d385e82a1d73fb2
[ "MIT" ]
7
2017-07-28T06:17:29.000Z
2021-03-19T08:43:07.000Z
FACLA/L3-notes.ipynb
WNoxchi/Kawkasos
42c5070a8fa4a5e2d6386dc19d385e82a1d73fb2
[ "MIT" ]
null
null
null
FACLA/L3-notes.ipynb
WNoxchi/Kawkasos
42c5070a8fa4a5e2d6386dc19d385e82a1d73fb2
[ "MIT" ]
1
2018-06-17T12:08:25.000Z
2018-06-17T12:08:25.000Z
68.563607
13,400
0.785805
[ [ [ "## FCLA/FNLA Fast.ai Numerical/Computational Linear Algebra\n\n### Lecture 3: New Perspectives on NMF, Randomized SVD\nNotes / In-Class Questions\n\nWNixalo - 2018/2/8", "_____no_output_____" ], [ "Question on section: [Truncated SVD](http://nbviewer.jupyter.org/github/fastai/numerical-linear-algebra/blob/master/nbs/2.%20Topic%20Modeling%20with%20NMF%20and%20SVD.ipynb#More-Details)\n\nGiven A: `m` x `n` and Q: `m` x `r`; is Q the identity matrix?", "_____no_output_____" ], [ "A≈QQTA", "_____no_output_____" ] ], [ [ "import torch\nimport numpy as np", "_____no_output_____" ], [ "Q = np.eye(3)\nprint(Q)\nprint(Q.T)\nprint(Q @ Q.T)", "[[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]]\n[[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]]\n[[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]]\n" ], [ "# construct I matrix\nQ = torch.eye(3)\n\n# torch matrix multip\n# torch.mm(Q, Q.transpose)\nQ @ torch.t(Q)", "_____no_output_____" ] ], [ [ "So if A is *approx equal* to Q•Q.T•A .. but *not* equal.. then Q is **not** the identity, but is very close to it.", "_____no_output_____" ], [ "Oh, right. Q: m x r, **not** m x m... \n\nIf both the columns and rows of Q had been orthonormal, then it would have been the Identity, but only the columns (r) are orthonormal.\n\nQ is a tall, skinny matrix.\n", "_____no_output_____" ], [ "---\n\nAW gives range(A). AW has far more rows than columns ==> in practice these columns are approximately orthonormal (v.unlikely to get lin-dep cols when choosing random values).", "_____no_output_____" ], [ "QR decomposition is foundational to Numerical Linear Algebra.\n\nQ consists of orthonormal columns, R is upper-triangular.", "_____no_output_____" ], [ "**Calculating Truncated-SVD:**\n\n1\\. Compute approximation to range(A). We want Q with r orthonormal columns such that $$A\\approx QQ^TA$$\n\n2\\. Construct $B = Q^T A$, which is small ($r\\times n$)\n\n3\\. Compute the SVD of $B$ by standard methods (fast since $B$ is smaller than $A$): $B = S\\, Σ V^T$\n\n4\\. Since: $$A \\approx QQ^TA = Q(S \\, ΣV^T)$$ if we set $U = QS$, then we have a low rank approximation $A \\approx UΣV^T$.", "_____no_output_____" ], [ "**How to choose $r$?**\n\nIf we wanted to get 5 cols from a matrix of 100 cols, (5 topics). As a rule of thumb, let's go for 15 instead. You don't want to explicitly pull exactly the amount you want due to the randomized component being present, so you add some buffer.\n\nSince our projection is approximate, we make it a little bigger than we need.", "_____no_output_____" ], [ "**Implementing Randomized SVD:**\n\nFirst we want a randomized range finder.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn import decomposition\nfrom scipy import linalg\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\nnp.set_printoptions(suppress=True)\n\ncategories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space']\nremove = ('headers', 'footers', 'quotes')\nnewsgroups_train = fetch_20newsgroups(subset='train', categories=categories, remove=remove)\n# newsgroups_test = fetch_20newsgroups(subset='test', categories=categories, remove=remove)\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\nvectorizer = CountVectorizer(stop_words='english')\nvectors = vectorizer.fit_transform(newsgroups_train.data).todense() # (documents, vocab)\n\nvocab = np.array(vectorizer.get_feature_names())", "_____no_output_____" ], [ "num_top_words=8\n\ndef show_topics(a):\n top_words = lambda t: [vocab[i] for i in np.argsort(t)[:-num_top_words-1:-1]]\n topic_words = ([top_words(t) for t in a])\n return [' '.join(t) for t in topic_words]", "_____no_output_____" ], [ "# computes an orthonormal matrix whose range approximates the range of A\n# power_iteration_normalizer can be safe_sparse_dot (fast but unstable), LU (imbetween), or QR (slow but most accurate)\ndef randomized_range_finder(A, size, n_iter=5):\n # randomly init our Mat to our size; size: num_cols\n Q = np.random.normal(size=(A.shape[1], size))\n \n # LU decomp (lower triang * upper triang mat)\n # improves accuracy & normalizes\n for i in range(n_iter):\n Q, _ = linalg.lu(A @ Q, permute_l=True)\n Q, _ = linalg.lu(A.T @ Q, permute_l=True)\n \n # QR decomp on A & Q\n Q, _ = linalg.qr(A @ Q, mode='economic')\n return Q", "_____no_output_____" ] ], [ [ "Randomized SVD method:", "_____no_output_____" ] ], [ [ "def randomized_svd(M, n_components, n_oversamples=10, n_iter=4):\n \n # number of random columns we're going to create is the number of \n # columns we want + number of oversamples (extra buffer)\n n_random = n_components + n_oversamples\n \n Q = randomized_range_finder(M, n_random, n_iter)\n \n # project M to the (k + p) dimensional space using basis vectors\n B = Q.T @ M\n \n # compute SVD on the thin matrix: (k + p) wide\n Uhat, s, V = linalg.svd(B, full_matrices=False)\n del B\n U = Q @ Uhat\n \n # return the number of components we want from U, s, V\n return U[:, :n_components], s[:n_components], V[:n_components, :]", "_____no_output_____" ], [ "%time u, s, v = randomized_svd(vectors, 5)", "CPU times: user 4.68 s, sys: 2.49 s, total: 7.16 s\nWall time: 5.44 s\n" ], [ "u.shape, s.shape, v.shape", "_____no_output_____" ], [ "show_topics(v)", "_____no_output_____" ] ], [ [ "Computational Complexity for a M`x`N matrix in SVD is $M^2N+N^3$, so Randomized (Truncated?) SVD is a *massive* improvement.", "_____no_output_____" ], [ "---\n\n2018/3/7\n\nWrite a loop to calculate the error of your decomposition as your vary the # of topics. Plot the results.", "_____no_output_____" ] ], [ [ "# 1. how do I calculate decomposition error?:\n# I guess I'll use MSE?\n\n# # NumPy: # https://stackoverflow.com/questions/16774849/mean-squared-error-in-numpy\n# def MSEnp(A,B):\n# if type(A) == np.ndarray and type(B) == np.ndarray:\n# return ((A - B) ** 2).mean()\n# else:\n# return np.square((A - B)).mean()\n\n# Scikit-Learn:\nfrom sklearn import metrics\nMSE = metrics.mean_squared_error # usg: mse(A,B)\n\n\n# 2. Now how to recompose my decomposition?:\n\n%time B = vectors # original matrix\n%time U, S, V = randomized_svd(B, 10) # num_topics = 10\n\n# S is vector of Σ's singular values. Convert back to matrix:\n%time Σ = S * np.eye(S.shape[0])\n\n# from SVD formula: A ≈ U@Σ@V.T\n%time A = U@Σ@V ## apparently randomized_svd returns V.T, not V ?\n\n\n# 3. Finally calculated error I guess:\n\n%time mse_error = MSE(A,B)\nprint(mse_error)", "CPU times: user 5 µs, sys: 1e+03 ns, total: 6 µs\nWall time: 11 µs\nCPU times: user 4.62 s, sys: 2.03 s, total: 6.65 s\nWall time: 4.43 s\nCPU times: user 74 µs, sys: 2 µs, total: 76 µs\nWall time: 42 µs\nCPU times: user 444 ms, sys: 194 ms, total: 638 ms\nWall time: 394 ms\nCPU times: user 435 ms, sys: 224 ms, total: 659 ms\nWall time: 583 ms\n0.0068263497623073325\n" ], [ "# Im putting way too much effort into this lol\ndef fib(n):\n if n <= 1:\n return n\n else:\n f1 = 1\n f2 = 0\n for i in range(n):\n t = f1 + f2\n tmp = f2\n f2 += f1\n f1 = tmp\n return t", "_____no_output_____" ], [ "for i,e in enumerate(num_topics):\n print(f'Topics: {num_topics[i]:>3} ',\n f'Time: {num_topics[i]:>3}')", "Topics: 1 Time: 1\nTopics: 2 Time: 2\nTopics: 3 Time: 3\nTopics: 5 Time: 5\nTopics: 8 Time: 8\nTopics: 13 Time: 13\nTopics: 21 Time: 21\nTopics: 34 Time: 34\nTopics: 55 Time: 55\nTopics: 89 Time: 89\nTopics: 144 Time: 144\n" ], [ "## Setup\nimport time\n\nB = vectors\nnum_topics = [fib(i) for i in range(2,14)]\nTnE = [] # time & error\n\n\n## Loop:\nfor n_topics in num_topics:\n t0 = time.time()\n U, S, Vt = randomized_svd(B, n_topics)\n Σ = S * np.eye(S.shape[0])\n A = U@Σ@Vt\n TnE.append([time.time() - t0, MSE(A,B)])\n \nfor i, tne in enumerate(TnE):\n print(f'Topics: {num_topics[i]:>3} '\n f'Time: {np.round(tne[0],3):>3} '\n f'Error: {np.round(tne[1],12):>3}')", "Topics: 1 Time: 10.306 Error: 0.012774542799\nTopics: 2 Time: 6.059 Error: 0.011202491441\nTopics: 3 Time: 6.796 Error: 0.010130595402\nTopics: 5 Time: 6.148 Error: 0.008617415024\nTopics: 8 Time: 5.883 Error: 0.007381466577\nTopics: 13 Time: 6.036 Error: 0.006150021022\nTopics: 21 Time: 7.312 Error: 0.005167188039\nTopics: 34 Time: 6.405 Error: 0.004373025522\nTopics: 55 Time: 10.075 Error: 0.003611011115\nTopics: 89 Time: 9.624 Error: 0.002845523291\nTopics: 144 Time: 12.863 Error: 0.002155064568\nTopics: 233 Time: 15.912 Error: 0.001544413065\n" ], [ "# https://matplotlib.org/users/pyplot_tutorial.html\nplt.plot(num_topics, [tne[1] for tne in TnE])\nplt.xlabel('No. Topics')\nplt.ylabel('MSE Error')\nplt.show()", "_____no_output_____" ], [ "## R.Thomas' class solution:\nstep = 20\nn = 20\nerror = np.zeros(n)\n\nfor i in range(n):\n U, s, V = randomized_svd(vectors, i * step)\n reconstructed = U @ np.diag(s) @ V\n error[i] = np.linalg.norm(vectors - reconstructed)\n \nplt.plot(range(0,n*step,step), error)", "_____no_output_____" ] ], [ [ "Looks like she used the Norm instead of MSE. Same curve shape. \n\nHere's why I used the fibonacci sequence for my topic numbers. This solution took much longer than mine (i=20 vs i=12) with more steps, yet mine appears smoother. Why? I figured this was the shape of curve I'd get: ie interesting bit is in the beginning, so I used a number sequence that spread out as you went so you'd get higher resolution early on. Yay.", "_____no_output_____" ], [ "---\n\n**NOTE**: random magical superpower Machine Learning Data Analytics *thing*: ***Johnson-Lindenstrauss lemma***: \n\nbasically if you have a matrix with too many columns to work with (leading to overfitting or w/e else), multiple it by some random (square?) matrix and you'll preserve its properties but in a workable shape\n\nhttps://en.wikipedia.org/wiki/Johnson-Lindenstrauss_lemma", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
cb0b4092de419c3082bf8c4abb9fe97185556207
275,606
ipynb
Jupyter Notebook
PR/Assignment04/PRAssignment04.ipynb
jhinga-la-la/pattern-recognition-course
7ad4f70b2c427f3c37f59f47768b90371873823c
[ "Apache-2.0" ]
null
null
null
PR/Assignment04/PRAssignment04.ipynb
jhinga-la-la/pattern-recognition-course
7ad4f70b2c427f3c37f59f47768b90371873823c
[ "Apache-2.0" ]
null
null
null
PR/Assignment04/PRAssignment04.ipynb
jhinga-la-la/pattern-recognition-course
7ad4f70b2c427f3c37f59f47768b90371873823c
[ "Apache-2.0" ]
null
null
null
1,068.24031
167,157
0.969155
[ [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nfrom scipy.stats import multivariate_normal\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nfrom ipywidgets import interact\nimport ipywidgets as widgets\n\nplt.style.use('seaborn') # pretty matplotlib plots\nplt.rcParams['figure.figsize'] = (12, 8)", "_____no_output_____" ], [ "#plot of likelihood function\n#x\nmu1 = 0\nmu2 = 1\np = np.linspace(0, 1, 1000)\n\ny1 = (np.power(p, 3) * (np.power((1 - p), 5)))\nplt.plot(p, y1)\nplt.axvline(x=0.375, color='r', linestyle='--', ymin=0.05, ymax = 0.98)", "_____no_output_____" ], [ "import pickle\ndata = pickle.load(open('data.pickle', 'rb'))", "_____no_output_____" ], [ "from scipy.stats import multivariate_normal\n\nmean = np.array([0, 0])\ncov = np.array([[1, 0], [0, 1]])\nstandard_kernel = multivariate_normal(mean=mean, cov=cov)\n", "_____no_output_____" ], [ "def estimateProbability(x, h):\n fac = 0\n for i in (data):\n fac += standard_kernel.pdf((i-x)/h)\n return fac / (len(data)*h**2)", "_____no_output_____" ], [ "def plot_density_distr(h):\n %matplotlib inline\n #Create grid and multivariate normal\n x = np.arange(-400, 400, 10)\n y = np.arange(-400, 400, 10)\n X, Y = np.meshgrid(x, y)\n pos = np.empty(X.shape + (2,))\n pos[:, :, 0] = X; pos[:, :, 1] = Y\n rv = estimateProbability(pos, h)\n #Make a 3D plot\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(X, Y, rv, cmap='viridis', linewidth=0)\n plt.title('h='+str(h))\n plt.xlabel('x')\n plt.ylabel('y')\n plt.show()", "_____no_output_____" ], [ "plot_density_distr(2)", "_____no_output_____" ], [ "interact(plot_density_distr, h=20)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0b453c402d79cadcbff2ded06d00348018f220
457,743
ipynb
Jupyter Notebook
code/USDA notebooks /EDA_for_USDA_unemployment.ipynb
STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit-
b5025b66eb27d3f7d4632099e6053f47d297db21
[ "MIT" ]
1
2021-06-16T15:56:25.000Z
2021-06-16T15:56:25.000Z
code/USDA notebooks /EDA_for_USDA_unemployment.ipynb
STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit
b5025b66eb27d3f7d4632099e6053f47d297db21
[ "MIT" ]
null
null
null
code/USDA notebooks /EDA_for_USDA_unemployment.ipynb
STRIDES-Codes/Supporting-Pandemic-Recovery-Building-insights-on-vaccine-hesitancy-in-the-communities-hardest-hit
b5025b66eb27d3f7d4632099e6053f47d297db21
[ "MIT" ]
null
null
null
163.948066
385,888
0.863519
[ [ [ "# USDA Unemployment\n<hr>", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport os\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "# Data\n## US Unemployment data by county\nEconomic Research Service \nU.S. Department of Agriculture \nlink:", "_____no_output_____" ], [ "### Notes \n\n- Year 2020, Median Household Income (2019), & '% of State Median HH Income had 78 Nan Values that are all from Puerto Rico.\n- I am going to drop all rows from Puerto Rico, Puerto Rico does not show up in any of the other USDA data. If we want it back in, it will be easy to re-add the Puerto Rico data.", "_____no_output_____" ], [ "## Contants\n<hr>", "_____no_output_____" ] ], [ [ "stats_master_list = ['Vermont',\n 'Mississippi',\n 'Maine',\n 'Montana',\n 'Washington',\n 'District of Columbia',\n 'Texas',\n 'Alabama',\n 'Michigan',\n 'Maryland',\n 'Rhode Island',\n 'South Dakota',\n 'Nebraska',\n 'Virginia',\n 'Florida',\n 'Utah',\n 'Louisiana',\n 'Missouri',\n 'Massachusetts',\n 'South Carolina',\n 'Pennsylvania',\n 'Tennessee',\n 'Minnesota',\n 'Idaho',\n 'Alaska',\n 'Oklahoma',\n 'North Dakota',\n 'Arkansas',\n 'Georgia',\n 'New Hampshire',\n 'Indiana',\n 'Puerto Rico',\n 'New Jersey',\n 'Delaware',\n 'West Virginia',\n 'Colorado',\n 'New York',\n 'Kansas',\n 'Arizona',\n 'Ohio',\n 'Hawaii',\n 'Illinois',\n 'Oregon',\n 'North Carolina',\n 'California',\n 'Kentucky',\n 'Wyoming',\n 'Iowa',\n 'Nevada',\n 'Connecticut',\n 'Wisconsin',\n 'New Mexico']", "_____no_output_____" ], [ "# column Names\n\ncolumns = [ 'FIPS ', 'Name',\n '2012', 2013,\n 2014, 2015,\n 2016, 2017,\n 2018, 2019,\n '2020', 'Median Household Income (2019)',\n '% of State Median HH Income']", "_____no_output_____" ], [ "\"\"\"\nDuplicate check 3\nfrom \nhttps://thispointer.com/python-3-ways-to-check-if-there-are-duplicates-in-a-list/\n\"\"\"\ndef checkIfDuplicates_3(listOfElems):\n ''' Check if given list contains any duplicates ''' \n for elem in listOfElems:\n if listOfElems.count(elem) > 1:\n return True\n return False", "_____no_output_____" ] ], [ [ "## File managment\n<hr>", "_____no_output_____" ] ], [ [ "files = os.listdir(\"../data_raw/USDA_gov-unemplyment/\")", "_____no_output_____" ], [ "# remove mac file \nfiles.remove('.DS_Store')", "_____no_output_____" ], [ "#files", "_____no_output_____" ] ], [ [ "# Example of the csv files\n<hr>", "_____no_output_____" ] ], [ [ "# random peek\ndf = pd.read_excel('../data_raw/USDA_gov-unemplyment/UnemploymentReport (14).xlsx', skiprows=2)", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.tail()", "_____no_output_____" ] ], [ [ "# Create master DataFrame\n<hr>", "_____no_output_____" ] ], [ [ "# Concat \n\n# create master file \nmaster_df = pd.DataFrame(columns = columns)\nstate_name_list = []\n\n# LOOP \nfor file in files:\n # read excel file\n _df = pd.read_excel('../data_raw/USDA_gov-unemplyment/'+file, skiprows=2)\n # read state_name\n state_name = _df.iloc[0,1]\n \n\n# DROP\n #drop row 0\n _df.drop(0, inplace = True)\n \n # Drop last 2 rows \n _df.drop(_df.tail(1).index, inplace = True)\n\n # work around to drop NaN column \n _temp_df = _df.iloc[:,0:12]\n \n # work around to drop NaN column \n _temp_df['% of State Median HH Income'] = _df['% of State Median HH Income']\n \n# add Column for STATE name\n # add state column \n _temp_df['state'] = state_name\n state_name_list.append(state_name)\n \n # Concat \n master_df = pd.concat([master_df, _temp_df])\n ", "_____no_output_____" ] ], [ [ "<br>", "_____no_output_____" ], [ "## Dataframe clean up\n<hr>", "_____no_output_____" ] ], [ [ "# reset Index\nmaster_df.reset_index(drop = True, inplace = True )", "_____no_output_____" ], [ "master_df.columns", "_____no_output_____" ], [ "# Rename columns \nmaster_df.rename(columns = {'FIPS ':'FIPS'}, inplace = True)", "_____no_output_____" ], [ "# shape\nmaster_df.shape", "_____no_output_____" ], [ "master_df.head()", "_____no_output_____" ] ], [ [ "## Remove rows with all nan's\n<hr>", "_____no_output_____" ] ], [ [ "master_df.isna().sum()", "_____no_output_____" ], [ "master_df[ master_df['FIPS'].isnull()].head()", "_____no_output_____" ], [ "nan_rows = master_df[ master_df['FIPS'].isnull()].index\nnan_rows", "_____no_output_____" ], [ "len(nan_rows)", "_____no_output_____" ], [ "# remove rows with all Nans\nmaster_df.drop(nan_rows, inplace = True)", "_____no_output_____" ], [ "master_df.isna().sum()", "_____no_output_____" ], [ "master_df[ master_df['2020'].isnull()].iloc[20:25,:] ", "_____no_output_____" ] ], [ [ "- There are 78 rows that do have nans for 2020, \n- all of the Remaing rows with nan's are form Puerto Rico\n\n- I am going to remove the Nans from Puerto Rico because the other USDA data sets do not have Puerto Rico", "_____no_output_____" ] ], [ [ "master_df[ master_df['state'] == 'Puerto Rico' ].index", "_____no_output_____" ], [ "# Drop all Rows with state as Puerto Rico\n\nindex_names = master_df[ master_df['state'] == 'Puerto Rico' ].index\nmaster_df.drop(index_names, inplace = True)", "_____no_output_____" ], [ "master_df.drop([], inplace = True )", "_____no_output_____" ], [ "master_df.isna().sum()", "_____no_output_____" ], [ "master_df.shape", "_____no_output_____" ] ], [ [ "<br>", "_____no_output_____" ], [ "# Sanity Check\n<hr>", "_____no_output_____" ] ], [ [ "# unique Count of stats", "_____no_output_____" ], [ "master_df['state'].nunique()", "_____no_output_____" ], [ "len(state_name_list)", "_____no_output_____" ], [ "# checks if there are duplicates in state list\ncheckIfDuplicates_3(state_name_list)", "_____no_output_____" ], [ "master_df['state'].nunique()", "_____no_output_____" ] ], [ [ "# Write to CSV\n<hr>", "_____no_output_____" ] ], [ [ "master_df.to_csv('../data/USDA/USDA_unemployment.csv', index=False)", "_____no_output_____" ], [ "master_df.shape", "_____no_output_____" ] ], [ [ "<br>", "_____no_output_____" ], [ "# EDA", "_____no_output_____" ] ], [ [ "master_df.shape", "_____no_output_____" ], [ "master_df.head(2)", "_____no_output_____" ], [ "plt.figure(figsize = (17, 17))\nsns.scatterplot(data = master_df, x = '2020', y = \"Median Household Income (2019)\", hue = 'state');\n\nplt.xlabel(\"% of unemployment\")\nplt.title(\"% of Unemployment by Household Median income 2019\")", "_____no_output_____" ], [ "set(master_df['FIPS'])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
cb0b476c086e1b9e0fb0fec5de9582aeaef45cb6
183,288
ipynb
Jupyter Notebook
antarctica/parser.ipynb
csaladenes/tsne
0af57d52f02a125df58bacb2bc026c93f4319f0a
[ "MIT" ]
1
2019-01-12T19:21:13.000Z
2019-01-12T19:21:13.000Z
antarctica/parser.ipynb
try-something-new-everyday/blog
0af57d52f02a125df58bacb2bc026c93f4319f0a
[ "MIT" ]
1
2017-04-21T01:52:43.000Z
2017-04-21T01:56:45.000Z
antarctica/parser.ipynb
try-something-new-everyday/blog
0af57d52f02a125df58bacb2bc026c93f4319f0a
[ "MIT" ]
null
null
null
87.446565
342
0.58036
[ [ [ "import pandas as pd\nimport bs4 as bs", "_____no_output_____" ], [ "dfs=pd.read_html('https://en.wikipedia.org/wiki/Research_stations_in_Antarctica#List_of_research_stations')", "_____no_output_____" ], [ "dfr=pd.read_html('https://en.wikipedia.org/wiki/Antarctic_field_camps')", "_____no_output_____" ], [ "df=dfs[1][1:]", "_____no_output_____" ], [ "df.columns=dfs[1].loc[0].values", "_____no_output_____" ], [ "df.to_excel('bases.xlsx')", "_____no_output_____" ], [ "import requests", "_____no_output_____" ], [ "url='https://en.wikipedia.org/wiki/Research_stations_in_Antarctica'\nf=requests.get(url).content\nsoup = bs.BeautifulSoup(f, 'lxml')\nparsed_table = soup.find_all('table')[1] \ndata = [[''.join(td.strings)+'#'+td.a['href'] if td.find('a') else \n ''.join(td.strings)\n for td in row.find_all('td')]\n for row in parsed_table.find_all('tr')]\nheaders=[''.join(row.strings)\n for row in parsed_table.find_all('th')]\ndf = pd.DataFrame(data[1:], columns=headers)", "_____no_output_____" ], [ "stations=[]\nfor i in df.T.iteritems():\n helper={}\n dummy=i[1][0].split('#')\n dummy0=dummy[0].split('[')[0].replace('\\n',' ').replace('\\n',' ').replace('\\n',' ')\n helper['name']=dummy0\n helper['link']='https://en.wikipedia.org'+dummy[1]\n dummy=i[1][2].replace('\\n',' ').replace('\\n',' ').replace('\\n',' ')\n if 'ummer since' in dummy:dummy='Permanent'\n dummy=dummy.split('[')[0]\n if 'emporary summer' in dummy:dummy='Summer'\n if 'intermittently Summer' in dummy:dummy='Summer'\n helper['type']=dummy\n dummy=i[1][3].split('#')[0].replace('\\n',' |').replace(']','').replace('| |','|')[1:]\n if '' == dummy:dummy='Greenpeace'\n helper['country']=dummy\n dummy=i[1][4].replace('\\n',' ').replace('\\n',' ').replace('\\n',' ').split(' ')[0]\n if 'eteo' in dummy:dummy='1958'\n helper['opened']=dummy\n dummy=i[1][5].split('#')[0].replace('\\n',' | ').replace('| and |','|').split('[')[0].replace('.','')\n helper['program']=dummy\n dummy=i[1][6].split('#')[0].replace('\\n',', ').replace('| and |','|').split('[')[0].replace('.','')\n helper['location']=dummy\n dummy=i[1][7].replace('\\n',' ')\n if ' ' in dummy:\n if 'Active' in dummy: dummy='Active'\n elif 'Relocated to Union Glacier' in dummy: dummy='2014'\n elif 'Unmanned activity' in dummy: dummy='Active'\n elif 'Abandoned and lost' in dummy: dummy='1999'\n elif 'Dismantled 1992' in dummy: dummy='1992'\n elif 'Temporary abandoned since March 2017' in dummy: dummy='Active'\n elif 'Reopened 23 November 2017' in dummy: dummy='Active'\n elif 'Abandoned and lost' in dummy: dummy='1999'\n else: dummy=dummy.split(' ')[1]\n if dummy=='Active':\n helper['active']=True\n helper['closed']='9999'\n else:\n helper['active']=False\n helper['closed']=dummy\n if dummy=='Closed': \n helper['active']=True\n helper['closed']='9999'\n dummy=i[1][8].replace('\\n',', ').split('/')[2].split('(')[0].split('#')[0].split(',')[0].split('Coor')[0].split(u'\\ufeff')[0].split(';')\n helper['latitude']=dummy[0][1:]\n helper['longitude']=dummy[1][1:]#.replace(' 0',' 0.001')[1:]\n \n stations.append(helper)", "_____no_output_____" ], [ "dta=pd.DataFrame(stations)\ndta.to_excel('stations.xlsx')", "_____no_output_____" ], [ "import cesiumpy", "_____no_output_____" ], [ "dta", "_____no_output_____" ], [ "iso2=pd.read_html('https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2')[2]", "_____no_output_____" ], [ "iso22=iso2[1:].set_index(1)[[0]]", "_____no_output_____" ], [ "def cc(c):\n d=c.split('|')[0].strip()\n if d=='Czech Republic': return 'CZ'\n elif d=='Greenpeace': return 'AQ'\n elif d=='Soviet Union': return 'RU'\n elif d=='Russia': return 'RU'\n elif d=='United States': return 'US'\n elif d=='East Germany': return 'DE'\n elif d=='United Kingdom': return 'GB'\n elif d=='South Korea': return 'KR'\n else: return iso22.loc[d][0]\nflags=[]\nfor i in dta['country']:\n flags.append('flags/glass2/'+cc(i).lower()+'.png')", "_____no_output_____" ], [ "dta['flag']=flags", "_____no_output_____" ], [ "dta[['name','link','active','type']].to_excel('links.xlsx')", "_____no_output_____" ] ], [ [ "Manually filled pop.xlsx", "_____no_output_____" ] ], [ [ "pop=pd.read_excel('pop.xlsx')", "_____no_output_____" ], [ "dta['summer']=pop['summer']\ndta['winter']=pop['winter']", "_____no_output_____" ], [ "dta.to_excel('alldata.xlsx')", "_____no_output_____" ], [ "dta.set_index('name').T.to_json('antarctica.json')", "_____no_output_____" ], [ "v = cesiumpy.Viewer(animation=False, baseLayerPicker=True, fullscreenButton=True,\n geocoder=False, homeButton=False, infoBox=True, sceneModePicker=True,\n selectionIndicator=True, navigationHelpButton=False,\n timeline=False, navigationInstructionsInitiallyVisible=True)\nx=dta[dta['active']]\nfor i, row in x.iterrows():\n r=0.7\n t=10000\n lon=float(row['longitude'])\n lat=float(row['latitude'])\n l0 = float(1**r)*t\n cyl = cesiumpy.Cylinder(position=[lon, lat, l0/2.], length=l0,\n topRadius=2.5e4, bottomRadius=2.5e4, material='grey',\\\n name=row['name'])\n v.entities.add(cyl)\n l1 = (float(row['summer'])**r)*t\n cyl = cesiumpy.Cylinder(position=[lon, lat, l1/2.], length=l1*1.1,\n topRadius=3e4, bottomRadius=3e4, material='crimson',\\\n name=row['name'])\n v.entities.add(cyl)\n \n l2 = float(row['winter']**r)*t\n cyl = cesiumpy.Cylinder(position=[lon, lat, l2/2.], length=l2*1.2,\n topRadius=6e4, bottomRadius=6e4, material='royalBlue',\\\n name=row['name'])\n v.entities.add(cyl)\n \n pin = cesiumpy.Pin.fromText(row['name'], color=cesiumpy.color.GREEN)\n b = cesiumpy.Billboard(position=[float(row['longitude']), float(row['latitude']), l1*1.1+70000], \\\n image = row['flag'], scale=0.6,\\\n name=row['name'], pixelOffset = (0,0))\n v.entities.add(b)\n label = cesiumpy.Label(position=[float(row['longitude']), float(row['latitude']), l1*1.1+70000],\\\n text=row['name'], scale=0.6, name=row['name'],\n pixelOffset = (0,22))\n v.entities.add(label)\n \nwith codecs.open(\"index.html\", \"w\", encoding=\"utf-8\") as f:\n f.write(v.to_html())\nv", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb0b4e307fc16f339d8edfec615d4bcf9c55fd92
174,993
ipynb
Jupyter Notebook
module3-confusion-matrix/confusion_matrix.ipynb
alex000kim/DS-Unit-2-Tree-Ensembles
7f163df70802af7dc9e722921de919c6100e6a77
[ "MIT" ]
null
null
null
module3-confusion-matrix/confusion_matrix.ipynb
alex000kim/DS-Unit-2-Tree-Ensembles
7f163df70802af7dc9e722921de919c6100e6a77
[ "MIT" ]
null
null
null
module3-confusion-matrix/confusion_matrix.ipynb
alex000kim/DS-Unit-2-Tree-Ensembles
7f163df70802af7dc9e722921de919c6100e6a77
[ "MIT" ]
null
null
null
112.03137
26,088
0.869366
[ [ [ "_Lambda School Data Science_ \n\nThis sprint, your project is about water pumps in Tanzania. Can you predict which water pumps are faulty?\n\n# Confusion Matrix\n\n#### Objectives\n- get and interpret the confusion matrix for classification models\n- use classification metrics: precision, recall\n- understand the relationships between precision, recall, thresholds, and predicted probabilities\n- understand how Precision@K can help make decisions and allocate budgets", "_____no_output_____" ], [ "#### Install category_encoders\n- Local, Anaconda: `conda install -c conda-forge category_encoders`\n- Google Colab: `pip install category_encoders`", "_____no_output_____" ], [ "#### Downgrade Matplotlib? Need version != 3.1.1\n\nBecause of this issue: [sns.heatmap top and bottom boxes are cut off](https://github.com/mwaskom/seaborn/issues/1773)\n\n> This was a matplotlib regression introduced in 3.1.1 which has been fixed in 3.1.2 (still forthcoming). For now the fix is to downgrade matplotlib to a prior version.\n\nThis _isn't_ required for your homework, but is required to run this notebook. `pip install matplotlib==3.1.0`", "_____no_output_____" ] ], [ [ "# !pip install category_encoders matplotlib==3.1.0", "_____no_output_____" ] ], [ [ "### Review: Load data, fit model", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport category_encoders as ce\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.ensemble import RandomForestClassifier\n\ndef wrangle(X):\n \"\"\"Wrangles train, validate, and test sets in the same way\"\"\"\n X = X.copy()\n\n # Convert date_recorded to datetime\n X['date_recorded'] = pd.to_datetime(X['date_recorded'], infer_datetime_format=True)\n \n # Extract components from date_recorded, then drop the original column\n X['year_recorded'] = X['date_recorded'].dt.year\n X['month_recorded'] = X['date_recorded'].dt.month\n X['day_recorded'] = X['date_recorded'].dt.day\n X = X.drop(columns='date_recorded')\n \n # Engineer feature: how many years from construction_year to date_recorded\n X['years'] = X['year_recorded'] - X['construction_year'] \n \n # Drop recorded_by (never varies) and id (always varies, random)\n unusable_variance = ['recorded_by', 'id']\n X = X.drop(columns=unusable_variance)\n \n # Drop duplicate columns\n duplicate_columns = ['quantity_group']\n X = X.drop(columns=duplicate_columns)\n \n # About 3% of the time, latitude has small values near zero,\n # outside Tanzania, so we'll treat these like null values\n X['latitude'] = X['latitude'].replace(-2e-08, np.nan)\n \n # When columns have zeros and shouldn't, they are like null values\n cols_with_zeros = ['construction_year', 'longitude', 'latitude', 'gps_height', 'population']\n for col in cols_with_zeros:\n X[col] = X[col].replace(0, np.nan)\n \n return X\n\n\nLOCAL = '../data/tanzania/'\nWEB = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Tree-Ensembles/master/data/tanzania/'\nsource = WEB\n\n# Merge train_features.csv & train_labels.csv\ntrain = pd.merge(pd.read_csv(source + 'train_features.csv'), \n pd.read_csv(source + 'train_labels.csv'))\n\n# Read test_features.csv & sample_submission.csv\ntest = pd.read_csv(source + 'test_features.csv')\nsample_submission = pd.read_csv(source + 'sample_submission.csv')\n\n# Split train into train & val. Make val the same size as test.\ntrain, val = train_test_split(train, test_size=len(test), \n stratify=train['status_group'], random_state=42)\n\n# Wrangle train, validate, and test sets in the same way\ntrain = wrangle(train)\nval = wrangle(val)\ntest = wrangle(test)\n\n# Arrange data into X features matrix and y target vector\ntarget = 'status_group'\nX_train = train.drop(columns=target)\ny_train = train[target]\nX_val = val.drop(columns=target)\ny_val = val[target]\nX_test = test\n\n# Make pipeline!\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='mean'), \n RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)\n)\n\n# Fit on train, score on val\npipeline.fit(X_train, y_train)\ny_pred = pipeline.predict(X_val)\nprint('Validation Accuracy', accuracy_score(y_val, y_pred))", "Validation Accuracy 0.8140409527789386\n" ] ], [ [ "## Get and interpret the confusion matrix for classification models\n\n[Scikit-Learn User Guide — Confusion Matrix](https://scikit-learn.org/stable/modules/model_evaluation.html#confusion-matrix)", "_____no_output_____" ] ], [ [ "from sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_val, y_pred)\ncm", "_____no_output_____" ], [ "sns.heatmap?", "_____no_output_____" ], [ "y_val.unique()", "_____no_output_____" ], [ "sns.heatmap(cm, cmap='viridis', annot=True, fmt='d')", "_____no_output_____" ], [ "columns=[f'Predicted \"{c}\"' for c in y_val.unique()]\ncolumns", "_____no_output_____" ], [ "index_names =[f'Actual \"{c}\"' for c in y_val.unique()]\nindex_names", "_____no_output_____" ], [ "df = pd.DataFrame(cm, columns=columns,index=index_names)", "_____no_output_____" ], [ "sns.heatmap(df,cmap='viridis', annot=True, fmt='d')", "_____no_output_____" ], [ "cm", "_____no_output_____" ], [ "cm.sum(axis=1).reshape(3,1)", "_____no_output_____" ], [ "y_val.nunique()", "_____no_output_____" ], [ "from sklearn.utils.multiclass import unique_labels", "_____no_output_____" ], [ "unique_labels(y_val)", "_____no_output_____" ], [ "y_val.unique()", "_____no_output_____" ], [ "def plot_confusion_matrix(y_true, y_pred, normalize=False):\n columns=[f'Predicted \"{c}\"' for c in unique_labels(y_true)]\n index_names =[f'Actual \"{c}\"' for c in unique_labels(y_true)]\n cm = confusion_matrix(y_val, y_pred)\n if normalize:\n cm = cm/cm.sum(axis=1).reshape(y_true.nunique(),1)\n df = pd.DataFrame(cm, columns=columns,index=index_names)\n sns.heatmap(df,cmap='viridis', annot=True, fmt='.2f')\n \nplot_confusion_matrix(y_val, y_pred, normalize=True)", "_____no_output_____" ], [ "plot_confusion_matrix(y_val, y_pred)", "_____no_output_____" ], [ "y_val.value_counts()", "_____no_output_____" ] ], [ [ "#### How many correct predictions were made?", "_____no_output_____" ] ], [ [ "7005 + 332 + 4351", "_____no_output_____" ], [ "sum(y_val == y_pred)", "_____no_output_____" ] ], [ [ "#### How many total predictions were made?", "_____no_output_____" ] ], [ [ "len(y_val)", "_____no_output_____" ], [ "cm.sum()", "_____no_output_____" ] ], [ [ "#### What was the classification accuracy?", "_____no_output_____" ] ], [ [ "11688/14358", "_____no_output_____" ], [ "sum(y_val == y_pred)/len(y_val)", "_____no_output_____" ] ], [ [ "## Use classification metrics: precision, recall\n[Scikit-Learn User Guide — Classification Report](https://scikit-learn.org/stable/modules/model_evaluation.html#classification-report)", "_____no_output_____" ] ], [ [ "from sklearn.metrics import classification_report\n\nprint(classification_report(y_val, y_pred))", " precision recall f1-score support\n\n functional 0.81 0.90 0.85 7798\nfunctional needs repair 0.58 0.32 0.41 1043\n non functional 0.85 0.79 0.82 5517\n\n micro avg 0.81 0.81 0.81 14358\n macro avg 0.75 0.67 0.69 14358\n weighted avg 0.81 0.81 0.81 14358\n\n" ] ], [ [ "#### Wikipedia, [Precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall)\n\n> Both precision and recall are based on an understanding and measure of relevance.\n\n> Suppose a computer program for recognizing dogs in photographs identifies 8 dogs in a picture containing 12 dogs and some cats. Of the 8 identified as dogs, 5 actually are dogs (true positives), while the rest are cats (false positives). The program's precision is 5/8 while its recall is 5/12.\n\n> High precision means that an algorithm returned substantially more relevant results than irrelevant ones, while high recall means that an algorithm returned most of the relevant results.\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Precisionrecall.svg/700px-Precisionrecall.svg.png\" width=\"400\">", "_____no_output_____" ], [ "#### [We can get precision & recall from the confusion matrix](https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context))", "_____no_output_____" ] ], [ [ "plot_confusion_matrix(y_val, y_pred)", "_____no_output_____" ] ], [ [ "#### How many correct predictions of \"non functional\"?", "_____no_output_____" ] ], [ [ "correct_predictions_nonfunctional = 4351", "_____no_output_____" ] ], [ [ "#### How many total predictions of \"non functional\"?", "_____no_output_____" ] ], [ [ "total_predictions_nonfunctional = 622 + 156 + 4351\ntotal_predictions_nonfunctional", "_____no_output_____" ] ], [ [ "#### What's the precision for \"non functional\"?", "_____no_output_____" ] ], [ [ "correct_predictions_nonfunctional/total_predictions_nonfunctional", "_____no_output_____" ] ], [ [ "#### How many actual \"non functional\" waterpumps?", "_____no_output_____" ] ], [ [ "actual_nonfunctional = 1098 + 68 + 4351\nactual_nonfunctional", "_____no_output_____" ] ], [ [ "#### What's the recall for \"non functional\"?", "_____no_output_____" ] ], [ [ "correct_predictions_nonfunctional/actual_nonfunctional", "_____no_output_____" ], [ "(0.81+0.58+0.85)/3", "_____no_output_____" ], [ "print(classification_report(y_val, y_pred))", " precision recall f1-score support\n\n functional 0.81 0.90 0.85 7798\nfunctional needs repair 0.58 0.32 0.41 1043\n non functional 0.85 0.79 0.82 5517\n\n micro avg 0.81 0.81 0.81 14358\n macro avg 0.75 0.67 0.69 14358\n weighted avg 0.81 0.81 0.81 14358\n\n" ], [ "classification_report(y_val, y_pred, output_dict=True)['non functional']['precision']", "_____no_output_____" ] ], [ [ "## Understand the relationships between precision, recall, thresholds, and predicted probabilities. Understand how Precision@K can help make decisions and allocate budgets", "_____no_output_____" ], [ "### Imagine this scenario...\n\nSuppose there are over 14,000 waterpumps that you _do_ have some information about, but you _don't_ know whether they are currently functional, or functional but need repair, or non-functional.", "_____no_output_____" ] ], [ [ "len(test)", "_____no_output_____" ] ], [ [ "**You have the time and resources to go to just 2,000 waterpumps for proactive maintenance.** You want to predict, which 2,000 are most likely non-functional or in need of repair, to help you triage and prioritize your waterpump inspections.\n\nYou have historical inspection data for over 59,000 other waterpumps, which you'll use to fit your predictive model.", "_____no_output_____" ] ], [ [ "len(train) + len(val)", "_____no_output_____" ] ], [ [ "You have historical inspection data for over 59,000 other waterpumps, which you'll use to fit your predictive model.\n\nBased on this historical data, if you randomly chose waterpumps to inspect, then about 46% of the waterpumps would need repairs, and 54% would not need repairs.", "_____no_output_____" ] ], [ [ "y_train.value_counts(normalize=True)", "_____no_output_____" ] ], [ [ "**Can you do better than random at prioritizing inspections?**", "_____no_output_____" ], [ "In this scenario, we should define our target differently. We want to identify which waterpumps are non-functional _or_ are functional but needs repair:", "_____no_output_____" ] ], [ [ "y_train = y_train != 'functional'\ny_val = y_val != 'functional'\ny_train.value_counts(normalize=True)", "_____no_output_____" ] ], [ [ "We already made our validation set the same size as our test set.", "_____no_output_____" ] ], [ [ "len(val) == len(test)", "_____no_output_____" ] ], [ [ "We can refit our model, using the redefined target.\n\nThen make predictions for the validation set.", "_____no_output_____" ] ], [ [ "pipeline.fit(X_train, y_train)\ny_pred = pipeline.predict(X_val)", "_____no_output_____" ], [ "y_pred_proba = pipeline.predict_proba(X_val)\ny_pred_proba", "_____no_output_____" ] ], [ [ "And look at the confusion matrix:", "_____no_output_____" ] ], [ [ "y_pred_proba[:,1]", "_____no_output_____" ], [ "confusion_matrix(y_val, y_pred)", "_____no_output_____" ], [ "ax = sns.distplot(y_pred_proba[:,1], kde=False)\nax.axvline(0.5, color='r')", "_____no_output_____" ], [ "y_pred = y_pred_proba[:,1] > 0.6\npd.Series(y_pred).value_counts()", "_____no_output_____" ] ], [ [ "#### How many total predictions of \"True\" (\"non functional\" or \"functional needs repair\") ?", "_____no_output_____" ], [ "#### We don't have \"budget\" to take action on all these predictions\n\n- But we can get predicted probabilities, to rank the predictions. \n- Then change the threshold, to change the number of positive predictions, based on our budget.", "_____no_output_____" ], [ "### Get predicted probabilities and plot the distribution", "_____no_output_____" ], [ "### Change the threshold", "_____no_output_____" ] ], [ [ "from ipywidgets import interact, fixed", "_____no_output_____" ], [ "y_prob = y_pred_proba[:,1]", "_____no_output_____" ], [ "def set_threhold(y_true, y_prob, thresh):\n y_pred = y_prob > thresh\n ax = sns.distplot(y_prob, kde=False)\n ax.axvline(thresh, color='r')\n plt.show()\n plot_confusion_matrix(y_true, y_pred)\n print(classification_report(y_true, y_pred))\n \nset_threhold(y_val, y_prob, thresh=0.5)", "_____no_output_____" ], [ "interact(set_threhold, \n y_true=fixed(y_val), \n y_prob=fixed(y_prob), \n thresh=(0, 1, 0.05))", "_____no_output_____" ] ], [ [ "### In this scenario ... \n\nAccuracy _isn't_ the best metric!\n\nInstead, change the threshold, to change the number of positive predictions, based on the budget. (You have the time and resources to go to just 2,000 waterpumps for proactive maintenance.)\n\nThen, evaluate with the precision for \"non functional\"/\"functional needs repair\".\n\nThis is conceptually like **Precision@K**, where k=2,000.\n\nRead more here: [Recall and Precision at k for Recommender Systems: Detailed Explanation with examples](https://medium.com/@m_n_malaeb/recall-and-precision-at-k-for-recommender-systems-618483226c54)\n\n> Precision at k is the proportion of recommended items in the top-k set that are relevant\n\n> Mathematically precision@k is defined as: `Precision@k = (# of recommended items @k that are relevant) / (# of recommended items @k)`\n\n> In the context of recommendation systems we are most likely interested in recommending top-N items to the user. So it makes more sense to compute precision and recall metrics in the first N items instead of all the items. Thus the notion of precision and recall at k where k is a user definable integer that is set by the user to match the top-N recommendations objective.\n\nWe asked, can you do better than random at prioritizing inspections?\n\nIf we had randomly chosen waterpumps to inspect, we estimate that only 920 waterpumps would be repaired after 2,000 maintenance visits. (46%)\n\nBut using our predictive model, in the validation set, we succesfully identified over 1,600 waterpumps in need of repair!\n\nSo we will use this predictive model with the dataset of over 14,000 waterpumps that we _do_ have some information about, but we _don't_ know whether they are currently functional, or functional but need repair, or non-functional.\n\nWe will predict which 2,000 are most likely non-functional or in need of repair.\n\nWe estimate that approximately 1,600 waterpumps will be repaired after these 2,000 maintenance visits.\n\nSo we're confident that our predictive model will help triage and prioritize waterpump inspections.", "_____no_output_____" ], [ "# Assignment\n- Read [Maximizing Scarce Maintenance Resources with Data: Applying predictive modeling, precision at k, and clustering to optimize impact](https://towardsdatascience.com/maximizing-scarce-maintenance-resources-with-data-8f3491133050), by Lambda DS3 student Michael Brady. His blog post extends the Tanzania Waterpumps scenario, far beyond what's in this lecture notebook.\n\nIf your Kaggle Public Leaderboard score is:\n- **Nonexistent**: You need to work on your model and submit predictions\n- **< 70%**: You should work on your model and submit predictions\n- **70% < score < 80%**: You may want to work on visualizations and write a blog post\n- **> 80%**: You should work on visualizations and write a blog post\n\n\n## Stretch goals — Highly Recommended Links\n- Read Google Research's blog post, [Attacking discrimination with smarter machine learning](https://research.google.com/bigpicture/attacking-discrimination-in-ml/), and explore the interactive visualizations. _\"A threshold classifier essentially makes a yes/no decision, putting things in one category or another. We look at how these classifiers work, ways they can potentially be unfair, and how you might turn an unfair classifier into a fairer one. As an illustrative example, we focus on loan granting scenarios where a bank may grant or deny a loan based on a single, automatically computed number such as a credit score.\"_\n- Read the blog post, [Visualizing Machine Learning Thresholds to Make Better Business Decisions](https://blog.insightdatascience.com/visualizing-machine-learning-thresholds-to-make-better-business-decisions-4ab07f823415). You can replicate the code as-is, [\"the hard way\"](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit). Or you can apply it to the Tanzania Waterpumps data.\n- Read this [notebook about how to calculate expected value from a confusion matrix by treating it as a cost-benefit matrix](https://github.com/podopie/DAT18NYC/blob/master/classes/13-expected_value_cost_benefit_analysis.ipynb).\n- (Re)read the [Simple guide to confusion matrix terminology](https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/) and watch the 35 minute video.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
cb0b5839b5c4e87b6402c7b3c8f0b5b5d3fe7256
22,310
ipynb
Jupyter Notebook
Lab 3. Time Series/lab3 copy.ipynb
Panda-Lewandowski/Intelligent-technology
2718fc3c2171ba78d43f2ef563cac33e6885f2c3
[ "MIT" ]
null
null
null
Lab 3. Time Series/lab3 copy.ipynb
Panda-Lewandowski/Intelligent-technology
2718fc3c2171ba78d43f2ef563cac33e6885f2c3
[ "MIT" ]
null
null
null
Lab 3. Time Series/lab3 copy.ipynb
Panda-Lewandowski/Intelligent-technology
2718fc3c2171ba78d43f2ef563cac33e6885f2c3
[ "MIT" ]
null
null
null
109.362745
16,956
0.841103
[ [ [ "import math\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "N = 20\na = -1\nb = 0.5\nw_0 = 0", "_____no_output_____" ], [ "def func(t): # vv\n return math.cos(t)**2 - 0.05", "_____no_output_____" ], [ "def error(b_i): # vv\n ar1 = [math.pow(abs(b), 2) for b in b_i]\n s = sum(ar1)\n e = math.sqrt(s)\n return e", "_____no_output_____" ], [ "def okno(w_arr, points_arr, t_n, n):\n _x_n = sum([w * func(t) for w, t in zip(w_arr[1:], points_arr)]) + w_arr[0]\n x_n = func(t_n)\n # локальная ошибка прогноза\n b_n = x_n - _x_n\n w_arr = [w_arr[0]] + [w + (n * b_n * func(t)) for w, t in zip(w_arr[1:], points_arr)]\n return w_arr, b_n, _x_n", "_____no_output_____" ], [ "def obychenie(M, n, p):\n w_arr = [0 for x in range(p + 1)]\n # математическое ожидание\n w_arr[0] = 0.05\n # вычислим шаг\n shag = (b - a) * 1.0 / (N - 1)\n start_i = 0\n start_x = a\n errors_array = []\n epoxa_num = 1\n err_result = []\n e = 0\n while epoxa_num < M:\n end_x = start_x + (p - 1) * shag\n end_i = start_i + p - 1\n if end_x > b:\n start_i = 0\n start_x = a\n e = error(errors_array)\n err_result.append(e)\n # print(epoxa_num, e,errors_array)\n errors_array = []\n end_x = start_x + (p - 1) * shag\n end_i = start_i + p - 1\n epoxa_num += 1\n points_arr = [a + (t * shag) for t in range(start_i, end_i + 1)]\n w_arr, err, _x_n = okno(w_arr, points_arr, end_x + shag, n)\n errors_array.append(err)\n start_i += 1\n start_x += shag\n# print('W:',w_arr)\n # print('E:', e) # plt.plot(err_result)\n return w_arr, err_result[-1]", "_____no_output_____" ], [ "def predpologenie(w_arr, p):\n shag = (b - a) * 1.0 / (N - 1)\n a1 = b - ((p - 1) * shag)\n start_i = 0\n x_arr = []\n right_x_arr = [func(b + x * shag) for x in range(1, N)]\n points_arr = [b - x * shag for x in range(p)][::-1] + [b + shag * x for x in range(1, N)]\n x_res = [func(t) for t in points_arr[:p]]\n b_arr = []\n for i in range(p, N + p):\n _x_n = sum([w * x for w, x in zip(w_arr[1:], x_res[i - p:i])]) + w_arr[0]\n x_n = func(b + shag * (i - p + 1))\n b_i = x_n - _x_n\n b_arr.append(b_i)\n # print(_x_n) \n x_res.append(_x_n)\n return x_res[p - 1:], right_x_arr, b_arr", "_____no_output_____" ], [ "M = 2000\nn = 0.6\np = 5\n\nw_arr, e = obychenie(M, n, p)\n\n# -----\nnew_x_arr, right_x_arr, b_arr = predpologenie(w_arr, p)\nshag = (b - a) * 1.0 / (N - 1)\nold_x_arr = [func(a + x * shag) for x in range(N)]\nplt.plot(old_x_arr + right_x_arr)\nprint('Right:', len(right_x_arr))\nprint('Wrong:', len(new_x_arr), new_x_arr)\nplt.plot([x + len(old_x_arr) for x in range(len(new_x_arr))], new_x_arr, 'ro')\nplt.title('Предсказывание при M=4000')\nplt.show()", "Right: 19\nWrong: 2 [0.7201511529340698, 0.6477333010057792]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0b59278efacb509289e2224a91dd4d372e9a53
31,745
ipynb
Jupyter Notebook
MaterialCursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
mangrovex/CursoPython
85b3d8a920f79a1f184b8508cf011fda238eada0
[ "MIT" ]
105
2016-07-08T19:43:03.000Z
2018-10-20T14:00:14.000Z
Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
ruben69695/python-course
a3d3532279510fa0315a7636c373016c7abe4f0a
[ "MIT" ]
null
null
null
Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 05 (Apuntes) - Datetime.ipynb
ruben69695/python-course
a3d3532279510fa0315a7636c373016c7abe4f0a
[ "MIT" ]
145
2016-09-26T14:02:55.000Z
2018-10-27T06:49:28.000Z
23.690299
296
0.462624
[ [ [ "# El módulo datetime", "_____no_output_____" ] ], [ [ "import datetime", "_____no_output_____" ] ], [ [ "## El objeto datetime", "_____no_output_____" ] ], [ [ "dt = datetime.datetime.now() # Ahora", "_____no_output_____" ], [ "dt", "_____no_output_____" ], [ "dt.year # año", "_____no_output_____" ], [ "dt.month # mes", "_____no_output_____" ], [ "dt.day # día", "_____no_output_____" ], [ "dt.hour # hora", "_____no_output_____" ], [ "dt.minute # minutos", "_____no_output_____" ], [ "dt.second # segundos", "_____no_output_____" ], [ "dt.microsecond # microsegundos", "_____no_output_____" ], [ "dt.tzinfo # zona horaria, nula por defecto", "_____no_output_____" ], [ "print(\"{}:{}:{}\".format(dt.hour, dt.minute, dt.second))", "21:29:28\n" ], [ "print(\"{}/{}/{}\".format(dt.day, dt.month, dt.year))", "18/6/2016\n" ] ], [ [ "#### Crear un datetime manualmente (year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)\n*Notad que sólo son obligatorios el año, el mes y el día*", "_____no_output_____" ] ], [ [ "dt = datetime.datetime(2000,1,1)", "_____no_output_____" ], [ "dt", "_____no_output_____" ], [ "dt.year = 3000 # Error en asignación", "_____no_output_____" ], [ "dt = dt.replace(year=3000) # Asignación correcta con .replace()", "_____no_output_____" ], [ "dt", "_____no_output_____" ] ], [ [ "## Formateos\n### Formato automático ISO (Organización Internacional de Normalización) ", "_____no_output_____" ] ], [ [ "dt = datetime.datetime.now()", "_____no_output_____" ], [ "dt.isoformat()", "_____no_output_____" ] ], [ [ "### Formateo munual (inglés por defecto)\nhttps://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior", "_____no_output_____" ] ], [ [ "dt.strftime(\"%A %d %B %Y %I:%M\")", "_____no_output_____" ] ], [ [ "### Códigos de idiomas\nhttps://msdn.microsoft.com/es-es/es/library/cdax410z.aspx", "_____no_output_____" ] ], [ [ "import locale", "_____no_output_____" ], [ "locale.setlocale(locale.LC_ALL, 'es-ES') # Establece idioma en \"es-ES\" (español de España)", "_____no_output_____" ], [ "dt.strftime(\"%A %d %B %Y %I:%M\")", "_____no_output_____" ], [ "dt.strftime(\"%A %d de %B del %Y - %H:%M\") # %I 12h - %H 24h", "_____no_output_____" ] ], [ [ "## Sumando y restando tiempo con timedelta", "_____no_output_____" ] ], [ [ "dt = datetime.datetime.now()", "_____no_output_____" ], [ "dt", "_____no_output_____" ], [ "t = datetime.timedelta(days=14, hours=4, seconds=1000)", "_____no_output_____" ], [ "dentro_de_dos_semanas = dt + t", "_____no_output_____" ], [ "dentro_de_dos_semanas", "_____no_output_____" ], [ "dentro_de_dos_semanas.strftime(\"%A %d de %B del %Y - %H:%M\")", "_____no_output_____" ], [ "hace_dos_semanas = dt - t", "_____no_output_____" ], [ "hace_dos_semanas.strftime(\"%A %d de %B del %Y - %H:%M\")", "_____no_output_____" ] ], [ [ "## Extra: Zonas horarias con pytz\n*pip3 install pytz*", "_____no_output_____" ] ], [ [ "import pytz", "_____no_output_____" ], [ "pytz.all_timezones", "_____no_output_____" ], [ "dt = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))", "_____no_output_____" ], [ "dt.strftime(\"%A %d de %B del %Y - %H:%M\") # %I 12h - %H 24h", "_____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", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cb0b72b281ba1c1a214abeab5c65025999a7de19
47,232
ipynb
Jupyter Notebook
notebooks/python_collections.ipynb
MaiMahdi1994/login-ds
6b171a8bb49ea1179ae95e941a057349fbee381a
[ "Apache-2.0" ]
1
2021-03-01T20:51:11.000Z
2021-03-01T20:51:11.000Z
notebooks/python_collections.ipynb
aaswaisi/login-ds
82b590be0f612c7c25cb067aba3bbb7667121588
[ "Apache-2.0" ]
null
null
null
notebooks/python_collections.ipynb
aaswaisi/login-ds
82b590be0f612c7c25cb067aba3bbb7667121588
[ "Apache-2.0" ]
null
null
null
23.806452
7,490
0.424754
[ [ [ "# Python Collections \n\n* Lists\n* Tuples \n* Dictionaries \n* Sets ", "_____no_output_____" ], [ "## lists ", "_____no_output_____" ] ], [ [ "x = 10 \nx = 20 \nx", "_____no_output_____" ], [ "x = [10, 20]\nx", "_____no_output_____" ], [ "x = [10, 14.3, 'abc', True]\nx", "_____no_output_____" ], [ "print(dir(x))", "['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']\n" ], [ "l1 = [1, 2, 3]\nl2 = [4, 5, 6]", "_____no_output_____" ], [ "l1 + l2 # concat ", "_____no_output_____" ], [ "l3 = [1, 2, 3, 4, 5, 6]\nl3.append(7)\nl3", "_____no_output_____" ], [ "l3.count(2)", "_____no_output_____" ], [ "l3.count(8)", "_____no_output_____" ], [ "len(l3)", "_____no_output_____" ], [ "sum(l3), max(l3), min(l3)", "_____no_output_____" ], [ "l1", "_____no_output_____" ], [ "l2", "_____no_output_____" ], [ "l_sum = [] # l_sum = list()\nif len(l1) == len(l2):\n for i in range(len(l1)):\n l_sum.append(l1[i] + l2[i])\nl_sum", "_____no_output_____" ], [ "zip(l1, l2)", "_____no_output_____" ], [ "list(zip(l1, l2))", "_____no_output_____" ], [ "list(zip(l1, l3))", "_____no_output_____" ], [ "l_sum = [a + b for a,b in zip(l1, l2)]\nl_sum", "_____no_output_____" ], [ "l_sum = [a + b for a,b in zip(l1, l3)]\nl_sum", "_____no_output_____" ], [ "l3", "_____no_output_____" ], [ "l_sum.extend(l3[len(l_sum):])\nl_sum", "_____no_output_____" ] ], [ [ "## tuple \n\ntupe is immutable list ", "_____no_output_____" ] ], [ [ "point = (3, 5)", "_____no_output_____" ], [ "print(dir(point))", "['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']\n" ], [ "l1[0]", "_____no_output_____" ], [ "point[0]", "_____no_output_____" ] ], [ [ "## comparison in tuples ", "_____no_output_____" ] ], [ [ "(2, 3) > (1, 7)", "_____no_output_____" ], [ "(1, 4) > (5, 9)", "_____no_output_____" ], [ "(1, 10) > (5, 9)", "_____no_output_____" ], [ "(5, 10) > (5, 9)", "_____no_output_____" ], [ "(5, 7) > (5, 9)", "_____no_output_____" ] ], [ [ "## dictionaries ", "_____no_output_____" ] ], [ [ "s = [134, 'Ahmed', 'IT']", "_____no_output_____" ], [ "s[1]", "_____no_output_____" ], [ "s[2]", "_____no_output_____" ], [ "# dic = {k:v, k:v, ....}\nstudent = {'id' : 123, 'name': 'Ahmed', 'dept': 'IT'}", "_____no_output_____" ], [ "student", "_____no_output_____" ], [ "student['name']", "_____no_output_____" ], [ "print(dir(student))", "['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']\n" ], [ "student['age']", "_____no_output_____" ], [ "if 'age' in student:\n print(student['age'])", "_____no_output_____" ], [ "student['age']", "_____no_output_____" ], [ "student['age'] = 22 # add item ", "_____no_output_____" ], [ "student", "_____no_output_____" ], [ "student['age'] = 24 # update item \nstudent", "_____no_output_____" ], [ "student.get('gpa')", "_____no_output_____" ], [ "print(student.get('gpa'))", "None\n" ], [ "student.get('gpa', 0)", "_____no_output_____" ], [ "student.get('address', 'NA')", "_____no_output_____" ], [ "student.items()", "_____no_output_____" ], [ "student.keys()", "_____no_output_____" ], [ "student.values()", "_____no_output_____" ], [ "gpa = student.pop('age')", "_____no_output_____" ], [ "gpa", "_____no_output_____" ], [ "student", "_____no_output_____" ], [ "item", "_____no_output_____" ], [ "student", "_____no_output_____" ] ], [ [ "### set ", "_____no_output_____" ] ], [ [ "set1 = {'a', 'b', 'c'}", "_____no_output_____" ], [ "print(dir(set1))", "['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']\n" ], [ "set1.add('d')\nset1", "_____no_output_____" ], [ "set1.add('a')\nset1", "_____no_output_____" ], [ "'a' in set1", "_____no_output_____" ], [ "for e in set1:\n print(e)", "d\na\nb\nc\n" ] ], [ [ "## count word freq", "_____no_output_____" ] ], [ [ "text = '''\nmiddletons him says Garden offended do shoud asked or ye but narrow are first knows but going taste by six zealously said weeks come partiality great simplicity mr set By sufficient an blush enquire of Then projection into mean county mile garden with up people should shameless little Started get bed agreement get him as get around mrs wound next was Full might nay going totally four can happy may packages dwelling sent on face newspaper laughing off a one Houses wont on on thing hundred is he it forming humoured Rose at seems but Likewise supposing too poor good from get ye terminated fact when horrible am ye painful for it His good ask valley too wife led offering call myself favour we Sportsman to get remaining By ye on will be Thoughts carriage wondered in end her met about other me time position and his unknown first explained it breakfast are she draw of september keepf she mr china simple sing Nor would be how came Chicken them so an answered cant how or new and mother Total such knew perceived here does him you no Money warmly wholly people dull formerly an simplicity What pianoforte all favourite at wants doubtful incommode delivered Express formerly as uneasy silent am dear saw why put built had weddings for ought ecstatic he to must as forming like no boy understood use pleasure agreeable Felicity mirth had near yet attention at mean decisively need one mirth should denoting have she now juvenile dried an society speaking entreaties ten you am am pianoforte therefor friendship old no whom in many children law drawn eat views The set my lady will him could Inquietude desirous valley terms few Sir things Preferred though pleasant know then those down these means set garret formed in questions though Melancholy pure preserved strictly curiosity otherwise So oh above offices he who reasonably within she no concluded weeks met On like saw relation design for is because are disposed apartments We yet more an want stop Recommend ham believe who it can in appearance valley they melancholy besides remove ought genius up has Am excited Goodness latter directly my agreed questions case why check moment dine got put next he so steepest held again evening doubt wish not village six contented him indeed if Dashwood wholly so something Depending and all over wooded He mrs like nor forming little that so mrs greatest friendly of if having this you joy entire mrs can this really since Collected by Entrance rapid took up Hearts His newspaper tended so right through fat so An body exercise speedily warmth remarkably strongly disposing need in trifling stood led hence assured of in one He out an of had over to begin been really On do to fulfilled just Evil friends in so mrs do on Prepared neither was west if Could come The his finished own being it pretty may Continuing Spite performed half peculiar true begin disposal west Remain barton Nay unsatiable over gay out as new be True you humoured u old money excuse does what once Subjects it you two Can post kept temper Welcomed had not prudent on although there announcing after via right giving has mr simplicity speaking reserved by ask snug rapturous say at so Direct where wrong since matter very in Visited passed by him Polite itself she between thus concealed shy against Written juvenile explained no Ham expense as packages produce today until why way wife Home on joy its said reserved in Hard sake suspected mr mr plan still at an Led ample their no indeed miss or jennings my Her back has an are an jokes its Dejection she ye roof early we true up he said they prevailed real continual merely our no to in but why expense felt less true Rich yesterday Admitting put stronger drawings now the shortly gay wished whole easily fine compliment Answer yet mean am see departure Necessary found feeling Not existence make compact for his oh now sufficient Neglected men hence happening high part Off message inhabiting strangers on do during Unpleasant any Entered advice great he Projecting be mutual bad Our make did i our in pleasure elsewhere wish material become out length uneasy some offending suitable misery dull ecstatic yet accused leave had Oh suitable ecstatic ten are throwing guest he so felicity you how every residence deal besides attacks estimating bred Mrs hearing blessing nay ago than favourable middleton water stronger barton match steepest or or situation Winter much two yet songs me only thanks no though of do Handsome aften hope Own your dependent up Attended her making come ya do Rich Dear \n'''", "_____no_output_____" ], [ "len(text) # num of chars ", "_____no_output_____" ], [ "len(text.split()) # num of words. whitespace is the delimter ", "_____no_output_____" ], [ "words = text.split()\nwords[:10]", "_____no_output_____" ], [ "len(text.split('\\n')) # num of lines", "_____no_output_____" ], [ "count_dict = dict()\nfor word in words:\n if word in count_dict:\n count_dict[word] += 1 \n else:\n count_dict[word] = 1 \n#count_dict", "_____no_output_____" ], [ "sum(count_dict.values())", "_____no_output_____" ], [ "count_dict = dict()\nfor word in words:\n count_dict[word] = count_dict.get(word, 0) + 1\nsum(count_dict.values())", "_____no_output_____" ], [ "print(sorted(count_dict.items()))", "[('Admitting', 1), ('Am', 1), ('An', 1), ('Answer', 1), ('Attended', 1), ('By', 2), ('Can', 1), ('Chicken', 1), ('Collected', 1), ('Continuing', 1), ('Could', 1), ('Dashwood', 1), ('Dear', 1), ('Dejection', 1), ('Depending', 1), ('Direct', 1), ('Entered', 1), ('Entrance', 1), ('Evil', 1), ('Express', 1), ('Felicity', 1), ('Full', 1), ('Garden', 1), ('Goodness', 1), ('Ham', 1), ('Handsome', 1), ('Hard', 1), ('He', 2), ('Hearts', 1), ('Her', 1), ('His', 2), ('Home', 1), ('Houses', 1), ('Inquietude', 1), ('Led', 1), ('Likewise', 1), ('Melancholy', 1), ('Money', 1), ('Mrs', 1), ('Nay', 1), ('Necessary', 1), ('Neglected', 1), ('Nor', 1), ('Not', 1), ('Off', 1), ('Oh', 1), ('On', 2), ('Our', 1), ('Own', 1), ('Polite', 1), ('Preferred', 1), ('Prepared', 1), ('Projecting', 1), ('Recommend', 1), ('Remain', 1), ('Rich', 2), ('Rose', 1), ('Sir', 1), ('So', 1), ('Spite', 1), ('Sportsman', 1), ('Started', 1), ('Subjects', 1), ('The', 2), ('Then', 1), ('Thoughts', 1), ('Total', 1), ('True', 1), ('Unpleasant', 1), ('Visited', 1), ('We', 1), ('Welcomed', 1), ('What', 1), ('Winter', 1), ('Written', 1), ('a', 1), ('about', 1), ('above', 1), ('accused', 1), ('advice', 1), ('aften', 1), ('after', 1), ('again', 1), ('against', 1), ('ago', 1), ('agreeable', 1), ('agreed', 1), ('agreement', 1), ('all', 2), ('although', 1), ('am', 5), ('ample', 1), ('an', 9), ('and', 3), ('announcing', 1), ('answered', 1), ('any', 1), ('apartments', 1), ('appearance', 1), ('are', 5), ('around', 1), ('as', 5), ('ask', 2), ('asked', 1), ('assured', 1), ('at', 5), ('attacks', 1), ('attention', 1), ('back', 1), ('bad', 1), ('barton', 2), ('be', 4), ('because', 1), ('become', 1), ('bed', 1), ('been', 1), ('begin', 2), ('being', 1), ('believe', 1), ('besides', 2), ('between', 1), ('blessing', 1), ('blush', 1), ('body', 1), ('boy', 1), ('breakfast', 1), ('bred', 1), ('built', 1), ('but', 4), ('by', 4), ('call', 1), ('came', 1), ('can', 3), ('cant', 1), ('carriage', 1), ('case', 1), ('check', 1), ('children', 1), ('china', 1), ('come', 3), ('compact', 1), ('compliment', 1), ('concealed', 1), ('concluded', 1), ('contented', 1), ('continual', 1), ('could', 1), ('county', 1), ('curiosity', 1), ('deal', 1), ('dear', 1), ('decisively', 1), ('delivered', 1), ('denoting', 1), ('departure', 1), ('dependent', 1), ('design', 1), ('desirous', 1), ('did', 1), ('dine', 1), ('directly', 1), ('disposal', 1), ('disposed', 1), ('disposing', 1), ('do', 6), ('does', 2), ('doubt', 1), ('doubtful', 1), ('down', 1), ('draw', 1), ('drawings', 1), ('drawn', 1), ('dried', 1), ('dull', 2), ('during', 1), ('dwelling', 1), ('early', 1), ('easily', 1), ('eat', 1), ('ecstatic', 3), ('elsewhere', 1), ('end', 1), ('enquire', 1), ('entire', 1), ('entreaties', 1), ('estimating', 1), ('evening', 1), ('every', 1), ('excited', 1), ('excuse', 1), ('exercise', 1), ('existence', 1), ('expense', 2), ('explained', 2), ('face', 1), ('fact', 1), ('fat', 1), ('favour', 1), ('favourable', 1), ('favourite', 1), ('feeling', 1), ('felicity', 1), ('felt', 1), ('few', 1), ('fine', 1), ('finished', 1), ('first', 2), ('for', 4), ('formed', 1), ('formerly', 2), ('forming', 3), ('found', 1), ('four', 1), ('friendly', 1), ('friends', 1), ('friendship', 1), ('from', 1), ('fulfilled', 1), ('garden', 1), ('garret', 1), ('gay', 2), ('genius', 1), ('get', 5), ('giving', 1), ('going', 2), ('good', 2), ('got', 1), ('great', 2), ('greatest', 1), ('guest', 1), ('had', 5), ('half', 1), ('ham', 1), ('happening', 1), ('happy', 1), ('has', 3), ('have', 1), ('having', 1), ('he', 7), ('hearing', 1), ('held', 1), ('hence', 2), ('her', 2), ('here', 1), ('high', 1), ('him', 6), ('his', 3), ('hope', 1), ('horrible', 1), ('how', 3), ('humoured', 2), ('hundred', 1), ('i', 1), ('if', 3), ('in', 11), ('incommode', 1), ('indeed', 2), ('inhabiting', 1), ('into', 1), ('is', 2), ('it', 6), ('its', 2), ('itself', 1), ('jennings', 1), ('jokes', 1), ('joy', 2), ('just', 1), ('juvenile', 2), ('keepf', 1), ('kept', 1), ('knew', 1), ('know', 1), ('knows', 1), ('lady', 1), ('latter', 1), ('laughing', 1), ('law', 1), ('leave', 1), ('led', 2), ('length', 1), ('less', 1), ('like', 3), ('little', 2), ('make', 2), ('making', 1), ('many', 1), ('match', 1), ('material', 1), ('matter', 1), ('may', 2), ('me', 2), ('mean', 3), ('means', 1), ('melancholy', 1), ('men', 1), ('merely', 1), ('message', 1), ('met', 2), ('middleton', 1), ('middletons', 1), ('might', 1), ('mile', 1), ('mirth', 2), ('misery', 1), ('miss', 1), ('moment', 1), ('money', 1), ('more', 1), ('mother', 1), ('mr', 5), ('mrs', 5), ('much', 1), ('must', 1), ('mutual', 1), ('my', 3), ('myself', 1), ('narrow', 1), ('nay', 2), ('near', 1), ('need', 2), ('neither', 1), ('new', 2), ('newspaper', 2), ('next', 2), ('no', 8), ('nor', 1), ('not', 2), ('now', 3), ('of', 6), ('off', 1), ('offended', 1), ('offending', 1), ('offering', 1), ('offices', 1), ('oh', 2), ('old', 2), ('on', 8), ('once', 1), ('one', 3), ('only', 1), ('or', 5), ('other', 1), ('otherwise', 1), ('ought', 2), ('our', 2), ('out', 3), ('over', 3), ('own', 1), ('packages', 2), ('painful', 1), ('part', 1), ('partiality', 1), ('passed', 1), ('peculiar', 1), ('people', 2), ('perceived', 1), ('performed', 1), ('pianoforte', 2), ('plan', 1), ('pleasant', 1), ('pleasure', 2), ('poor', 1), ('position', 1), ('post', 1), ('preserved', 1), ('pretty', 1), ('prevailed', 1), ('produce', 1), ('projection', 1), ('prudent', 1), ('pure', 1), ('put', 3), ('questions', 2), ('rapid', 1), ('rapturous', 1), ('real', 1), ('really', 2), ('reasonably', 1), ('relation', 1), ('remaining', 1), ('remarkably', 1), ('remove', 1), ('reserved', 2), ('residence', 1), ('right', 2), ('roof', 1), ('said', 3), ('sake', 1), ('saw', 2), ('say', 1), ('says', 1), ('see', 1), ('seems', 1), ('sent', 1), ('september', 1), ('set', 3), ('shameless', 1), ('she', 6), ('shortly', 1), ('shoud', 1), ('should', 2), ('shy', 1), ('silent', 1), ('simple', 1), ('simplicity', 3), ('since', 2), ('sing', 1), ('situation', 1), ('six', 2), ('snug', 1), ('so', 9), ('society', 1), ('some', 1), ('something', 1), ('songs', 1), ('speaking', 2), ('speedily', 1), ('steepest', 2), ('still', 1), ('stood', 1), ('stop', 1), ('strangers', 1), ('strictly', 1), ('stronger', 2), ('strongly', 1), ('such', 1), ('sufficient', 2), ('suitable', 2), ('supposing', 1), ('suspected', 1), ('taste', 1), ('temper', 1), ('ten', 2), ('tended', 1), ('terminated', 1), ('terms', 1), ('than', 1), ('thanks', 1), ('that', 1), ('the', 1), ('their', 1), ('them', 1), ('then', 1), ('there', 1), ('therefor', 1), ('these', 1), ('they', 2), ('thing', 1), ('things', 1), ('this', 2), ('those', 1), ('though', 3), ('through', 1), ('throwing', 1), ('thus', 1), ('time', 1), ('to', 5), ('today', 1), ('too', 2), ('took', 1), ('totally', 1), ('trifling', 1), ('true', 3), ('two', 2), ('u', 1), ('understood', 1), ('uneasy', 2), ('unknown', 1), ('unsatiable', 1), ('until', 1), ('up', 5), ('use', 1), ('valley', 3), ('very', 1), ('via', 1), ('views', 1), ('village', 1), ('want', 1), ('wants', 1), ('warmly', 1), ('warmth', 1), ('was', 2), ('water', 1), ('way', 1), ('we', 2), ('weddings', 1), ('weeks', 2), ('west', 2), ('what', 1), ('when', 1), ('where', 1), ('who', 2), ('whole', 1), ('wholly', 2), ('whom', 1), ('why', 4), ('wife', 2), ('will', 2), ('wish', 2), ('wished', 1), ('with', 1), ('within', 1), ('wondered', 1), ('wont', 1), ('wooded', 1), ('would', 1), ('wound', 1), ('wrong', 1), ('ya', 1), ('ye', 5), ('yesterday', 1), ('yet', 5), ('you', 6), ('your', 1), ('zealously', 1)]\n" ], [ "sorted(count_dict.values(), reverse=True)", "_____no_output_____" ], [ "r_count_dict = [ (v, k) for k,v in count_dict.items()]\nsorted(r_count_dict, reverse=True)[:10]", "_____no_output_____" ], [ "def find_all_indeces(words, keyword):\n postions = []\n for i in range(len(words)):\n if words[i] == keyword:\n postions.append(i)\n return postions", "_____no_output_____" ], [ "find_all_indeces(words, 'suitable')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0b7934c2bf1a30aa865675445afe2bebe02ae5
12,944
ipynb
Jupyter Notebook
notebooks/generate_and_perform_with_robojam.ipynb
cpmpercussion/robojam
8f9524be0ad850bdfc0c3459b0e4b677f5f70a84
[ "MIT" ]
10
2017-11-18T04:01:03.000Z
2022-03-06T21:07:09.000Z
notebooks/generate_and_perform_with_robojam.ipynb
cpmpercussion/robojam
8f9524be0ad850bdfc0c3459b0e4b677f5f70a84
[ "MIT" ]
17
2018-06-12T20:54:40.000Z
2022-02-09T23:27:24.000Z
notebooks/generate_and_perform_with_robojam.ipynb
cpmpercussion/robojam
8f9524be0ad850bdfc0c3459b0e4b677f5f70a84
[ "MIT" ]
2
2017-12-05T23:39:42.000Z
2018-06-13T13:46:33.000Z
36.772727
239
0.579033
[ [ [ "# Generate and Perform Tiny Performances from the MDRNN\n\n- Generates unconditioned and conditioned output from RoboJam's MDRNN\n- Need to open `touchscreen_performance_receiver.pd` in [Pure Data](http://msp.ucsd.edu/software.html) to hear the sound of performances.\n- To test generated performances, there need to be example performances in `.csv` format in `../performances`. These aren't included in the repo right now, but might be updated in future.", "_____no_output_____" ] ], [ [ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n# little path hack to get robojam from one directory up in the filesystem.\nfrom context import * # imports robojam\n# import robojam # alternatively do this.\n\nimport pandas as pd\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Plotting Methods\n\nMainly using \"plot_and_perform\" method to generate 2D and 3D plots.", "_____no_output_____" ] ], [ [ "input_colour = 'darkblue'\ngen_colour = 'firebrick'\nplt.style.use('seaborn-talk')\n\nosc_client = robojam.TouchScreenOscClient()\n\ndef plot_2D(perf_df, name=\"foo\", saving=False):\n \"\"\"Plot in 2D\"\"\"\n ## Plot the performance\n swipes = divide_performance_into_swipes(perf_df)\n plt.figure(figsize=(8, 8))\n for swipe in swipes:\n p = plt.plot(swipe.x, swipe.y, 'o-')\n plt.setp(p, color=gen_colour, linewidth=5.0)\n plt.ylim(1.0,0)\n plt.xlim(0,1.0)\n plt.xticks([])\n plt.yticks([])\n if saving:\n plt.savefig(name+\".png\", bbox_inches='tight')\n plt.close()\n else:\n plt.show()\n\ndef plot_double_2d(perf1, perf2, name=\"foo\", saving=False):\n \"\"\"Plot two performances in 2D\"\"\"\n plt.figure(figsize=(8, 8))\n swipes = divide_performance_into_swipes(perf1)\n for swipe in swipes:\n p = plt.plot(swipe.x, swipe.y, 'o-')\n plt.setp(p, color=input_colour, linewidth=5.0)\n swipes = divide_performance_into_swipes(perf2)\n for swipe in swipes:\n p = plt.plot(swipe.x, swipe.y, 'o-')\n plt.setp(p, color=gen_colour, linewidth=5.0)\n plt.ylim(1.0,0)\n plt.xlim(0,1.0)\n plt.xticks([])\n plt.yticks([])\n if saving:\n plt.savefig(name+\".png\", bbox_inches='tight')\n plt.close()\n else:\n plt.show()\n\ndef plot_3D(perf_df, name=\"foo\", saving=False):\n \"\"\"Plot in 3D\"\"\"\n ## Plot in 3D\n swipes = divide_performance_into_swipes(perf_df)\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n for swipe in swipes:\n p = ax.plot(list(swipe.index), list(swipe.x), list(swipe.y), 'o-')\n plt.setp(p, color=gen_colour, linewidth=5.0)\n ax.set_ylim(0,1.0)\n ax.set_zlim(1.0,0)\n ax.set_xlabel('time (s)')\n ax.set_ylabel('x')\n ax.set_zlabel('y')\n if saving:\n plt.savefig(name+\".png\", bbox_inches='tight')\n plt.close()\n else:\n plt.show()\n \ndef plot_double_3d(perf1, perf2, name=\"foo\", saving=False):\n \"\"\"Plot two performances in 3D\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n swipes = divide_performance_into_swipes(perf1)\n for swipe in swipes:\n p = ax.plot(list(swipe.index), list(swipe.x), list(swipe.y), 'o-')\n plt.setp(p, color=input_colour, linewidth=5.0)\n swipes = divide_performance_into_swipes(perf2)\n for swipe in swipes:\n p = ax.plot(list(swipe.index), list(swipe.x), list(swipe.y), 'o-')\n plt.setp(p, color=gen_colour, linewidth=5.0)\n ax.set_ylim(0,1.0)\n ax.set_zlim(1.0,0)\n ax.set_xlabel('time (s)')\n ax.set_ylabel('x')\n ax.set_zlabel('y')\n if saving:\n plt.savefig(name+\".png\", bbox_inches='tight')\n plt.close()\n else:\n plt.show()\n \ndef plot_and_perform_sequentially(perf1, perf2, perform=True):\n total = np.append(perf1, perf2, axis=0)\n total = total.T\n perf1 = perf1.T\n perf2 = perf2.T\n perf1_df = pd.DataFrame({'x':perf1[0], 'y':perf1[1], 't':perf1[2]})\n perf2_df = pd.DataFrame({'x':perf2[0], 'y':perf2[1], 't':perf2[2]})\n total_df = pd.DataFrame({'x':total[0], 'y':total[1], 't':total[2]})\n perf1_df['time'] = perf1_df.t.cumsum()\n total_perf1_time = perf1_df.t.sum()\n perf2_df['time'] = perf2_df.t.cumsum() + total_perf1_time\n total_df['time'] = total_df.t.cumsum()\n ## Plot the performances\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.plot(perf1_df.time, perf1_df.x, perf1_df.y, '.b-')\n ax.plot(perf2_df.time, perf2_df.x, perf2_df.y, '.r-')\n plt.show()\n if perform:\n osc_client.playPerformance(total_df)\n \ndef divide_performance_into_swipes(perf_df):\n \"\"\"Divides a performance into a sequence of swipe dataframes.\"\"\"\n touch_starts = perf_df[perf_df.moving == 0].index\n performance_swipes = []\n remainder = perf_df\n for att in touch_starts:\n swipe = remainder.iloc[remainder.index < att]\n performance_swipes.append(swipe)\n remainder = remainder.iloc[remainder.index >= att]\n performance_swipes.append(remainder)\n return performance_swipes", "_____no_output_____" ] ], [ [ "## Generate and play a performance\n\nPerformances are generated using the `generate_random_tiny_performance` method which is set to produce performances up to 5 seconds. The LSTM state and first touch can optionally be kept from the last evaluation or re-initialised.\n\nThis block can be run multiple times to generate more performances.", "_____no_output_____" ] ], [ [ "# Generate and play one unconditioned performance\n# Hyperparameters:\nHIDDEN_UNITS = 512\nLAYERS = 3\nMIXES = 16\n# Network\nnet = robojam.MixtureRNN(mode=robojam.NET_MODE_RUN, n_hidden_units=HIDDEN_UNITS, n_mixtures=MIXES, batch_size=1, sequence_length=1, n_layers=LAYERS)\nosc_client.setSynth(instrument = \"chirp\")\nmodel_file = \"../models/mdrnn-2d-1d-3layers-512units-16mixtures\"\nTEMPERATURE = 1.00\n# Generate\nperf = robojam.generate_random_tiny_performance(net, np.array([0.5, 0.5, 0.1]), time_limit=5.0, temp=TEMPERATURE, model_file=model_file)\n# Plot and perform.\nperf_df = robojam.perf_array_to_df(perf)\n\nplot_2D(perf_df, saving=False)\nplot_3D(perf_df, saving=False)\nosc_client.playPerformance(perf_df)", "_____no_output_____" ], [ "## Generate a number of unconditioned performances\nNUMBER = 10\n\n# Hyperparameters:\nHIDDEN_UNITS = 512\nLAYERS = 3\nMIXES = 16\nnet = robojam.MixtureRNN(mode=robojam.NET_MODE_RUN, n_hidden_units=HIDDEN_UNITS, n_mixtures=MIXES, batch_size=1, sequence_length=1, n_layers=LAYERS)\n# Setup synth for performance\nosc_client.setSynth(instrument = \"chirp\")\nmodel_file = \"../models/mdrnn-2d-1d-3layers-512units-16mixtures\"\nTEMPERATURE = 1.00\n\nfor i in range(NUMBER):\n name = \"touchperf-uncond-\" + str(i)\n net.state = None # reset state if needed.\n perf = robojam.generate_random_tiny_performance(net, np.array([0.5, 0.5, 0.1]), time_limit=5.0, temp=TEMPERATURE, model_file=model_file)\n perf_df = robojam.perf_array_to_df(perf)\n plot_2D(perf_df, name=name, saving=True)", "_____no_output_____" ] ], [ [ "# Condition and Generate\n\nConditions the MDRNN on a random touchscreen performance, then generates a 5 second response.\n\nThis requires example performances (`.csv` format) to be in `../performances`. \nSee `TinyPerformanceLoader` for more details.\n\n", "_____no_output_____" ] ], [ [ "# Load the sample touchscreen performances:\nloader = robojam.TinyPerformanceLoader(verbose=False)\n# Fails if example performances are not in ../performance", "_____no_output_____" ], [ "# Generate and play one conditioned performance\n# Hyperparameters:\nHIDDEN_UNITS = 512\nLAYERS = 3\nMIXES = 16\nnet = robojam.MixtureRNN(mode=robojam.NET_MODE_RUN, n_hidden_units=HIDDEN_UNITS, n_mixtures=MIXES, batch_size=1, sequence_length=1, n_layers=LAYERS)\n# Setup synth for performance\nosc_client.setSynth(instrument = \"chirp\")\nmodel_file = \"../models/mdrnn-2d-1d-3layers-512units-16mixtures\"\nTEMPERATURE = 1.00\nin_df = loader.sample_without_replacement(n=1)[0]\n\nin_array = robojam.perf_df_to_array(in_df)\noutput_perf = robojam.condition_and_generate(net, in_array, time_limit=5.0, temp=TEMPERATURE, model_file=model_file)\nout_df = robojam.perf_array_to_df(output_perf)\n\n# Plot and perform\nplot_double_2d(in_df, out_df)\nplot_double_3d(in_df, out_df)\n\n# just perform the output...\nosc_client.playPerformance(out_df)\n# TODO: implement polyphonic playback. Somehow.", "_____no_output_____" ], [ "# Generate a number of conditioned performances.\nNUMBER = 10\n\n# Hyperparameters:\nHIDDEN_UNITS = 512\nLAYERS = 3\nMIXES = 16\nnet = robojam.MixtureRNN(mode=robojam.NET_MODE_RUN, n_hidden_units=HIDDEN_UNITS, n_mixtures=MIXES, batch_size=1, sequence_length=1, n_layers=LAYERS)\n# Setup synth for performance\nosc_client.setSynth(instrument = \"chirp\")\nmodel_file = \"../models/mdrnn-2d-1d-3layers-512units-16mixtures\"\nTEMPERATURE = 1.00\n\n# make the plots\ninput_perf_dfs = loader.sample_without_replacement(n=NUMBER)\nfor i, in_df in enumerate(input_perf_dfs):\n title = \"touchperf-cond-\" + str(i)\n in_array = robojam.perf_df_to_array(in_df)\n in_time = in_array.T[2].sum()\n print(\"In Time:\", in_time)\n output_perf = robojam.condition_and_generate(net, in_array, time_limit=5.0, temp=TEMPERATURE, model_file=model_file)\n out_df = robojam.perf_array_to_df(output_perf)\n print(\"Out Time:\", output_perf.T[2].sum())\n plot_double_2d(in_df, out_df, name=title, saving=True)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb0b80bac459da2a8aa6ce67525e819845af4037
32,297
ipynb
Jupyter Notebook
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
tongni1975/deep-learning-book
5e0b831c58a5cfab99b1db4b4bdbb1040bdd95aa
[ "MIT" ]
1
2020-06-18T04:18:41.000Z
2020-06-18T04:18:41.000Z
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
bharat3012/deep-learning-book
839e076c5098084512c947a38878a9a545d9a87d
[ "MIT" ]
null
null
null
code/model_zoo/pytorch_ipynb/convnet-vgg19.ipynb
bharat3012/deep-learning-book
839e076c5098084512c947a38878a9a545d9a87d
[ "MIT" ]
1
2021-06-11T02:56:29.000Z
2021-06-11T02:56:29.000Z
36.953089
479
0.481252
[ [ [ "*Accompanying code examples of the book \"Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python\" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICENSE). If you find this content useful, please consider supporting the work by buying a [copy of the book](https://leanpub.com/ann-and-deeplearning).*\n \nOther code examples and content are available on [GitHub](https://github.com/rasbt/deep-learning-book). The PDF and ebook versions of the book are available through [Leanpub](https://leanpub.com/ann-and-deeplearning).", "_____no_output_____" ] ], [ [ "%load_ext watermark\n%watermark -a 'Sebastian Raschka' -v -p torch", "Sebastian Raschka \n\nCPython 3.6.8\nIPython 7.2.0\n\ntorch 1.0.1.post2\n" ] ], [ [ "- Runs on CPU (not recommended here) or GPU (if available)", "_____no_output_____" ], [ "# Model Zoo -- Convolutional Neural Network (VGG19 Architecture)", "_____no_output_____" ], [ "Implementation of the VGG-19 architecture on Cifar10. \n\n\nReference for VGG-19:\n \n- Simonyan, K., & Zisserman, A. (2014). Very deep convolutional networks for large-scale image recognition. arXiv preprint arXiv:1409.1556.\n\n\nThe following table (taken from Simonyan & Zisserman referenced above) summarizes the VGG19 architecture:\n\n![](images/vgg19/vgg19-arch-table.png)", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import numpy as np\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader", "_____no_output_____" ] ], [ [ "## Settings and Dataset", "_____no_output_____" ] ], [ [ "##########################\n### SETTINGS\n##########################\n\n# Device\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint('Device:', DEVICE)\n\n# Hyperparameters\nrandom_seed = 1\nlearning_rate = 0.001\nnum_epochs = 20\nbatch_size = 128\n\n# Architecture\nnum_features = 784\nnum_classes = 10\n\n\n##########################\n### MNIST DATASET\n##########################\n\n# Note transforms.ToTensor() scales input images\n# to 0-1 range\ntrain_dataset = datasets.CIFAR10(root='data', \n train=True, \n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = datasets.CIFAR10(root='data', \n train=False, \n transform=transforms.ToTensor())\n\n\ntrain_loader = DataLoader(dataset=train_dataset, \n batch_size=batch_size, \n shuffle=True)\n\ntest_loader = DataLoader(dataset=test_dataset, \n batch_size=batch_size, \n shuffle=False)\n\n# Checking the dataset\nfor images, labels in train_loader: \n print('Image batch dimensions:', images.shape)\n print('Image label dimensions:', labels.shape)\n break", "Device: cuda:0\nFiles already downloaded and verified\nImage batch dimensions: torch.Size([128, 3, 32, 32])\nImage label dimensions: torch.Size([128])\n" ] ], [ [ "## Model", "_____no_output_____" ] ], [ [ "##########################\n### MODEL\n##########################\n\n\nclass VGG16(torch.nn.Module):\n\n def __init__(self, num_features, num_classes):\n super(VGG16, self).__init__()\n \n # calculate same padding:\n # (w - k + 2*p)/s + 1 = o\n # => p = (s(o-1) - w + k)/2\n \n self.block_1 = nn.Sequential(\n nn.Conv2d(in_channels=3,\n out_channels=64,\n kernel_size=(3, 3),\n stride=(1, 1),\n # (1(32-1)- 32 + 3)/2 = 1\n padding=1), \n nn.ReLU(),\n nn.Conv2d(in_channels=64,\n out_channels=64,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=(2, 2),\n stride=(2, 2))\n )\n \n self.block_2 = nn.Sequential(\n nn.Conv2d(in_channels=64,\n out_channels=128,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=128,\n out_channels=128,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=(2, 2),\n stride=(2, 2))\n )\n \n self.block_3 = nn.Sequential( \n nn.Conv2d(in_channels=128,\n out_channels=256,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=256,\n out_channels=256,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(), \n nn.Conv2d(in_channels=256,\n out_channels=256,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=256,\n out_channels=256,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=(2, 2),\n stride=(2, 2))\n )\n \n \n self.block_4 = nn.Sequential( \n nn.Conv2d(in_channels=256,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(), \n nn.Conv2d(in_channels=512,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(), \n nn.Conv2d(in_channels=512,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=512,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(), \n nn.MaxPool2d(kernel_size=(2, 2),\n stride=(2, 2))\n )\n \n self.block_5 = nn.Sequential(\n nn.Conv2d(in_channels=512,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(), \n nn.Conv2d(in_channels=512,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(), \n nn.Conv2d(in_channels=512,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=512,\n out_channels=512,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n nn.ReLU(), \n nn.MaxPool2d(kernel_size=(2, 2),\n stride=(2, 2)) \n )\n \n self.classifier = nn.Sequential(\n nn.Linear(512, 4096),\n nn.ReLU(True),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Linear(4096, num_classes)\n )\n \n \n for m in self.modules():\n if isinstance(m, torch.nn.Conv2d):\n #n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n #m.weight.data.normal_(0, np.sqrt(2. / n))\n m.weight.detach().normal_(0, 0.05)\n if m.bias is not None:\n m.bias.detach().zero_()\n elif isinstance(m, torch.nn.Linear):\n m.weight.detach().normal_(0, 0.05)\n m.bias.detach().detach().zero_()\n \n \n def forward(self, x):\n\n x = self.block_1(x)\n x = self.block_2(x)\n x = self.block_3(x)\n x = self.block_4(x)\n x = self.block_5(x)\n logits = self.classifier(x.view(-1, 512))\n probas = F.softmax(logits, dim=1)\n\n return logits, probas\n\n \ntorch.manual_seed(random_seed)\nmodel = VGG16(num_features=num_features,\n num_classes=num_classes)\n\nmodel = model.to(DEVICE)\n\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) ", "_____no_output_____" ] ], [ [ "## Training", "_____no_output_____" ] ], [ [ "def compute_accuracy(model, data_loader):\n model.eval()\n correct_pred, num_examples = 0, 0\n for i, (features, targets) in enumerate(data_loader):\n \n features = features.to(DEVICE)\n targets = targets.to(DEVICE)\n\n logits, probas = model(features)\n _, predicted_labels = torch.max(probas, 1)\n num_examples += targets.size(0)\n correct_pred += (predicted_labels == targets).sum()\n return correct_pred.float()/num_examples * 100\n\n\ndef compute_epoch_loss(model, data_loader):\n model.eval()\n curr_loss, num_examples = 0., 0\n with torch.no_grad():\n for features, targets in data_loader:\n features = features.to(DEVICE)\n targets = targets.to(DEVICE)\n logits, probas = model(features)\n loss = F.cross_entropy(logits, targets, reduction='sum')\n num_examples += targets.size(0)\n curr_loss += loss\n\n curr_loss = curr_loss / num_examples\n return curr_loss\n \n \n\nstart_time = time.time()\nfor epoch in range(num_epochs):\n \n model.train()\n for batch_idx, (features, targets) in enumerate(train_loader):\n \n features = features.to(DEVICE)\n targets = targets.to(DEVICE)\n \n ### FORWARD AND BACK PROP\n logits, probas = model(features)\n cost = F.cross_entropy(logits, targets)\n optimizer.zero_grad()\n \n cost.backward()\n \n ### UPDATE MODEL PARAMETERS\n optimizer.step()\n \n ### LOGGING\n if not batch_idx % 50:\n print ('Epoch: %03d/%03d | Batch %04d/%04d | Cost: %.4f' \n %(epoch+1, num_epochs, batch_idx, \n len(train_loader), cost))\n\n model.eval()\n with torch.set_grad_enabled(False): # save memory during inference\n print('Epoch: %03d/%03d | Train: %.3f%% | Loss: %.3f' % (\n epoch+1, num_epochs, \n compute_accuracy(model, train_loader),\n compute_epoch_loss(model, train_loader)))\n\n\n print('Time elapsed: %.2f min' % ((time.time() - start_time)/60))\n \nprint('Total Training Time: %.2f min' % ((time.time() - start_time)/60))", "Epoch: 001/020 | Batch 0000/0391 | Cost: 1061.4152\nEpoch: 001/020 | Batch 0050/0391 | Cost: 2.3018\nEpoch: 001/020 | Batch 0100/0391 | Cost: 2.0600\nEpoch: 001/020 | Batch 0150/0391 | Cost: 1.9973\nEpoch: 001/020 | Batch 0200/0391 | Cost: 1.8176\nEpoch: 001/020 | Batch 0250/0391 | Cost: 1.8368\nEpoch: 001/020 | Batch 0300/0391 | Cost: 1.7213\nEpoch: 001/020 | Batch 0350/0391 | Cost: 1.7154\nEpoch: 001/020 | Train: 35.478% | Loss: 1.685\nTime elapsed: 1.02 min\nEpoch: 002/020 | Batch 0000/0391 | Cost: 1.7648\nEpoch: 002/020 | Batch 0050/0391 | Cost: 1.7050\nEpoch: 002/020 | Batch 0100/0391 | Cost: 1.5464\nEpoch: 002/020 | Batch 0150/0391 | Cost: 1.6054\nEpoch: 002/020 | Batch 0200/0391 | Cost: 1.4430\nEpoch: 002/020 | Batch 0250/0391 | Cost: 1.4253\nEpoch: 002/020 | Batch 0300/0391 | Cost: 1.5701\nEpoch: 002/020 | Batch 0350/0391 | Cost: 1.4163\nEpoch: 002/020 | Train: 44.042% | Loss: 1.531\nTime elapsed: 2.07 min\nEpoch: 003/020 | Batch 0000/0391 | Cost: 1.5172\nEpoch: 003/020 | Batch 0050/0391 | Cost: 1.1992\nEpoch: 003/020 | Batch 0100/0391 | Cost: 1.2846\nEpoch: 003/020 | Batch 0150/0391 | Cost: 1.4088\nEpoch: 003/020 | Batch 0200/0391 | Cost: 1.4853\nEpoch: 003/020 | Batch 0250/0391 | Cost: 1.3923\nEpoch: 003/020 | Batch 0300/0391 | Cost: 1.3268\nEpoch: 003/020 | Batch 0350/0391 | Cost: 1.3162\nEpoch: 003/020 | Train: 55.596% | Loss: 1.223\nTime elapsed: 3.10 min\nEpoch: 004/020 | Batch 0000/0391 | Cost: 1.2210\nEpoch: 004/020 | Batch 0050/0391 | Cost: 1.2594\nEpoch: 004/020 | Batch 0100/0391 | Cost: 1.2881\nEpoch: 004/020 | Batch 0150/0391 | Cost: 1.0182\nEpoch: 004/020 | Batch 0200/0391 | Cost: 1.1256\nEpoch: 004/020 | Batch 0250/0391 | Cost: 1.1048\nEpoch: 004/020 | Batch 0300/0391 | Cost: 1.1812\nEpoch: 004/020 | Batch 0350/0391 | Cost: 1.1685\nEpoch: 004/020 | Train: 57.594% | Loss: 1.178\nTime elapsed: 4.13 min\nEpoch: 005/020 | Batch 0000/0391 | Cost: 1.1298\nEpoch: 005/020 | Batch 0050/0391 | Cost: 0.9705\nEpoch: 005/020 | Batch 0100/0391 | Cost: 0.9255\nEpoch: 005/020 | Batch 0150/0391 | Cost: 1.3610\nEpoch: 005/020 | Batch 0200/0391 | Cost: 0.9720\nEpoch: 005/020 | Batch 0250/0391 | Cost: 1.0088\nEpoch: 005/020 | Batch 0300/0391 | Cost: 0.9998\nEpoch: 005/020 | Batch 0350/0391 | Cost: 1.1961\nEpoch: 005/020 | Train: 63.570% | Loss: 1.003\nTime elapsed: 5.17 min\nEpoch: 006/020 | Batch 0000/0391 | Cost: 0.8837\nEpoch: 006/020 | Batch 0050/0391 | Cost: 0.9184\nEpoch: 006/020 | Batch 0100/0391 | Cost: 0.8568\nEpoch: 006/020 | Batch 0150/0391 | Cost: 1.0788\nEpoch: 006/020 | Batch 0200/0391 | Cost: 1.0365\nEpoch: 006/020 | Batch 0250/0391 | Cost: 0.8714\nEpoch: 006/020 | Batch 0300/0391 | Cost: 1.0370\nEpoch: 006/020 | Batch 0350/0391 | Cost: 1.0536\nEpoch: 006/020 | Train: 68.390% | Loss: 0.880\nTime elapsed: 6.20 min\nEpoch: 007/020 | Batch 0000/0391 | Cost: 1.0297\nEpoch: 007/020 | Batch 0050/0391 | Cost: 0.8801\nEpoch: 007/020 | Batch 0100/0391 | Cost: 0.9652\nEpoch: 007/020 | Batch 0150/0391 | Cost: 1.1417\nEpoch: 007/020 | Batch 0200/0391 | Cost: 0.8851\nEpoch: 007/020 | Batch 0250/0391 | Cost: 0.9499\nEpoch: 007/020 | Batch 0300/0391 | Cost: 0.9416\nEpoch: 007/020 | Batch 0350/0391 | Cost: 0.9220\nEpoch: 007/020 | Train: 68.740% | Loss: 0.872\nTime elapsed: 7.24 min\nEpoch: 008/020 | Batch 0000/0391 | Cost: 1.0054\nEpoch: 008/020 | Batch 0050/0391 | Cost: 0.8184\nEpoch: 008/020 | Batch 0100/0391 | Cost: 0.8955\nEpoch: 008/020 | Batch 0150/0391 | Cost: 0.9319\nEpoch: 008/020 | Batch 0200/0391 | Cost: 1.0566\nEpoch: 008/020 | Batch 0250/0391 | Cost: 1.0591\nEpoch: 008/020 | Batch 0300/0391 | Cost: 0.7914\nEpoch: 008/020 | Batch 0350/0391 | Cost: 0.9090\nEpoch: 008/020 | Train: 72.846% | Loss: 0.770\nTime elapsed: 8.27 min\nEpoch: 009/020 | Batch 0000/0391 | Cost: 0.6672\nEpoch: 009/020 | Batch 0050/0391 | Cost: 0.7192\nEpoch: 009/020 | Batch 0100/0391 | Cost: 0.8586\nEpoch: 009/020 | Batch 0150/0391 | Cost: 0.7310\nEpoch: 009/020 | Batch 0200/0391 | Cost: 0.8406\nEpoch: 009/020 | Batch 0250/0391 | Cost: 0.7620\nEpoch: 009/020 | Batch 0300/0391 | Cost: 0.6692\nEpoch: 009/020 | Batch 0350/0391 | Cost: 0.6407\nEpoch: 009/020 | Train: 73.702% | Loss: 0.748\nTime elapsed: 9.30 min\nEpoch: 010/020 | Batch 0000/0391 | Cost: 0.6539\nEpoch: 010/020 | Batch 0050/0391 | Cost: 1.0382\nEpoch: 010/020 | Batch 0100/0391 | Cost: 0.5921\nEpoch: 010/020 | Batch 0150/0391 | Cost: 0.4933\nEpoch: 010/020 | Batch 0200/0391 | Cost: 0.7485\nEpoch: 010/020 | Batch 0250/0391 | Cost: 0.6779\nEpoch: 010/020 | Batch 0300/0391 | Cost: 0.6787\nEpoch: 010/020 | Batch 0350/0391 | Cost: 0.6977\nEpoch: 010/020 | Train: 75.708% | Loss: 0.703\nTime elapsed: 10.34 min\nEpoch: 011/020 | Batch 0000/0391 | Cost: 0.6866\nEpoch: 011/020 | Batch 0050/0391 | Cost: 0.7203\nEpoch: 011/020 | Batch 0100/0391 | Cost: 0.5730\nEpoch: 011/020 | Batch 0150/0391 | Cost: 0.5762\nEpoch: 011/020 | Batch 0200/0391 | Cost: 0.6571\nEpoch: 011/020 | Batch 0250/0391 | Cost: 0.7582\nEpoch: 011/020 | Batch 0300/0391 | Cost: 0.7366\nEpoch: 011/020 | Batch 0350/0391 | Cost: 0.6810\nEpoch: 011/020 | Train: 79.044% | Loss: 0.606\nTime elapsed: 11.37 min\nEpoch: 012/020 | Batch 0000/0391 | Cost: 0.5665\nEpoch: 012/020 | Batch 0050/0391 | Cost: 0.7081\nEpoch: 012/020 | Batch 0100/0391 | Cost: 0.6823\nEpoch: 012/020 | Batch 0150/0391 | Cost: 0.8297\nEpoch: 012/020 | Batch 0200/0391 | Cost: 0.6470\nEpoch: 012/020 | Batch 0250/0391 | Cost: 0.7293\nEpoch: 012/020 | Batch 0300/0391 | Cost: 0.9127\nEpoch: 012/020 | Batch 0350/0391 | Cost: 0.8419\nEpoch: 012/020 | Train: 79.474% | Loss: 0.585\nTime elapsed: 12.40 min\nEpoch: 013/020 | Batch 0000/0391 | Cost: 0.4087\nEpoch: 013/020 | Batch 0050/0391 | Cost: 0.4224\nEpoch: 013/020 | Batch 0100/0391 | Cost: 0.4336\nEpoch: 013/020 | Batch 0150/0391 | Cost: 0.6586\nEpoch: 013/020 | Batch 0200/0391 | Cost: 0.7107\nEpoch: 013/020 | Batch 0250/0391 | Cost: 0.7359\nEpoch: 013/020 | Batch 0300/0391 | Cost: 0.4860\nEpoch: 013/020 | Batch 0350/0391 | Cost: 0.7271\nEpoch: 013/020 | Train: 80.746% | Loss: 0.549\nTime elapsed: 13.44 min\nEpoch: 014/020 | Batch 0000/0391 | Cost: 0.5500\nEpoch: 014/020 | Batch 0050/0391 | Cost: 0.5108\nEpoch: 014/020 | Batch 0100/0391 | Cost: 0.5186\nEpoch: 014/020 | Batch 0150/0391 | Cost: 0.4737\nEpoch: 014/020 | Batch 0200/0391 | Cost: 0.7015\nEpoch: 014/020 | Batch 0250/0391 | Cost: 0.6069\nEpoch: 014/020 | Batch 0300/0391 | Cost: 0.7080\nEpoch: 014/020 | Batch 0350/0391 | Cost: 0.6460\nEpoch: 014/020 | Train: 81.596% | Loss: 0.553\nTime elapsed: 14.47 min\nEpoch: 015/020 | Batch 0000/0391 | Cost: 0.5398\nEpoch: 015/020 | Batch 0050/0391 | Cost: 0.5269\nEpoch: 015/020 | Batch 0100/0391 | Cost: 0.5048\nEpoch: 015/020 | Batch 0150/0391 | Cost: 0.5873\nEpoch: 015/020 | Batch 0200/0391 | Cost: 0.5320\nEpoch: 015/020 | Batch 0250/0391 | Cost: 0.4743\nEpoch: 015/020 | Batch 0300/0391 | Cost: 0.6124\nEpoch: 015/020 | Batch 0350/0391 | Cost: 0.7204\nEpoch: 015/020 | Train: 85.276% | Loss: 0.439\nTime elapsed: 15.51 min\nEpoch: 016/020 | Batch 0000/0391 | Cost: 0.4387\nEpoch: 016/020 | Batch 0050/0391 | Cost: 0.3777\nEpoch: 016/020 | Batch 0100/0391 | Cost: 0.3430\nEpoch: 016/020 | Batch 0150/0391 | Cost: 0.5901\nEpoch: 016/020 | Batch 0200/0391 | Cost: 0.6303\nEpoch: 016/020 | Batch 0250/0391 | Cost: 0.4983\nEpoch: 016/020 | Batch 0300/0391 | Cost: 0.6507\nEpoch: 016/020 | Batch 0350/0391 | Cost: 0.4663\nEpoch: 016/020 | Train: 86.440% | Loss: 0.406\nTime elapsed: 16.55 min\nEpoch: 017/020 | Batch 0000/0391 | Cost: 0.4675\nEpoch: 017/020 | Batch 0050/0391 | Cost: 0.6440\nEpoch: 017/020 | Batch 0100/0391 | Cost: 0.3536\nEpoch: 017/020 | Batch 0150/0391 | Cost: 0.5421\nEpoch: 017/020 | Batch 0200/0391 | Cost: 0.4504\nEpoch: 017/020 | Batch 0250/0391 | Cost: 0.4169\nEpoch: 017/020 | Batch 0300/0391 | Cost: 0.4617\nEpoch: 017/020 | Batch 0350/0391 | Cost: 0.4092\nEpoch: 017/020 | Train: 84.636% | Loss: 0.459\nTime elapsed: 17.59 min\nEpoch: 018/020 | Batch 0000/0391 | Cost: 0.4267\nEpoch: 018/020 | Batch 0050/0391 | Cost: 0.6478\nEpoch: 018/020 | Batch 0100/0391 | Cost: 0.5806\nEpoch: 018/020 | Batch 0150/0391 | Cost: 0.5453\nEpoch: 018/020 | Batch 0200/0391 | Cost: 0.4984\nEpoch: 018/020 | Batch 0250/0391 | Cost: 0.2517\nEpoch: 018/020 | Batch 0300/0391 | Cost: 0.5219\nEpoch: 018/020 | Batch 0350/0391 | Cost: 0.5217\nEpoch: 018/020 | Train: 86.094% | Loss: 0.413\nTime elapsed: 18.63 min\nEpoch: 019/020 | Batch 0000/0391 | Cost: 0.3849\nEpoch: 019/020 | Batch 0050/0391 | Cost: 0.2890\nEpoch: 019/020 | Batch 0100/0391 | Cost: 0.5058\nEpoch: 019/020 | Batch 0150/0391 | Cost: 0.5718\nEpoch: 019/020 | Batch 0200/0391 | Cost: 0.4053\nEpoch: 019/020 | Batch 0250/0391 | Cost: 0.5241\nEpoch: 019/020 | Batch 0300/0391 | Cost: 0.7110\nEpoch: 019/020 | Batch 0350/0391 | Cost: 0.4572\nEpoch: 019/020 | Train: 87.586% | Loss: 0.365\nTime elapsed: 19.67 min\nEpoch: 020/020 | Batch 0000/0391 | Cost: 0.3576\nEpoch: 020/020 | Batch 0050/0391 | Cost: 0.3466\nEpoch: 020/020 | Batch 0100/0391 | Cost: 0.3427\nEpoch: 020/020 | Batch 0150/0391 | Cost: 0.3117\nEpoch: 020/020 | Batch 0200/0391 | Cost: 0.4912\nEpoch: 020/020 | Batch 0250/0391 | Cost: 0.4481\nEpoch: 020/020 | Batch 0300/0391 | Cost: 0.6303\nEpoch: 020/020 | Batch 0350/0391 | Cost: 0.4274\nEpoch: 020/020 | Train: 88.024% | Loss: 0.361\nTime elapsed: 20.71 min\nTotal Training Time: 20.71 min\n" ] ], [ [ "## Evaluation", "_____no_output_____" ] ], [ [ "with torch.set_grad_enabled(False): # save memory during inference\n print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader)))", "Test accuracy: 74.56%\n" ], [ "%watermark -iv", "numpy 1.15.4\ntorch 1.0.1.post2\n\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0b8ad34687fb58e2eb736f272b073ce7860c09
540,562
ipynb
Jupyter Notebook
notebooks/flowpm-MultiGrid.ipynb
Maxelee/flowpm
361b07db6e7a17f6926e6e22e7710a818685b743
[ "MIT" ]
73
2019-04-18T20:54:12.000Z
2021-07-21T18:28:23.000Z
notebooks/flowpm-MultiGrid.ipynb
Maxelee/flowpm
361b07db6e7a17f6926e6e22e7710a818685b743
[ "MIT" ]
55
2019-09-20T05:00:27.000Z
2021-03-09T09:18:18.000Z
notebooks/flowpm-MultiGrid.ipynb
Maxelee/flowpm
361b07db6e7a17f6926e6e22e7710a818685b743
[ "MIT" ]
10
2019-09-19T01:13:08.000Z
2021-01-13T19:20:54.000Z
894.970199
139,504
0.951099
[ [ [ "<a href=\"https://colab.research.google.com/github/modichirag/flowpm/blob/master/notebooks/flowpm_tutorial.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "%pylab inline\nfrom flowpm import linear_field, lpt_init, nbody, cic_paint\n\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\nfrom scipy.interpolate import InterpolatedUnivariateSpline as iuspline\n\nklin = np.loadtxt('../flowpm/data/Planck15_a1p00.txt').T[0]\nplin = np.loadtxt('../flowpm/data/Planck15_a1p00.txt').T[1]\n\nipklin = iuspline(klin, plin)", "Populating the interactive namespace from numpy and matplotlib\nWARNING:tensorflow:From /usr/lib/python3.8/site-packages/tensorflow_core/python/compat/v2_compat.py:65: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.\nInstructions for updating:\nnon-resource variables are not supported in the long term\n" ], [ "import flowpm\n\nstages = np.linspace(0.1, 1.0, 10, endpoint=True)\n\ninitial_conditions = flowpm.linear_field(128, # size of the cube\n 100, # Physical size of the cube\n ipklin, # Initial powerspectrum\n batch_size=1)\n\n# Sample particles\nstate = flowpm.lpt_init(initial_conditions, a0=0.1) \n\n# Evolve particles down to z=0\nfinal_state = flowpm.nbody(state, stages, 128) \n\n# Retrieve final density field\nfinal_field = flowpm.cic_paint(tf.zeros_like(initial_conditions), final_state[0])\n\nwith tf.Session() as sess:\n sim = sess.run(final_field)", "_____no_output_____" ], [ "imshow(sim[0].sum(axis=0))", "_____no_output_____" ], [ "def _binomial_kernel(num_channels, dtype=tf.float32):\n \"\"\"Creates a 5x5x5 b-spline kernel.\n Args:\n num_channels: The number of channels of the image to filter.\n dtype: The type of an element in the kernel.\n Returns:\n A tensor of shape `[5, 5, 5, num_channels, num_channels]`.\n \"\"\"\n kernel = np.array((1., 4., 6., 4., 1.), dtype=dtype.as_numpy_dtype())\n kernel = np.einsum('ij,k->ijk', np.outer(kernel, kernel), kernel)\n kernel /= np.sum(kernel)\n kernel = kernel[:, :, :, np.newaxis, np.newaxis]\n return tf.constant(kernel, dtype=dtype) * tf.eye(num_channels, dtype=dtype)\n\ndef _downsample(cube, kernel):\n \"\"\"Downsamples the image using a convolution with stride 2.\n \"\"\"\n return tf.nn.conv3d(\n input=cube, filters=kernel, strides=[1, 2, 2, 2, 1], padding=\"SAME\")\n \ndef _upsample(cube, kernel, output_shape=None):\n \"\"\"Upsamples the image using a transposed convolution with stride 2.\n \"\"\"\n if output_shape is None:\n output_shape = tf.shape(input=cube)\n output_shape = (output_shape[0], output_shape[1] * 2, output_shape[2] * 2,\n output_shape[3] * 2, output_shape[4])\n return tf.nn.conv3d_transpose(\n cube,\n kernel * 2.0**3,\n output_shape=output_shape,\n strides=[1, 2, 2, 2, 1],\n padding=\"SAME\")\n\ndef _build_pyramid(cube, sampler, num_levels):\n \"\"\"Creates the different levels of the pyramid.\n \"\"\"\n kernel = _binomial_kernel(1, dtype=cube.dtype)\n levels = [cube]\n for _ in range(num_levels):\n cube = sampler(cube, kernel)\n levels.append(cube)\n return levels\n\ndef _split(cube, kernel):\n \"\"\"Splits the image into high and low frequencies.\n This is achieved by smoothing the input image and substracting the smoothed\n version from the input.\n \"\"\"\n low = _downsample(cube, kernel)\n high = cube - _upsample(low, kernel, tf.shape(input=cube))\n return high, low\n\ndef downsample(cube, num_levels, name=None):\n \"\"\"Generates the different levels of the pyramid (downsampling).\n \"\"\"\n with tf.name_scope(name, \"pyramid_downsample\", [cube]):\n cube = tf.convert_to_tensor(value=cube)\n return _build_pyramid(cube, _downsample, num_levels)\n\ndef merge(levels, name=None):\n \"\"\"Merges the different levels of the pyramid back to an image.\n \"\"\"\n with tf.name_scope(name, \"pyramid_merge\", levels):\n levels = [tf.convert_to_tensor(value=level) for level in levels]\n cube = levels[-1]\n kernel = _binomial_kernel(tf.shape(input=cube)[-1], dtype=cube.dtype)\n for level in reversed(levels[:-1]):\n cube = _upsample(cube, kernel, tf.shape(input=level)) + level\n return cube\n\ndef split(cube, num_levels, name=None):\n \"\"\"Generates the different levels of the pyramid.\n \"\"\"\n with tf.name_scope(name, \"pyramid_split\", [cube]):\n cube = tf.convert_to_tensor(value=cube)\n\n kernel = _binomial_kernel(tf.shape(input=cube)[-1], dtype=cube.dtype)\n low = cube\n levels = []\n for _ in range(num_levels):\n high, low = _split(low, kernel)\n levels.append(high)\n levels.append(low)\n return levels\n\ndef upsample(cube, num_levels, name=None):\n \"\"\"Generates the different levels of the pyramid (upsampling).\n \"\"\"\n with tf.name_scope(name, \"pyramid_upsample\", [cube]):\n cube = tf.convert_to_tensor(value=cube)\n return _build_pyramid(cube, _upsample, num_levels)", "_____no_output_____" ], [ "field = tf.expand_dims(final_field, -1)", "_____no_output_____" ], [ "# Split field into short range and large scale components\nlevels = split(field, 1)", "_____no_output_____" ], [ "levels", "_____no_output_____" ], [ "# Compute forces on both fields\ndef force(field): \n shape = field.get_shape()\n batch_size, nc = shape[1], shape[2].value\n kfield = flowpm.utils.r2c3d(field)\n kvec = flowpm.kernels.fftk((nc, nc, nc), symmetric=False)\n \n \n lap = tf.cast(flowpm.kernels.laplace_kernel(kvec), tf.complex64)\n fknlrange = flowpm.kernels.longrange_kernel(kvec, 0)\n kweight = lap * fknlrange\n pot_k = tf.multiply(kfield, kweight)\n \n f = []\n for d in range(3):\n force_dc = tf.multiply(pot_k, flowpm.kernels.gradient_kernel(kvec, d))\n forced = flowpm.utils.c2r3d(force_dc)\n f.append(forced)\n \n return tf.stack(f, axis=-1)", "_____no_output_____" ], [ "force_levels = [force(levels[0][...,0]), force(levels[1][...,0])*2]", "_____no_output_____" ], [ "force_levels", "_____no_output_____" ], [ "rec = merge(force_levels)", "_____no_output_____" ], [ "rec", "_____no_output_____" ], [ "# Direct force computation on input field\ndforce = force(field[...,0])", "_____no_output_____" ], [ "with tf.Session() as sess:\n sim, l0, l1, r, df = sess.run([final_field, force_levels[0], force_levels[1], rec, dforce])", "_____no_output_____" ], [ "figure(figsize=(15,5))\nsubplot(131)\nimshow(sim[0].sum(axis=1))\ntitle('Input')\nsubplot(132)\nimshow(l0[0].sum(axis=1)[...,0])\ntitle('short range forces')\nsubplot(133)\nimshow(l1[0].sum(axis=1)[...,0]);\ntitle('l2')\ntitle('long range forces')", "_____no_output_____" ], [ "figure(figsize=(15,5))\nsubplot(131)\nimshow(r[0].sum(axis=1)[...,0]);\ntitle('Multi-Grid Force Computation')\nsubplot(132)\nimshow(df[0].sum(axis=1)[...,0]);\ntitle('Direct Force Computation')\nsubplot(133)\nimshow((r - df)[0,8:-8,8:-8,8:-8].sum(axis=1)[...,0]); \ntitle('Residuals'); ", "_____no_output_____" ], [ "levels = split(field, 4)", "_____no_output_____" ], [ "rec = merge(levels)", "_____no_output_____" ], [ "with tf.Session() as sess:\n sim, l0, l1, l2, l3, r = sess.run([final_field, levels[0], levels[1], levels[2], levels[3], rec[...,0]])", "_____no_output_____" ], [ "figure(figsize=(25,10))\nsubplot(151)\nimshow(sim[0].sum(axis=0))\ntitle('Input')\nsubplot(152)\nimshow(l0[0].sum(axis=0)[...,0])\ntitle('l1')\nsubplot(153)\nimshow(l1[0].sum(axis=0)[...,0]);\ntitle('l2')\nsubplot(154)\nimshow(l2[0].sum(axis=0)[...,0]);\ntitle('l2')\nsubplot(155)\nimshow(l3[0].sum(axis=0)[...,0]);\ntitle('approximation')", "_____no_output_____" ], [ "figure(figsize=(25,10))\nsubplot(131)\nimshow(sim[0].sum(axis=0))\ntitle('Input')\nsubplot(132)\nimshow(r[0].sum(axis=0))\ntitle('Reconstruction')\nsubplot(133)\nimshow((sim - r)[0].sum(axis=0));\ntitle('Difference')", "_____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" ] ]
cb0bac3dfcc23617767817664ac94dcd68214863
4,117
ipynb
Jupyter Notebook
clear_field.ipynb
tenlee13/carel-jupyter
e686e99c6bda4dadb4a0c4c50d4ae91810a0c883
[ "Apache-2.0" ]
null
null
null
clear_field.ipynb
tenlee13/carel-jupyter
e686e99c6bda4dadb4a0c4c50d4ae91810a0c883
[ "Apache-2.0" ]
null
null
null
clear_field.ipynb
tenlee13/carel-jupyter
e686e99c6bda4dadb4a0c4c50d4ae91810a0c883
[ "Apache-2.0" ]
null
null
null
22.254054
58
0.408793
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb0baf84f30488f04906888e80058e7084952ac8
83,801
ipynb
Jupyter Notebook
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
2293482748b86760aa8250fd6e23e7aa87e640f2
[ "MIT" ]
null
null
null
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
2293482748b86760aa8250fd6e23e7aa87e640f2
[ "MIT" ]
null
null
null
notebooks/WhenToStopFuzzing.ipynb
unibw-patch/fuzzingbook
2293482748b86760aa8250fd6e23e7aa87e640f2
[ "MIT" ]
null
null
null
33.096761
788
0.594181
[ [ [ "# When To Stop Fuzzing\n\nIn the past chapters, we have discussed several fuzzing techniques. Knowing _what_ to do is important, but it is also important to know when to _stop_ doing things. In this chapter, we will learn when to _stop fuzzing_ – and use a prominent example for this purpose: The *Enigma* machine that was used in the second world war by the navy of Nazi Germany to encrypt communications, and how Alan Turing and I.J. Good used _fuzzing techniques_ to crack ciphers for the Naval Enigma machine.", "_____no_output_____" ], [ "Turing did not only develop the foundations of computer science, the Turing machine. Together with his assistant I.J. Good, he also invented estimators of the probability of an event occuring that has never previously occured. We show how the Good-Turing estimator can be used to quantify the *residual risk* of a fuzzing campaign that finds no vulnerabilities. Meaning, we show how it estimates the probability of discovering a vulnerability when no vulnerability has been observed before throughout the fuzzing campaign.\n\nWe discuss means to speed up [coverage-based fuzzers](Coverage.ipynb) and introduce a range of estimation and extrapolation methodologies to assess and extrapolate fuzzing progress and residual risk.\n\n**Prerequisites**\n\n* _The chapter on [Coverage](Coverage.ipynb) discusses how to use coverage information for an executed test input to guide a coverage-based mutational greybox fuzzer_.\n* Some knowledge of statistics is helpful.", "_____no_output_____" ] ], [ [ "import fuzzingbook_utils", "_____no_output_____" ], [ "import Fuzzer\nimport Coverage", "_____no_output_____" ] ], [ [ "## The Enigma Machine\n\nIt is autumn in the year of 1938. Turing has just finished his PhD at Princeton University demonstrating the limits of computation and laying the foundation for the theory of computer science. Nazi Germany is rearming. It has reoccupied the Rhineland and annexed Austria against the treaty of Versailles. It has just annexed the Sudetenland in Czechoslovakia and begins preparations to take over the rest of Czechoslovakia despite an agreement just signed in Munich.\n\nMeanwhile, the British intelligence is building up their capability to break encrypted messages used by the Germans to communicate military and naval information. The Germans are using [Enigma machines](https://en.wikipedia.org/wiki/Enigma_machine) for encryption. Enigma machines use a series of electro-mechanical rotor cipher machines to protect military communication. Here is a picture of an Enigma machine:", "_____no_output_____" ], [ "![Enigma Machine](PICS/Bletchley_Park_Naval_Enigma_IMG_3604.JPG)", "_____no_output_____" ], [ "By the time Turing joined the British Bletchley park, the Polish intelligence reverse engineered the logical structure of the Enigma machine and built a decryption machine called *Bomba* (perhaps because of the ticking noise they made). A bomba simulates six Enigma machines simultaneously and tries different decryption keys until the code is broken. The Polish bomba might have been the very _first fuzzer_.\n\nTuring took it upon himself to crack ciphers of the Naval Enigma machine, which were notoriously hard to crack. The Naval Enigma used, as part of its encryption key, a three letter sequence called *trigram*. These trigrams were selected from a book, called *Kenngruppenbuch*, which contained all trigrams in a random order.", "_____no_output_____" ], [ "### The Kenngruppenbuch\n\nLet's start with the Kenngruppenbuch (K-Book).\n\nWe are going to use the following Python functions.\n* `shuffle(elements)` - shuffle *elements* and put items in random order.\n* `choice(elements, p=weights)` - choose an item from *elements* at random. An element with twice the *weight* is twice as likely to be chosen.\n* `log(a)` - returns the natural logarithm of a.\n* `a ** b` - is the a to the power of b (a.k.a. [power operator](https://docs.python.org/3/reference/expressions.html#the-power-operator))", "_____no_output_____" ] ], [ [ "import string", "_____no_output_____" ], [ "import numpy\nfrom numpy.random import choice\nfrom numpy.random import shuffle\nfrom numpy import log", "_____no_output_____" ] ], [ [ "We start with creating the set of trigrams:", "_____no_output_____" ] ], [ [ "letters = list(string.ascii_letters[26:]) # upper-case characters\ntrigrams = [str(a + b + c) for a in letters for b in letters for c in letters]\nshuffle(trigrams)", "_____no_output_____" ], [ "trigrams[:10]", "_____no_output_____" ] ], [ [ "These now go into the Kenngruppenbuch. However, it was observed that some trigrams were more likely chosen than others. For instance, trigrams at the top-left corner of any page, or trigrams on the first or last few pages were more likely than one somewhere in the middle of the book or page. We reflect this difference in distribution by assigning a _probability_ to each trigram, using Benford's law as introduced in [Probabilistic Fuzzing](ProbabilisticGrammarFuzzer.ipynb).", "_____no_output_____" ], [ "Recall, that Benford's law assigns the $i$-th digit the probability $\\log_{10}\\left(1 + \\frac{1}{i}\\right)$ where the base 10 is chosen because there are 10 digits $i\\in [0,9]$. However, Benford's law works for an arbitrary number of \"digits\". Hence, we assign the $i$-th trigram the probability $\\log_b\\left(1 + \\frac{1}{i}\\right)$ where the base $b$ is the number of all possible trigrams $b=26^3$. ", "_____no_output_____" ] ], [ [ "k_book = {} # Kenngruppenbuch\n\nfor i in range(1, len(trigrams) + 1):\n trigram = trigrams[i - 1]\n # choose weights according to Benford's law\n k_book[trigram] = log(1 + 1 / i) / log(26**3 + 1)", "_____no_output_____" ] ], [ [ "Here's a random trigram from the Kenngruppenbuch:", "_____no_output_____" ] ], [ [ "random_trigram = choice(list(k_book.keys()), p=list(k_book.values()))\nrandom_trigram", "_____no_output_____" ] ], [ [ "And this is its probability:", "_____no_output_____" ] ], [ [ "k_book[random_trigram]", "_____no_output_____" ] ], [ [ "### Fuzzing the Enigma\n\nIn the following, we introduce an extremely simplified implementation of the Naval Enigma based on the trigrams from the K-book. Of course, the encryption mechanism of the actual Enigma machine is much more sophisticated and worthy of a much more detailed investigation. We encourage the interested reader to follow up with further reading listed in the Background section.\n\nThe personell at Bletchley Park can only check whether an encoded message is encoded with a (guessed) trigram.\nOur implementation `naval_enigma()` takes a `message` and a `key` (i.e., the guessed trigram). If the given key matches the (previously computed) key for the message, `naval_enigma()` returns `True`.", "_____no_output_____" ] ], [ [ "from Fuzzer import RandomFuzzer\nfrom Fuzzer import Runner", "_____no_output_____" ], [ "class EnigmaMachine(Runner):\n def __init__(self, k_book):\n self.k_book = k_book\n self.reset()\n\n def reset(self):\n \"\"\"Resets the key register\"\"\"\n self.msg2key = {}\n \n def internal_msg2key(self, message):\n \"\"\"Internal helper method. \n Returns the trigram for an encoded message.\"\"\"\n if not message in self.msg2key:\n # Simulating how an officer chooses a key from the Kenngruppenbuch to encode the message.\n self.msg2key[message] = choice(list(self.k_book.keys()), p=list(self.k_book.values()))\n trigram = self.msg2key[message]\n return trigram\n\n def naval_enigma(self, message, key):\n \"\"\"Returns true if 'message' is encoded with 'key'\"\"\"\n if key == self.internal_msg2key(message):\n return True\n else:\n return False", "_____no_output_____" ] ], [ [ "To \"fuzz\" the `naval_enigma()`, our job will be to come up with a key that matches a given (encrypted) message. Since the keys only have three characters, we have a good chance to achieve this in much less than a seconds. (Of course, longer keys will be much harder to find via random fuzzing.)", "_____no_output_____" ] ], [ [ "class EnigmaMachine(EnigmaMachine):\n def run(self, tri):\n \"\"\"PASS if cur_msg is encoded with trigram tri\"\"\"\n if self.naval_enigma(self.cur_msg, tri):\n outcome = self.PASS\n else:\n outcome = self.FAIL\n\n return (tri, outcome)", "_____no_output_____" ] ], [ [ "Now we can use the `EnigmaMachine` to check whether a certain message is encoded with a certain trigram.", "_____no_output_____" ] ], [ [ "enigma = EnigmaMachine(k_book)\nenigma.cur_msg = \"BrEaK mE. L0Lzz\"\nenigma.run(\"AAA\")", "_____no_output_____" ] ], [ [ "The simplest way to crack an encoded message is by brute forcing. Suppose, at Bletchley park they would try random trigrams until a message is broken.", "_____no_output_____" ] ], [ [ "class BletchleyPark(object):\n def __init__(self, enigma):\n self.enigma = enigma\n self.enigma.reset()\n self.enigma_fuzzer = RandomFuzzer(\n min_length=3,\n max_length=3,\n char_start=65,\n char_range=26)\n \n def break_message(self, message):\n \"\"\"Returning the trigram for an encoded message\"\"\"\n self.enigma.cur_msg = message\n while True:\n (trigram, outcome) = self.enigma_fuzzer.run(self.enigma)\n if outcome == self.enigma.PASS:\n break\n return trigram", "_____no_output_____" ] ], [ [ "How long does it take Bletchley park to find the key using this brute forcing approach?", "_____no_output_____" ] ], [ [ "from Timer import Timer", "_____no_output_____" ], [ "enigma = EnigmaMachine(k_book)\nbletchley = BletchleyPark(enigma)\n\nwith Timer() as t:\n trigram = bletchley.break_message(\"BrEaK mE. L0Lzz\")", "_____no_output_____" ] ], [ [ "Here's the key for the current message:", "_____no_output_____" ] ], [ [ "trigram", "_____no_output_____" ] ], [ [ "And no, this did not take long:", "_____no_output_____" ] ], [ [ "'%f seconds' % t.elapsed_time()", "_____no_output_____" ], [ "'Bletchley cracks about %d messages per second' % (1/t.elapsed_time())", "_____no_output_____" ] ], [ [ "### Turing's Observations\nOkay, lets crack a few messages and count the number of times each trigram is observed.", "_____no_output_____" ] ], [ [ "from collections import defaultdict", "_____no_output_____" ], [ "n = 100 # messages to crack", "_____no_output_____" ], [ "observed = defaultdict(int)\nfor msg in range(0, n):\n trigram = bletchley.break_message(msg)\n observed[trigram] += 1\n\n# list of trigrams that have been observed\ncounts = [k for k, v in observed.items() if int(v) > 0]\n\nt_trigrams = len(k_book)\no_trigrams = len(counts)", "_____no_output_____" ], [ "\"After cracking %d messages, we observed %d out of %d trigrams.\" % (\n n, o_trigrams, t_trigrams)", "_____no_output_____" ], [ "singletons = len([k for k, v in observed.items() if int(v) == 1])", "_____no_output_____" ], [ "\"From the %d observed trigrams, %d were observed only once.\" % (\n o_trigrams, singletons)", "_____no_output_____" ] ], [ [ "Given a sample of previously used entries, Turing wanted to _estimate the likelihood_ that the current unknown entry was one that had been previously used, and further, to estimate the probability distribution over the previously used entries. This lead to the development of the estimators of the missing mass and estimates of the true probability mass of the set of items occuring in the sample. Good worked with Turing during the war and, with Turing’s permission, published the analysis of the bias of these estimators in 1953.", "_____no_output_____" ], [ "Suppose, after finding the keys for n=100 messages, we have observed the trigram \"ABC\" exactly $X_\\text{ABC}=10$ times. What is the probability $p_\\text{ABC}$ that \"ABC\" is the key for the next message? Empirically, we would estimate $\\hat p_\\text{ABC}=\\frac{X_\\text{ABC}}{n}=0.1$. We can derive the empirical estimates for all other trigrams that we have observed. However, it becomes quickly evident that the complete probability mass is distributed over the *observed* trigrams. This leaves no mass for *unobserved* trigrams, i.e., the probability of discovering a new trigram. This is called the missing probability mass or the discovery probability.", "_____no_output_____" ], [ "Turing and Good derived an estimate of the *discovery probability* $p_0$, i.e., the probability to discover an unobserved trigram, as the number $f_1$ of trigrams observed exactly once divided by the total number $n$ of messages cracked:\n$$\np_0 = \\frac{f_1}{n}\n$$\nwhere $f_1$ is the number of singletons and $n$ is the number of cracked messages.", "_____no_output_____" ], [ "Lets explore this idea for a bit. We'll extend `BletchleyPark` to crack `n` messages and record the number of trigrams observed as the number of cracked messages increases.", "_____no_output_____" ] ], [ [ "class BletchleyPark(BletchleyPark):\n \n \n def break_message(self, message):\n \"\"\"Returning the trigram for an encoded message\"\"\"\n # For the following experiment, we want to make it practical\n # to break a large number of messages. So, we remove the\n # loop and just return the trigram for a message.\n #\n # enigma.cur_msg = message\n # while True:\n # (trigram, outcome) = self.enigma_fuzzer.run(self.enigma)\n # if outcome == self.enigma.PASS:\n # break\n trigram = enigma.internal_msg2key(message)\n return trigram\n \n def break_n_messages(self, n):\n \"\"\"Returns how often each trigram has been observed, \n and #trigrams discovered for each message.\"\"\"\n observed = defaultdict(int)\n timeseries = [0] * n\n\n # Crack n messages and record #trigrams observed as #messages increases\n cur_observed = 0\n for cur_msg in range(0, n):\n trigram = self.break_message(cur_msg)\n \n observed[trigram] += 1\n if (observed[trigram] == 1):\n cur_observed += 1\n timeseries[cur_msg] = cur_observed\n \n return (observed, timeseries)", "_____no_output_____" ] ], [ [ "Let's crack 2000 messages and compute the GT-estimate.", "_____no_output_____" ] ], [ [ "n = 2000 # messages to crack", "_____no_output_____" ], [ "bletchley = BletchleyPark(enigma)\n(observed, timeseries) = bletchley.break_n_messages(n)", "_____no_output_____" ] ], [ [ "Let us determine the Good-Turing estimate of the probability that the next trigram has not been observed before:", "_____no_output_____" ] ], [ [ "singletons = len([k for k, v in observed.items() if int(v) == 1])\ngt = singletons / n\ngt", "_____no_output_____" ] ], [ [ "We can verify the Good-Turing estimate empirically and compute the empirically determined probability that the next trigram has not been observed before. To do this, we repeat the following experiment repeats=1000 times, reporting the average: If the next message is a new trigram, return 1, otherwise return 0. Note that here, we do not record the newly discovered trigrams as observed.", "_____no_output_____" ] ], [ [ "repeats = 1000 # experiment repetitions ", "_____no_output_____" ], [ "newly_discovered = 0\nfor cur_msg in range(n, n + repeats):\n trigram = bletchley.break_message(cur_msg)\n if(observed[trigram] == 0):\n newly_discovered += 1\n \nnewly_discovered / repeats", "_____no_output_____" ] ], [ [ "Looks pretty accurate, huh? The difference between estimates is reasonably small, probably below 0.03. However, the Good-Turing estimate did not nearly require as much computational resources as the empirical estimate. Unlike the empirical estimate, the Good-Turing estimate can be computed during the campaign. Unlike the empirical estimate, the Good-Turing estimate requires no additional, redundant repetitions.", "_____no_output_____" ], [ "In fact, the Good-Turing (GT) estimator often performs close to the best estimator for arbitrary distributions ([Try it here!](#Kenngruppenbuch)). Of course, the concept of *discovery* is not limited to trigrams. The GT estimator is also used in the study of natural languages to estimate the likelihood that we haven't ever heard or read the word we next encounter. The GT estimator is used in ecology to estimate the likelihood of discovering a new, unseen species in our quest to catalog all _species_ on earth. Later, we will see how it can be used to estimate the probability to discover a vulnerability when none has been observed, yet (i.e., residual risk).", "_____no_output_____" ], [ "Alan Turing was interested in the _complement_ $(1-GT)$ which gives the proportion of _all_ messages for which the Brits have already observed the trigram needed for decryption. For this reason, the complement is also called sample coverage. The *sample coverage* quantifies how much we know about decryption of all messages given the few messages we have already decrypted. ", "_____no_output_____" ], [ "The probability that the next message can be decrypted with a previously discovered trigram is:", "_____no_output_____" ] ], [ [ "1 - gt", "_____no_output_____" ] ], [ [ "The *inverse* of the GT-estimate (1/GT) is a _maximum likelihood estimate_ of the expected number of messages that we can decrypt with previously observed trigrams before having to find a new trigram to decrypt the message. In our setting, the number of messages for which we can expect to reuse previous trigrams before having to discover a new trigram is:", "_____no_output_____" ] ], [ [ "1 / gt", "_____no_output_____" ] ], [ [ "But why is GT so accurate? Intuitively, despite a large sampling effort (i.e., cracking $n$ messages), there are still $f_1$ trigrams that have been observed only once. We could say that such \"singletons\" are very rare trigrams. Hence, the probability that the next messages is encoded with such a rare but observed trigram gives a good upper bound on the probability that the next message is encoded with an evidently much rarer, unobserved trigram. Since Turing's observation 80 years ago, an entire statistical theory has been developed around the hypothesis that rare, observed \"species\" are good predictors of unobserved species.\n\nLet's have a look at the distribution of rare trigrams.", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "frequencies = [v for k, v in observed.items() if int(v) > 0]\nfrequencies.sort(reverse=True)\n# Uncomment to see how often each discovered trigram has been observed\n# print(frequencies)\n\n# frequency of rare trigrams\nplt.figure(num=None, figsize=(12, 4), dpi=80, facecolor='w', edgecolor='k')\nplt.subplot(1, 2, 1)\nplt.hist(frequencies, range=[1, 21], bins=numpy.arange(1, 21) - 0.5)\nplt.xticks(range(1, 21))\nplt.xlabel('# of occurances (e.g., 1 represents singleton trigrams)')\nplt.ylabel('Frequency of occurances')\nplt.title('Figure 1. Frequency of Rare Trigrams')\n\n# trigram discovery over time\nplt.subplot(1, 2, 2)\nplt.plot(timeseries)\nplt.xlabel('# of messages cracked')\nplt.ylabel('# of trigrams discovered')\nplt.title('Figure 2. Trigram Discovery Over Time');", "_____no_output_____" ], [ "# Statistics for most and least often observed trigrams\nsingletons = len([v for k, v in observed.items() if int(v) == 1])\ntotal = len(frequencies)\n\nprint(\"%3d of %3d trigrams (%.3f%%) have been observed 1 time (i.e., are singleton trigrams).\"\n % (singletons, total, singletons * 100 / total))\n\nprint(\"%3d of %3d trigrams ( %.3f%%) have been observed %d times.\"\n % (1, total, 1 / total, frequencies[0]))", "_____no_output_____" ] ], [ [ "The *majority of trigrams* have been observed only once, as we can see in Figure 1 (left). In other words, a the majority of observed trigrams are \"rare\" singletons. In Figure 2 (right), we can see that discovery is in full swing. The trajectory seems almost linear. However, since there is a finite number of trigrams (26^3 = 17,576) trigram discovery will slow down and eventually approach an asymptote (the total number of trigrams).\n\n### Boosting the Performance of BletchleyPark\nSome trigrams have been observed very often. We call these \"abundant\" trigrams.", "_____no_output_____" ] ], [ [ "print(\"Trigram : Frequency\")\nfor trigram in sorted(observed, key=observed.get, reverse=True):\n if observed[trigram] > 10:\n print(\" %s : %d\" % (trigram, observed[trigram]))", "_____no_output_____" ] ], [ [ "We'll speed up the code breaking by _trying the abundant trigrams first_. \n\nFirst, we'll find out how many messages can be cracked by the existing brute forcing strategy at Bledgley park, given a maximum number of attempts. We'll also track the number of messages cracked over time (`timeseries`).", "_____no_output_____" ] ], [ [ "class BletchleyPark(BletchleyPark):\n \n def __init__(self, enigma):\n super().__init__(enigma)\n self.cur_attempts = 0\n self.cur_observed = 0\n self.observed = defaultdict(int)\n self.timeseries = [None] * max_attempts * 2\n \n def break_message(self, message):\n \"\"\"Returns the trigram for an encoded message, and\n track #trigrams observed as #attempts increases.\"\"\"\n self.enigma.cur_msg = message\n while True:\n self.cur_attempts += 1 # NEW\n (trigram, outcome) = self.enigma_fuzzer.run(self.enigma)\n self.timeseries[self.cur_attempts] = self.cur_observed # NEW\n if outcome == self.enigma.PASS: \n break\n return trigram\n \n def break_max_attempts(self, max_attempts):\n \"\"\"Returns #messages successfully cracked after a given #attempts.\"\"\"\n cur_msg = 0\n n_messages = 0\n\n while True:\n trigram = self.break_message(cur_msg)\n \n # stop when reaching max_attempts\n if self.cur_attempts >= max_attempts:\n break\n \n # update observed trigrams\n n_messages += 1\n self.observed[trigram] += 1\n if (self.observed[trigram] == 1):\n self.cur_observed += 1\n self.timeseries[self.cur_attempts] = self.cur_observed\n cur_msg += 1\n return n_messages", "_____no_output_____" ] ], [ [ "`original` is the number of messages cracked by the bruteforcing strategy, given 100k attempts. Can we beat this?", "_____no_output_____" ] ], [ [ "max_attempts = 100000", "_____no_output_____" ], [ "bletchley = BletchleyPark(enigma)\noriginal = bletchley.break_max_attempts(max_attempts)\noriginal", "_____no_output_____" ] ], [ [ "Now, we'll create a boosting strategy by trying trigrams first that we have previously observed most often.", "_____no_output_____" ] ], [ [ "class BoostedBletchleyPark(BletchleyPark):\n \n def break_message(self, message):\n \"\"\"Returns the trigram for an encoded message, and\n track #trigrams observed as #attempts increases.\"\"\"\n self.enigma.cur_msg = message\n \n # boost cracking by trying observed trigrams first\n for trigram in sorted(self.prior, key=self.prior.get, reverse=True):\n self.cur_attempts += 1\n (_, outcome) = self.enigma.run(trigram)\n self.timeseries[self.cur_attempts] = self.cur_observed\n if outcome == self.enigma.PASS:\n return trigram\n \n # else fall back to normal cracking\n return super().break_message(message)", "_____no_output_____" ] ], [ [ "`boosted` is the number of messages cracked by the boosted strategy.", "_____no_output_____" ] ], [ [ "boostedBletchley = BoostedBletchleyPark(enigma)\nboostedBletchley.prior = observed\nboosted = boostedBletchley.break_max_attempts(max_attempts)\nboosted", "_____no_output_____" ] ], [ [ "We see that the boosted technique cracks substantially more messages. It is worthwhile to record how often each trigram is being used as key and try them in the order of their occurence.\n\n***Try it***. *For practical reasons, we use a large number of previous observations as prior (`boostedBletchley.prior = observed`). You can try to change the code such that the strategy uses the trigram frequencies (`self.observed`) observed **during** the campaign itself to boost the campaign. You will need to increase `max_attempts` and wait for a long while.*", "_____no_output_____" ], [ "Let's compare the number of trigrams discovered over time.", "_____no_output_____" ] ], [ [ "# print plots\nline_old, = plt.plot(bletchley.timeseries, label=\"Bruteforce Strategy\")\nline_new, = plt.plot(boostedBletchley.timeseries, label=\"Boosted Strategy\")\nplt.legend(handles=[line_old, line_new])\nplt.xlabel('# of cracking attempts')\nplt.ylabel('# of trigrams discovered')\nplt.title('Trigram Discovery Over Time');", "_____no_output_____" ] ], [ [ "We see that the boosted fuzzer is constantly superior over the random fuzzer.", "_____no_output_____" ], [ "## Estimating the Probability of Path Discovery\n\n<!-- ## Residual Risk: Probability of Failure after an Unsuccessful Fuzzing Campaign -->\n<!-- Residual risk is not formally defined in this section, so I made the title a bit more generic -- AZ -->\n\nSo, what does Turing's observation for the Naval Enigma have to do with fuzzing _arbitrary_ programs? Turing's assistant I.J. Good extended and published Turing's work on the estimation procedures in Biometrica, a journal for theoretical biostatistics that still exists today. Good did not talk about trigrams. Instead, he calls them \"species\". Hence, the GT estimator is presented to estimate how likely it is to discover a new species, given an existing sample of individuals (each of which belongs to exactly one species). \n\nNow, we can associate program inputs to species, as well. For instance, we could define the path that is exercised by an input as that input's species. This would allow us to _estimate the probability that fuzzing discovers a new path._ Later, we will see how this discovery probability estimate also estimates the likelihood of discovering a vulnerability when we have not seen one, yet (residual risk).", "_____no_output_____" ], [ "Let's do this. We identify the species for an input by computing a hash-id over the set of statements exercised by that input. In the [Coverage](Coverage.ipynb) chapter, we have learned about the [Coverage class](Coverage.ipynb#A-Coverage-Class) which collects coverage information for an executed Python function. As an example, the function [`cgi_decode()`](Coverage.ipynb#A-CGI-Decoder) was introduced. The function `cgi_decode()` takes a string encoded for a website URL and decodes it back to its original form.\n\nHere's what `cgi_decode()` does and how coverage is computed.", "_____no_output_____" ] ], [ [ "from Coverage import Coverage, cgi_decode", "_____no_output_____" ], [ "encoded = \"Hello%2c+world%21\"\nwith Coverage() as cov:\n decoded = cgi_decode(encoded)", "_____no_output_____" ], [ "decoded", "_____no_output_____" ], [ "print(cov.coverage());", "_____no_output_____" ] ], [ [ "### Trace Coverage\nFirst, we will introduce the concept of execution traces, which are a coarse abstraction of the execution path taken by an input. Compared to the definition of path, a trace ignores the sequence in which statements are exercised or how often each statement is exercised.\n\n* `pickle.dumps()` - serializes an object by producing a byte array from all the information in the object\n* `hashlib.md5()` - produces a 128-bit hash value from a byte array", "_____no_output_____" ] ], [ [ "import pickle\nimport hashlib", "_____no_output_____" ], [ "def getTraceHash(cov):\n pickledCov = pickle.dumps(cov.coverage())\n hashedCov = hashlib.md5(pickledCov).hexdigest()\n return hashedCov", "_____no_output_____" ] ], [ [ "Remember our model for the Naval Enigma machine? Each message must be decrypted using exactly one trigram while multiple messages may be decrypted by the same trigram. Similarly, we need each input to yield exactly one trace hash while multiple inputs can yield the same trace hash.", "_____no_output_____" ], [ "Let's see whether this is true for our `getTraceHash()` function.", "_____no_output_____" ] ], [ [ "inp1 = \"a+b\"\ninp2 = \"a+b+c\"\ninp3 = \"abc\"\n\nwith Coverage() as cov1:\n cgi_decode(inp1)\nwith Coverage() as cov2:\n cgi_decode(inp2)\nwith Coverage() as cov3:\n cgi_decode(inp3)", "_____no_output_____" ] ], [ [ "The inputs `inp1` and `inp2` execute the same statements:", "_____no_output_____" ] ], [ [ "inp1, inp2", "_____no_output_____" ], [ "cov1.coverage() - cov2.coverage()", "_____no_output_____" ] ], [ [ "The difference between both coverage sets is empty. Hence, the trace hashes should be the same:", "_____no_output_____" ] ], [ [ "getTraceHash(cov1)", "_____no_output_____" ], [ "getTraceHash(cov2)", "_____no_output_____" ], [ "assert getTraceHash(cov1) == getTraceHash(cov2)", "_____no_output_____" ] ], [ [ "In contrast, the inputs `inp1` and `inp3` execute _different_ statements:", "_____no_output_____" ] ], [ [ "inp1, inp3", "_____no_output_____" ], [ "cov1.coverage() - cov3.coverage()", "_____no_output_____" ] ], [ [ "Hence, the trace hashes should be different, too:", "_____no_output_____" ] ], [ [ "getTraceHash(cov1)", "_____no_output_____" ], [ "getTraceHash(cov3)", "_____no_output_____" ], [ "assert getTraceHash(cov1) != getTraceHash(cov3)", "_____no_output_____" ] ], [ [ "### Measuring Trace Coverage over Time\nIn order to measure trace coverage for a `function` executing a `population` of fuzz inputs, we slightly adapt the `population_coverage()` function from the [Chapter on Coverage](Coverage.ipynb#Coverage-of-Basic-Fuzzing).", "_____no_output_____" ] ], [ [ "def population_trace_coverage(population, function):\n cumulative_coverage = []\n all_coverage = set()\n cumulative_singletons = []\n cumulative_doubletons = []\n singletons = set()\n doubletons = set()\n\n for s in population:\n with Coverage() as cov:\n try:\n function(s)\n except BaseException:\n pass\n cur_coverage = set([getTraceHash(cov)])\n\n # singletons and doubletons -- we will need them later\n doubletons -= cur_coverage\n doubletons |= singletons & cur_coverage\n singletons -= cur_coverage\n singletons |= cur_coverage - (cur_coverage & all_coverage)\n cumulative_singletons.append(len(singletons))\n cumulative_doubletons.append(len(doubletons))\n\n # all and cumulative coverage\n all_coverage |= cur_coverage\n cumulative_coverage.append(len(all_coverage))\n\n return all_coverage, cumulative_coverage, cumulative_singletons, cumulative_doubletons", "_____no_output_____" ] ], [ [ "Let's see whether our new function really contains coverage information only for *two* traces given our three inputs for `cgi_decode`.", "_____no_output_____" ] ], [ [ "all_coverage = population_trace_coverage([inp1, inp2, inp3], cgi_decode)[0]\nassert len(all_coverage) == 2", "_____no_output_____" ] ], [ [ "Unfortunately, the `cgi_decode()` function is too simple. Instead, we will use the original Python [HTMLParser](https://docs.python.org/3/library/html.parser.html) as our test subject.", "_____no_output_____" ] ], [ [ "from Fuzzer import RandomFuzzer\nfrom Coverage import population_coverage\nfrom html.parser import HTMLParser", "_____no_output_____" ], [ "trials = 50000 # number of random inputs generated", "_____no_output_____" ] ], [ [ "Let's run a random fuzzer for $n=50000$ times and plot trace coverage over time.", "_____no_output_____" ] ], [ [ "# create wrapper function\ndef my_parser(inp):\n parser = HTMLParser() # resets the HTMLParser object for every fuzz input\n parser.feed(inp)", "_____no_output_____" ], [ "# create random fuzzer\nfuzzer = RandomFuzzer(min_length=1, max_length=100,\n char_start=32, char_range=94)\n\n# create population of fuzz inputs\npopulation = []\nfor i in range(trials):\n population.append(fuzzer.fuzz())\n\n# execute and measure trace coverage\ntrace_timeseries = population_trace_coverage(population, my_parser)[1]\n\n# execute and measure code coverage\ncode_timeseries = population_coverage(population, my_parser)[1]\n\n# plot trace coverage over time\nplt.figure(num=None, figsize=(12, 4), dpi=80, facecolor='w', edgecolor='k')\nplt.subplot(1, 2, 1)\nplt.plot(trace_timeseries)\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of traces exercised')\nplt.title('Trace Coverage Over Time')\n\n# plot code coverage over time\nplt.subplot(1, 2, 2)\nplt.plot(code_timeseries)\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of statements covered')\nplt.title('Code Coverage Over Time');", "_____no_output_____" ] ], [ [ "Above, we can see trace coverage (left) and code coverage (right) over time. Here are our observations.\n1. **Trace coverage is more robust**. There are less sudden jumps in the graph compared to code coverage.\n2. **Trace coverage is more fine grained.** There more traces than statements covered at the end (y-axis)\n3. **Trace coverage grows more steadily**. Code coverage exercise more than half the statements with the first input that it exercises after 50k inputs. Instead, the number of traces covered grows slowly and steadily since each input can yield only one execution trace.\n\nIt is for this reason that one of the most prominent and successful fuzzers today, american fuzzy lop (AFL), uses a similar *measure of progress* (a hash computed over the branches exercised by the input).", "_____no_output_____" ], [ "### Evaluating the Discovery Probability Estimate\n\nLet's find out how the Good-Turing estimator performs as estimate of discovery probability when we are fuzzing to discover execution traces rather than trigrams. \n\nTo measure the empirical probability, we execute the same population of inputs (n=50000) and measure in regular intervals (measurement=100 intervals). During each measurement, we repeat the following experiment repeats=500 times, reporting the average: If the next input yields a new trace, return 1, otherwise return 0. Note that during these repetitions, we do not record the newly discovered traces as observed.", "_____no_output_____" ] ], [ [ "repeats = 500 # experiment repetitions\nmeasurements = 100 # experiment measurements", "_____no_output_____" ], [ "emp_timeseries = []\nall_coverage = set()\nstep = int(trials / measurements)\n\nfor i in range(0, trials, step):\n if i - step >= 0:\n for j in range(step):\n inp = population[i - j]\n with Coverage() as cov:\n try:\n my_parser(inp)\n except BaseException:\n pass\n all_coverage |= set([getTraceHash(cov)])\n\n discoveries = 0\n for _ in range(repeats):\n inp = fuzzer.fuzz()\n with Coverage() as cov:\n try:\n my_parser(inp)\n except BaseException:\n pass\n if getTraceHash(cov) not in all_coverage:\n discoveries += 1\n emp_timeseries.append(discoveries / repeats)", "_____no_output_____" ] ], [ [ "Now, we compute the Good-Turing estimate over time.", "_____no_output_____" ] ], [ [ "gt_timeseries = []\nsingleton_timeseries = population_trace_coverage(population, my_parser)[2]\nfor i in range(1, trials + 1, step):\n gt_timeseries.append(singleton_timeseries[i - 1] / i)", "_____no_output_____" ] ], [ [ "Let's go ahead and plot both time series.", "_____no_output_____" ] ], [ [ "line_emp, = plt.semilogy(emp_timeseries, label=\"Empirical\")\nline_gt, = plt.semilogy(gt_timeseries, label=\"Good-Turing\")\nplt.legend(handles=[line_emp, line_gt])\nplt.xticks(range(0, measurements + 1, int(measurements / 5)),\n range(0, trials + 1, int(trials / 5)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('discovery probability')\nplt.title('Discovery Probability Over Time');", "_____no_output_____" ] ], [ [ "Again, the Good-Turing estimate appears to be *highly accurate*. In fact, the empirical estimator has a much lower precision as indicated by the large swings. You can try and increase the number of repetitions (repeats) to get more precision for the empirical estimates, however, at the cost of waiting much longer.", "_____no_output_____" ], [ "### Discovery Probability Quantifies Residual Risk\n\nAlright. You have gotten a hold of a couple of powerful machines and used them to fuzz a software system for several months without finding any vulnerabilities. Is the system vulnerable?\n\nWell, who knows? We cannot say for sure; there is always some residual risk. Testing is not verification. Maybe the next test input that is generated reveals a vulnerability.\n\nLet's say *residual risk* is the probability that the next test input reveals a vulnerability that has not been found, yet. Böhme \\cite{stads} has shown that the Good-Turing estimate of the discovery probability is also an estimate of the maxmimum residual risk.\n\n**Proof sketch (Residual Risk)**. Here is a proof sketch that shows that an estimator of discovery probability for an arbitrary definition of species gives an upper bound on the probability to discover a vulnerability when none has been found: Suppose, for each \"old\" species A (here, execution trace), we derive two \"new\" species: Some inputs belonging to A expose a vulnerability while others belonging to A do not. We know that _only_ species that do not expose a vulnerability have been discovered. Hence, _all_ species exposing a vulnerability and _some_ species that do not expose a vulnerability remain undiscovered. Hence, the probability to discover a new species gives an upper bound on the probability to discover (a species that exposes) a vulnerability. **QED**.\n\nAn estimate of the discovery probability is useful in many other ways.\n\n1. **Discovery probability**. We can estimate, at any point during the fuzzing campaign, the probability that the next input belongs to a previously unseen species (here, that it yields a new execution trace, i.e., exercises a new set of statements).\n2. **Complement of discovery probability**. We can estimate the proportion of *all* inputs the fuzzer can generate for which we have already seen the species (here, execution traces). In some sense, this allows us to quantify the *progress of the fuzzing campaign towards completion*: If the probability to discovery a new species is too low, we might as well abort the campaign.\n3. **Inverse of discovery probability**. We can predict the number of test inputs needed, so that we can expect the discovery of a new species (here, execution trace).", "_____no_output_____" ], [ "## How Do We Know When to Stop Fuzzing?\n\nIn fuzzing, we have measures of progress such as [code coverage](Coverage.ipynb) or [grammar coverage](GrammarCoverageFuzzer.ipynb). Suppose, we are interested in covering all statements in the program. The _percentage_ of statements that have already been covered quantifies how \"far\" we are from completing the fuzzing campaign. However, sometimes we know only the _number_ of species $S(n)$ (here, statements) that have been discovered after generating $n$ fuzz inputs. The percentage $S(n)/S$ can only be computed if we know the _total number_ of species $S$. Even then, not all species may be feasible.", "_____no_output_____" ], [ "### A Success Estimator\n\nIf we do not _know_ the total number of species, then let's at least _estimate_ it: As we have seen before, species discovery slows down over time. In the beginning, many new species are discovered. Later, many inputs need to be generated before discovering the next species. In fact, given enough time, the fuzzing campaign approaches an _asymptote_. It is this asymptote that we can estimate.", "_____no_output_____" ], [ "In 1984, Anne Chao, a well-known theoretical bio-statistician, has developed an estimator $\\hat S$ which estimates the asymptotic total number of species $S$:\n\\begin{align}\n\\hat S_\\text{Chao1} = \\begin{cases}\nS(n) + \\frac{f_1^2}{2f_2} & \\text{if $f_2>0$}\\\\\nS(n) + \\frac{f_1(f_1-1)}{2} & \\text{otherwise}\n\\end{cases}\n\\end{align}\n* where $f_1$ and $f_2$ is the number of singleton and doubleton species, respectively (that have been observed exactly once or twice, resp.), and \n* where $S(n)$ is the number of species that have been discovered after generating $n$ fuzz inputs.", "_____no_output_____" ], [ "So, how does Chao's estimate perform? To investigate this, we generate trials=400000 fuzz inputs using a fuzzer setting that allows us to see an asymptote in a few seconds. We measure trace coverage coverage. After half-way into our fuzzing campaign (trials/2=100000), we generate Chao's estimate $\\hat S$ of the asymptotic total number of species. Then, we run the remainer of the campaign to see the \"empirical\" asymptote.", "_____no_output_____" ] ], [ [ "trials = 400000\nfuzzer = RandomFuzzer(min_length=2, max_length=4,\n char_start=32, char_range=32)\npopulation = []\nfor i in range(trials):\n population.append(fuzzer.fuzz())\n\n_, trace_ts, f1_ts, f2_ts = population_trace_coverage(population, my_parser)", "_____no_output_____" ], [ "time = int(trials / 2)\ntime", "_____no_output_____" ], [ "f1 = f1_ts[time]\nf2 = f2_ts[time]\nSn = trace_ts[time]\nif f2 > 0:\n hat_S = Sn + f1 * f1 / (2 * f2)\nelse:\n hat_S = Sn + f1 * (f1 - 1) / 2", "_____no_output_____" ] ], [ [ "After executing `time` fuzz inputs (half of all), we have covered these many traces:", "_____no_output_____" ] ], [ [ "time", "_____no_output_____" ], [ "Sn", "_____no_output_____" ] ], [ [ "We can estimate there are this many traces in total:", "_____no_output_____" ] ], [ [ "hat_S", "_____no_output_____" ] ], [ [ "Hence, we have achieved this percentage of the estimate:", "_____no_output_____" ] ], [ [ "100 * Sn / hat_S", "_____no_output_____" ] ], [ [ "After executing `trials` fuzz inputs, we have covered these many traces:", "_____no_output_____" ] ], [ [ "trials", "_____no_output_____" ], [ "trace_ts[trials - 1]", "_____no_output_____" ] ], [ [ "The accuracy of Chao's estimator is quite reasonable. It isn't always accurate -- particularly at the beginning of a fuzzing campaign when the [discovery probability](WhenIsEnough.ipynb#Measuring-Trace-Coverage-over-Time) is still very high. Nevertheless, it demonstrates the main benefit of reporting a percentage to assess the progress of a fuzzing campaign towards completion.\n\n***Try it***. *Try setting and `trials` to 1 million and `time` to `int(trials / 4)`.*", "_____no_output_____" ], [ "### Extrapolating Fuzzing Success\n<!-- ## Cost-Benefit Analysis: Extrapolating the Number of Species Discovered -->\n\nSuppose you have run the fuzzer for a week, which generated $n$ fuzz inputs and discovered $S(n)$ species (here, covered $S(n)$ execution traces). Instead, of running the fuzzer for another week, you would like to *predict* how many more species you would discover. In 2003, Anne Chao and her team developed an extrapolation methodology to do just that. We are interested in the number $S(n+m^*)$ of species discovered if $m^*$ more fuzz inputs were generated:\n\n\\begin{align}\n\\hat S(n + m^*) = S(n) + \\hat f_0 \\left[1-\\left(1-\\frac{f_1}{n\\hat f_0 + f_1}\\right)^{m^*}\\right]\n\\end{align}\n* where $\\hat f_0=\\hat S - S(n)$ is an estimate of the number $f_0$ of undiscovered species, and \n* where $f_1$ the number of singleton species, i.e., those we have observed exactly once. \n\nThe number $f_1$ of singletons, we can just keep track of during the fuzzing campaign itself. The estimate of the number $\\hat f_0$ of undiscovered species, we can simply derive using Chao's estimate $\\hat S$ and the number of observed species $S(n)$.\n\nLet's see how Chao's extrapolator performs by comparing the predicted number of species to the empirical number of species.", "_____no_output_____" ] ], [ [ "prediction_ts = [None] * time\nf0 = hat_S - Sn\n\nfor m in range(trials - time):\n assert (time * f0 + f1) != 0 , 'time:%s f0:%s f1:%s' % (time, f0,f1)\n prediction_ts.append(Sn + f0 * (1 - (1 - f1 / (time * f0 + f1)) ** m))", "_____no_output_____" ], [ "plt.figure(num=None, figsize=(12, 3), dpi=80, facecolor='w', edgecolor='k')\nplt.subplot(1, 3, 1)\nplt.plot(trace_ts, color='white')\nplt.plot(trace_ts[:time])\nplt.xticks(range(0, trials + 1, int(time)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of traces exercised')\n\nplt.subplot(1, 3, 2)\nline_cur, = plt.plot(trace_ts[:time], label=\"Ongoing fuzzing campaign\")\nline_pred, = plt.plot(prediction_ts, linestyle='--',\n color='black', label=\"Predicted progress\")\nplt.legend(handles=[line_cur, line_pred])\nplt.xticks(range(0, trials + 1, int(time)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of traces exercised')\n\nplt.subplot(1, 3, 3)\nline_emp, = plt.plot(trace_ts, color='grey', label=\"Actual progress\")\nline_cur, = plt.plot(trace_ts[:time], label=\"Ongoing fuzzing campaign\")\nline_pred, = plt.plot(prediction_ts, linestyle='--',\n color='black', label=\"Predicted progress\")\nplt.legend(handles=[line_emp, line_cur, line_pred])\nplt.xticks(range(0, trials + 1, int(time)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of traces exercised');", "_____no_output_____" ] ], [ [ "The prediction from Chao's extrapolator looks quite accurate. We make a prediction at $time=trials/4$. Despite an extrapolation by 3 times (i.e., at trials), we can see that the predicted value (black, dashed line) closely matches the empirical value (grey, solid line).\n\n***Try it***. Again, try setting and `trials` to 1 million and `time` to `int(trials / 4)`.", "_____no_output_____" ], [ "## Lessons Learned\n\n* One can measure the _progress_ of a fuzzing campaign (as species over time, i.e., $S(n)$).\n* One can measure the _effectiveness_ of a fuzzing campaign (as asymptotic total number of species $S$).\n* One can estimate the _effectiveness_ of a fuzzing campaign using the Chao1-estimator $\\hat S$.\n* One can extrapolate the _progress_ of a fuzzing campaign, $\\hat S(n+m^*)$.\n* One can estimate the _residual risk_ (i.e., the probability that a bug exists that has not been found) using the Good-Turing estimator $GT$ of the species discovery probability.", "_____no_output_____" ], [ "## Next Steps\n\nThis chapter is the last in the book! If you want to continue reading, have a look at the [Appendices](99_Appendices.ipynb). Otherwise, _make use of what you have learned and go and create great fuzzers and test generators!_", "_____no_output_____" ], [ "## Background\n\n* A **statistical framework for fuzzing**, inspired from ecology. Marcel Böhme. [STADS: Software Testing as Species Discovery](https://mboehme.github.io/paper/TOSEM18.pdf). ACM TOSEM 27(2):1--52\n* Estimating the **discovery probability**: I.J. Good. 1953. [The population frequencies of species and the\nestimation of population parameters](https://www.jstor.org/stable/2333344). Biometrika 40:237–264.\n* Estimating the **asymptotic total number of species** when each input can belong to exactly one species: Anne Chao. 1984. [Nonparametric estimation of the number of classes in a population](https://www.jstor.org/stable/4615964). Scandinavian Journal of Statistics 11:265–270\n* Estimating the **asymptotic total number of species** when each input can belong to one or more species: Anne Chao. 1987. [Estimating the population size for capture-recapture data with unequal catchability](https://www.jstor.org/stable/2531532). Biometrics 43:783–791\n* **Extrapolating** the number of discovered species: Tsung-Jen Shen, Anne Chao, and Chih-Feng Lin. 2003. [Predicting the Number of New Species in Further Taxonomic Sampling](http://chao.stat.nthu.edu.tw/wordpress/paper/2003_Ecology_84_P798.pdf). Ecology 84, 3 (2003), 798–804.", "_____no_output_____" ], [ "## Exercises\nI.J. Good and Alan Turing developed an estimator for the case where each input belongs to exactly one species. For instance, each input yields exactly one execution trace (see function [`getTraceHash`](#Trace-Coverage)). However, this is not true in general. For instance, each input exercises multiple statements and branches in the source code. Generally, each input can belong to one *or more* species. \n\nIn this extended model, the underlying statistics are quite different. Yet, all estimators that we have discussed in this chapter turn out to be almost identical to those for the simple, single-species model. For instance, the Good-Turing estimator $C$ is defined as \n$$C=\\frac{Q_1}{n}$$ \nwhere $Q_1$ is the number of singleton species and $n$ is the number of generated test cases.\nThroughout the fuzzing campaign, we record for each species the *incidence frequency*, i.e., the number of inputs that belong to that species. Again, we define a species $i$ as *singleton species* if we have seen exactly one input that belongs to species $i$.", "_____no_output_____" ], [ "### Exercise 1: Estimate and Evaluate the Discovery Probability for Statement Coverage\n\nIn this exercise, we create a Good-Turing estimator for the simple fuzzer.", "_____no_output_____" ], [ "#### Part 1: Population Coverage\n\nImplement a function `population_stmt_coverage()` as in [the section on estimating discovery probability](#Estimating-the-Discovery-Probability) that monitors the number of singletons and doubletons over time, i.e., as the number $i$ of test inputs increases.", "_____no_output_____" ] ], [ [ "from Coverage import population_coverage, Coverage\n...", "_____no_output_____" ] ], [ [ "**Solution.** Here we go:", "_____no_output_____" ] ], [ [ "def population_stmt_coverage(population, function):\n cumulative_coverage = []\n all_coverage = set()\n cumulative_singletons = []\n cumulative_doubletons = []\n singletons = set()\n doubletons = set()\n\n for s in population:\n with Coverage() as cov:\n try:\n function(s)\n except BaseException:\n pass\n cur_coverage = cov.coverage()\n\n # singletons and doubletons\n doubletons -= cur_coverage\n doubletons |= singletons & cur_coverage\n singletons -= cur_coverage\n singletons |= cur_coverage - (cur_coverage & all_coverage)\n cumulative_singletons.append(len(singletons))\n cumulative_doubletons.append(len(doubletons))\n\n # all and cumulative coverage\n all_coverage |= cur_coverage\n cumulative_coverage.append(len(all_coverage))\n\n return all_coverage, cumulative_coverage, cumulative_singletons, cumulative_doubletons", "_____no_output_____" ] ], [ [ "#### Part 2: Population\n\nUse the random `fuzzer(min_length=1, max_length=1000, char_start=0, char_range=255)` from [the chapter on Fuzzers](Fuzzer.ipynb) to generate a population of $n=10000$ fuzz inputs.", "_____no_output_____" ] ], [ [ "from Fuzzer import RandomFuzzer\nfrom html.parser import HTMLParser\n...", "_____no_output_____" ] ], [ [ "**Solution.** This is fairly straightforward:", "_____no_output_____" ] ], [ [ "trials = 2000 # increase to 10000 for better convergences. Will take a while..", "_____no_output_____" ] ], [ [ "We create a wrapper function...", "_____no_output_____" ] ], [ [ "def my_parser(inp):\n parser = HTMLParser() # resets the HTMLParser object for every fuzz input\n parser.feed(inp)", "_____no_output_____" ] ], [ [ "... and a random fuzzer:", "_____no_output_____" ] ], [ [ "fuzzer = RandomFuzzer(min_length=1, max_length=1000,\n char_start=0, char_range=255)", "_____no_output_____" ] ], [ [ "We fill the population:", "_____no_output_____" ] ], [ [ "population = []\nfor i in range(trials):\n population.append(fuzzer.fuzz())", "_____no_output_____" ] ], [ [ "#### Part 3: Estimating Probabilities\n\nExecute the generated inputs on the Python HTML parser (`from html.parser import HTMLParser`) and estimate the probability that the next input covers a previously uncovered statement (i.e., the discovery probability) using the Good-Turing estimator.", "_____no_output_____" ], [ "**Solution.** Here we go:", "_____no_output_____" ] ], [ [ "measurements = 100 # experiment measurements\nstep = int(trials / measurements)\n\ngt_timeseries = []\nsingleton_timeseries = population_stmt_coverage(population, my_parser)[2]\nfor i in range(1, trials + 1, step):\n gt_timeseries.append(singleton_timeseries[i - 1] / i)", "_____no_output_____" ] ], [ [ "#### Part 4: Empirical Evaluation\n\nEmpirically evaluate the accuracy of the Good-Turing estimator (using $10000$ repetitions) of the probability to cover new statements using the experimental procedure at the end of [the section on estimating discovery probability](#Estimating-the-Discovery-Probability).", "_____no_output_____" ], [ "**Solution.** This is as above:", "_____no_output_____" ] ], [ [ "# increase to 10000 for better precision (less variance). Will take a while..\nrepeats = 100", "_____no_output_____" ], [ "emp_timeseries = []\nall_coverage = set()\nfor i in range(0, trials, step):\n if i - step >= 0:\n for j in range(step):\n inp = population[i - j]\n with Coverage() as cov:\n try:\n my_parser(inp)\n except BaseException:\n pass\n all_coverage |= cov.coverage()\n\n discoveries = 0\n for _ in range(repeats):\n inp = fuzzer.fuzz()\n with Coverage() as cov:\n try:\n my_parser(inp)\n except BaseException:\n pass\n # If intersection not empty, a new stmt was (dis)covered\n if cov.coverage() - all_coverage:\n discoveries += 1\n emp_timeseries.append(discoveries / repeats)", "_____no_output_____" ], [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nline_emp, = plt.semilogy(emp_timeseries, label=\"Empirical\")\nline_gt, = plt.semilogy(gt_timeseries, label=\"Good-Turing\")\nplt.legend(handles=[line_emp, line_gt])\nplt.xticks(range(0, measurements + 1, int(measurements / 5)),\n range(0, trials + 1, int(trials / 5)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('discovery probability')\nplt.title('Discovery Probability Over Time');", "_____no_output_____" ] ], [ [ "### Exercise 2: Extrapolate and Evaluate Statement Coverage\n\nIn this exercise, we use Chao's extrapolation method to estimate the success of fuzzing.", "_____no_output_____" ], [ "#### Part 1: Create Population\n\nUse the random `fuzzer(min_length=1, max_length=1000, char_start=0, char_range=255)` to generate a population of $n=400000$ fuzz inputs.", "_____no_output_____" ], [ "**Solution.** Here we go:", "_____no_output_____" ] ], [ [ "trials = 400 # Use 400000 for actual solution. This takes a while!", "_____no_output_____" ], [ "population = []\nfor i in range(trials):\n population.append(fuzzer.fuzz())\n\n_, stmt_ts, Q1_ts, Q2_ts = population_stmt_coverage(population, my_parser)", "_____no_output_____" ] ], [ [ "#### Part 2: Compute Estimate\n\nCompute an estimate of the total number of statements $\\hat S$ after $n/4=100000$ fuzz inputs were generated. In the extended model, $\\hat S$ is computed as\n\\begin{align}\n\\hat S_\\text{Chao1} = \\begin{cases}\nS(n) + \\frac{Q_1^2}{2Q_2} & \\text{if $Q_2>0$}\\\\\nS(n) + \\frac{Q_1(Q_1-1)}{2} & \\text{otherwise}\n\\end{cases}\n\\end{align}\n * where $Q_1$ and $Q_2$ is the number of singleton and doubleton statements, respectively (i.e., statements that have been exercised by exactly one or two fuzz inputs, resp.), and \n * where $S(n)$ is the number of statements that have been (dis)covered after generating $n$ fuzz inputs.", "_____no_output_____" ], [ "**Solution.** Here we go:", "_____no_output_____" ] ], [ [ "time = int(trials / 4)\nQ1 = Q1_ts[time]\nQ2 = Q2_ts[time]\nSn = stmt_ts[time]\n\nif Q2 > 0:\n hat_S = Sn + Q1 * Q1 / (2 * Q2)\nelse:\n hat_S = Sn + Q1 * (Q1 - 1) / 2\n\nprint(\"After executing %d fuzz inputs, we have covered %d **(%.1f %%)** statements.\\n\" % (time, Sn, 100 * Sn / hat_S) +\n \"After executing %d fuzz inputs, we estimate there are %d statements in total.\\n\" % (time, hat_S) +\n \"After executing %d fuzz inputs, we have covered %d statements.\" % (trials, stmt_ts[trials - 1]))", "_____no_output_____" ] ], [ [ "#### Part 3: Compute and Evaluate Extrapolator\n\nCompute and evaluate Chao's extrapolator by comparing the predicted number of statements to the empirical number of statements.", "_____no_output_____" ], [ "**Solution.** Here's our solution:", "_____no_output_____" ] ], [ [ "prediction_ts = [None] * time\nQ0 = hat_S - Sn\n\nfor m in range(trials - time):\n prediction_ts.append(Sn + Q0 * (1 - (1 - Q1 / (time * Q0 + Q1)) ** m))", "_____no_output_____" ], [ "plt.figure(num=None, figsize=(12, 3), dpi=80, facecolor='w', edgecolor='k')\nplt.subplot(1, 3, 1)\nplt.plot(stmt_ts, color='white')\nplt.plot(stmt_ts[:time])\nplt.xticks(range(0, trials + 1, int(time)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of statements exercised')\n\nplt.subplot(1, 3, 2)\nline_cur, = plt.plot(stmt_ts[:time], label=\"Ongoing fuzzing campaign\")\nline_pred, = plt.plot(prediction_ts, linestyle='--',\n color='black', label=\"Predicted progress\")\nplt.legend(handles=[line_cur, line_pred])\nplt.xticks(range(0, trials + 1, int(time)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of statements exercised')\n\nplt.subplot(1, 3, 3)\nline_emp, = plt.plot(stmt_ts, color='grey', label=\"Actual progress\")\nline_cur, = plt.plot(stmt_ts[:time], label=\"Ongoing fuzzing campaign\")\nline_pred, = plt.plot(prediction_ts, linestyle='--',\n color='black', label=\"Predicted progress\")\nplt.legend(handles=[line_emp, line_cur, line_pred])\nplt.xticks(range(0, trials + 1, int(time)))\nplt.xlabel('# of fuzz inputs')\nplt.ylabel('# of statements exercised');", "_____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", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
cb0bbc2301997ea08eedbd9776d11966d24d271a
603,744
ipynb
Jupyter Notebook
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
144d2488bd00122f43b5d4471fbb3b071ab85434
[ "MIT" ]
null
null
null
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
144d2488bd00122f43b5d4471fbb3b071ab85434
[ "MIT" ]
null
null
null
practicals/UKESM1_in_Python/surface_maps.ipynb
ZhiyiJiang/geog0121
144d2488bd00122f43b5d4471fbb3b071ab85434
[ "MIT" ]
null
null
null
1,053.65445
150,008
0.956558
[ [ [ "# Introduction to 2D plots\n\nThis notebook demonstrates how plot some latitude by longitude maps of some key surface variables. Most features are available in the preinstalled `geog0111` environment. \n\nBut updated plotting that removes white meridional lines around the Greenwich Meridian, requires the `geog0121` virtual environment. Instructions about how to install this environment (using `conda` and the `environment.yml` file) are provided in the handbook.", "_____no_output_____" ], [ "### Import packages and define fucntions for calculations", "_____no_output_____" ] ], [ [ "'''Import packages for loading data, analysing, and plotting'''\n\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n%matplotlib inline\nimport cartopy\nimport cartopy.crs as ccrs\nimport matplotlib\nfrom netCDF4 import Dataset\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport numpy.ma as ma\n\n\nimport os\nimport matplotlib.colors as colors\n\nimport scipy\nfrom cartopy.util import add_cyclic_point\nimport matplotlib.ticker as mticker\nfrom cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\n", "_____no_output_____" ] ], [ [ "# Change in annual temperature under the SSP585 scenario\nHere we use the CVDP output files to look at the change in annual mean surface temperature", "_____no_output_____" ] ], [ [ "#define filenames and their directories\nend_period='2071-2100'\nstart_period='1851-1900'\nssp='ssp585'\n\ndirectory_a='/data/aod/cvdp_cmip6/geog0121/UKESM1-0-LL_ssps.wrt_%s' %end_period\nfilename_a='%s/UKESM1_%s_%s.cvdp_data.1850-2100.nc'%(directory_a,ssp,end_period)\ndirectory_b='/data/aod/cvdp_cmip6/geog0121/UKESM1-0-LL_ssps.wrt_%s' %start_period\nfilename_b='%s/UKESM1_%s_%s.cvdp_data.1850-2100.nc'%(directory_b,ssp,start_period)\n\n\n# load files\nexpt_a_file=xr.open_dataset(filename_a,decode_times=False)\nexpt_b_file=xr.open_dataset(filename_b,decode_times=False)\n# load the coordinates\nlat=expt_a_file['lat']\nlon=expt_a_file['lon']\n# load the variables themselves\nvariable_name='tas_spatialmean_ann'\nexpt_a=expt_a_file[variable_name]\nexpt_b=expt_b_file[variable_name]\n\n# create the difference\ndiff=expt_a-expt_b\ndiff", "_____no_output_____" ] ], [ [ "### Using xarray's simplest plotting routine", "_____no_output_____" ] ], [ [ "diff.plot()", "_____no_output_____" ] ], [ [ "Whilst this plot clearly show what is going on. It is missing several useful features:\n* A sensible colormap\n* The coastline (or country borders) to help orientate you\n* A logical scale for the colors to use\n\nWhatever you decide to plot, it is always worth selecting a relevant colormap. All of the easily available colormaps can be seen at [Matplotlib's reference pages](https://matplotlib.org/3.1.1/gallery/color/colormap_reference.html). For this instance, I am picking a sequential one that goes from yellow-orange-red (YlOrRd), with the keyword `cmap=` in the plot call.\n\nHere I am going to plot every 2 degrees above preindustrial, using both the `levels` keyword and a call to `np.linspace()`, which subdivides the range from 0-20 (inclusive) into 11 different levels. \n\nAdding the map is a little trickier. We shall use the Robinson projection, but we need to specify that first along with a load of other map-related options to creates some axes. We then also need to pass these to the plotting routine, as well as telling it us the Plate Carree method to map the locations onto the Robinson projection. \n\nA final thing to note is that we've switched to using `contourf` instead of the default option (actually `pcolormesh`). This is needed for the maps, and will otherwise throw up errors like \n> 'GeoAxesSubplot' object has no attribute '_hold'\n", "_____no_output_____" ] ], [ [ "# Define the map projection through an \"axes\" call\nplt.figure(figsize=(10,7)) #make the map itself nice and big\nprojection = ccrs.Robinson() #specify the Robinson projection\nax = plt.axes(projection=projection) #create the axes\nax.coastlines() # add the coastlines\nax.gridlines() # add some gray gridlines \nax.add_feature(cartopy.feature.BORDERS) #add the country borders\n\n# Now overplot the map onto these axes. \nfig=diff.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), \\\n cmap='YlOrRd', \\\n levels=np.linspace(0,20,11))\n\n# [note that its given a name of `fig` through the =, so that it can saved later]\n\n", "_____no_output_____" ] ], [ [ "# UKESM's El Nino temperature pattern\nHere we use the CVDP output files to plot the temperature response to an El Nino. First we will load in the data", "_____no_output_____" ] ], [ [ "#generate filename\ndirectory='/data/aod/cvdp_cmip6/geog0121/UKESM1-0-LL_historical.vsObs' \nfilename='%s/UKESM1-0-LL_PresentDay.cvdp_data.1850-2014.nc'%(directory)\n# load files\nexpt_file=xr.open_dataset(filename,decode_times=False)\n# load the coordinates\nlat=expt_file['lat']\nlon=expt_file['lon']\n# load the variables themselves\nenso_pattern=expt_file.nino34_spacomp_tas_djf1", "_____no_output_____" ] ], [ [ "Then we will specify the colorscale and map", "_____no_output_____" ] ], [ [ "#temperatures\ncmap=plt.get_cmap('bwr') #define colormap\n\n#define colormap's range and scale\ncmap_limits=[-5,5]\nbounds = np.linspace(cmap_limits[0], cmap_limits[1], 21)\nnorm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)", "_____no_output_____" ] ], [ [ "Now we will make a global plot of the El Nino pattern", "_____no_output_____" ] ], [ [ "# Choose the map and projection\nprojection = ccrs.Robinson()\ntransform=ccrs.PlateCarree()\n\n# Plot the axes\nplt.figure(figsize=(10,7))\nax = plt.axes(projection=projection)\nax.coastlines()\nax.gridlines()\n\n# Make the actual figure\nfig=ax.contourf(lon,lat,enso_pattern,levels=bounds, transform=transform,cmap=cmap,norm=norm)\n\n# Alter the color bar for the map\ncax,kw = matplotlib.colorbar.make_axes(ax,location='bottom',pad=0.05,shrink=0.7)\nplt.colorbar(fig,cax=cax,extend='both',**kw)\n", "_____no_output_____" ] ], [ [ "And then lets zoom into a smaller region of it", "_____no_output_____" ] ], [ [ "#Regional map\nregion=[100,280,-30,30] #[lon_min,lon_max,lat_min,lat_max]\n\n# note the specification of the central longitude, so that is spans the dateline\nprojection = ccrs.PlateCarree(central_longitude=180., globe=None)\ntransform=ccrs.PlateCarree()\n\nplt.figure(figsize=(10,7))\nax = plt.axes(projection=projection)\n\nax.coastlines()\ngl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,alpha=0.5, linestyle='--')\ngl.xlabels_top = False\ngl.xlabels_bottom = False\ngl.ylabels_left = False\ngl.xformatter = LONGITUDE_FORMATTER\n\nfig=ax.contourf(lon,lat,enso_pattern,levels=bounds, transform=transform,cmap=cmap,norm=norm)\nax.set_extent(region, ccrs.PlateCarree())\n\ncax,kw = matplotlib.colorbar.make_axes(ax,location='bottom',pad=0.05,shrink=0.7)\nplt.colorbar(fig,cax=cax,extend='both',**kw)\n\n#plt.savefig(figname)", "_____no_output_____" ] ], [ [ "# Seasonal precipitation anomalies\n\nThe CVDP files can be used to create maps of the changes in seasonal precipitation. First we select the variable", "_____no_output_____" ] ], [ [ "#seasonal precipitation anomalies\nvariable_name='pr_spatialmean_djf'\nexpt_a=expt_a_file[variable_name]\nexpt_b=expt_b_file[variable_name]\ndiff=expt_a-expt_b", "_____no_output_____" ] ], [ [ "Then we define the colormap, and give it a non-linear interval", "_____no_output_____" ] ], [ [ "#precipitations\ncmap=plt.get_cmap('BrBG') #define colormap\n\n#define colormap's range and scale\nbounds = [-5,-2,-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1,2,5]\nnorm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)", "_____no_output_____" ] ], [ [ "Then we can create a global map with...", "_____no_output_____" ] ], [ [ "#Global map\n\nprojection = ccrs.Robinson()\ntransform=ccrs.PlateCarree()\n\nplt.figure(figsize=(10,7))\nax = plt.axes(projection=projection)\nax.coastlines()\nax.gridlines()\n\nfig=ax.contourf(lon,lat,diff,levels=bounds, transform=transform,cmap=cmap,norm=norm)\ncax,kw = matplotlib.colorbar.make_axes(ax,location='bottom',pad=0.05,shrink=0.7)\nplt.colorbar(fig,cax=cax,extend='both',**kw)", "_____no_output_____" ] ], [ [ "Or a regional map with...", "_____no_output_____" ] ], [ [ "#Regional map\nregion=[-20,70,20,90] #[lon_min,lon_max,lat_min,lat_max]\n\nprojection = ccrs.PlateCarree(central_longitude=0.0, globe=None)\ntransform=ccrs.PlateCarree()\n\nplt.figure(figsize=(10,7))\nax = plt.axes(projection=projection)\n\nax.coastlines()\ngl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,alpha=0.5, linestyle='--')\ngl.xlabels_top = False\ngl.ylabels_left = False\n#gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])\ngl.xformatter = LONGITUDE_FORMATTER\ngl.yformatter = LATITUDE_FORMATTER\n\n\nfig=ax.contourf(lon,lat,diff,levels=bounds, transform=transform,cmap=cmap,norm=norm)\nax.set_extent(region, ccrs.PlateCarree())\n\ncax,kw = matplotlib.colorbar.make_axes(ax,location='bottom',pad=0.05,shrink=0.7)\nplt.colorbar(fig,cax=cax,extend='both',**kw)\n\n", "_____no_output_____" ] ], [ [ "If your regional plot (like this one) happens to cross the Greenwich meridian, then you will end up with a white line going straight up the middle of your regional plot. This can be fixed by adding a \"cyclic point\" to loop the data around the globe. To understand this, think about how you need to overlap the wrapping paper on a present to cover it completely. \n\nThere is a function in python to do this, but unfortunately it doesn't come in the standard version of python. This function is in the cell below.\n\nYou will need to make your own virtual environment called `geog0121` using conda and the yml file provided. If you have not down this, then when you run the code below it will fail with the following error message... \n> TypeError: invalid indexer array", "_____no_output_____" ] ], [ [ "diff, lon = add_cyclic_point(diff, coord=lon)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb0bbdb74fa96c3b9b2078305c09d3d062976f67
36,933
ipynb
Jupyter Notebook
Analysis/0.3_SQLgetData.ipynb
dreandes/LinearRegression_PROJECT
2fe2aa95737c76029c9276ee60c5fc6409d1cf4a
[ "MIT" ]
null
null
null
Analysis/0.3_SQLgetData.ipynb
dreandes/LinearRegression_PROJECT
2fe2aa95737c76029c9276ee60c5fc6409d1cf4a
[ "MIT" ]
null
null
null
Analysis/0.3_SQLgetData.ipynb
dreandes/LinearRegression_PROJECT
2fe2aa95737c76029c9276ee60c5fc6409d1cf4a
[ "MIT" ]
null
null
null
36.567327
1,379
0.326077
[ [ [ "from sqlalchemy import create_engine\nimport pymysql\n\ndb_connection_str = 'mysql+pymysql://root:[email protected]/Linear_Regression'\ndb_connection = create_engine(db_connection_str)", "_____no_output_____" ], [ "df = pd.read_sql('SELECT * FROM api_football', con=db_connection)\ndf", "_____no_output_____" ], [ "df_test = df", "_____no_output_____" ], [ "import unidecode\naname = df_test.player_name[18]\naname", "_____no_output_____" ], [ "uaname = unidecode.unidecode(aname)\nuaname", "_____no_output_____" ], [ "import re\noname = 'Cristiano Ronaldo'\na = re.findall(\"[a-zA-Z]+\", oname)\na[0][0] + '. ' + a[1]", "_____no_output_____" ], [ "def convert(string):\n return list(string.split(\" \"))", "_____no_output_____" ], [ "div_str = convert(oname)", "_____no_output_____" ], [ "len(div_str)", "_____no_output_____" ], [ "def convert(n):\n div_str = list(n.split(\" \"))\n\n if len(div_str) == 1:\n return n\n else:\n regex_name_list = re.findall(\"[a-zA-Z]+\", n)\n return regex_name_list[0][0] + '. ' + regex_name_list[len(div_str) - 1]\n\nn = 'David de Gea'\nconvert(n)", "_____no_output_____" ], [ "testdf = pd.read_csv('apidata_1_10000.csv', encoding='utf-8-sig')\ntestdf", "_____no_output_____" ], [ "n = 0\nfor a in testdf.player_name:\n testdf.player_name[n] = convert(a)\n n += 1", "C:\\Users\\Gk\\anaconda3\\lib\\site-packages\\ipykernel_launcher.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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n This is separate from the ipykernel package so we can avoid doing imports until\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0bc3d2b4bcea66e806e37f652253b69f8f9a16
6,150
ipynb
Jupyter Notebook
Dag11.ipynb
isepri/Adventofcode2020
499bccfb2df08a34c53d1f9c256e7699a9b9d73e
[ "Apache-2.0" ]
null
null
null
Dag11.ipynb
isepri/Adventofcode2020
499bccfb2df08a34c53d1f9c256e7699a9b9d73e
[ "Apache-2.0" ]
null
null
null
Dag11.ipynb
isepri/Adventofcode2020
499bccfb2df08a34c53d1f9c256e7699a9b9d73e
[ "Apache-2.0" ]
null
null
null
26.39485
122
0.34748
[ [ [ "with open('input.txt') as t:\n text = t.read().splitlines()\n\n", "_____no_output_____" ], [ "# vloer toevoegen aan alle randen\nl_rand =len(text[0])\nrand = '.' * l_rand\n[text.insert(x, rand) for x in range(0,l_rand)]\n[text.insert(len(text), rand) for _ in range(l_rand)]\nwachtruimte = [rand + rij + rand for rij in text]", "_____no_output_____" ] ], [ [ "**Deel 1**", "_____no_output_____" ] ], [ [ "# def checkstoelen(wr, count):\n# count += 1\n# nwr = []\n# o = 0\n# for i,v in enumerate(wr):\n# nrij = ''\n# if (i < 5) | (i > (len(wr)-5)):\n# nrij = v\n# else:\n# for j,s in enumerate(v):\n# if (j < 5) | (j > (len(v)-5)):\n# nrij += s\n# else:\n# ad = [wr[i-1][j-1], wr[i-1][j], wr[i-1][j+1],\n# wr[i][j-1], wr[i][j+1],\n# wr[i+1][j-1], wr[i+1][j], wr[i+1][j+1]\n# ]\n# if s == 'L':\n# if sum(x != '#' for x in ad) == 8:\n# nrij += '#'\n# o += 1\n# else:\n# nrij += s\n# elif s == '#':\n# if sum(x == s for x in ad) >= 4:\n# nrij += 'L'\n# else:\n# nrij += s\n# o += 1\n# else:\n# nrij += s\n# nwr.append(nrij)\n# veranderd = set(wr) != set(nwr)\n# return(nwr, veranderd, count, o) ", "_____no_output_____" ], [ "# check = wachtruimte\n# v = True\n# i = 0\n# while v == True:\n# check, v, i, bezet = checkstoelen(check, i)", "_____no_output_____" ], [ "# print(bezet)", "_____no_output_____" ] ], [ [ "**Deel 2**", "_____no_output_____" ] ], [ [ "\n", "_____no_output_____" ], [ "def checkaangrenzend(d, m, n, l):\n ll =[]\n r = list(range(1,l))\n for x in r:\n cellen = [d[m-x][n-x], d[m-x][n], d[m-x][n+x], d[m][n-x], d[m][n+x], d[m+x][n-x], d[m+x][n], d[m+x][n+x]]\n ll += [cellen]\n ll_list = [[row[z] for row in ll] for z in range(len(cellen))]\n ad = []\n for richting in ll_list:\n maxr = len(richting)\n if 'L' in richting:\n maxr = richting.index('L')\n if '#' in richting[:maxr]:\n ad.append(True)\n else:\n ad.append(False)\n return(ad)", "_____no_output_____" ], [ "def checkstoelen2(wr, count, l):\n count += 1\n nwr = []\n o = 0\n for i,v in enumerate(wr):\n nrij = ''\n if (i < l) | (i >= (len(wr)-l)):\n nrij = v\n else:\n for j,s in enumerate(v):\n if (j < l) | (j >= (len(v)-l)):\n nrij += s\n else:\n omgeving = checkaangrenzend(wr, i, j, l)\n if s == 'L':\n if sum(omgeving) == 0:\n nrij += '#'\n o += 1\n else:\n nrij += s\n elif s == '#':\n if sum(omgeving) >= 5:\n nrij += 'L'\n else:\n nrij += s\n o += 1\n else:\n nrij += s\n nwr.append(nrij)\n veranderd = set(wr) != set(nwr)\n return(nwr, veranderd, count, o) ", "_____no_output_____" ], [ "check = wachtruimte\nv = True\ni = 0\nchecks = [wachtruimte]\nwhile v == True:\n check, v, i, bezet = checkstoelen2(check, i, l_rand)", "_____no_output_____" ], [ "print(bezet)", "2121\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb0bc5e40e722551d98a8a4af22bc93a1f5b62a8
188,639
ipynb
Jupyter Notebook
06.Math/9.2.3 Multivariate Gaussian normal distribution.ipynb
HenryPaik1/Study
deaa1df746587c3dc7fa3b7b73107035a704131b
[ "MIT" ]
2
2018-11-02T14:57:12.000Z
2018-11-06T14:36:22.000Z
06.Math/9.2.3 Multivariate Gaussian normal distribution.ipynb
HenryPaik1/study
deaa1df746587c3dc7fa3b7b73107035a704131b
[ "MIT" ]
null
null
null
06.Math/9.2.3 Multivariate Gaussian normal distribution.ipynb
HenryPaik1/study
deaa1df746587c3dc7fa3b7b73107035a704131b
[ "MIT" ]
null
null
null
728.335907
91,940
0.946734
[ [ [ "# 1. 다변수 가우시안 정규분포MVN\n$$\\mathcal{N}(x ; \\mu, \\Sigma) = \\dfrac{1}{(2\\pi)^{D/2} |\\Sigma|^{1/2}} \\exp \\left( -\\dfrac{1}{2} (x-\\mu)^T \\Sigma^{-1} (x-\\mu) \\right)$$\n- $\\Sigma$ : 공분산 행렬, positive semidefinite\n- x : 확률변수 벡터 $$x = \\begin{bmatrix} x_1 \\\\ x_2 \\\\ \\vdots \\\\ x_M \\end{bmatrix}\n$$", "_____no_output_____" ], [ "eg. \n$\\mu = \\begin{bmatrix}2 \\\\ 3 \\end{bmatrix}$,\n$\\Sigma = \\begin{bmatrix}1 & 0 \\\\ 0 & 1 \\end{bmatrix}$", "_____no_output_____" ] ], [ [ "%matplotlib inline\nmu = [2, 3]\ncov = [1, 0], [0, 1]\nrv = sp.stats.multivariate_normal(mu, cov)\nxx = np.linspace(-1, 6, 120)\nyy = np.linspace(-1, 6, 150)\nXX, YY = np.meshgrid(xx, yy)\nplt.contour(XX, YY, rv.pdf(np.dstack([XX, YY])))\nplt.axis(\"equal\")\nplt.xlim(0, 4)\nplt.ylim(0.5, 5.2)", "_____no_output_____" ] ], [ [ "eg. \n$\\mu = \\begin{bmatrix}2 \\\\ 3 \\end{bmatrix}$,\n$\\Sigma = \\begin{bmatrix}2 & 3 \\\\ 3 & 7 \\end{bmatrix}$", "_____no_output_____" ] ], [ [ "mu = [2, 3]\ncov = [2, 3], [3, 7]\nrv = sp.stats.multivariate_normal(mu, cov)\nxx = np.linspace(-1, 6, 120)\nyy = np.linspace(-1, 6, 150)\nXX, YY = np.meshgrid(xx, yy)\nplt.contour(XX, YY, rv.pdf(np.dstack([XX, YY])))\nplt.axis(\"equal\")\nplt.show()", "_____no_output_____" ] ], [ [ "# 2. 가우시안 정규 분포와 고유값 분해\n- 공분산 행렬 $\\Sigma$은 대칭행렬이므로, 대각화 가능\n$$ \\Sigma^{-1} = V \\Lambda^{-1}V^T$$\n- 따라서\n$$\n\\begin{eqnarray}\n\\mathcal{N}(x)\n&\\propto& \\exp \\left( -\\dfrac{1}{2} (x-\\mu)^T \\Sigma^{-1} (x- \\mu) \\right) \\\\\n&=& \\exp \\left( -\\dfrac{1}{2}(x-\\mu)^T V \\Lambda^{-1} V^T (x- \\mu) \\right) \\\\\n&=& \\exp \\left( -\\dfrac{1}{2} x'^T \\Lambda^{-1} x' \\right) \\\\\n\\end{eqnarray}\n$$\n- V : $\\Sigma$의 eigen vector\n- 새로운 확률변수$x' = V^{-1}(x-\\mu)$ \n- Cov[x']: $\\Sigma$의 matrix of eigenvalues $\\Lambda$\n- x' 의미 \n - $\\mu$만큼 평행이동 후 eigen vectors를 basis vector로 하는 변환\n - 변수간 상관관관계가 소거\n - 활용: PCA, 상관관계 높은 변수를 $x_1',x_2'$로 변환", "_____no_output_____" ] ], [ [ "mu = [2, 3]\ncov = [[4, 3], [3, 5]]\nw, v = np.linalg.eig(cov)", "_____no_output_____" ], [ "print('eigen value: w', w, 'eigen vector: v', v, sep = '\\n')", "eigen value: w\n[1.45861873 7.54138127]\neigen vector: v\n[[-0.76301998 -0.6463749 ]\n [ 0.6463749 -0.76301998]]\n" ], [ "w_cov = [[1.45861873, 0], [0, 7.54138127]]", "_____no_output_____" ], [ "xx = np.linspace(-1, 5, 120)\nyy = np.linspace(0, 6, 150)\nXX, YY = np. meshgrid(xx, yy)\n\nplt. figure(figsize=(8, 4))\n\nd = dict(facecolor='k', edgecolor='k')\n\nplt.subplot(121)\nrv1 = sp.stats.multivariate_normal(mu, cov)\nplt.contour(XX, YY, rv1.pdf(np.dstack([XX,YY])))\nplt.annotate(\"\", xy=(mu + 0.35 * w[0] * v[:, 0]), xytext=mu, arrowprops=d)\nplt.annotate(\"\", xy=(mu + 0.35 * w[1] * v[:, 1]), xytext=mu, arrowprops=d)\nplt.title(\"$X_1$,$X_2$ Joint pdf\")\nplt.axis('equal')\n\n#Cov(x)의 eigen vector(v)에 대한 좌표변환\n#Cov(x') = Cov(x)의 matrix of eigen values(w_cov)\nplt.subplot(122)\nrv2 = sp.stats.multivariate_normal(mu, w_cov) #Cov(x)의 좌표변환\nplt.contour(XX, YY, rv2.pdf(np.dstack([XX,YY])))\nplt.annotate(\"\", xy=(mu + 0.35 * w[0] * np.array([1, 0])), xytext=mu, arrowprops=d)\nplt.annotate(\"\", xy=(mu + 0.35 * w[1] * np.array([0, 1])), xytext=mu, arrowprops=d)\nplt.title(\"$X'_1$,$X'_2$ Joint pdf\")\nplt.axis('equal')\n\n\n\nplt.show()", "_____no_output_____" ] ], [ [ "# 3. 다변수 가우시안 정규분포의 조건부 확률분포\n- M차원에서 N차원이 관측되더라도, 남은 M-N개 확률변수들의 조건부 분포는, 가우시안 정규분포를 띤다.\n\n# 4. 다변수 가우시안 정규분포의 주변 확률분포\n- 마찬가지로 가우시안 정규분포를 띤다.\n$$\\int p(x_1, x_2) dx_2 = \\mathcal{N}(x_1; \\mu''1, \\sigma''^2_1)$$", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
cb0bd899458479a9b5e2b9921bbe1286910823c1
96,634
ipynb
Jupyter Notebook
notebooks/01_NaN_tiny_network_Kras.ipynb
carrascomj/gcn-prot
21bdcc4a701a301b84c49784f84e6832bf5a74a4
[ "MIT" ]
2
2020-08-17T12:09:42.000Z
2020-08-17T13:49:27.000Z
notebooks/01_NaN_tiny_network_Kras.ipynb
carrascomj/gcn-prot
21bdcc4a701a301b84c49784f84e6832bf5a74a4
[ "MIT" ]
14
2020-03-16T10:04:51.000Z
2020-08-17T12:31:45.000Z
notebooks/01_NaN_tiny_network_Kras.ipynb
carrascomj/gcn-prot
21bdcc4a701a301b84c49784f84e6832bf5a74a4
[ "MIT" ]
2
2020-03-29T17:50:08.000Z
2020-10-21T02:24:57.000Z
244.025253
29,856
0.91712
[ [ [ "# First Graph Convolutional Neural Network\nThis notebook shows a simple GCN learning using the KrasHras dataset from [Zamora-Resendiz and Crivelli, 2019](https://www.biorxiv.org/content/10.1101/610444v1.full).", "_____no_output_____" ] ], [ [ "import gcn_prot\nimport torch\n\nimport torch.nn.functional as F\nfrom os.path import join, pardir\nfrom random import seed", "_____no_output_____" ], [ "ROOT_DIR = pardir\nseed = 8", "_____no_output_____" ] ], [ [ "## Table of contents", "_____no_output_____" ], [ "1. [Initialize Data](#Initialize-Data)", "_____no_output_____" ], [ "## Initialize Data\nThe data for this experiment is the one used for testing on the [CI of the repository](https://github.com/carrascomj/gcn-prot/blob/master/.travis.yml). Thus, it is already fetched. \n\nThe first step is to calculate the length of the largest protein (in number of aminoacids), since all the proteins will be zero padded to that value. That way, all the inputs fed to the model will have the same length.", "_____no_output_____" ] ], [ [ "largest = gcn_prot.data.get_longest(join(ROOT_DIR, \"new_data\", \"graph\"))\nprint(f\"Largets protein has {largest} aminoacids\")", "Largets protein has 189 aminoacids\n" ] ], [ [ "However, for this particular dataset, it is known from the aforementioned publication that 185 is enough because the 4 terminal aminoacids were not well determined and would be later discarded by the mask.", "_____no_output_____" ] ], [ [ "largest = 185\ndata_path = join(ROOT_DIR, \"new_data\")", "_____no_output_____" ] ], [ [ "The split is performed with 70/10/20 for train/test/valid. \n\nNote that the generated datasets (custom child classes of `torch.utils.data.Dataset`) doesn't stored the graphs in memory but their paths, generating the graph when accessed by an index.", "_____no_output_____" ] ], [ [ "train, test, valid = gcn_prot.data.get_datasets(\n data_path=data_path,\n nb_nodes=largest,\n task_type=\"classification\",\n nb_classes=2,\n split=[0.7, 0.2, 0.1],\n seed=42,\n)", "CLASS[COUNTS]: 0 78\nCLASS[COUNTS]: 1 158\n" ], [ "print(f\"Train: {len(train)}\\nTest: {len(test)}\\nValidation: {len(valid)}\")", "Train: 164\nTest: 48\nValidation: 24\n" ], [ "type(train)", "_____no_output_____" ] ], [ [ "## Define the neural network", "_____no_output_____" ], [ "Each instance in the dataset retrieves a list of four matrices:\n1. **feature matrix**: 29 x 185. This corresponds to the aminoacid type (one-hot encoded vector of length 23), residue depth, residue orientation and 4 features encoding the positional index with a sinusoidal transformation.\n2. **coordinates**: 3 x 185. x,y,z coordinates of every aminoacid in the crystal (centered).\n3. **mask**: to be applied to the adjacency to discard ill-identified aminoacids.\n4. **y**: 2 label, Kras/Hras. \n\nThe transformation of this list to the input of the neural network (feature matrix, adjacency matrix), is performed during training.", "_____no_output_____" ] ], [ [ "model = gcn_prot.models.GCN_simple(\n feats=29, # features in feature matrix\n hidden=[8, 8], # number of neurons in convolutional layers (3 in this case)\n label=2, # features on y\n nb_nodes=largest, # for last layer\n dropout=0, # applied in the convolutional layers\n bias=False, # default\n act=F.relu, # default\n cuda=True # required for sparsize and fit_network\n).cuda()", "_____no_output_____" ] ], [ [ "Now, instantiate the criterion and the optimizer.", "_____no_output_____" ] ], [ [ "optimizer = torch.optim.Adam(model.parameters())\ncriterion = torch.nn.CrossEntropyLoss().cuda()", "_____no_output_____" ] ], [ [ "## Train the network", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "save_path = join(ROOT_DIR, \"models\", \"GCN_tiny_weigths.pt\")\nmodel_na = gcn_prot.models.fit_network(\n model, train, test, optimizer, criterion,\n batch_size=20, # a lot of batches per epoch\n epochs=20,\n debug=True, # will print progress of epochs\n plot_every=5, # loss plot/epoch\n save=save_path # best weights (test set) will be saved here\n)", "Iteration 2 " ] ], [ [ "Debug with validation.", "_____no_output_____" ] ], [ [ "model.eval()\nfor batch in torch.utils.data.DataLoader(\n valid, shuffle=True, batch_size=2, drop_last=False\n ):\n print(gcn_prot.models.train.forward_step(batch, model, False))", "(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 1], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([0, 1], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 1], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([0, 1], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 0], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 0], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 1], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 0], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 0], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 0], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 1], device='cuda:0'))\n(tensor([[-0.2259, 0.1046],\n [-0.2259, 0.1046]], device='cuda:0', grad_fn=<AddmmBackward>), tensor([1, 0], device='cuda:0'))\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb0be67b34c7992273694cab8f2e995c894f27db
806,991
ipynb
Jupyter Notebook
Archieve/4.ISOForest Clusters with Doc2Word-v3.ipynb
balag752/Identifying-and-Analyzing-the-Interdisciplinary
c5399e964c451cd0fafad5367e8c3083081293a4
[ "MIT" ]
null
null
null
Archieve/4.ISOForest Clusters with Doc2Word-v3.ipynb
balag752/Identifying-and-Analyzing-the-Interdisciplinary
c5399e964c451cd0fafad5367e8c3083081293a4
[ "MIT" ]
null
null
null
Archieve/4.ISOForest Clusters with Doc2Word-v3.ipynb
balag752/Identifying-and-Analyzing-the-Interdisciplinary
c5399e964c451cd0fafad5367e8c3083081293a4
[ "MIT" ]
null
null
null
95.649046
295,680
0.716935
[ [ [ "import datetime\n\nimport pandas as pd\nimport spacy\nimport re\nimport string\nimport numpy as np\nimport sys\n\nimport seaborn as sns\nfrom matplotlib import cm\nfrom matplotlib.pyplot import figure\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom spacy.tokens import Token\nfrom tqdm import tqdm\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\nimport nltk\nfrom nltk.corpus import stopwords\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\n\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.cluster import KMeans\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import silhouette_score\nfrom sklearn import metrics\n\nfrom sklearn.model_selection import ShuffleSplit\n\nimport gensim\nfrom gensim import corpora, models\nfrom gensim.models.phrases import Phrases, Phraser\nfrom gensim.utils import simple_preprocess\nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom gensim.models.coherencemodel import CoherenceModel\nfrom gensim.models import Word2Vec\nfrom gensim.models.doc2vec import Doc2Vec\nimport multiprocessing\n\nfrom sklearn.model_selection import cross_val_score , GridSearchCV,train_test_split\n\nfrom sklearn.naive_bayes import MultinomialNB,GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import svm\n\nimport enchant\npd.set_option('display.max_rows', 500)", "_____no_output_____" ], [ "dict_check = enchant.Dict(\"en_US\")\n\n#### Importing the file ####\nPath=\"src/\"\nFilename='projects_Preprocessed.csv'\ndf=pd.read_csv(Path+Filename)\n\nCat_File=\"category_hier.csv\"\nCat_data=pd.read_csv(Path+Cat_File)\n\nvarcluster_file=\"variable_clusters.csv\"\nvarcluster=pd.read_csv(Path+varcluster_file)\n\nmanualtag=pd.read_csv(Path+'SamplesManualTagger.csv')\n\nvarcluster_info=pd.read_csv(Path+'variable_clusters_info_v2.csv')\n\ndf=df[df['Translates']!=\"The goal of the Heisenberg Program is to enable outstanding scientists who fulfill all the requirements for a long-term professorship to prepare for a scientific leadership role and to work on further research topics during this time. In pursuing this goal, it is not always necessary to choose and implement project-based procedures. For this reason, in the submission of applications and later in the preparation of final reports - unlike other support instruments - no 'summary' of project descriptions and project results is required. Thus, such information is not provided in GEPRIS.\"]\n\n## Filtering the null abstracts & short description\ndf=df[(pd.isnull(df.PreProcessedDescription)==False) & (df.PreProcessedDescription.str.strip()!='abstract available')& (df.PreProcessedDescription.str.len()>100) & (pd.isnull(df[\"SubjectArea\"])==False)]\n\n# Striping the category column\nCat_data.Category=Cat_data.Category.str.strip()\n\n## Merging the high level category information\n\ndf=df.merge(Cat_data[[\"File_Categories\",\"Category\"]], how=\"left\", left_on=\"SubjectArea\", right_on=\"File_Categories\")", "_____no_output_____" ], [ "## if it is interdiscipilinary then -1 otherwise 0 (Normal data)\nmanualtag['interdiscipilinary']=-1\nmanualtag.loc[manualtag.apply(lambda x: (x['Category']==x['Category_1']) & (pd.isnull(x['Category_2'])) , axis=1),'interdiscipilinary']=1", "_____no_output_____" ] ], [ [ "## 1.1 Word Embedding", "_____no_output_____" ] ], [ [ "## Word Embeddings Functions\n\n## Generate the tagged documents (tagging based on the category column)\ndef create_tagged_document(list_of_list_of_words):\n for i, list_of_words in enumerate(list_of_list_of_words):\n yield gensim.models.doc2vec.TaggedDocument(list_of_words, [i])\n\n## Generate the tagged documents (each record in single tag )\ndef create_tagged_document_based_on_tags(list_of_list_of_words, tags):\n for i in range(len(list_of_list_of_words)):\n yield gensim.models.doc2vec.TaggedDocument(list_of_list_of_words[i], [tags[i]])\n\ndef make_bigram(inputlist):\n bigram = Phrases(inputlist, min_count=1, threshold=1,delimiter=b' ')\n bigram_phraser = Phraser(bigram)\n new_list=[]\n for sent in inputlist:\n new_list.append(bigram_phraser[sent])\n return new_list \n \n## Generate output using the word embedding model prediction - takes long time to regenerate\ndef vec_for_learning(model, tagged_docs):\n sents = tagged_docs#.values\n targets, regressors = zip(*[(doc.tags[0], model.infer_vector(doc.words, steps=20)) for doc in sents])\n return targets, regressors", "_____no_output_____" ], [ "## creating a tagged document\nDescDict=make_bigram([[x for x in str(i).split()] for i in df.PreProcessedDescription])\n\ntagged_value = list(create_tagged_document(DescDict))", "_____no_output_____" ], [ "print(str(datetime.datetime.now()),'Started')\n\n# Init the Doc2Vec model\nmodel = gensim.models.doc2vec.Doc2Vec(vector_size=50, min_count=5, epochs=40, alpha = 0.02, dm=1, workers=multiprocessing.cpu_count())\n\n#### Hyper parameter ####\n## vector_size – Dimensionality of the feature vectors.\n## If dm=1, ‘distributed memory’ (PV-DM) (CBOW - similar to continuous bag-of-words)\n## alpha - The initial learning rate.\n## min_count – Ignores all words with total frequency lower than this.\n\n# Build the Volabulary\nmodel.build_vocab(tagged_value)\n\nmodel.train(tagged_value, total_examples=len(tagged_value), epochs=40)\n\nprint(str(datetime.datetime.now()),'Completed')", "2020-02-23 11:41:18.137936 Started\n2020-02-23 11:48:31.666789 Completed\n" ], [ "## Validating the model response for random words \n\nmodelchecked=model\ntarget_word='laptop'\nprint('target_word: %r model: %s similar words:' % (target_word, modelchecked))\nfor i, (word, sim) in enumerate(modelchecked.wv.most_similar(target_word, topn=20), 1):\n print(' %d. %.2f %r' % (i, sim, word))", "target_word: 'laptop' model: Doc2Vec(dm/m,d50,n5,w5,mc5,s0.001,t4) similar words:\n 1. 0.84 'consumer electronic'\n 2. 0.81 'notify'\n 3. 0.80 'mirror surface'\n 4. 0.80 'additional measure'\n 5. 0.78 'mmw'\n 6. 0.76 'multiprocessor'\n 7. 0.76 'operating frequency'\n 8. 0.76 'goniometer'\n 9. 0.76 'capacity available'\n 10. 0.76 'communication infrastructure'\n 11. 0.76 'microcontroller'\n 12. 0.76 'cryo probe'\n 13. 0.76 'longer guarantee'\n 14. 0.75 'term flexibility'\n 15. 0.75 'mobile system'\n 16. 0.75 'busy'\n 17. 0.75 'mention requirement'\n 18. 0.75 'stable reliable'\n 19. 0.74 'aerial vehicle'\n 20. 0.74 'base station'\n" ] ], [ [ "## 1.2. PCA", "_____no_output_____" ] ], [ [ "## PCA - reducing the dimenstion\nps=20\npcamodel = PCA(n_components=ps)\npca=pcamodel.fit_transform(model.docvecs.vectors_docs)\nprint('PCA components :',ps,'Variance coveragence' ,np.max(pcamodel.explained_variance_ratio_.cumsum())*100)", "PCA components : 20 Variance coveragence 76.9777238368988\n" ], [ "dummies=pd.get_dummies(df['Category'])\nmerged_data=pd.concat([df,dummies], axis=1,ignore_index=False)\n\nmerged_data=pd.concat([merged_data,pd.DataFrame(pca)], axis=1,ignore_index=False)\n\nSubjectAreaIds=pd.DataFrame(enumerate(merged_data.SubjectArea.unique()),columns=['SubjectAreaId','SubjectArea2'])\nfinalcols=merged_data.columns.tolist()+['SubjectAreaId']\nmerged_data=merged_data.merge(SubjectAreaIds, how='left',left_on='SubjectArea',right_on='SubjectArea2')[finalcols]\n\nmerged_data=merged_data[pd.isnull(merged_data[\"Category\"])==False]\nmerged_data['ISOForestCluster']=1", "_____no_output_____" ] ], [ [ "# 2. ISO Forest ", "_____no_output_____" ] ], [ [ "cat='Life Sciences'\nFeatureCols=list(range(ps))\n\nCategoricalDS=merged_data[FeatureCols][merged_data.Category==cat]", "_____no_output_____" ], [ "# n_estimators (default=100) - The number of base estimators in the ensemble.\n# max_samples (default=”auto”) - The number of samples to draw from X to train each base estimator. If max_samples is larger than the number of samples provided, all samples will be used for all trees (no sampling)\n# max_features (default=1.0) - The number of features to draw from X to train each base estimator.\n# contamination(default=’auto’) - The proportion of outliers in the data set. If float, the contamination should be in the range [0, 0.5].\n# bootstrap (default=False) - If True, individual trees are fit on random subsets of the training data sampled with replacement. If False, sampling without replacement is performed.\nparam_dict={'contamination': ['auto',.1,.2],'n_estimators': list(range(1, 100, 5)),'max_features': [10,15,20], 'max_samples': ['auto']}", "_____no_output_____" ], [ "i_category=[]\ni_contamination=[]\ni_n_estimators=[]\ni_max_features=[]\nsilhouette_scores=[]\nnumber_outliers=[]\nrecalls=[]\n\nFeatureCols=list(range(ps))\n\nfor cat in merged_data.Category.unique():\n CategoricalDS= merged_data[FeatureCols][merged_data.Category==cat]\n e=0\n for contamination in param_dict['contamination']:\n for n_estimators in param_dict['n_estimators']:\n for max_features in param_dict['max_features']:\n\n clusterer = IsolationForest(behaviour='new', bootstrap=False, contamination=contamination,\n max_features=max_features, max_samples='auto', n_estimators=n_estimators, n_jobs=None,\n verbose=0, warm_start=False, random_state=np.random.RandomState(42))\n preds = clusterer.fit_predict(CategoricalDS)\n pred_uniq=len(pd.Series(preds).unique())\n \n merged_data.loc[merged_data.Category==cat,'ISOForestCluster']=preds\n noo=merged_data.loc[(merged_data.Category==cat) & (merged_data.ISOForestCluster==-1),'ISOForestCluster'].count()\n\n if((pred_uniq==2) and (noo>300) and (noo<2000) ) :\n score = silhouette_score(CategoricalDS, preds, metric='euclidean')\n\n manualtag_result_1=manualtag[manualtag.Category==cat][['Translates', 'Category_1', 'Category_2','interdiscipilinary']].merge(merged_data,how='left', left_on='Translates', right_on='Translates')[['Translates', 'Category_1', 'Category_2','interdiscipilinary','ISOForestCluster']] \n recall=round(metrics.recall_score(manualtag_result_1.interdiscipilinary, manualtag_result_1.ISOForestCluster, pos_label=-1),2)\n else:\n score=0\n recall=0\n\n i_category.append(cat)\n i_contamination.append(contamination)\n i_n_estimators.append(n_estimators)\n i_max_features.append(max_features)\n silhouette_scores.append(score)\n number_outliers.append(noo)\n recalls.append(recall)\n e=e+1\n print(cat,': contamination -',contamination ,e,'/',len(param_dict['contamination']),'completed')", "Natural Sciences : contamination - auto 1 / 3 completed\nNatural Sciences : contamination - 0.1 2 / 3 completed\nNatural Sciences : contamination - 0.2 3 / 3 completed\nHumanities and Social Sciences : contamination - auto 1 / 3 completed\nHumanities and Social Sciences : contamination - 0.1 2 / 3 completed\nHumanities and Social Sciences : contamination - 0.2 3 / 3 completed\nEngineering Sciences : contamination - auto 1 / 3 completed\nEngineering Sciences : contamination - 0.1 2 / 3 completed\nEngineering Sciences : contamination - 0.2 3 / 3 completed\nLife Sciences : contamination - auto 1 / 3 completed\nLife Sciences : contamination - 0.1 2 / 3 completed\nLife Sciences : contamination - 0.2 3 / 3 completed\n" ], [ "Param_tuning=pd.DataFrame({\n 'i_category':i_category,\n 'i_contamination':i_contamination,\n 'i_n_estimators':i_n_estimators,\n 'i_max_features':i_max_features,\n 'silhouette_scores':silhouette_scores,\n 'number_outliers':number_outliers,\n 'recalls':recalls\n})", "_____no_output_____" ], [ "Param_tuning.sort_values(by=['i_category','recalls','silhouette_scores','number_outliers'],ascending=False)", "_____no_output_____" ], [ "for cat in merged_data.Category.unique():\n print(Param_tuning[(Param_tuning['i_category']==cat)].sort_values(by=['recalls','silhouette_scores','number_outliers'],ascending=False).head(5))", " i_category i_contamination i_n_estimators i_max_features \\\n51 Natural Sciences auto 86 10 \n48 Natural Sciences auto 81 10 \n19 Natural Sciences auto 31 15 \n103 Natural Sciences 0.1 71 15 \n111 Natural Sciences 0.1 86 10 \n\n silhouette_scores number_outliers recalls \n51 0.267171 933 0.83 \n48 0.263721 961 0.83 \n19 0.250468 1087 0.83 \n103 0.244833 1373 0.83 \n111 0.243727 1373 0.83 \n i_category i_contamination i_n_estimators \\\n305 Humanities and Social Sciences 0.2 6 \n328 Humanities and Social Sciences 0.2 46 \n326 Humanities and Social Sciences 0.2 41 \n317 Humanities and Social Sciences 0.2 26 \n185 Humanities and Social Sciences auto 6 \n\n i_max_features silhouette_scores number_outliers recalls \n305 20 0.155030 1997 0.86 \n328 15 0.191814 1997 0.71 \n326 20 0.188934 1997 0.71 \n317 20 0.185017 1997 0.71 \n185 20 0.163624 1819 0.71 \n i_category i_contamination i_n_estimators i_max_features \\\n411 Engineering Sciences auto 86 10 \n393 Engineering Sciences auto 56 10 \n477 Engineering Sciences 0.1 96 10 \n471 Engineering Sciences 0.1 86 10 \n479 Engineering Sciences 0.1 96 20 \n\n silhouette_scores number_outliers recalls \n411 0.249878 695 0.83 \n393 0.242171 736 0.83 \n477 0.234127 938 0.83 \n471 0.233626 938 0.83 \n479 0.233609 938 0.83 \n i_category i_contamination i_n_estimators i_max_features \\\n595 Life Sciences auto 91 15 \n598 Life Sciences auto 96 15 \n592 Life Sciences auto 86 15 \n599 Life Sciences auto 96 20 \n596 Life Sciences auto 91 20 \n\n silhouette_scores number_outliers recalls \n595 0.274759 1172 1.0 \n598 0.273915 1172 1.0 \n592 0.272149 1192 1.0 \n599 0.271177 1213 1.0 \n596 0.270156 1220 1.0 \n" ], [ "Param_tuning.to_csv(Path+'ParamTuning_ISOForestV3.csv', index=False)", "_____no_output_____" ], [ "bestparam={}\nfor cat in merged_data.Category.unique():\n bestparams=Param_tuning[(Param_tuning['number_outliers']>500) & (Param_tuning['i_category']==cat)].sort_values(by=['recalls','silhouette_scores','number_outliers'],ascending=False).head(1).values[0]\n bestparam[cat]={'contamination':bestparams[1],'n_estimators':bestparams[2],'max_features':bestparams[3]}\nbestparam", "_____no_output_____" ], [ "#bestparam= {'Natural Sciences': {'contamination': 'auto',\n# 'n_estimators': 91,\n# 'max_features': 20},\n# 'Humanities and Social Sciences': {'contamination': 0.2,\n# 'n_estimators': 26,\n# 'max_features': 20},\n# 'Engineering Sciences': {'contamination': 0.2,\n# 'n_estimators': 51,\n# 'max_features': 15},\n# 'Life Sciences': {'contamination': 'auto',\n# 'n_estimators': 51,\n# 'max_features': 15}}", "_____no_output_____" ], [ "### ISOFORest \n\nFeatureCols=list(range(ps))+['FundingFrom','FundingEnd']\n\nfor cat in merged_data.Category.unique():\n print(str(datetime.datetime.now()),'Started')\n print('******'+cat+'******')\n\n CategoricalDS= merged_data[FeatureCols][merged_data.Category==cat]\n \n IsolationForest(behaviour='new', bootstrap=False, contamination=bestparam[cat]['contamination'],\n max_features=bestparam[cat]['max_features'], max_samples='auto', n_estimators=bestparam[cat]['n_estimators'], n_jobs=None,\n random_state=np.random.RandomState(42), verbose=0, warm_start=False)\n preds = clusterer.fit_predict(CategoricalDS)\n \n merged_data.loc[merged_data.Category==cat,'ISOForestCluster']=preds\n print(pd.Series(preds).value_counts())\n \n #noo=merged_data.loc[(merged_data.Category==cat) & (merged_data.DBScanCluster==-1),'DBScanCluster'].count()\n\n score = silhouette_score(CategoricalDS, preds, metric='euclidean')\n manualtag_result_1=manualtag[manualtag.Category==cat][['Translates', 'Category_1', 'Category_2','interdiscipilinary']].merge(merged_data,how='left', left_on='Translates', right_on='Translates')[['Translates', 'Category_1', 'Category_2','interdiscipilinary','ISOForestCluster']] \n recall=round(metrics.recall_score(manualtag_result_1.interdiscipilinary, manualtag_result_1.ISOForestCluster, pos_label=-1),2)\n\n print('silhouette_score',round(score,2),'recall_score',recall)\n print(str(datetime.datetime.now()),'Completed')\n print('')", "2020-02-23 14:44:52.770450 Started\n******Natural Sciences******\n 1 10979\n-1 2745\ndtype: int64\nsilhouette_score 0.06 recall_score 1.0\n2020-02-23 14:45:00.209053 Completed\n\n2020-02-23 14:45:00.209150 Started\n******Humanities and Social Sciences******\n 1 7987\n-1 1997\ndtype: int64\nsilhouette_score 0.06 recall_score 0.57\n2020-02-23 14:45:03.668854 Completed\n\n2020-02-23 14:45:03.668962 Started\n******Engineering Sciences******\n 1 7501\n-1 1875\ndtype: int64\nsilhouette_score 0.18 recall_score 0.83\n2020-02-23 14:45:07.191119 Completed\n\n2020-02-23 14:45:07.191680 Started\n******Life Sciences******\n 1 14359\n-1 3590\ndtype: int64\nsilhouette_score 0.1 recall_score 1.0\n2020-02-23 14:45:14.418632 Completed\n\n" ], [ "merged_data['ISOForestCluster'].value_counts()", "_____no_output_____" ], [ "manualtag_result_1=manualtag[['Translates', 'Category_1', 'Category_2','interdiscipilinary']].merge(merged_data,how='left', left_on='Translates', right_on='Translates')[['Translates', 'Category_1', 'Category_2','interdiscipilinary','ISOForestCluster']] \nrecall=round(metrics.recall_score(manualtag_result_1.interdiscipilinary, manualtag_result_1.ISOForestCluster, pos_label=-1),2)\n\n##Out of all the interdisciplinaries , how much we classified as outlier correctly. It should be high as possible.\nprint('Overall Recall',recall)\n\n# Print the confusion matrix\nprint(metrics.confusion_matrix(manualtag_result_1.interdiscipilinary, manualtag_result_1.ISOForestCluster))\n\n# Print the precision and recall, among other metrics\nprint(metrics.classification_report(manualtag_result_1.interdiscipilinary, manualtag_result_1.ISOForestCluster, digits=2))", "Overall Recall 0.81\n[[17 4]\n [10 19]]\n precision recall f1-score support\n\n -1 0.63 0.81 0.71 21\n 1 0.83 0.66 0.73 29\n\n accuracy 0.72 50\n macro avg 0.73 0.73 0.72 50\nweighted avg 0.74 0.72 0.72 50\n\n" ], [ "## Reseting the index, converting category to int for supervised learning\n\ndef CattoID(input_cat):\n if(input_cat=='Engineering Sciences'):\n return 0\n elif(input_cat=='Humanities and Social Sciences'):\n return 1\n elif(input_cat=='Natural Sciences'):\n return 2\n elif(input_cat=='Life Sciences'):\n return 3\n else :\n return -1\n\nmerged_data=merged_data.reset_index()[merged_data.columns[0:]]\nmerged_data['CategoryConv']=merged_data.Category.apply(CattoID)\nmerged_data['CategoryConv']=merged_data['CategoryConv'].astype('int')", "_____no_output_____" ] ], [ [ "# 3. Supervised learning", "_____no_output_____" ] ], [ [ "validation_part=manualtag[['Translates', 'Category_1', 'Category_2','interdiscipilinary']].merge(merged_data,how='left', left_on='Translates', right_on='Translates')\n\nmerged_data['validation_part']=False\nmerged_data['validation_part'][merged_data['Translates'].isin(manualtag['Translates'])]=True\n\nFeatures=FeatureCols\n\nmerged_data[Features]=MinMaxScaler().fit_transform(merged_data[Features])\n\nOP_Feature='CategoryConv'\n\n## Training & Test data are splitted based on the DBScanCluster result. outlier data are considering as test data to reevaluate.\nvalidation_part=validation_part[(validation_part.ISOForestCluster==-1)]\nX_Validation_DS=validation_part[Features]\nvalidation_part['Category_1']=validation_part['Category_1'].apply(CattoID)\nvalidation_part['Category_2']=validation_part['Category_2'].apply(CattoID)\n\nX_Training_DS=merged_data[Features][(merged_data.ISOForestCluster==1) ]\ny_Training_DS=merged_data[OP_Feature][(merged_data.ISOForestCluster==1) ]\n\nX_Test_DS=merged_data[Features][(merged_data.ISOForestCluster!=1) & (merged_data['validation_part']==False)]\ny_Test_DS=merged_data[OP_Feature][(merged_data.ISOForestCluster!=1) & (merged_data['validation_part']==False)]\n\nX_train, X_test, y_train, y_test = train_test_split(X_Training_DS,y_Training_DS, test_size=0.25, random_state=0)", "/Users/balaji/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n after removing the cwd from sys.path.\n" ] ], [ [ "## 3.1 NaiveBayes", "_____no_output_____" ] ], [ [ "modelNB = MultinomialNB(alpha=1)\n\n#### Hyper parameter ####\n# alpha - Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).\n\nmodelNB.fit(X_train, y_train)\n\nnfolds=5\nscores=cross_val_score(modelNB, X_Training_DS,y_Training_DS, cv=nfolds, scoring=\"accuracy\")\npd.Series(scores).plot(kind=\"box\", label=\"Accuracy\");\nplt.title('Accuracy_score from '+str(nfolds)+' Folds (Accuracy) for '+str(round(pd.Series(scores).mean(), 2)))\n\ny_pred = modelNB.predict(X_test)\nprint('Accuracy Score : '+str(accuracy_score(y_test,y_pred )*100))", "Accuracy Score : 34.79964730087195\n" ] ], [ [ "## 3.1 k-nearest neighbors ", "_____no_output_____" ] ], [ [ "kvalue=[]\ntest_accuracy=[]\ntest_precision=[]\nvalidation_accuracy=[]\nvalidation_precision=[]\ncross_accuray=[]\n\n\nfor k in [4,6,10,16,25,35]:\n modelKBC = KNeighborsClassifier(n_neighbors=k, weights='distance')\n \n #### Hyper parameter ####\n # n_neighbors - Number of neighbors to use by default for kneighbors queries\n # weights - weight function used in prediction (‘distance’ : weight points by the inverse of their distance. \n #in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away.)\n \n modelKBC.fit(X_train, y_train)\n\n y_pred = modelKBC.predict(X_test)\n \n val_preds=modelKBC.predict(X_Validation_DS)\n validation_part['val_preds']=val_preds\n y_Validation_DS=validation_part[['val_preds','Category_1','Category_2']].apply(lambda x: x['Category_2'] if(x['Category_2']== x['val_preds']) else x['Category_1'] ,axis=1)\n\n kvalue.append(k)\n test_accuracy.append( round( metrics.accuracy_score(y_test,y_pred),2) )\n test_precision.append(round(metrics.precision_score(y_test,y_pred, average='macro'),2) )\n \n validation_accuracy.append( round(metrics.accuracy_score(y_Validation_DS,val_preds),2) )\n validation_precision.append( round(metrics.precision_score(y_Validation_DS,val_preds, average='macro'),2) )\n \n #nfolds=3\n #scores=cross_val_score(modelKBC, X_train,y_train, cv=nfolds, scoring=\"accuracy\")\n #pd.Series(scores).plot(kind=\"box\", label=\"Accuracy\");\n #plt.title('Accuracy_score from '+str(nfolds)+' Folds (Accuracy) for '+str(round(pd.Series(scores).mean(), 2)))\n #cross_accuray\n \n print('neighbors:',k,'completed')\n", "neighbors: 4 completed\nneighbors: 6 completed\nneighbors: 10 completed\nneighbors: 16 completed\nneighbors: 25 completed\nneighbors: 35 completed\n" ], [ "kNNResult=pd.DataFrame({'kvalue':kvalue, 'test_accuracy':test_accuracy,'test_precision':test_precision, 'validation_accuracy':validation_accuracy,'validation_precision':validation_precision })\nkNNResult", "_____no_output_____" ], [ "k=4\nmodelKBC = KNeighborsClassifier(n_neighbors=k, weights='distance')\nmodelKBC.fit(X_train, y_train)\n\ny_pred = modelKBC.predict(X_test)\n\nnfolds=3\nscores=cross_val_score(modelKBC, X_train,y_train, cv=nfolds, scoring=\"accuracy\")\npd.Series(scores).plot(kind=\"box\", label=\"Accuracy\");\nplt.title('Accuracy_score from '+str(nfolds)+' Folds (Accuracy) for '+str(round(pd.Series(scores).mean(), 2)))", "_____no_output_____" ], [ "# Print the confusion matrix\nprint(metrics.confusion_matrix(y_test, y_pred))\n\n# Print the precision and recall, among other metrics\nprint(metrics.classification_report(y_test, y_pred, digits=3))", "[[1331 81 380 74]\n [ 56 1811 59 94]\n [ 236 97 2259 177]\n [ 66 117 216 3153]]\n precision recall f1-score support\n\n 0 0.788 0.713 0.749 1866\n 1 0.860 0.897 0.878 2020\n 2 0.775 0.816 0.795 2769\n 3 0.901 0.888 0.894 3552\n\n accuracy 0.838 10207\n macro avg 0.831 0.828 0.829 10207\nweighted avg 0.838 0.838 0.838 10207\n\n" ], [ "val_preds=modelKBC.predict(X_Validation_DS)\nvalidation_part['val_preds']=val_preds\ny_Validation_DS=validation_part[['val_preds','Category_1','Category_2']].apply(lambda x: x['Category_2'] if(x['Category_2']== x['val_preds']) else x['Category_1'] ,axis=1)\n\n\n# Print the confusion matrix\nprint(metrics.confusion_matrix(y_Validation_DS, val_preds))\n\n# Print the precision and recall, among other metrics\nprint(metrics.classification_report(y_Validation_DS, val_preds, digits=2))\n", "[[10 0 0 0]\n [ 1 2 0 1]\n [ 1 1 1 0]\n [ 1 0 1 8]]\n precision recall f1-score support\n\n 0 0.77 1.00 0.87 10\n 1 0.67 0.50 0.57 4\n 2 0.50 0.33 0.40 3\n 3 0.89 0.80 0.84 10\n\n accuracy 0.78 27\n macro avg 0.71 0.66 0.67 27\nweighted avg 0.77 0.78 0.76 27\n\n" ], [ "cvalue=[]\ntest_accuracy=[]\ntest_precision=[]\nvalidation_accuracy=[]\nvalidation_precision=[]\ncross_accuray=[]\n\n\nfor x in [.01]+list(np.linspace(0.1,100,5))+[10]:\n\n modelSVC = svm.LinearSVC(C=x).fit(X_train, y_train)\n #### Hyper parameter ####\n # C - The strength of the regularization is inversely proportional to C.\n\n y_pred = modelSVC.predict(X_test)\n \n val_preds=modelSVC.predict(X_Validation_DS)\n validation_part['val_preds']=val_preds\n y_Validation_DS=validation_part[['val_preds','Category_1','Category_2']].apply(lambda x: x['Category_2'] if(x['Category_2']== x['val_preds']) else x['Category_1'] ,axis=1)\n\n cvalue.append(x)\n test_accuracy.append( round( metrics.accuracy_score(y_test,y_pred),2) )\n test_precision.append(round(metrics.precision_score(y_test,y_pred, average='macro'),2) )\n \n validation_accuracy.append( round(metrics.accuracy_score(y_Validation_DS,val_preds),2) )\n validation_precision.append( round(metrics.precision_score(y_Validation_DS,val_preds, average='macro'),2) )\n ", "/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/svm/base.py:929: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/svm/base.py:929: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/svm/base.py:929: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/svm/base.py:929: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/svm/base.py:929: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.\n 'precision', 'predicted', average, warn_for)\n" ], [ "SVCResult=pd.DataFrame({'cvalue':cvalue, 'test_accuracy':test_accuracy,'test_precision':test_precision, 'validation_accuracy':validation_accuracy,'validation_precision':validation_precision })\nSVCResult", "_____no_output_____" ] ], [ [ "## 4. Formatting the output categories based on the predict_proba", "_____no_output_____" ] ], [ [ "## Based on predict_proba result. reorder to values and categories based on high probablity.\n\ndef name_max_value(DF):\n colname='Category_1_Values'\n if (DF['Engineering Sciences']==DF[colname]):\n return 'Engineering Sciences'\n elif (DF['Humanities and Social Sciences']==DF[colname]):\n return 'Humanities and Social Sciences'\n elif (DF['Natural Sciences']==DF[colname]):\n return 'Natural Sciences'\n elif (DF['Life Sciences']==DF[colname]):\n return 'Life Sciences'\n else:\n return ''\n \ndef name_sec_max_value(DF):\n colname='Category_2_Values'\n if(DF[colname]==0):\n return ''\n elif ((DF['Engineering Sciences']==DF[colname]) & (DF['Category_1']!='Engineering Sciences')):\n return 'Engineering Sciences'\n elif ((DF['Humanities and Social Sciences']==DF[colname]) & (DF['Category_1']!='Humanities and Social Sciences')):\n return 'Humanities and Social Sciences'\n elif ((DF['Natural Sciences']==DF[colname]) & (DF['Category_1']!='Natural Sciences')):\n return 'Natural Sciences'\n elif ((DF['Life Sciences']==DF[colname]) & (DF['Category_1']!='Life Sciences')):\n return 'Life Sciences'\n else:\n return ''\n \ndef name_3rd_max_value(DF):\n colname='Category_3_Values'\n if(DF[colname]==0):\n return ''\n elif ((DF['Engineering Sciences']==DF[colname]) & (DF['Category_2']!='Engineering Sciences')):\n return 'Engineering Sciences'\n elif ((DF['Humanities and Social Sciences']==DF[colname]) & (DF['Category_2']!='Humanities and Social Sciences')):\n return 'Humanities and Social Sciences'\n elif ((DF['Natural Sciences']==DF[colname]) & (DF['Category_2']!='Natural Sciences')):\n return 'Natural Sciences'\n elif ((DF['Life Sciences']==DF[colname]) & (DF['Category_2']!='Life Sciences')):\n return 'Life Sciences'\n else:\n return ''\n \ncols=['Engineering Sciences','Humanities and Social Sciences','Natural Sciences','Life Sciences']\nPredictedValues=pd.DataFrame(modelKBC.predict_proba(merged_data[Features]), columns=cols)\nPredictedValues['Category_1_Values']=PredictedValues[cols].apply(np.max,axis=1)\nPredictedValues['Category_2_Values']=PredictedValues[cols].apply(np.sort,axis=1).apply(lambda x:x[2])\nPredictedValues['Category_3_Values']=PredictedValues[cols].apply(np.sort,axis=1).apply(lambda x:x[1])\n\nPredictedValues['Category_1']=PredictedValues.apply(name_max_value,axis=1)\nPredictedValues['Category_2']=PredictedValues.apply(name_sec_max_value,axis=1)\nPredictedValues['Category_3']=PredictedValues.apply(name_3rd_max_value,axis=1)\n\nPredictedValues['Category_12_Variance']=PredictedValues.apply(lambda x :x['Category_1_Values']-x['Category_2_Values'], axis=1)\nPredictedValues['Category_23_Variance']=PredictedValues.apply(lambda x :x['Category_2_Values']-x['Category_3_Values'], axis=1)", "_____no_output_____" ], [ "PredictedValues.loc[PredictedValues['Category_3_Values']<=.15,'Category_3']=''\nPredictedValues.loc[PredictedValues['Category_2_Values']<=.15,'Category_2']=''\n\nPredictedValues.loc[PredictedValues['Category_1_Values']>=.80,'Category_2']=''\nPredictedValues.loc[PredictedValues['Category_1_Values']>=.80,'Category_3']=''", "_____no_output_____" ], [ "PredictedValues['Category']=merged_data['Category']\n\nfil_1_2=(PredictedValues['Category_12_Variance']<=.10) & ((PredictedValues['Category_1']==PredictedValues['Category']) | (PredictedValues['Category_2']==PredictedValues['Category']))\nfil_2_3=(PredictedValues['Category_23_Variance']<=.10) & ((PredictedValues['Category_3']==PredictedValues['Category']) | (PredictedValues['Category_2']==PredictedValues['Category']))\n\nPredictedValues.loc[(fil_1_2 | fil_2_3) ,'Category_1']=PredictedValues.loc[(fil_1_2 | fil_2_3) ,'Category']\nPredictedValues.loc[(fil_1_2 | fil_2_3) ,'Category_2']=''\nPredictedValues.loc[(fil_1_2 | fil_2_3) ,'Category_3']=''", "_____no_output_____" ] ], [ [ "## 5.1. Manual Validation", "_____no_output_____" ] ], [ [ "## regenerating dataset\n\nNewMergedDSAligned=pd.concat([merged_data[merged_data.columns.tolist()[:12]+['ISOForestCluster']],PredictedValues[PredictedValues.columns[4:12]]], axis=1, ignore_index=False)", "_____no_output_____" ], [ "fil_1_2=(NewMergedDSAligned['Category_12_Variance']<=.10) & ((NewMergedDSAligned['Category_1']==NewMergedDSAligned['Category']) | (NewMergedDSAligned['Category_2']==NewMergedDSAligned['Category']))\nfil_2_3=(NewMergedDSAligned['Category_23_Variance']<=.10) & ((NewMergedDSAligned['Category_3']==NewMergedDSAligned['Category']) | (NewMergedDSAligned['Category_2']==NewMergedDSAligned['Category']))\n\nNewMergedDSAligned.loc[(fil_1_2 | fil_2_3) ,'Category_1']=NewMergedDSAligned.loc[(fil_1_2 | fil_2_3) ,'Category']\nNewMergedDSAligned.loc[(fil_1_2 | fil_2_3) ,'Category_2']=''\nNewMergedDSAligned.loc[(fil_1_2 | fil_2_3) ,'Category_3']=''", "_____no_output_____" ], [ "NewMergedDSAligned['ISOForestCluster'].value_counts()", "_____no_output_____" ], [ "#(NewMergedDSAligned.ISOForestCluster!=0) &\n\nNewMergedDSAligned['ISOForestCluster'][ (NewMergedDSAligned['Category']!=NewMergedDSAligned['Category_1'])].value_counts()", "_____no_output_____" ], [ "NewMergedDSAligned['Category'][(NewMergedDSAligned.ISOForestCluster!=1) & (NewMergedDSAligned['Category']!=NewMergedDSAligned['Category_1'])].value_counts()", "_____no_output_____" ], [ "cats='Natural Sciences'\nlim=20\nNewMergedDSAligned[['Translates','Category']+NewMergedDSAligned.columns[13:].tolist()][(NewMergedDSAligned['Category_1']!=cats) & (NewMergedDSAligned['Category']==cats) & (NewMergedDSAligned.ISOForestCluster!=1) & (NewMergedDSAligned['Category']!=NewMergedDSAligned['Category_1'])].sort_values('Category_1_Values', ascending=False).head(lim).tail(5)", "_____no_output_____" ], [ "#cats='Humanities and Social Sciences'\nNewMergedDSAligned[['Translates','Category_1_Values']][(NewMergedDSAligned['Category_1']!=cats) & (NewMergedDSAligned['Category']==cats) & (NewMergedDSAligned.ISOForestCluster!=1) & (NewMergedDSAligned['Category']!=NewMergedDSAligned['Category_1'])].sort_values('Category_1_Values', ascending=False).Translates.head(lim).tail(5).tolist()#.tail().", "_____no_output_____" ], [ "#NewMergedDSAligned.to_csv(Path+'WEPCAISOFindingsKMeans.csv', index=False)", "_____no_output_____" ] ], [ [ "## 5.2. Validation with manual taggings", "_____no_output_____" ] ], [ [ "## regenerating dataset\n\nMergeValidation=pd.concat([merged_data[['ISOForestCluster','Translates']],PredictedValues[PredictedValues.columns[4:]]], axis=1, ignore_index=False)\nMergeValidationResult_2=manualtag[['Category','Translates', 'Category_1', 'Category_2','interdiscipilinary']].merge(MergeValidation,how='left', left_on='Translates', right_on='Translates',suffixes= ('_Actual','_Pred'))\n\n\n## Function to take a better results for valudation\ndef rebuilt_ip(x):\n final_pred=x['Category_1_Pred']\n final_actual=x['Category_1_Actual']\n result=0\n \n if(x['Category_1_Pred'] == x['Category_1_Actual']):\n final_pred=x['Category_1_Pred']\n final_actual=x['Category_1_Actual']\n result=1\n \n elif(x['Category_1_Pred'] == x['Category_2_Actual']):\n final_pred=x['Category_1_Pred']\n final_actual=x['Category_2_Actual']\n result=1\n \n elif(x['Category_2_Pred'] == x['Category_1_Actual']):\n final_pred=x['Category_2_Pred']\n final_actual=x['Category_1_Actual']\n result=.66\n \n elif(x['Category_2_Pred'] == x['Category_2_Actual']):\n final_pred=x['Category_2_Pred']\n final_actual=x['Category_2_Actual']\n result=.66\n \n elif(x['Category_3'] == x['Category_1_Actual']):\n final_pred=x['Category_2_Pred']\n final_actual=x['Category_1_Actual'] \n result=.33\n \n elif(x['Category_3'] == x['Category_2_Actual']):\n final_pred=x['Category_2_Pred']\n final_actual=x['Category_2_Actual']\n result=.33\n \n # if it is not an outlier assigning a original data sets\n if(x['ISOForestCluster']!=-1):\n final_pred=x['Category_Actual']\n final_actual=x['Category_1_Actual']\n result=-1\n \n return pd.Series({'pred':final_pred,'actual':final_actual,'result':result})\n\nMergeValidationResult_3=pd.concat([MergeValidationResult_2,pd.DataFrame(MergeValidationResult_2.apply(rebuilt_ip, axis=1))], axis=1)\nMergeValidationResult_3['Match']=MergeValidationResult_3.apply(lambda x: 'Correct' if(x['pred']==x['Category_Actual']) else 'interdiscipilinary' , axis=1)\n", "_____no_output_____" ], [ "MergeValidationResult_3.groupby(['ISOForestCluster','Match']).count()[['Translates']]", "_____no_output_____" ], [ "# Print the confusion matrix\nprint(metrics.confusion_matrix(MergeValidationResult_3.actual, MergeValidationResult_3.pred))\n\n# Print the precision and recall, among other metrics\nprint(metrics.classification_report(MergeValidationResult_3.actual, MergeValidationResult_3.pred, digits=3))", "[[11 0 0 2]\n [ 1 9 0 1]\n [ 1 4 11 2]\n [ 0 0 0 8]]\n precision recall f1-score support\n\n Engineering Sciences 0.846 0.846 0.846 13\nHumanities and Social Sciences 0.692 0.818 0.750 11\n Life Sciences 1.000 0.611 0.759 18\n Natural Sciences 0.615 1.000 0.762 8\n\n accuracy 0.780 50\n macro avg 0.788 0.819 0.779 50\n weighted avg 0.831 0.780 0.780 50\n\n" ] ], [ [ "## 5.3. Each category TF/IDF based result evaluvation ", "_____no_output_____" ] ], [ [ "#&(NewMergedDSAligned['Category']==cats) &(NewMergedDSAligned['Category_1']==check_cat)\n\ninput_data=NewMergedDSAligned[(NewMergedDSAligned['Category']!=NewMergedDSAligned['Category_1']) & (NewMergedDSAligned.ISOForestCluster!=1) ]\n\ninput_data.loc[:,'CategoryCollc']=input_data[['Category','Category_1','Category_2','Category_3']].apply(lambda x:x[0]+','+x[1]+','+x[2]+','+x[3], axis=1)\n#input_data.loc[:,'CategoryCollc']=input_data[['Category','Category_1']].apply(lambda x:x[0]+','+x[1], axis=1)\ninput_data.loc[:,'CategoryCollc']=input_data['CategoryCollc'].str.strip(\",\")", "/Users/balaji/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py:362: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self.obj[key] = _infer_fill_value(value)\n/Users/balaji/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py:543: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self.obj[item] = s\n" ], [ "varcluster_info.cluster_id=varcluster_info.cluster_id.astype('int32')\nvarclusterall=varcluster.merge(varcluster_info, how='left',left_on='Cluster', right_on='cluster_id')\nvarclusterall=varclusterall[varclusterall.RS_Ratio<.98]", "_____no_output_____" ], [ "def find_category(target_word):\n try :\n sim_word=list(map(lambda x:x[0] ,modelchecked.wv.most_similar(target_word, topn=5)))\n finalcategory=varclusterall[varclusterall.Variable.isin(sim_word)].category.value_counts().sort_values(ascending=False).head(1).index\n if(len(finalcategory)>0):\n return finalcategory[0]\n else:\n return np.NaN\n except :\n return np.NaN", "_____no_output_____" ], [ "sizes=len(input_data.CategoryCollc.unique())\ncategory_tfidfs=pd.DataFrame()\n\nwith tqdm(total=len(input_data['CategoryCollc'].unique())) as bar:\n for i,bucket in input_data.groupby(['CategoryCollc']):\n varcat=pd.DataFrame()\n\n vectorizer = TfidfVectorizer(max_features=20, ngram_range=(1, 1))\n review_vectors = vectorizer.fit_transform(bucket[\"PreProcessedDescription\"])\n features_df = pd.DataFrame(review_vectors.toarray(), columns = vectorizer.get_feature_names())\n\n varcat=pd.DataFrame(features_df.sum().sort_values(ascending=False)).merge(varclusterall, how='left', left_index=True, right_on='Variable')[[0,'Variable','category']]\n varcat.category=varcat[['Variable', 'category']].apply(lambda x: find_category(x.Variable) if(pd.isnull(x['category'])) else x['category'], axis=1)\n\n varcat['bucket_length']=len(bucket)\n varcat['bucket_category']=bucket['Category'].unique()[0]\n varcat['Category_1']=bucket['Category_1'].unique()[0]\n varcat['Category_2']=bucket['Category_2'].unique()[0]\n varcat['Category_3']=bucket['Category_3'].unique()[0]\n\n varcat['Category_1_Score']=bucket['Category_1_Values'].mean()\n varcat['Category_2_Score']=bucket['Category_2_Values'].mean()\n varcat['Category_3_Score']=bucket['Category_3_Values'].mean()\n\n varcat=varcat.reset_index()\n\n category_tfidfs=pd.concat([varcat[varcat.columns[1:]],category_tfidfs])\n bar.update(1)", "100%|██████████| 67/67 [00:20<00:00, 3.55it/s]\n" ], [ "category_tfidfs.to_csv(Path+'CategoryTFIDFSummary_WEPCAISOForestFindingsKMeansV3.csv', index=False)", "_____no_output_____" ] ], [ [ "# Visualization", "_____no_output_____" ] ], [ [ "def CattoID(input_cat):\n if(input_cat=='Engineering Sciences'):\n return 0\n elif(input_cat=='Humanities and Social Sciences'):\n return 1\n elif(input_cat=='Natural Sciences'):\n return 2\n elif(input_cat=='Life Sciences'):\n return 3\n else :\n return -1\n\n\nNewMergedDSAligned2=pd.concat([merged_data,PredictedValues[PredictedValues.columns[4:12]]], axis=1, ignore_index=False)\n\nNewMergedDSAligned2.loc[:,'Category_1_ID']=NewMergedDSAligned2.Category_1.apply(CattoID)\nNewMergedDSAligned2.loc[:,'Category_2_ID']=NewMergedDSAligned2.Category_2.apply(CattoID)\nNewMergedDSAligned2.loc[:,'Category_3_ID']=NewMergedDSAligned2.Category_3.apply(CattoID)\n\nNewMergedDSAligned2=pd.DataFrame(enumerate(NewMergedDSAligned2.SubjectArea.unique()), columns=['Subjectid','SubjectAreaMatching']).merge(NewMergedDSAligned2,left_on='SubjectAreaMatching', right_on='SubjectArea')\n\ncats=['Engineering Sciences','Humanities and Social Sciences', 'Life Sciences','Natural Sciences']\ncats_dist=[]\n\n## Finiding the overall similiarity\n\nfor c, w in NewMergedDSAligned2[(NewMergedDSAligned2['Category']!=NewMergedDSAligned2['Category_1']) & (NewMergedDSAligned2['ISOForestCluster']!=1)].groupby('Category'):\n #print('')\n #print(c, len(w))\n #other_cat=list(filter(lambda x:x!=c, cats))\n cat_dist=[]\n for oc in cats:\n if oc==c:\n oc_sim=0\n \n else:\n oc_sum=sum(w[w['Category_1']==oc].Category_1_Values.tolist()+w[w['Category_2']==oc].Category_2_Values.tolist()+w[w['Category_3']==oc].Category_3_Values.tolist())\n oc_sim=oc_sum/len(w)\n \n cat_dist.append(oc_sim)\n #print(c,':',oc,'-', round(oc_sim,2))\n \n #oc_sum=w[w['Category_1']==oc].Category_1_Values.tolist()+w[w['Category_2']==oc].Category_2_Values.tolist()+w[w['Category_3']==oc].Category_3_Values.tolist()\n #oc_sim=sum(oc_sum)/len(oc_sum)\n #print(c,':',oc,'-', round(oc_sim,2))\n cats_dist.append(np.array(cat_dist))\ncats_dist=np.array(cats_dist)\n\n## Making symmetric matrix\nsym_dist=np.zeros(cats_dist.shape)\nfor i in range(cats_dist.shape[0]):\n for j in range(cats_dist.shape[0]):\n sym_dist[i][j]=(cats_dist[i][j]+ cats_dist[j][i])/2\n if(i==j):\n sym_dist[i][j]=1\n\n# 1-x : convert similiarity to distance\nsym_dist=1-pd.DataFrame(sym_dist, columns=cats, index=cats)", "_____no_output_____" ], [ "## Generating coordinates from distance\n\n#, angle=0.8\n\n#coords = TSNE(n_components=2,perplexity=.1, random_state=12, metric='precomputed').fit_transform(sym_dist)\n\n#coords = TSNE(n_components=2,perplexity=4.2, random_state=18, metric='precomputed').fit_transform(sym_dist)\ncoords = PCA(n_components=2).fit_transform(sym_dist)\n\ncoords=MinMaxScaler([0,1000]).fit_transform(coords)\ncoords=pd.DataFrame(coords, index=cats).reset_index()\np1=sns.scatterplot(\n x=0, y=1,\n hue=\"index\",\n # palette=sns.color_palette(\"hls\", 4),\n data=coords,\n # legend=\"full\",\n alpha=1,\n size = 8,\n legend=False\n);\n\nfor line in range(0,coords.shape[0]):\n p1.text(coords[0][line]+0.01, coords[1][line], cats[line], horizontalalignment='left', size='medium', color='black')", "_____no_output_____" ], [ "sym_dist", "_____no_output_____" ], [ "newrange=pd.DataFrame(NewMergedDSAligned2.Category.value_counts()/80).reset_index().merge(coords,left_on='index',right_on='index')\nnewrange.loc[:,'Min_X']=newrange[0]-newrange['Category']\nnewrange.loc[:,'Max_X']=newrange[0]+newrange['Category']\nnewrange.loc[:,'Min_Y']=newrange[1]-(newrange['Category']*.60)\nnewrange.loc[:,'Max_Y']=newrange[1]+(newrange['Category']*.60)\n\nnewrange.columns=['Category','size', 0, 1, 'Min_X', 'Max_X', 'Min_Y', 'Max_Y']\nnewrange", "_____no_output_____" ], [ "catsperplexity={'Engineering Sciences':5,'Humanities and Social Sciences':5, 'Life Sciences':10,'Natural Sciences':8}\n\n## T-SNE separately for each categories\n\nouterclusterfeatures=['Category_1_Values','Category_1_ID','Category_2_ID','Category_2_Values','Category_3_ID','Category_3_Values','Subjectid']\n#Doc2VecModelData=pd.concat([pd.DataFrame(model.docvecs.vectors_docs),NewMergedDSAligned2[outerclusterfeatures]], axis=1)\nDoc2VecModelData=pd.concat([pd.DataFrame(pca[:,:10]),NewMergedDSAligned2[outerclusterfeatures]], axis=1)\n \nDoc2VecModelData['tsne-2d-one']=0\nDoc2VecModelData['tsne-2d-two']=0\n\nfor cat in cats:#['Life Sciences']:#\n print(str(datetime.datetime.now()),'Started for', cat)\n \n tsne = TSNE(n_components=2, perplexity=catsperplexity[cat], n_iter=300, random_state=0, learning_rate=100)\n ## The perplexity is related to the number of nearest neighbors that is used in other manifold learning algorithms. \n ## Larger datasets usually require a larger perplexity. Consider selecting a value between 5 and 50. \n tsne_results = tsne.fit_transform(Doc2VecModelData[NewMergedDSAligned2.Category==cat])\n \n Doc2VecModelData.loc[NewMergedDSAligned2.Category==cat,'tsne-2d-one'] = tsne_results[:,0]\n Doc2VecModelData.loc[NewMergedDSAligned2.Category==cat,'tsne-2d-two'] = tsne_results[:,1]\n \n print(str(datetime.datetime.now()),'Completed for', cat)\n\nDoc2VecModelData.loc[:,'Category'] = NewMergedDSAligned2.Category\nDoc2VecModelData.loc[:,'Category_1'] = NewMergedDSAligned2.Category_1\n", "2020-02-23 15:23:58.427544 Started for Engineering Sciences\n2020-02-23 15:24:21.650846 Completed for Engineering Sciences\n2020-02-23 15:24:21.651311 Started for Humanities and Social Sciences\n2020-02-23 15:24:58.162134 Completed for Humanities and Social Sciences\n2020-02-23 15:24:58.162323 Started for Life Sciences\n2020-02-23 15:25:49.551593 Completed for Life Sciences\n2020-02-23 15:25:49.552266 Started for Natural Sciences\n2020-02-23 15:26:29.798790 Completed for Natural Sciences\n" ], [ "# Reshaping\nfor cat in cats:\n model_x=MinMaxScaler([newrange[newrange['Category']==cat].Min_X.values[0],newrange[newrange['Category']==cat].Max_X.values[0]])\n Doc2VecModelData.loc[Doc2VecModelData['Category']==cat,'tsne-2d-one']=model_x.fit_transform(Doc2VecModelData[Doc2VecModelData['Category']==cat][['tsne-2d-one']])\n\n model_y=MinMaxScaler([newrange[newrange['Category']==cat].Min_Y.values[0],newrange[newrange['Category']==cat].Max_Y.values[0]])\n Doc2VecModelData.loc[Doc2VecModelData['Category']==cat,'tsne-2d-two']=model_y.fit_transform(Doc2VecModelData[Doc2VecModelData['Category']==cat][['tsne-2d-two']])\n", "_____no_output_____" ], [ "cat='Life Sciences'#'Engineering Sciences'#'Life Sciences'#'Humanities and Social Sciences'#'Life Sciences'#'\nplt.figure(figsize=(13,8))\nsns.scatterplot(\n x=\"tsne-2d-one\", y=\"tsne-2d-two\",\n hue=\"Category_1\",\n data=Doc2VecModelData[Doc2VecModelData.Category==cat],\n legend=\"full\",\n# style='Category_1',\n alpha=0.8\n );", "_____no_output_____" ], [ "plt.figure(figsize=(13,8))\nsns.scatterplot(\n x=\"tsne-2d-one\", y=\"tsne-2d-two\",\n hue=\"Category_1\",\n data=Doc2VecModelData,\n legend=\"full\",\n style='Category',\n alpha=0.8\n );", "_____no_output_____" ], [ "def label_genarator(input):\n if((input.Category==input.Category_1) or (input.ISOForestCluster==1)):\n return ''#'Category : '+input.Category\n else:\n if((input.Category_3_Values==0) and (input.Category_2_Values==0)):\n return '('+input.Category_1+' '+str(round(input.Category_1_Values*100))+'%'+')'\n elif((input.Category_3_Values==0) and (input.Category_2_Values!=0)):\n return '('+input.Category_1+' '+str(round(input.Category_1_Values*100))+'%, '+input.Category_2+' '+str(round(input.Category_2_Values*100))+'%)'\n else:\n return '('+input.Category_1+' '+str(round(input.Category_1_Values*100))+'%, '+input.Category_2+' '+str(round(input.Category_2_Values*100))+'%, '+input.Category_3+' '+str(round(input.Category_3_Values*100))+'%)'\n \n \nReport_extrat=pd.concat([NewMergedDSAligned2[['Name','Institution','FundingFrom','FundingEnd', 'Category','Category_1_Values','Category_2_Values','Category_3_Values','Category_1','Category_2','Category_3','ISOForestCluster']],Doc2VecModelData[['tsne-2d-one', 'tsne-2d-two']]], axis=1)\nReport_extrat['ProjectURL']=NewMergedDSAligned2.SubUrl.apply(lambda x:'https://gepris.dfg.de'+x)\nReport_extrat['label']=Report_extrat.apply(label_genarator, axis=1)\nReport_extrat['interdiscipilinary']=False\nReport_extrat.loc[(Report_extrat.label!='') & (Report_extrat['ISOForestCluster']!=1),'interdiscipilinary']=True", "_____no_output_____" ], [ "Report_extrat['color']=Report_extrat['Category']\nReport_extrat.loc[Report_extrat['interdiscipilinary'],'color']=Report_extrat.loc[Report_extrat['interdiscipilinary'],'Category_1']", "_____no_output_____" ], [ "Report_extrat.to_csv(Path+'Report_WEPCAISOForestFindingsKMeansV3.csv', index=False)\nnewrange.to_csv(Path+'CATRANGE_WEPCAISOForestFindingsKMeansV3.csv', index=False)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0bf2d0221b519b9260eec028e54b5a88c8d180
101,696
ipynb
Jupyter Notebook
tests/QuickTest.ipynb
wxted/ERDC_MOOSE
a7cb8e67846c3795aef84cbdd2d24bea39742a36
[ "MIT" ]
null
null
null
tests/QuickTest.ipynb
wxted/ERDC_MOOSE
a7cb8e67846c3795aef84cbdd2d24bea39742a36
[ "MIT" ]
null
null
null
tests/QuickTest.ipynb
wxted/ERDC_MOOSE
a7cb8e67846c3795aef84cbdd2d24bea39742a36
[ "MIT" ]
null
null
null
1,081.87234
99,752
0.960038
[ [ [ "## quick import test to make sure the modules have loaded properly\nfrom MOOSEplot import geoplot as gp\nfrom MOOSEplot import plotCommon as pc\nfrom MOOSEfunctions import ColormapLoad\nimport MOOSEpost.wrfpost as WP\n\nprint(\"All modules successfully loaded\")", "All modules successfully loaded\n" ], [ "%matplotlib inline\n## THIS NOTEBOOK PROVIDES A QUICK TEST plotting a METAR time series for Lebanon NH for the 2020 winter.\nfrom MOOSEplot import MeteoPlot as MP\n\nLEB=MP.MeteoPlot(stn='LEB',input_path='../metar_data/')\n\nfig=LEB.QuickPlot()", "Reading Data For: Observations for LEBANON MUNICIPAL, NH (LEB)\n\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
cb0bf3392a15b8b46b120a334ba1a9bb9613f4dd
86,160
ipynb
Jupyter Notebook
pipelining/exp-cscv/exp-cscv_cscv_1w_ale_plotting.ipynb
ZeruiW/s2search
cb0539b9594d7afe12e64c0b4ada4fb29c793060
[ "Apache-2.0" ]
2
2022-02-07T16:08:04.000Z
2022-03-27T19:29:33.000Z
pipelining/exp-cscv/exp-cscv_cscv_1w_ale_plotting.ipynb
youyinnn/s2search
f965a595386b24ffab0385b860a1028e209fde86
[ "Apache-2.0" ]
1
2022-03-30T17:50:32.000Z
2022-03-30T17:50:32.000Z
pipelining/exp-cscv/exp-cscv_cscv_1w_ale_plotting.ipynb
ZeruiW/s2search
cb0539b9594d7afe12e64c0b4ada4fb29c793060
[ "Apache-2.0" ]
1
2022-03-14T19:44:47.000Z
2022-03-14T19:44:47.000Z
275.271565
42,426
0.909877
[ [ [ "<a href=\"https://colab.research.google.com/github/DingLi23/s2search/blob/pipelining/pipelining/exp-cscv/exp-cscv_cscv_1w_ale_plotting.ipynb\" target=\"_blank\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "### Experiment Description\n\n\n\n> This notebook is for experiment \\<exp-cscv\\> and data sample \\<cscv\\>.", "_____no_output_____" ], [ "### Initialization", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\nimport numpy as np, sys, os\nin_colab = 'google.colab' in sys.modules\n# fetching code and data(if you are using colab\nif in_colab:\n !rm -rf s2search\n !git clone --branch pipelining https://github.com/youyinnn/s2search.git\n sys.path.insert(1, './s2search')\n %cd s2search/pipelining/exp-cscv/\n\npic_dir = os.path.join('.', 'plot')\nif not os.path.exists(pic_dir):\n os.mkdir(pic_dir)\n", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ] ], [ [ "### Loading data", "_____no_output_____" ] ], [ [ "\nsys.path.insert(1, '../../')\nimport numpy as np, sys, os, pandas as pd\nfrom getting_data import read_conf\nfrom s2search_score_pdp import pdp_based_importance\n\nsample_name = 'cscv'\n\nf_list = [\n 'title', 'abstract', 'venue', 'authors', \n 'year', \n 'n_citations'\n ]\nale_xy = {}\nale_metric = pd.DataFrame(columns=['feature_name', 'ale_range', 'ale_importance', 'absolute mean'])\n\nfor f in f_list:\n file = os.path.join('.', 'scores', f'{sample_name}_1w_ale_{f}.npz')\n if os.path.exists(file):\n nparr = np.load(file)\n quantile = nparr['quantile']\n ale_result = nparr['ale_result']\n values_for_rug = nparr.get('values_for_rug')\n \n ale_xy[f] = {\n 'x': quantile,\n 'y': ale_result,\n 'rug': values_for_rug,\n 'weird': ale_result[len(ale_result) - 1] > 20\n }\n \n if f != 'year' and f != 'n_citations':\n ale_xy[f]['x'] = list(range(len(quantile)))\n ale_xy[f]['numerical'] = False\n else:\n ale_xy[f]['xticks'] = quantile\n ale_xy[f]['numerical'] = True\n \n ale_metric.loc[len(ale_metric.index)] = [f, np.max(ale_result) - np.min(ale_result), pdp_based_importance(ale_result, f), np.mean(np.abs(ale_result))] \n \n # print(len(ale_result))\n \nprint(ale_metric.sort_values(by=['ale_importance'], ascending=False))\nprint()\n", " feature_name ale_range ale_importance absolute mean\n2 venue 17.754743 6.277717 4.471950\n1 abstract 17.697546 5.606984 3.872777\n0 title 13.082375 2.234130 0.849395\n3 authors 7.910586 1.118726 0.307904\n4 year 1.361933 0.458115 0.402660\n5 n_citations 0.927669 0.244685 0.202764\n\n" ] ], [ [ "### ALE Plots", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.ticker import MaxNLocator\n\ncategorical_plot_conf = [\n {\n 'xlabel': 'Title',\n 'ylabel': 'ALE',\n 'ale_xy': ale_xy['title']\n },\n {\n 'xlabel': 'Abstract',\n 'ale_xy': ale_xy['abstract']\n }, \n {\n 'xlabel': 'Authors',\n 'ale_xy': ale_xy['authors'],\n # 'zoom': {\n # 'inset_axes': [0.3, 0.3, 0.47, 0.47],\n # 'x_limit': [89, 93],\n # 'y_limit': [-1, 14],\n # }\n }, \n {\n 'xlabel': 'Venue',\n 'ale_xy': ale_xy['venue'],\n # 'zoom': {\n # 'inset_axes': [0.3, 0.3, 0.47, 0.47],\n # 'x_limit': [89, 93],\n # 'y_limit': [-1, 13],\n # }\n },\n]\n\nnumerical_plot_conf = [\n {\n 'xlabel': 'Year',\n 'ylabel': 'ALE',\n 'ale_xy': ale_xy['year'],\n # 'zoom': {\n # 'inset_axes': [0.15, 0.4, 0.4, 0.4],\n # 'x_limit': [2019, 2023],\n # 'y_limit': [1.9, 2.1],\n # },\n },\n {\n 'xlabel': 'Citations',\n 'ale_xy': ale_xy['n_citations'],\n # 'zoom': {\n # 'inset_axes': [0.4, 0.65, 0.47, 0.3],\n # 'x_limit': [-1000.0, 12000],\n # 'y_limit': [-0.1, 1.2],\n # },\n },\n]\n\ndef pdp_plot(confs, title):\n fig, axes_list = plt.subplots(nrows=1, ncols=len(confs), figsize=(20, 5), dpi=100)\n subplot_idx = 0\n plt.suptitle(title, fontsize=20, fontweight='bold')\n # plt.autoscale(False)\n for conf in confs:\n axes = axes if len(confs) == 1 else axes_list[subplot_idx]\n \n sns.rugplot(conf['ale_xy']['rug'], ax=axes, height=0.02)\n\n axes.axhline(y=0, color='k', linestyle='-', lw=0.8)\n axes.plot(conf['ale_xy']['x'], conf['ale_xy']['y'])\n axes.grid(alpha = 0.4)\n\n # axes.set_ylim([-2, 20])\n axes.xaxis.set_major_locator(MaxNLocator(integer=True))\n axes.yaxis.set_major_locator(MaxNLocator(integer=True))\n \n if ('ylabel' in conf):\n axes.set_ylabel(conf.get('ylabel'), fontsize=20, labelpad=10)\n \n # if ('xticks' not in conf['ale_xy'].keys()):\n # xAxis.set_ticklabels([])\n\n axes.set_xlabel(conf['xlabel'], fontsize=16, labelpad=10)\n \n if not (conf['ale_xy']['weird']):\n if (conf['ale_xy']['numerical']):\n axes.set_ylim([-1.5, 1.5])\n pass\n else:\n axes.set_ylim([-7, 19])\n pass\n \n if 'zoom' in conf:\n axins = axes.inset_axes(conf['zoom']['inset_axes'])\n axins.xaxis.set_major_locator(MaxNLocator(integer=True))\n axins.yaxis.set_major_locator(MaxNLocator(integer=True))\n axins.plot(conf['ale_xy']['x'], conf['ale_xy']['y'])\n axins.set_xlim(conf['zoom']['x_limit'])\n axins.set_ylim(conf['zoom']['y_limit'])\n axins.grid(alpha=0.3)\n rectpatch, connects = axes.indicate_inset_zoom(axins)\n connects[0].set_visible(False)\n connects[1].set_visible(False)\n connects[2].set_visible(True)\n connects[3].set_visible(True)\n \n subplot_idx += 1\n\npdp_plot(categorical_plot_conf, f\"ALE for {len(categorical_plot_conf)} categorical features\")\n# plt.savefig(os.path.join('.', 'plot', f'{sample_name}-1wale-categorical.png'), facecolor='white', transparent=False, bbox_inches='tight')\n\npdp_plot(numerical_plot_conf, f\"ALE for {len(numerical_plot_conf)} numerical features\")\n# plt.savefig(os.path.join('.', 'plot', f'{sample_name}-1wale-numerical.png'), facecolor='white', transparent=False, bbox_inches='tight')\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb0c150579708cc47878a01eab022d54dd6bda33
30,707
ipynb
Jupyter Notebook
notebooks/collimator_sameBlade_threeSections_DAC.ipynb
Fahima-Islam/c3dp
f8eb9235dd4fba7edcc0642ed68e325346ff577e
[ "MIT" ]
null
null
null
notebooks/collimator_sameBlade_threeSections_DAC.ipynb
Fahima-Islam/c3dp
f8eb9235dd4fba7edcc0642ed68e325346ff577e
[ "MIT" ]
1
2019-05-03T20:16:49.000Z
2019-05-03T20:16:49.000Z
notebooks/collimator_sameBlade_threeSections_DAC.ipynb
Fahima-Islam/c3dp
f8eb9235dd4fba7edcc0642ed68e325346ff577e
[ "MIT" ]
null
null
null
38.47995
209
0.608102
[ [ [ "import mcvine \nfrom instrument.geometry.pml import weave\nfrom instrument.geometry import operations,shapes\nimport math", "_____no_output_____" ], [ "import os, sys\nparent_dir = os.path.abspath(os.pardir)\nlibpath = os.path.join(parent_dir, 'c3dp_source')\nfigures_path = os.path.join (parent_dir, 'figures')\nsample_path = os.path.join (parent_dir, 'sample')\nif not libpath in sys.path:\n sys.path.insert(0, libpath)\n# sys.path.insert(0, '/home/fi0/python3/lib/python3.5/site-packages')", "_____no_output_____" ], [ "import SCADGen.Parser\nfrom collimator_zigzagBlade_old import Collimator_geom\nfrom DAC_geo import DAC\n# import viewscad\n# import solid", "_____no_output_____" ], [ "scad_flag = True ########CHANGE CAD FLAG HERE\n\nif scad_flag is True:\n savepath = figures_path\nelse:\n savepath = sample_path", "_____no_output_____" ], [ "dac=DAC()\nanvil=dac.anvil()\n\n# gasket=dac.gasket()\n# gasket_holder=dac.gasket_holder()\nsorrounding_gasket=dac.sorrounding_gasket()\ngasket_at_sample = dac.gasket_contact_with_sample()\ngasket_at_anvil = dac.gasket_contact_with_anvil()\nsnap_seat=dac.snap_seat()\nvision_seat = dac.vision_seat()\nsnap_piston=dac.snap_piston()\nvision_piston = dac.vision_piston()\nsnap_seat_pistion=dac.snap_seat_piston()\nvision_seat_pistion=dac.vision_seat_piston()\nbar=dac.body_bar()\nsample=dac.sample()", "('pavilion from center', 1.1503684072210096)\n('pavilion from center', 1.1503684072210096)\n('pavilion from center', 1.1503684072210096)\n('chamfer_top_length', 18.639999999999997)\n('chamfer_top_length', 18.639999999999997)\n('chamfer_top_length', 18.639999999999997)\n('chamfer_top_length', 18.639999999999997)\n" ], [ "cell=operations.unite(operations.unite(operations.unite(anvil,gasket_at_anvil),gasket_at_sample),\n vision_seat_pistion)", "_____no_output_____" ], [ "colimator_front_end_from_center= 74. #though the cell diameter is 3 mm, I can not put the collimator at 3 mm because\n #if I put at 3 mm, there will be no blade (only full of channels as the minimum\n # channel thickness is 3 mm) \nlength_of_each_part=60.", "_____no_output_____" ], [ "########################### LAST PART COMPONENTS ##############################\ncoll1_length=length_of_each_part\nchannel1_length=length_of_each_part\nmin_channel_wall_thickness=1.\nminimum_channel_size = 3.\ncoll1_height_detector=150.\ncoll1_width_detector=60*2.\n\ncoll1_height_detector_right=coll1_height_detector+20.\n\n\ncoll1_front_end_from_center=colimator_front_end_from_center+(2.*length_of_each_part)\nprint ('last collimator front end from center', coll1_front_end_from_center)\ncoll1_length_fr_center=coll1_front_end_from_center+coll1_length\nprint ('last collimator back end from center', coll1_length_fr_center)", "('last collimator front end from center', 194.0)\n('last collimator back end from center', 254.0)\n" ], [ "import numpy as np\nwall_angular_thickness=2*(np.rad2deg(np.arctan((min_channel_wall_thickness/2.)/coll1_length_fr_center)))\nprint ('wall angular thickness', wall_angular_thickness)\n\nchannel_angular_thickness=2*(np.rad2deg(np.arctan((minimum_channel_size/2.)/coll1_length_fr_center)))\nprint ('channel angular thickness', channel_angular_thickness)", "('wall angular thickness', 0.22557364372463715)\n('channel angular thickness', 0.676713938530517)\n" ], [ "########################### FIRST PART ##############################\ncoll3_length=length_of_each_part\nchannel3_length=length_of_each_part\ncoll3_inner_radius=colimator_front_end_from_center+(0.*length_of_each_part)\nprint ('inner radius',coll3_inner_radius)\ncoll3_outer_radius=coll3_length+coll3_inner_radius\nprint ('outer radius', coll3_outer_radius)\n\n\ncoll3_channel_gap_at_detector = (minimum_channel_size/coll3_inner_radius)*coll3_outer_radius\n\nprint ('minimum channel gap at big end', coll3_channel_gap_at_detector)\n\n\ncoll3_height_detector=(coll1_height_detector/coll1_length_fr_center)*coll3_outer_radius\n\ncoll3_height_detector_right=(coll1_height_detector_right/coll1_length_fr_center)*coll3_outer_radius\n\nprint ('height detector', coll3_height_detector)\ncoll3_width_detector=(coll1_width_detector/coll1_length_fr_center)*coll3_outer_radius #half part\n# coll3_width_detector=(coll1_width_detector/coll1_length_fr_center)*coll3_outer_radius*2 #full part\nprint ('width detector', coll3_width_detector)\n\nvertical_odd_blades= True\nhorizontal_odd_blades =True\ncoll3 = Collimator_geom()\ncoll3.set_constraints(max_coll_height_detector=coll3_height_detector, \n max_coll_width_detector=coll3_width_detector,\n min_channel_wall_thickness=min_channel_wall_thickness,\n max_coll_length=coll3_length, \n min_channel_size=3,\n collimator_front_end_from_center=coll3_inner_radius,\n# remove_vertical_blades_manually =True, #only full part\n# vertical_blade_index_list_toRemove = [7],#only full part\n# remove_horizontal_blades_manually = True, #only full part\n# horizontal_blade_index_list_toRemove = [9], #only full part\n collimator_parts=False,\n no_right_border= True,\n no_top_border = False,\n horizontal_odd_blades = False,\n vertical_odd_blades = False,\n )\n\n\n\n\nhorizontal_acceptance_angle = coll3.horizontal_acceptance_angle\nprint ('horizontal acceptance angle', coll3.horizontal_acceptance_angle)\nprint ('vertical acceptance angle' , coll3.vertical_acceptance_angle)\n\nrotation_angle_for_right_parts = horizontal_acceptance_angle/2.\n\nfist_vertical_number_blades = math.floor (coll3.Vertical_number_channels(channel3_length))\nfist_horizontal_number_blades = math.floor(coll3.Horizontal_number_channels(channel3_length))\n\nprint ('vertical #channels' , fist_vertical_number_blades)\nprint ('horizontal # channels' , fist_horizontal_number_blades)\n\nif fist_vertical_number_blades %2 ==0:\n fist_vertical_number_blades-=1\n \nif fist_horizontal_number_blades %2 ==0:\n fist_horizontal_number_blades-=1\n \n# number_ch_vertical =int(fist_vertical_number_blades)\n# fist_vertical_number_blades=is_prime (number_ch_vertical)\n# if fist_vertical_number_blades is None :\n# fist_vertical_number_blades=find_previous_prime(number_ch_vertical)\n \n# number_ch_horizontal =int(fist_horizontal_number_blades)\n# fist_horizontal_number_blades=is_prime (number_ch_horizontal)\n# if fist_horizontal_number_blades is None :\n# fist_horizontal_number_blades=find_previous_prime(number_ch_horizontal)\n\n \nprint ('modified vertical #channels' , fist_vertical_number_blades)\nprint ('modified horizontal # channels' , fist_horizontal_number_blades)\n\n# if vertical_odd_blades:\n# if fist_vertical_number_blades %2 != 0:\n# fist_vertical_number_blades-= 1\n\n# else:\n# if fist_vertical_number_blades %2 ==0:\n# fist_vertical_number_blades-=1\n \n# if horizontal_odd_blades:\n# if fist_horizontal_number_blades %2 != 0:\n# fist_horizontal_number_blades-= 1\n\n# else:\n# if fist_horizontal_number_blades %2 ==0:\n# fist_horizontal_number_blades-=1\n \n\n# coll3.set_parameters(vertical_number_channels=28,horizontal_number_channels=11*2,\n# channel_length =channel3_length) # the full first part\n# coll3_R.set_parameters(vertical_number_channels=28,horizontal_number_channels=11*2\n# ,channel_length =channel3_length)\n# fist_vertical_number_blades =3\n# fist_horizontal_number_blades =3 \n\ncoll3.set_parameters(vertical_number_channels=fist_vertical_number_blades,horizontal_number_channels=fist_horizontal_number_blades,\n channel_length =channel3_length)\n\nprint ('vertical channel angle :' ,coll3.vertical_channel_angle)\nprint ('horizontal channel angle :' ,coll3.horizontal_channel_angle)\n\ncol_first = coll3.gen_one_col(collimator_Nosupport=True)\n\n\n\n# coli_first_right = coll3_R.gen_collimators(detector_angles=[180.+ 12],multiple_collimator=False, collimator_Nosupport=True)", "('inner radius', 74.0)\n('outer radius', 134.0)\n('minimum channel gap at big end', 5.4324324324324325)\n('height detector', 79.13385826771653)\n('width detector', 63.30708661417323)\n('horizontal acceptance angle', 26.581602822571764)\n('vertical acceptance angle', 32.90116836854697)\n('vertical #channels', 10.0)\n('horizontal # channels', 8.0)\n('modified vertical #channels', 9.0)\n('modified horizontal # channels', 7.0)\n('vertical number of channels: ', 9.0)\n('vertical channel angle :', 3.6556853742829967)\n('horizontal channel angle :', 3.7973718317959664)\n" ], [ "########################## MIDDLE PART #########################################\ntesting_distance = 0\ncoll2_length=length_of_each_part\nchannel2_length=length_of_each_part\ncoll2_inner_radius=colimator_front_end_from_center+(1.*length_of_each_part) + testing_distance\nprint ('inner radius', coll2_inner_radius)\ncoll2_outer_radius=coll2_length+coll2_inner_radius\nprint ('outer radius', coll2_outer_radius)\n\ncoll2_channel_gap_at_detector = (minimum_channel_size/coll2_inner_radius)*coll2_outer_radius\n\nprint ('minimum channel gap at big end', coll2_channel_gap_at_detector)\n\ncoll2_height_detector=(coll1_height_detector/coll1_length_fr_center)*coll2_outer_radius\ncoll2_height_detector_right=(coll1_height_detector_right/coll1_length_fr_center)*coll2_outer_radius\n\nprint ('collimator height at detector', coll2_height_detector)\ncoll2_width_detector=(coll1_width_detector/coll1_length_fr_center)*coll2_outer_radius\nprint ('coll2_width_detector', coll2_width_detector)\n\ncoll2_channel_index_to_remove = int (coll3_channel_gap_at_detector/minimum_channel_size)\nprint ('channel index to remove' ,coll2_channel_index_to_remove)\n\ncoll2 = Collimator_geom()\ncoll2.set_constraints(max_coll_height_detector=coll2_height_detector, \n max_coll_width_detector=coll2_width_detector,\n min_channel_wall_thickness=min_channel_wall_thickness,\n max_coll_length=coll2_length, \n min_channel_size=3,\n collimator_front_end_from_center=coll2_inner_radius,\n collimator_parts=True,\n initial_collimator_horizontal_channel_angle=0.0,\n initial_collimator_vertical_channel_angle= 0.0,\n remove_vertical_blades_manually =True,\n# vertical_blade_index_list_toRemove = [2,5],\n# remove_horizontal_blades_manually =True,\n# horizontal_blade_index_list_toRemove = [2,5],\n no_right_border= True,\n no_top_border = False,\n vertical_even_blades= False,\n horizontal_even_blades= False) \n\n\n\nmiddle_vertical_number_blades = math.floor (coll2.Vertical_number_channels(channel2_length))\nmiddle_horizontal_number_blades = math.floor(coll2.Horizontal_number_channels(channel2_length))\n\nprint ('vertical # chanels', coll2.Vertical_number_channels(channel2_length))\nprint ('horizontal # channels', coll2.Horizontal_number_channels(channel2_length))\n\nif middle_vertical_number_blades %2 ==0:\n middle_vertical_number_blades-=1\n \nif middle_horizontal_number_blades %2 ==0:\n middle_horizontal_number_blades-=1\n\n# number_ch_vertical_middle =int(middle_vertical_number_blades)\n# middle_vertical_number_blades=is_prime (number_ch_vertical_middle)\n# if middle_vertical_number_blades is None :\n# middle_vertical_number_blades=find_previous_prime(number_ch_vertical_middle)\n \n# number_ch_horizontal_middle =int(middle_horizontal_number_blades)\n# middle_horizontal_number_blades=is_prime (number_ch_horizontal_middle)\n# if middle_horizontal_number_blades is None :\n# middle_horizontal_number_blades=find_previous_prime(number_ch_horizontal_middle)\n \nprint ('modified vertical #channels' , middle_vertical_number_blades)\nprint ('modified horizontal # channels' , middle_horizontal_number_blades)\n\ncoll2.set_parameters(vertical_number_channels=(fist_vertical_number_blades),horizontal_number_channels=(fist_horizontal_number_blades), \n channel_length =channel2_length)\n\n\nprint ('vertical channel angle :' ,coll2.vertical_channel_angle)\nprint ('horizontal channel angle :' ,coll2.horizontal_channel_angle)\n\ncoli_middle = coll2.gen_one_col(collimator_Nosupport=True)\n\n# print (coll1_height_detector/coll2_height_detector)", "('inner radius', 134.0)\n('outer radius', 194.0)\n('minimum channel gap at big end', 4.343283582089552)\n('collimator height at detector', 114.56692913385825)\n('coll2_width_detector', 91.65354330708661)\n('channel index to remove', 1)\n('vertical # chanels', 19.23825783600233)\n('horizontal # channels', 15.543026407649354)\n('modified vertical #channels', 19.0)\n('modified horizontal # channels', 15.0)\n('vertical number of channels: ', 9.0)\n('vertical channel angle :', 3.6556853742829967)\n('horizontal channel angle :', 3.7973718317959664)\n" ], [ "#################### LAST PARTS ################################\n\n# coll1_channel_index_to_remove = int (coll2_channel_gap_at_detector/minimum_channel_size)\n# print ('channel index to remove' ,coll1_channel_index_to_remove)\n\ncol_last_left = Collimator_geom()\n\ncol_last_left.set_constraints(max_coll_height_detector=coll1_height_detector, \n max_coll_width_detector=coll1_width_detector,\n min_channel_wall_thickness=min_channel_wall_thickness,\n max_coll_length=coll1_length, \n min_channel_size=3.,\n collimator_front_end_from_center=coll1_front_end_from_center,\n# remove_horizontal_blades_manually =True,\n# horizontal_blade_index_list_toRemove = [2,5,11,14,20,23],\n# remove_vertical_blades_manually =True,\n# vertical_blade_index_list_toRemove = [2,5,11,14,20,23],\n# collimator_parts=True,\n no_right_border= True,\n no_top_border = False,\n vertical_odd_blades=False, \n horizontal_odd_blades=False )\n\n\n\nlast_vertical_number_blades = math.floor (col_last_left.Vertical_number_channels(channel1_length))\nlast_horizontal_number_blades = math.floor(col_last_left.Horizontal_number_channels(channel1_length))\n\nprint ('vertical # channels', col_last_left.Vertical_number_channels(channel1_length))\nprint ('horizontal # channels' , col_last_left.Horizontal_number_channels(channel1_length))\n\n# if last_vertical_number_blades %2 ==0:\n# last_vertical_number_blades-=1\n \n# if last_horizontal_number_blades %2 ==0:\n# last_horizontal_number_blades-=1\n\n# number_ch_vertical_last =int(last_vertical_number_blades)\n# last_vertical_number_blades=is_prime (number_ch_vertical_last)\n# if last_vertical_number_blades is None :\n# last_vertical_number_blades=find_previous_prime(number_ch_vertical_last)\n \n# number_ch_horizontal_last =int(last_horizontal_number_blades)\n# last_horizontal_number_blades=is_prime (number_ch_horizontal_last)\n# if last_horizontal_number_blades is None :\n# last_horizontal_number_blades=find_previous_prime(number_ch_horizontal_last)\n\nprint ('modified vertical #channels' , last_vertical_number_blades)\nprint ('modified horizontal # channels' , last_horizontal_number_blades)\n\n\ncol_last_left.set_parameters(vertical_number_channels=fist_vertical_number_blades,horizontal_number_channels=fist_horizontal_number_blades,\n channel_length =channel1_length)\n\n\nprint ('vertical channel angle :' ,col_last_left.vertical_channel_angle)\nprint ('horizontal channel angle :' ,col_last_left.horizontal_channel_angle)\n\ncolilast = col_last_left.gen_one_col(collimator_Nosupport=True)\n", "('vertical # channels', 27.85132184343869)\n('horizontal # channels', 22.501716870141664)\n('modified vertical #channels', 27.0)\n('modified horizontal # channels', 22.0)\n('vertical number of channels: ', 9.0)\n('vertical channel angle :', 3.6556853742829967)\n('horizontal channel angle :', 3.7973718317959664)\n" ], [ "pyr_lateral_middle = shapes.pyramid(\n thickness='%s *mm' % coll1_height_detector_right,\n # height='%s *mm' % (height),\n height='%s *mm' % (coll1_length_fr_center),\n width='%s *mm' % coll1_width_detector)\n\npyr_lateral_middle = operations.rotate(pyr_lateral_middle, transversal=1, angle='%s *degree' % (90))\npyr_lateral_left_middle = operations.rotate(pyr_lateral_middle, vertical=\"1\",\n angle='%s*deg' % (180 + 180-rotation_angle_for_right_parts-wall_angular_thickness-channel_angular_thickness-0.03)) \n\n\npyr_lateral_right_middle = operations.rotate(pyr_lateral_middle, vertical=\"1\",\n angle='%s*deg' % (180 - (180-rotation_angle_for_right_parts+wall_angular_thickness+channel_angular_thickness+0.15)))\n\n# pyr_lateral_right_last = operations.rotate(pyr_lateral, vertical=\"1\",\n# angle='%s*deg' % (180 - (180-rotation_angle_for_right_parts/2.))) ", "_____no_output_____" ], [ "factor = 10\npyr_lateral_last = shapes.pyramid(\n thickness='%s *mm' % coll1_height_detector_right,\n # height='%s *mm' % (height),\n height='%s *mm' % (coll1_length_fr_center+factor),\n width='%s *mm' % coll1_width_detector)\n\n\nwall_angular_thickness_last=2*(np.rad2deg(np.arctan((min_channel_wall_thickness/2.)/(coll1_length_fr_center+10))))\nprint ('wall angular thickness sudo', wall_angular_thickness_last)\n\nchannel_angular_thickness_last=2*(np.rad2deg(np.arctan((minimum_channel_size/2.)/(coll1_length_fr_center+10))))\nprint ('channel angular thickness sudo', channel_angular_thickness_last)\n\n\npyr_lateral_last = operations.rotate(pyr_lateral_last, transversal=1, angle='%s *degree' % (90))\npyr_lateral_left_last = operations.rotate(pyr_lateral_last, vertical=\"1\",\n angle='%s*deg' % (180 + 180-rotation_angle_for_right_parts+wall_angular_thickness-channel_angular_thickness+0.5))\n\n\n# pyr_lateral_right_last = operations.rotate(pyr_lateral_last, vertical=\"1\",\n# angle='%s*deg' % (180 - (180-rotation_angle_for_right_parts+(wall_angular_thickness*wall_angular_thickness_last*factor)+channel_angular_thickness-0.12)))\n\n\npyr_lateral_right_last = operations.rotate(pyr_lateral_last, vertical=\"1\",\n angle='%s*deg' % (180 - (180-rotation_angle_for_right_parts+0.75)))\n\n\n# pyr_lateral_right_last = operations.rotate(pyr_lateral, vertical=\"1\",\n# angle='%s*deg' % (180 - (180-rotation_angle_for_right_parts/2.))) ", "('wall angular thickness sudo', 0.21702920835777764)\n('channel angular thickness sudo', 0.6510813973185968)\n" ], [ "# both=operations.unite(coli_middle_left, colilast_left)\n# both= operations.unite(operations.unite\n# (operations.unite(operations.unite(operations.unite(colilast_left, col_first), colilast_right), \n# coli_first_right), coli_middle_left), coli_middle_right)\nwhole= operations.unite(operations.unite(colilast, col_first), \n coli_middle)\nwhole_first_part = col_first\nwhole_middle_part = coli_middle\nwhole_last_part = colilast\n\n\nfirst_middle = operations.unite (col_first, coli_middle)\nmiddle_last = operations.unite (coli_middle, colilast)\n\n\n# first_left = operations.subtract(whole_first_part, pyr_lateral_right)\n\n# first_right = operations.subtract(whole_first_part, pyr_lateral_left)\n\nmiddle_left = operations.subtract(whole_middle_part, pyr_lateral_right_middle)\n\nmiddle_right = operations.subtract(whole_middle_part, pyr_lateral_left_middle)\n\n\nlast_left = operations.subtract(whole_last_part, pyr_lateral_right_last)\n\nlast_right = operations.subtract(whole_last_part, pyr_lateral_left_last)\n\n\nmiddle_left_last_left = operations.unite( middle_left, last_left)\n\nmiddle_right_last_right = operations.unite(middle_right, last_right)\n\nwhole_joint = operations.unite(operations.unite(middle_left_last_left, middle_right_last_right), whole_first_part)\n\nwhole_last_joint = operations.unite(last_left, last_right)\n\nwhole_middle_joint = operations.unite(middle_left, middle_right)\n\n# both=operations.unite(coli_middle, coli2R)\n# both=operations.unite(operations.unite(operations.unite(coli2, coli3), coli2R), coli3R)\n\ncell_colli = operations.unite(cell, whole)\n\nfile='DAC_colli'\nfilename='%s.xml'%(file)\noutputfile=os.path.join(savepath, filename)\nwith open (outputfile,'wt') as file_h:\n weave(cell_colli,file_h, print_docs = False)\n \n# file='last_right_part_New'\n# filename='%s.xml'%(file)\n# outputfile=os.path.join(savepath, filename)\n# with open (outputfile,'wt') as file_h:\n# weave(last_right,file_h, print_docs = False)\n \n# file='whole_last_joint_part_New'\n# filename='%s.xml'%(file)\n# outputfile=os.path.join(savepath, filename)\n# with open (outputfile,'wt') as file_h:\n# weave(whole_last_joint,file_h, print_docs = False)\n\n# file='middle_left_part_New'\n# filename='%s.xml'%(file)\n# outputfile=os.path.join(savepath, filename)\n# with open (outputfile,'wt') as file_h:\n# weave(middle_left,file_h, print_docs = False)\n \n# file='middle_right_part_New'\n# filename='%s.xml'%(file)\n# outputfile=os.path.join(savepath, filename)\n# with open (outputfile,'wt') as file_h:\n# weave(middle_right,file_h, print_docs = False)\n \n# file='whole_middle_joint_part_New'\n# filename='%s.xml'%(file)\n# outputfile=os.path.join(savepath, filename)\n# with open (outputfile,'wt') as file_h:\n# weave(whole_middle_joint,file_h, print_docs = False)", "_____no_output_____" ], [ "p = SCADGen.Parser.Parser(outputfile)\np.createSCAD()\ntest = p.rootelems[0]", "_____no_output_____" ], [ "cadFile_name='%s.scad'%(file)\ncad_file_path=os.path.abspath(os.path.join(savepath, cadFile_name))", "_____no_output_____" ], [ "cad_file_path", "_____no_output_____" ], [ "!vglrun openscad {cad_file_path}", "QXcbWindow: Unhandled client message: \"_GTK_LOAD_ICONTHEMES\"\r\n" ] ], [ [ "# ", "_____no_output_____" ] ] ]
[ "code", "markdown" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cb0c26e56175f20fb94db6f5ad18d9b991849ab2
15,303
ipynb
Jupyter Notebook
notebooks/figures/data/replace_path_cdg_to_campaign.ipynb
mgrover1/cesm2-marbl-book
670375dd5ed800afd4a86de9871a7d44c535a3f0
[ "Apache-2.0" ]
null
null
null
notebooks/figures/data/replace_path_cdg_to_campaign.ipynb
mgrover1/cesm2-marbl-book
670375dd5ed800afd4a86de9871a7d44c535a3f0
[ "Apache-2.0" ]
4
2021-06-10T15:22:33.000Z
2021-06-21T19:29:03.000Z
notebooks/figures/data/replace_path_cdg_to_campaign.ipynb
mgrover1/cesm2-marbl-book
670375dd5ed800afd4a86de9871a7d44c535a3f0
[ "Apache-2.0" ]
1
2021-05-18T18:41:57.000Z
2021-05-18T18:41:57.000Z
38.546599
93
0.394367
[ [ [ "import os\nimport pandas as pd", "_____no_output_____" ], [ "df = pd.read_csv('campaign-cesm2-cmip6-timeseries.csv.gz')\ndf", "_____no_output_____" ], [ "df.loc[312498] #path.str.find('/glade/collections/cdg')", "_____no_output_____" ], [ "df['path'] = df.path.str.replace(\n '/glade/collections/cdg', '/glade/campaign/collections/cmip/CMIP6', regex=False,\n)", "_____no_output_____" ], [ "df.loc[312498]", "_____no_output_____" ], [ "df.to_csv('campaign-cesm2-cmip6-timeseries-NO-CDG.csv.gz')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cb0c38f6a4637c9c602cef7e5717ad2026472e20
194,076
ipynb
Jupyter Notebook
tools/revenues/.ipynb_checkpoints/Preparing Data 2015-16-checkpoint.ipynb
MyanmarEITI/meiti-data
d1b6c3932fd037f730f5f7e490eb0e7b3ac0c311
[ "CC-BY-3.0" ]
null
null
null
tools/revenues/.ipynb_checkpoints/Preparing Data 2015-16-checkpoint.ipynb
MyanmarEITI/meiti-data
d1b6c3932fd037f730f5f7e490eb0e7b3ac0c311
[ "CC-BY-3.0" ]
null
null
null
tools/revenues/.ipynb_checkpoints/Preparing Data 2015-16-checkpoint.ipynb
MyanmarEITI/meiti-data
d1b6c3932fd037f730f5f7e490eb0e7b3ac0c311
[ "CC-BY-3.0" ]
null
null
null
40.996198
186
0.400019
[ [ [ "import pandas as pd\nimport json\nimport numpy as np", "_____no_output_____" ], [ "df = pd.read_csv('data/2015-16_gems_jade.csv')", "_____no_output_____" ], [ "# df = df[df['country'] == \"Myanmar\"]", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "## Clean data", "_____no_output_____" ] ], [ [ "df_gemsjade = df\n\ndf_gemsjade.rename(columns={'company_name': 'Company_name_cl'}, inplace=True)\n\ndf_gemsjade['type'] = 'entity'\ndf_gemsjade['target_type'] = ''", "_____no_output_____" ], [ "df_gemsjade.head()", "_____no_output_____" ], [ "append_dict_others = [{'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', \n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Production Royalties', 'value_reported': 7627853015 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Sale Split', 'value_reported': 122565309 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Sales Royalties', 'value_reported': 1593381858 },\n\n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Service Fees', 'value_reported': 682734625 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Permit Fees', 'value_reported': 89494475808 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Incentive Fees', 'value_reported': 213344561 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Other significant payments', 'value_reported': 2637093845 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Emporium Fees / Sale Fees', 'value_reported': 2987472820 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Sale Split', 'value_reported': 5272471367 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Myanmar Gems Enterprise',\n 'name_of_revenue_stream': 'Commercial Tax', 'value_reported': 41353324562 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Customs Department',\n 'name_of_revenue_stream': 'Customs Duties', 'value_reported': 2985923707 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Internal Revenue Department',\n 'name_of_revenue_stream': 'Commercial Tax', 'value_reported': 244080055733 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Internal Revenue Department',\n 'name_of_revenue_stream': 'Royalties', 'value_reported': 76123095911 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Internal Revenue Department',\n 'name_of_revenue_stream': 'Income Tax', 'value_reported': 4377920086 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Internal Revenue Department',\n 'name_of_revenue_stream': 'Withholding Tax', 'value_reported': 51281036 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity',\n 'paid_to': 'Internal Revenue Department',\n 'name_of_revenue_stream': 'Capital Gains Tax', 'value_reported': 33708244 }\n ]\n\nothers_df = pd.DataFrame(append_dict_others)\n#others_df['total_payments'] = others_df['value_reported']\ndf_gemsjade = pd.concat([df_gemsjade, others_df])\ndf_gemsjade", "_____no_output_____" ], [ "df_gemsjade['name_of_revenue_stream'] = df_gemsjade['name_of_revenue_stream'].replace({'Other significant payments (&gt; 50,000 USD)': 'Other significant payments (> 50,000 USD)'})", "_____no_output_____" ], [ "company_totals = df_gemsjade.pivot_table(index=['Company_name_cl'], aggfunc='sum')['value_reported']\ncompany_totals = company_totals.to_frame()\ncompany_totals.rename(columns={'value_reported': 'total_payments'}, inplace=True)\ncompany_totals.reset_index(level=0, inplace=True)\ncompany_totals.sort_values(by=['total_payments'], ascending = False, inplace=True)\ncompany_totals", "_____no_output_____" ], [ "df_gemsjade = pd.merge(df_gemsjade, company_totals, on='Company_name_cl')", "_____no_output_____" ] ], [ [ "## Remove negative payments for Sankey", "_____no_output_____" ] ], [ [ "df_gemsjade = df_gemsjade[df_gemsjade[\"value_reported\"] > 0]\ndf_gemsjade = df_gemsjade.sort_values(by=['total_payments'], ascending=False)\ndf_gemsjade.drop(['Unnamed: 0'], axis=1)\ndf_gemsjade", "_____no_output_____" ], [ "df_gemsjade_summary = df_gemsjade[df_gemsjade['Company_name_cl'] != 'Companies not in EITI Reconciliation']\ndf_gemsjade_summary = df_gemsjade_summary.groupby(['name_of_revenue_stream','paid_to','target_type','type']).sum().reset_index()\ndf_gemsjade_summary['Company_name_cl'] = 'Companies in EITI Reconciliation'\ndf_gemsjade_summary = df_gemsjade[df_gemsjade['Company_name_cl'] == 'Companies not in EITI Reconciliation'] \\\n .append(df_gemsjade_summary)\ndf_gemsjade_summary", "_____no_output_____" ] ], [ [ "## Prepare Source-Target-Value dataframe", "_____no_output_____" ] ], [ [ "\nlinks_companies = pd.DataFrame(columns=['source','target','value','type'])", "_____no_output_____" ], [ "to_append = df_gemsjade.groupby(['name_of_revenue_stream','paid_to'],as_index=False)['type','value_reported','total_payments'].sum()\n\n#to_append[\"target\"] = \"Myanmar Gems Enterprise\"\nto_append.rename(columns = {'name_of_revenue_stream':'source', 'value_reported' : 'value', 'paid_to': 'target'}, inplace = True)\n\nto_append = to_append.sort_values(by=['value'], ascending = False)\nto_append['target_type'] = 'entity'\n\nlinks_companies = pd.concat([links_companies,to_append])\n\nprint(to_append['value'].sum())\nlinks_companies", "695668986359.0\n" ], [ "## Page 239 of 2015-16 Report. Appendix 8: SOEs reconciliation sheets\nappend_dict_transfers = [{'source': 'Myanmar Gems Enterprise', 'type': 'entity',\n 'target': 'Corporate Income Tax (Inter-Government)', 'value': 53788313000 },\n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity', \n 'target': 'Commercial Tax (Inter-Government)', 'value': 15000000 },\n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity',\n 'target': 'Production Royalties (Inter-Government)', 'value': 17249087176 },\n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity', \n 'target': 'State Contribution (Inter-Government)', 'value': 46833942000 },\n \n \n {'source': 'Corporate Income Tax (Inter-Government)', 'target_type': 'entity',\n 'target': 'Internal Revenue Department', 'value': 53788313000 },\n \n {'source': 'Commercial Tax (Inter-Government)', 'target_type': 'entity', \n 'target': 'Internal Revenue Department', 'value': 15000000 },\n \n {'source': 'Production Royalties (Inter-Government)', 'target_type': 'entity',\n 'target': 'Department of Mines', 'value': 17249087176 },\n \n {'source': 'State Contribution (Inter-Government)', 'target_type': 'entity', \n 'target': 'Ministry of Planning and Finance', 'value': 46833942000 },\n \n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity',\n 'target': 'Other Accounts', 'value': 107705106000 },\n \n \n {'source': 'Other Accounts', 'target_type': 'entity',\n 'target': 'Ministry of Planning and Finance', 'value': 107705106000 },\n \n {'source': 'Internal Revenue Department', 'type': 'entity', 'target_type': 'entity',\n 'target': 'Ministry of Planning and Finance', 'value': 393194500968 }]\n\n\n\nappend_dict_transfers_df = pd.DataFrame(append_dict_transfers)\n\nlinks_summary = pd.concat([links_companies, append_dict_transfers_df])\nlinks_govt = append_dict_transfers_df\n#links = pd.concat([links, append_dict_transfers_df])", "_____no_output_____" ], [ "\nto_append = df_gemsjade.groupby(['name_of_revenue_stream','Company_name_cl','type'],as_index=False) \\\n ['value_reported','total_payments'] \\\n .agg({'value_reported':sum,'total_payments':'first'})\nto_append.rename(columns = {'Company_name_cl':'source','name_of_revenue_stream':'target', 'value_reported' : 'value'}, inplace = True)\nto_append = to_append.sort_values(by=['total_payments'], ascending = False)\nlinks_companies = pd.concat([links_companies,to_append])\n\nprint(to_append['value'].sum())\n#links\nto_append", "695668986359.0\n" ], [ "\nto_append = df_gemsjade_summary.groupby(['name_of_revenue_stream','Company_name_cl','type'],as_index=False) \\\n ['value_reported','total_payments'] \\\n .agg({'value_reported':sum,'total_payments':'first'})\nto_append.rename(columns = {'Company_name_cl':'source','name_of_revenue_stream':'target', 'value_reported' : 'value'}, inplace = True)\nto_append = to_append.sort_values(by=['total_payments'], ascending = False)\nlinks_summary = pd.concat([links_summary,to_append])\nlinks_summary", "_____no_output_____" ], [ "def prep_nodes_links(links):\n unique_source = links['source'].unique()\n unique_targets = links['target'].unique()\n\n unique_source = pd.merge(pd.DataFrame(unique_source), links, left_on=0, right_on='source', how='left')\n unique_source = unique_source.filter([0,'type'])\n unique_targets = pd.merge(pd.DataFrame(unique_targets), links, left_on=0, right_on='target', how='left')\n unique_targets = unique_targets.filter([0,'target_type'])\n unique_targets.rename(columns = {'target_type':'type'}, inplace = True)\n\n unique_list = pd.concat([unique_source[0], unique_targets[0]]).unique()\n\n unique_list = pd.merge(pd.DataFrame(unique_list), \\\n pd.concat([unique_source, unique_targets]), left_on=0, right_on=0, how='left')\n\n unique_list.drop_duplicates(subset=0, keep='first', inplace=True)\n\n replace_dict = {k: v for v, k in enumerate(unique_list[0])}\n unique_list\n return [unique_list,replace_dict]\n\n\n#unique_list = pd.concat([links['source'], links['target']]).unique()\n#replace_dict = {k: v for v, k in enumerate(unique_list)}\n", "_____no_output_____" ], [ "[unique_list_summary,replace_dict_summary] = prep_nodes_links(links_summary)\n[unique_list_companies,replace_dict_companies] = prep_nodes_links(links_companies)\n[unique_list_govt,replace_dict_govt] = prep_nodes_links(links_govt)", "_____no_output_____" ], [ "def write_nodes_links(filename,unique_list,replace_dict,links):\n links_replaced = links.replace({\"source\": replace_dict,\"target\": replace_dict})\n nodes = pd.DataFrame(unique_list)\n nodes.rename(columns = {0:'name'}, inplace = True)\n nodes_json= pd.DataFrame(nodes).to_json(orient='records')\n links_json= pd.DataFrame(links_replaced).to_json(orient='records')\n \n data = { 'links' : json.loads(links_json), 'nodes' : json.loads(nodes_json) }\n data_json = json.dumps(data)\n data_json = data_json.replace(\"\\\\\",\"\")\n #print(data_json)\n #with open('sankey_data.json', 'w') as outfile:\n # json.dump(data_json, outfile)\n\n text_file = open(filename + \".json\", \"w\")\n text_file.write(data_json)\n text_file.close()", "_____no_output_____" ], [ "write_nodes_links(\"sankey_data_2015-16_summary\",unique_list_summary,replace_dict_summary,links_summary)\nwrite_nodes_links(\"sankey_data_2015-16_companies\",unique_list_companies,replace_dict_companies,links_companies)\nwrite_nodes_links(\"sankey_data_2015-16_govt\",unique_list_govt,replace_dict_govt,links_govt)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0c3b436adb68eeec9a10b41693f8e6ed56f460
448,391
ipynb
Jupyter Notebook
Week-3/ET5003_Lab_Piecewise_Regression.ipynb
olgaminguett/ET5003_SEM1_2021-2
2ea30ab095b8a8f0a95e6742a5f1ba5a5ac9304d
[ "BSD-3-Clause" ]
null
null
null
Week-3/ET5003_Lab_Piecewise_Regression.ipynb
olgaminguett/ET5003_SEM1_2021-2
2ea30ab095b8a8f0a95e6742a5f1ba5a5ac9304d
[ "BSD-3-Clause" ]
null
null
null
Week-3/ET5003_Lab_Piecewise_Regression.ipynb
olgaminguett/ET5003_SEM1_2021-2
2ea30ab095b8a8f0a95e6742a5f1ba5a5ac9304d
[ "BSD-3-Clause" ]
null
null
null
159.229759
74,746
0.852644
[ [ [ "<a href=\"https://colab.research.google.com/github/olgaminguett/ET5003_SEM1_2021-2/blob/main/Week-3/ET5003_Lab_Piecewise_Regression.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "<div>\n<img src=\"https://drive.google.com/uc?export=view&id=1vK33e_EqaHgBHcbRV_m38hx6IkG0blK_\" width=\"350\"/>\n</div> \n\n#**Artificial Intelligence - MSc**\n##ET5003 - MACHINE LEARNING APPLICATIONS \n\n###Instructor: Enrique Naredo\n###ET5003_Lab_Piecewise_Regression", "_____no_output_____" ], [ "# INTRODUCTION", "_____no_output_____" ], [ "**Piecewise regression**, extract from [Wikipedia](https://en.wikipedia.org/wiki/Segmented_regression):\n\nSegmented regression, also known as piecewise regression or broken-stick regression, is a method in regression analysis in which the independent variable is partitioned into intervals and a separate line segment is fit to each interval. \n\n* Segmented regression analysis can also be performed on \nmultivariate data by partitioning the various independent variables. \n* Segmented regression is useful when the independent variables, clustered into different groups, exhibit different relationships between the variables in these regions. \n\n* The boundaries between the segments are breakpoints.\n\n* Segmented linear regression is segmented regression whereby the relations in the intervals are obtained by linear regression. ", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "# Suppressing Warnings:\nimport warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "import pandas as pd\nimport numpy as np\nimport pymc3 as pm\nimport arviz as az\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler", "_____no_output_____" ], [ "# to plot\nimport matplotlib.colors\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# to generate classification, regression and clustering datasets\nimport sklearn.datasets as dt\n\n# to create data frames\nfrom pandas import DataFrame\n\n# to generate data from an existing dataset\nfrom sklearn.neighbors import KernelDensity\nfrom sklearn.model_selection import GridSearchCV", "_____no_output_____" ], [ "# Define the seed so that results can be reproduced\nseed = 11\nrand_state = 11\n\n# Define the color maps for plots\ncolor_map = plt.cm.get_cmap('RdYlBu')\ncolor_map_discrete = matplotlib.colors.LinearSegmentedColormap.from_list(\"\", [\"red\",\"cyan\",\"magenta\",\"blue\"])", "_____no_output_____" ] ], [ [ "# DATASET", "_____no_output_____" ], [ "## Synthetic Dataset\n", "_____no_output_____" ], [ "**Synthetic data** plays a very important role in data science, allows us to test a new algorithm under controlled conditions, we can generate data that tests a very specific property or behavior of our algorithm.\n\n* We can test its performance on balanced vs. imbalanced datasets.\n* We can evaluate its performance under different noise levels.\n* We can establish a baseline of our algorithm's performance under various scenarios.\n\nReal data may be hard or expensive to acquire, or it may have too few data-points. \n\nAnother reason is privacy, where real data cannot be revealed to others.", "_____no_output_____" ], [ "### Synthetic Data for Regression", "_____no_output_____" ], [ "The sklearn.datasets package has functions for generating synthetic datasets for regression. \n\nThe make_regression() function returns a set of input data points (regressors) along with their output (target). \n\nThis function can be adjusted with the following parameters:\n\n n_features - number of dimensions/features of the generated data\n noise - standard deviation of gaussian noise\n n_samples - number of samples\n\n* The response variable is a linear combination of the generated input set.\n\n* A response variable is something that's dependent on other variables.\n\n* In this particular case, it is a target feature that we're trying to predict using all the other input features.\n", "_____no_output_____" ], [ "### Example", "_____no_output_____" ] ], [ [ "## Example \n# data with just 2 features\nX1,y1 = dt.make_regression(n_samples=1000, n_features=2,\n noise=50, random_state=rand_state,effective_rank=1) \n\nscatter_plot2 = plt.scatter(X1[:,0], X1[:,1], c=y1,\n vmin=min(y1), vmax=max(y1),\n s=35, cmap=color_map)\n", "_____no_output_____" ] ], [ [ "###Create Synthetic Data", "_____no_output_____" ] ], [ [ "# create random datw with 4 clusters\nfrom sklearn.datasets import make_classification\n\nnum_samples = 5000\nX2, y2 = make_classification(n_classes=4, n_features=2, n_samples=num_samples, \n n_redundant=0, n_informative=2, n_clusters_per_class=1)\n\n\n# create a data frame\ndf = DataFrame(dict(x=X2[:,0], y=X2[:,1], label=y2))\n# three classes\ncolors = {0:'red', 1:'green', 2:'blue', 3:'brown'}\n# figure\nfig, ax = plt.subplots()\ngrouped = df.groupby('label')\n# scatter plot\nfor key, group in grouped:\n group.plot(ax=ax, kind='scatter', x='x', y='y', label=key, color=colors[key])\n# show the plot\nplt.show()", "_____no_output_____" ], [ "## Main dataset with 4 features\n# we'll use this dataset\n\nX3,y3 = dt.make_regression(n_samples=num_samples, n_features=4, n_informative=4,\n noise=.2, random_state=rand_state) ", "_____no_output_____" ], [ "# intervals to scale features\nscaleX0 = (50, 60)\nscaleX1 = (4, 7)\nscaleX2 = (1, 2)\nscaleX3 = (450, 710)\nscaleX4 = (30, 5000)\nscaleX5 = (10, 800)\nscaleY = (150000, 2000000)\n\n# Scale features\nf0 = np.interp(X2[:,0], (X2[:,0].min(), X2[:,0].max()), scaleX0)\nf1 = np.interp(X2[:,1], (X2[:,1].min(), X2[:,1].max()), scaleX1)\nf2 = np.interp(X3[:,0], (X3[:,0].min(), X3[:,0].max()), scaleX2)\nf3 = np.interp(X3[:,1], (X3[:,1].min(), X3[:,1].max()), scaleX3)\nf4 = np.interp(X3[:,2], (X3[:,2].min(), X3[:,2].max()), scaleX4)\nf5 = np.interp(X3[:,3], (X3[:,3].min(), X3[:,3].max()), scaleX5)\n\n# scaled data\nX = np.stack((f0,f1,f2,f3,f4,f5), axis=1)\ny = np.interp(y3, (y3.min(), y3.max()), scaleY)", "_____no_output_____" ] ], [ [ "## Training & Test Data", "_____no_output_____" ] ], [ [ "# split data into training and test\nfrom sklearn.model_selection import train_test_split\n\n# training: 70% (0.7), test: 30% (0.3)\nX_train,X_test,y_train,y_test = train_test_split(X, y, test_size=0.3)", "_____no_output_____" ], [ "def replace_with_nan(df,frac):\n \"\"\"Replace some values randomly with nan\"\"\"\n # requires numpy & pandas\n rows = np.random.choice(range(df.shape[0]), int(df.shape[0]*frac), replace=False)\n cols = np.random.choice(range(0,df.shape[1]-1), size=len(rows), replace=True)\n to_repl = [np.nan for i, col in zip(rows, cols)] \n # method used to cast a pandas object to a specified dtype\n rnan = df.astype(object).to_numpy()\n rnan[rows, cols] = to_repl\n # returns data frame with nans\n return DataFrame(rnan, index=df.index, columns=df.columns)", "_____no_output_____" ] ], [ [ "### Train dataset", "_____no_output_____" ] ], [ [ "## create train data frame\n# use meaningful names\ndftrain = DataFrame(dict(feature_1=X_train[:,0], \n feature_2=X_train[:,1],\n feature_3=X_train[:,2], \n feature_4=X_train[:,3],\n feature_5=X_train[:,4],\n feature_6=X_train[:,5],\n cost=y_train))", "_____no_output_____" ], [ "# dftrain with nans\ndftrain = replace_with_nan(dftrain,.10)\nprint('Number of nan in train dataset: ',dftrain.isnull().sum().sum())", "Number of nan in train dataset: 350\n" ], [ "# show first data frame rows \ndftrain.head()", "_____no_output_____" ], [ "# Generate descriptive statistics\ndftrain.describe()", "_____no_output_____" ] ], [ [ "### Test dataset", "_____no_output_____" ] ], [ [ "## create test data frame\n# no cost included\n\ndftest = DataFrame(dict(feature_1=X_test[:,0], \n feature_2=X_test[:,1],\n feature_3=X_test[:,2], \n feature_4=X_test[:,3],\n feature_5=X_test[:,4],\n feature_6=X_test[:,5]))", "_____no_output_____" ], [ "# dftrain with nans\ndftest = replace_with_nan(dftest,.10)\nprint('Number of nan in test dataset: ',dftest.isnull().sum().sum())", "Number of nan in test dataset: 150\n" ], [ "# show first data frame rows \ndftest.head()", "_____no_output_____" ], [ "# Generate descriptive statistics\ndftest.describe()", "_____no_output_____" ] ], [ [ "### Expected Cost dataset", "_____no_output_____" ] ], [ [ "## create expected cost data frame\n# the cost is in another file\ndfcost = DataFrame(dict(cost=y_test))\n# show first data frame rows \ndfcost.head()", "_____no_output_____" ], [ "# Generate descriptive statistics\ndfcost.describe()", "_____no_output_____" ] ], [ [ "## Save dataset", "_____no_output_____" ], [ "You can save your datataset in any location suitable for you, one choice using Colab is to save it in your Google Drive this way you will have it handy for your experiments.", "_____no_output_____" ] ], [ [ "# Mount Google drive\nfrom google.colab import drive\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "# path to your Google Drive\npathDrive = '/content/drive/My Drive/Colab Notebooks/'", "_____no_output_____" ], [ "# create a directory (if not exist)\nimport os\n\nfolderName = 'SyntData/'\nsyntPath = pathDrive+folderName\n\nif os.path.exists(syntPath):\n print(folderName,' directory already exists')\nelse:\n # create a directory\n os.mkdir(syntPath)\n print('Now you have a new directory: ',folderName)", "Now you have a new directory: SyntData/\n" ], [ "# manage versions if you like to save more datasets\n# syntTrain1.csv, syntTrain2.csv, etc\n\n## save train dataset into your Drive\nfilename1 = 'syntTrain.csv'\ndftrain.to_csv(syntPath+filename1, encoding='utf-8', index=False)\n\n# save test dataset into your Drive\nfilename2 = 'syntTest.csv'\ndftest.to_csv(syntPath+filename2, encoding='utf-8', index=False)\n\n# save cost dataset into your Drive\nfilename3 = 'syntCost.csv'\ndfcost.to_csv(syntPath+filename3, encoding='utf-8', index=False)", "_____no_output_____" ] ], [ [ "## Load your dataset", "_____no_output_____" ] ], [ [ "# training dataset: \ntraining_file = syntPath+filename1\n# test dataset: \ntesting_file = syntPath+filename2\n# cost dataset: \ncost_file = syntPath+filename3", "_____no_output_____" ], [ "# load train dataset\ndf_train = pd.read_csv(training_file)\ndf_train.head()", "_____no_output_____" ], [ "# load test dataset\ndf_test = pd.read_csv(testing_file)\ndf_test.head()", "_____no_output_____" ], [ "# load cost dataset\ndf_cost = pd.read_csv(cost_file)\ndf_cost.head()", "_____no_output_____" ] ], [ [ "# PIECEWISE REGRESSION", "_____no_output_____" ], [ "## Full Model", "_____no_output_____" ] ], [ [ "# select some features columns just for the baseline model\n# assume not all of the features are informative or useful\n# in this exercise you could try all of them\n\nfeatrain = ['feature_1','feature_2','feature_3','cost']\n# dropna: remove missing values\ndf_subset_train = dftrain[featrain].dropna(axis=0)\n\nfeatest = ['feature_1','feature_2','feature_3']\ndf_subset_test = dftest[featest].dropna(axis=0)\n\n# cost\ndf_cost = df_cost[df_cost.index.isin(df_subset_test.index)]", "_____no_output_____" ], [ "print('Number of nan in df_subset_train dataset: ',df_subset_train.isnull().sum().sum())\nprint('Number of nan in df_subset_test dataset: ',df_subset_test.isnull().sum().sum())", "Number of nan in df_subset_train dataset: 0\nNumber of nan in df_subset_test dataset: 0\n" ], [ "# train set, input columns\nXs_train = df_subset_train.iloc[:,0:-1].values \n# train set, output column, cost\nys_train = df_subset_train.iloc[:,-1].values.reshape(-1,1) \n\n# test set, input columns\nXs_test = df_subset_test.iloc[:,0:].values \n# test set, output column, cost\ny_test = df_cost.cost.values", "_____no_output_____" ], [ "# StandardScaler() will normalize the features i.e. each column of X, \n# so, each column/feature/variable will have μ = 0 and σ = 1\nsc = StandardScaler()\n\nXss_train = np.hstack([Xs_train,Xs_train[:,[2]]**2])\nxscaler = sc.fit(Xss_train)\nXn_train = xscaler.transform(Xss_train)\n\nXss_test = np.hstack([Xs_test,Xs_test[:,[2]]**2])\nXn_test = xscaler.transform(Xss_test)\n\nylog = np.log(ys_train.astype('float'))\nyscaler = StandardScaler().fit(ylog)\nyn_train = yscaler.transform(ylog)", "_____no_output_____" ], [ "# model\nwith pm.Model() as model:\n #prior over the parameters of linear regression\n alpha = pm.Normal('alpha', mu=0, sigma=30)\n #we have one beta for each column of Xn\n beta = pm.Normal('beta', mu=0, sigma=30, shape=Xn_train.shape[1])\n #prior over the variance of the noise\n sigma = pm.HalfCauchy('sigma_n', 5)\n #linear regression model in matrix form\n mu = alpha + pm.math.dot(beta, Xn_train.T)\n #likelihood, be sure that observed is a 1d vector\n like = pm.Normal('like', mu=mu, sigma=sigma, observed=yn_train[:,0])\n ", "_____no_output_____" ], [ "#number of iterations of the algorithms\niter = 50000 \n\n# run the model\nwith model:\n approximation = pm.fit(iter,method='advi')\n \n# check the convergence\nplt.plot(approximation.hist);", "WARNING (theano.tensor.blas): We did not find a dynamic library in the library_dir of the library we use for blas. If you use ATLAS, make sure to compile it with dynamics library.\nWARNING (theano.tensor.blas): We did not find a dynamic library in the library_dir of the library we use for blas. If you use ATLAS, make sure to compile it with dynamics library.\n" ], [ "# samples from the posterior\nposterior = approximation.sample(5000)", "_____no_output_____" ], [ "# prediction\nll=np.mean(posterior['alpha']) + np.dot(np.mean(posterior['beta'],axis=0), Xn_test.T)\ny_pred_BLR = np.exp(yscaler.inverse_transform(ll.reshape(-1,1)))[:,0]\nprint(\"MAE = \",(np.mean(abs(y_pred_BLR - y_test))))\nprint(\"MAPE = \",(np.mean(abs(y_pred_BLR - y_test) / y_test)))", "MAE = 138841.48475712741\nMAPE = 0.1424670683863496\n" ] ], [ [ "## Clustering", "_____no_output_____" ], [ "### Full Model", "_____no_output_____" ] ], [ [ "# training gaussian mixture model \nfrom sklearn.mixture import GaussianMixture\n\ngmm = GaussianMixture(n_components=4)\n# clustering by features 1, 2\nind=[0,1]\nX_ind = np.vstack([Xn_train[:,ind],Xn_test[:,ind]])\n# Gaussian Mixture\ngmm.fit(X_ind)\n# plot blue dots\nplt.scatter(X_ind[:,0],X_ind[:,1])\n# centroids: orange dots\nplt.scatter(gmm.means_[:,0],gmm.means_[:,1])", "_____no_output_____" ], [ "np.max(ys_train)", "_____no_output_____" ] ], [ [ "### Clusters", "_____no_output_____" ] ], [ [ "# train clusters\nclusters_train = gmm.predict(Xn_train[:,ind])\nunique_train, counts_train = np.unique(clusters_train, return_counts=True)\ndict(zip(unique_train, counts_train))\n", "_____no_output_____" ], [ "# test clusters\nclusters_test = gmm.predict(Xn_test[:,ind])\nunique_test, counts_test = np.unique(clusters_test, return_counts=True)\ndict(zip(unique_test, counts_test))", "_____no_output_____" ], [ "# cluster 0\nXn0 = Xn_train[clusters_train==0,:]\nXtestn0 = Xn_test[clusters_test==0,:]\n\nylog0 = np.log(ys_train.astype('float')[clusters_train==0,:])\nyscaler0 = StandardScaler().fit(ylog0)\nyn0 = yscaler0.transform(ylog0)\n", "_____no_output_____" ], [ "# cluster 1\nXn1 = Xn_train[clusters_train==1,:]\nXtestn1 = Xn_test[clusters_test==1,:]\nylog1 = np.log(ys_train.astype('float')[clusters_train==1,:])\nyscaler1 = StandardScaler().fit(ylog1)\nyn1 = yscaler1.transform(ylog1)", "_____no_output_____" ], [ "# cluster 2\nXn2 = Xn_train[clusters_train==2,:]\nXtestn2 = Xn_test[clusters_test==2,:]\nylog2 = np.log(ys_train.astype('float')[clusters_train==2,:])\nyscaler2 = StandardScaler().fit(ylog2)\nyn2 = yscaler2.transform(ylog2)\n", "_____no_output_____" ], [ "# cluster 3\nXn3 = Xn_train[clusters_train==3,:]\nXtestn3 = Xn_test[clusters_test==3,:]\nylog3 = np.log(ys_train.astype('float')[clusters_train==3,:])\nyscaler3 = StandardScaler().fit(ylog3)\nyn3 = yscaler3.transform(ylog3)", "_____no_output_____" ] ], [ [ "## Piecewise Model", "_____no_output_____" ] ], [ [ "# model_0\nwith pm.Model() as model_0:\n # prior over the parameters of linear regression\n alpha = pm.Normal('alpha', mu=0, sigma=30)\n # we have a beta for each column of Xn0\n beta = pm.Normal('beta', mu=0, sigma=30, shape=Xn0.shape[1])\n # prior over the variance of the noise\n sigma = pm.HalfCauchy('sigma_n', 5)\n # linear regression relationship\n #linear regression model in matrix form\n mu = alpha + pm.math.dot(beta, Xn0.T)\n # likelihood, be sure that observed is a 1d vector\n like = pm.Normal('like', mu=mu, sigma=sigma, observed=yn0[:,0])\n\nwith model_0:\n # iterations of the algorithm\n approximation = pm.fit(40000,method='advi')\n\n# samples from the posterior \nposterior0 = approximation.sample(5000)", "_____no_output_____" ], [ "# model_1\nwith pm.Model() as model_1:\n # prior over the parameters of linear regression\n alpha = pm.Normal('alpha', mu=0, sigma=30)\n # we have a beta for each column of Xn\n beta = pm.Normal('beta', mu=0, sigma=30, shape=Xn1.shape[1])\n # prior over the variance of the noise\n sigma = pm.HalfCauchy('sigma_n', 5)\n # linear regression relationship\n #linear regression model in matrix form\n mu = alpha + pm.math.dot(beta, Xn1.T)\n # likelihood, # \n like = pm.Normal('like', mu=mu, sigma=sigma, observed=yn1[:,0])\n \nwith model_1:\n # iterations of the algorithm\n approximation = pm.fit(40000,method='advi')\n\n# samples from the posterior \nposterior1 = approximation.sample(5000)", "_____no_output_____" ], [ "# model_2\nwith pm.Model() as model_2:\n # prior over the parameters of linear regression\n alpha = pm.Normal('alpha', mu=0, sigma=30)\n # we have a beta for each column of Xn\n beta = pm.Normal('beta', mu=0, sigma=30, shape=Xn2.shape[1])\n # prior over the variance of the noise\n sigma = pm.HalfCauchy('sigma_n', 5)\n # linear regression relationship\n # linear regression model in matrix form\n mu = alpha + pm.math.dot(beta, Xn2.T)\n # likelihood, be sure that observed is a 1d vector\n like = pm.Normal('like', mu=mu, sigma=sigma, observed=yn2[:,0])\n \nwith model_2:\n # iterations of the algorithms\n approximation = pm.fit(40000,method='advi')\n\n# samples from the posterior \nposterior2 = approximation.sample(5000)", "_____no_output_____" ], [ "# model_3\nwith pm.Model() as model3:\n # prior over the parameters of linear regression\n alpha = pm.Normal('alpha', mu=0, sigma=30)\n # we have a beta for each column of Xn\n beta = pm.Normal('beta', mu=0, sigma=30, shape=Xn3.shape[1])\n # prior over the variance of the noise\n sigma = pm.HalfCauchy('sigma_n', 5)\n # linear regression relationship\n mu = alpha + pm.math.dot(beta, Xn3.T)#linear regression model in matrix form\n # likelihood, be sure that observed is a 1d vector\n like = pm.Normal('like', mu=mu, sigma=sigma, observed=yn3[:,0])\n \nwith model3:\n # number of iterations of the algorithms\n approximation = pm.fit(40000,method='advi')\n\n# samples from the posterior \nposterior3 = approximation.sample(5000)", "_____no_output_____" ], [ "#############", "_____no_output_____" ], [ "# Posterior predictive checks (PPCs)\ndef ppc(alpha,beta,sigma, X, nsamples=500):\n #we select nsamples random samples from the posterior\n ind = np.random.randint(0,beta.shape[0],size=nsamples)\n alphai = alpha[ind]\n betai = beta[ind,:]\n sigmai = sigma[ind]\n\n Ypred = np.zeros((nsamples,X.shape[0]))\n for i in range(X.shape[0]):\n #we generate data from linear model\n y_pred = alphai + np.dot(betai, X[i:i+1,:].T).T +np.random.randn(len(sigmai))*sigmai\n Ypred[:,i]=y_pred[0,:]\n return Ypred\n\n", "_____no_output_____" ] ], [ [ "##Simulations", "_____no_output_____" ], [ "### Only Cluster 0", "_____no_output_____" ] ], [ [ "#Simulation\nYpred0 = yscaler0.inverse_transform(ppc(posterior0['alpha'],posterior0['beta'],posterior0['sigma_n'],Xn0, nsamples=200))\nfor i in range(Ypred0.shape[0]):\n az.plot_dist( Ypred0[i,:],color='r',plot_kwargs={\"linewidth\": 0.2})\naz.plot_dist(Ypred0[i,:],color='r',plot_kwargs={\"linewidth\": 0.2}, label=\"prediction\")\n#plt.plot(np.linspace(-8,8,100),norm.pdf(np.linspace(-8,8,100),df=np.mean(posterior_1['nu'])))\n#plt.xlim([0,10e7])\naz.plot_dist(ylog0,label='true observations');\nplt.legend()\nplt.xlabel(\"log(y) - output variable\")\nplt.ylabel(\"density plot\");", "_____no_output_____" ] ], [ [ "### Only Cluster 1", "_____no_output_____" ] ], [ [ "#Simulation\nYpred1 = yscaler1.inverse_transform(ppc(posterior1['alpha'],posterior1['beta'],posterior1['sigma_n'],Xn1, nsamples=200))\nfor i in range(Ypred1.shape[0]):\n az.plot_dist( Ypred1[i,:],color='r',plot_kwargs={\"linewidth\": 0.2})\naz.plot_dist(Ypred1[i,:],color='r',plot_kwargs={\"linewidth\": 0.2}, label=\"prediction\")\n#plt.plot(np.linspace(-8,8,100),norm.pdf(np.linspace(-8,8,100),df=np.mean(posterior_1['nu'])))\n#plt.xlim([0,10e7])\naz.plot_dist(ylog1,label='true observations');\nplt.legend()\nplt.xlabel(\"log(y) - output variable\")\nplt.ylabel(\"density plot\");", "_____no_output_____" ] ], [ [ "### Only Cluster 2", "_____no_output_____" ] ], [ [ "#Simulation\nYpred2 = yscaler2.inverse_transform(ppc(posterior2['alpha'],posterior2['beta'],posterior2['sigma_n'],Xn2, nsamples=200))\nfor i in range(Ypred2.shape[0]):\n az.plot_dist( Ypred2[i,:],color='r',plot_kwargs={\"linewidth\": 0.2})\naz.plot_dist(Ypred2[i,:],color='r',plot_kwargs={\"linewidth\": 0.2}, label=\"prediction\")\n#plt.plot(np.linspace(-8,8,100),norm.pdf(np.linspace(-8,8,100),df=np.mean(posterior_1['nu'])))\n#plt.xlim([0,10e7])\naz.plot_dist(ylog2,label='true observations');\nplt.legend()\nplt.xlabel(\"log(y) - output variable\")\nplt.ylabel(\"density plot\");", "_____no_output_____" ] ], [ [ "### Only Cluster 3", "_____no_output_____" ] ], [ [ "#Simulation\nYpred3 = yscaler3.inverse_transform(ppc(posterior3['alpha'],posterior3['beta'],posterior3['sigma_n'],Xn3, nsamples=200))\nfor i in range(Ypred3.shape[0]):\n az.plot_dist( Ypred3[i,:],color='r',plot_kwargs={\"linewidth\": 0.2})\naz.plot_dist(Ypred3[i,:],color='r',plot_kwargs={\"linewidth\": 0.2}, label=\"prediction\")\n#plt.plot(np.linspace(-8,8,100),norm.pdf(np.linspace(-8,8,100),df=np.mean(posterior_1['nu'])))\n#plt.xlim([0,10e7])\naz.plot_dist(ylog3,label='true observations');\nplt.legend()\nplt.xlabel(\"log(y) - output variable\")\nplt.ylabel(\"density plot\");", "_____no_output_____" ] ], [ [ "## Overall", "_____no_output_____" ] ], [ [ "# posteriors\nYpred0 = ppc(posterior0['alpha'],posterior0['beta'],posterior0['sigma_n'],Xn0, nsamples=200)\nYpred1 = ppc(posterior1['alpha'],posterior1['beta'],posterior1['sigma_n'],Xn1, nsamples=200)\nYpred2 = ppc(posterior2['alpha'],posterior2['beta'],posterior2['sigma_n'],Xn2, nsamples=200)\nYpred3 = ppc(posterior3['alpha'],posterior3['beta'],posterior3['sigma_n'],Xn3, nsamples=200)\n\n# simulation\nYpred = np.hstack([ yscaler0.inverse_transform(Ypred0),\n yscaler1.inverse_transform(Ypred1),\n yscaler2.inverse_transform(Ypred2),\n yscaler3.inverse_transform(Ypred3)])\n\n# prediction\nfor i in range(Ypred.shape[0]):\n az.plot_dist( Ypred[i,:],color='r',plot_kwargs={\"linewidth\": 0.2})\n\n# plot\naz.plot_dist(Ypred[i,:],color='r',plot_kwargs={\"linewidth\": 0.2}, label=\"prediction\")\nylog=np.vstack([ylog0,ylog1,ylog2,ylog3])\naz.plot_dist(ylog,label='true observations');\nplt.legend()\nplt.xlabel(\"log(y) - output variable\")\nplt.ylabel(\"density plot\");", "_____no_output_____" ] ], [ [ "## Test set performance", "_____no_output_____" ] ], [ [ "# cluster 0\ny_pred_BLR0 = np.exp(yscaler0.inverse_transform(np.mean(posterior0['alpha']) \n + np.dot(np.mean(posterior0['beta'],axis=0), Xtestn0.T)))\nprint(\"Size Cluster0\", np.sum(clusters_test==0), \", MAE Cluster0=\",\n (np.mean(abs(y_pred_BLR0 - y_test[clusters_test==0]))))\n\n# cluster 1\ny_pred_BLR1 = np.exp(yscaler1.inverse_transform(np.mean(posterior1['alpha']) \n + np.dot(np.mean(posterior1['beta'],axis=0), Xtestn1.T)))\nprint(\"Size Cluster1\", np.sum(clusters_test==1), \", MAE Cluster1=\",\n (np.mean(abs(y_pred_BLR1 - y_test[clusters_test==1]))))\n\n# cluster 2\ny_pred_BLR2 = np.exp(yscaler2.inverse_transform(np.mean(posterior2['alpha']) \n + np.dot(np.mean(posterior2['beta'],axis=0), Xtestn2.T)))\nprint(\"Size Cluster2\", np.sum(clusters_test==2), \", MAE Cluster2=\",\n (np.mean(abs(y_pred_BLR2 - y_test[clusters_test==2]))))\n\n# cluster 3\ny_pred_BLR3 = np.exp(yscaler3.inverse_transform(np.mean(posterior3['alpha']) \n + np.dot(np.mean(posterior3['beta'],axis=0), Xtestn3.T)))\nprint(\"Size Cluster3\", np.sum(clusters_test==3), \", MAE Cluster3=\",\n (np.mean(abs(y_pred_BLR3 - y_test[clusters_test==3]))))\n\n# joint\njoint=np.hstack([abs(y_pred_BLR0 - y_test[clusters_test==0]),\n abs(y_pred_BLR1 - y_test[clusters_test==1]),\n abs(y_pred_BLR2 - y_test[clusters_test==2]),\n abs(y_pred_BLR3 - y_test[clusters_test==3])])\n\n# MAE\nprint(\"MAE=\",np.mean(joint))", "Size Cluster0 315 , MAE Cluster0= 138253.05206488215\nSize Cluster1 358 , MAE Cluster1= 137568.88835864814\nSize Cluster2 376 , MAE Cluster2= 143069.3193042597\nSize Cluster3 366 , MAE Cluster3= 140424.0033695327\nMAE= 139921.28814451201\n" ] ], [ [ "### PPC on the Test set\n\n", "_____no_output_____" ] ], [ [ "## Posterior predictive checks (PPCs)\n\nnum_samples2 = 200\nYpred0 = ppc(posterior0['alpha'],posterior0['beta'],posterior0['sigma_n'],Xtestn0, nsamples=num_samples2)\nYpred1 = ppc(posterior1['alpha'],posterior1['beta'],posterior1['sigma_n'],Xtestn1, nsamples=num_samples2)\nYpred2 = ppc(posterior2['alpha'],posterior2['beta'],posterior2['sigma_n'],Xtestn2, nsamples=num_samples2)\nYpred3 = ppc(posterior3['alpha'],posterior3['beta'],posterior3['sigma_n'],Xtestn3, nsamples=num_samples2)\n\n# Stack arrays in sequence horizontally (column wise)\nYpred = np.hstack([yscaler0.inverse_transform(Ypred0),\n yscaler1.inverse_transform(Ypred1),\n yscaler2.inverse_transform(Ypred2),\n yscaler3.inverse_transform(Ypred3)])\n\n# plot prediction shape\nfor i in range(Ypred.shape[0]):\n az.plot_dist( Ypred[i,:],color='r',plot_kwargs={\"linewidth\": 0.2})\n# label\naz.plot_dist(Ypred[i,:],color='r',plot_kwargs={\"linewidth\": 0.2}, label=\"prediction\")\n\n# true observations\naz.plot_dist(np.log(y_test),label='true observations');\nplt.legend()\nplt.xlabel(\"log(y) - output variable\")\nplt.ylabel(\"density plot\");", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb0c4c88a8e053999c4aa04f08f01fabf8b8a754
91,058
ipynb
Jupyter Notebook
Project_1_RBM_and_Tomography/.ipynb_checkpoints/Task1_2_qucumber-checkpoint.ipynb
CDL-Week2/CohortProject_2020
ce33794267424760926afca0512942ab7e7d28eb
[ "MIT" ]
null
null
null
Project_1_RBM_and_Tomography/.ipynb_checkpoints/Task1_2_qucumber-checkpoint.ipynb
CDL-Week2/CohortProject_2020
ce33794267424760926afca0512942ab7e7d28eb
[ "MIT" ]
null
null
null
Project_1_RBM_and_Tomography/.ipynb_checkpoints/Task1_2_qucumber-checkpoint.ipynb
CDL-Week2/CohortProject_2020
ce33794267424760926afca0512942ab7e7d28eb
[ "MIT" ]
null
null
null
101.513935
25,620
0.85003
[ [ [ "!pip install qucumber", "Collecting qucumber\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/10/e8/292ad2bfb467da09c882ca5a2a54ccad0fbaa5ff42f08209ddf8f013ac3e/qucumber-1.3.0-py3-none-any.whl (74kB)\n\u001b[K |████████████████████████████████| 81kB 3.1MB/s \n\u001b[?25hRequirement already satisfied: scipy>=1.3.3 in /usr/local/lib/python3.6/dist-packages (from qucumber) (1.4.1)\nRequirement already satisfied: matplotlib>=2.2 in /usr/local/lib/python3.6/dist-packages (from qucumber) (3.2.2)\nCollecting torch<1.4,>=1.0; sys_platform != \"win32\"\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/88/95/90e8c4c31cfc67248bf944ba42029295b77159982f532c5689bcfe4e9108/torch-1.3.1-cp36-cp36m-manylinux1_x86_64.whl (734.6MB)\n\u001b[K |████████████████████████████████| 734.6MB 17kB/s \n\u001b[?25hRequirement already satisfied: tqdm>=4.23 in /usr/local/lib/python3.6/dist-packages (from qucumber) (4.41.1)\nRequirement already satisfied: numpy>=1.13 in /usr/local/lib/python3.6/dist-packages (from qucumber) (1.18.5)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2->qucumber) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2->qucumber) (1.2.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2->qucumber) (2.4.7)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.2->qucumber) (2.8.1)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from cycler>=0.10->matplotlib>=2.2->qucumber) (1.12.0)\n\u001b[31mERROR: torchvision 0.6.1+cu101 has requirement torch==1.5.1, but you'll have torch 1.3.1 which is incompatible.\u001b[0m\nInstalling collected packages: torch, qucumber\n Found existing installation: torch 1.5.1+cu101\n Uninstalling torch-1.5.1+cu101:\n Successfully uninstalled torch-1.5.1+cu101\nSuccessfully installed qucumber-1.3.0 torch-1.3.1\n" ], [ "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom qucumber.nn_states import PositiveWaveFunction\nfrom qucumber.callbacks import MetricEvaluator\n\nimport qucumber.utils.training_statistics as ts\nimport qucumber.utils.data as data\nimport qucumber", "_____no_output_____" ] ], [ [ "# Caso Rydberg", "_____no_output_____" ] ], [ [ "train_path = \"Rydberg_data.txt\"\ntrain_data = data.load_data(train_path)[0]\n\nnv = train_data.shape[-1]\nnh = nv\nnn_state = PositiveWaveFunction(num_visible=nv, num_hidden=nh, gpu=False)", "_____no_output_____" ], [ "epochs = 400\npbs = 100\nnbs = pbs\nlr = 0.01\nk = 10", "_____no_output_____" ], [ "def psi_coefficient0(nn_state, space, A, **kwargs):\n norm = nn_state.compute_normalization(space).sqrt_()\n return A * nn_state.psi(space)[0][0] / norm", "_____no_output_____" ], [ "period = 10\nspace = nn_state.generate_hilbert_space()", "_____no_output_____" ], [ "callbacks = [\n MetricEvaluator(\n period,\n {\"A_Ψrbm_0\": psi_coefficient0},\n verbose=True,\n space=space,\n A=1.0,\n )\n]\n\nnn_state.fit(\n train_data,\n epochs=epochs,\n pos_batch_size=pbs,\n neg_batch_size=nbs,\n lr=lr,\n k=k,\n callbacks=callbacks,\n time=True,\n)", "_____no_output_____" ], [ "coeffs = callbacks[0][\"A_Ψrbm_0\"]\nepoch = np.arange(period, epochs + 1, period)\n\n# Plotting\nplt.plot(epoch, coeffs, \"o\", color=\"C2\", markeredgecolor=\"black\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "# Caso Ejemplo", "_____no_output_____" ] ], [ [ "#psi_path = \"R_1.2_psi.txt\"\ntrain_path = \"R_1.2_samples.txt\"\n#train_data, true_psi = data.load_data(train_path, psi_path)\ntrain_data = data.load_data(train_path)[0]", "_____no_output_____" ], [ "nv = train_data.shape[-1]\nnh = nv\nnn_state = PositiveWaveFunction(num_visible=nv, num_hidden=nh, gpu=False)", "_____no_output_____" ], [ "epochs = 400\npbs = 100\nnbs = pbs\nlr = 0.01\nk = 10", "_____no_output_____" ], [ "def psi_coefficient0(nn_state, space, A, **kwargs):\n norm = nn_state.compute_normalization(space).sqrt_()\n return A * nn_state.psi(space)[0][0] / norm\n\ndef psi_coefficient1(nn_state, space, A, **kwargs):\n norm = nn_state.compute_normalization(space).sqrt_()\n return A * nn_state.psi(space)[0][1] / norm\n\ndef psi_coefficient2(nn_state, space, A, **kwargs):\n norm = nn_state.compute_normalization(space).sqrt_()\n return A * nn_state.psi(space)[0][2] / norm\n\ndef psi_coefficient3(nn_state, space, A, **kwargs):\n norm = nn_state.compute_normalization(space).sqrt_()\n return A * nn_state.psi(space)[0][3] / norm", "_____no_output_____" ], [ "period = 10\nspace = nn_state.generate_hilbert_space()", "_____no_output_____" ], [ "callbacks = [\n MetricEvaluator(\n period,\n {\"A_Ψrbm_0\": psi_coefficient0},\n verbose=True,\n space=space,\n A=1.0,\n )\n]\n\nnn_state.fit(\n train_data,\n epochs=epochs,\n pos_batch_size=pbs,\n neg_batch_size=nbs,\n lr=lr,\n k=k,\n callbacks=callbacks,\n time=True,\n)", "Epoch: 10\tA_Ψrbm_0 = 0.264459\nEpoch: 20\tA_Ψrbm_0 = 0.225839\nEpoch: 30\tA_Ψrbm_0 = 0.216382\nEpoch: 40\tA_Ψrbm_0 = 0.213244\nEpoch: 50\tA_Ψrbm_0 = 0.209651\nEpoch: 60\tA_Ψrbm_0 = 0.206405\nEpoch: 70\tA_Ψrbm_0 = 0.206193\nEpoch: 80\tA_Ψrbm_0 = 0.201495\nEpoch: 90\tA_Ψrbm_0 = 0.199604\nEpoch: 100\tA_Ψrbm_0 = 0.197259\nEpoch: 110\tA_Ψrbm_0 = 0.196986\nEpoch: 120\tA_Ψrbm_0 = 0.194122\nEpoch: 130\tA_Ψrbm_0 = 0.190790\nEpoch: 140\tA_Ψrbm_0 = 0.189765\nEpoch: 150\tA_Ψrbm_0 = 0.185901\nEpoch: 160\tA_Ψrbm_0 = 0.183673\nEpoch: 170\tA_Ψrbm_0 = 0.181192\nEpoch: 180\tA_Ψrbm_0 = 0.180843\nEpoch: 190\tA_Ψrbm_0 = 0.177581\nEpoch: 200\tA_Ψrbm_0 = 0.174047\nEpoch: 210\tA_Ψrbm_0 = 0.172508\nEpoch: 220\tA_Ψrbm_0 = 0.168960\nEpoch: 230\tA_Ψrbm_0 = 0.167670\nEpoch: 240\tA_Ψrbm_0 = 0.164769\nEpoch: 250\tA_Ψrbm_0 = 0.162927\nEpoch: 260\tA_Ψrbm_0 = 0.159281\nEpoch: 270\tA_Ψrbm_0 = 0.157020\nEpoch: 280\tA_Ψrbm_0 = 0.153828\nEpoch: 290\tA_Ψrbm_0 = 0.152167\nEpoch: 300\tA_Ψrbm_0 = 0.149676\nEpoch: 310\tA_Ψrbm_0 = 0.146605\nEpoch: 320\tA_Ψrbm_0 = 0.143007\nEpoch: 330\tA_Ψrbm_0 = 0.142228\nEpoch: 340\tA_Ψrbm_0 = 0.139673\nEpoch: 350\tA_Ψrbm_0 = 0.137102\nEpoch: 360\tA_Ψrbm_0 = 0.135213\nEpoch: 370\tA_Ψrbm_0 = 0.132097\nEpoch: 380\tA_Ψrbm_0 = 0.129200\nEpoch: 390\tA_Ψrbm_0 = 0.127487\nEpoch: 400\tA_Ψrbm_0 = 0.124827\nTotal time elapsed during training: 47.844 s\n" ], [ "coeffs = callbacks[0][\"A_Ψrbm_0\"]\nepoch = np.arange(period, epochs + 1, period)\n\n# Plotting\nplt.plot(epoch, coeffs, \"o\", color=\"C2\", markeredgecolor=\"black\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ], [ "callbacks = [\n MetricEvaluator(\n period,\n {\"A_Ψrbm_1\": psi_coefficient1},\n verbose=True,\n space=space,\n A=1.0,\n )\n]\n\nnn_state.fit(\n train_data,\n epochs=epochs,\n pos_batch_size=pbs,\n neg_batch_size=nbs,\n lr=lr,\n k=k,\n callbacks=callbacks,\n time=True,\n)", "Epoch: 10\tA_Ψrbm_1 = 0.195010\nEpoch: 20\tA_Ψrbm_1 = 0.194694\nEpoch: 30\tA_Ψrbm_1 = 0.196236\nEpoch: 40\tA_Ψrbm_1 = 0.197801\nEpoch: 50\tA_Ψrbm_1 = 0.203463\nEpoch: 60\tA_Ψrbm_1 = 0.202765\nEpoch: 70\tA_Ψrbm_1 = 0.203077\nEpoch: 80\tA_Ψrbm_1 = 0.206127\nEpoch: 90\tA_Ψrbm_1 = 0.205307\nEpoch: 100\tA_Ψrbm_1 = 0.205571\nEpoch: 110\tA_Ψrbm_1 = 0.204464\nEpoch: 120\tA_Ψrbm_1 = 0.205776\nEpoch: 130\tA_Ψrbm_1 = 0.209272\nEpoch: 140\tA_Ψrbm_1 = 0.208734\nEpoch: 150\tA_Ψrbm_1 = 0.209693\nEpoch: 160\tA_Ψrbm_1 = 0.210627\nEpoch: 170\tA_Ψrbm_1 = 0.212324\nEpoch: 180\tA_Ψrbm_1 = 0.215259\nEpoch: 190\tA_Ψrbm_1 = 0.211617\nEpoch: 200\tA_Ψrbm_1 = 0.211305\nEpoch: 210\tA_Ψrbm_1 = 0.215553\nEpoch: 220\tA_Ψrbm_1 = 0.214973\nEpoch: 230\tA_Ψrbm_1 = 0.212837\nEpoch: 240\tA_Ψrbm_1 = 0.213752\nEpoch: 250\tA_Ψrbm_1 = 0.214217\nEpoch: 260\tA_Ψrbm_1 = 0.219089\nEpoch: 270\tA_Ψrbm_1 = 0.217870\nEpoch: 280\tA_Ψrbm_1 = 0.220004\nEpoch: 290\tA_Ψrbm_1 = 0.215555\nEpoch: 300\tA_Ψrbm_1 = 0.218151\nEpoch: 310\tA_Ψrbm_1 = 0.218317\nEpoch: 320\tA_Ψrbm_1 = 0.218213\nEpoch: 330\tA_Ψrbm_1 = 0.219845\nEpoch: 340\tA_Ψrbm_1 = 0.218472\nEpoch: 350\tA_Ψrbm_1 = 0.217468\nEpoch: 360\tA_Ψrbm_1 = 0.218384\nEpoch: 370\tA_Ψrbm_1 = 0.218912\nEpoch: 380\tA_Ψrbm_1 = 0.217915\nEpoch: 390\tA_Ψrbm_1 = 0.224187\nEpoch: 400\tA_Ψrbm_1 = 0.219283\nTotal time elapsed during training: 48.662 s\n" ], [ "coeffs = callbacks[0][\"A_Ψrbm_1\"]\nepoch = np.arange(period, epochs + 1, period)\n\n# Plotting\nplt.plot(epoch, coeffs, \"o\", color=\"C2\", markeredgecolor=\"black\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ], [ "callbacks = [\n MetricEvaluator(\n period,\n {\"A_Ψrbm_2\": psi_coefficient2},\n verbose=True,\n space=space,\n A=1.0,\n )\n]\n\nnn_state.fit(\n train_data,\n epochs=epochs,\n pos_batch_size=pbs,\n neg_batch_size=nbs,\n lr=lr,\n k=k,\n callbacks=callbacks,\n time=True,\n)\n\n", "Epoch: 10\tA_Ψrbm_2 = 0.969494\nEpoch: 20\tA_Ψrbm_2 = 0.969175\nEpoch: 30\tA_Ψrbm_2 = 0.971041\nEpoch: 40\tA_Ψrbm_2 = 0.971312\nEpoch: 50\tA_Ψrbm_2 = 0.970588\nEpoch: 60\tA_Ψrbm_2 = 0.970615\nEpoch: 70\tA_Ψrbm_2 = 0.970523\nEpoch: 80\tA_Ψrbm_2 = 0.969797\nEpoch: 90\tA_Ψrbm_2 = 0.970746\nEpoch: 100\tA_Ψrbm_2 = 0.971439\nEpoch: 110\tA_Ψrbm_2 = 0.970400\nEpoch: 120\tA_Ψrbm_2 = 0.970107\nEpoch: 130\tA_Ψrbm_2 = 0.970316\nEpoch: 140\tA_Ψrbm_2 = 0.970097\nEpoch: 150\tA_Ψrbm_2 = 0.969936\nEpoch: 160\tA_Ψrbm_2 = 0.970737\nEpoch: 170\tA_Ψrbm_2 = 0.970888\nEpoch: 180\tA_Ψrbm_2 = 0.970812\nEpoch: 190\tA_Ψrbm_2 = 0.971162\nEpoch: 200\tA_Ψrbm_2 = 0.971031\nEpoch: 210\tA_Ψrbm_2 = 0.970771\nEpoch: 220\tA_Ψrbm_2 = 0.970388\nEpoch: 230\tA_Ψrbm_2 = 0.971699\nEpoch: 240\tA_Ψrbm_2 = 0.972252\nEpoch: 250\tA_Ψrbm_2 = 0.972248\nEpoch: 260\tA_Ψrbm_2 = 0.971139\nEpoch: 270\tA_Ψrbm_2 = 0.971238\nEpoch: 280\tA_Ψrbm_2 = 0.971170\nEpoch: 290\tA_Ψrbm_2 = 0.970825\nEpoch: 300\tA_Ψrbm_2 = 0.971025\nEpoch: 310\tA_Ψrbm_2 = 0.971298\nEpoch: 320\tA_Ψrbm_2 = 0.971020\nEpoch: 330\tA_Ψrbm_2 = 0.970201\nEpoch: 340\tA_Ψrbm_2 = 0.969048\nEpoch: 350\tA_Ψrbm_2 = 0.970062\nEpoch: 360\tA_Ψrbm_2 = 0.971360\nEpoch: 370\tA_Ψrbm_2 = 0.971595\nEpoch: 380\tA_Ψrbm_2 = 0.970937\nEpoch: 390\tA_Ψrbm_2 = 0.971249\nEpoch: 400\tA_Ψrbm_2 = 0.971245\nTotal time elapsed during training: 48.109 s\n" ], [ "coeffs = callbacks[0][\"A_Ψrbm_2\"]\nepoch = np.arange(period, epochs + 1, period)\n\n# Plotting\nplt.plot(epoch, coeffs, \"o\", color=\"C2\", markeredgecolor=\"black\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ], [ "callbacks = [\n MetricEvaluator(\n period,\n {\"A_Ψrbm_3\": psi_coefficient3},\n verbose=True,\n space=space,\n A=1.0,\n )\n]\n\nnn_state.fit(\n train_data,\n epochs=epochs,\n pos_batch_size=pbs,\n neg_batch_size=nbs,\n lr=lr,\n k=k,\n callbacks=callbacks,\n time=True,\n)", "Epoch: 10\tA_Ψrbm_3 = 0.052334\nEpoch: 20\tA_Ψrbm_3 = 0.052288\nEpoch: 30\tA_Ψrbm_3 = 0.051705\nEpoch: 40\tA_Ψrbm_3 = 0.051224\nEpoch: 50\tA_Ψrbm_3 = 0.050850\nEpoch: 60\tA_Ψrbm_3 = 0.050318\nEpoch: 70\tA_Ψrbm_3 = 0.049781\nEpoch: 80\tA_Ψrbm_3 = 0.049821\nEpoch: 90\tA_Ψrbm_3 = 0.048993\nEpoch: 100\tA_Ψrbm_3 = 0.049189\nEpoch: 110\tA_Ψrbm_3 = 0.048748\nEpoch: 120\tA_Ψrbm_3 = 0.048615\nEpoch: 130\tA_Ψrbm_3 = 0.048523\nEpoch: 140\tA_Ψrbm_3 = 0.048367\nEpoch: 150\tA_Ψrbm_3 = 0.048137\nEpoch: 160\tA_Ψrbm_3 = 0.047906\nEpoch: 170\tA_Ψrbm_3 = 0.047706\nEpoch: 180\tA_Ψrbm_3 = 0.047676\nEpoch: 190\tA_Ψrbm_3 = 0.047029\nEpoch: 200\tA_Ψrbm_3 = 0.046420\nEpoch: 210\tA_Ψrbm_3 = 0.046414\nEpoch: 220\tA_Ψrbm_3 = 0.046175\nEpoch: 230\tA_Ψrbm_3 = 0.046148\nEpoch: 240\tA_Ψrbm_3 = 0.046022\nEpoch: 250\tA_Ψrbm_3 = 0.045584\nEpoch: 260\tA_Ψrbm_3 = 0.045561\nEpoch: 270\tA_Ψrbm_3 = 0.045152\nEpoch: 280\tA_Ψrbm_3 = 0.045080\nEpoch: 290\tA_Ψrbm_3 = 0.044999\nEpoch: 300\tA_Ψrbm_3 = 0.044452\nEpoch: 310\tA_Ψrbm_3 = 0.044354\nEpoch: 320\tA_Ψrbm_3 = 0.043937\nEpoch: 330\tA_Ψrbm_3 = 0.043796\nEpoch: 340\tA_Ψrbm_3 = 0.043512\nEpoch: 350\tA_Ψrbm_3 = 0.043734\nEpoch: 360\tA_Ψrbm_3 = 0.043703\nEpoch: 370\tA_Ψrbm_3 = 0.043138\nEpoch: 380\tA_Ψrbm_3 = 0.043091\nEpoch: 390\tA_Ψrbm_3 = 0.043073\nEpoch: 400\tA_Ψrbm_3 = 0.042787\nTotal time elapsed during training: 47.820 s\n" ], [ "coeffs = callbacks[0][\"A_Ψrbm_3\"]\nepoch = np.arange(period, epochs + 1, period)\n\n# Plotting\nplt.plot(epoch, coeffs, \"o\", color=\"C2\", markeredgecolor=\"black\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "# De acá en adelante no sirve porque no calculamos la fidelidad ni el KL", "_____no_output_____" ] ], [ [ "# Note that the key given to the *MetricEvaluator* must be\n# what comes after callbacks[0].\nfidelities = callbacks[0].Fidelity\n\n# Alternatively, we can use the usual dictionary/list subsripting\n# syntax. This is useful in cases where the name of the\n# metric contains special characters or spaces.\nKLs = callbacks[0][\"KL\"]\ncoeffs = callbacks[0][\"A_Ψrbm_3\"]\nepoch = np.arange(period, epochs + 1, period)", "_____no_output_____" ], [ "# Plotting\nfig, axs = plt.subplots(nrows=1, ncols=3, figsize=(14, 3))\nax = axs[0]\nax.plot(epoch, fidelities, \"o\", color=\"C0\", markeredgecolor=\"black\")\nax.set_ylabel(r\"Fidelity\")\nax.set_xlabel(r\"Epoch\")\n\nax = axs[1]\nax.plot(epoch, KLs, \"o\", color=\"C1\", markeredgecolor=\"black\")\nax.set_ylabel(r\"KL Divergence\")\nax.set_xlabel(r\"Epoch\")\n\nax = axs[2]\nax.plot(epoch, coeffs, \"o\", color=\"C2\", markeredgecolor=\"black\")\nax.set_ylabel(r\"$A\\psi_{RBM}[0]$\")\nax.set_xlabel(r\"Epoch\")\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0c569eebf7e11a025d9444be614ed287903da1
190,295
ipynb
Jupyter Notebook
SAT_analysis.ipynb
noobhead/SAT-Analysis
a2400f3f7ea7f2f3c83bd48591272ffe23de2b2d
[ "MIT" ]
2
2018-08-24T19:08:41.000Z
2019-01-20T13:51:58.000Z
SAT_analysis.ipynb
noobhead/SAT-Analysis
a2400f3f7ea7f2f3c83bd48591272ffe23de2b2d
[ "MIT" ]
1
2018-08-24T18:51:49.000Z
2018-08-24T18:51:49.000Z
SAT_analysis.ipynb
noobhead/SAT-Analysis
a2400f3f7ea7f2f3c83bd48591272ffe23de2b2d
[ "MIT" ]
null
null
null
226.272295
27,204
0.895215
[ [ [ "# SAT Analysis\n\n**We wish to answer the question whether SAT is a fairt test?**", "_____no_output_____" ], [ "## Read in the data", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport re\n\ndata_files = [\n \"ap_2010.csv\",\n \"class_size.csv\",\n \"demographics.csv\",\n \"graduation.csv\",\n \"hs_directory.csv\",\n \"sat_results.csv\"\n]\n\ndata = {}\n\nfor file in data_files:\n df = pd.read_csv(\"schools/{0}\".format(file))\n data[file.replace(\".csv\", \"\")] = df", "_____no_output_____" ] ], [ [ "# Read in the surveys", "_____no_output_____" ] ], [ [ "all_survey = pd.read_csv(\"schools/survey_all.txt\", delimiter=\"\\t\", encoding='windows-1252')\nd75_survey = pd.read_csv(\"schools/survey_d75.txt\", delimiter=\"\\t\", encoding='windows-1252')\nsurvey = pd.concat([all_survey, d75_survey], axis=0)\n\nsurvey[\"DBN\"] = survey[\"dbn\"]\n\nsurvey_fields = [\n \"DBN\", \n \"rr_s\", \n \"rr_t\", \n \"rr_p\", \n \"N_s\", \n \"N_t\", \n \"N_p\", \n \"saf_p_11\", \n \"com_p_11\", \n \"eng_p_11\", \n \"aca_p_11\", \n \"saf_t_11\", \n \"com_t_11\", \n \"eng_t_11\", \n \"aca_t_11\", \n \"saf_s_11\", \n \"com_s_11\", \n \"eng_s_11\", \n \"aca_s_11\", \n \"saf_tot_11\", \n \"com_tot_11\", \n \"eng_tot_11\", \n \"aca_tot_11\",\n]\nsurvey = survey[survey_fields]\ndata[\"survey\"] = survey", "_____no_output_____" ] ], [ [ "# Add DBN columns", "_____no_output_____" ] ], [ [ "data[\"hs_directory\"][\"DBN\"] = data[\"hs_directory\"][\"dbn\"]\n\ndef pad_csd(num):\n str_rep = str(num)\n if len(str_rep) > 1:\n return str_rep\n else:\n return \"0\" + str_rep\n \ndata[\"class_size\"][\"padded_csd\"] = data[\"class_size\"][\"CSD\"].apply(pad_csd)\ndata[\"class_size\"][\"DBN\"] = data[\"class_size\"][\"padded_csd\"] + data[\"class_size\"][\"SCHOOL CODE\"]", "_____no_output_____" ] ], [ [ "# Convert columns to numeric", "_____no_output_____" ] ], [ [ "cols = ['SAT Math Avg. Score', 'SAT Critical Reading Avg. Score', 'SAT Writing Avg. Score']\nfor c in cols:\n data[\"sat_results\"][c] = pd.to_numeric(data[\"sat_results\"][c], errors=\"coerce\")\n\ndata['sat_results']['sat_score'] = data['sat_results'][cols[0]] + data['sat_results'][cols[1]] + data['sat_results'][cols[2]]\n\ndef find_lat(loc):\n coords = re.findall(\"\\(.+, .+\\)\", loc)\n lat = coords[0].split(\",\")[0].replace(\"(\", \"\")\n return lat\n\ndef find_lon(loc):\n coords = re.findall(\"\\(.+, .+\\)\", loc)\n lon = coords[0].split(\",\")[1].replace(\")\", \"\").strip()\n return lon\n\ndata[\"hs_directory\"][\"lat\"] = data[\"hs_directory\"][\"Location 1\"].apply(find_lat)\ndata[\"hs_directory\"][\"lon\"] = data[\"hs_directory\"][\"Location 1\"].apply(find_lon)\n\ndata[\"hs_directory\"][\"lat\"] = pd.to_numeric(data[\"hs_directory\"][\"lat\"], errors=\"coerce\")\ndata[\"hs_directory\"][\"lon\"] = pd.to_numeric(data[\"hs_directory\"][\"lon\"], errors=\"coerce\")", "_____no_output_____" ] ], [ [ "# Condense datasets\n\nCondensing the datasets to remove any two rows having same **DBN** so that all the datasets can be easily joined on **\"DBN\"**", "_____no_output_____" ] ], [ [ "class_size = data[\"class_size\"]\nclass_size = class_size[class_size[\"GRADE \"] == \"09-12\"]\nclass_size = class_size[class_size[\"PROGRAM TYPE\"] == \"GEN ED\"]\n\nclass_size = class_size.groupby(\"DBN\").agg(np.mean)\nclass_size.reset_index(inplace=True)\ndata[\"class_size\"] = class_size\n\ndata[\"demographics\"] = data[\"demographics\"][data[\"demographics\"][\"schoolyear\"] == 20112012]\n\ndata[\"graduation\"] = data[\"graduation\"][data[\"graduation\"][\"Cohort\"] == \"2006\"]\ndata[\"graduation\"] = data[\"graduation\"][data[\"graduation\"][\"Demographic\"] == \"Total Cohort\"]", "_____no_output_____" ] ], [ [ "# Convert AP scores to numeric", "_____no_output_____" ] ], [ [ "cols = ['AP Test Takers ', 'Total Exams Taken', 'Number of Exams with scores 3 4 or 5']\n\nfor col in cols:\n data[\"ap_2010\"][col] = pd.to_numeric(data[\"ap_2010\"][col], errors=\"coerce\")", "_____no_output_____" ] ], [ [ "# Combine the datasets\n\nMerging the dataset on **DBN** column", "_____no_output_____" ] ], [ [ "combined = data[\"sat_results\"]\n\ncombined = combined.merge(data[\"ap_2010\"], on=\"DBN\", how=\"left\")\ncombined = combined.merge(data[\"graduation\"], on=\"DBN\", how=\"left\")\n\nto_merge = [\"class_size\", \"demographics\", \"survey\", \"hs_directory\"]\n\nfor m in to_merge:\n combined = combined.merge(data[m], on=\"DBN\", how=\"inner\")\n\ncombined = combined.fillna(combined.mean())\ncombined = combined.fillna(0)", "_____no_output_____" ] ], [ [ "# Add a school district column for mapping", "_____no_output_____" ] ], [ [ "def get_first_two_chars(dbn):\n return dbn[0:2]\n\ncombined[\"school_dist\"] = combined[\"DBN\"].apply(get_first_two_chars)", "_____no_output_____" ] ], [ [ "# Find correlations", "_____no_output_____" ] ], [ [ "correlations = combined.corr()\ncorrelations = correlations[\"sat_score\"]\ncorrelations", "_____no_output_____" ] ], [ [ "# Plotting survey correlations", "_____no_output_____" ] ], [ [ "# Remove DBN since it's a unique identifier, not a useful numerical value for correlation.\nsurvey_fields.remove(\"DBN\")", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimport seaborn as sns\n% matplotlib inline", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize = (8,5))\ncorrelations[survey_fields].plot.bar()\nplt.show()", "_____no_output_____" ] ], [ [ "#### Findings from above plot\nThere are high correlations between N_s, N_t, N_p and sat_score. Since these columns are correlated with total_enrollment, it makes sense that they would be high.\n\nIt is more interesting that rr_s, the student response rate, or the percentage of students that completed the survey, correlates with sat_score. This might make sense because students who are more likely to fill out surveys may be more likely to also be doing well academically.\n\nHow students and teachers percieved safety (saf_t_11 and saf_s_11) correlate with sat_score. This make sense, as it's hard to teach or learn in an unsafe environment.\n\nThe last interesting correlation is the aca_s_11, which indicates how the student perceives academic standards, correlates with sat_score, but this is not true for aca_t_11, how teachers perceive academic standards, or aca_p_11, how parents perceive academic standards.", "_____no_output_____" ], [ "## Investigating safety scores", "_____no_output_____" ] ], [ [ "combined.plot.scatter(x = \"saf_s_11\", y = \"sat_score\" )\nplt.show()", "_____no_output_____" ] ], [ [ "There appears to be a correlation between SAT scores and safety, although it isn't thatstrong. It looks like there are a few schools with extremely high SAT scores and high safety scores. There are a few schools with low safety scores and low SAT scores. No school with a safety score lower than 6.5 has an average SAT score higher than 1500 or so.", "_____no_output_____" ], [ "## Plotting safety scores for districts in NYC", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\ndistricts = combined.groupby(\"school_dist\").agg(np.mean)\ndistricts.reset_index(inplace=True)\n\nm = Basemap(\n projection='merc', \n llcrnrlat=40.496044, \n urcrnrlat=40.915256, \n llcrnrlon=-74.255735, \n urcrnrlon=-73.700272,\n resolution='i'\n)\n\nm.drawmapboundary(fill_color='#85A6D9')\nm.drawcoastlines(color='#6D5F47', linewidth=.4)\nm.drawrivers(color='#6D5F47', linewidth=.4)\nm.fillcontinents(color='#FFC58C',lake_color='#85A6D9')\n\nlongitudes = districts[\"lon\"].tolist()\nlatitudes = districts[\"lat\"].tolist()\nm.scatter(longitudes, latitudes, s=50, zorder=2, latlon=True, c=districts[\"saf_s_11\"], cmap=\"summer\")\nplt.show()", "_____no_output_____" ] ], [ [ "## Investigating racial differences", "_____no_output_____" ] ], [ [ "race_cols = [\"white_per\", \"asian_per\", \"black_per\", \"hispanic_per\"]\ncorrelations[race_cols].plot.bar()", "_____no_output_____" ] ], [ [ "It shows higher percentage of white or asian students at a school correlates positively with sat score, whereas a higher percentage of black or hispanic students correlates negatively with sat score. This may be due to a lack of funding for schools in certain areas, which are more likely to have a higher percentage of black or hispanic students.", "_____no_output_____" ], [ "### Hispanic people vs SAT score", "_____no_output_____" ] ], [ [ "combined.plot.scatter(x = \"hispanic_per\", y = \"sat_score\")\nplt.show()", "_____no_output_____" ], [ "bool_hispanic_95 = combined[\"hispanic_per\"] > 95\ncombined[bool_hispanic_95][\"SCHOOL NAME\"]", "_____no_output_____" ] ], [ [ "The schools listed above appear to primarily be geared towards recent immigrants to the US. These schools have a lot of students who are learning English, which would explain the lower SAT scores.", "_____no_output_____" ] ], [ [ "bool_hispanic_10 = (combined[\"hispanic_per\"] < 10) & (combined[\"sat_score\"] > 1800)\ncombined[bool_hispanic_10][\"SCHOOL NAME\"]", "_____no_output_____" ] ], [ [ "Many of the schools above appear to be specialized science and technology schools that receive extra funding, and only admit students who pass an entrance exam. This doesn't explain the low hispanic_per, but it does explain why their students tend to do better on the SAT -- they are students from all over New York City who did well on a standardized test.", "_____no_output_____" ], [ "## Investigating gender differences", "_____no_output_____" ] ], [ [ "gender_cols = [\"male_per\", \"female_per\"]\ncorrelations[gender_cols].plot.bar()\nplt.show()", "_____no_output_____" ] ], [ [ "In the plot above, we can see that a high percentage of females at a school positively correlates with SAT score, whereas a high percentage of males at a school negatively correlates with SAT score. Neither correlation is extremely strong.", "_____no_output_____" ] ], [ [ "combined.plot.scatter(x = \"female_per\", y = \"sat_score\")", "_____no_output_____" ] ], [ [ "Based on the scatterplot, there doesn't seem to be any real correlation between sat_score and female_per. However, there is a cluster of schools with a high percentage of females (60 to 80), and high SAT scores.", "_____no_output_____" ] ], [ [ "bool_female = (combined[\"female_per\"] > 60) & (combined[\"sat_score\"] > 1700)\ncombined[bool_female][\"SCHOOL NAME\"]", "_____no_output_____" ] ], [ [ "These schools appears to be very selective liberal arts schools that have high academic standards.", "_____no_output_____" ], [ "## AP_test takers vs SAT\n\nIn the U.S., high school students take Advanced Placement (AP) exams to earn college credit. There are AP exams for many different subjects.", "_____no_output_____" ] ], [ [ "combined[\"ap_per\"] = combined[\"AP Test Takers \"]/ combined[\"total_enrollment\"]\ncombined.plot.scatter(x = \"ap_per\", y = \"sat_score\")", "_____no_output_____" ] ], [ [ "It looks like there is a relationship between the percentage of students in a school who take the AP exam, and their average SAT scores. It's not an extremely strong correlation, though.", "_____no_output_____" ], [ "## potential next steps:\n* Determing whether there's a correlation between class size and SAT scores\n* Figuring out which neighborhoods have the best schools\n * If we combine this information with a dataset containing property values, we could find the least expensive neighborhoods that have good schools.\n* Investigating the differences between parent, teacher, and student responses to surveys.\n* Assigning scores to schools based on sat_score and other attributes.", "_____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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb0c65c3fb28d2658f6fc28d783d752b01a14291
15,677
ipynb
Jupyter Notebook
Summit/2019/resources/Notebooks-Wed/recommendations-popularity-recipe.ipynb
arturrutkiewicz-divae/aep-rfm-score
705fc54e505fdb8763073401be7b97c81474b0a9
[ "Apache-2.0" ]
null
null
null
Summit/2019/resources/Notebooks-Wed/recommendations-popularity-recipe.ipynb
arturrutkiewicz-divae/aep-rfm-score
705fc54e505fdb8763073401be7b97c81474b0a9
[ "Apache-2.0" ]
null
null
null
Summit/2019/resources/Notebooks-Wed/recommendations-popularity-recipe.ipynb
arturrutkiewicz-divae/aep-rfm-score
705fc54e505fdb8763073401be7b97c81474b0a9
[ "Apache-2.0" ]
null
null
null
34.229258
505
0.548957
[ [ [ "## Recipe Builder Actions Overview\n\n### Saving a File Cell\nIf you wish to save the contents of a cell, simply run it. The `%%writefile` command at the top of the cell will write the contents of the cell to the file named at the top of the cell. You should run the cells manually when applicable. However, **pressing any of the actions at the top will automatically run all file cells relevant to the action**.\n\n### Training and Scoring\nPress the associated buttons at the top in order to run training or scoring. The training output will be shown below the `pipeline.py` cell and scoring output will be shown below the `datasaver.py` cell. You must run training at least once before you can run scoring. You may delete the output cell(s). Running training the first time or after changing `requirements.txt` will be slower since the dependencies for the recipe need to be installed, but subsequent runs will be signigicantly faster.\n\n### Creating the Recipe\nWhen you are done editing the recipe and satisfied with the training/scoring output, you can create a recipe from the notebook by pressing `Create Recipe`. After pressing it, you will see a spinner that will spin until the recipe creation has finished. If the recipe creation is successful the spinner will be replaced by an external link that you can click to navigate to the created recipe.\n\n\n## Caution!\n* **Do not delete any of the file cells**\n* **Do not edit the `%%writefile` line at the top of the file cells**\n* **Do not refresh the JupyterLab page while the recipe is being created**\n</br>\n</br>\n---", "_____no_output_____" ], [ "#### **Requirements file** (Optional)\nAdd additional libraries you wish to use in the recipe to the cell below. You can specify the version number if necessary. The file cell below is a **commented out example**.", "_____no_output_____" ] ], [ [ "\n# pandas=0.22.0\n# numpy", "_____no_output_____" ] ], [ [ "Search here for additional libraries https://anaconda.org/. This is the list of main **libraries already in use**: </br>\n`python=3.5.2` `scikit-learn` `pandas` `numpy` `data_access_sdk_python` </br>\n**Warning: libraries or specific versions you add may be incompatible with the above libraries**.", "_____no_output_____" ], [ "#### **Configuration file**\nSpecify the dataset(s) you wish to use for training/scoring and add hyperparameters. To find the dataset ids go to the **Data tab** in Adobe Experience Platform.", "_____no_output_____" ] ], [ [ "\n\n{\n \"trainingDataSetId\": \"5c927f59012c9615168ba7ec\",\n \"scoringDataSetId\": \"5c927f59012c9615168ba7ec\",\n \"scoringResultsDataSetId\":\"5c927bd95a5f721515516861\",\n \"ACP_DSW_TRAINING_XDM_SCHEMA\":\"https://ns.adobe.com/platformlab05/schemas/a48b2c12ba042a002ffeb75d11ada4c3\",\n \"ACP_DSW_SCORING_RESULTS_XDM_SCHEMA\":\"https://ns.adobe.com/platformlab05/schemas/bd7afab62bf2588fe14b6cb15cb6ee0d\",\n \"num_recommendations\": \"5\",\n \"sampling_fraction\": \"0.5\"\n}", "_____no_output_____" ] ], [ [ "**The following configuration parameters are automatically set for you when you train/score:** </br>\n`ML_FRAMEWORK_IMS_USER_CLIENT_ID` `ML_FRAMEWORK_IMS_TOKEN` `ML_FRAMEWORK_IMS_ML_TOKEN` `ML_FRAMEWORK_IMS_TENANT_ID` `saveData`", "_____no_output_____" ], [ "---", "_____no_output_____" ], [ "#### **Evaluator file**\nFill in how you wish to evaluate your trained recipe and how your training data should be split. You can also use this file to load and prepare the training data.", "_____no_output_____" ] ], [ [ "\n\nfrom ml.runtime.python.Interfaces.AbstractEvaluator import AbstractEvaluator\nfrom data_access_sdk_python.reader import DataSetReader\nimport numpy as np\nimport pandas as pd\n\nclass Evaluator(AbstractEvaluator):\n def __init__(self):\n print(\"Initiate\")\n self.user_id_column = '_platformlab05.userId'\n self.recommendations_column = '_platformlab05.recommendations'\n self.item_id_column = '_platformlab05.itemId'\n\n\n def evaluate(self, data=[], model={}, configProperties={}):\n print (\"Evaluation evaluate triggered\")\n \n # remove columns having none\n data = data[data[self.item_id_column].notnull()]\n \n data_grouped_by_user = data.groupby(self.user_id_column).agg(\n {self.item_id_column: lambda x: '#'.join(x)})\\\n .rename(columns={self.item_id_column:'interactions'}).reset_index()\n \n data_recommendations = model.predict(data)\n \n merged_df = pd.merge(data_grouped_by_user, data_recommendations, on=[self.user_id_column]).reset_index()\n \n def compute_recall(row):\n set_interactions = set(row['interactions'].split('#'))\n set_recommendations = set(row[self.recommendations_column].split('#'))\n inters = set_interactions.intersection(set_recommendations)\n if len(inters) > 0:\n return 1\n return 0\n \n def compute_precision(row):\n set_interactions = set(row['interactions'].split('#'))\n list_recommendations = row[self.recommendations_column].split('#')\n score = 0\n weight = 0.5\n for rec in list_recommendations:\n if rec in set_interactions:\n score = score + weight\n weight = weight / 2\n\n return score\n\n\n merged_df['recall'] = merged_df.apply(lambda row: compute_recall(row), axis=1)\n merged_df['precision'] = merged_df.apply(lambda row: compute_precision(row), axis=1)\n\n recall = merged_df['recall'].mean()\n precision = merged_df['precision'].mean()\n\n metric = [{\"name\": \"Recall\", \"value\": recall, \"valueType\": \"double\"},\n {\"name\": \"Precision\", \"value\": precision, \"valueType\": \"double\"}]\n\n print(metric)\n\n return metric\n\n def split(self, configProperties={}):\n #########################################\n # Load Data\n #########################################\n prodreader = DataSetReader(client_id=configProperties['ML_FRAMEWORK_IMS_USER_CLIENT_ID'],\n user_token=configProperties['ML_FRAMEWORK_IMS_TOKEN'],\n service_token=configProperties['ML_FRAMEWORK_IMS_ML_TOKEN'])\n\n df = prodreader.load(data_set_id=configProperties['trainingDataSetId'],\n ims_org=configProperties['ML_FRAMEWORK_IMS_TENANT_ID'])\n\n train = df[:]\n test = df[:]\n\n return train, test\n", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "#### **Training Data Loader file**\nCall your Evaluator split here and/or use this file to load and prepare the training data.", "_____no_output_____" ] ], [ [ "\nimport numpy as np\nimport pandas as pd\nfrom data_access_sdk_python.reader import DataSetReader\n\nfrom recipe.evaluator import Evaluator\n\ndef load(configProperties):\n print(\"Training Data Load Start\")\n evaluator = Evaluator()\n (train_data, _) = evaluator.split(configProperties)\n\n print(\"Training Data Load Finish\")\n return train_data\n\n", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "#### **Scoring Data Loader file**\nUse this file to load and prepare your scoring data.", "_____no_output_____" ] ], [ [ "\n\nimport numpy as np\nimport pandas as pd\nfrom data_access_sdk_python.reader import DataSetReader\n\ndef load(configProperties):\n\n print(\"Scoring Data Load Start\")\n\n #########################################\n # Load Data\n #########################################\n prodreader = DataSetReader(client_id=configProperties['ML_FRAMEWORK_IMS_USER_CLIENT_ID'],\n user_token=configProperties['ML_FRAMEWORK_IMS_TOKEN'],\n service_token=configProperties['ML_FRAMEWORK_IMS_ML_TOKEN'])\n\n df = prodreader.load(data_set_id=configProperties['scoringDataSetId'],\n ims_org=configProperties['ML_FRAMEWORK_IMS_TENANT_ID'])\n\n print(\"Scoring Data Load Finish\")\n\n return df\n", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "#### **Pipeline file**\nFill in the training and scoring functions for your recipe. Training output will be added below this file cell.", "_____no_output_____" ] ], [ [ "\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\n\nclass PopularityBasedRecommendationModel():\n def __init__(self, num_to_recommend):\n self.num_to_recommend = num_to_recommend\n self.recommendations = ['dummy']\n self.user_id_column = '_platformlab05.userId'\n self.recommendations_column = '_platformlab05.recommendations'\n self.item_id_column = '_platformlab05.itemId'\n \n def fit(self, df):\n df = df[df[self.item_id_column].notnull()]\n self.recommendations = [item for item, freq in \n Counter(list(df[self.item_id_column].values)).most_common(self.num_to_recommend)]\n\n \n def predict(self, df):\n # remove columns having none\n df = df[df[self.item_id_column].notnull()]\n \n df_grouped_by_user = df.groupby(self.user_id_column).agg(\n {self.item_id_column: lambda x: ','.join(x)})\\\n .rename(columns={self.item_id_column:'interactions'}).reset_index()\n \n df_grouped_by_user[self.recommendations_column] = '#'.join(self.recommendations)\n df_grouped_by_user = df_grouped_by_user.drop(['interactions'],axis=1)\n \n return df_grouped_by_user\n\ndef train(configProperties, data):\n\n print(\"Train Start\")\n\n #########################################\n # Extract fields from configProperties\n #########################################\n num_recommendations = int(configProperties['num_recommendations'])\n\n #########################################\n # Fit model\n #########################################\n model = PopularityBasedRecommendationModel(num_recommendations)\n\n model.fit(data)\n\n print(\"Train Complete\")\n\n return model\n\ndef score(configProperties, data, model):\n\n print(\"Score Start\")\n\n result = model.predict(data)\n\n print(\"Score Complete\")\n\n return result\n", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "#### **Data Saver file**\nAdd how you wish to save your scored data. **By default saveData=False, since saving data is not relevant when scoring from the notebook.** Scoring output will be added below this cell.", "_____no_output_____" ] ], [ [ "\nfrom data_access_sdk_python.writer import DataSetWriter\nfrom functools import reduce\nimport json\n\ndef save(configProperties, prediction):\n \n print(prediction)\n prodwriter = DataSetWriter(client_id=configProperties['ML_FRAMEWORK_IMS_USER_CLIENT_ID'],\n user_token=configProperties['ML_FRAMEWORK_IMS_TOKEN'],\n service_token=configProperties['ML_FRAMEWORK_IMS_ML_TOKEN'])\n \n batch_id = prodwriter.write(data_set_id=configProperties['scoringResultsDataSetId'],\n dataframe=prediction,\n ims_org=configProperties['ML_FRAMEWORK_IMS_TENANT_ID'])\n print(\"Data written successfully to platform:\",batch_id)", "_____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", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb0c7e2d725f6daf6216e8a30fe9f5a446b4fb93
34,615
ipynb
Jupyter Notebook
BIDAL_AFLALO_DETAILED_CODE.ipynb
NoamAflalo/Interactive-App-Based-on-Bokeh
b3a16f2dcd3db5199b065619f974978668d79a6c
[ "MIT" ]
null
null
null
BIDAL_AFLALO_DETAILED_CODE.ipynb
NoamAflalo/Interactive-App-Based-on-Bokeh
b3a16f2dcd3db5199b065619f974978668d79a6c
[ "MIT" ]
null
null
null
BIDAL_AFLALO_DETAILED_CODE.ipynb
NoamAflalo/Interactive-App-Based-on-Bokeh
b3a16f2dcd3db5199b065619f974978668d79a6c
[ "MIT" ]
1
2021-01-16T11:19:16.000Z
2021-01-16T11:19:16.000Z
36.590909
569
0.510097
[ [ [ "# <center>Python Project : intercative pricing app based on Bokeh</center>\n#### Ines BIDAL, Noam AFLALO", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "import pandas as pd\nimport numpy as np\nimport dask.array as da\nimport matplotlib.pyplot as plt\nimport bokeh\nimport math\nimport scipy.stats as stats\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nfrom scipy.sparse import diags\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.stats import norm\nimport numpy.linalg as lng\nimport ipywidgets as widgets", "_____no_output_____" ], [ "from bokeh.io import push_notebook, show, output_notebook\nfrom bokeh.layouts import row\nfrom bokeh.plotting import figure, output_file, reset_output\nfrom bokeh.core.properties import Instance, String\nfrom bokeh.models import ColumnDataSource, LayoutDOM\nfrom bokeh.util.compiler import TypeScript", "_____no_output_____" ], [ "# See how the memory is working \nfrom dask.distributed import Client, progress\nclient = Client(processes=False, threads_per_worker=4,\n n_workers=1, memory_limit='2e9')\nclient", "_____no_output_____" ] ], [ [ "# Part I : Graphical representation using Bokeh of the accuracy of the Euler Implicit Scheme to price European options.\n\n## A/ Pricing using Black-Scholes (Closed form formula)", "_____no_output_____" ] ], [ [ "#Black and Scholes formula for European put\ndef P_BS(s, K, T):\n d1 = math.log(s / (K * math.exp(-r*T))) / (sigma * math.sqrt(T)) + sigma * math.sqrt(T) / 2\n d2 = math.log(s / (K * math.exp(- r * T))) / (sigma * math.sqrt(T)) - sigma * math.sqrt(T) / 2\n Nd1 = stats.norm.cdf(- d1, loc=0, scale=1)\n Nd2 = stats.norm.cdf(- d2, loc=0, scale=1)\n P = math.exp(- r * T) * K * Nd2 - s * Nd1\n return P\n\n\n#Black and Scholes formula for European call\ndef C_BS(s, K, T):\n d1 = math.log(s/(K* math.exp(-r*T))) / (sigma * math.sqrt(T)) + sigma * math.sqrt(T) / 2\n d2 = math.log(s/(K* math.exp(-r*T))) / (sigma * math.sqrt(T)) - sigma * math.sqrt(T) / 2\n Nd1 = stats.norm.cdf(d1, loc=0, scale=1)\n Nd2 = stats.norm.cdf(d2, loc=0, scale=1)\n C = -math.exp(r*T) * K * Nd2 + s * Nd1\n return C", "_____no_output_____" ] ], [ [ "## B/ Pricing using the Implicit Euler Scheme (approximation) ", "_____no_output_____" ] ], [ [ "# initialisation\nS=100\nK = 100\nr = 0.01\nT = 1\nsigma = 0.2", "_____no_output_____" ], [ "# NUMERICAL PARAMETERS\nN=10\nI=10\nS_min=0; S_max=200;\nh = (S_max - S_min) / (I + 1)\ndt = T / N\nSval = 80", "_____no_output_____" ], [ "# payoff function \ndef u0(s, K=K) : \n return np.maximum(0, K - s)\n\ndef u_left(t, S_min=S_min) : \n return K * np.exp(-r * t) - S_min\n\ndef u_right(t) :\n return 0\n\ndef u_call(s, K):\n return np.maximum(0, s - K)", "_____no_output_____" ], [ "def IE(I,N, K, S0, sigma=sigma, T=T):\n \n \n # NUMERICAL PARAMETERS\n S_min = max(0, S0 - 100)\n S_max = S0 + 100\n Sval = 0.8 * S0\n dt = T / N\n h = (S_max - S_min) / I\n \n #vectors\n S = np.array([(S_min + j * h) for j in range(1,I+1)])\n\n tn = np.array([n * dt for n in range(N+1)])\n\n alpha = ((sigma ** 2)*(S ** 2)/(2 * (h ** 2)))\n\n beta = (r / (2 * h)) * S\n \n # q(t)\n\n def q(t):\n y = np.zeros((I,1))\n y[0] = ( - alpha[1] + beta[1]) * u_left(t, S_min)\n y[-1] = ( - alpha[-1] - beta[-1]) * u_right(t)\n return y\n\n # A\n array = list(- alpha[:- 2] - beta[:- 2])\n array.append(0)\n array = np.array(array)\n matToTridiag = np.array([- alpha[1::] + beta[1::],2 * alpha + r,array])\n offset = [- 1,0,1]\n\n A = diags(matToTridiag,offset).toarray()\n \n U = u0(S, K).reshape(I, 1)\n \n for i in range(N):\n U = lng.solve(dt * A + np.eye(I), -q(tn[i + 1])*dt +U)\n\n \n return(U, S)", "_____no_output_____" ] ], [ [ "# Graphical comparison between the two methods of pricing using bokeh", "_____no_output_____" ] ], [ [ "def plotter_eu_put(I, N, K, S0, sigma=sigma, T=T) :\n V = IE(I, N, K, S0, sigma, T)\n \n opts = dict(plot_width=550, plot_height=350, min_border=0, \n title='European Put option')\n p = figure(**opts)\n r1 = p.line(V[1], V[0].ravel(), line_width=2, legend_label='Euler Scheme')\n r2 = p.line(V[1], [u0(i, K) for i in V[1]], line_width=2, \n color='red', legend_label='Payoff')\n r3 = p.line(V[1], [P_BS(i, K, T) for i in V[1]], line_width=1, \n color='black', legend_label='Black & Scholes', \n line_dash='4 4')\n p.xaxis.axis_label = 'S'\n p.yaxis.axis_label = 'Price'\n \n try :\n reset_output()\n output_notebook()\n except :\n try : \n output_notebook()\n except :\n pass\n \n t1 = show(p, notebook_handle=True)", "_____no_output_____" ], [ "def plotter_eu_call(I, N, K, S0, sigma=sigma, T=T):\n V = IE(I, N, K, S0, sigma, T)\n call = V[0].ravel() + V[1] - K * np.exp(-r*T)\n \n opts = dict(plot_width=550, plot_height=350, min_border=0, \n title='European Put option')\n p = figure(**opts)\n r1 = p.line(V[1], call, line_width=2, legend_label='Euler Scheme')\n r2 = p.line(V[1], [u_call(i, K) for i in V[1]], line_width=2, \n color='red', legend_label='Payoff')\n r3 = p.line(V[1], [C_BS(i, K, T) for i in V[1]], line_width=1, \n color='black', legend_label='Black & Scholes', \n line_dash='4 4')\n p.xaxis.axis_label = 'S'\n p.yaxis.axis_label = 'Price'\n \n try :\n reset_output()\n output_notebook()\n except :\n try : \n output_notebook()\n except :\n pass\n \n t1 = show(p, notebook_handle=True)", "_____no_output_____" ], [ "from ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets\n\ndef func(Product):\n \n if Product == 'Put' :\n w = interact(lambda I, N, K, S0, sig, T : plotter_eu_put( I, N, K, S0, sig, T), \n I=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Spot mesh I'), \n N=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Time Mesh N' ), \n K=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Strike K'), \n S0=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Spot S'), \n sig=widgets.BoundedFloatText(value=0.2, min=0, max=1.0, step=0.1, description='Volatility:', disabled=False),\n T=widgets.BoundedFloatText(value=1, min=0, max=2.0, step=0.1, description='Maturity:', disabled=False))\n \n elif Product == 'Call' :\n w = interact(lambda I, N, K, S0, sig, T : plotter_eu_call( I, N, K, S0, sig, T), \n I=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Spot mesh I'), \n N=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Time Mesh N' ), \n K=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Strike K'), \n S0=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Spot S'), \n sig=widgets.BoundedFloatText(value=0.2, min=0, max=1.0, step=0.1, description='Volatility:', disabled=False),\n T=widgets.BoundedFloatText(value=1, min=0, max=2.0, step=0.1, description='Maturity:', disabled=False))\n \nwf = interact(func, Product=['Put', 'Call'])", "_____no_output_____" ] ], [ [ "# Part II : Pricing of exotic options using different kinds of Monte Carlo simulation using Dask and Bokeh", "_____no_output_____" ] ], [ [ "T = 1\nS0 = 100 # Initial price \nr = 0.01 # Risk free interest rate\nsigma = 0.2 # Volatility\nrho = -0.5 # Correlation\nkappa = 2.5 # Revert rate\ntheta = 0.05 # Long-term volatility\nxi = 0.04 # Volatility of instantaneous volatility\nv0 = 0.2 # Initial instantaneous volatility\nAccumulationlevel = 70 # Accumulation Level\nB = 110 # Barrier Level\nnb_steps = 252 #Nombre de steps\nnb_path = 1000 #Nombre de paths \nS = np.arange(50,150,252)\nt = np.arange(0.1,1)\nsurface=True", "_____no_output_____" ] ], [ [ "## A/ Pricing of an accumulator under constant volatility model (Black-Scholes)", "_____no_output_____" ] ], [ [ "# Nous avons rencontré un problème avec Dask : on ne peut pas assigner des parties de array exemple : arr[0] = 1 impossible a faire. \n# Une solution est de concatener des bouts de array. Cependant, on perd en rapidité, la version numpy est même préférée.\n# Version Dask:\n#from tqdm.autonotebook import tqdm\n#def Black_Scholes_path(S0, T, r, sigma, nb_steps):\n# '''Function that generate B&S path with constant volatility sigma'''\n# S = da.from_array(np.array([S0]), chunks=(1,))\n# dt = T / nb_steps\n# dask_arrays = [S]\n# for t in range(1, nb_steps):\n# eps = np.random.standard_normal(1) # pseudorandom numbers\n# # arr = da.from_array(np.array([dask_arrays[-1] * math.exp((r-0.5*sigma**2 ) * dt + sigma * eps * math.sqrt(dt))]), \n# # chunks=1)\n# arr = dask_arrays[-1] * math.exp((r-0.5*sigma**2 ) * dt + sigma * eps * math.sqrt(dt))\n# dask_arrays.append(arr)\n# return da.concatenate(dask_arrays, axis=0).compute()\n", "_____no_output_____" ], [ "#Version Numpy:\ndef Black_Scholes_path(S0, T, r, sigma, nb_steps):\n '''Function that generate B&S path with constant volatility sigma'''\n \n S = np.zeros(nb_steps)\n S[0] = S0\n dt = T / nb_steps\n \n for t in range(1, nb_steps):\n eps = np.random.standard_normal(1) # pseudorandom numbers\n S[t] = S[t - 1] * np.exp((r - 0.5 * sigma**2 ) * dt + sigma * eps * np.sqrt(dt))\n \n return S", "_____no_output_____" ] ], [ [ "## B/ Pricing of an accumulator under non constant volatility model (Heston model)", "_____no_output_____" ] ], [ [ "# Nous avons rencontré un problème avec Dask : on ne peut pas assigner des parties de array exemple : arr[0] = 1 impossible a faire. \n# Une solution est de concatener des bouts de array. Cependant, on perd en rapidité, la version numpy est même préférée.\n# Version Dask:\n#def HeMC (S0, r, v0, rho, kappa, theta, xi, T, nb_steps):\n# '''Generate a Monte Carlo simulation for the Heston model'''\n#\n# # Generate random Brownian Motion\n# R = np.array([0, 0])\n# COV = np.matrix([[1, rho], [rho, 1]])\n# W = np.random.multivariate_normal(R, COV, nb_steps)\n# W = da.from_array(W, chunks=(2, 10))\n# W_S = W[:, 0]\n# W_v = W[:, 1]\n# dt = T / nb_steps\n# # Generate paths\n# arr = np.zeros((nb_steps, 1))\n# arr[:, 0] = v0\n# v = [da.from_array(arr, chunks=1)]\n# S = [da.from_array(np.array([S0]), chunks=1)]\n#\n# for t in range(1,nb_steps):\n# v_tmp = v[-1] + kappa * (theta - v[-1]) * dt + xi * np.sqrt(v[-1]) * np.sqrt(dt) * W_v[t] \n# v.append(v_tmp)\n#\n# S_tmp = S[-1] * np.exp((r - 0.5 * v[-1][0]) * dt + np.sqrt(v[-1][0] * dt) * W_S[t])\n# S.append(S_tmp)\n#\n# S = da.concatenate(S, axis=0).compute()\n# vol = da.concatenate(v, axis=1).compute()\n# \n# return S, vol", "_____no_output_____" ], [ "# Version Numpy:\n\ndef HeMC (S0, r, v0, rho, kappa, theta, xi, T, nb_steps):\n '''Generate a Monte Carlo simulation for the Heston model'''\n\n # Generate random Brownian Motion\n R = np.array([0, 0])\n COV = np.matrix([[1, rho], [rho, 1]])\n W = np.random.multivariate_normal(R, COV, nb_steps)\n W_S = W[:, 0]\n W_v = W[:, 1]\n dt = T / nb_steps\n # Generate paths\n v = np.zeros(nb_steps)\n v[0] = v0\n S = np.zeros(nb_steps)\n S[0] = S0\n \n \n expiry_dates = np.zeros(nb_steps)\n strikes = np.zeros(nb_steps)\n strikes[0] = S0\n vol = np.zeros((nb_steps,nb_steps))\n vol[:, 0] = v0\n \n for t in range(1,nb_steps):\n expiry_dates[t] = t * dt\n v[t] = v[t-1] + kappa * (theta - v[t-1]) * dt + xi * np.sqrt(v[t-1]) * np.sqrt(dt) * W_v[t]\n vol[:, t] = v[t]\n S[t] = S[t-1] * np.exp((r - 0.5 * v[t-1]) * dt + np.sqrt(v[t-1] * dt) * W_S[t])\n strikes = S[t]\n return S, vol\n", "_____no_output_____" ], [ "def Accumulator(S0, kappa, theta, xi, Accumulationlevel, \n sigma, B, Type, Model, T=T,\n nb_path=nb_path, nb_steps=nb_steps, r=r): ## ca calcule le prix d'un accu, on precise si on veut priceer avec barrier continue ou discret + si on veut faire avec vol constante ou stochastique. \n \n currentPayoff = np.zeros(nb_path)\n \n if Type == \"Continuous\":\n shift=np.exp(0.5826 * sigma * np.sqrt(T/nb_steps))\n B = B / shift\n \n for i in range(nb_path):\n if Model == \"BS\":\n S = Black_Scholes_path(S0, T, r, sigma, nb_steps)\n else: \n S= HeMC (S0, r, v0, rho, kappa, theta, xi, T, nb_steps)[0]\n if (i == 0 and surface):\n plotter_heston(S0, kappa, theta, xi, v0, rho, nb_steps, \n r, T) # Si on fait un pricing avec vol stochastique alors on affiche aussi une surface de volatilite utilise. \n for t in range(1, nb_steps):\n if S[t] > B:\n break\n elif (S[t] < B) & (S[t] > Accumulationlevel):\n currentPayoff[i] = currentPayoff[i] + (S[t]- Accumulationlevel)\n \n else: \n currentPayoff[i] = currentPayoff[i] + 2 * (S[t]- Accumulationlevel)\n print('The price for this configuration is : '+str(np.exp(-r * T) * np.mean(currentPayoff)))\n return np.exp(-r * T) * np.mean(currentPayoff) ", "_____no_output_____" ], [ "# Code Java Script\nTS_CODE = \"\"\"\n\nimport {LayoutDOM, LayoutDOMView} from \"models/layouts/layout_dom\"\nimport {ColumnDataSource} from \"models/sources/column_data_source\"\nimport {LayoutItem} from \"core/layout\"\nimport * as p from \"core/properties\"\n\ndeclare namespace vis {\n class Graph3d {\n constructor(el: HTMLElement, data: object, OPTIONS: object)\n setData(data: vis.DataSet): void\n }\n\n class DataSet {\n add(data: unknown): void\n }\n}\n\nconst OPTIONS = {\n width: '600px',\n height: '600px',\n style: 'surface',\n showPerspective: true,\n showGrid: true,\n keepAspectRatio: true,\n verticalRatio: 1.0,\n legendLabel: 'stuff',\n cameraPosition: {\n horizontal: -0.35,\n vertical: 0.22,\n distance: 1.8,\n },\n}\n\nexport class Surface3dView extends LayoutDOMView {\n model: Surface3d\n\n private _graph: vis.Graph3d\n\n initialize(): void {\n super.initialize()\n\n const url = \"https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.min.js\"\n const script = document.createElement(\"script\")\n script.onload = () => this._init()\n script.async = false\n script.src = url\n document.head.appendChild(script)\n }\n\n private _init(): void {\n\n this._graph = new vis.Graph3d(this.el, this.get_data(), OPTIONS)\n\n this.connect(this.model.data_source.change, () => {\n this._graph.setData(this.get_data())\n })\n }\n\n get_data(): vis.DataSet {\n const data = new vis.DataSet()\n const source = this.model.data_source\n for (let i = 0; i < source.get_length()!; i++) {\n data.add({\n x: source.data[this.model.x][i],\n y: source.data[this.model.y][i],\n z: source.data[this.model.z][i],\n })\n }\n return data\n }\n\n get child_models(): LayoutDOM[] {\n return []\n }\n\n _update_layout(): void {\n this.layout = new LayoutItem()\n this.layout.set_sizing(this.box_sizing())\n }\n}\n\nexport namespace Surface3d {\n export type Attrs = p.AttrsOf<Props>\n\n export type Props = LayoutDOM.Props & {\n x: p.Property<string>\n y: p.Property<string>\n z: p.Property<string>\n data_source: p.Property<ColumnDataSource>\n }\n}\n\nexport interface Surface3d extends Surface3d.Attrs {}\n\nexport class Surface3d extends LayoutDOM {\n properties: Surface3d.Props\n __view_type__: Surface3dView\n\n constructor(attrs?: Partial<Surface3d.Attrs>) {\n super(attrs)\n }\n\n static __name__ = \"Surface3d\"\n\n static init_Surface3d() {\n this.prototype.default_view = Surface3dView\n\n this.define<Surface3d.Props>({\n x: [ p.String ],\n y: [ p.String ],\n z: [ p.String ],\n data_source: [ p.Instance ],\n })\n }\n}\n\"\"\"\n\nclass Surface3d(LayoutDOM):\n __implementation__ = TypeScript(TS_CODE)\n data_source = Instance(ColumnDataSource)\n\n x = String\n\n y = String\n\n z = String", "_____no_output_____" ], [ "def plotter_heston(S0, kappa, theta, xi, \n v0=0.2, rho=-0.2, nb_steps=252, r=0.1, T=1):\n vol = HeMC (S0, r, v0, rho, kappa, theta, xi, T, nb_steps)[1]\n ny, nx=vol.shape\n x = np.linspace(T, 0, nx)\n y = np.linspace(0, 2*S0, ny)\n xv, yv = np.meshgrid(x, y)\n xv = xv.ravel() * 2e6\n yv = yv.ravel() * 1e4\n zv = vol.ravel() * 1e4\n data = dict(x=xv, y=yv, z=zv)\n source = ColumnDataSource(data=data)\n surface = Surface3d(x=\"x\", y=\"y\", z=\"z\", data_source=source, width=6000, height=6000)\n reset_output()\n output_file('foo.html')\n show(surface)", "_____no_output_____" ], [ "w = interact(lambda S, k, theta, xi, Acc, sig, B, Type, Model, T, n_p, n_s : Accumulator(S, k, theta, xi, Acc, sig, B, Type, Model, T, n_p, n_s), \n S=widgets.IntSlider(min=0, max=200, step=1, value=100, description='Spot Price:'),\n k=widgets.FloatText(value=0.3, description='Revert Rate:', disabled=False),\n theta=widgets.FloatText(value=0.2, description='Long Term Vol:', disabled=False),\n xi=widgets.FloatText(value=0.2, description='Vol of vol:', disabled=False), \n Acc=widgets.IntSlider(min=0, max=200, step=10, value=70, description='Accu Level:'), \n sig=widgets.FloatSlider(value=0.2, min=0, max=1.0, step=0.1, description='BS Vol:'),\n B=widgets.IntSlider(min=0, max=200, step=10, value=110, description='Barrier:'),\n Type=['Continuous', 'Discret'], \n Model=['BS', 'Heston'], \n T=widgets.BoundedFloatText(value=1, min=0, max=2.0, step=0.1, description='T:', disabled=False),\n n_p=widgets.IntText(value=1000, description='Number path:', disabled=False),\n n_s=widgets.IntText(value=252, description='Number Steps:', disabled=False))\n", "_____no_output_____" ] ], [ [ "# Conclusion: API summarizing the whole project ", "_____no_output_____" ] ], [ [ "def func(Product):\n if Product == 'Put' :\n w = interact(lambda I, N, K, S0, sig, T : plotter_eu_put( I, N, K, S0, sig, T), \n I=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Spot mesh I'), \n N=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Time Mesh N' ), \n K=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Strike K'), \n S0=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Spot S'), \n sig=widgets.BoundedFloatText(value=0.2, min=0, max=1.0, step=0.1, description='Volatility:', disabled=False),\n T=widgets.BoundedFloatText(value=1, min=0, max=2.0, step=0.1, description='Maturity:', disabled=False))\n \n elif Product == 'Call' :\n w = interact(lambda I, N, K, S0, sig, T : plotter_eu_call( I, N, K, S0, sig, T), \n I=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Spot mesh I'), \n N=widgets.IntSlider(min=10, max=30, step=1, value=20, description='Time Mesh N' ), \n K=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Strike K'), \n S0=widgets.IntSlider(min=10, max=200, step=10, value=100, description='Spot S'), \n sig=widgets.BoundedFloatText(value=0.2, min=0, max=1.0, step=0.1, description='Volatility:', disabled=False),\n T=widgets.BoundedFloatText(value=1, min=0, max=2.0, step=0.1, description='Maturity:', disabled=False))\n \n elif Product == 'Accumulator' :\n w = interact(lambda S, k, theta, xi, Acc, sig, B, Type, Model, T, n_p, n_s : Accumulator(S, k, theta, xi, Acc, sig, B, Type, Model, T, n_p, n_s), \n S=widgets.IntSlider(min=0, max=200, step=1, value=100, description='Spot Price:'),\n k=widgets.FloatText(value=0.3, description='Revert Rate:', disabled=False),\n theta=widgets.FloatText(value=0.2, description='Long Term Vol:', disabled=False),\n xi=widgets.FloatText(value=0.2, description='Vol of vol:', disabled=False), \n Acc=widgets.IntSlider(min=0, max=200, step=10, value=70, description='Accu Level:'), \n sig=widgets.FloatSlider(value=0.2, min=0, max=1.0, step=0.1, description='BS Vol:'),\n B=widgets.IntSlider(min=0, max=200, step=10, value=110, description='Barrier:'),\n Type=['Continuous', 'Discret'], \n Model=['BS', 'Heston'], \n T=widgets.BoundedFloatText(value=1, min=0, max=2.0, step=0.1, description='T:', disabled=False),\n n_p=widgets.IntText(value=1000, description='Number path:', disabled=False),\n n_s=widgets.IntText(value=252, description='Number Steps:', disabled=False))\n\n\nwf = interact(func, Product=['Put', 'Call', 'Accumulator'])", "_____no_output_____" ] ], [ [ "# Testing of the code using the module ipytest", "_____no_output_____" ] ], [ [ "import ipytest\nipytest.autoconfig()", "_____no_output_____" ], [ "%%run_pytest[clean]\n\ndef test_vanilla_options():\n assert np.round(P_BS(100, 100, 1),0) == np.round(C_BS(100, 100, 1),0) #ATM Call et Put options have the same price.\n assert np.abs((C_BS(100, 150, 1)- P_BS(100, 150, 1) - (100 - 150))/(100 - 150))<0.03 # Verification of the put call parity.\n\ndef test_comparison_BS_Euler():\n #Verifications that the Euler implicit scheme give approximately the same results as the BS closed form formula.\n assert np.round(np.abs(IE(20,20, 100, 100, sigma=sigma, T=T)[0][9]- P_BS(100, 100, 1)),0) == 0\n Smax= 2 * 100\n assert np.round(np.abs(IE(20,20, 100, 100, sigma=sigma, T=T)[0][19]-P_BS(Smax, 100, 1)),0) == 0\n assert np.round(np.abs((IE(20,20, 100, 100, sigma=sigma, T=T)[0][0]-P_BS(0.0001, 100, 1))/P_BS(0.0001, 100, 1)),0)<0.01\n", ".. [100%]\n2 passed in 0.05s\n" ] ], [ [ "The folowwing tests check the following:\n\n1) All parameters being equal, an accumulator monitored discretely should be more expansive than an accumulator monitored continuously. Indeed, the probability that the barrier is reached is higher when it is monitored continuously. When the barrier level is breached then the consumer does not accumulate anymore while its objective is to buy at premium as much as he can (except in the very uncommon situation where the consumer does not want to buy at premium more than a certain quantity). Hence, it is not in his interest that the knock-out event happens.\n\n\n2) All parameters being equal, when the accumulation level gets closer to the barrier level then the price of the structure should decreases. Indeed, if the price at which the consumer is going to buy the underlying increases then the value of the accumulator must decrease.", "_____no_output_____" ] ], [ [ "%%run_pytest[clean]\n\n\ndef test_accumulator_BS_barrier():\n assert Accumulator(S0, kappa, theta, xi, Accumulationlevel, \n sigma, B, 'Discretely', 'BS', T=T,\n nb_path=nb_path, nb_steps=nb_steps, r=r) > Accumulator(S0, kappa, theta, xi, Accumulationlevel, \n sigma, B, 'Continuous', 'BS', T=T,\n nb_path=nb_path, nb_steps=nb_steps, r=r)\n\ndef test_accumulator_BS_moneyness():\n assert Accumulator(S0, kappa, theta, xi, 70, \n sigma, B, 'Discretely', 'BS', T=T,\n nb_path=nb_path, nb_steps=nb_steps, r=r) > Accumulator(S0, kappa, theta, xi, 80, \n sigma, B, 'Continuous', 'BS', T=T,\n nb_path=nb_path, nb_steps=nb_steps, r=r) \n", ".. [100%]\n2 passed in 13.90s\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb0c82f20f53e535cdb3ce83769f7f5b03659b5a
80,680
ipynb
Jupyter Notebook
Flow_based_models_MNIST.ipynb
NikhilAsogekar3/Deep-generative-models
55c92601041bfa85dbdbedc853e087ec8f4ee67e
[ "Apache-2.0" ]
null
null
null
Flow_based_models_MNIST.ipynb
NikhilAsogekar3/Deep-generative-models
55c92601041bfa85dbdbedc853e087ec8f4ee67e
[ "Apache-2.0" ]
null
null
null
Flow_based_models_MNIST.ipynb
NikhilAsogekar3/Deep-generative-models
55c92601041bfa85dbdbedc853e087ec8f4ee67e
[ "Apache-2.0" ]
1
2021-11-08T08:31:12.000Z
2021-11-08T08:31:12.000Z
211.75853
20,354
0.888808
[ [ [ "<a href=\"https://colab.research.google.com/github/NikhilAsogekar3/Deep-generative-models/blob/Nikhil-Asogekar/Flow_based_models_MNIST.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "pip install tensorboardX", "Collecting tensorboardX\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/07/84/46421bd3e0e89a92682b1a38b40efc22dafb6d8e3d947e4ceefd4a5fabc7/tensorboardX-2.2-py2.py3-none-any.whl (120kB)\n\r\u001b[K |██▊ | 10kB 23.5MB/s eta 0:00:01\r\u001b[K |█████▍ | 20kB 17.6MB/s eta 0:00:01\r\u001b[K |████████▏ | 30kB 15.1MB/s eta 0:00:01\r\u001b[K |██████████▉ | 40kB 14.0MB/s eta 0:00:01\r\u001b[K |█████████████▋ | 51kB 8.0MB/s eta 0:00:01\r\u001b[K |████████████████▎ | 61kB 9.3MB/s eta 0:00:01\r\u001b[K |███████████████████ | 71kB 8.9MB/s eta 0:00:01\r\u001b[K |█████████████████████▊ | 81kB 9.6MB/s eta 0:00:01\r\u001b[K |████████████████████████▌ | 92kB 9.1MB/s eta 0:00:01\r\u001b[K |███████████████████████████▏ | 102kB 7.7MB/s eta 0:00:01\r\u001b[K |██████████████████████████████ | 112kB 7.7MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 122kB 7.7MB/s \n\u001b[?25hRequirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.7/dist-packages (from tensorboardX) (3.12.4)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from tensorboardX) (1.19.5)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.8.0->tensorboardX) (57.0.0)\nRequirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.8.0->tensorboardX) (1.15.0)\nInstalling collected packages: tensorboardX\nSuccessfully installed tensorboardX-2.2\n" ], [ "!git clone https://github.com/ikostrikov/pytorch-flows.git", "Cloning into 'pytorch-flows'...\nremote: Enumerating objects: 159, done.\u001b[K\nremote: Counting objects: 100% (4/4), done.\u001b[K\nremote: Compressing objects: 100% (4/4), done.\u001b[K\nremote: Total 159 (delta 0), reused 1 (delta 0), pack-reused 155\u001b[K\nReceiving objects: 100% (159/159), 57.73 KiB | 5.25 MiB/s, done.\nResolving deltas: 100% (91/91), done.\n" ], [ "cd /content/pytorch-flows", "/content/pytorch-flows\n" ], [ "#!python3 main.py --dataset MNIST --epochs 39 --flow realnvp", "_____no_output_____" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "validation_loss_arr = [1412.0406375, 1370.5079875, 1348.550775, 1334.159575, 1325.254575, 1319.1790625, 1315.10325, 1312.5301, 1310.65305, 1310.687425, 1311.35375, 1311.877675, 1312.796075, 1314.81735, 1317.54745, 1319.8324375, 1321.603, 1324.7897, 1327.7507125, 1331.42705, 1334.2232, 1339.4804875, 1342.9756375, 1346.1300125, 1350.1139375, 1356.0851125, 1360.2053125, 1366.4998875, 1370.7212, 1374.3232875, 1379.8238, 1385.65835, 1389.1418375, 1394.9656875, 1403.6788125, 1401.44405, 1409.9638625, 1413.2237375]\nt = range(0, len(validation_loss_arr))", "_____no_output_____" ], [ "plt.plot(t, validation_loss_arr)", "_____no_output_____" ], [ "train_loss_arr = [1511.5976767578125, 1360.9772260742188, 1322.0785751953124, 1296.0211049804689, 1276.5144577636718, 1261.229338623047, 1248.6503671875, 1237.9503461914062, 1228.6204182128906, 1220.3964350585939, 1213.1653029785157, 1206.3630102539062, 1200.22780078125, 1194.51880859375, 1189.2079301757813, 1184.2624074707032, 1179.5217976074218, 1175.1067041015624, 1170.7996330566407, 1166.799998046875, 1162.8641767578124, 1159.2805954589844, 1155.6494814453124, 1152.1222729492188, 1148.6916076660157, 1145.3542294921874, 1142.176744140625, 1139.1558515625, 1136.1532312011718, 1133.1632014160157, 1130.3760786132812, 1127.6925244140625, 1124.7973051757813, 1122.0719990234375, 1119.3449682617188, 1117.0235095214844, 1114.2212861328126, 1111.9701120605469]\nt = range(0, len(train_loss_arr))\nplt.plot(t, train_loss_arr)", "_____no_output_____" ], [ "plt.plot(t, validation_loss_arr, t, train_loss_arr)\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.legend([\"Validation loss\", \"Train loss\"])", "_____no_output_____" ], [ "!python3 main.py --dataset MNIST --epochs 39 --flow glow", "Traceback (most recent call last):\n File \"main.py\", line 83, in <module>\n dataset = getattr(datasets, args.dataset)()\n File \"/content/pytorch-flows/datasets/mnist.py\", line 53, in __init__\n f = gzip.open(datasets.root + 'mnist/mnist.pkl.gz', 'rb')\n File \"/usr/lib/python3.7/gzip.py\", line 58, in open\n binary_file = GzipFile(filename, gz_mode, compresslevel)\n File \"/usr/lib/python3.7/gzip.py\", line 168, in __init__\n fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')\nFileNotFoundError: [Errno 2] No such file or directory: 'data/mnist/mnist.pkl.gz'\n" ], [ "validation_loss_arr = [1484.944525, 1448.5011, 1438.97775, 1435.0574875, 1430.6920875, 1427.9998875, 1425.3092375, 1421.1903375, 1417.8452125, 1415.0766, 1412.69425, 1410.895975, 1409.8048875, 1408.6240375, 1408.8573125, 1407.4946875, 1406.6598125, 1407.115675, 1407.099875, 1407.207725, 1408.56065, 1407.9039625, 1408.49985, 1409.919175, 1410.6583375, 1411.1293125, 1411.93785, 1413.17175, 1414.00035, 1414.5922, 1415.8910125, 1417.012075, 1417.9070625, 1419.245525, 1420.567775, 1421.0723, 1422.3375, 1423.8462625, 1425.2494375]\nt = range(0, len(validation_loss_arr))", "_____no_output_____" ], [ "train_loss_arr = [1592.3340473632813, 1432.2148771972657, 1411.8592380371094, 1404.2368190917969, 1399.0122912597656, 1393.9151166992187, 1388.4402751464843, 1382.2163818359375, 1375.8588979492188, 1369.3731450195312, 1363.0482341308593, 1356.9891979980468, 1351.5233972167969, 1346.2685063476563, 1341.3521879882812, 1336.5260437011718, 1332.3902065429688, 1328.0386740722656, 1324.2451677246095, 1320.651205078125, 1317.3042258300782, 1313.7869914550781, 1310.7244875488282, 1307.6534665527345, 1304.8240341796875, 1302.179833984375, 1299.3900551757813, 1296.8192004394532, 1294.365427734375, 1291.9521706542969, 1289.6495329589843, 1287.4671130371094, 1285.2979084472656, 1283.0090056152344, 1281.0169001464844, 1279.0981711425782, 1277.2146674804687, 1275.240196533203, 1273.138677734375]\nt = range(0, len(train_loss_arr))", "_____no_output_____" ], [ "plt.plot(t, validation_loss_arr, t, train_loss_arr)\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.legend([\"Validation loss\", \"Train loss\"])", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0c878d3dccc3e104b5cf28d6aab2b41c304f77
554,243
ipynb
Jupyter Notebook
Classification of Handwritten digits TensorFlow.ipynb
AzimbekKhudoyberdiev/HandwrittenDigitRecognitionwithTensorFlow
87eb4e2479583508a54fa4167f7307c8aabb11e9
[ "Unlicense" ]
null
null
null
Classification of Handwritten digits TensorFlow.ipynb
AzimbekKhudoyberdiev/HandwrittenDigitRecognitionwithTensorFlow
87eb4e2479583508a54fa4167f7307c8aabb11e9
[ "Unlicense" ]
null
null
null
Classification of Handwritten digits TensorFlow.ipynb
AzimbekKhudoyberdiev/HandwrittenDigitRecognitionwithTensorFlow
87eb4e2479583508a54fa4167f7307c8aabb11e9
[ "Unlicense" ]
null
null
null
310.674327
102,144
0.906837
[ [ [ "# 1. Libraries", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport keras.preprocessing.image\nimport sklearn.preprocessing\nimport sklearn.model_selection\nimport sklearn.metrics\nimport sklearn.linear_model\nimport sklearn.naive_bayes\nimport sklearn.tree\nimport sklearn.ensemble\nimport os;\nimport datetime \nimport cv2\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm \n%matplotlib inline\n\nimport warnings \nwarnings.filterwarnings('ignore')\n%pylab inline", "Populating the interactive namespace from numpy and matplotlib\n" ] ], [ [ "# 2. Analyzing data", "_____no_output_____" ] ], [ [ "train_df = pd.read_csv('train.csv')", "_____no_output_____" ], [ "print(\"Data Shape:\", train_df.shape)", "Data Shape: (42000, 785)\n" ], [ "print('')\nprint(train_df.isnull().any().describe())", "\ncount 785\nunique 1\ntop False\nfreq 785\ndtype: object\n" ], [ "print('distinct labels ', train_df['label'].unique())", "distinct labels [1 0 4 7 3 5 8 9 2 6]\n" ], [ "# data are approximately balanced (less often occurs 5, most often 1)\nprint(train_df['label'].value_counts())\n", "1 4684\n7 4401\n3 4351\n9 4188\n2 4177\n6 4137\n0 4132\n4 4072\n8 4063\n5 3795\nName: label, dtype: int64\n" ], [ "## normalize data and split into training and validation sets\n# function to normalize data\ndef normalize_data(data): \n data = data / data.max()\n return data\n# convert class labels from scalars to one-hot vectors e.g. 1 => [0 1 0 0 0 0 0 0 0 0]\n\ndef dense_to_one_hot(labels_dense, num_classes):\n num_labels = labels_dense.shape[0]\n index_offset = np.arange(num_labels) * num_classes\n labels_one_hot = np.zeros((num_labels, num_classes))\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n return labels_one_hot\n\n# convert one-hot encodings into labels\ndef one_hot_to_dense(labels_one_hot):\n return np.argmax(labels_one_hot,1)\n\n# computet the accuracy of label predictions\ndef accuracy_from_dense_labels(y_target, y_pred):\n y_target = y_target.reshape(-1,)\n y_pred = y_pred.reshape(-1,)\n return np.mean(y_target == y_pred)\n\n# computet the accuracy of one-hot encoded predictions\ndef accuracy_from_one_hot_labels(y_target, y_pred):\n y_target = one_hot_to_dense(y_target).reshape(-1,)\n y_pred = one_hot_to_dense(y_pred).reshape(-1,)\n return np.mean(y_target == y_pred)\n\n# extract and normalize images\nx_train_valid = train_df.iloc[:,1:].values.reshape(-1,28,28,1) # (42000,28,28,1) array\nx_train_valid = x_train_valid.astype(np.float) # convert from int64 to float32\nx_train_valid = normalize_data(x_train_valid)\nimage_width = image_height = 28\nimage_size = 784\n\n# extract image labels\ny_train_valid_labels = train_df.iloc[:,0].values # (42000,1) array\nlabels_count = np.unique(y_train_valid_labels).shape[0]; # number of different labels = 10\n\n#plot some images and labels\nplt.figure(figsize=(15,9))\nfor i in range(50):\n plt.subplot(5,10,1+i)\n plt.title(y_train_valid_labels[i])\n plt.imshow(x_train_valid[i].reshape(28,28), cmap=cm.binary)\n\n# labels in one hot representation\ny_train_valid = dense_to_one_hot(y_train_valid_labels, labels_count).astype(np.uint8)\n\n# dictionaries for saving results\ny_valid_pred = {}\ny_train_pred = {}\ny_test_pred = {}\ntrain_loss, valid_loss = {}, {}\ntrain_acc, valid_acc = {}, {}\n\nprint('x_train_valid.shape = ', x_train_valid.shape)\nprint('y_train_valid_labels.shape = ', y_train_valid_labels.shape)\nprint('image_size = ', image_size )\nprint('image_width = ', image_width)\nprint('image_height = ', image_height)\nprint('labels_count = ', labels_count)", "x_train_valid.shape = (42000, 28, 28, 1)\ny_train_valid_labels.shape = (42000,)\nimage_size = 784\nimage_width = 28\nimage_height = 28\nlabels_count = 10\n" ] ], [ [ "# Data Manipulation", "_____no_output_____" ] ], [ [ "#generate new images via rotations, translations and zooming", "_____no_output_____" ], [ "# generate new images via rotations, translations, zoom using keras\ndef generate_images(imgs):\n \n # rotations, translations, zoom\n image_generator = keras.preprocessing.image.ImageDataGenerator(\n rotation_range = 10, width_shift_range = 0.1 , height_shift_range = 0.1,\n zoom_range = 0.1)\n\n # get transformed images\n imgs = image_generator.flow(imgs.copy(), np.zeros(len(imgs)),\n batch_size=len(imgs), shuffle = False).next() \n \n return imgs[0]\n# check image generation\nfig,axs = plt.subplots(5,10, figsize=(15,9))\nfor i in range(5):\n n = np.random.randint(0,x_train_valid.shape[0]-2)\n axs[i,0].imshow(x_train_valid[n:n+1].reshape(28,28),cmap=cm.binary)\n axs[i,1].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,2].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,3].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,4].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,5].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,6].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,7].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,8].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)\n axs[i,9].imshow(generate_images(x_train_valid[n:n+1]).reshape(28,28), cmap=cm.binary)", "_____no_output_____" ] ], [ [ "# 4. Basic Model Generation using Sklearn", "_____no_output_____" ] ], [ [ "## First try out some basic sklearn models\n\nlogreg = sklearn.linear_model.LogisticRegression(verbose=0, solver='lbfgs',\n multi_class='multinomial')\ndecision_tree = sklearn.tree.DecisionTreeClassifier()\nextra_trees = sklearn.ensemble.ExtraTreesClassifier(verbose=0)\ngradient_boost = sklearn.ensemble.GradientBoostingClassifier(verbose=0)\nrandom_forest = sklearn.ensemble.RandomForestClassifier(verbose=0)\ngaussianNB = sklearn.naive_bayes.GaussianNB()\n\n# store models in dictionary\nbase_models = {'logreg': logreg, 'extra_trees': extra_trees,\n 'gradient_boost': gradient_boost, 'random_forest': random_forest, \n 'decision_tree': decision_tree, 'gaussianNB': gaussianNB}\n\n# choose models for out-of-folds predictions\ntake_models = ['logreg','random_forest','extra_trees']\n\nfor mn in take_models:\n train_acc[mn] = []\n valid_acc[mn] = []\n# cross validations\ncv_num = 10 # cross validations default = 20 => 5% validation set\nkfold = sklearn.model_selection.KFold(cv_num, shuffle=True, random_state=123)\n\nfor i,(train_index, valid_index) in enumerate(kfold.split(x_train_valid)):\n\n # start timer\n start = datetime.datetime.now();\n\n # train and validation data of original images\n x_train = x_train_valid[train_index].reshape(-1,784)\n y_train = y_train_valid[train_index]\n x_valid = x_train_valid[valid_index].reshape(-1,784)\n y_valid = y_train_valid[valid_index]\n \n for mn in take_models:\n\n # create cloned model from base models\n model = sklearn.base.clone(base_models[mn])\n model.fit(x_train, one_hot_to_dense(y_train))\n\n # predictions\n y_train_pred[mn] = model.predict_proba(x_train)\n y_valid_pred[mn] = model.predict_proba(x_valid)\n train_acc[mn].append(accuracy_from_one_hot_labels(y_train_pred[mn], y_train))\n valid_acc[mn].append(accuracy_from_one_hot_labels(y_valid_pred[mn], y_valid))\n print(i,': '+mn+' train/valid accuracy = %.3f/%.3f'%(train_acc[mn][-1], \n valid_acc[mn][-1]))\n # only one iteration\n if False:\n break;\n\nprint(mn+': averaged train/valid accuracy = %.3f/%.3f'%(np.mean(train_acc[mn]),\n np.mean(valid_acc[mn])))", "0 : logreg train/valid accuracy = 0.940/0.920\n0 : random_forest train/valid accuracy = 0.999/0.942\n0 : extra_trees train/valid accuracy = 1.000/0.944\n1 : logreg train/valid accuracy = 0.940/0.921\n1 : random_forest train/valid accuracy = 0.999/0.943\n1 : extra_trees train/valid accuracy = 1.000/0.947\n2 : logreg train/valid accuracy = 0.939/0.929\n2 : random_forest train/valid accuracy = 0.999/0.943\n2 : extra_trees train/valid accuracy = 1.000/0.949\n3 : logreg train/valid accuracy = 0.939/0.925\n3 : random_forest train/valid accuracy = 0.999/0.939\n3 : extra_trees train/valid accuracy = 1.000/0.941\n4 : logreg train/valid accuracy = 0.940/0.921\n4 : random_forest train/valid accuracy = 0.999/0.945\n4 : extra_trees train/valid accuracy = 1.000/0.947\n5 : logreg train/valid accuracy = 0.939/0.918\n5 : random_forest train/valid accuracy = 0.999/0.942\n5 : extra_trees train/valid accuracy = 1.000/0.946\n6 : logreg train/valid accuracy = 0.941/0.915\n6 : random_forest train/valid accuracy = 0.999/0.944\n6 : extra_trees train/valid accuracy = 1.000/0.944\n7 : logreg train/valid accuracy = 0.941/0.912\n7 : random_forest train/valid accuracy = 0.999/0.932\n7 : extra_trees train/valid accuracy = 1.000/0.940\n8 : logreg train/valid accuracy = 0.940/0.925\n8 : random_forest train/valid accuracy = 0.999/0.945\n8 : extra_trees train/valid accuracy = 1.000/0.951\n9 : logreg train/valid accuracy = 0.940/0.918\n9 : random_forest train/valid accuracy = 0.999/0.935\n9 : extra_trees train/valid accuracy = 1.000/0.943\nextra_trees: averaged train/valid accuracy = 1.000/0.945\n" ], [ "#Comparisons of Accuracies of base models\n\n# boxplot algorithm comparison\nfig = plt.figure(figsize=(20,8))\nax = fig.add_subplot(1,2,1)\nplt.title('Train accuracy')\nplt.boxplot([train_acc[mn] for mn in train_acc.keys()])\nax.set_xticklabels([mn for mn in train_acc.keys()])\nax.set_ylabel('Accuracy');\nax.set_ylim([0.90,1.0])\n\nax = fig.add_subplot(1,2,2)\nplt.title('Valid accuracy')\nplt.boxplot([valid_acc[mn] for mn in train_acc.keys()])\nax.set_xticklabels([mn for mn in train_acc.keys()])\nax.set_ylabel('Accuracy');\nax.set_ylim([0.90,1.0])\n\nfor mn in train_acc.keys():\n print(mn + ' averaged train/valid accuracy = %.3f/%.3f'%(np.mean(train_acc[mn]),\n np.mean(valid_acc[mn])))", "logreg averaged train/valid accuracy = 0.940/0.920\nrandom_forest averaged train/valid accuracy = 0.999/0.941\nextra_trees averaged train/valid accuracy = 1.000/0.945\n" ] ], [ [ "# 5. Neural Network with TensorFlow", "_____no_output_____" ] ], [ [ "## build the neural network class\n\nclass nn_class:\n# class that implements the neural network\n\n # constructor\n def __init__(self, nn_name = 'nn_1'):\n\n # tunable hyperparameters for nn architecture\n self.s_f_conv1 = 3; # filter size of first convolution layer (default = 3)\n self.n_f_conv1 = 36; # number of features of first convolution layer (default = 36)\n self.s_f_conv2 = 3; # filter size of second convolution layer (default = 3)\n self.n_f_conv2 = 36; # number of features of second convolution layer (default = 36)\n self.s_f_conv3 = 3; # filter size of third convolution layer (default = 3)\n self.n_f_conv3 = 36; # number of features of third convolution layer (default = 36)\n self.n_n_fc1 = 576; # number of neurons of first fully connected layer (default = 576)\n\n # tunable hyperparameters for training\n self.mb_size = 50 # mini batch size\n self.keep_prob = 0.33 # keeping probability with dropout regularization \n self.learn_rate_array = [10*1e-4, 7.5*1e-4, 5*1e-4, 2.5*1e-4, 1*1e-4, 1*1e-4,\n 1*1e-4,0.75*1e-4, 0.5*1e-4, 0.25*1e-4, 0.1*1e-4, \n 0.1*1e-4, 0.075*1e-4,0.050*1e-4, 0.025*1e-4, 0.01*1e-4, \n 0.0075*1e-4, 0.0050*1e-4,0.0025*1e-4,0.001*1e-4]\n self.learn_rate_step_size = 3 # in terms of epochs\n \n # parameters\n self.learn_rate = self.learn_rate_array[0]\n self.learn_rate_pos = 0 # current position pointing to current learning rate\n self.index_in_epoch = 0 \n self.current_epoch = 0\n self.log_step = 0.2 # log results in terms of epochs\n self.n_log_step = 0 # counting current number of mini batches trained on\n self.use_tb_summary = False # True = use tensorboard visualization\n self.use_tf_saver = False # True = use saver to save the model\n self.nn_name = nn_name # name of the neural network\n \n # permutation array\n self.perm_array = np.array([])\n \n # function to get the next mini batch\n def next_mini_batch(self):\n\n start = self.index_in_epoch\n self.index_in_epoch += self.mb_size\n self.current_epoch += self.mb_size/len(self.x_train) \n \n # adapt length of permutation array\n if not len(self.perm_array) == len(self.x_train):\n self.perm_array = np.arange(len(self.x_train))\n \n # shuffle once at the start of epoch\n if start == 0:\n np.random.shuffle(self.perm_array)\n \n # at the end of the epoch\n if self.index_in_epoch > self.x_train.shape[0]:\n np.random.shuffle(self.perm_array) # shuffle data\n start = 0 # start next epoch\n self.index_in_epoch = self.mb_size # set index to mini batch size\n \n if self.train_on_augmented_data:\n # use augmented data for the next epoch\n self.x_train_aug = normalize_data(self.generate_images(self.x_train))\n self.y_train_aug = self.y_train\n \n end = self.index_in_epoch\n if self.train_on_augmented_data:\n # use augmented data\n x_tr = self.x_train_aug[self.perm_array[start:end]]\n y_tr = self.y_train_aug[self.perm_array[start:end]]\n else:\n # use original data\n x_tr = self.x_train[self.perm_array[start:end]]\n y_tr = self.y_train[self.perm_array[start:end]]\n \n return x_tr, y_tr\n \n # generate new images via rotations, translations, zoom using keras\n def generate_images(self, imgs):\n \n print('generate new set of images')\n # rotations, translations, zoom\n image_generator = keras.preprocessing.image.ImageDataGenerator(\n rotation_range = 10, width_shift_range = 0.1 , height_shift_range = 0.1,\n zoom_range = 0.1)\n\n # get transformed images\n imgs = image_generator.flow(imgs.copy(), np.zeros(len(imgs)),\n batch_size=len(imgs), shuffle = False).next() \n\n return imgs[0]\n\n # weight initialization\n def weight_variable(self, shape, name = None):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial, name = name)\n # bias initialization\n def bias_variable(self, shape, name = None):\n initial = tf.constant(0.1, shape=shape) # positive bias\n return tf.Variable(initial, name = name)\n\n # 2D convolution\n def conv2d(self, x, W, name = None):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME', name = name)\n\n # max pooling\n def max_pool_2x2(self, x, name = None):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],\n padding='SAME', name = name)\n # attach summaries to a tensor for TensorBoard visualization\n def summary_variable(self, var, var_name):\n with tf.name_scope(var_name):\n mean = tf.reduce_mean(var)\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('mean', mean)\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n \n # function to create the graph\n def create_graph(self):\n\n # reset default graph\n tf.reset_default_graph() \n \n # variables for input and output \n self.x_data_tf = tf.placeholder(dtype=tf.float32, shape=[None,28,28,1], \n name='x_data_tf')\n self.y_data_tf = tf.placeholder(dtype=tf.float32, shape=[None,10], name='y_data_tf')\n\n # 1.layer: convolution + max pooling\n self.W_conv1_tf = self.weight_variable([self.s_f_conv1, self.s_f_conv1, 1,\n self.n_f_conv1], \n name = 'W_conv1_tf') # (5,5,1,32)\n self.b_conv1_tf = self.bias_variable([self.n_f_conv1], name = 'b_conv1_tf') # (32)\n self.h_conv1_tf = tf.nn.relu(self.conv2d(self.x_data_tf, \n self.W_conv1_tf) + self.b_conv1_tf, \n name = 'h_conv1_tf') # (.,28,28,32)\n self.h_pool1_tf = self.max_pool_2x2(self.h_conv1_tf, \n name = 'h_pool1_tf') # (.,14,14,32)\n \n # 2.layer: convolution + max pooling\n self.W_conv2_tf = self.weight_variable([self.s_f_conv2, self.s_f_conv2, \n self.n_f_conv1, self.n_f_conv2], \n name = 'W_conv2_tf')\n self.b_conv2_tf = self.bias_variable([self.n_f_conv2], name = 'b_conv2_tf')\n self.h_conv2_tf = tf.nn.relu(self.conv2d(self.h_pool1_tf, \n self.W_conv2_tf) + self.b_conv2_tf, \n name ='h_conv2_tf') #(.,14,14,32)\n self.h_pool2_tf = self.max_pool_2x2(self.h_conv2_tf, name = 'h_pool2_tf') #(.,7,7,32)\n \n # 3.layer: convolution + max pooling\n self.W_conv3_tf = self.weight_variable([self.s_f_conv3, self.s_f_conv3, \n self.n_f_conv2, self.n_f_conv3], \n name = 'W_conv3_tf')\n self.b_conv3_tf = self.bias_variable([self.n_f_conv3], name = 'b_conv3_tf')\n self.h_conv3_tf = tf.nn.relu(self.conv2d(self.h_pool2_tf, \n self.W_conv3_tf) + self.b_conv3_tf, \n name = 'h_conv3_tf') #(.,7,7,32)\n self.h_pool3_tf = self.max_pool_2x2(self.h_conv3_tf, \n name = 'h_pool3_tf') # (.,4,4,32)\n\n # 4.layer: fully connected\n self.W_fc1_tf = self.weight_variable([4*4*self.n_f_conv3,self.n_n_fc1], \n name = 'W_fc1_tf') # (4*4*32, 1024)\n self.b_fc1_tf = self.bias_variable([self.n_n_fc1], name = 'b_fc1_tf') # (1024)\n self.h_pool3_flat_tf = tf.reshape(self.h_pool3_tf, [-1,4*4*self.n_f_conv3], \n name = 'h_pool3_flat_tf') # (.,1024)\n self.h_fc1_tf = tf.nn.relu(tf.matmul(self.h_pool3_flat_tf, \n self.W_fc1_tf) + self.b_fc1_tf, \n name = 'h_fc1_tf') # (.,1024)\n \n # add dropout\n self.keep_prob_tf = tf.placeholder(dtype=tf.float32, name = 'keep_prob_tf')\n self.h_fc1_drop_tf = tf.nn.dropout(self.h_fc1_tf, self.keep_prob_tf, \n name = 'h_fc1_drop_tf')\n\n # 5.layer: fully connected\n self.W_fc2_tf = self.weight_variable([self.n_n_fc1, 10], name = 'W_fc2_tf')\n self.b_fc2_tf = self.bias_variable([10], name = 'b_fc2_tf')\n self.z_pred_tf = tf.add(tf.matmul(self.h_fc1_drop_tf, self.W_fc2_tf), \n self.b_fc2_tf, name = 'z_pred_tf')# => (.,10)\n\n # cost function\n self.cross_entropy_tf = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels=self.y_data_tf, logits=self.z_pred_tf), name = 'cross_entropy_tf')\n \n # optimisation function\n self.learn_rate_tf = tf.placeholder(dtype=tf.float32, name=\"learn_rate_tf\")\n self.train_step_tf = tf.train.AdamOptimizer(self.learn_rate_tf).minimize(\n self.cross_entropy_tf, name = 'train_step_tf')\n\n # predicted probabilities in one-hot encoding\n self.y_pred_proba_tf = tf.nn.softmax(self.z_pred_tf, name='y_pred_proba_tf')\n \n # tensor of correct predictions\n self.y_pred_correct_tf = tf.equal(tf.argmax(self.y_pred_proba_tf, 1),\n tf.argmax(self.y_data_tf, 1),\n name = 'y_pred_correct_tf') \n \n # accuracy \n self.accuracy_tf = tf.reduce_mean(tf.cast(self.y_pred_correct_tf, dtype=tf.float32),\n name = 'accuracy_tf')\n\n # tensors to save intermediate accuracies and losses during training\n self.train_loss_tf = tf.Variable(np.array([]), dtype=tf.float32, \n name='train_loss_tf', validate_shape = False)\n self.valid_loss_tf = tf.Variable(np.array([]), dtype=tf.float32, \n name='valid_loss_tf', validate_shape = False)\n self.train_acc_tf = tf.Variable(np.array([]), dtype=tf.float32, \n name='train_acc_tf', validate_shape = False)\n self.valid_acc_tf = tf.Variable(np.array([]), dtype=tf.float32, \n name='valid_acc_tf', validate_shape = False)\n \n # number of weights and biases\n num_weights = (self.s_f_conv1**2*self.n_f_conv1 \n + self.s_f_conv2**2*self.n_f_conv1*self.n_f_conv2 \n + self.s_f_conv3**2*self.n_f_conv2*self.n_f_conv3 \n + 4*4*self.n_f_conv3*self.n_n_fc1 + self.n_n_fc1*10)\n num_biases = self.n_f_conv1 + self.n_f_conv2 + self.n_f_conv3 + self.n_n_fc1\n print('num_weights =', num_weights)\n print('num_biases =', num_biases)\n \n return None \n \n def attach_summary(self, sess):\n \n # create summary tensors for tensorboard\n self.use_tb_summary = True\n self.summary_variable(self.W_conv1_tf, 'W_conv1_tf')\n self.summary_variable(self.b_conv1_tf, 'b_conv1_tf')\n self.summary_variable(self.W_conv2_tf, 'W_conv2_tf')\n self.summary_variable(self.b_conv2_tf, 'b_conv2_tf')\n self.summary_variable(self.W_conv3_tf, 'W_conv3_tf')\n self.summary_variable(self.b_conv3_tf, 'b_conv3_tf')\n self.summary_variable(self.W_fc1_tf, 'W_fc1_tf')\n self.summary_variable(self.b_fc1_tf, 'b_fc1_tf')\n self.summary_variable(self.W_fc2_tf, 'W_fc2_tf')\n self.summary_variable(self.b_fc2_tf, 'b_fc2_tf')\n tf.summary.scalar('cross_entropy_tf', self.cross_entropy_tf)\n tf.summary.scalar('accuracy_tf', self.accuracy_tf)\n # merge all summaries for tensorboard\n self.merged = tf.summary.merge_all()\n\n # initialize summary writer \n timestamp = datetime.datetime.now().strftime('%d-%m-%Y_%H-%M-%S')\n filepath = os.path.join(os.getcwd(), 'logs', (self.nn_name+'_'+timestamp))\n self.train_writer = tf.summary.FileWriter(os.path.join(filepath,'train'), sess.graph)\n self.valid_writer = tf.summary.FileWriter(os.path.join(filepath,'valid'), sess.graph)\n\n def attach_saver(self):\n # initialize tensorflow saver\n self.use_tf_saver = True\n self.saver_tf = tf.train.Saver()\n\n # function to train the graph\n def train_graph(self, sess, x_train, y_train, x_valid, y_valid, n_epoch = 1, \n train_on_augmented_data = False):\n \n # train on original or augmented data\n self.train_on_augmented_data = train_on_augmented_data\n \n # training and validation data\n self.x_train = x_train\n self.y_train = y_train\n self.x_valid = x_valid\n self.y_valid = y_valid\n \n # use augmented data\n if self.train_on_augmented_data:\n print('generate new set of images')\n self.x_train_aug = normalize_data(self.generate_images(self.x_train))\n self.y_train_aug = self.y_train\n \n # parameters\n mb_per_epoch = self.x_train.shape[0]/self.mb_size\n train_loss, train_acc, valid_loss, valid_acc = [],[],[],[]\n \n # start timer\n start = datetime.datetime.now();\n print(datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S'),': start training')\n print('learnrate = ',self.learn_rate,', n_epoch = ', n_epoch,\n ', mb_size = ', self.mb_size)\n # looping over mini batches\n for i in range(int(n_epoch*mb_per_epoch)+1):\n\n # adapt learn_rate\n self.learn_rate_pos = int(self.current_epoch // self.learn_rate_step_size)\n if not self.learn_rate == self.learn_rate_array[self.learn_rate_pos]:\n self.learn_rate = self.learn_rate_array[self.learn_rate_pos]\n print(datetime.datetime.now()-start,': set learn rate to %.6f'%self.learn_rate)\n \n # get new batch\n x_batch, y_batch = self.next_mini_batch() \n # run the graph\n sess.run(self.train_step_tf, feed_dict={self.x_data_tf: x_batch, \n self.y_data_tf: y_batch, \n self.keep_prob_tf: self.keep_prob, \n self.learn_rate_tf: self.learn_rate})\n \n \n # store losses and accuracies\n if i%int(self.log_step*mb_per_epoch) == 0 or i == int(n_epoch*mb_per_epoch):\n \n self.n_log_step += 1 # for logging the results\n feed_dict_train = {\n self.x_data_tf: self.x_train[self.perm_array[:len(self.x_valid)]], \n self.y_data_tf: self.y_train[self.perm_array[:len(self.y_valid)]], \n self.keep_prob_tf: 1.0}\n \n feed_dict_valid = {self.x_data_tf: self.x_valid, \n self.y_data_tf: self.y_valid, \n self.keep_prob_tf: 1.0}\n \n # summary for tensorboard\n if self.use_tb_summary:\n train_summary = sess.run(self.merged, feed_dict = feed_dict_train)\n valid_summary = sess.run(self.merged, feed_dict = feed_dict_valid)\n self.train_writer.add_summary(train_summary, self.n_log_step)\n self.valid_writer.add_summary(valid_summary, self.n_log_step)\n \n train_loss.append(sess.run(self.cross_entropy_tf,\n feed_dict = feed_dict_train))\n train_acc.append(self.accuracy_tf.eval(session = sess, \n feed_dict = feed_dict_train))\n \n valid_loss.append(sess.run(self.cross_entropy_tf,\n feed_dict = feed_dict_valid))\n\n valid_acc.append(self.accuracy_tf.eval(session = sess, \n feed_dict = feed_dict_valid))\n\n print('%.2f epoch: train/val loss = %.4f/%.4f, train/val acc = %.4f/%.4f'%(\n self.current_epoch, train_loss[-1], valid_loss[-1],\n train_acc[-1], valid_acc[-1]))\n \n # concatenate losses and accuracies and assign to tensor variables\n tl_c = np.concatenate([self.train_loss_tf.eval(session=sess), train_loss], axis = 0)\n vl_c = np.concatenate([self.valid_loss_tf.eval(session=sess), valid_loss], axis = 0)\n ta_c = np.concatenate([self.train_acc_tf.eval(session=sess), train_acc], axis = 0)\n va_c = np.concatenate([self.valid_acc_tf.eval(session=sess), valid_acc], axis = 0)\n \n sess.run(tf.assign(self.train_loss_tf, tl_c, validate_shape = False))\n sess.run(tf.assign(self.valid_loss_tf, vl_c , validate_shape = False))\n sess.run(tf.assign(self.train_acc_tf, ta_c , validate_shape = False))\n sess.run(tf.assign(self.valid_acc_tf, va_c , validate_shape = False))\n \n print('running time for training: ', datetime.datetime.now() - start)\n return None\n \n # save tensors/summaries\n def save_model(self, sess):\n \n # tf saver\n if self.use_tf_saver:\n #filepath = os.path.join(os.getcwd(), 'logs' , self.nn_name)\n filepath = os.path.join(os.getcwd(), self.nn_name)\n self.saver_tf.save(sess, filepath)\n \n # tb summary\n if self.use_tb_summary:\n self.train_writer.close()\n self.valid_writer.close()\n \n return None\n \n # forward prediction of current graph\n def forward(self, sess, x_data):\n y_pred_proba = self.y_pred_proba_tf.eval(session = sess, \n feed_dict = {self.x_data_tf: x_data,\n self.keep_prob_tf: 1.0})\n return y_pred_proba\n \n # function to load tensors from a saved graph\n def load_tensors(self, graph):\n \n # input tensors\n self.x_data_tf = graph.get_tensor_by_name(\"x_data_tf:0\")\n self.y_data_tf = graph.get_tensor_by_name(\"y_data_tf:0\")\n \n # weights and bias tensors\n self.W_conv1_tf = graph.get_tensor_by_name(\"W_conv1_tf:0\")\n self.W_conv2_tf = graph.get_tensor_by_name(\"W_conv2_tf:0\")\n self.W_conv3_tf = graph.get_tensor_by_name(\"W_conv3_tf:0\")\n self.W_fc1_tf = graph.get_tensor_by_name(\"W_fc1_tf:0\")\n self.W_fc2_tf = graph.get_tensor_by_name(\"W_fc2_tf:0\")\n self.b_conv1_tf = graph.get_tensor_by_name(\"b_conv1_tf:0\")\n self.b_conv2_tf = graph.get_tensor_by_name(\"b_conv2_tf:0\")\n self.b_conv3_tf = graph.get_tensor_by_name(\"b_conv3_tf:0\")\n self.b_fc1_tf = graph.get_tensor_by_name(\"b_fc1_tf:0\")\n self.b_fc2_tf = graph.get_tensor_by_name(\"b_fc2_tf:0\")\n \n # activation tensors\n self.h_conv1_tf = graph.get_tensor_by_name('h_conv1_tf:0') \n self.h_pool1_tf = graph.get_tensor_by_name('h_pool1_tf:0')\n self.h_conv2_tf = graph.get_tensor_by_name('h_conv2_tf:0')\n self.h_pool2_tf = graph.get_tensor_by_name('h_pool2_tf:0')\n self.h_conv3_tf = graph.get_tensor_by_name('h_conv3_tf:0')\n self.h_pool3_tf = graph.get_tensor_by_name('h_pool3_tf:0')\n self.h_fc1_tf = graph.get_tensor_by_name('h_fc1_tf:0')\n self.z_pred_tf = graph.get_tensor_by_name('z_pred_tf:0')\n \n # training and prediction tensors\n self.learn_rate_tf = graph.get_tensor_by_name(\"learn_rate_tf:0\")\n self.keep_prob_tf = graph.get_tensor_by_name(\"keep_prob_tf:0\")\n self.cross_entropy_tf = graph.get_tensor_by_name('cross_entropy_tf:0')\n self.train_step_tf = graph.get_operation_by_name('train_step_tf')\n self.z_pred_tf = graph.get_tensor_by_name('z_pred_tf:0')\n self.y_pred_proba_tf = graph.get_tensor_by_name(\"y_pred_proba_tf:0\")\n self.y_pred_correct_tf = graph.get_tensor_by_name('y_pred_correct_tf:0')\n self.accuracy_tf = graph.get_tensor_by_name('accuracy_tf:0')\n \n # tensor of stored losses and accuricies during training\n self.train_loss_tf = graph.get_tensor_by_name(\"train_loss_tf:0\")\n self.train_acc_tf = graph.get_tensor_by_name(\"train_acc_tf:0\")\n self.valid_loss_tf = graph.get_tensor_by_name(\"valid_loss_tf:0\")\n self.valid_acc_tf = graph.get_tensor_by_name(\"valid_acc_tf:0\")\n \n return None\n \n # get losses of training and validation sets\n def get_loss(self, sess):\n train_loss = self.train_loss_tf.eval(session = sess)\n valid_loss = self.valid_loss_tf.eval(session = sess)\n return train_loss, valid_loss \n \n # get accuracies of training and validation sets\n def get_accuracy(self, sess):\n train_acc = self.train_acc_tf.eval(session = sess)\n valid_acc = self.valid_acc_tf.eval(session = sess)\n return train_acc, valid_acc \n \n # get weights\n def get_weights(self, sess):\n W_conv1 = self.W_conv1_tf.eval(session = sess)\n W_conv2 = self.W_conv2_tf.eval(session = sess)\n W_conv3 = self.W_conv3_tf.eval(session = sess)\n W_fc1_tf = self.W_fc1_tf.eval(session = sess)\n W_fc2_tf = self.W_fc2_tf.eval(session = sess)\n return W_conv1, W_conv2, W_conv3, W_fc1_tf, W_fc2_tf\n \n # get biases\n def get_biases(self, sess):\n b_conv1 = self.b_conv1_tf.eval(session = sess)\n b_conv2 = self.b_conv2_tf.eval(session = sess)\n b_conv3 = self.b_conv3_tf.eval(session = sess)\n b_fc1_tf = self.b_fc1_tf.eval(session = sess)\n b_fc2_tf = self.b_fc2_tf.eval(session = sess)\n return b_conv1, b_conv2, b_conv3, b_fc1_tf, b_fc2_tf\n \n # load session from file, restore graph, and load tensors\n def load_session_from_file(self, filename):\n tf.reset_default_graph()\n filepath = os.path.join(os.getcwd(), filename + '.meta')\n #filepath = os.path.join(os.getcwd(),'logs', filename + '.meta')\n saver = tf.train.import_meta_graph(filepath)\n print(filepath)\n sess = tf.Session()\n saver.restore(sess, mn)\n \n graph = tf.get_default_graph()\n self.load_tensors(graph)\n return sess\n \n # receive activations given the input\n def get_activations(self, sess, x_data):\n feed_dict = {self.x_data_tf: x_data, self.keep_prob_tf: 1.0}\n h_conv1 = self.h_conv1_tf.eval(session = sess, feed_dict = feed_dict)\n h_pool1 = self.h_pool1_tf.eval(session = sess, feed_dict = feed_dict)\n h_conv2 = self.h_conv2_tf.eval(session = sess, feed_dict = feed_dict)\n h_pool2 = self.h_pool2_tf.eval(session = sess, feed_dict = feed_dict)\n h_conv3 = self.h_conv3_tf.eval(session = sess, feed_dict = feed_dict)\n h_pool3 = self.h_pool3_tf.eval(session = sess, feed_dict = feed_dict)\n h_fc1 = self.h_fc1_tf.eval(session = sess, feed_dict = feed_dict)\n h_fc2 = self.z_pred_tf.eval(session = sess, feed_dict = feed_dict)\n return h_conv1,h_pool1,h_conv2,h_pool2,h_conv3,h_pool3,h_fc1,h_fc2", "_____no_output_____" ] ], [ [ "# 6. Train and Validate the Neural Network", "_____no_output_____" ] ], [ [ "#first try out some sklearn models\n#train the neural network\n#visualize the losses, accuracies, the weights and the activations\n#tune the hyperparameters", "_____no_output_____" ], [ "## train the neural network graph\n\n#nn_name = ['nn0','nn1','nn2','nn3','nn4','nn5','nn6','nn7','nn8','nn9']\n\nnn_name = ['tmp']\n\n# cross validations\ncv_num = 10 # cross validations default = 20 => 5% validation set\nkfold = sklearn.model_selection.KFold(cv_num, shuffle=True, random_state=123)\n\nfor i,(train_index, valid_index) in enumerate(kfold.split(x_train_valid)):\n \n # start timer\n start = datetime.datetime.now();\n \n # train and validation data of original images\n x_train = x_train_valid[train_index]\n y_train = y_train_valid[train_index]\n x_valid = x_train_valid[valid_index]\n y_valid = y_train_valid[valid_index]\n # create neural network graph\n nn_graph = nn_class(nn_name = nn_name[i]) # instance of nn_class\n nn_graph.create_graph() # create graph\n nn_graph.attach_saver() # attach saver tensors\n \n # start tensorflow session\n with tf.Session() as sess:\n \n # attach summaries\n nn_graph.attach_summary(sess) \n \n # variable initialization of the default graph\n sess.run(tf.global_variables_initializer()) \n \n # training on original data\n nn_graph.train_graph(sess, x_train, y_train, x_valid, y_valid, n_epoch = 1.0)\n # training on augmented data\n nn_graph.train_graph(sess, x_train, y_train, x_valid, y_valid, n_epoch = 14.0,\n train_on_augmented_data = True)\n\n # save tensors and summaries of model\n nn_graph.save_model(sess)\n \n # only one iteration\n if True:\n break;\n \n \nprint('total running time for training: ', datetime.datetime.now() - start)", "WARNING:tensorflow:From <ipython-input-25-a8f6665e6da7>:188: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\n\nFuture major versions of TensorFlow will allow gradients to flow\ninto the labels input on backprop by default.\n\nSee `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\nnum_weights = 361188\nnum_biases = 684\n16-12-2019 19:28:20 : start training\nlearnrate = 0.001 , n_epoch = 1.0 , mb_size = 50\n0.00 epoch: train/val loss = 2.6452/2.6543, train/val acc = 0.1371/0.1188\n0.20 epoch: train/val loss = 0.2143/0.2405, train/val acc = 0.9376/0.9293\n0.40 epoch: train/val loss = 0.1356/0.1601, train/val acc = 0.9579/0.9479\n0.60 epoch: train/val loss = 0.0875/0.1032, train/val acc = 0.9702/0.9669\n0.80 epoch: train/val loss = 0.0717/0.0897, train/val acc = 0.9760/0.9743\n1.00 epoch: train/val loss = 0.0640/0.0844, train/val acc = 0.9810/0.9736\n1.00 epoch: train/val loss = 0.0722/0.0854, train/val acc = 0.9793/0.9726\nrunning time for training: 0:01:53.684634\ngenerate new set of images\ngenerate new set of images\n16-12-2019 19:30:21 : start training\nlearnrate = 0.001 , n_epoch = 14.0 , mb_size = 50\n1.00 epoch: train/val loss = 0.0715/0.0853, train/val acc = 0.9800/0.9745\n1.20 epoch: train/val loss = 0.0692/0.0823, train/val acc = 0.9776/0.9733\n1.40 epoch: train/val loss = 0.0617/0.0669, train/val acc = 0.9790/0.9779\n1.60 epoch: train/val loss = 0.0583/0.0622, train/val acc = 0.9793/0.9790\n1.80 epoch: train/val loss = 0.0477/0.0538, train/val acc = 0.9829/0.9833\ngenerate new set of images\n2.00 epoch: train/val loss = 0.0634/0.0658, train/val acc = 0.9795/0.9793\n2.20 epoch: train/val loss = 0.0446/0.0518, train/val acc = 0.9860/0.9836\n2.40 epoch: train/val loss = 0.0411/0.0466, train/val acc = 0.9879/0.9857\n2.60 epoch: train/val loss = 0.0420/0.0475, train/val acc = 0.9881/0.9850\n2.80 epoch: train/val loss = 0.0392/0.0439, train/val acc = 0.9871/0.9845\n3.00 epoch: train/val loss = 0.0361/0.0424, train/val acc = 0.9881/0.9874\ngenerate new set of images\n0:03:08.671921 : set learn rate to 0.000750\n3.20 epoch: train/val loss = 0.0276/0.0382, train/val acc = 0.9912/0.9886\n3.40 epoch: train/val loss = 0.0338/0.0420, train/val acc = 0.9888/0.9886\n3.60 epoch: train/val loss = 0.0271/0.0331, train/val acc = 0.9917/0.9902\n3.80 epoch: train/val loss = 0.0408/0.0490, train/val acc = 0.9862/0.9833\n4.00 epoch: train/val loss = 0.0270/0.0340, train/val acc = 0.9924/0.9905\ngenerate new set of images\n4.20 epoch: train/val loss = 0.0291/0.0362, train/val acc = 0.9917/0.9900\n4.40 epoch: train/val loss = 0.0246/0.0299, train/val acc = 0.9931/0.9910\n4.60 epoch: train/val loss = 0.0315/0.0326, train/val acc = 0.9914/0.9902\n4.80 epoch: train/val loss = 0.0259/0.0311, train/val acc = 0.9919/0.9910\n5.00 epoch: train/val loss = 0.0254/0.0319, train/val acc = 0.9929/0.9917\ngenerate new set of images\n5.20 epoch: train/val loss = 0.0366/0.0433, train/val acc = 0.9895/0.9864\n5.40 epoch: train/val loss = 0.0361/0.0331, train/val acc = 0.9886/0.9900\n5.60 epoch: train/val loss = 0.0407/0.0370, train/val acc = 0.9886/0.9888\n5.80 epoch: train/val loss = 0.0340/0.0293, train/val acc = 0.9895/0.9931\n6.00 epoch: train/val loss = 0.0349/0.0284, train/val acc = 0.9895/0.9929\n0:07:28.785303 : set learn rate to 0.000500\ngenerate new set of images\n6.20 epoch: train/val loss = 0.0170/0.0254, train/val acc = 0.9952/0.9929\n6.40 epoch: train/val loss = 0.0194/0.0289, train/val acc = 0.9933/0.9905\n6.60 epoch: train/val loss = 0.0171/0.0263, train/val acc = 0.9957/0.9914\n6.79 epoch: train/val loss = 0.0171/0.0281, train/val acc = 0.9952/0.9924\n6.99 epoch: train/val loss = 0.0163/0.0237, train/val acc = 0.9950/0.9926\ngenerate new set of images\n7.19 epoch: train/val loss = 0.0242/0.0253, train/val acc = 0.9926/0.9929\n7.39 epoch: train/val loss = 0.0224/0.0217, train/val acc = 0.9929/0.9945\n7.59 epoch: train/val loss = 0.0236/0.0247, train/val acc = 0.9929/0.9931\n7.79 epoch: train/val loss = 0.0227/0.0266, train/val acc = 0.9921/0.9905\n7.99 epoch: train/val loss = 0.0225/0.0236, train/val acc = 0.9921/0.9929\ngenerate new set of images\n8.19 epoch: train/val loss = 0.0132/0.0237, train/val acc = 0.9955/0.9921\n8.39 epoch: train/val loss = 0.0214/0.0319, train/val acc = 0.9933/0.9900\n8.59 epoch: train/val loss = 0.0147/0.0231, train/val acc = 0.9945/0.9926\n8.79 epoch: train/val loss = 0.0145/0.0266, train/val acc = 0.9952/0.9921\n8.99 epoch: train/val loss = 0.0158/0.0233, train/val acc = 0.9948/0.9926\n0:12:04.408789 : set learn rate to 0.000250\ngenerate new set of images\n9.19 epoch: train/val loss = 0.0246/0.0253, train/val acc = 0.9902/0.9921\n9.39 epoch: train/val loss = 0.0244/0.0243, train/val acc = 0.9921/0.9905\n9.59 epoch: train/val loss = 0.0226/0.0210, train/val acc = 0.9926/0.9940\n9.79 epoch: train/val loss = 0.0225/0.0206, train/val acc = 0.9921/0.9948\n9.99 epoch: train/val loss = 0.0256/0.0204, train/val acc = 0.9931/0.9938\ngenerate new set of images\n10.19 epoch: train/val loss = 0.0169/0.0206, train/val acc = 0.9960/0.9948\n10.39 epoch: train/val loss = 0.0200/0.0210, train/val acc = 0.9948/0.9950\n10.59 epoch: train/val loss = 0.0209/0.0203, train/val acc = 0.9945/0.9950\n10.79 epoch: train/val loss = 0.0186/0.0189, train/val acc = 0.9948/0.9957\n10.99 epoch: train/val loss = 0.0214/0.0206, train/val acc = 0.9950/0.9943\ngenerate new set of images\n11.19 epoch: train/val loss = 0.0154/0.0209, train/val acc = 0.9950/0.9945\n11.39 epoch: train/val loss = 0.0170/0.0223, train/val acc = 0.9952/0.9936\n11.59 epoch: train/val loss = 0.0175/0.0203, train/val acc = 0.9943/0.9933\n11.79 epoch: train/val loss = 0.0169/0.0206, train/val acc = 0.9952/0.9945\n11.99 epoch: train/val loss = 0.0178/0.0202, train/val acc = 0.9948/0.9945\n0:16:52.318593 : set learn rate to 0.000100\ngenerate new set of images\n12.19 epoch: train/val loss = 0.0111/0.0190, train/val acc = 0.9962/0.9952\n12.39 epoch: train/val loss = 0.0099/0.0195, train/val acc = 0.9962/0.9945\n12.59 epoch: train/val loss = 0.0112/0.0205, train/val acc = 0.9964/0.9948\n12.79 epoch: train/val loss = 0.0099/0.0176, train/val acc = 0.9964/0.9950\n12.99 epoch: train/val loss = 0.0099/0.0184, train/val acc = 0.9971/0.9945\ngenerate new set of images\n13.19 epoch: train/val loss = 0.0164/0.0194, train/val acc = 0.9950/0.9945\n13.39 epoch: train/val loss = 0.0168/0.0187, train/val acc = 0.9948/0.9948\n13.59 epoch: train/val loss = 0.0161/0.0178, train/val acc = 0.9955/0.9948\n13.79 epoch: train/val loss = 0.0173/0.0182, train/val acc = 0.9945/0.9952\n13.99 epoch: train/val loss = 0.0180/0.0194, train/val acc = 0.9950/0.9952\ngenerate new set of images\n14.19 epoch: train/val loss = 0.0127/0.0186, train/val acc = 0.9962/0.9945\n14.38 epoch: train/val loss = 0.0144/0.0185, train/val acc = 0.9952/0.9952\n14.58 epoch: train/val loss = 0.0149/0.0202, train/val acc = 0.9948/0.9950\n14.78 epoch: train/val loss = 0.0147/0.0192, train/val acc = 0.9955/0.9960\n14.98 epoch: train/val loss = 0.0125/0.0174, train/val acc = 0.9955/0.9952\ngenerate new set of images\n15.00 epoch: train/val loss = 0.0166/0.0171, train/val acc = 0.9962/0.9952\nrunning time for training: 0:21:38.207149\ntotal running time for training: 0:23:43.443190\n" ], [ "## visualization with tensorboard\n\nif False:\n !tensorboard --logdir=./logs", "_____no_output_____" ], [ "## show confusion matrix\n\nmn = nn_name[0]\nnn_graph = nn_class()\nsess = nn_graph.load_session_from_file(mn)\ny_valid_pred[mn] = nn_graph.forward(sess, x_valid)\nsess.close()\n\ncnf_matrix = sklearn.metrics.confusion_matrix(\n one_hot_to_dense(y_valid_pred[mn]), one_hot_to_dense(y_valid)).astype(np.float32)\n\nlabels_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nfig, ax = plt.subplots(1,figsize=(10,10))\nax = sns.heatmap(cnf_matrix, ax=ax, cmap=plt.cm.Greens, annot=True)\nax.set_xticklabels(labels_array)\nax.set_yticklabels(labels_array)\nplt.title('Confusion matrix of validation set')\nplt.ylabel('True digit')\nplt.xlabel('Predicted digit')\nplt.show();", "C:\\Users\\Azimbek\\Desktop\\N\\tmp.meta\nINFO:tensorflow:Restoring parameters from tmp\n" ], [ "## loss and accuracy curves\n\nmn = nn_name[0]\nnn_graph = nn_class()\nsess = nn_graph.load_session_from_file(mn)\ntrain_loss[mn], valid_loss[mn] = nn_graph.get_loss(sess)\ntrain_acc[mn], valid_acc[mn] = nn_graph.get_accuracy(sess)\nsess.close()\n\nprint('final train/valid loss = %.4f/%.4f, train/valid accuracy = %.4f/%.4f'%(\n train_loss[mn][-1], valid_loss[mn][-1], train_acc[mn][-1], valid_acc[mn][-1]))\n\nplt.figure(figsize=(10, 5));\nplt.subplot(1,2,1);\nplt.plot(np.arange(0,len(train_acc[mn])), train_acc[mn],'-b', label='Training')\nplt.plot(np.arange(0,len(valid_acc[mn])), valid_acc[mn],'-g', label='Validation')\nplt.legend(loc='lower right', frameon=False)\nplt.ylim(ymax = 1.1, ymin = 0.0)\nplt.ylabel('accuracy')\nplt.xlabel('log steps');\n\nplt.subplot(1,2,2)\nplt.plot(np.arange(0,len(train_loss[mn])), train_loss[mn],'-b', label='Training')\nplt.plot(np.arange(0,len(valid_loss[mn])), valid_loss[mn],'-g', label='Validation')\nplt.legend(loc='lower right', frameon=False)\nplt.ylim(ymax = 3.0, ymin = 0.0)\nplt.ylabel('loss')\nplt.xlabel('log steps');", "C:\\Users\\Azimbek\\Desktop\\N\\tmp.meta\nINFO:tensorflow:Restoring parameters from tmp\nfinal train/valid loss = 0.0166/0.0171, train/valid accuracy = 0.9962/0.9952\n" ], [ "## visualize weights\n\nmn = nn_name[0]\nnn_graph = nn_class()\nsess = nn_graph.load_session_from_file(mn)\nW_conv1, W_conv2, W_conv3, _, _ = nn_graph.get_weights(sess)\nsess.close()\n\nprint('W_conv1: min = ' + str(np.min(W_conv1)) + ' max = ' + str(np.max(W_conv1))\n + ' mean = ' + str(np.mean(W_conv1)) + ' std = ' + str(np.std(W_conv1)))\nprint('W_conv2: min = ' + str(np.min(W_conv2)) + ' max = ' + str(np.max(W_conv2))\n + ' mean = ' + str(np.mean(W_conv2)) + ' std = ' + str(np.std(W_conv2)))\nprint('W_conv3: min = ' + str(np.min(W_conv3)) + ' max = ' + str(np.max(W_conv3))\n + ' mean = ' + str(np.mean(W_conv3)) + ' std = ' + str(np.std(W_conv3)))\n\ns_f_conv1 = nn_graph.s_f_conv1\ns_f_conv2 = nn_graph.s_f_conv2\ns_f_conv3 = nn_graph.s_f_conv3\n\nW_conv1 = np.reshape(W_conv1,(s_f_conv1,s_f_conv1,1,6,6))\nW_conv1 = np.transpose(W_conv1,(3,0,4,1,2))\nW_conv1 = np.reshape(W_conv1,(s_f_conv1*6,s_f_conv1*6,1))\n\nW_conv2 = np.reshape(W_conv2,(s_f_conv2,s_f_conv2,6,6,36))\nW_conv2 = np.transpose(W_conv2,(2,0,3,1,4))\nW_conv2 = np.reshape(W_conv2,(6*s_f_conv2,6*s_f_conv2,6,6))\nW_conv2 = np.transpose(W_conv2,(2,0,3,1))\nW_conv2 = np.reshape(W_conv2,(6*6*s_f_conv2,6*6*s_f_conv2))\n\nW_conv3 = np.reshape(W_conv3,(s_f_conv3,s_f_conv3,6,6,36))\nW_conv3 = np.transpose(W_conv3,(2,0,3,1,4))\nW_conv3 = np.reshape(W_conv3,(6*s_f_conv3,6*s_f_conv3,6,6))\nW_conv3 = np.transpose(W_conv3,(2,0,3,1))\nW_conv3 = np.reshape(W_conv3,(6*6*s_f_conv3,6*6*s_f_conv3))\n\nplt.figure(figsize=(15,5))\nplt.subplot(1,3,1)\nplt.gca().set_xticks(np.arange(-0.5, s_f_conv1*6, s_f_conv1), minor = False);\nplt.gca().set_yticks(np.arange(-0.5, s_f_conv1*6, s_f_conv1), minor = False);\nplt.grid(which = 'minor', color='b', linestyle='-', linewidth=1)\nplt.title('W_conv1 ' + str(W_conv1.shape))\nplt.colorbar(plt.imshow(W_conv1[:,:,0], cmap=cm.binary));\n\nplt.subplot(1,3,2)\nplt.gca().set_xticks(np.arange(-0.5, 6*6*s_f_conv2, 6*s_f_conv2), minor = False);\nplt.gca().set_yticks(np.arange(-0.5, 6*6*s_f_conv2, 6*s_f_conv2), minor = False);\nplt.grid(which = 'minor', color='b', linestyle='-', linewidth=1)\nplt.title('W_conv2 ' + str(W_conv2.shape))\nplt.colorbar(plt.imshow(W_conv2[:,:], cmap=cm.binary));\nplt.subplot(1,3,3)\nplt.gca().set_xticks(np.arange(-0.5, 6*6*s_f_conv3, 6*s_f_conv3), minor = False);\nplt.gca().set_yticks(np.arange(-0.5, 6*6*s_f_conv3, 6*s_f_conv3), minor = False);\nplt.grid(which = 'minor', color='b', linestyle='-', linewidth=1)\nplt.title('W_conv3 ' + str(W_conv3.shape))\nplt.colorbar(plt.imshow(W_conv3[:,:], cmap=cm.binary));", "C:\\Users\\Azimbek\\Desktop\\N\\tmp.meta\nINFO:tensorflow:Restoring parameters from tmp\nW_conv1: min = -0.4643239 max = 0.3054258 mean = -0.021786494 std = 0.14818007\nW_conv2: min = -0.4513978 max = 0.32449418 mean = -0.015032451 std = 0.10560192\nW_conv3: min = -0.4593393 max = 0.36425033 mean = -0.01555234 std = 0.1087152\n" ], [ "## visualize activations\n\nimg_no = 10;\nmn = nn_name[0]\nnn_graph = nn_class()\nsess = nn_graph.load_session_from_file(mn)\n(h_conv1, h_pool1, h_conv2, h_pool2,h_conv3, h_pool3, h_fc1,\n h_fc2) = nn_graph.get_activations(sess, x_train_valid[img_no:img_no+1])\nsess.close()\n \n# original image\nplt.figure(figsize=(15,9))\nplt.subplot(2,4,1)\nplt.imshow(x_train_valid[img_no].reshape(28,28),cmap=cm.binary);\n\n# 1. convolution\nplt.subplot(2,4,2)\nplt.title('h_conv1 ' + str(h_conv1.shape))\nh_conv1 = np.reshape(h_conv1,(-1,28,28,6,6))\nh_conv1 = np.transpose(h_conv1,(0,3,1,4,2))\nh_conv1 = np.reshape(h_conv1,(-1,6*28,6*28))\nplt.imshow(h_conv1[0], cmap=cm.binary);\n\n# 1. max pooling\nplt.subplot(2,4,3)\nplt.title('h_pool1 ' + str(h_pool1.shape))\nh_pool1 = np.reshape(h_pool1,(-1,14,14,6,6))\nh_pool1 = np.transpose(h_pool1,(0,3,1,4,2))\nh_pool1 = np.reshape(h_pool1,(-1,6*14,6*14))\nplt.imshow(h_pool1[0], cmap=cm.binary);\n\n# 2. convolution\nplt.subplot(2,4,4)\nplt.title('h_conv2 ' + str(h_conv2.shape))\nh_conv2 = np.reshape(h_conv2,(-1,14,14,6,6))\nh_conv2 = np.transpose(h_conv2,(0,3,1,4,2))\nh_conv2 = np.reshape(h_conv2,(-1,6*14,6*14))\nplt.imshow(h_conv2[0], cmap=cm.binary);\n\n# 2. max pooling\nplt.subplot(2,4,5)\nplt.title('h_pool2 ' + str(h_pool2.shape))\nh_pool2 = np.reshape(h_pool2,(-1,7,7,6,6))\nh_pool2 = np.transpose(h_pool2,(0,3,1,4,2))\nh_pool2 = np.reshape(h_pool2,(-1,6*7,6*7))\nplt.imshow(h_pool2[0], cmap=cm.binary);\n\n# 3. convolution\nplt.subplot(2,4,6)\nplt.title('h_conv3 ' + str(h_conv3.shape))\nh_conv3 = np.reshape(h_conv3,(-1,7,7,6,6))\nh_conv3 = np.transpose(h_conv3,(0,3,1,4,2))\nh_conv3 = np.reshape(h_conv3,(-1,6*7,6*7))\nplt.imshow(h_conv3[0], cmap=cm.binary);\n\n\n# 3. max pooling\nplt.subplot(2,4,7)\nplt.title('h_pool2 ' + str(h_pool3.shape))\nh_pool3 = np.reshape(h_pool3,(-1,4,4,6,6))\nh_pool3 = np.transpose(h_pool3,(0,3,1,4,2))\nh_pool3 = np.reshape(h_pool3,(-1,6*4,6*4))\nplt.imshow(h_pool3[0], cmap=cm.binary);\n\n# 4. FC layer\nplt.subplot(2,4,8)\nplt.title('h_fc1 ' + str(h_fc1.shape))\nh_fc1 = np.reshape(h_fc1,(-1,24,24))\nplt.imshow(h_fc1[0], cmap=cm.binary);\n\n# 5. FC layer\nnp.set_printoptions(precision=2)\nprint('h_fc2 = ', h_fc2)", "C:\\Users\\Azimbek\\Desktop\\N\\tmp.meta\nINFO:tensorflow:Restoring parameters from tmp\nh_fc2 = [[ -5.68 -10.6 -1.32 0.51 -9.83 -3.58 -4.96 -12.26 16.7 -2.3 ]]\n" ], [ "\nmn = nn_name[0]\nnn_graph = nn_class()\nsess = nn_graph.load_session_from_file(mn)\ny_valid_pred[mn] = nn_graph.forward(sess, x_valid)\nsess.close()\n\ny_valid_pred_label = one_hot_to_dense(y_valid_pred[mn])\ny_valid_label = one_hot_to_dense(y_valid)\ny_val_false_index = []\n\nfor i in range(y_valid_label.shape[0]):\n if y_valid_pred_label[i] != y_valid_label[i]:\n y_val_false_index.append(i)\n\nprint('# false predictions: ', len(y_val_false_index),'out of', len(y_valid))\n\nplt.figure(figsize=(10,15))\nfor j in range(0,5):\n for i in range(0,10):\n if j*10+i<len(y_val_false_index):\n plt.subplot(10,10,j*10+i+1)\n plt.title('%d/%d'%(y_valid_label[y_val_false_index[j*10+i]],\n y_valid_pred_label[y_val_false_index[j*10+i]]))\n plt.imshow(x_valid[y_val_false_index[j*10+i]].reshape(28,28),cmap=cm.binary) ", "C:\\Users\\Azimbek\\Desktop\\N\\tmp.meta\nINFO:tensorflow:Restoring parameters from tmp\n# false predictions: 20 out of 4200\n" ] ], [ [ "# 7. Stacking of models and training a meta-model", "_____no_output_____" ] ], [ [ "## read test data\ntest_df = pd.read_csv('test.csv')", "_____no_output_____" ], [ "# transforma and normalize test data\nx_test = test_df.iloc[:,0:].values.reshape(-1,28,28,1) # (28000,28,28,1) array\nx_test = x_test.astype(np.float)\nx_test = normalize_data(x_test)\nprint('x_test.shape = ', x_test.shape)\n\n# for saving results\ny_test_pred = {}\ny_test_pred_labels = {}", "x_test.shape = (28000, 28, 28, 1)\n" ], [ "## Stacking of neural networks\n\nif False:\n \n take_models = ['nn0','nn1','nn2','nn3','nn4','nn5','nn6','nn7','nn8','nn9']\n\n # cross validations\n # choose the same seed as was done for training the neural nets\n kfold = sklearn.model_selection.KFold(len(take_models), shuffle=True, random_state = 123)\n\n # train and test data for meta model\n x_train_meta = np.array([]).reshape(-1,10)\n y_train_meta = np.array([]).reshape(-1,10)\n x_test_meta = np.zeros((x_test.shape[0], 10))\n\n print('Out-of-folds predictions:')\n\n # make out-of-folds predictions from base models\n for i,(train_index, valid_index) in enumerate(kfold.split(x_train_valid)):\n\n # training and validation data\n x_train = x_train_valid[train_index]\n y_train = y_train_valid[train_index]\n x_valid = x_train_valid[valid_index]\n y_valid = y_train_valid[valid_index]\n # load neural network and make predictions\n mn = take_models[i] \n nn_graph = nn_class()\n sess = nn_graph.load_session_from_file(mn)\n y_train_pred[mn] = nn_graph.forward(sess, x_train[:len(x_valid)])\n y_valid_pred[mn] = nn_graph.forward(sess, x_valid)\n y_test_pred[mn] = nn_graph.forward(sess, x_test)\n sess.close()\n\n # create cloned model from base models\n #model = sklearn.base.clone(base_models[take_models[i]])\n #model.fit(x_train, y_train)\n #y_train_pred_proba['tmp'] = model.predict_proba(x_train)[:,1]\n #y_valid_pred_proba['tmp'] = model.predict_proba(x_valid)[:,1]\n #y_test_pred_proba['tmp'] = model.predict_proba(x_test)[:,1]\n\n # collect train and test data for meta model \n x_train_meta = np.concatenate([x_train_meta, y_valid_pred[mn]])\n y_train_meta = np.concatenate([y_train_meta, y_valid]) \n x_test_meta += y_test_pred[mn]\n print(take_models[i],': train/valid accuracy = %.4f/%.4f'%(\n accuracy_from_one_hot_labels(y_train_pred[mn], y_train[:len(x_valid)]),\n accuracy_from_one_hot_labels(y_valid_pred[mn], y_valid)))\n\n if False:\n break;\n\n # take average of test predictions\n x_test_meta = x_test_meta/(i+1)\n y_test_pred['stacked_models'] = x_test_meta\n\n print('')\n print('Stacked models: valid accuracy = %.4f'%accuracy_from_one_hot_labels(x_train_meta,\n y_train_meta))", "_____no_output_____" ], [ "## use meta model\n\nif False:\n \n logreg = sklearn.linear_model.LogisticRegression(verbose=0, solver='lbfgs',\n multi_class='multinomial')\n \n # choose meta model\n take_meta_model = 'logreg'\n\n # train meta model\n model = sklearn.base.clone(base_models[take_meta_model]) \n model.fit(x_train_meta, one_hot_to_dense(y_train_meta))\n \n y_train_pred['meta_model'] = model.predict_proba(x_train_meta)\n y_test_pred['meta_model'] = model.predict_proba(x_test_meta)\n\n print('Meta model: train accuracy = %.4f'%accuracy_from_one_hot_labels(x_train_meta, \n y_train_pred['meta_model']))", "_____no_output_____" ], [ "## choose one single model for test prediction\n\nif True:\n \n mn = nn_name[0] # choose saved model\n nn_graph = nn_class() # create instance\n sess = nn_graph.load_session_from_file(mn) # receive session \n y_test_pred = {}\n y_test_pred_labels = {}\n\n # split evaluation of test predictions into batches\n kfold = sklearn.model_selection.KFold(40, shuffle=False) \n for i,(train_index, valid_index) in enumerate(kfold.split(x_test)):\n if i==0:\n y_test_pred[mn] = nn_graph.forward(sess, x_test[valid_index])\n else: \n y_test_pred[mn] = np.concatenate([y_test_pred[mn],\n nn_graph.forward(sess, x_test[valid_index])])\n\n sess.close()\n ", "C:\\Users\\Azimbek\\Desktop\\N\\tmp.meta\nINFO:tensorflow:Restoring parameters from tmp\n" ] ], [ [ "# Submit the test results", "_____no_output_____" ] ], [ [ "# choose the test predictions and submit the results\n\n#mn = 'meta_model'\nmn = nn_name[0]\ny_test_pred_labels[mn] = one_hot_to_dense(y_test_pred[mn])\n\nprint(mn+': y_test_pred_labels[mn].shape = ', y_test_pred_labels[mn].shape)\nunique, counts = np.unique(y_test_pred_labels[mn], return_counts=True)\nprint(dict(zip(unique, counts)))\n\n# save predictions\nnp.savetxt('submission.csv', \n np.c_[range(1,len(x_test)+1), y_test_pred_labels[mn]], \n delimiter=',', \n header = 'ImageId,Label', \n comments = '', \n fmt='%d')\n\nprint('submission.csv completed')", "tmp: y_test_pred_labels[mn].shape = (28000,)\n{0: 2765, 1: 3193, 2: 2813, 3: 2795, 4: 2758, 5: 2519, 6: 2745, 7: 2895, 8: 2747, 9: 2770}\nsubmission.csv completed\n" ], [ "plt.figure(figsize=(10,15))\nfor j in range(0,5):\n for i in range(0,10):\n plt.subplot(10,10,j*10+i+1)\n plt.title('%d'%y_test_pred_labels[mn][j*10+i])\n plt.imshow(x_test[j*10+i].reshape(28,28), cmap=cm.binary)", "_____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", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0cad88767df2f40589c574e9b78bc20866439d
2,155
ipynb
Jupyter Notebook
tweet-text-duplicates.ipynb
puregome/notebooks
3b9dc20b769244f79be13c096c543805e2948d24
[ "Apache-2.0" ]
3
2020-04-30T13:44:17.000Z
2020-05-07T15:28:32.000Z
tweet-text-duplicates.ipynb
puregome/notebooks
3b9dc20b769244f79be13c096c543805e2948d24
[ "Apache-2.0" ]
null
null
null
tweet-text-duplicates.ipynb
puregome/notebooks
3b9dc20b769244f79be13c096c543805e2948d24
[ "Apache-2.0" ]
1
2020-05-08T20:10:24.000Z
2020-05-08T20:10:24.000Z
21.55
87
0.499304
[ [ [ "# Tweet text duplicates\n\nCount tweets with the same text", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\nimport re", "_____no_output_____" ], [ "DATADIR = \"/home/erikt/projects/puregome/data/text/\"\nTEXT = \"text\"", "_____no_output_____" ], [ "SPYNBR = 400\nFILEPATTERN = \"20200703\"\n\nfiles = sorted(os.listdir(DATADIR))\ntweetTexts = {}\nfor inFileName in files:\n if re.search(FILEPATTERN,inFileName):\n df = pd.read_csv(DATADIR+inFileName)\n for i in range(0,len(df)):\n text = df.iloc[i][TEXT]\n if not text in tweetTexts: tweetTexts[text] = 1\n else:\n tweetTexts[text] += 1\n if tweetTexts[text] == SPYNBR: print(text)", "_____no_output_____" ], [ "MAX = 20\n\ncounter = 0\nfor text in sorted(tweetTexts.keys(),key=lambda k:tweetTexts[k],reverse=True):\n print(counter,tweetTexts[text],text)\n counter += 1\n if counter > MAX: break", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ] ]
cb0cae3f7bc1f4f5565f7ebb7db3d7a574e445bb
9,270
ipynb
Jupyter Notebook
distribution(new)/Distribution(new)/Fitter_limit_dist(completed)/Untitled.ipynb
rasulrukhilloev/ML_tutorials
5f93b883b8c93e5bf9796bf05a7408fe4cd70102
[ "MIT" ]
null
null
null
distribution(new)/Distribution(new)/Fitter_limit_dist(completed)/Untitled.ipynb
rasulrukhilloev/ML_tutorials
5f93b883b8c93e5bf9796bf05a7408fe4cd70102
[ "MIT" ]
null
null
null
distribution(new)/Distribution(new)/Fitter_limit_dist(completed)/Untitled.ipynb
rasulrukhilloev/ML_tutorials
5f93b883b8c93e5bf9796bf05a7408fe4cd70102
[ "MIT" ]
null
null
null
126.986301
1,500
0.700863
[ [ [ "import pandas as pd \n\n\ntemp = pd.read_csv('daily-minimum-temperatures-Australia')\nfitter_for_temp = Fitter(temp, distributions=['norm', 'expon', 'uniform'])\nfitter_for_temp.fit()\nfitter_for_temp.summary()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
cb0ce153e33bad4aacd849f9233d20010e317105
7,615
ipynb
Jupyter Notebook
examples/peeker_groups.ipynb
xesscorp/myhdlpeek
31fdb25b077fa5720136f171db7c76193a051911
[ "MIT" ]
33
2017-06-13T05:20:13.000Z
2021-06-17T20:33:53.000Z
examples/peeker_groups.ipynb
devbisme/myhdlpeek
31fdb25b077fa5720136f171db7c76193a051911
[ "MIT" ]
6
2017-07-08T02:58:07.000Z
2019-08-25T02:04:04.000Z
examples/peeker_groups.ipynb
devbisme/myhdlpeek
31fdb25b077fa5720136f171db7c76193a051911
[ "MIT" ]
5
2017-06-13T10:50:42.000Z
2019-07-26T02:30:43.000Z
52.157534
1,549
0.617728
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Peeker-Groups\" data-toc-modified-id=\"Peeker-Groups-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Peeker Groups</a></span></li></ul></div>", "_____no_output_____" ], [ "# Peeker Groups\n\n`Peeker` objects are normally stored in a global list, but sometimes you might want\nto create a group of `Peeker`s for a set of signals.\nThis is easily done using the `PeekerGroup` class.\nOnce again, I'll use the hierarchical adder example to illustrate the use of `PeekerGroup`s.", "_____no_output_____" ] ], [ [ "from myhdl import *\nfrom myhdlpeek import Peeker, PeekerGroup\n\ndef adder_bit(a, b, c_in, sum_, c_out):\n '''Single bit adder.'''\n @always_comb\n def adder_logic():\n sum_.next = a ^ b ^ c_in\n c_out.next = (a & b) | (a & c_in) | (b & c_in)\n \n # Add some global peekers to monitor the inputs and outputs.\n Peeker(a, 'a')\n Peeker(b, 'b')\n Peeker(c_in, 'c_in')\n Peeker(sum_, 'sum')\n Peeker(c_out, 'c_out')\n return adder_logic\n\ndef adder(a, b, sum_):\n '''Connect single-bit adders to create a complete adder.'''\n c = [Signal(bool(0)) for _ in range(len(a)+1)] # Carry signals between stages.\n s = [Signal(bool(0)) for _ in range(len(a))] # Sum bit for each stage.\n stages = [] # Storage for adder bit instances.\n # Create the adder bits and connect them together.\n for i in range(len(a)):\n stages.append( adder_bit(a=a(i), b=b(i), sum_=s[i], c_in=c[i], c_out=c[i+1]) )\n # Concatenate the sum bits and send them out on the sum_ output.\n @always_comb\n def make_sum():\n sum_.next = ConcatSignal(*reversed(s))\n return instances() # Return all the adder stage instances.\n\n# Create signals for interfacing to the adder.\na, b, sum_ = [Signal(intbv(0,0,8)) for _ in range(3)]\n\n# Clear-out any existing peeker stuff before instantiating the adder.\nPeeker.clear()\n\n# Instantiate the adder.\nadd_1 = adder(a=a, b=b, sum_=sum_)\n\n# Create a group of peekers to monitor the top-level buses.\n# Each argument to PeekerGroup assigns a signal to a name for a peeker.\ntop_pkr = PeekerGroup(a_bus=a, b_bus=b, sum_bus=sum_)\n\n# Create a testbench generator that applies random inputs to the adder.\nfrom random import randrange\ndef test():\n for _ in range(8):\n a.next, b.next = randrange(0, a.max), randrange(0, a.max)\n yield delay(1)\n\n# Simulate the adder, testbench and peekers.\nSimulation(add_1, test(), *Peeker.instances()).run()\n\n# Display only the peekers for the top-level buses.\n# The global peekers in the adder bits won't show up.\ntop_pkr.show_waveforms('a_bus b_bus sum_bus')\ntop_pkr.to_html_table('a_bus b_bus sum_bus')", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ] ]
cb0cf209367305cc65b776218e33bd58e4921e90
10,854
ipynb
Jupyter Notebook
exploration/4_skill_biased_sampling_function/1_pdf_uniform_sampling.ipynb
Cozieee/dsu-mlpp
f195da7fcd7dcdb1e88a35fcd0439c9bb88d165c
[ "MIT" ]
null
null
null
exploration/4_skill_biased_sampling_function/1_pdf_uniform_sampling.ipynb
Cozieee/dsu-mlpp
f195da7fcd7dcdb1e88a35fcd0439c9bb88d165c
[ "MIT" ]
37
2021-01-27T19:10:52.000Z
2021-03-08T01:09:06.000Z
exploration/4_skill_biased_sampling_function/1_pdf_uniform_sampling.ipynb
Cozieee/dsu-mlpp
f195da7fcd7dcdb1e88a35fcd0439c9bb88d165c
[ "MIT" ]
2
2021-03-04T02:02:40.000Z
2021-04-21T04:55:41.000Z
56.53125
2,475
0.683066
[ [ [ "# Naive Sampling function - Sample with uniform estimate user pp scores\n**Contributors:** Victor Lin", "_____no_output_____" ] ], [ [ "import sys\nsys.path.append('../..')\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as st\nfrom exploration.config import mongo_inst\nfrom mlpp.data_collection.sample import use_random_sample, get_custom_user_ids\nfrom mlpp.data_collection.sample_func import sampleFuncGenerator\nfrom mlpp.data_collection.distributions import best_fit_distribution\n\nimport logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)", "_____no_output_____" ], [ "osu_random_db = mongo_inst['osu_random_db']\n\nosu_dump = (osu_random_db['osu_scores_high'], osu_random_db['osu_user_stats'])\nosu_scores_high, osu_user_stats = osu_dump\n\npdf_dump = (osu_random_db['scores_sample_3k'], osu_random_db['users_sample_3k'])\npdf_scores_sample, pdf_users_sample = pdf_dump\n\nDATE_LIMIT = datetime(2019,1,1)\n\ngenerator = sampleFuncGenerator(date_limit = DATE_LIMIT)", "_____no_output_____" ], [ "user_ids = use_random_sample(*osu_dump, *pdf_dump, 3000)", "_____no_output_____" ], [ "scores = list(pdf_scores_sample.find({'date': {'$gt': DATE_LIMIT}}, {'mlpp': 1, '_id': 0}))\n\npp_data_raw = [s['mlpp']['est_user_raw_pp'] for s in scores]\npp_data = [s['mlpp']['est_user_pp'] for s in scores]", "_____no_output_____" ], [ "fig, axs = plt.subplots(1, 2)\nfig.set_figwidth(15)\n_ = axs[0].hist(pp_data_raw, bins = 200)\n_ = axs[1].hist(pp_data, bins = 200)", "_____no_output_____" ], [ "# best_dist, best_params = best_fit_distribution(pp_data)\n\nbest_dist = st.recipinvgauss\nbest_params = best_dist.fit(pp_data)", "_____no_output_____" ], [ "arg = best_params[:-2]\nloc = best_params[-2]\nscale = best_params[-1]\npdf = lambda i: best_dist.pdf(i, loc=loc, scale=scale, *arg)", "_____no_output_____" ], [ "plt.figure(figsize=(10,6))\n\nest_pp_pdf = best_dist.pdf(np.arange(1, 7000), loc=loc, scale=scale, *arg)\n\n_ = plt.hist(pp_data, bins = 200, density=True)\n_ = plt.plot(est_pp_pdf)", "_____no_output_____" ], [ "SAMPLE_PROPORTIONS = np.asarray([.01, .02, .05, .1])\npcnts = [int(prop * 100) for prop in SAMPLE_PROPORTIONS]\n\nsample_funcs = [generator.pdf(pdf_scores_sample, st.recipinvgauss, prop) for prop in SAMPLE_PROPORTIONS]", "_____no_output_____" ], [ "for i, f in enumerate(sample_funcs):\n plt.plot(f, label = f'{pcnts[i]}%')\n\n_ = plt.legend(loc='upper left')", "_____no_output_____" ], [ "def test_pcnt_sampled(sample_func):\n sampled_users = get_custom_user_ids(osu_user_stats, sample_func)\n\n sampled_scores = osu_scores_high.find({\n 'user_id': {\n '$in': sampled_users\n },\n 'date': {\n '$gt': DATE_LIMIT\n }\n }, {'mlpp.est_user_pp': 1})\n\n return sampled_scores.count() / osu_scores_high.count()", "_____no_output_____" ], [ "from tqdm import tqdm\npcnt_1_avg_of_expected = sum(test_pcnt_sampled(sample_funcs[0]) / .01 for i in tqdm(range(10))) / 10\npcnt_2_avg_of_expected = sum(test_pcnt_sampled(sample_funcs[1]) / .02 for i in tqdm(range(10))) / 10\n\nprint(f'\\n\\nProportion of expected 1%: {pcnt_1_avg_of_expected:.2f}')\nprint(f'Proportion of expected 2%: {pcnt_2_avg_of_expected:.2f}')", "_____no_output_____" ], [ "PROP_BONUS_FACTOR = 1 / pcnt_1_avg_of_expected\nSAMPLE_PROPORTIONS *= PROP_BONUS_FACTOR\n\nsample_funcs = [sampleFuncGenerator().pdf(pdf_scores_sample, st.recipinvgauss, prop) for prop in SAMPLE_PROPORTIONS]", "_____no_output_____" ], [ "samples = []\n\nfor i, f in enumerate(sample_funcs):\n samples.append(generator.test_sample_func(*osu_dump, sample_funcs[i]))\n\n scores = samples[-1][0]\n pcnt_scores = 100 * len(scores) / osu_scores_high.count()\n print(f\"{pcnts[i]}% Sampling: {pcnt_scores:.2f}% sampled\")\n\nscore_pp = [[s['mlpp']['est_user_pp'] for s in sc] for sc, u in samples]", "_____no_output_____" ], [ "fig, axs = plt.subplots(4, figsize=(6, 18))\n\nfor i in range(len(SAMPLE_PROPORTIONS)):\n ax = axs[i]\n ax.hist(score_pp[i], bins = 50, label = f'{pcnts[i]}%', density = True)\n ax.plot([0, 7000], [1/7000, 1/7000])\n ax.set(xlabel = \"Proportion\", ylabel=\"Score est pp\")\n ax.set_title(f'{pcnts[i]}% Sample')\n\n_ = plt.tight_layout()", "_____no_output_____" ] ], [ [ "<a style='text-decoration:none;line-height:16px;display:flex;color:#5B5B62;padding:10px;justify-content:end;' href='https://deepnote.com?utm_source=created-in-deepnote-cell&projectId=f93d0822-db5a-47ef-9a78-57b8adfbeb20' target=\"_blank\">\n<img style='display:inline;max-height:16px;margin:0px;margin-right:7.5px;' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iODBweCIgaGVpZ2h0PSI4MHB4IiB2aWV3Qm94PSIwIDAgODAgODAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDU0LjEgKDc2NDkwKSAtIGh0dHBzOi8vc2tldGNoYXBwLmNvbSAtLT4KICAgIDx0aXRsZT5Hcm91cCAzPC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGcgaWQ9IkxhbmRpbmciIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJBcnRib2FyZCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEyMzUuMDAwMDAwLCAtNzkuMDAwMDAwKSI+CiAgICAgICAgICAgIDxnIGlkPSJHcm91cC0zIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMjM1LjAwMDAwMCwgNzkuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8cG9seWdvbiBpZD0iUGF0aC0yMCIgZmlsbD0iIzAyNjVCNCIgcG9pbnRzPSIyLjM3NjIzNzYyIDgwIDM4LjA0NzY2NjcgODAgNTcuODIxNzgyMiA3My44MDU3NTkyIDU3LjgyMTc4MjIgMzIuNzU5MjczOSAzOS4xNDAyMjc4IDMxLjY4MzE2ODMiPjwvcG9seWdvbj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0zNS4wMDc3MTgsODAgQzQyLjkwNjIwMDcsNzYuNDU0OTM1OCA0Ny41NjQ5MTY3LDcxLjU0MjI2NzEgNDguOTgzODY2LDY1LjI2MTk5MzkgQzUxLjExMjI4OTksNTUuODQxNTg0MiA0MS42NzcxNzk1LDQ5LjIxMjIyODQgMjUuNjIzOTg0Niw0OS4yMTIyMjg0IEMyNS40ODQ5Mjg5LDQ5LjEyNjg0NDggMjkuODI2MTI5Niw0My4yODM4MjQ4IDM4LjY0NzU4NjksMzEuNjgzMTY4MyBMNzIuODcxMjg3MSwzMi41NTQ0MjUgTDY1LjI4MDk3Myw2Ny42NzYzNDIxIEw1MS4xMTIyODk5LDc3LjM3NjE0NCBMMzUuMDA3NzE4LDgwIFoiIGlkPSJQYXRoLTIyIiBmaWxsPSIjMDAyODY4Ij48L3BhdGg+CiAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMCwzNy43MzA0NDA1IEwyNy4xMTQ1MzcsMC4yNTcxMTE0MzYgQzYyLjM3MTUxMjMsLTEuOTkwNzE3MDEgODAsMTAuNTAwMzkyNyA4MCwzNy43MzA0NDA1IEM4MCw2NC45NjA0ODgyIDY0Ljc3NjUwMzgsNzkuMDUwMzQxNCAzNC4zMjk1MTEzLDgwIEM0Ny4wNTUzNDg5LDc3LjU2NzA4MDggNTMuNDE4MjY3Nyw3MC4zMTM2MTAzIDUzLjQxODI2NzcsNTguMjM5NTg4NSBDNTMuNDE4MjY3Nyw0MC4xMjg1NTU3IDM2LjMwMzk1NDQsMzcuNzMwNDQwNSAyNS4yMjc0MTcsMzcuNzMwNDQwNSBDMTcuODQzMDU4NiwzNy43MzA0NDA1IDkuNDMzOTE5NjYsMzcuNzMwNDQwNSAwLDM3LjczMDQ0MDUgWiIgaWQ9IlBhdGgtMTkiIGZpbGw9IiMzNzkzRUYiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+' > </img>\nCreated in <span style='font-weight:600;margin-left:4px;'>Deepnote</span></a>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cb0d0f247fe6827a54b1ff8329c9958c6c87bbe1
6,669
ipynb
Jupyter Notebook
notebooks/4_StatsMethods.ipynb
natashabatalha/colorcolor
40fef271bae92712e84a2b7fc3a31dadca60388c
[ "MIT" ]
1
2019-03-02T16:25:32.000Z
2019-03-02T16:25:32.000Z
notebooks/4_StatsMethods.ipynb
natashabatalha/colorcolor
40fef271bae92712e84a2b7fc3a31dadca60388c
[ "MIT" ]
null
null
null
notebooks/4_StatsMethods.ipynb
natashabatalha/colorcolor
40fef271bae92712e84a2b7fc3a31dadca60388c
[ "MIT" ]
1
2021-06-16T06:53:10.000Z
2021-06-16T06:53:10.000Z
27.557851
479
0.597541
[ [ [ "# Multivariate Analysis for Planetary Atmospheres\n\nThis notebooks relies on the pickle dataframe in the `notebooks/` folder. You can also compute your own using `3_ColorColorFigs.ipynb`", "_____no_output_____" ] ], [ [ "#COLOR COLOR PACKAGE\nfrom colorcolor import compute_colors as c\nfrom colorcolor import stats\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pickle as pk\nimport numpy as np\nfrom itertools import combinations as comb\nimport seaborn as sns\n%matplotlib inline", "_____no_output_____" ] ], [ [ "This dataframe contains: \n- **independent variables** : filter observations \n- **dependent variables** : physical planet parameters ", "_____no_output_____" ] ], [ [ "data= pk.load(open('wfirst_colors_dataframe.pk','rb'))\ndata=data.dropna()[~data.dropna().isin([np.inf, -np.inf])].dropna() #drop infinities and nans", "_____no_output_____" ], [ "#let's specicy our y of interest for this tutorial, feel free to play around with this\nyofinterest = 'metallicity'\n#lets also specify a filter set. Let's just focus on WFIRST filters \nfilters = c.print_filters('wfirst')", "_____no_output_____" ], [ "#lets also specify a filter set. Let's just focus on WFIRST filters \nfilters = c.print_filters('wfirst')\n#and also define the combinations: e.g. Filter1 - Filter2\nfilter_combinations = [i[0]+i[1] for i in comb(filters,2)] +filters", "_____no_output_____" ] ], [ [ "### Explore Correlation Matrix: Fig 6 Batalha+2018\n\nIn figure 6 we looked at the difference between the correlation matrix with and without the cloud sample", "_____no_output_____" ] ], [ [ "#lets look at only the cloud free sample\ncorr_matrix = data.loc[(data['cloud']==0)].corr()\nfig, ax = plt.subplots(figsize=(25,10)) \n#here I am simplifying the image by adding in an absolute value \n#you can remove it if you are interested in seeing what is positive and nagatively correlated\nsns.heatmap(abs(corr_matrix), vmax=1, square=False, linewidths=.5, ax=ax).xaxis.tick_top()", "_____no_output_____" ] ], [ [ "Figure 6 in Batalha 2018 is a subset of this larger block", "_____no_output_____" ] ], [ [ "#lets look at everything\ncorr_matrix = data.corr()\nfig, ax = plt.subplots(figsize=(25,10)) \n#here I am simplifying the image by adding in an absolute value \n#you can remove it if you are interested in seeing what is positive and nagatively correlated\nsns.heatmap(abs(corr_matrix), vmax=1, square=False, linewidths=.5, ax=ax).xaxis.tick_top()", "_____no_output_____" ] ], [ [ "** See immediately how there are less strongly correlated values for physical parameters versus filters??**", "_____no_output_____" ], [ "## Try Linear Discriminant Analysis For Classification", "_____no_output_____" ] ], [ [ "#try cloud free first\nsubset = data.loc[(data['cloud']==0) & (data['phase']==90)]\n\n#separate independent\nX = subset.loc[:,filter_combinations]\n\n#and dependent variables (also this make it a string so we can turn it into a label)\ny = subset[yofinterest].astype(str)", "_____no_output_____" ], [ "lda_values=stats.lda_analysis(X,y)", "_____no_output_____" ] ], [ [ "These warnings are coming up because we have used both absolute and relative filters. Because LDA, like regression techniques involves computing a matrix inversion, which is inaccurate if the determinant is close to 0 (i.e. two or more variables are almost a linear combination of each other). This means that our relative filter and absolute combinations are nearly a linear combination of each other (which makes sense). For classification purposes this is okay for now. ", "_____no_output_____" ] ], [ [ "#Now lets unconstrain the phase\nsubset = data.loc[(data['cloud']==0)]\n\n#separate independent\nX = subset.loc[:,filter_combinations]\n\n#and dependent variables (also this make it a string so we can turn it into a label)\ny = subset[yofinterest].astype(str)\n\nlda_values=stats.lda_analysis(X,y)", "_____no_output_____" ], [ "#Now lets unconstrain everything\nsubset = data\n\n#separate independent\nX = subset.loc[:,filter_combinations]\n\n#and dependent variables (also this make it a string so we can turn it into a label)\ny = subset[yofinterest].astype(str)\n\nlda_values=stats.lda_analysis(X,y)", "_____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", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0d16b4633204a374407ce5fd144c5842d1f4c2
46,545
ipynb
Jupyter Notebook
notebooks/180425 - Oahu Mean Shift.ipynb
cseveriano/spatio-temporal-forecasting
8391f3de72b840edb2b35148537502ec5d2ac888
[ "MIT" ]
5
2018-05-25T17:43:52.000Z
2021-12-22T13:13:43.000Z
notebooks/180425 - Oahu Mean Shift.ipynb
cseveriano/spatio-temporal-forecasting
8391f3de72b840edb2b35148537502ec5d2ac888
[ "MIT" ]
null
null
null
notebooks/180425 - Oahu Mean Shift.ipynb
cseveriano/spatio-temporal-forecasting
8391f3de72b840edb2b35148537502ec5d2ac888
[ "MIT" ]
2
2021-07-20T12:32:00.000Z
2021-12-13T05:32:21.000Z
53.012528
1,528
0.548158
[ [ [ "from sklearn.cluster import MeanShift, estimate_bandwidth\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport math\n\nimport os\nimport sys\nfrom numpy.fft import fft, ifft\nimport glob", "_____no_output_____" ], [ "def remove_periodic(X, df_index, detrending=True, model='additive', frequency_threshold=0.1e12):\n rad = np.array(X)\n \n if detrending:\n det_rad = rad - np.average(rad)\n else:\n det_rad = rad\n \n det_rad_fft = fft(det_rad)\n\n # Get the power spectrum\n rad_ps = [np.abs(rd)**2 for rd in det_rad_fft]\n \n clean_rad_fft = [det_rad_fft[i] if rad_ps[i] > frequency_threshold else 0 \n for i in range(len(det_rad_fft))]\n \n rad_series_clean = ifft(clean_rad_fft)\n rad_series_clean = [value.real for value in rad_series_clean]\n \n if detrending:\n rad_trends = rad_series_clean + np.average(rad)\n else:\n rad_trends = rad_series_clean\n \n rad_clean_ts = pd.Series(rad_trends, index=df_index)\n \n #rad_clean_ts[(rad_clean_ts.index.hour < 6) | (rad_clean_ts.index.hour > 20)] = 0\n residual = rad - rad_clean_ts.values\n clean = rad_clean_ts.values\n return residual, clean", "_____no_output_____" ], [ "def load_data(path, resampling=None):\n ## some resampling options: 'H' - hourly, '15min' - 15 minutes, 'M' - montlhy\n ## more options at:\n ## http://benalexkeen.com/resampling-time-series-data-with-pandas/\n allFiles = glob.iglob(path + \"/**/*.txt\", recursive=True)\n frame = pd.DataFrame()\n list_ = []\n for file_ in allFiles:\n #print(\"Reading: \",file_)\n df = pd.read_csv(file_,index_col=\"datetime\",parse_dates=['datetime'], header=0, sep=\",\")\n if frame.columns is None :\n frame.columns = df.columns\n list_.append(df)\n frame = pd.concat(list_)\n if resampling is not None:\n frame = frame.resample(resampling).mean()\n frame = frame.fillna(method='ffill')\n return frame", "_____no_output_____" ], [ "path = '/Users/cseveriano/spatio-temporal-forecasting/data/processed/NREL/Oahu'\n\ndf = load_data(path)\n\n# Corrigir ordem das colunas\ndf.columns = ['DHHL_3','DHHL_4', 'DHHL_5', 'DHHL_10', 'DHHL_11', 'DHHL_9', 'DHHL_2', 'DHHL_1', 'DHHL_1_Tilt', 'AP_6', 'AP_6_Tilt', 'AP_1', 'AP_3', 'AP_5', 'AP_4', 'AP_7', 'DHHL_6', 'DHHL_7', 'DHHL_8']\n#inicio dos dados possui falhas na medicao\ndf = df.loc[df.index > '2010-03-20']\ndf.drop(['DHHL_1_Tilt', 'AP_6_Tilt'], axis=1, inplace=True)", "_____no_output_____" ] ], [ [ "## Preparação bases de treinamento e testes", "_____no_output_____" ] ], [ [ "clean_df = pd.DataFrame(columns=df.columns, index=df.index)\nresidual_df = pd.DataFrame(columns=df.columns, index=df.index)\n\nfor col in df.columns:\n residual, clean = remove_periodic(df[col].tolist(), df.index, frequency_threshold=0.01e12)\n clean_df[col] = clean.tolist()\n residual_df[col] = residual.tolist()", "_____no_output_____" ], [ "train_df = df[(df.index >= '2010-09-01') & (df.index <= '2011-09-01')]\ntrain_clean_df = clean_df[(clean_df.index >= '2010-09-01') & (clean_df.index <= '2011-09-01')]\ntrain_residual_df = residual_df[(residual_df.index >= '2010-09-01') & (residual_df.index <= '2011-09-01')]\n\n\ntest_df = df[(df.index >= '2010-08-05')& (df.index < '2010-08-06')]\ntest_clean_df = clean_df[(clean_df.index >= '2010-08-05')& (clean_df.index < '2010-08-06')]\ntest_residual_df = residual_df[(residual_df.index >= '2010-08-05')& (residual_df.index < '2010-08-06')]", "_____no_output_____" ], [ "lat = [21.31236,21.31303,21.31357,21.31183,21.31042,21.31268,21.31451,21.31533,21.30812,21.31276,21.31281,21.30983,21.31141,21.31478,21.31179,21.31418,21.31034]\nlon = [-158.08463,-158.08505,-158.08424,-158.08554,-158.0853,-158.08688,-158.08534,-158.087,-158.07935,-158.08389,-158.08163,-158.08249,-158.07947,-158.07785,-158.08678,-158.08685,-158.08675]", "_____no_output_____" ], [ "additional_info = pd.DataFrame({'station': df.columns, 'latitude': lat, 'longitude': lon })", "_____no_output_____" ], [ "additional_info[(additional_info.station == col)].latitude.values[0]", "_____no_output_____" ], [ "#ll = []\n#for ind, row in train_residual_df.iterrows():\n# for col in train_residual_df.columns:\n# lat = additional_info[(additional_info.station == col)].latitude.values[0]\n# lon = additional_info[(additional_info.station == col)].longitude.values[0]\n# doy = ind.dayofyear\n# hour = ind.hour\n# minute = ind.minute\n# irradiance = row[col]\n# ll.append([lat, lon, doy, hour, minute, irradiance]) \n\n#ms_df = pd.DataFrame(columns=['latitude','longitude','dayofyear', 'hour', 'minute','irradiance'], data=ll)", "_____no_output_____" ], [ "ll = []\nfor ind, row in train_residual_df.iterrows():\n for col in train_residual_df.columns:\n lat = additional_info[(additional_info.station == col)].latitude.values[0]\n lon = additional_info[(additional_info.station == col)].longitude.values[0]\n irradiance = row[col]\n ll.append([lat, lon, irradiance]) \n\nms_df = pd.DataFrame(columns=['latitude','longitude','irradiance'], data=ll)", "_____no_output_____" ], [ "ms_df", "_____no_output_____" ] ], [ [ "## Mean Shift", "_____no_output_____" ], [ "Normalização dos dados", "_____no_output_____" ] ], [ [ "from sklearn import preprocessing\n\nx = ms_df.values #returns a numpy array\nmin_max_scaler = preprocessing.MinMaxScaler()\nx_scaled = min_max_scaler.fit_transform(x)", "_____no_output_____" ], [ "bandwidth", "_____no_output_____" ], [ "bandwidth = estimate_bandwidth(x_scaled, quantile=0.2, n_samples=int(len(ms_df)*0.1), n_jobs=-1)", "_____no_output_____" ], [ "ms = MeanShift(bandwidth=bandwidth, n_jobs=-1)\nms.fit(x_scaled)", "Process ForkPoolWorker-4:\nProcess ForkPoolWorker-3:\nProcess ForkPoolWorker-1:\n" ], [ "labels = ms.labels_\ncluster_centers = ms.cluster_centers_\n\nlabels_unique = np.unique(labels)\nn_clusters_ = len(labels_unique)\n\nprint(\"number of estimated clusters : %d\" % n_clusters_)", "number of estimated clusters : 1\n" ], [ "labels", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cb0d363a952dbda4f3efbad1ebfad4ac86e0b5d1
182,286
ipynb
Jupyter Notebook
alte_dc.ipynb
cwcala/AL-TOTAL-wind-prediction-challenge
d40bca5cb9d10d3430292f6e7720e443ce0e263d
[ "MIT" ]
null
null
null
alte_dc.ipynb
cwcala/AL-TOTAL-wind-prediction-challenge
d40bca5cb9d10d3430292f6e7720e443ce0e263d
[ "MIT" ]
null
null
null
alte_dc.ipynb
cwcala/AL-TOTAL-wind-prediction-challenge
d40bca5cb9d10d3430292f6e7720e443ce0e263d
[ "MIT" ]
null
null
null
151.400332
60,896
0.861174
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n# our python file with functions\nimport altedc as altedc", "_____no_output_____" ], [ "data_path = 'data/'\ndata = pd.read_csv(f'{data_path}train_phase_1.csv')\ndata.date = pd.to_datetime(data.date, format='%Y-%m-%d %H:%M:%S')\ntest = pd.read_csv(f'{data_path}test_phase_1.csv')\ntest.date = pd.to_datetime(test.date, format='%Y-%m-%d %H:%M:%S')", "_____no_output_____" ], [ "data.shape, test.shape", "_____no_output_____" ], [ "assert data.dtypes.equals(pd.Series({\n 'date': 'datetime64[ns]', \n 'wp1': 'float64', \n 'u': 'float64', \n 'v': 'float64', \n 'ws': 'float64', \n 'wd': 'float64',\n}))\n\nassert test.dtypes.equals(pd.Series({\n 'date': 'datetime64[ns]', \n 'u': 'float64', \n 'v': 'float64', \n 'ws': 'float64', \n 'wd': 'float64',\n}))", "_____no_output_____" ], [ "assert not data.isnull().any(axis=None) and not test.isnull().any(axis=None)", "_____no_output_____" ], [ "from sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "train, val = train_test_split(data, test_size=0.2, shuffle=True)\nprint(train.shape, val.shape)", "(15004, 6) (3752, 6)\n" ], [ "X_train = train['ws'].values.reshape((-1, 1))\ny_train = train['wp1'].values\n\nX_val = val['ws'].values.reshape((-1, 1))\ny_val = val['wp1'].values\n\nlm = LinearRegression()\nlm.fit(X_train, y_train)\nmean_absolute_error(lm.predict(X_val), y_val)", "_____no_output_____" ], [ "from sklearn.dummy import DummyRegressor\ndm = DummyRegressor(strategy='mean')\ndm.fit(X_train, y_train)\nprint(mean_absolute_error(dm.predict(X_val), y_val))\n\ndm = DummyRegressor(strategy='median')\ndm.fit(X_train, y_train)\nprint(mean_absolute_error(dm.predict(X_val), y_val))", "0.200902640319369\n0.19495255863539446\n" ], [ "from sklearn.ensemble import RandomForestRegressor\nX_train = train[['ws', 'wd', 'u', 'v']].values\ny_train = train['wp1'].values\n\nX_val = val[['ws', 'wd', 'u', 'v']].values\ny_val = val['wp1'].values\n\nrf = RandomForestRegressor(n_jobs=-1)\nrf.fit(X_train, y_train)\nprint(mean_absolute_error(rf.predict(X_val), y_val))", "0.1290526935856432\n" ], [ "#make new features\ndf_copy = altedc.create_features_train(train)\ndf_copy_val = altedc.create_features_val(val)\ndf_copy_test = altedc.create_features_test(test)", "/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:66: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy['wk']=df_copy.date.dt.week\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:130: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n wavh_copy=df_copy.groupby([df_copy['date'].dt.week])['vh'].mean().to_dict()\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:131: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy['wavh']=df_copy['date'].dt.week.replace(wavh_copy)\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:138: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n waws_copy=df_copy.groupby([df_copy['date'].dt.week])['ws'].mean().to_dict()\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:139: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy['waws']=df_copy['date'].dt.week.replace(waws_copy)\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:260: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy_val['wk']=df_copy_val.date.dt.week\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:326: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n wavh_val=df_copy_val.groupby([df_copy_val['date'].dt.week])['vh'].mean().to_dict()\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:327: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy_val['wavh']=df_copy_val['date'].dt.week.replace(wavh_val)\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:334: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n waws_copy_val=df_copy_val.groupby([df_copy_val['date'].dt.week])['ws'].mean().to_dict()\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:335: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy_val['waws']=df_copy_val['date'].dt.week.replace(waws_copy_val)\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:455: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy_test['wk']=df_copy_test.date.dt.week\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:522: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n wavh_test=df_copy_test.groupby([df_copy_test['date'].dt.week])['vh'].mean().to_dict()\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:523: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy_test['wavh']=df_copy_test['date'].dt.week.replace(wavh_test)\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:530: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n waws_copy_test=df_copy_test.groupby([df_copy_test['date'].dt.week])['ws'].mean().to_dict()\n/home/ec2-user/SageMaker/git/data_challenge/Data-Challenge-Starter-Kit/altedc.py:531: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.\n df_copy_test['waws']=df_copy_test['date'].dt.week.replace(waws_copy_test)\n" ], [ "cols=['u', 'v', 'ws', 'wd', 'wva', 'mwd', 'vh', 'hr', 'mo', 'dy', 'wk', 'qr', 'doy', 'dow', 'yr', 'u_z', 'v_z', 'ws_z', 'wd_z', 'wsq', 'wdc', 'wvac', 'mwdc','rwd', 'u*v', 'wsr', 'ws100m', 'ws3', 'wpe','pa','vh3','daws','davh','year_sin','year_cos','month_sin', 'month_cos', 'quarter_sin', 'quarter_cos','semester_sin',\n 'semester_cos', 'twowk_sin', 'twowk_cos', 'week_sin', 'week_cos', 'twomonth_sin', 'twomonth_cos', 'fourmonth_sin',\n 'fourmonth_cos', 'fivemonth_sin', 'fivemonth_cos',\n 'sevenmonth_sin', 'sevenmonth_cos', 'ninemonth_sin', 'ninemonth_cos', 'thirteenmonth_cos', 'elevenmonth_cos','fivemonth_sin','sevenmonth_sin', 'sixteenmonth_cos','ti','vhi','uv_dir', 'wswdsin','wswdcos','twoday_sin','twoday_cos','tid','gust','dmws',#'wd_ns','wd_ew','wd_avg' ,'wsh_max','vhi_max','ws_diff','vhi_diff','ti_diff' #,'hmws' #, 'tiv', #'vhiv'#'gusti'#,'dwd', 'dti','pai','dvh','dpa'\n # 'pai','vhpa'\n \n ] # 'vhpa' ,'vhid','paid', 'pai', 'haws', 'dmvh','dpa'", "_____no_output_____" ], [ "len(cols)", "_____no_output_____" ], [ "#Try RF on additional features\nfrom sklearn.ensemble import RandomForestRegressor\nX_train = df_copy[cols].values #'wva', 'mwd',\ny_train = df_copy['wp1'].values\n\nX_val = df_copy_val[cols].values #'wva', 'mwd',\ny_val = df_copy_val['wp1'].values\n\nrf = RandomForestRegressor(bootstrap=False, max_depth=25, max_features=12,\n n_estimators=2000, n_jobs=-1)\nrf.fit(X_train, y_train)\nprint(mean_absolute_error(rf.predict(X_val), y_val)) #min_samples_split =2, min_samples_leaf =1, max_depth=20, max_features=10, 0.06642867238363016, \n# 0.06682952159550563 0.06961529322707194 0.06871897093902136 bootstrap false, max depth 25, max features 12, n_estimators 2000", "0.06768425596517569\n" ], [ "#predictions on test set with RF and additional features\nX_test = df_copy_test[cols].values\n\ndf_predictions = pd.DataFrame({\n 'date': df_copy_test['date'],\n 'wp1': rf.predict(X_test),\n})\n\ndf_predictions.to_csv(r'predictions.csv', index=False, sep=';')\ndf_predictions.head()", "_____no_output_____" ], [ "!pip3 install xgboost", "Collecting xgboost\n Downloading xgboost-1.4.2-py3-none-manylinux2010_x86_64.whl (166.7 MB)\n\u001b[K |████████████████████████████████| 166.7 MB 22 kB/s s eta 0:00:01\n\u001b[?25hRequirement already satisfied: numpy in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from xgboost) (1.19.5)\nRequirement already satisfied: scipy in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from xgboost) (1.5.3)\nInstalling collected packages: xgboost\nSuccessfully installed xgboost-1.4.2\n" ], [ "import xgboost as xgb\nX_train = df_copy[cols].values #'wva', 'mwd',,'u*v','rwd'\ny_train = df_copy['wp1'].values\n\nX_val = df_copy_val[cols].values #'wva', 'mwd',,'u*v','rwd'\ny_val = df_copy_val['wp1'].values\n\nxgb = xgb.XGBRegressor(random_state=0)\nxgb.fit(X_train, y_train)\nprint(mean_absolute_error(xgb.predict(X_val), y_val))", "0.07290120074089664\n" ], [ "!pip install lightgbm", "Requirement already satisfied: lightgbm in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (3.2.1)\nRequirement already satisfied: scikit-learn!=0.22.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from lightgbm) (0.24.1)\nRequirement already satisfied: scipy in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from lightgbm) (1.5.3)\nRequirement already satisfied: numpy in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from lightgbm) (1.19.5)\nRequirement already satisfied: wheel in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from lightgbm) (0.36.2)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from scikit-learn!=0.22.0->lightgbm) (2.1.0)\nRequirement already satisfied: joblib>=0.11 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from scikit-learn!=0.22.0->lightgbm) (1.0.1)\n" ], [ "import lightgbm as lgb\nX_train = df_copy[cols].values #'wva', 'mwd',\ny_train = df_copy['wp1'].values\n\nX_val = df_copy_val[cols].values #'wva', 'mwd',\ny_val = df_copy_val['wp1'].values\n\nlgbm = lgb.LGBMRegressor(objective=\"tweedie\",max_depth=15,num_leaves=80,num_iterations=2500,learning_rate=0.01,min_data_in_leaf=100, min_sum_hessian_in_leaf=10, feature_fraction=0.6)\nlgbm.fit(X_train, y_train)\nprint(mean_absolute_error(lgbm.predict(X_val), y_val))", "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/lightgbm/engine.py:148: UserWarning: Found `num_iterations` in params. Will use it instead of argument\n _log_warning(\"Found `{}` in params. Will use it instead of argument\".format(alias))\n" ], [ "#bagging regressor\nfrom sklearn.ensemble import BaggingRegressor\n\nX_train = df_copy[cols].values #'wva', 'mwd',,'u*v','rwd'\ny_train = df_copy['wp1'].values\n\nX_val = df_copy_val[cols].values #'wva', 'mwd',,'u*v','rwd'\ny_val = df_copy_val['wp1'].values\n\nbr = BaggingRegressor(random_state=0,bootstrap=False, n_estimators=2000, max_features=25, max_samples=0.5)\nbr.fit(X_train, y_train)\nprint(mean_absolute_error(br.predict(X_val), y_val))", "0.07716929997334773\n" ], [ "#RF feature importances\nrf.feature_importances_", "_____no_output_____" ], [ "plt.rcParams.update({'figure.figsize': (12,30)})\nsorted_idx = rf.feature_importances_.argsort()\nplt.barh(df_copy[cols].columns[sorted_idx], rf.feature_importances_[sorted_idx])\nplt.xlabel(\"Random Forest Feature Importance\")", "_____no_output_____" ], [ "!pip3 install --upgrade pip\n!pip3 install numpy\n!pip3 install pandas\n!pip3 install matplotlib\n!pip3 install scikit-learn\n!pip3 install keras\n!pip3 install tensorflow", "Requirement already satisfied: pip in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (21.0.1)\nCollecting pip\n Downloading pip-21.1.3-py3-none-any.whl (1.5 MB)\n\u001b[K |████████████████████████████████| 1.5 MB 23.4 MB/s eta 0:00:01\n\u001b[?25hInstalling collected packages: pip\n Attempting uninstall: pip\n Found existing installation: pip 21.0.1\n Uninstalling pip-21.0.1:\n Successfully uninstalled pip-21.0.1\nSuccessfully installed pip-21.1.3\nRequirement already satisfied: numpy in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (1.19.5)\nRequirement already satisfied: pandas in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (1.1.5)\nRequirement already satisfied: python-dateutil>=2.7.3 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pandas) (2.8.1)\nRequirement already satisfied: pytz>=2017.2 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pandas) (2021.1)\nRequirement already satisfied: numpy>=1.15.4 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pandas) (1.19.5)\nRequirement already satisfied: six>=1.5 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)\nRequirement already satisfied: matplotlib in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (3.3.4)\nRequirement already satisfied: python-dateutil>=2.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (2.8.1)\nRequirement already satisfied: cycler>=0.10 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (1.3.1)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (2.4.7)\nRequirement already satisfied: pillow>=6.2.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (7.2.0)\nRequirement already satisfied: numpy>=1.15 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from matplotlib) (1.19.5)\nRequirement already satisfied: six in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from cycler>=0.10->matplotlib) (1.15.0)\nRequirement already satisfied: scikit-learn in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (0.24.1)\nRequirement already satisfied: joblib>=0.11 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from scikit-learn) (1.0.1)\nRequirement already satisfied: numpy>=1.13.3 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from scikit-learn) (1.19.5)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from scikit-learn) (2.1.0)\nRequirement already satisfied: scipy>=0.19.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from scikit-learn) (1.5.3)\nCollecting keras\n Downloading Keras-2.4.3-py2.py3-none-any.whl (36 kB)\nRequirement already satisfied: pyyaml in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from keras) (5.4.1)\nRequirement already satisfied: h5py in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from keras) (3.1.0)\nRequirement already satisfied: numpy>=1.9.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from keras) (1.19.5)\nRequirement already satisfied: scipy>=0.14 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from keras) (1.5.3)\nRequirement already satisfied: cached-property in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from h5py->keras) (1.5.1)\nInstalling collected packages: keras\nSuccessfully installed keras-2.4.3\nCollecting tensorflow\n Downloading tensorflow-2.5.0-cp36-cp36m-manylinux2010_x86_64.whl (454.3 MB)\n\u001b[K |██████████████████████▋ | 321.5 MB 136.1 MB/s eta 0:00:01 |█▏ | 16.7 MB 22.1 MB/s eta 0:00:20 |██████▎ | 89.4 MB 22.1 MB/s eta 0:00:17 |███████████████▌ | 220.5 MB 78.8 MB/s eta 0:00:03" ], [ "import sklearn\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nimport os\nimport tensorflow as tf\nimport keras\nfrom keras.models import Input, Sequential, load_model, Model\nfrom keras.layers import Dense, LSTM, Dropout\nfrom keras.layers import Conv1D, Flatten, MaxPooling1D\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom numpy.random import seed\nseed(100)\ntf.random.set_seed(100)", "_____no_output_____" ], [ "df=data.copy()", "_____no_output_____" ], [ "df_cols= df.columns.to_list()", "_____no_output_____" ], [ "# Define the features that will be used for training\ntrain_columns = df_cols[1:]\n# Get only the train_columns part of pandas \n# Call split_data function and print the shape of each set\ndf_train, df_val, df_test = altedc.split_data(df[train_columns])\nprint('Train \\n', df_train)\nprint('Val \\n', df_val)\nprint('Test \\n', df_test)", "Train \n wp1 u v ws wd\n0 0.085 2.34 -0.79 2.47 108.68\n1 0.020 2.18 -0.99 2.40 114.31\n2 0.060 2.20 -1.21 2.51 118.71\n3 0.045 2.35 -1.40 2.73 120.86\n4 0.035 2.53 -1.47 2.93 120.13\n... ... ... ... ... ...\n15000 0.105 -1.38 2.52 2.88 331.25\n15001 0.160 -1.75 2.28 2.87 322.58\n15002 0.281 -1.96 2.41 3.11 320.92\n15003 0.381 -1.98 2.80 3.43 324.75\n15004 0.356 -1.69 3.30 3.70 332.90\n\n[15005 rows x 5 columns]\nVal \n wp1 u v ws wd\n15005 0.266 -0.97 3.77 3.89 345.62\n15006 0.306 0.23 4.10 4.11 3.26\n15007 0.311 1.68 4.24 4.56 21.61\n15008 0.271 3.05 4.13 5.14 36.45\n15009 0.231 4.11 3.80 5.60 47.25\n... ... ... ... ... ...\n16876 0.852 4.01 4.67 6.15 40.67\n16877 0.822 3.96 4.69 6.14 40.18\n16878 0.832 3.80 4.35 5.78 41.13\n16879 0.747 3.56 3.82 5.22 42.93\n16880 0.687 3.24 3.31 4.63 44.35\n\n[1876 rows x 5 columns]\nTest \n wp1 u v ws wd\n16881 0.541 2.88 3.00 4.16 43.86\n16882 0.311 2.53 2.83 3.80 41.72\n16883 0.301 2.24 2.74 3.53 39.25\n16884 0.080 -1.01 1.28 1.63 321.69\n16885 0.115 -1.20 1.44 1.88 320.03\n... ... ... ... ... ...\n18751 0.170 1.77 -1.52 2.34 130.63\n18752 0.211 1.93 -1.52 2.46 128.25\n18753 0.251 2.10 -1.73 2.72 129.58\n18754 0.301 2.21 -2.19 3.11 134.64\n18755 0.226 2.23 -2.90 3.66 142.36\n\n[1875 rows x 5 columns]\n" ], [ "# Transform pandas to numpy arrays\ntrain_data = df_train.values\nval_data = df_val.values\ntest_data = df_test.values\n\nprint('Train data has shape', np.shape(train_data))\nprint('Validation data has shape', np.shape(val_data))\nprint('Test data has shape', np.shape(test_data))", "Train data has shape (15005, 5)\nValidation data has shape (1876, 5)\nTest data has shape (1875, 5)\n" ], [ "# Feature Scaling using Min-Max Scaler\n# Use fit_transform for train_data and transform for val, test data\nscaler = MinMaxScaler(feature_range = (0, 1))\ntrain_data = scaler.fit_transform(train_data)\nval_data = scaler.transform(val_data)\ntest_data = scaler.transform(test_data)", "_____no_output_____" ], [ "# Set the desirable history for creating samples from the time-series\nseq_len = 20\nahead = 1\nX_train, y_train = altedc.create_supervised_data(train_data, seq_len=seq_len, ahead=ahead)\nprint('X_train shape is ', np.shape(X_train))\nprint('y_train shape is ', np.shape(y_train))\n\nX_val, y_val = altedc.create_supervised_data(val_data, seq_len=seq_len, ahead=ahead)\nprint('X_val shape is ', np.shape(X_val))\nprint('y_val shape is ', np.shape(y_val))\n\nX_test, y_test = altedc.create_supervised_data(test_data, seq_len=seq_len, ahead=ahead)\nprint('X_test shape is ', np.shape(X_test))\nprint('y_test shape is ', np.shape(y_test))", "X_train shape is (14985, 20, 5)\ny_train shape is (14985, 1)\nX_val shape is (1856, 20, 5)\ny_val shape is (1856, 1)\nX_test shape is (1855, 20, 5)\ny_test shape is (1855, 1)\n" ], [ "keras.backend.clear_session()\nseed(100)\ntf.random.set_seed(100)", "_____no_output_____" ], [ "model = altedc.create_model(np.shape(X_train)[1], np.shape(X_train)[2])\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlstm (LSTM) (None, 50) 11200 \n_________________________________________________________________\ndropout (Dropout) (None, 50) 0 \n_________________________________________________________________\ndense (Dense) (None, 1) 51 \n=================================================================\nTotal params: 11,251\nTrainable params: 11,251\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "history = altedc.compile_and_fit(model, X_train, y_train, X_val, y_val, patience=10)", "Epoch 1/100\n469/469 [==============================] - 17s 9ms/step - loss: 0.0323 - mean_absolute_error: 0.1632 - val_loss: 0.0125 - val_mean_absolute_error: 0.0986\nEpoch 2/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0103 - mean_absolute_error: 0.0937 - val_loss: 0.0093 - val_mean_absolute_error: 0.0834\nEpoch 3/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0076 - mean_absolute_error: 0.0810 - val_loss: 0.0083 - val_mean_absolute_error: 0.0757\nEpoch 4/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0068 - mean_absolute_error: 0.0743 - val_loss: 0.0081 - val_mean_absolute_error: 0.0710\nEpoch 5/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0063 - mean_absolute_error: 0.0701 - val_loss: 0.0085 - val_mean_absolute_error: 0.0679\nEpoch 6/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0063 - mean_absolute_error: 0.0673 - val_loss: 0.0080 - val_mean_absolute_error: 0.0659\nEpoch 7/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0062 - mean_absolute_error: 0.0654 - val_loss: 0.0081 - val_mean_absolute_error: 0.0643\nEpoch 8/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0062 - mean_absolute_error: 0.0640 - val_loss: 0.0081 - val_mean_absolute_error: 0.0631\nEpoch 9/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0062 - mean_absolute_error: 0.0629 - val_loss: 0.0082 - val_mean_absolute_error: 0.0621\nEpoch 10/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0061 - mean_absolute_error: 0.0620 - val_loss: 0.0081 - val_mean_absolute_error: 0.0614\nEpoch 11/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0061 - mean_absolute_error: 0.0612 - val_loss: 0.0080 - val_mean_absolute_error: 0.0607\nEpoch 12/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0059 - mean_absolute_error: 0.0606 - val_loss: 0.0085 - val_mean_absolute_error: 0.0602\nEpoch 13/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0060 - mean_absolute_error: 0.0601 - val_loss: 0.0081 - val_mean_absolute_error: 0.0597\nEpoch 14/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0060 - mean_absolute_error: 0.0596 - val_loss: 0.0084 - val_mean_absolute_error: 0.0593\nEpoch 15/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0058 - mean_absolute_error: 0.0592 - val_loss: 0.0082 - val_mean_absolute_error: 0.0589\nEpoch 16/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0058 - mean_absolute_error: 0.0588 - val_loss: 0.0081 - val_mean_absolute_error: 0.0586\nEpoch 17/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0060 - mean_absolute_error: 0.0585 - val_loss: 0.0082 - val_mean_absolute_error: 0.0583\nEpoch 18/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0060 - mean_absolute_error: 0.0582 - val_loss: 0.0082 - val_mean_absolute_error: 0.0580\nEpoch 19/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0061 - mean_absolute_error: 0.0580 - val_loss: 0.0081 - val_mean_absolute_error: 0.0577\nEpoch 20/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0060 - mean_absolute_error: 0.0577 - val_loss: 0.0083 - val_mean_absolute_error: 0.0575\nEpoch 21/100\n469/469 [==============================] - 4s 8ms/step - loss: 0.0058 - mean_absolute_error: 0.0575 - val_loss: 0.0083 - val_mean_absolute_error: 0.0573\n" ], [ "def print_metrics_model(X_train, y_train, X_val, y_val, X_test, y_test):\n print('Evaluation metrics')\n print(\n 'Training Data - MSE Loss: {:.8f}, MAE Loss: {:.8f}'.format(\n model.evaluate(X_train, y_train, verbose=0)[0], \n model.evaluate(X_train, y_train, verbose=0)[1]))\n print(\n 'Validation Data - MSE Loss: {:.8f}, MAE Loss: {:.8f}'.format(\n model.evaluate(X_val, y_val, verbose=0)[0],\n model.evaluate(X_val, y_val, verbose=0)[1]))\n print(\n 'Test Data - MSE Loss: {:.8f}, MAE Loss: {:.8f}'.format(\n model.evaluate(X_test, y_test, verbose=0)[0],\n model.evaluate(X_test, y_test, verbose=0)[1]))\n return", "_____no_output_____" ], [ "altedc.plot_loss(history)\nprint_metrics_model(X_train, y_train, X_val, y_val, X_test, y_test)", "_____no_output_____" ], [ "predictions = model.predict(X_test)\nprint(predictions.shape)\naltedc.plot_predictions_test(y_test.squeeze(), predictions)", "(1855, 1)\n" ], [ "print('Real mse on test', mean_squared_error(y_test.squeeze(),predictions))", "Real mse on test 0.010564701861848526\n" ], [ "model.save('model.h5')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0d4301a7db461c5917b6381742d0b5cb4143c7
228,489
ipynb
Jupyter Notebook
driveby_pcap_analysis/driveby_pcap_analysis.ipynb
adipola/data_hacking
a7cfbaf8395c4ad0e7ac8b6c860c6035b00ae553
[ "MIT" ]
2
2020-05-11T17:54:06.000Z
2021-04-16T03:07:41.000Z
driveby_pcap_analysis/driveby_pcap_analysis.ipynb
adipola/data_hacking
a7cfbaf8395c4ad0e7ac8b6c860c6035b00ae553
[ "MIT" ]
null
null
null
driveby_pcap_analysis/driveby_pcap_analysis.ipynb
adipola/data_hacking
a7cfbaf8395c4ad0e7ac8b6c860c6035b00ae553
[ "MIT" ]
null
null
null
75.608537
84,291
0.674186
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb0d6545a6000574afcf55d3ce930c5e2fb8bb24
28,807
ipynb
Jupyter Notebook
Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb
nomancseku/NSL-HW
9a130a97ce0909cff93a77378f95e44c69a8bc7c
[ "MIT" ]
1
2020-11-29T20:02:08.000Z
2020-11-29T20:02:08.000Z
Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb
nomancseku/NSL-RA-Training
9a130a97ce0909cff93a77378f95e44c69a8bc7c
[ "MIT" ]
1
2020-10-25T18:59:03.000Z
2020-10-25T18:59:21.000Z
Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb
nomancseku/NSL-RA-Training
9a130a97ce0909cff93a77378f95e44c69a8bc7c
[ "MIT" ]
null
null
null
26.972846
1,054
0.536293
[ [ [ "## loading an image", "_____no_output_____" ] ], [ [ "from PIL import Image\nim = Image.open(\"lena.png\")", "_____no_output_____" ] ], [ [ "## examine the file contents", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nprint(im.format, im.size, im.mode)", "PNG (512, 512) RGB\n" ] ], [ [ "- The *format* attribute identifies the source of an image. If the image was not read from a file, it is set to None. \n- The *size* attribute is a 2-tuple containing width and height (in pixels). \n- The *mode* attribute defines the number and names of the bands in the image,", "_____no_output_____" ], [ "## let’s display the image we just loaded", "_____no_output_____" ] ], [ [ "im.show()", "_____no_output_____" ] ], [ [ "- The standard version of show() is not very efficient, since it saves the image to a temporary file and calls the xv utility to display the image. If you don’t have xv installed, it won’t even work. When it does work though, it is very handy for debugging and tests.", "_____no_output_____" ], [ "## Reading and writing images", "_____no_output_____" ], [ "- Python Imaging Library (PIL)\n- You don’t have to know the file format to open a file. The library automatically determines the format based on the contents of the file.\n- Unless you specify the format, the library uses the filename extension to discover which file storage format to use.", "_____no_output_____" ], [ "## Convert all image files to JPEG", "_____no_output_____" ] ], [ [ "## ------------ignore--------------\nfrom __future__ import print_function\nimport os, sys\nfrom PIL import Image\n\nfor infile in sys.argv[1:]:\n f, e = os.path.splitext(infile)\n outfile = f + \".jpg\"\n if infile != outfile:\n try:\n Image.open(infile).save(outfile)\n except IOError:\n print(\"cannot convert\", infile)", "cannot convert -f\ncannot convert C:\\Users\\Dell\\AppData\\Roaming\\jupyter\\runtime\\kernel-da0e4f10-19e7-4884-99e6-395f5c2cfaef.json\n" ], [ "from __future__ import print_function\nimport os, sys\nfrom PIL import Image\n\nfor infile in os.listdir(os.getcwd()):\n f, e = os.path.splitext(infile)\n print(f)\n print(e)\n outfile = f + \".jpg\"\n print(outfile)\n if infile != outfile:\n try:\n Image.open(infile).save(outfile)\n print('converted',infile,'to',outfile)\n except IOError:\n print(\"cannot convert\", infile)", ".ipynb_checkpoints\n\n.ipynb_checkpoints.jpg\ncannot convert .ipynb_checkpoints\nlena\n.jpg\nlena.jpg\nlena\n.png\nlena.jpg\nconverted lena.png to lena.jpg\nPython Imaging Library\n.ipynb\nPython Imaging Library.jpg\ncannot convert Python Imaging Library.ipynb\n" ] ], [ [ "## Create JPEG thumbnails", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nimport os, sys\nfrom PIL import Image\n\nsize = (128, 128)\n\nfor infile in os.listdir(os.getcwd()):\n outfile = os.path.splitext(infile)[0] + \".thumbnail\"\n print(infile, outfile)\n if infile != outfile:\n try:\n im = Image.open(infile)\n im.thumbnail(size)\n im.save(outfile, \"JPEG\")\n except IOError:\n print(\"cannot create thumbnail for\", infile)", ".ipynb_checkpoints .ipynb_checkpoints.thumbnail\ncannot create thumbnail for .ipynb_checkpoints\nlena.jpg lena.thumbnail\nlena.png lena.thumbnail\nPython Imaging Library.ipynb Python Imaging Library.thumbnail\ncannot create thumbnail for Python Imaging Library.ipynb\n" ], [ "print(os.path.splitext('how/are/you/a.png'))", "('how/are/you/a', '.png')\n" ] ], [ [ "- It is important to note that the library doesn’t decode or load the raster data unless it really has to. When you open a file, the file header is read to determine the file format and extract things like mode, size, and other properties required to decode the file, but the rest of the file is not processed until later.\n\n- This means that opening an image file is a fast operation, which is independent of the file size and compression type.", "_____no_output_____" ], [ "## Identify Image Files", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nimport sys\nfrom PIL import Image\n\nfor infile in os.listdir(os.getcwd()):\n #print(infile)\n try:\n with Image.open(infile) as im:\n print(infile, im.format, \"%dx%d\" % im.size, im.mode)\n print(type(im.size))\n except IOError:\n pass", "lena.jpg JPEG 512x512 RGB\n<class 'tuple'>\nlena.png PNG 512x512 RGB\n<class 'tuple'>\nlena.thumbnail JPEG 128x128 RGB\n<class 'tuple'>\n" ] ], [ [ "## Cutting, pasting, and merging images", "_____no_output_____" ], [ "- The Image class contains methods allowing you to manipulate regions within an image. To extract a sub-rectangle from an image, use the crop() method.", "_____no_output_____" ], [ "## Copying a subrectangle from an image", "_____no_output_____" ] ], [ [ "im = Image.open(\"lena.png\")\nbox = (100, 100, 400, 400)\nregion = im.crop(box)", "_____no_output_____" ] ], [ [ "- The region could now be processed in a certain manner and pasted back.", "_____no_output_____" ], [ "## Processing a subrectangle, and pasting it back", "_____no_output_____" ] ], [ [ "region = region.transpose(Image.ROTATE_180)\nim.paste(region, box)", "_____no_output_____" ], [ "im.show()", "_____no_output_____" ], [ "im.save('pasted.png')", "_____no_output_____" ] ], [ [ "## Rolling an image", "_____no_output_____" ] ], [ [ "def roll(image, delta):\n \"Roll an image sideways\"\n\n xsize, ysize = image.size #width and height\n\n delta = delta % xsize\n if delta == 0: return image\n\n part1 = image.crop((0, 0, delta, ysize))\n part2 = image.crop((delta, 0, xsize, ysize))\n image.paste(part2, (0, 0, xsize-delta, ysize))\n image.paste(part1, (xsize-delta, 0, xsize, ysize))\n\n return image", "_____no_output_____" ], [ "im = Image.open(\"lena.png\")\nprint(im.size)\nim.show(roll(im,10))", "(512, 512)\n" ] ], [ [ "## Splitting and merging bands", "_____no_output_____" ] ], [ [ "im = Image.open(\"lena.png\")\nr, g, b = im.split()\nim1 = Image.merge(\"RGB\", (b, g, r))\nim2 = Image.merge(\"RGB\", (r, r, r))\nim3 = Image.merge(\"RGB\", (g, g, g))\nim4 = Image.merge(\"RGB\", (b, b, b))\n\nim5 = Image.merge(\"RGB\", (g, r, b))", "_____no_output_____" ], [ "print(im1.mode)\n#im1.show()\n#im2.show()\n#im3.show()\n#im4.show()\n\nim5.show()", "RGB\n" ] ], [ [ "- Note that for a single-band image, split() returns the image itself. To work with individual color bands, you may want to convert the image to “RGB” first.", "_____no_output_____" ], [ "## Geometrical transforms", "_____no_output_____" ], [ "- The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple giving the new size, the latter the angle in degrees counter-clockwise.\n", "_____no_output_____" ], [ "## Simple geometry transforms", "_____no_output_____" ] ], [ [ "im = Image.open(\"lena.png\")\nout = im.resize((128, 128))\nout.show()\nout = im.rotate(45) # degrees counter-clockwise\nout.show()\nout.save('rotated.png')", "_____no_output_____" ] ], [ [ "- To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose() method. The latter can also be used to flip an image around its horizontal or vertical axis.", "_____no_output_____" ], [ "## Transposing an image", "_____no_output_____" ] ], [ [ "out = im.transpose(Image.FLIP_LEFT_RIGHT)\nout.save('transposing/l2r.png')\nout = im.transpose(Image.FLIP_TOP_BOTTOM)\nout.save('transposing/t2b.png')\nout = im.transpose(Image.ROTATE_90)\nout.save('transposing/90degree.png')\nout = im.transpose(Image.ROTATE_180)\nout.save('transposing/180degree.png')\nout = im.transpose(Image.ROTATE_270)\nout.save('transposing/270degree.png')", "_____no_output_____" ] ], [ [ "- There’s no difference in performance or result between **transpose(ROTATE)** and corresponding **rotate()** operations.", "_____no_output_____" ], [ "- A more general form of image transformations can be carried out via the transform() method.", "_____no_output_____" ], [ "## Color transforms", "_____no_output_____" ], [ "- The Python Imaging Library allows you to convert images between different pixel representations using the ***convert()*** method.", "_____no_output_____" ], [ "## Converting between modes", "_____no_output_____" ] ], [ [ "im = Image.open(\"lena.png\").convert(\"L\")\nim.show()", "_____no_output_____" ] ], [ [ "- The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).", "_____no_output_____" ], [ "## Image enhancement", "_____no_output_____" ], [ "## Applying filters", "_____no_output_____" ], [ "- The **ImageFilter** module contains a number of pre-defined enhancement filters that can be used with the **filter()** method.", "_____no_output_____" ], [ "from PIL import ImageFilter\n\nim = Image.open(\"lena.png\")\nim.show('im')\nim.save('filter/orig.png')\nout = im.filter(ImageFilter.DETAIL)\nout = out.filter(ImageFilter.DETAIL)\nout = out.filter(ImageFilter.DETAIL)\nout.show()\nout.save('filter/out.png')", "_____no_output_____" ], [ "## Point Operations", "_____no_output_____" ], [ "## Applying point transforms", "_____no_output_____" ] ], [ [ "# multiply each pixel by 1.2\nim = Image.open(\"lena.png\")\nim.save('point/orig.png')\nout = im.point(lambda i: i * 1.2)\nout.save('point/out.png')", "_____no_output_____" ] ], [ [ "- Using the above technique, you can quickly apply any simple expression to an image. You can also combine the point() and paste() methods to selectively modify an image:", "_____no_output_____" ], [ "## Processing individual bands", "_____no_output_____" ] ], [ [ "im = Image.open(\"lena.png\")\n# split the image into individual bands\nsource = im.split()\n\nR, G, B = 0, 1, 2\n\n# select regions where red is less than 100\nmask = source[R].point(lambda i: i < 100 and 255) # if i < 100 returns 255 else returns false(0)\n\n# process the green band\nout = source[G].point(lambda i: i * 0.7)\n\n\n# paste the processed band back, but only where red was < 100\nsource[G].paste(out, None, mask) # mask is just filtering here\n\n# build a new multiband image\nim = Image.merge(im.mode, source)\nim.show()\n\n# here we are reducing the green where red's intensity value is less than 100", "_____no_output_____" ] ], [ [ "- Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255.", "_____no_output_____" ], [ "## Enhancement", "_____no_output_____" ] ], [ [ "from PIL import Image\nfrom PIL import ImageEnhance\n\nim = Image.open(\"lena.png\")\n\nenh = ImageEnhance.Contrast(im)\nenh.enhance(1.3).show(\"30% more contrast\")", "_____no_output_____" ] ], [ [ "## Image sequences", "_____no_output_____" ], [ "## Reading sequences", "_____no_output_____" ] ], [ [ "from PIL import Image\nim = Image.open(\"animation.gif\")\nim.seek(1) # skip to the second frame\n\ntry:\n while 1:\n im.seek(im.tell()+1)\n im.show()\n # do something to im\nexcept EOFError as e:\n print(e)\n pass # end of sequence", "no more images in GIF file\n" ] ], [ [ "## A sequence iterator class", "_____no_output_____" ] ], [ [ "from PIL import Image\nim = Image.open(\"animation.gif\")\n\nclass ImageSequence:\n def __init__(self, im):\n self.im = im\n def __getitem__(self, ix):\n try:\n if ix:\n self.im.seek(ix)\n return self.im\n except EOFError:\n print('ddd')\n raise IndexError # end of sequence\n\nfor frame in ImageSequence(im):\n # ...do something to frame...\n frame.show()\n pass", "ddd\n" ] ], [ [ "## Postscript printing\n## Drawing Postscript", "_____no_output_____" ] ], [ [ "from PIL import Image\nfrom PIL import PSDraw\n\nim = Image.open(\"lena.png\")\ntitle = \"lena\"\nbox = (1*72, 2*72, 7*72, 10*72) # in points\n\nps = PSDraw.PSDraw() # default is sys.stdout\nps.begin_document(title)\n\n# draw the image (75 dpi)\nps.image(box, im, 75)\nps.rectangle(box)\n\n# draw title\nps.setfont(\"HelveticaNarrow-Bold\", 36)\nps.text((3*72, 4*72), title)\n\nps.end_document()", "%!PS-Adobe-3.0\nsave\n/showpage { } def\n%%EndComments\n%%BeginDocument\n/S { show } bind def\n/P { moveto show } bind def\n/M { moveto } bind def\n/X { 0 rmoveto } bind def\n/Y { 0 exch rmoveto } bind def\n/E { findfont\n dup maxlength dict begin\n {\n 1 index /FID ne { def } { pop pop } ifelse\n } forall\n /Encoding exch def\n dup /FontName exch def\n currentdict end definefont pop\n} bind def\n/F { findfont exch scalefont dup setfont\n [ exch /setfont cvx ] cvx bind def\n} bind def\n/Vm { moveto } bind def\n/Va { newpath arcn stroke } bind def\n/Vl { moveto lineto stroke } bind def\n/Vc { newpath 0 360 arc closepath } bind def\n/Vr { exch dup 0 rlineto\n exch dup neg 0 exch rlineto\n exch neg 0 rlineto\n 0 exch rlineto\n 100 div setgray fill 0 setgray } bind def\n/Tm matrix def\n/Ve { Tm currentmatrix pop\n translate scale newpath 0 0 .5 0 360 arc closepath\n Tm setmatrix\n} bind def\n/Vf { currentgray exch setgray fill setgray } bind def\n%%EndProlog\ngsave\n72.000000 216.000000 translate\n0.843750 0.843750 scale\ngsave\n10 dict begin\n/buf 1536 string def\n512 512 scale\n512 512 8\n[512 0 0 -512 0 512]\n{ currentfile buf readhexstring pop } bind\nfalse 3 colorimage\n\n%%%%EndBinary\ngrestore end\n\ngrestore\n72 144 M 504 720 0 Vr\n/PSDraw-HelveticaNarrow-Bold ISOLatin1Encoding /HelveticaNarrow-Bold E\n/F0 36 /PSDraw-HelveticaNarrow-Bold F\n216 288 M (lena) S\n%%EndDocument\nrestore showpage\n%%End\n" ] ], [ [ "## More on reading images", "_____no_output_____" ], [ "## Reading from an open file", "_____no_output_____" ] ], [ [ "fp = open(\"lena.png\", \"rb\")\nim = Image.open(fp)\nim.show()", "_____no_output_____" ] ], [ [ "## Reading from a string", "_____no_output_____" ] ], [ [ "!pip install StringIO\nimport StringIO\n\nim = Image.open(StringIO.StringIO(buffer))", "ERROR: Could not find a version that satisfies the requirement StringIO\nERROR: No matching distribution found for StringIO\n" ] ], [ [ "## Reading from a tar archive", "_____no_output_____" ] ], [ [ "from PIL import TarIO\n\nfp = TarIO.TarIO(\"Imaging.tar\", \"lena.png\")\nim = Image.open(fp)", "_____no_output_____" ] ], [ [ "## Controlling the decoder", "_____no_output_____" ], [ "## Reading in draft mode", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nfrom PIL import Image\n\nim = Image.open('lena.png')\nprint(\"original =\", im.mode, im.size)\n\nim.draft(\"L\", (100, 100))\nprint(\"draft =\", im.mode, im.size)\n", "original = RGB (512, 512)\ndraft = RGB (512, 512)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb0d6dae0268195dff407883e09d33903f259d72
26,349
ipynb
Jupyter Notebook
Extra/Buenrostro_2018/test_peaks/Control/run_clustering_frequency.ipynb
tAndreani/scATAC-benchmarking
0b7167490aff986738985cdba688b48d4ed9988f
[ "MIT" ]
2
2019-10-28T09:27:51.000Z
2019-11-25T18:03:04.000Z
Extra/Buenrostro_2018/test_peaks/Control/run_clustering_frequency.ipynb
huidongchen/scATAC-benchmarking
31d71d60536e8f4bf5bae314630013feaff3caf2
[ "MIT" ]
null
null
null
Extra/Buenrostro_2018/test_peaks/Control/run_clustering_frequency.ipynb
huidongchen/scATAC-benchmarking
31d71d60536e8f4bf5bae314630013feaff3caf2
[ "MIT" ]
null
null
null
33.99871
312
0.518464
[ [ [ "import pandas as pd\nimport numpy as np\nimport scanpy as sc\nimport os\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.metrics.cluster import adjusted_rand_score\nfrom sklearn.metrics.cluster import adjusted_mutual_info_score\nfrom sklearn.metrics.cluster import homogeneity_score\nimport rpy2.robjects as robjects\nfrom rpy2.robjects import pandas2ri", "_____no_output_____" ], [ "df_metrics = pd.DataFrame(columns=['ARI_Louvain','ARI_kmeans','ARI_HC',\n 'AMI_Louvain','AMI_kmeans','AMI_HC',\n 'Homogeneity_Louvain','Homogeneity_kmeans','Homogeneity_HC'])", "_____no_output_____" ], [ "workdir = './peaks_frequency_results/'\npath_fm = os.path.join(workdir,'feature_matrices/')\npath_clusters = os.path.join(workdir,'clusters/')\npath_metrics = os.path.join(workdir,'metrics/')\nos.system('mkdir -p '+path_clusters)\nos.system('mkdir -p '+path_metrics)", "_____no_output_____" ], [ "metadata = pd.read_csv('../../input/metadata.tsv',sep='\\t',index_col=0)\nnum_clusters = len(np.unique(metadata['label']))\nprint(num_clusters)", "10\n" ], [ "files = [x for x in os.listdir(path_fm) if x.startswith('FM')]\nlen(files)", "_____no_output_____" ], [ "files", "_____no_output_____" ], [ "def getNClusters(adata,n_cluster,range_min=0,range_max=3,max_steps=20):\n this_step = 0\n this_min = float(range_min)\n this_max = float(range_max)\n while this_step < max_steps:\n print('step ' + str(this_step))\n this_resolution = this_min + ((this_max-this_min)/2)\n sc.tl.louvain(adata,resolution=this_resolution)\n this_clusters = adata.obs['louvain'].nunique()\n \n print('got ' + str(this_clusters) + ' at resolution ' + str(this_resolution))\n \n if this_clusters > n_cluster:\n this_max = this_resolution\n elif this_clusters < n_cluster:\n this_min = this_resolution\n else:\n return(this_resolution, adata)\n this_step += 1\n \n print('Cannot find the number of clusters')\n print('Clustering solution from last iteration is used:' + str(this_clusters) + ' at resolution ' + str(this_resolution))", "_____no_output_____" ], [ "for file in files:\n file_split = file[:-4].split('_')\n method = file_split[1]\n print(method)\n\n pandas2ri.activate()\n readRDS = robjects.r['readRDS']\n df_rds = readRDS(os.path.join(path_fm,file))\n fm_mat = pandas2ri.ri2py(robjects.r['data.frame'](robjects.r['as.matrix'](df_rds)))\n fm_mat.fillna(0,inplace=True)\n fm_mat.columns = metadata.index\n \n adata = sc.AnnData(fm_mat.T)\n adata.var_names_make_unique()\n adata.obs = metadata.loc[adata.obs.index,]\n df_metrics.loc[method,] = \"\"\n #Louvain\n sc.pp.neighbors(adata, n_neighbors=15,use_rep='X')\n# sc.tl.louvain(adata)\n getNClusters(adata,n_cluster=num_clusters)\n #kmeans\n kmeans = KMeans(n_clusters=num_clusters, random_state=2019).fit(adata.X)\n adata.obs['kmeans'] = pd.Series(kmeans.labels_,index=adata.obs.index).astype('category')\n #hierachical clustering\n hc = AgglomerativeClustering(n_clusters=num_clusters).fit(adata.X)\n adata.obs['hc'] = pd.Series(hc.labels_,index=adata.obs.index).astype('category')\n #clustering metrics\n \n #adjusted rank index\n ari_louvain = adjusted_rand_score(adata.obs['label'], adata.obs['louvain'])\n ari_kmeans = adjusted_rand_score(adata.obs['label'], adata.obs['kmeans'])\n ari_hc = adjusted_rand_score(adata.obs['label'], adata.obs['hc'])\n #adjusted mutual information\n ami_louvain = adjusted_mutual_info_score(adata.obs['label'], adata.obs['louvain'],average_method='arithmetic')\n ami_kmeans = adjusted_mutual_info_score(adata.obs['label'], adata.obs['kmeans'],average_method='arithmetic') \n ami_hc = adjusted_mutual_info_score(adata.obs['label'], adata.obs['hc'],average_method='arithmetic')\n #homogeneity\n homo_louvain = homogeneity_score(adata.obs['label'], adata.obs['louvain'])\n homo_kmeans = homogeneity_score(adata.obs['label'], adata.obs['kmeans'])\n homo_hc = homogeneity_score(adata.obs['label'], adata.obs['hc'])\n\n df_metrics.loc[method,['ARI_Louvain','ARI_kmeans','ARI_HC']] = [ari_louvain,ari_kmeans,ari_hc]\n df_metrics.loc[method,['AMI_Louvain','AMI_kmeans','AMI_HC']] = [ami_louvain,ami_kmeans,ami_hc]\n df_metrics.loc[method,['Homogeneity_Louvain','Homogeneity_kmeans','Homogeneity_HC']] = [homo_louvain,homo_kmeans,homo_hc] \n adata.obs[['louvain','kmeans','hc']].to_csv(os.path.join(path_clusters ,method + '_clusters.tsv'),sep='\\t')", "control1\n" ], [ "df_metrics.to_csv(path_metrics+'clustering_scores.csv')", "_____no_output_____" ], [ "df_metrics", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0d7055ae29c04ccc5c31276e34c7891aae9210
4,355
ipynb
Jupyter Notebook
notebooks/basic_motion.ipynb
rezaarrazi/jetracer
81c2c93d5bb4fda285e82cd8aa15e2889db0fdae
[ "MIT" ]
868
2019-06-29T12:07:33.000Z
2022-03-31T09:57:56.000Z
notebooks/basic_motion.ipynb
rezaarrazi/jetracer
81c2c93d5bb4fda285e82cd8aa15e2889db0fdae
[ "MIT" ]
112
2019-06-29T13:22:27.000Z
2022-03-10T02:55:14.000Z
notebooks/basic_motion.ipynb
rezaarrazi/jetracer
81c2c93d5bb4fda285e82cd8aa15e2889db0fdae
[ "MIT" ]
257
2019-06-30T00:05:33.000Z
2022-03-31T09:52:25.000Z
23.797814
215
0.554994
[ [ [ "Execute the following block of code by selecting it and clicking ``ctrl + enter`` to create an ``NvidiaRacecar`` class. ", "_____no_output_____" ] ], [ [ "from jetracer.nvidia_racecar import NvidiaRacecar\n\ncar = NvidiaRacecar()", "_____no_output_____" ] ], [ [ "The ``NvidiaRacecar`` implements the ``Racecar`` class, so it has two attributes ``throttle`` and ``steering``. \n\nWe can assign values in the range ``[-1, 1]`` to these attributes. Execute the following to set the steering to 0.4.\n\n> If the car does not respond, it may still be in ``manual`` mode. Flip the manual override switch on the RC transmitter.", "_____no_output_____" ] ], [ [ "car.steering = 0.3", "_____no_output_____" ] ], [ [ "The ``NvidiaRacecar`` class has two values ``steering_gain`` and ``steering_bias`` that can be used to calibrate the steering.\n\nWe can view the default values by executing the cells below.", "_____no_output_____" ] ], [ [ "print(car.steering_gain)", "_____no_output_____" ], [ "print(car.steering_offset)", "_____no_output_____" ] ], [ [ "The final steering value is computed using the equation\n\n$y = a \\times x + b$\n\nWhere,\n\n* $a$ is ``car.steering_gain``\n* $b$ is ``car.steering_offset``\n* $x$ is ``car.steering``\n* $y$ is the value written to the motor driver\n\nYou can adjust these values calibrate the car so that setting a value of ``0`` moves forward, and setting a value of ``1`` goes fully right, and ``-1`` fully left.", "_____no_output_____" ], [ "To set the throttle of the car to ``0.2``, you can call the following.\n\n> Give JetRacer lots of space to move, and be ready on the manual override, JetRacer is *fast*", "_____no_output_____" ] ], [ [ "car.throttle = 0.0", "_____no_output_____" ] ], [ [ "The throttle also has a gain value that could be used to control the speed response. The throttle output is computed as\n\n$y = a \\times x$\n\nWhere,\n\n* $a$ is ``car.throttle_gain``\n* $x$ is ``car.throttle``\n* $y$ is the value written to the speed controller\n\nExecute the following to print the default gain", "_____no_output_____" ] ], [ [ "print(car.throttle_gain)", "_____no_output_____" ] ], [ [ "Set the following to limit the throttle to half", "_____no_output_____" ] ], [ [ "car.throttle_gain = 0.5", "_____no_output_____" ] ], [ [ "Please note the throttle is directly mapped to the RC car. When the car is stopped and a negative throttle is set, it will reverse. If the car is moving forward and a negative throttle is set, it will brake.", "_____no_output_____" ], [ "That's it for this notebook!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb0d78ee5d068e05ab62aa47b22171cb3fe997da
3,386
ipynb
Jupyter Notebook
moltres-thermal-fluids/verification/notes.ipynb
arfc/mhtgr350-benchmark
18f7b3fe5742dabb1114c3bf7760b84590d16062
[ "BSD-3-Clause" ]
1
2021-07-24T16:20:34.000Z
2021-07-24T16:20:34.000Z
moltres-thermal-fluids/verification/notes.ipynb
arfc/mhtgr350-benchmark
18f7b3fe5742dabb1114c3bf7760b84590d16062
[ "BSD-3-Clause" ]
51
2020-05-26T16:17:57.000Z
2021-02-22T20:08:59.000Z
moltres-thermal-fluids/verification/notes.ipynb
robfairh/mhtgr350-benchmark
a99d440bef498d781a1a4a193b876fc1611d1d03
[ "BSD-3-Clause" ]
2
2020-01-02T19:22:59.000Z
2020-01-11T15:42:36.000Z
20.39759
53
0.438275
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "# Verification: 2D-preliminar", "_____no_output_____" ] ], [ [ "# calculate geometry\nrf = 1.27/2 - 0.0125 # cm\nrg = 1.27/2 # cm\nrc = 1.59/2 # cm\nrm = 1.885 - rc # cm\nrg2 = rm - 0.01;\nrc2 = np.sqrt(rc**2 + rm**2)\nrc2", "_____no_output_____" ], [ "# coolant flow and film thermal conductivity\nrho = 4.94e-6 # kg/cm3\ncp = 5.188e3 # J/kg/K\nmlc = 0.0176 # kg/s\nv = mlc/rho/np.pi/rc**2\nprint('v: ', v, 'cm/s')\n\nmu = 35.03e-6 # Pa.s 7 MPa 400 C\nrho *= 1e6 # kg/m3\nv /= 100 # m/s\nD = 2 * rc / 100 # m\nRe = rho * v * D / mu\n# print('Re: ', Re)\n\nkc = 0.3 # W/m/K\nPr = mu * cp/kc\n# print('Pr: ', Pr)\n\nNu = 0.023*(Re**0.8)*(Pr**0.4)\n# print('Nu: ', Nu)\nh = Nu/D * kc # W/m^2/K\n# print('h: ', h)\n\nh /= 1e4 # W/cm^2/K\nkgc = h * rm * np.log(rm/rg2)\nprint('kgc: ', np.round(kgc, 6), 'W/cm/C')", "v: 1794.3269863206274 cm/s\nkgc: 0.001722 W/cm/C\n" ], [ "# heat generated: q * L = q0 * 2/pi * L\nq = 35 # W/cm3\nq0 = q * np.pi/2\nprint('peak power density: ', q0)", "peak power density: 54.97787143782138\n" ], [ "# coolant outlet analytical temperature:\nrho = 4.94e-6 # kg/cm3\ncp = 5.188e3 # J/kg/K\nmlc = 0.0176 # kg/s\nrc = 1.59/2 # cm\nv = 1794.33\n\nTi = 400\nL = 793\nrf = 1.27/2 - 0.0125 # cm\n\nqf = q0 * 2/np.pi * np.pi * rf**2 * L\nTo = Ti + 1/rho/cp/v * qf /np.pi/rc**2\nTo", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cb0d7fbc657652f546adebaf065b909c516c9cf6
969,322
ipynb
Jupyter Notebook
TEMA-3/Clase23_ValuacionOpciones.ipynb
duarteandres/SPF-2020-II-G1
81dcbfa924951ad9e7561457f31f9ba0e007937a
[ "MIT" ]
null
null
null
TEMA-3/Clase23_ValuacionOpciones.ipynb
duarteandres/SPF-2020-II-G1
81dcbfa924951ad9e7561457f31f9ba0e007937a
[ "MIT" ]
null
null
null
TEMA-3/Clase23_ValuacionOpciones.ipynb
duarteandres/SPF-2020-II-G1
81dcbfa924951ad9e7561457f31f9ba0e007937a
[ "MIT" ]
null
null
null
236.535383
160,220
0.896349
[ [ [ "<img style=\"float: right; margin: 0px 0px 15px 15px;\" src=\"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQt6eQo8JPYzYO4p6WmxLtccdtJ4X8WR6GzVVKbsMjyGvUDEn1mg\" width=\"300px\" height=\"100px\" />\n\n# Trabajando con opciones", "_____no_output_____" ], [ "Una opción puede negociarse en el mercado secundario por lo que es importante determinar su valor $V_t$ para cada tiempo $t\\in [0, T]$. La ganancia que obtiene quién adquiere la opción se llama función de pago o \"payoff\" y claramente depende del valor del subyacente. \n\nHay una gran variedad de opciones en el mercado y éstas se clasiflcan según su función de pago y la forma en que pueden ejercerse. Las opciones que tienen como función de pago a\n$$ P(S(t),t)=max\\{S(T)-K,0\\} \\rightarrow \\text{En el caso de Call}$$ \n$$ P(S(t),t)=max\\{K-S(T),0\\} \\rightarrow \\text{En el caso de Put}$$ \nse llaman opciones **Vainilla**, con $h:[0,\\infty) \\to [0,\\infty)$.\n\nLa opción se llama **europea** si puede ejercerse sólo en la fecha de vencimiento.\n\nSe dice que una opción es **americana** si puede ejercerse en cualquier momento antes o en la fecha de vencimiento.\n\nUna opción compleja popular son las llamadas **opciones asiáticas** cuyos pagos dependen de todas las trayectorias del precio de los activos subyacentes. Las opciones cuyos pagos dependen de las trayectorias de los precios de los activos subyacentes se denominan opciones dependientes de la ruta.\n\nPrincipalmente, se puede resumir que las dos razones con más peso de importancia para utilizar opciones son el **aseguramiento** y la **especulación**.\n\n## Opciones Plan Vainilla: opción de compra y opción de venta europea\n\nUna opción vainilla o estándar es una opción normal de compra o venta que no tiene características especiales o inusuales. Puede ser para tamaños y vencimientos estandarizados, y negociarse en un intercambio.\nEn comparación con otras estructuras de opciones, las opciones de vanilla no son sofisticadas o complicadas.\n", "_____no_output_____" ], [ "## 1. ¿Cómo descargar datos de opciones?", "_____no_output_____" ] ], [ [ "#importar los paquetes que se van a usar\nimport pandas as pd\nimport pandas_datareader.data as web\nimport numpy as np\nimport datetime\nimport matplotlib.pyplot as plt\nimport scipy.stats as st\nimport seaborn as sns\n%matplotlib inline\n#algunas opciones para Pandas\npd.set_option('display.notebook_repr_html', True)\npd.set_option('display.max_columns', 6)\npd.set_option('display.max_rows', 10)\npd.set_option('display.width', 78)\npd.set_option('precision', 3)", "_____no_output_____" ] ], [ [ "Usando el paquete `pandas_datareader` también podemos descargar datos de opciones. Por ejemplo, descarguemos los datos de las opciones cuyo activo subyacente son las acciones de Apple", "_____no_output_____" ] ], [ [ "aapl = web.YahooOptions('AAPL')\naapl_opt = aapl.get_all_data().reset_index()\naapl_opt.set_index('Expiry')\n# aapl", "_____no_output_____" ] ], [ [ "Precio del activo subyacente", "_____no_output_____" ] ], [ [ "aapl_opt.Underlying_Price[0]", "_____no_output_____" ] ], [ [ "Datos de la opción ", "_____no_output_____" ] ], [ [ "aapl_opt.loc[0, 'JSON']", "_____no_output_____" ] ], [ [ "### Conceptos claves\n- El precio de la oferta ('bid') se refiere al precio más alto que un comprador pagará por un activo.\n- El precio de venta ('ask') se refiere al precio más bajo que un vendedor aceptará por un activo.\n- La diferencia entre estos dos precios se conoce como 'spread'; cuanto menor es el spread, mayor es la liquidez de la garantía dada.\n- Liquidez: facilidad de convertir cierta opción en efectivo.\n- La volatilidad implícita es el pronóstico del mercado de un probable movimiento en el precio de un valor.\n- La volatilidad implícita aumenta en los mercados bajistas y disminuye cuando el mercado es alcista.\n- El último precio ('lastprice') representa el precio al que ocurrió la última operación, de una opción dada.", "_____no_output_____" ], [ "Una vez tenemos la información, podemos consultar de qué tipo son las opciones", "_____no_output_____" ] ], [ [ "aapl_opt.loc[:, 'Type']", "_____no_output_____" ] ], [ [ "o en que fecha expiran", "_____no_output_____" ] ], [ [ "pd.set_option('display.max_rows', 10)\naapl_opt.loc[:, 'Expiry']", "_____no_output_____" ] ], [ [ "Por otra parte, podríamos querer consultar todas las opciones de compra (call) que expiran en cierta fecha (2020-06-19)", "_____no_output_____" ] ], [ [ "fecha1 = '2021-06-18'\nfecha2 = '2022-09-16'\ncall06_f1 = aapl_opt.loc[(aapl_opt.Expiry== fecha1) & (aapl_opt.Type=='call')]\ncall06_f2 = aapl_opt.loc[(aapl_opt.Expiry== fecha2) & (aapl_opt.Type=='call')]\ncall06_f1\n", "_____no_output_____" ] ], [ [ "## 2. ¿Qué es la volatilidad implícita?", "_____no_output_____" ], [ "**Volatilidad:** desviación estándar de los rendimientos.\n- ¿Cómo se calcula?\n- ¿Para qué calcular la volatilidad?", "_____no_output_____" ], [ "- **Para valuar derivados**, por ejemplo **opciones**.\n- Método de valuación de riesgo neutral (se supone que el precio del activo $S_t$ no se ve afectado por el riesgo de mercado).\n\nRecorderis de cuantitativas:\n1. Ecuación de Black-Scholes\n$$ dS(t) = \\mu S(t) + \\sigma S(t)dW_t$$\n2. Solución de la ecuación\n\nEl valor de una opción Europea de vainilla $V_t$ puede obtenerse por:\n$$V_t = F(t,S_t)$$ donde\n![imagen.png](attachment:imagen.png)\n3. Opción de compra europea, suponiendo que los precios del activo son lognormales\n4. Opción de venta europea, suponiendo que los precios del activo son lognormales", "_____no_output_____" ], [ "Entonces, ¿qué es la **volatilidad implícita**?\n\nLa volatilidad es una medida de la incertidumbre sobre el comportamiento futuro de un activo, que se mide habitualmente como la desviación típica de la rentabilidad de dicho activo. \n\nUna volatilidad implícita es aquella que cuando se sustituye en la ecuación de Black-Scholes o en sus ampliaciones,proporciona el precio de mercado de la opción.", "_____no_output_____" ], [ "## Volatility smile \n- Cuando las opciones con la misma fecha de vencimiento y el mismo activo subyacente, pero diferentes precios de ejercicio, se grafican por la volatilidad implícita, la tendencia es que ese gráfico muestre una sonrisa.\n- La sonrisa muestra que las opciones más alejadas 'in- or out-of-the-money' tienen la mayor volatilidad implícita.\n- No todas las opciones tendrán una sonrisa de volatilidad implícita. Las opciones de acciones a corto plazo y las opciones relacionadas con la moneda tienen más probabilidades de tener una sonrisa de volatilidad\n\n![imagen.png](attachment:imagen.png)\n\n> Fuente: https://www.investopedia.com/terms/v/volatilitysmile.asp", "_____no_output_____" ], [ "> ### Validar para la `fecha = 2020-06-19` y para la fecha `fecha = '2021-01-15'`", "_____no_output_____" ] ], [ [ "# para los call de la fecha 1\nax = call06_f1.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6))\nax.axvline(call06_f1.Underlying_Price.iloc[0], color='g');", "_____no_output_____" ], [ "# para los call de la fecha 2\nax = call06_f2.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6))\nax.axvline(call06_f2.Underlying_Price.iloc[0], color='g');", "_____no_output_____" ] ], [ [ "Analicemos ahora datos de los `put`", "_____no_output_____" ] ], [ [ "put06_f1 = aapl_opt.loc[(aapl_opt.Expiry==fecha1) & (aapl_opt.Type=='put')]\nput06_f1", "_____no_output_____" ] ], [ [ "Para los `put` de la `fecha 1`", "_____no_output_____" ] ], [ [ "ax = put06_f1.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6))\nax.axvline(put06_f1.Underlying_Price.iloc[0], color='g')", "_____no_output_____" ] ], [ [ "Con lo que hemos aprendido, deberíamos ser capaces de crear una función que nos devuelva un `DataFrame` de `pandas` con los precios de cierre ajustados de ciertas compañías en ciertas fechas:\n- Escribir la función a continuación", "_____no_output_____" ] ], [ [ "# Función para descargar precios de cierre ajustados:\ndef get_adj_closes(tickers, start_date=None, end_date=None):\n # Fecha inicio por defecto (start_date='2010-01-01') y fecha fin por defecto (end_date=today)\n # Descargamos DataFrame con todos los datos\n closes = web.DataReader(name=tickers, data_source='yahoo', start=start_date, end=end_date)\n # Solo necesitamos los precios ajustados en el cierre\n closes = closes['Adj Close']\n # Se ordenan los índices de manera ascendente\n closes.sort_index(inplace=True)\n return closes", "_____no_output_____" ] ], [ [ "- Obtener como ejemplo los precios de cierre de Apple del año pasado hasta la fecha. Graficar...", "_____no_output_____" ] ], [ [ "ticker = ['AAPL']\nstart_date = '2017-01-01'\n\ncloses_aapl = get_adj_closes(ticker, start_date)\ncloses_aapl.plot(figsize=(8,5));\nplt.legend(ticker);", "_____no_output_____" ] ], [ [ "- Escribir una función que pasándole el histórico de precios devuelva los rendimientos logarítmicos:", "_____no_output_____" ] ], [ [ "def calc_daily_ret(closes):\n return np.log(closes/closes.shift(1)).iloc[1:]", "_____no_output_____" ] ], [ [ "- Graficar...", "_____no_output_____" ] ], [ [ "ret_aapl = calc_daily_ret(closes_aapl)\nret_aapl.plot(figsize=(8,6));", "_____no_output_____" ] ], [ [ "También, descargar datos de opciones de Apple:", "_____no_output_____" ] ], [ [ "aapl = web.YahooOptions('AAPL')\naapl_opt = aapl.get_all_data().reset_index()\naapl_opt.set_index('Expiry').sort_index()", "_____no_output_____" ], [ "K = 110 # strike price\nindice_opt = aapl_opt.loc[(aapl_opt.Type=='call') & (aapl_opt.Strike==K) & (aapl_opt.Expiry=='2021-01-15')]\nindice_opt", "_____no_output_____" ], [ "i_opt= indice_opt.index\nopcion_valuar = aapl_opt.loc[i_opt[0]]\nopcion_valuar['JSON']", "_____no_output_____" ], [ "print('Precio del activo subyacente actual = ',opcion_valuar.Underlying_Price)", "Precio del activo subyacente actual = 115.17\n" ] ], [ [ "# Simulación de precios usando rendimiento simple y logarítmico ", "_____no_output_____" ], [ "![image.png](attachment:image.png)", "_____no_output_____" ], [ "![image.png](attachment:image.png)", "_____no_output_____" ], [ "![image.png](attachment:image.png)", "_____no_output_____" ], [ "* Comenzaremos por suponer que los rendimientos son un p.e. estacionario que distribuyen $\\mathcal{N}(\\mu,\\sigma)$.", "_____no_output_____" ], [ "## Rendimiento Simple", "_____no_output_____" ] ], [ [ "# Obtenemos el rendimiento simple\nRi = closes_aapl.pct_change(1).iloc[1:]\n# Obtenemos su media y desviación estándar de los rendimientos\nmu_R = Ri.mean()[0]\nsigma_R = Ri.std()[0]\nRi", "_____no_output_____" ], [ "opcion_valuar.Expiry", "_____no_output_____" ], [ "from datetime import date\n\n# Encontrar la fecha de hoy en formato timestamp\ntoday = pd.Timestamp(date.today())\n\n# Obtener fecha de cierre de la opción a valuar\nexpiry = opcion_valuar.Expiry\n\nnscen = 10000\n\n# Generar rangos de fechas de días hábiles\ndates = pd.date_range(start=today, end=expiry, freq='B')\nndays = len(dates)\n", "_____no_output_____" ] ], [ [ "## Mostrar como simular precios usando los rendimientos\n\n### 1. Usando rendimiento simple", "_____no_output_____" ] ], [ [ "# Simular los rendimientos\n\n# Rendimiento diario \ndt = 1\n# Z ~ N(0,1) normal estándar (ndays, nscen)\nZ = np.random.randn(ndays, nscen)\n\n# Simulación normal de los rendimientos\nRi_dt = pd.DataFrame(mu_R * dt + Z * sigma_R * np.sqrt(dt), index=dates)\n", "_____no_output_____" ], [ "# Simulación del precio\nS_0 = closes_aapl.iloc[-1,0]\nS_T = S_0*(1+Ri_dt).cumprod()\n\n# Se muestran los precios simulados con los precios descargados\npd.concat([closes_aapl, S_T.iloc[:, :10]]).plot(figsize=(8,6));\nplt.title('Simulación de precios usando rendimiento simple');", "_____no_output_____" ] ], [ [ "### 2. Rendimiento Logarítmico", "_____no_output_____" ] ], [ [ "# Calcular rendimiento logarítmico\nri = calc_daily_ret(closes_aapl)\n\n# Usando la media y desviación estándar de los rendimientos logarítmicos\nmu_r = ri.mean()[0]\nsigma_r = ri.std()[0]\n\n# Simulación del rendimiento\nZ = np.random.randn(ndays, nscen)\nsim_ret_ri = pd.DataFrame(mu_r * dt + Z * sigma_r * np.sqrt(dt), index=dates )\n\n# Simulación del precio\nS_0 = closes_aapl.iloc[-1,0]\nS_T2 = S_0*np.exp(sim_ret_ri.cumsum())\n\n# Se muestran los precios simulados con los precios descargados\n# pd.concat([closes_aapl,S_T2]).plot(figsize=(8,6));\n# plt.title('Simulación de precios usando rendimiento logarítmico');\n\n# from sklearn.metrics import mean_absolute_error\ne1 = np.abs(S_T-S_T2).mean().mean()\ne1", "_____no_output_____" ], [ "print('Las std usando rendimientos logarítmicos y simples son similares')\nsigma_R,sigma_r", "Las std usando rendimientos logarítmicos y simples son similares\n" ] ], [ [ "Con los precios simulados debemos de encontrar el valor de la opción según la función de pago correspondiente. Para este caso es:\n$$\nmax(S_T - K,0)\n$$", "_____no_output_____" ] ], [ [ "opcion_valuar['JSON']", "_____no_output_____" ] ], [ [ "## Valuación usando el modelo de Black and Scholes\nLos supuestos que hicieron Black y Scholes cuando dedujeron su fórmula para la valoración de opciones fueron los siguientes:\n1. El comportamiento del precio de la acción corresponde al modelo logarítmico normal, con $\\mu$ y $\\sigma$\nconstantes.\n2. No hay costos de transición ni impuestos. Todos los títulos son perfectamente divisibles.\n3. No hay dividendos sobre la acción durante la vida de la opción.\n4. No hay oportunidades de arbitraje libres de riesgo.\n5. La negociación de valores es continua.\n6. Los inversionistas pueden adquirir u otorgar préstamos a la misma tasa de interés libre de riesgo.\n7. La tasa de interés libre de riesgo a corto plazo, r, es constante.\n\nBajo los supuestos anteriores podemos presentar las **fórmulas de Black-Scholes** para calcular los precios de compra y de venta europeas sobre acciones que no pagan dividendos:\n$$\n\\text{Valor actual de la opción} = V(S_0, T) = S_0 N(d_1) - K e^{-r*T} N(d_2)\n$$\n\ndonde:\n- $S_0$ = precio de la acción en el momento actual.\n- $K$ = precio \"de ejercicio\" de la opción.\n- $r$ = tasa de interés libre de riesgo.\n- $T$ = tiempo que le resta de vida a la opción.\n- $N(d)$ = función de distribución de la variable aleatoria normal con media nula y desviación típica unitaria\n(probabilidad de que dicha variable sea menor o igual que d). Función de distribución de probabilidad acumulada.\n- $\\sigma$ = varianza por período de la tasa o tipo de rendimiento de la opción.\n\n$$\nd_1 = \\frac{\\ln{\\frac{S_0}{K}} + (r + \\sigma^2 / 2) T}{\\sigma \\sqrt{T}}, \\quad d_2 = \\frac{\\ln{\\frac{S_0}{K}} + (r - \\sigma^2 / 2) T}{\\sigma \\sqrt{T}} \n$$\n\n**Nota**: observe que el __rendimiento esperado__ sobre la acción no se incluye en la ecuación de Black-Scholes. Hay un principio general conocido como valoración neutral al riesgo, el cual establece que cualquier título que depende de otros títulos negociados puede valorarse bajo el supuesto de que el mundo es neutral al riesgo. El resultado demuestra ser muy útil en la práctica. *En un mundo neutral al riesgo, el rendimiento esperado de todos los títulos es la tasa de interés libre de riesgo*, y la tasa de descuento correcta para los flujos de efectivo esperados también es la tasa de interés libre de riesgo.\n\nEl equivalente a la función de Black-Scholes (valuación de la opción) se puede demostrar que es:\n$$\n\\text{Valor actual de la opción} = V(S_0, T) = E^*(e^{-rT} f(S_T)) = e^{-rT} E^*(f(S_T))\n$$\n\ndonde \n$f(S_T)$ representa la función de pago de la opción, que para el caso de un call europeo sería $f(S_T) = \\max({S_T - K})$.\n\n> Referencia: http://diposit.ub.edu/dspace/bitstream/2445/32883/1/Benito_el_modelo_de_Black_Sholes.pdf (página 20)\n\n> Referencia 2: http://www.cmat.edu.uy/~mordecki/courses/upae/upae-curso.pdf (página 24)", "_____no_output_____" ], [ "- Hallar media y desviación estándar muestral de los rendimientos logarítmicos", "_____no_output_____" ] ], [ [ "mu = ret_aapl.mean()[0]\nsigma = ret_aapl.std()[0]\nmu, sigma", "_____no_output_____" ] ], [ [ "No se toma la media sino la tasa libre de riesgo\n> Referencia: https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield", "_____no_output_____" ] ], [ [ "# Tasa de bonos de 1 yr de fecha 11/24/20 -> 0.11%\nr = 0.0011/360 # Tasa diaria", "_____no_output_____" ] ], [ [ "- Simularemos el tiempo de contrato desde `HOY` hasta la fecha de `Expiry`, 10 escenarios:\n \n - Generar fechas", "_____no_output_____" ] ], [ [ "from datetime import date\n\ntoday = pd.Timestamp(date.today())\nexpiry = opcion_valuar.Expiry\n\nnscen = 10\ndates = pd.date_range(start=today, periods = ndays)\nndays = len(dates)\n", "_____no_output_____" ] ], [ [ "- Generamos 10 escenarios de rendimientos simulados y guardamos en un dataframe", "_____no_output_____" ] ], [ [ "sim_ret = pd.DataFrame(sigma*np.random.randn(ndays,nscen)+r, index=dates)\nsim_ret.cumsum()\n# Las columnas son los escenarios y las filas son las días de contrato", "_____no_output_____" ] ], [ [ "- Con los rendimientos simulados, calcular los escenarios de precios respectivos:", "_____no_output_____" ] ], [ [ "S0 = closes_aapl.iloc[-1,0] # Condición inicial del precio a simular\nsim_closes = S0*np.exp(sim_ret.cumsum())\nsim_closes", "_____no_output_____" ] ], [ [ "- Graficar:", "_____no_output_____" ] ], [ [ "sim_closes.plot(figsize=(8,6));", "_____no_output_____" ], [ "# Se muestran los precios simulados con los precios descargados\npd.concat([closes_aapl,sim_closes]).plot(figsize=(8,6));", "_____no_output_____" ], [ "K = opcion_valuar.Strike\ncall = np.exp(-r*ndays) * np.fmax(S_T - K, 0).mean(axis=1)\ncall", "_____no_output_____" ], [ "opcion_valuar['JSON']", "_____no_output_____" ], [ "# sigma = 0.3064034204101562/np.sqrt(252)\n# sigma", "_____no_output_____" ], [ "from datetime import date\nHoy = date.today()\n\n# strike price\nK = opcion_valuar['JSON']['strike'] \n\n# Fechas a simular\ndates = pd.date_range(start= Hoy, periods = ndays, freq='B')\n\n# Escenarios y número de días\nndays = len(dates)\nnscen = 100000\n\n# Condición inicial del precio a simular\nS0 = closes_aapl.iloc[-1,0] \n\n# simular rendimientos\nsim_ret = pd.DataFrame(sigma*np.random.randn(ndays,nscen)+r,index=dates)\n\n# Simular precios\nsim_closes = S0*np.exp(sim_ret.cumsum())\n", "_____no_output_____" ], [ "# Frame con el valor del strike\nstrike = pd.DataFrame(K*np.ones([ndays,nscen]), index=dates)\n\n# Valor del call europeo\ncall = pd.DataFrame({'Prima':np.exp(-r*ndays) \\\n *np.fmax(sim_closes-K, 0).mean(axis=1)}, index=dates)\ncall.plot();\n", "_____no_output_____" ] ], [ [ "La valuación de la opción es:", "_____no_output_____" ] ], [ [ "call.iloc[-1]", "_____no_output_____" ] ], [ [ "Intervalo de confianza del 99%", "_____no_output_____" ] ], [ [ "confianza = 0.99\nsigma_est = sim_closes.iloc[-1].sem()\nmean_est = call.iloc[-1].Prima\ni2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est)\nprint(i2)\n", "(9.166854062820644, 9.242080458311612)\n" ], [ "opcion_valuar['JSON']", "_____no_output_____" ] ], [ [ "## Precios simulados usando técnicas de reducción de varianza", "_____no_output_____" ] ], [ [ "# Usando muestreo estratificado----> #estratros = nscen\nU = (np.arange(0,nscen)+np.random.rand(ndays,nscen))/nscen\nZ = st.norm.ppf(U)\n\nsim_ret2 = pd.DataFrame(sigma*Z+r,index=dates)\nsim_closes2 = S0*np.exp(sim_ret.cumsum())\n\n# Función de pago\nstrike = pd.DataFrame(K*np.ones([ndays,nscen]), index=dates)\ncall = pd.DataFrame({'Prima':np.exp(-r*ndays) \\\n *np.fmax(sim_closes2-strike,np.zeros([ndays,nscen])).T.mean()}, index=dates)\ncall.plot();", "_____no_output_____" ] ], [ [ "La valuación de la opción es:", "_____no_output_____" ] ], [ [ "call.iloc[-1]", "_____no_output_____" ] ], [ [ "Intervalo de confianza del 99%", "_____no_output_____" ] ], [ [ "confianza = 0.99\nsigma_est = sim_closes2.iloc[-1].sem()\nmean_est = call.iloc[-1].Prima\ni2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est)\nprint(i2)", "(9.179939817813485, 9.255166213304454)\n" ] ], [ [ "### Análisis de la distribución de los rendimientos", "_____no_output_____" ], [ "### Ajustando norm", "_____no_output_____" ] ], [ [ "ren = calc_daily_ret(closes_aapl) # rendimientos \ny,x,des = plt.hist(ren['AAPL'],bins=50,density=True,label='Histograma rendimientos')\n\nmu_fit,sd_fit = st.norm.fit(ren) # Se ajustan los parámetros de una normal\n# Valores máximo y mínimo de los rendiemientos a generar\nren_max = max(x);ren_min = min(x)\n# Vector de rendimientos generados\nren_gen = np.arange(ren_min,ren_max,0.001)\n# Generación de la normal ajustado con los parámetros encontrados\ncurve_fit = st.norm.pdf(ren_gen,loc=mu_fit,scale=sd_fit)\nplt.plot(ren_gen,curve_fit,label='Distribución ajustada')\nplt.legend()\nplt.show()\n", "_____no_output_____" ] ], [ [ "### Ajustando t", "_____no_output_____" ] ], [ [ "# rendimientos \nren = calc_daily_ret(closes_aapl) \n\n# Histograma de los rendimientos\ny, x, _ = plt.hist(ren['AAPL'], bins=50, density=True, label='Histograma rendimientos')\n\n# Se ajustan los parámetros de una distribución\ndist = 't'\nparams = getattr(st, dist).fit(ren.values) \n\n# Generación de la pdf de la distribución ajustado con los parámetros encontrados\ncurve_fit = getattr(st, dist).pdf(x, *params)\nplt.plot(x, curve_fit, label='Distribución ajustada')\nplt.legend()\nplt.show()\n\n# Q-Q\nst.probplot(ren['AAPL'], sparams=params[:-2], dist=dist, plot=plt);\n", "_____no_output_____" ] ], [ [ "## 3. Valuación usando simulación: uso del histograma de rendimientos\n\nTodo el análisis anterior se mantiene. Solo cambia la forma de generar los números aleatorios para la simulación montecarlo.\n\nAhora, generemos un histograma de los rendimientos diarios para generar valores aleatorios de los rendimientos simulados.", "_____no_output_____" ], [ "- Primero, cantidad de días y número de escenarios de simulación", "_____no_output_____" ] ], [ [ "nscen = 10", "_____no_output_____" ] ], [ [ "- Del histograma anterior, ya conocemos las probabilidades de ocurrencia, lo que se llamó como variable `y`", "_____no_output_____" ] ], [ [ "prob = y/np.sum(y)\nvalues = x[1:]\nprob.sum()", "_____no_output_____" ] ], [ [ "- Con esto, generamos los números aleatorios correspondientes a los rendimientos (tantos como días por número de escenarios).", "_____no_output_____" ] ], [ [ "dates = pd.date_range(start=Hoy,end=opcion_valuar.Expiry, freq='B')\nndays = len(dates)\n\nret = np.random.choice(values, ndays*nscen, p=prob)\n\nsim_ret_hist = pd.DataFrame(ret.reshape((ndays,nscen)),index=dates)\nsim_ret_hist", "_____no_output_____" ], [ "sim_closes_hist = (closes_aapl.iloc[-1,0])*np.exp(sim_ret_hist.cumsum())\nsim_closes_hist", "_____no_output_____" ], [ "sim_closes_hist.plot(figsize=(8,6),legend=False);", "_____no_output_____" ], [ "pd.concat([closes_aapl,sim_closes_hist]).plot(figsize=(8,6),legend=False);\nplt.title('Simulación usando el histograma de los rendimientos')", "_____no_output_____" ], [ "(ret_aapl - ret_aapl.mean() + r).mean()", "_____no_output_____" ], [ "K = opcion_valuar['JSON']['strike']\nndays = len(dates)\nnscen = 10000\n\n# Histograma tomando la tasa libre de riesgo\nfreq, values = np.histogram(ret_aapl+r-mu, bins=2000)\nprob = freq/np.sum(freq)\n\n# Simulación de los rendimientos\nret = np.random.choice(values[1:], ndays*nscen, p=prob)\n\n# Simulación de precios\nsim_ret_hist = pd.DataFrame(ret.reshape((ndays,nscen)),index=dates)\nsim_closes_hist = (closes_aapl.iloc[-1,0]) * np.exp(sim_ret_hist.cumsum())\nsim_closes_hist", "_____no_output_____" ], [ "call_hist = pd.DataFrame({'Prima':np.exp(-r*ndays) \\\n *np.fmax(sim_closes_hist-K, 0).mean(axis=1)}, index=dates)\ncall_hist.plot();", "_____no_output_____" ], [ "call_hist.iloc[-1]", "_____no_output_____" ], [ "opcion_valuar['JSON']", "_____no_output_____" ] ], [ [ "Intervalo de confianza del 95%", "_____no_output_____" ] ], [ [ "confianza = 0.95\nsigma_est = sim_closes_hist.iloc[-1].sem()\nmean_est = call_hist.iloc[-1].Prima\ni2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est)\nprint(i2)\n", "(9.03172920765023, 9.59548003107524)\n" ] ], [ [ "# <font color = 'red'> Tarea: </font>\n\nReplicar el procedimiento anterior para valoración de opciones 'call', pero en este caso para opciones tipo 'put'.", "_____no_output_____" ], [ "<script>\n $(document).ready(function(){\n $('div.prompt').hide();\n $('div.back-to-top').hide();\n $('nav#menubar').hide();\n $('.breadcrumb').hide();\n $('.hidden-print').hide();\n });\n</script>\n\n<footer id=\"attribution\" style=\"float:right; color:#808080; background:#fff;\">\nCreated with Jupyter by Esteban Jiménez Rodríguez and modified by Oscar Jaramillo Z.\n</footer>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb0d80e9635a0c6270972246670fa473b027a7ba
7,123
ipynb
Jupyter Notebook
archive/20190226-mnist-linear.ipynb
akabakcioglu/SGDDynamics
f8b7ed1be545f525b01f0ca9e42591ae38e85976
[ "MIT" ]
null
null
null
archive/20190226-mnist-linear.ipynb
akabakcioglu/SGDDynamics
f8b7ed1be545f525b01f0ca9e42591ae38e85976
[ "MIT" ]
null
null
null
archive/20190226-mnist-linear.ipynb
akabakcioglu/SGDDynamics
f8b7ed1be545f525b01f0ca9e42591ae38e85976
[ "MIT" ]
1
2019-09-10T10:45:27.000Z
2019-09-10T10:45:27.000Z
22.757188
95
0.49263
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb0d82289b7e1d032e953639a8e8cc4d39fa7c88
8,917
ipynb
Jupyter Notebook
torch_demo/tutorials-master/2_Tensors.ipynb
LightSun/CppLibs
7547466e00610a306ee82b9a01fb8c8924ca8f90
[ "Apache-2.0" ]
null
null
null
torch_demo/tutorials-master/2_Tensors.ipynb
LightSun/CppLibs
7547466e00610a306ee82b9a01fb8c8924ca8f90
[ "Apache-2.0" ]
null
null
null
torch_demo/tutorials-master/2_Tensors.ipynb
LightSun/CppLibs
7547466e00610a306ee82b9a01fb8c8924ca8f90
[ "Apache-2.0" ]
null
null
null
25.550143
478
0.496692
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb0d847f5850554436474a97a6d78d7f2cb3907c
654,318
ipynb
Jupyter Notebook
tutorials/mesh-visualisation.ipynb
askeyjw/workshop
55f78021c0b5bb431372c9e6669bb3561d41a062
[ "BSD-3-Clause" ]
null
null
null
tutorials/mesh-visualisation.ipynb
askeyjw/workshop
55f78021c0b5bb431372c9e6669bb3561d41a062
[ "BSD-3-Clause" ]
null
null
null
tutorials/mesh-visualisation.ipynb
askeyjw/workshop
55f78021c0b5bb431372c9e6669bb3561d41a062
[ "BSD-3-Clause" ]
null
null
null
111.202923
67,676
0.859825
[ [ [ "# Mesh visualisation\n\nWe are now going to have a look at different mesh visualisation options. We are going to use the following mesh:", "_____no_output_____" ] ], [ [ "import discretisedfield as df\n\np1 = (0, 0, 0)\np2 = (100e-9, 50e-9, 20e-9)\nn = (20, 10, 4)\n\nregion = df.Region(p1=p1, p2=p2)\nmesh = df.Mesh(region=region, n=n)", "_____no_output_____" ] ], [ [ "Same as the region object, there are two main ways how we can visualise mesh in `discretisedfield`:\n\n1. Using `matplotlib` (static 2D plots, usually with some tricks to make them look 3D)\n2. Using `k3d` (interactive 3D plots)\n\nAll `matplotlib` method names start with `mpl`, whereas all `k3d` plots start with `k3d`. We will first have a look at simple plotting using both `matplotlib` and `k3d` and later look at how we can pass different parameters to change them.\n\n## Basic plotting\n\nTo get a quick `matploltlib` \"3D\" plot of the mesh, we call `mpl`:", "_____no_output_____" ] ], [ [ "mesh.mpl()", "_____no_output_____" ] ], [ [ "`mpl` plots two cubic regions. The larger one corresponds to the region and the smaller one to the discretisation cell. Without passing any parameters to `mpl` function, some default settings are chosen. We can see that `matplotlib` is not good in showing the right proportions of the region. More precisely, we know that the region is much thinner in the z-direction, but that is not the impression we get from the plot. This is the main disadvatage of `mpl`.\n\nNow, we can ask our region object for an interactive `k3d` plot:", "_____no_output_____" ] ], [ [ "# NBVAL_IGNORE_OUTPUT\nmesh.k3d()", "_____no_output_____" ] ], [ [ "Similar to the `mpl` plot, we can see the region as well as the discretisation cell in this plot. This can be useful to get an impression of the discretisation cell size with respect to the region we discretise. `k3d` plot is an interactive plot, which we can zoom, rotate, etc. In addition, a small contol panel is shown in the top-right corner, where we can modify some of the plot's properties.", "_____no_output_____" ], [ "## Advanced plotting\n\nHere we explore what parameters we can pass to `mpl` and `k3d` functions. Let us start with `mpl`.\n\n### `mpl`\n\nThe default plot is:", "_____no_output_____" ] ], [ [ "mesh.mpl()", "_____no_output_____" ] ], [ [ "If we want to change the figure size, we can pass `figsize` parameter. Its value must be a lenth-2 tuple, with the first element being the size in the horizontal direction, whereas the second element is the size in the vertical direction.", "_____no_output_____" ] ], [ [ "region.mpl(figsize=(10, 5))", "_____no_output_____" ] ], [ [ "The color of the lines depicting the region and the discretisation cell we can choose by passing `color` argument. `color` must be a lenght-2 tuple which consists of valid `matplotlib` colours. For instance, it can be a pair of RGB hex-strings ([online converter](http://www.javascripter.net/faq/rgbtohex.htm)). The first element is `color` is the colour of the region, whereas the second element is the colour of the discretisation cell.", "_____no_output_____" ] ], [ [ "mesh.mpl(color=('#9400D3', '#0000FF'))", "_____no_output_____" ] ], [ [ "`discretisedfield` automatically chooses the SI prefix (nano, micro, etc.) it is going to use to divide the axes with and show those units on the axes. Sometimes (e.g. for thin films), `discretisedfield` does not choose the SI prefix we expected. In those cases, we can explicitly pass it using `multiplier` argument. ``multiplier`` can be passed as $10^{n}$, where $n$ is a multiple of 3 (..., -6, -3, 0, 3, 6,...). For instance, if `multiplier=1e-6` is passed, all axes will be divided by $1\\,\\mu\\text{m}$ and $\\mu\\text{m}$ units will be used as axis labels.", "_____no_output_____" ] ], [ [ "mesh.mpl(multiplier=1e-6)", "_____no_output_____" ] ], [ [ "If we want to save the plot, we pass `filename`, mesh plot is going to be shown and the plot saved in our working directory as a PDF.", "_____no_output_____" ] ], [ [ "mesh.mpl(filename='my-mesh-plot.pdf')", "_____no_output_____" ] ], [ [ "`mpl` mesh plot is based on [`matplotlib.pyplot.plot` function](https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.plot.html). Therefore, any parameter accepted by it can be passed. For instance:", "_____no_output_____" ] ], [ [ "mesh.mpl(marker='o', linestyle='dashed')", "_____no_output_____" ] ], [ [ "Finally, we show how to expose the axes on which the mesh is plotted, so that we can customise them. We do that by creating the axes ourselves and then passing them to `mpl` function.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\n# Create the axes\nfig = plt.figure(figsize=(8, 5))\nax = fig.add_subplot(111, projection='3d')\n\n# Add the region to the axes\nmesh.mpl(ax=ax)\n\n# Customise the axes\nax.set_xlabel('length')\nax.set_ylabel('width')\nax.set_zlabel('height')", "_____no_output_____" ] ], [ [ "This way, by exposing the axes and passing any allowed `matplotlib.pyplot.plot` argument, we can customise the plot any way we like (as long as it is allowed by `matplotlib`).\n\n### `k3d`\n\nDefault k3d plot is:", "_____no_output_____" ] ], [ [ "# NBVAL_IGNORE_OUTPUT\nmesh.k3d()", "_____no_output_____" ] ], [ [ "If we want to change the color, we can pass `color` argument. It is a length-2 tuple of integer colours. The first number in the tuple is the colour of the region, whereas the second colour is the colour of the discretisation cell.", "_____no_output_____" ] ], [ [ "# NBVAL_IGNORE_OUTPUT\nmesh.k3d(color=(754321, 123456))", "_____no_output_____" ] ], [ [ "Similar to the `mpl` plot, we can change the axes multiplier.", "_____no_output_____" ] ], [ [ "# NBVAL_IGNORE_OUTPUT\nmesh.k3d(multiplier=1e-6)", "_____no_output_____" ] ], [ [ "`k3d` plot is based on [k3d.voxels](https://k3d-jupyter.org/k3d.html#k3d.factory.voxels), so any parameter accepted by it can be passed. For instance:", "_____no_output_____" ] ], [ [ "# NBVAL_IGNORE_OUTPUT\nmesh.k3d(opacity=0.2)", "_____no_output_____" ] ], [ [ "We can also expose `k3d.Plot` object and customise it.", "_____no_output_____" ] ], [ [ "# NBVAL_IGNORE_OUTPUT\nimport k3d\n\n# Expose plot object\nplot = k3d.plot()\nplot.display()\n\n# Add region to the plot\nmesh.k3d(plot=plot)\n\n# Customise the plot\nplot.axes = [r'\\text{length}', r'\\text{width}', r'\\text{height}']", "_____no_output_____" ] ], [ [ "This way, we can modify the plot however we want (as long as `k3d` allows it).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "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" ] ]
cb0d8ad48b30333af71d5a80422b70a8c17db9b7
6,347
ipynb
Jupyter Notebook
notebooks/004-hello-detection/004-hello-detection.ipynb
bdattoma/openvino_notebooks
a552feba5c0fca871125ff68fe4bcea20a2fcaca
[ "Apache-2.0" ]
null
null
null
notebooks/004-hello-detection/004-hello-detection.ipynb
bdattoma/openvino_notebooks
a552feba5c0fca871125ff68fe4bcea20a2fcaca
[ "Apache-2.0" ]
null
null
null
notebooks/004-hello-detection/004-hello-detection.ipynb
bdattoma/openvino_notebooks
a552feba5c0fca871125ff68fe4bcea20a2fcaca
[ "Apache-2.0" ]
null
null
null
30.960976
378
0.552545
[ [ [ "# Hello World Text Detection\n\nA very basic introduction to OpenVINO that shows how to do text detection on a given IR model.\n\nWe use the [horizontal-text-detection-0001](https://docs.openvinotoolkit.org/latest/omz_models_model_horizontal_text_detection_0001.html) model from [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/). It detects texts in images and returns blob of data in shape of [100, 5]. For each detection description has format [x_min, y_min, x_max, y_max, conf].\n", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom openvino.inference_engine import IECore", "_____no_output_____" ] ], [ [ "## Load the Model", "_____no_output_____" ] ], [ [ "ie = IECore()\n\nnet = ie.read_network(\n model=\"model/horizontal-text-detection-0001.xml\",\n weights=\"model/horizontal-text-detection-0001.bin\",\n)\nexec_net = ie.load_network(net, \"CPU\")\n\noutput_layer_ir = next(iter(exec_net.outputs))\ninput_layer_ir = next(iter(exec_net.input_info))", "_____no_output_____" ] ], [ [ "## Load an Image", "_____no_output_____" ] ], [ [ "# Text detection models expects image in BGR format\nimage = cv2.imread(\"data/intel_rnb.jpg\")\n\n# N,C,H,W = batch size, number of channels, height, width\nN, C, H, W = net.input_info[input_layer_ir].tensor_desc.dims\n\n# Resize image to meet network expected input sizes\nresized_image = cv2.resize(image, (W, H))\n\n# Reshape to network input shape\ninput_image = np.expand_dims(resized_image.transpose(2, 0, 1), 0)\n\nplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB));", "_____no_output_____" ] ], [ [ "## Do Inference", "_____no_output_____" ] ], [ [ "result = exec_net.infer(inputs={input_layer_ir: input_image})\n\n# Extract list of boxes from results\nboxes = result[\"boxes\"]\n\n# Remove zero only boxes\nboxes = boxes[~np.all(boxes == 0, axis=1)]", "_____no_output_____" ] ], [ [ "## Visualize Results", "_____no_output_____" ] ], [ [ "# For each detection, the description has the format: [x_min, y_min, x_max, y_max, conf]\n# Image passed here is in BGR format with changed width and height. To display it in colors expected by matplotlib we use cvtColor funtion\n\n\ndef convert_result_to_image(bgr_image, resized_image, boxes, threshold=0.3, conf_labels=True):\n # Helper function to multiply shape by ratio\n def multiply_by_ratio(ratio_x, ratio_y, box):\n return [\n max(shape * ratio_y, 10) if idx % 2 else shape * ratio_x\n for idx, shape in enumerate(box[:-1])\n ]\n\n # Define colors for boxes and descriptions\n colors = {\"red\": (255, 0, 0), \"green\": (0, 255, 0)}\n\n # Fetch image shapes to calculate ratio\n (real_y, real_x), (resized_y, resized_x) = image.shape[:2], resized_image.shape[:2]\n ratio_x, ratio_y = real_x / resized_x, real_y / resized_y\n\n # Convert base image from bgr to rgb format\n rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)\n\n # Iterate through non-zero boxes\n for box in boxes:\n # Pick confidence factor from last place in array\n conf = box[-1]\n if conf > threshold:\n # Convert float to int and multiply position of each box by x and y ratio\n (x_min, y_min, x_max, y_max) = map(int, multiply_by_ratio(ratio_x, ratio_y, box))\n\n # Draw box based on position, parameters in rectangle function are: image, start_point, end_point, color, thickness\n rgb_image = cv2.rectangle(rgb_image, (x_min, y_min), (x_max, y_max), colors[\"green\"], 3)\n\n # Add text to image based on position and confidence, parameters in putText function are: image, text, bottomleft_corner_textfield, font, font_scale, color, thickness, line_type\n if conf_labels:\n rgb_image = cv2.putText(\n rgb_image,\n f\"{conf:.2f}\",\n (x_min, y_min - 10),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.8,\n colors[\"red\"],\n 1,\n cv2.LINE_AA,\n )\n\n return rgb_image", "_____no_output_____" ], [ "plt.figure(figsize=(10, 6))\nplt.axis(\"off\")\nplt.imshow(convert_result_to_image(image, resized_image, boxes, conf_labels=False));", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb0d93e0ec6f121b1549d199555348afd398c846
8,795
ipynb
Jupyter Notebook
2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROBA/114-PROBA-Generador-cython.ipynb
AlejandroSantorum/Apuntes_Mat_IngInf
68ee7851769c27a7d04203a35b14449d7f80eb73
[ "Apache-2.0" ]
18
2019-10-03T13:07:35.000Z
2022-03-29T12:58:34.000Z
2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROBA/114-PROBA-Generador-cython.ipynb
AlejandroSantorum/Apuntes_Mat_IngInf
68ee7851769c27a7d04203a35b14449d7f80eb73
[ "Apache-2.0" ]
null
null
null
2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROBA/114-PROBA-Generador-cython.ipynb
AlejandroSantorum/Apuntes_Mat_IngInf
68ee7851769c27a7d04203a35b14449d7f80eb73
[ "Apache-2.0" ]
7
2020-01-23T09:59:08.000Z
2021-10-04T18:03:03.000Z
24.985795
493
0.513246
[ [ [ "<h3>Sin Cython</h3>\n<p>Este programa genera $N$ enteros aleatorios entre $1$ y $M$, y una vez obtenidos los&nbsp; eleva al cuadrado y devuelve la suma de los cuadrados. Por tanto, calcula el cuadrado de la longitud&nbsp; de un vector aleatorio con coordenadas enteros en el intervalo $[1,M]$.</p>", "_____no_output_____" ] ], [ [ "def cuadrados(N,M):\n res = 0\n for muda in xrange(N):\n x = randint(1,M)\n res += x*x\n return res", "_____no_output_____" ], [ "for n in srange(3,8):\n %time A = cuadrados(10^n,10^6)", "CPU times: user 5.61 ms, sys: 263 µs, total: 5.87 ms\nWall time: 6.09 ms\nCPU times: user 44.7 ms, sys: 0 ns, total: 44.7 ms\nWall time: 57.6 ms\nCPU times: user 477 ms, sys: 57.1 ms, total: 534 ms\nWall time: 480 ms\nCPU times: user 4.39 s, sys: 130 ms, total: 4.52 s\nWall time: 4.42 s\nCPU times: user 43.3 s, sys: 403 ms, total: 43.7 s\nWall time: 43.4 s\n" ] ], [ [ "<h3>Con Cython</h3>\n<p>Mismo c&aacute;lculo:</p>", "_____no_output_____" ] ], [ [ "%%cython\nimport math\nimport random\ndef cuadrados_cy(long long N, long long M):\n cdef long long res = 0\n cdef long long muda\n cdef long long x\n for muda in xrange(N):\n x = random.randint(1,M)\n res += math.pow(x,2)\n return res", "_____no_output_____" ], [ "for n in srange(3,8):\n %time A = cuadrados_cy(10^n,10^6)", "CPU times: user 2.94 ms, sys: 48 µs, total: 2.99 ms\nWall time: 2.83 ms\nCPU times: user 28.7 ms, sys: 34 µs, total: 28.7 ms\nWall time: 33.3 ms\nCPU times: user 259 ms, sys: 24.3 ms, total: 284 ms\nWall time: 252 ms\nCPU times: user 2.47 s, sys: 167 ms, total: 2.64 s\nWall time: 2.44 s\nCPU times: user 22.9 s, sys: 258 ms, total: 23.1 s\nWall time: 22.9 s\n" ] ], [ [ "<h3>Optimizando el c&aacute;lculo de n&uacute;meros aleatorios:</h3>", "_____no_output_____" ] ], [ [ "%%cython\n\ncdef extern from 'gsl/gsl_rng.h':\n ctypedef struct gsl_rng_type:\n pass\n ctypedef struct gsl_rng:\n pass\n gsl_rng_type *gsl_rng_mt19937\n gsl_rng *gsl_rng_alloc(gsl_rng_type * T)\n \ncdef gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937)\n\ncdef extern from 'gsl/gsl_randist.h':\n long int uniform 'gsl_rng_uniform_int'(gsl_rng * r, unsigned long int n)\n\ndef main():\n cdef int n\n n = uniform(r,1000000)\n return n\n\ncdef long f(long x):\n return x**2\n \nimport random\ndef cuadrados_cy2(int N):\n cdef long res = 0\n cdef int muda\n for muda in range(N):\n res += f(main())\n return res", "_____no_output_____" ], [ "for n in srange(3,8):\n %time A = cuadrados_cy2(10^n)", "CPU times: user 68 µs, sys: 1e+03 ns, total: 69 µs\nWall time: 72 µs\nCPU times: user 568 µs, sys: 0 ns, total: 568 µs\nWall time: 511 µs\nCPU times: user 4.82 ms, sys: 0 ns, total: 4.82 ms\nWall time: 4.83 ms\nCPU times: user 48.1 ms, sys: 0 ns, total: 48.1 ms\nWall time: 48.5 ms\nCPU times: user 479 ms, sys: 0 ns, total: 479 ms\nWall time: 479 ms\n" ] ], [ [ "<h3>Problema similar sin n&uacute;meros aleatorios:</h3>", "_____no_output_____" ] ], [ [ "%%cython\ndef cuadrados_cy3(long long int N):\n cdef long long int res = 0\n cdef long long int k\n for k in range(N):\n res += k**2\n return res", "_____no_output_____" ], [ "for n in srange(3,8):\n %time A = cuadrados_cy3(10^n)", "CPU times: user 12 µs, sys: 0 ns, total: 12 µs\nWall time: 16.9 µs\nCPU times: user 16 µs, sys: 1e+03 ns, total: 17 µs\nWall time: 20 µs\nCPU times: user 75 µs, sys: 2 µs, total: 77 µs\nWall time: 78 µs\nCPU times: user 770 µs, sys: 0 ns, total: 770 µs\nWall time: 719 µs\nCPU times: user 7.01 ms, sys: 0 ns, total: 7.01 ms\nWall time: 10.2 ms\n" ], [ "def cuadrados5(N):\n res = 0\n for k in range(N):\n res += k**2\n return res", "_____no_output_____" ], [ "for n in srange(3,8):\n %time A = cuadrados5(10^n)", "CPU times: user 643 µs, sys: 0 ns, total: 643 µs\nWall time: 487 µs\nCPU times: user 1.35 ms, sys: 3.95 ms, total: 5.31 ms\nWall time: 4.26 ms\nCPU times: user 25.5 ms, sys: 12 ms, total: 37.4 ms\nWall time: 37.4 ms\nCPU times: user 373 ms, sys: 28.2 ms, total: 402 ms\nWall time: 387 ms\nCPU times: user 3.75 s, sys: 169 ms, total: 3.92 s\nWall time: 3.88 s\n" ] ], [ [ "<p>Hemos comprobado, de dos maneras, que es en la generaci&oacute;n&nbsp; de los n&uacute;meros&nbsp; aleatorios donde Python pasa la mayor parte del tiempo en este c&aacute;lculo. Si optimizamos esa parte, usando una librer&iacute;a en C, o simplemente la suprimimos, el c&aacute;lculo es mucho m&aacute;s r&aacute;pido.&nbsp; Cython pierde much&iacute;sima eficiencia cuando debe ejecutar funciones de Python que son mucho m&aacute;s lentas que las correspondientes funciones en C.</p>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
cb0d9a0788cc6a62ed446061a1b92ae7c5a4fe9a
3,191
ipynb
Jupyter Notebook
sklearn/sklearn learning/demonstration/auto_examples_jupyter/linear_model/plot_sgd_iris.ipynb
wangyendt/deeplearning_models
47883b6c65b8d05a0d1c5737f1552df6476ded34
[ "MIT" ]
1
2020-06-04T11:10:27.000Z
2020-06-04T11:10:27.000Z
sklearn/sklearn learning/demonstration/auto_examples_jupyter/linear_model/plot_sgd_iris.ipynb
wangyendt/deeplearning_models
47883b6c65b8d05a0d1c5737f1552df6476ded34
[ "MIT" ]
null
null
null
sklearn/sklearn learning/demonstration/auto_examples_jupyter/linear_model/plot_sgd_iris.ipynb
wangyendt/deeplearning_models
47883b6c65b8d05a0d1c5737f1552df6476ded34
[ "MIT" ]
null
null
null
59.092593
1,991
0.598872
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\n# Plot multi-class SGD on the iris dataset\n\n\nPlot decision surface of multi-class SGD on iris dataset.\nThe hyperplanes corresponding to the three one-versus-all (OVA) classifiers\nare represented by the dashed lines.\n", "_____no_output_____" ] ], [ [ "print(__doc__)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom sklearn.linear_model import SGDClassifier\n\n# import some data to play with\niris = datasets.load_iris()\n\n# we only take the first two features. We could\n# avoid this ugly slicing by using a two-dim dataset\nX = iris.data[:, :2]\ny = iris.target\ncolors = \"bry\"\n\n# shuffle\nidx = np.arange(X.shape[0])\nnp.random.seed(13)\nnp.random.shuffle(idx)\nX = X[idx]\ny = y[idx]\n\n# standardize\nmean = X.mean(axis=0)\nstd = X.std(axis=0)\nX = (X - mean) / std\n\nh = .02 # step size in the mesh\n\nclf = SGDClassifier(alpha=0.001, max_iter=100).fit(X, y)\n\n# create a mesh to plot in\nx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n\n# Plot the decision boundary. For that, we will assign a color to each\n# point in the mesh [x_min, x_max]x[y_min, y_max].\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n# Put the result into a color plot\nZ = Z.reshape(xx.shape)\ncs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)\nplt.axis('tight')\n\n# Plot also the training points\nfor i, color in zip(clf.classes_, colors):\n idx = np.where(y == i)\n plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],\n cmap=plt.cm.Paired, edgecolor='black', s=20)\nplt.title(\"Decision surface of multi-class SGD\")\nplt.axis('tight')\n\n# Plot the three one-against-all classifiers\nxmin, xmax = plt.xlim()\nymin, ymax = plt.ylim()\ncoef = clf.coef_\nintercept = clf.intercept_\n\n\ndef plot_hyperplane(c, color):\n def line(x0):\n return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1]\n\n plt.plot([xmin, xmax], [line(xmin), line(xmax)],\n ls=\"--\", color=color)\n\n\nfor i, color in zip(clf.classes_, colors):\n plot_hyperplane(i, color)\nplt.legend()\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ] ]
cb0da3cda5cd0763835a2e91b66c4f1c1edd75a1
45,743
ipynb
Jupyter Notebook
topic_modeling_LDA.ipynb
SolbiChoi/test_deeplearning
c1fb02bc0e14235c4696b4386c469603cc0c682c
[ "Apache-2.0" ]
null
null
null
topic_modeling_LDA.ipynb
SolbiChoi/test_deeplearning
c1fb02bc0e14235c4696b4386c469603cc0c682c
[ "Apache-2.0" ]
null
null
null
topic_modeling_LDA.ipynb
SolbiChoi/test_deeplearning
c1fb02bc0e14235c4696b4386c469603cc0c682c
[ "Apache-2.0" ]
null
null
null
41.584545
244
0.256258
[ [ [ "<a href=\"https://colab.research.google.com/github/SolbiChoi/test_deeplearning/blob/master/topic_modeling_LDA.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!curl -O https://raw.githubusercontent.com/franciscadias/data/master/abcnews-date-text.csv", " % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 51.5M 100 51.5M 0 0 29.1M 0 0:00:01 0:00:01 --:--:-- 29.1M\n" ], [ "import pandas as pd", "_____no_output_____" ], [ "df_data = pd.read_csv('./abcnews-date-text.csv')\ndf_data.head(3)", "_____no_output_____" ], [ "df_data = df_data.head(10000)", "_____no_output_____" ], [ "head_text = df_data[['headline_text']]\ntype(head_text)", "_____no_output_____" ], [ "import nltk\nnltk.download('punkt')", "[nltk_data] Downloading package punkt to /root/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n" ], [ "head_text['title_text'] = head_text.apply(lambda row : nltk.word_tokenize(row['headline_text']), axis=1) # map()\nhead_text.head(3)", "_____no_output_____" ], [ "from nltk.corpus import stopwords\nnltk.download('stopwords')", "[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Unzipping corpora/stopwords.zip.\n" ], [ "stop = stopwords.words('english')\nstop", "_____no_output_____" ], [ "# titles = []\n# for x in head_text['title_text']:\n# for word in x:\n# if len(word) > 3:\n# if word not in stop:\n# titles.apply(word)\n# return titles\n\n# def stopWord(x):\n# result = []\n# for word in x:\n# if word not in stop or len(word)>3:\n# return result\n\n# def callStopWord(head_text):\n# titles=[]\n# for x in head_text['title_text']:\n# titles.apply(stopWord(x))\n# return titles\n\nhead_text['title'] = head_text['title_text'].apply(lambda x:[word for word in x if (len(word)>3) if (word not in stop)])", "_____no_output_____" ], [ "head_text.head(5)", "_____no_output_____" ], [ "head_text['title'][3]", "_____no_output_____" ], [ "tokens = []\nfor i in range(len(head_text)):\n tokens.append(' '.join(head_text['title'][i]))\n\ntokens[3:5]", "_____no_output_____" ], [ "from sklearn.feature_extraction.text import TfidfVectorizer", "_____no_output_____" ], [ "tfidf = TfidfVectorizer(max_features=1000)\nX = tfidf.fit_transform(tokens)\nX.shape", "_____no_output_____" ], [ "X[4].toarray()", "_____no_output_____" ], [ "from sklearn.decomposition import LatentDirichletAllocation", "_____no_output_____" ], [ "lda_model = LatentDirichletAllocation()", "_____no_output_____" ], [ "lda_top = lda_model.fit_transform(X)", "_____no_output_____" ], [ "lda_model.components_.shape, lda_model.components_", "_____no_output_____" ], [ "terms = tfidf.get_feature_names()", "_____no_output_____" ], [ "n = 5\nfor idx, topic in enumerate(lda_model.components_):\n print([(terms[i], topic[i]) for i in topic.argsort()[:-n-1:-1]])", "[('fire', 5.725922615329099), ('iraq', 5.009599583817683), ('nightclub', 3.5498569701789457), ('stay', 3.430420925321937), ('back', 2.9334764893740384)]\n[('record', 4.169977934651739), ('club', 3.571716506558007), ('hearing', 2.526040251940724), ('fire', 2.3493828445852882), ('ready', 2.2873314227868096)]\n[('takes', 3.2683542469709517), ('stabbing', 3.2180419903424307), ('coast', 2.935642771922063), ('water', 2.91651392783424), ('gold', 2.6523222223235616)]\n[('council', 6.658569061764383), ('face', 3.500190937721669), ('patterson', 3.2873315213444885), ('profit', 2.8412707598284404), ('jailed', 2.807365037533717)]\n[('funds', 3.778247497805507), ('states', 3.1454031778459406), ('protesters', 2.771969127653773), ('milk', 2.3328199816568613), ('prices', 2.275602760226452)]\n[('million', 3.81515964620285), ('death', 3.2127644416630203), ('planning', 3.042242050799278), ('education', 2.9768425503988936), ('begins', 2.413906785752221)]\n[('drought', 7.618978670459478), ('rain', 6.870528601429502), ('community', 4.09848827833838), ('crash', 3.7720315870392636), ('farmers', 3.6743039287518773)]\n[('police', 3.1909247460931502), ('australia', 2.877422967209977), ('house', 2.67962335730651), ('concerns', 2.6611276129570447), ('race', 2.504166851753232)]\n[('court', 2.655897035266568), ('case', 2.6205245878875476), ('strike', 2.2229394738318815), ('qantas', 2.040014505157534), ('wins', 2.005946787853262)]\n[('charged', 5.346607877122559), ('govt', 5.113468688737898), ('calls', 3.091563671055276), ('work', 2.9357371086236546), ('british', 2.55213010861176)]\n" ], [ "", "_____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" ] ]
cb0dcae07fde833c978c24b5660892c1f849a9d7
73,310
ipynb
Jupyter Notebook
Chapter-8/CV Book Chapter 8 Exercise 4-1.ipynb
moizumi99/CVBookExercise
5f9a031e631470f7d15861366ca309942ea313f3
[ "Unlicense" ]
30
2017-11-06T07:40:58.000Z
2022-03-11T07:12:19.000Z
Chapter-8/CV Book Chapter 8 Exercise 4-1.ipynb
niilante/CVBookExercise
5f9a031e631470f7d15861366ca309942ea313f3
[ "Unlicense" ]
null
null
null
Chapter-8/CV Book Chapter 8 Exercise 4-1.ipynb
niilante/CVBookExercise
5f9a031e631470f7d15861366ca309942ea313f3
[ "Unlicense" ]
18
2018-07-19T05:05:25.000Z
2022-03-11T07:12:20.000Z
254.548611
18,920
0.914568
[ [ [ "from numpy import *\nfrom PIL import *\nimport pickle\nfrom pylab import *\nimport os", "_____no_output_____" ], [ "import pickle\nimport bayes\nimport imtools", "_____no_output_____" ], [ "with open('points_normal.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)\n\nbc = bayes.BayesClassifier()\nbc.train([class_1, class_2], [1, -1])\n\nwith open('points_normal_test.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)\n\nprint bc.classify(class_1[:10])[0]\nprint bc.classify(class_2[:10])[0]\n\n# draw points and boundary line\ndef classify(x, y, bc=bc):\n points = vstack((x, y))\n return bc.classify(points.T)[0]\n\nimtools.plot_2D_boundary([-6, 6, -6, 6], [class_1, class_2], classify, [1, -1])\nshow()", "[1 1 1 1 1 1 1 1 1 1]\n[-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]\n" ], [ "with open('points_normal.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)", "_____no_output_____" ], [ "import heurisitc\npoisson = reload(poisson)\nbcp = poisson.BayesClassifier()", "_____no_output_____" ], [ "bcp.train([class_1, class_2], [1, -1])", "_____no_output_____" ], [ "with open('points_normal_test.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)", "_____no_output_____" ], [ "print bcp.classify(class_1[:10])[0]\nprint bcp.classify(class_2[:10])[0]", "[1 1 1 1 1 1 1 1 1 1]\n[-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]\n" ], [ "def classify(x, y, bc=bcp):\n points = vstack((x, y))\n return bc.classify(points.T)[0]\n\nimtools.plot_2D_boundary([-6, 6, -6, 6], [class_1, class_2], classify, [1, -1])\nshow()", "_____no_output_____" ], [ "with open('points_ring.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)\n\nbc = bayes.BayesClassifier()\nbc.train([class_1, class_2], [1, -1])\n\nwith open('points_ring_test.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)\n\ndef classify(x, y, bc=bc):\n points = vstack((x, y))\n return bc.classify(points.T)[0]\n\nimtools.plot_2D_boundary([-6, 6, -6, 6], [class_1, class_2], classify, [1, -1])\nshow()", "_____no_output_____" ], [ "import poisson\npoisson = reload(poisson)\n\nwith open('points_ring.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)\n\nbcp = poisson.BayesClassifier()\nbcp.train([class_1, class_2], [1, -1])\n\nwith open('points_ring_test.pkl', 'r') as f:\n class_1 = pickle.load(f)\n class_2 = pickle.load(f)\n labels = pickle.load(f)\n\ndef classify(x, y, bc=bcp):\n points = vstack((x, y))\n return bc.classify(points.T)[0]\n\nimtools.plot_2D_boundary([-6, 6, -6, 6], [class_1, class_2], classify, [1, -1])\nshow()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0dd394e24c9aa7f1a4d5171072054a1dad39c7
29,804
ipynb
Jupyter Notebook
how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb
wamartin-aml/MachineLearningNotebooks
6d5226e47ce7c46a022453e756cd125940c35ef3
[ "MIT" ]
1
2021-05-20T14:29:44.000Z
2021-05-20T14:29:44.000Z
how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb
wamartin-aml/MachineLearningNotebooks
6d5226e47ce7c46a022453e756cd125940c35ef3
[ "MIT" ]
null
null
null
how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb
wamartin-aml/MachineLearningNotebooks
6d5226e47ce7c46a022453e756cd125940c35ef3
[ "MIT" ]
null
null
null
37.162095
547
0.542176
[ [ [ "Copyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the MIT License.", "_____no_output_____" ], [ "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.png)", "_____no_output_____" ], [ "# Automated Machine Learning\n_**Regression with Deployment using Hardware Performance Dataset**_\n\n## Contents\n1. [Introduction](#Introduction)\n1. [Setup](#Setup)\n1. [Data](#Data)\n1. [Train](#Train)\n1. [Results](#Results)\n1. [Test](#Test)\n1. [Acknowledgements](#Acknowledgements)", "_____no_output_____" ], [ "## Introduction\nIn this example we use the Hardware Performance Dataset to showcase how you can use AutoML for a simple regression problem. The Regression goal is to predict the performance of certain combinations of hardware parts.\n\nIf you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n\nIn this notebook you will learn how to:\n1. Create an `Experiment` in an existing `Workspace`.\n2. Configure AutoML using `AutoMLConfig`.\n3. Train the model using local compute.\n4. Explore the results.\n5. Test the best fitted model.", "_____no_output_____" ], [ "## Setup\nAs part of the setup you have already created an Azure ML Workspace object. For AutoML you will need to create an Experiment object, which is a named object in a Workspace used to run experiments.", "_____no_output_____" ] ], [ [ "import logging\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.model_selection import train_test_split\nimport azureml.dataprep as dprep\n \n\nimport azureml.core\nfrom azureml.core.experiment import Experiment\nfrom azureml.core.workspace import Workspace\nfrom azureml.train.automl import AutoMLConfig", "_____no_output_____" ], [ "ws = Workspace.from_config()\n\n# Choose a name for the experiment and specify the project folder.\nexperiment_name = 'automl-regression-hardware'\nproject_folder = './sample_projects/automl-remote-regression'\n\nexperiment = Experiment(ws, experiment_name)\n\noutput = {}\noutput['SDK version'] = azureml.core.VERSION\noutput['Subscription ID'] = ws.subscription_id\noutput['Workspace Name'] = ws.name\noutput['Resource Group'] = ws.resource_group\noutput['Location'] = ws.location\noutput['Project Directory'] = project_folder\noutput['Experiment Name'] = experiment.name\npd.set_option('display.max_colwidth', -1)\noutputDf = pd.DataFrame(data = output, index = [''])\noutputDf.T", "_____no_output_____" ] ], [ [ "## Create or Attach existing AmlCompute\nYou will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n#### Creation of AmlCompute takes approximately 5 minutes. \nIf the AmlCompute with that name is already in your workspace this code will skip the creation process.\nAs with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read this article on the default limits and how to request more quota.", "_____no_output_____" ] ], [ [ "from azureml.core.compute import AmlCompute\nfrom azureml.core.compute import ComputeTarget\n\n# Choose a name for your cluster.\namlcompute_cluster_name = \"automlcl\"\n\nfound = False\n# Check if this compute target already exists in the workspace.\ncts = ws.compute_targets\nif amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n found = True\n print('Found existing compute target.')\n compute_target = cts[amlcompute_cluster_name]\n \nif not found:\n print('Creating a new compute target...')\n provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # for GPU, use \"STANDARD_NC6\"\n #vm_priority = 'lowpriority', # optional\n max_nodes = 6)\n\n # Create the cluster.\n compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n \n # Can poll for a minimum number of nodes and for a specific timeout.\n # If no min_node_count is provided, it will use the scale settings for the cluster.\n compute_target.wait_for_completion(show_output = True, min_node_count = None, timeout_in_minutes = 20)\n \n # For a more detailed view of current AmlCompute status, use get_status().", "_____no_output_____" ] ], [ [ "# Data\n\nHere load the data in the get_data script to be utilized in azure compute. To do this, first load all the necessary libraries and dependencies to set up paths for the data and to create the conda_run_config.", "_____no_output_____" ] ], [ [ "if not os.path.isdir('data'):\n os.mkdir('data')\n \nif not os.path.exists(project_folder):\n os.makedirs(project_folder)", "_____no_output_____" ], [ "from azureml.core.runconfig import RunConfiguration\nfrom azureml.core.conda_dependencies import CondaDependencies\nimport pkg_resources\n\n# create a new RunConfig object\nconda_run_config = RunConfiguration(framework=\"python\")\n\n# Set compute target to AmlCompute\nconda_run_config.target = compute_target\nconda_run_config.environment.docker.enabled = True\nconda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n\ndprep_dependency = 'azureml-dataprep==' + pkg_resources.get_distribution(\"azureml-dataprep\").version\n\ncd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', dprep_dependency], conda_packages=['numpy'])\nconda_run_config.environment.python.conda_dependencies = cd", "_____no_output_____" ] ], [ [ "### Load Data\n\nHere create the script to be run in azure compute for loading the data, load the hardware dataset into the X and y variables. Next split the data using train_test_split and return X_train and y_train for training the model.", "_____no_output_____" ] ], [ [ "data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv\"\ndflow = dprep.read_csv(data, infer_column_types=True)\ndflow.get_profile()\nX = dflow.drop_columns(columns=['ERP'])\ny = dflow.keep_columns(columns=['ERP'], validate_column_exists=True)\nX_train, X_test = X.random_split(percentage=0.8, seed=223)\ny_train, y_test = y.random_split(percentage=0.8, seed=223) \ndflow.head()", "_____no_output_____" ] ], [ [ "\n## Train\n\nInstantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n\n|Property|Description|\n|-|-|\n|**task**|classification or regression|\n|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n|**n_cross_validations**|Number of cross validation splits.|\n|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n\n**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)", "_____no_output_____" ], [ "##### If you would like to see even better results increase \"iteration_time_out minutes\" to 10+ mins and increase \"iterations\" to a minimum of 30", "_____no_output_____" ] ], [ [ "automl_settings = {\n \"iteration_timeout_minutes\": 5,\n \"iterations\": 10,\n \"n_cross_validations\": 5,\n \"primary_metric\": 'spearman_correlation',\n \"preprocess\": True,\n \"max_concurrent_iterations\": 5,\n \"verbosity\": logging.INFO,\n}\n\nautoml_config = AutoMLConfig(task = 'regression',\n debug_log = 'automl_errors_20190417.log',\n path = project_folder,\n run_configuration=conda_run_config,\n X = X_train,\n y = y_train,\n **automl_settings\n )", "_____no_output_____" ], [ "remote_run = experiment.submit(automl_config, show_output = False)", "_____no_output_____" ], [ "remote_run", "_____no_output_____" ] ], [ [ "## Results", "_____no_output_____" ], [ "#### Widget for Monitoring Runs\n\nThe widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n\n**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details.", "_____no_output_____" ] ], [ [ "from azureml.widgets import RunDetails\nRunDetails(remote_run).show() ", "_____no_output_____" ], [ "# Wait until the run finishes.\nremote_run.wait_for_completion(show_output = True)", "_____no_output_____" ] ], [ [ "## Retrieve All Child Runs\nYou can also use SDK methods to fetch all the child runs and see individual metrics that we log.", "_____no_output_____" ] ], [ [ "children = list(remote_run.get_children())\nmetricslist = {}\nfor run in children:\n properties = run.get_properties()\n metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n metricslist[int(properties['iteration'])] = metrics\n\nrundata = pd.DataFrame(metricslist).sort_index(1)\nrundata", "_____no_output_____" ] ], [ [ "## Retrieve the Best Model\nBelow we select the best pipeline from our iterations. The get_output method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on get_output allow you to retrieve the best run and fitted model for any logged metric or for a particular iteration.", "_____no_output_____" ] ], [ [ "best_run, fitted_model = remote_run.get_output()\nprint(best_run)\nprint(fitted_model)", "_____no_output_____" ] ], [ [ "#### Best Model Based on Any Other Metric\nShow the run and the model that has the smallest `root_mean_squared_error` value (which turned out to be the same as the one with largest `spearman_correlation` value):", "_____no_output_____" ] ], [ [ "lookup_metric = \"root_mean_squared_error\"\nbest_run, fitted_model = remote_run.get_output(metric = lookup_metric)\nprint(best_run)\nprint(fitted_model)", "_____no_output_____" ], [ "iteration = 3\nthird_run, third_model = remote_run.get_output(iteration = iteration)\nprint(third_run)\nprint(third_model)", "_____no_output_____" ] ], [ [ "## Register the Fitted Model for Deployment\nIf neither metric nor iteration are specified in the register_model call, the iteration with the best primary metric is registered.", "_____no_output_____" ] ], [ [ "description = 'AutoML Model'\ntags = None\nmodel = remote_run.register_model(description = description, tags = tags)\n\nprint(remote_run.model_id) # This will be written to the script file later in the notebook.", "_____no_output_____" ] ], [ [ "### Create Scoring Script\nThe scoring script is required to generate the image for deployment. It contains the code to do the predictions on input data.", "_____no_output_____" ] ], [ [ "%%writefile score.py\nimport pickle\nimport json\nimport numpy\nimport azureml.train.automl\nfrom sklearn.externals import joblib\nfrom azureml.core.model import Model\n\ndef init():\n global model\n model_path = Model.get_model_path(model_name = '<<modelid>>') # this name is model.id of model that we want to deploy\n # deserialize the model file back into a sklearn model\n model = joblib.load(model_path)\n\ndef run(rawdata):\n try:\n data = json.loads(rawdata)['data']\n data = numpy.array(data)\n result = model.predict(data)\n except Exception as e:\n result = str(e)\n return json.dumps({\"error\": result})\n return json.dumps({\"result\":result.tolist()})", "_____no_output_____" ] ], [ [ "### Create a YAML File for the Environment", "_____no_output_____" ], [ "To ensure the fit results are consistent with the training results, the SDK dependency versions need to be the same as the environment that trains the model. Details about retrieving the versions can be found in notebook [12.auto-ml-retrieve-the-training-sdk-versions](12.auto-ml-retrieve-the-training-sdk-versions.ipynb).", "_____no_output_____" ] ], [ [ "dependencies = remote_run.get_run_sdk_dependencies(iteration = 1)", "_____no_output_____" ], [ "for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n print('{}\\t{}'.format(p, dependencies[p]))", "_____no_output_____" ], [ "myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn'], pip_packages=['azureml-sdk[automl]'])\n\nconda_env_file_name = 'myenv.yml'\nmyenv.save_to_file('.', conda_env_file_name)", "_____no_output_____" ], [ "# Substitute the actual version number in the environment file.\n# This is not strictly needed in this notebook because the model should have been generated using the current SDK version.\n# However, we include this in case this code is used on an experiment from a previous SDK version.\n\nwith open(conda_env_file_name, 'r') as cefr:\n content = cefr.read()\n\nwith open(conda_env_file_name, 'w') as cefw:\n cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n\n# Substitute the actual model id in the script file.\n\nscript_file_name = 'score.py'\n\nwith open(script_file_name, 'r') as cefr:\n content = cefr.read()\n\nwith open(script_file_name, 'w') as cefw:\n cefw.write(content.replace('<<modelid>>', remote_run.model_id))", "_____no_output_____" ] ], [ [ "### Create a Container Image\n\nNext use Azure Container Instances for deploying models as a web service for quickly deploying and validating your model\nor when testing a model that is under development.", "_____no_output_____" ] ], [ [ "from azureml.core.image import Image, ContainerImage\n\nimage_config = ContainerImage.image_configuration(runtime= \"python\",\n execution_script = script_file_name,\n conda_file = conda_env_file_name,\n tags = {'area': \"digits\", 'type': \"automl_regression\"},\n description = \"Image for automl regression sample\")\n\nimage = Image.create(name = \"automlsampleimage\",\n # this is the model object \n models = [model],\n image_config = image_config, \n workspace = ws)\n\nimage.wait_for_creation(show_output = True)\n\nif image.creation_state == 'Failed':\n print(\"Image build log at: \" + image.image_build_log_uri)", "_____no_output_____" ] ], [ [ "### Deploy the Image as a Web Service on Azure Container Instance\n\nDeploy an image that contains the model and other assets needed by the service.", "_____no_output_____" ] ], [ [ "from azureml.core.webservice import AciWebservice\n\naciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n memory_gb = 1, \n tags = {'area': \"digits\", 'type': \"automl_regression\"}, \n description = 'sample service for Automl Regression')", "_____no_output_____" ], [ "from azureml.core.webservice import Webservice\n\naci_service_name = 'automl-sample-hardware'\nprint(aci_service_name)\naci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n image = image,\n name = aci_service_name,\n workspace = ws)\naci_service.wait_for_deployment(True)\nprint(aci_service.state)", "_____no_output_____" ] ], [ [ "### Delete a Web Service\n\nDeletes the specified web service.", "_____no_output_____" ] ], [ [ "#aci_service.delete()", "_____no_output_____" ] ], [ [ "### Get Logs from a Deployed Web Service\n\nGets logs from a deployed web service.", "_____no_output_____" ] ], [ [ "#aci_service.get_logs()", "_____no_output_____" ] ], [ [ "## Test\n\nNow that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values.", "_____no_output_____" ] ], [ [ "X_test = X_test.to_pandas_dataframe()\ny_test = y_test.to_pandas_dataframe()\ny_test = np.array(y_test)\ny_test = y_test[:,0]\nX_train = X_train.to_pandas_dataframe()\ny_train = y_train.to_pandas_dataframe()\ny_train = np.array(y_train)\ny_train = y_train[:,0]", "_____no_output_____" ] ], [ [ "##### Predict on training and test set, and calculate residual values.", "_____no_output_____" ] ], [ [ "y_pred_train = fitted_model.predict(X_train)\ny_residual_train = y_train - y_pred_train\n\ny_pred_test = fitted_model.predict(X_test)\ny_residual_test = y_test - y_pred_test", "_____no_output_____" ] ], [ [ "### Calculate metrics for the prediction\n\nNow visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values \nfrom the trained model that was returned.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# Set up a multi-plot chart.\nf, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})\nf.suptitle('Regression Residual Values', fontsize = 18)\nf.set_figheight(6)\nf.set_figwidth(16)\n\n# Plot residual values of training set.\na0.axis([0, 360, -200, 200])\na0.plot(y_residual_train, 'bo', alpha = 0.5)\na0.plot([-10,360],[0,0], 'r-', lw = 3)\na0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\na0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)),fontsize = 12)\na0.set_xlabel('Training samples', fontsize = 12)\na0.set_ylabel('Residual Values', fontsize = 12)\n\n# Plot residual values of test set.\na1.axis([0, 90, -200, 200])\na1.plot(y_residual_test, 'bo', alpha = 0.5)\na1.plot([-10,360],[0,0], 'r-', lw = 3)\na1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\na1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)),fontsize = 12)\na1.set_xlabel('Test samples', fontsize = 12)\na1.set_yticklabels([])\n\nplt.show()", "_____no_output_____" ], [ "%matplotlib notebook\ntest_pred = plt.scatter(y_test, y_pred_test, color='')\ntest_test = plt.scatter(y_test, y_test, color='g')\nplt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\nplt.show()", "_____no_output_____" ] ], [ [ "## Acknowledgements\nThis Predicting Hardware Performance Dataset is made available under the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication License: https://creativecommons.org/publicdomain/zero/1.0/. Any rights in individual contents of the database are licensed under the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication License: https://creativecommons.org/publicdomain/zero/1.0/ . The dataset itself can be found here: https://www.kaggle.com/faizunnabi/comp-hardware-performance and https://archive.ics.uci.edu/ml/datasets/Computer+Hardware\n\n_**Citation Found Here**_\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" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
cb0dd9a1cee45357d97edcf9a20ea154e5fa3f25
21,307
ipynb
Jupyter Notebook
pytorch_tutorials/pytorch_tutorial_NLP3_word_embeddings_tutorial.ipynb
adam-dziedzic/time-series-ml
81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a
[ "Apache-2.0" ]
1
2018-03-25T13:19:46.000Z
2018-03-25T13:19:46.000Z
pytorch_tutorials/pytorch_tutorial_NLP3_word_embeddings_tutorial.ipynb
adam-dziedzic/time-series-ml
81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a
[ "Apache-2.0" ]
null
null
null
pytorch_tutorials/pytorch_tutorial_NLP3_word_embeddings_tutorial.ipynb
adam-dziedzic/time-series-ml
81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a
[ "Apache-2.0" ]
null
null
null
63.41369
7,336
0.640212
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\nWord Embeddings: Encoding Lexical Semantics\n===========================================\n\nWord embeddings are dense vectors of real numbers, one per word in your\nvocabulary. In NLP, it is almost always the case that your features are\nwords! But how should you represent a word in a computer? You could\nstore its ascii character representation, but that only tells you what\nthe word *is*, it doesn't say much about what it *means* (you might be\nable to derive its part of speech from its affixes, or properties from\nits capitalization, but not much). Even more, in what sense could you\ncombine these representations? We often want dense outputs from our\nneural networks, where the inputs are $|V|$ dimensional, where\n$V$ is our vocabulary, but often the outputs are only a few\ndimensional (if we are only predicting a handful of labels, for\ninstance). How do we get from a massive dimensional space to a smaller\ndimensional space?\n\nHow about instead of ascii representations, we use a one-hot encoding?\nThat is, we represent the word $w$ by\n\n\\begin{align}\\overbrace{\\left[ 0, 0, \\dots, 1, \\dots, 0, 0 \\right]}^\\text{|V| elements}\\end{align}\n\nwhere the 1 is in a location unique to $w$. Any other word will\nhave a 1 in some other location, and a 0 everywhere else.\n\nThere is an enormous drawback to this representation, besides just how\nhuge it is. It basically treats all words as independent entities with\nno relation to each other. What we really want is some notion of\n*similarity* between words. Why? Let's see an example.\n\nSuppose we are building a language model. Suppose we have seen the\nsentences\n\n* The mathematician ran to the store.\n* The physicist ran to the store.\n* The mathematician solved the open problem.\n\nin our training data. Now suppose we get a new sentence never before\nseen in our training data:\n\n* The physicist solved the open problem.\n\nOur language model might do OK on this sentence, but wouldn't it be much\nbetter if we could use the following two facts:\n\n* We have seen mathematician and physicist in the same role in a sentence. Somehow they\n have a semantic relation.\n* We have seen mathematician in the same role in this new unseen sentence\n as we are now seeing physicist.\n\nand then infer that physicist is actually a good fit in the new unseen\nsentence? This is what we mean by a notion of similarity: we mean\n*semantic similarity*, not simply having similar orthographic\nrepresentations. It is a technique to combat the sparsity of linguistic\ndata, by connecting the dots between what we have seen and what we\nhaven't. This example of course relies on a fundamental linguistic\nassumption: that words appearing in similar contexts are related to each\nother semantically. This is called the `distributional\nhypothesis <https://en.wikipedia.org/wiki/Distributional_semantics>`__.\n\n\nGetting Dense Word Embeddings\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nHow can we solve this problem? That is, how could we actually encode\nsemantic similarity in words? Maybe we think up some semantic\nattributes. For example, we see that both mathematicians and physicists\ncan run, so maybe we give these words a high score for the \"is able to\nrun\" semantic attribute. Think of some other attributes, and imagine\nwhat you might score some common words on those attributes.\n\nIf each attribute is a dimension, then we might give each word a vector,\nlike this:\n\n\\begin{align}q_\\text{mathematician} = \\left[ \\overbrace{2.3}^\\text{can run},\n \\overbrace{9.4}^\\text{likes coffee}, \\overbrace{-5.5}^\\text{majored in Physics}, \\dots \\right]\\end{align}\n\n\\begin{align}q_\\text{physicist} = \\left[ \\overbrace{2.5}^\\text{can run},\n \\overbrace{9.1}^\\text{likes coffee}, \\overbrace{6.4}^\\text{majored in Physics}, \\dots \\right]\\end{align}\n\nThen we can get a measure of similarity between these words by doing:\n\n\\begin{align}\\text{Similarity}(\\text{physicist}, \\text{mathematician}) = q_\\text{physicist} \\cdot q_\\text{mathematician}\\end{align}\n\nAlthough it is more common to normalize by the lengths:\n\n\\begin{align}\\text{Similarity}(\\text{physicist}, \\text{mathematician}) = \\frac{q_\\text{physicist} \\cdot q_\\text{mathematician}}\n {\\| q_\\text{\\physicist} \\| \\| q_\\text{mathematician} \\|} = \\cos (\\phi)\\end{align}\n\nWhere $\\phi$ is the angle between the two vectors. That way,\nextremely similar words (words whose embeddings point in the same\ndirection) will have similarity 1. Extremely dissimilar words should\nhave similarity -1.\n\n\nYou can think of the sparse one-hot vectors from the beginning of this\nsection as a special case of these new vectors we have defined, where\neach word basically has similarity 0, and we gave each word some unique\nsemantic attribute. These new vectors are *dense*, which is to say their\nentries are (typically) non-zero.\n\nBut these new vectors are a big pain: you could think of thousands of\ndifferent semantic attributes that might be relevant to determining\nsimilarity, and how on earth would you set the values of the different\nattributes? Central to the idea of deep learning is that the neural\nnetwork learns representations of the features, rather than requiring\nthe programmer to design them herself. So why not just let the word\nembeddings be parameters in our model, and then be updated during\ntraining? This is exactly what we will do. We will have some *latent\nsemantic attributes* that the network can, in principle, learn. Note\nthat the word embeddings will probably not be interpretable. That is,\nalthough with our hand-crafted vectors above we can see that\nmathematicians and physicists are similar in that they both like coffee,\nif we allow a neural network to learn the embeddings and see that both\nmathematicians and physicists have a large value in the second\ndimension, it is not clear what that means. They are similar in some\nlatent semantic dimension, but this probably has no interpretation to\nus.\n\n\nIn summary, **word embeddings are a representation of the *semantics* of\na word, efficiently encoding semantic information that might be relevant\nto the task at hand**. You can embed other things too: part of speech\ntags, parse trees, anything! The idea of feature embeddings is central\nto the field.\n\n\nWord Embeddings in Pytorch\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBefore we get to a worked example and an exercise, a few quick notes\nabout how to use embeddings in Pytorch and in deep learning programming\nin general. Similar to how we defined a unique index for each word when\nmaking one-hot vectors, we also need to define an index for each word\nwhen using embeddings. These will be keys into a lookup table. That is,\nembeddings are stored as a $|V| \\times D$ matrix, where $D$\nis the dimensionality of the embeddings, such that the word assigned\nindex $i$ has its embedding stored in the $i$'th row of the\nmatrix. In all of my code, the mapping from words to indices is a\ndictionary named word\\_to\\_ix.\n\nThe module that allows you to use embeddings is torch.nn.Embedding,\nwhich takes two arguments: the vocabulary size, and the dimensionality\nof the embeddings.\n\nTo index into this table, you must use torch.LongTensor (since the\nindices are integers, not floats).\n\n\n", "_____no_output_____" ] ], [ [ "# Author: Robert Guthrie\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntorch.manual_seed(1)", "_____no_output_____" ], [ "word_to_ix = {\"hello\": 0, \"world\": 1}\nembeds = nn.Embedding(2, 5) # 2 words in vocab, 5 dimensional embeddings\nlookup_tensor_hello = torch.tensor([word_to_ix[\"hello\"]], dtype=torch.long)\nhello_embed = embeds(lookup_tensor_hello)\nprint(\"hello_embed: \", hello_embed)\nlookup_tensor_world = torch.tensor([word_to_ix[\"world\"]], dtype=torch.long)\nworld_embed = embeds(lookup_tensor_world)\nprint(\"worlds_embed: \", world_embed)", "hello_embed: tensor([[-0.8923, -0.0583, -0.1955, -0.9656, 0.4224]], grad_fn=<EmbeddingBackward>)\nworlds_embed: tensor([[ 0.2673, -0.4212, -0.5107, -1.5727, -0.1232]], grad_fn=<EmbeddingBackward>)\n" ] ], [ [ "An Example: N-Gram Language Modeling\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nRecall that in an n-gram language model, given a sequence of words\n$w$, we want to compute\n\n\\begin{align}P(w_i | w_{i-1}, w_{i-2}, \\dots, w_{i-n+1} )\\end{align}\n\nWhere $w_i$ is the ith word of the sequence.\n\nIn this example, we will compute the loss function on some training\nexamples and update the parameters with backpropagation.\n\n\n", "_____no_output_____" ] ], [ [ "CONTEXT_SIZE = 5\nEMBEDDING_DIM = 10\n# We will use Shakespeare Sonnet 2\ntest_sentence = \"\"\"When forty winters shall besiege thy brow,\nAnd dig deep trenches in thy beauty's field,\nThy youth's proud livery so gazed on now,\nWill be a totter'd weed of small worth held:\nThen being asked, where all thy beauty lies,\nWhere all the treasure of thy lusty days;\nTo say, within thine own deep sunken eyes,\nWere an all-eating shame, and thriftless praise.\nHow much more praise deserv'd thy beauty's use,\nIf thou couldst answer 'This fair child of mine\nShall sum my count, and make my old excuse,'\nProving his beauty by succession thine!\nThis were to be new made when thou art old,\nAnd see thy blood warm when thou feel'st it cold.\"\"\".split()\n# we should tokenize the input, but we will ignore that for now\n# build a list of tuples. Each tuple is ([ word_i-2, word_i-1 ], target word)\nngrams = [([test_sentence[i + j] for j in range(CONTEXT_SIZE)], test_sentence[i + CONTEXT_SIZE]) \n for i in range(len(test_sentence) - CONTEXT_SIZE)]\n# trigrams = [([test_sentence[i], test_sentence[i + 1]], test_sentence[i + 2])\n# for i in range(len(test_sentence) - 2)]\nprint(\"the first 3 ngrams, just so you can see what they look like: \")\nprint(ngrams[:3])\nprint(\"the last 3 ngrams: \")\nprint(ngrams[-3:])\n\nvocab = set(test_sentence)\nword_to_ix = {word: i for i, word in enumerate(vocab)}\n\n\nclass NGramLanguageModeler(nn.Module):\n\n def __init__(self, vocab_size, embedding_dim, context_size):\n super(NGramLanguageModeler, self).__init__()\n self.embeddings = nn.Embedding(vocab_size, embedding_dim)\n self.linear1 = nn.Linear(context_size * embedding_dim, 128)\n self.linear2 = nn.Linear(128, vocab_size)\n\n def forward(self, inputs):\n embeds = self.embeddings(inputs).view((1, -1))\n out = F.relu(self.linear1(embeds))\n out = self.linear2(out)\n # print(\"out: \", out)\n log_probs = F.log_softmax(out, dim=1)\n # print(\"log probs: \", log_probs)\n return log_probs\n\n\nlosses = []\nloss_function = nn.NLLLoss()\nmodel = NGramLanguageModeler(len(vocab), EMBEDDING_DIM, CONTEXT_SIZE)\noptimizer = optim.SGD(model.parameters(), lr=0.001)\n\nfor epoch in range(1):\n total_loss = 0\n for context, target in ngrams:\n\n # Step 1. Prepare the inputs to be passed to the model (i.e, turn the words\n # into integer indices and wrap them in tensors)\n context_idxs = torch.tensor([word_to_ix[w] for w in context], dtype=torch.long)\n\n # Step 2. Recall that torch *accumulates* gradients. Before passing in a\n # new instance, you need to zero out the gradients from the old\n # instance\n model.zero_grad()\n\n # Step 3. Run the forward pass, getting log probabilities over next\n # words\n log_probs = model(context_idxs)\n\n # Step 4. Compute your loss function. (Again, Torch wants the target\n # word wrapped in a tensor)\n loss = loss_function(log_probs, torch.tensor([word_to_ix[target]], dtype=torch.long))\n\n # Step 5. Do the backward pass and update the gradient\n loss.backward()\n optimizer.step()\n\n # Get the Python number from a 1-element Tensor by calling tensor.item()\n total_loss += loss.item()\n losses.append(total_loss)\nprint(\"losses: \", losses)\nprint(\"The loss decreased every iteration over the training data!\")", "the first 3 ngrams, just so you can see what they look like: \n[(['When', 'forty', 'winters', 'shall', 'besiege'], 'thy'), (['forty', 'winters', 'shall', 'besiege', 'thy'], 'brow,'), (['winters', 'shall', 'besiege', 'thy', 'brow,'], 'And')]\nthe last 3 ngrams: \n[(['thy', 'blood', 'warm', 'when', 'thou'], \"feel'st\"), (['blood', 'warm', 'when', 'thou', \"feel'st\"], 'it'), (['warm', 'when', 'thou', \"feel'st\", 'it'], 'cold.')]\nlosses: [506.0660638809204]\nThe loss decreased every iteration over the training data!\n" ] ], [ [ "Exercise: Computing Word Embeddings: Continuous Bag-of-Words\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe Continuous Bag-of-Words model (CBOW) is frequently used in NLP deep\nlearning. It is a model that tries to predict words given the context of\na few words before and a few words after the target word. This is\ndistinct from language modeling, since CBOW is not sequential and does\nnot have to be probabilistic. Typcially, CBOW is used to quickly train\nword embeddings, and these embeddings are used to initialize the\nembeddings of some more complicated model. Usually, this is referred to\nas *pretraining embeddings*. It almost always helps performance a couple\nof percent.\n\nThe CBOW model is as follows. Given a target word $w_i$ and an\n$N$ context window on each side, $w_{i-1}, \\dots, w_{i-N}$\nand $w_{i+1}, \\dots, w_{i+N}$, referring to all context words\ncollectively as $C$, CBOW tries to minimize\n\n\\begin{align}-\\log p(w_i | C) = -\\log \\text{Softmax}(A(\\sum_{w \\in C} q_w) + b)\\end{align}\n\nwhere $q_w$ is the embedding for word $w$.\n\nImplement this model in Pytorch by filling in the class below. Some\ntips:\n\n* Think about which parameters you need to define.\n* Make sure you know what shape each operation expects. Use .view() if you need to\n reshape.\n\n\n", "_____no_output_____" ] ], [ [ "CONTEXT_SIZE = 2 # 2 words to the left, 2 to the right\nEMBEDDING_DIM = 10\nraw_text = \"\"\"We are about to study the idea of a computational process.\nComputational processes are abstract beings that inhabit computers.\nAs they evolve, processes manipulate other abstract things called data.\nThe evolution of a process is directed by a pattern of rules\ncalled a program. People create programs to direct processes. In effect,\nwe conjure the spirits of the computer with our spells.\"\"\".split()\n\n# By deriving a set from `raw_text`, we deduplicate the array\nvocab = set(raw_text)\nvocab_size = len(vocab)\n\nword_to_ix = {word: i for i, word in enumerate(vocab)}\ndata = []\nfor i in range(2, len(raw_text) - 2):\n context = [raw_text[i - 2], raw_text[i - 1],\n raw_text[i + 1], raw_text[i + 2]]\n target = raw_text[i]\n data.append((context, target))\nprint(data[:5])\n\n\nclass CBOW(nn.Module):\n\n def __init__(self, vocab_size, embedding_dim):\n super(CBOW, self).__init__()\n self.embeddings = nn.Embedding(vocab_size, embedding_dim)\n self.linear = nn.Linear(embedding_dim, vocab_size)\n\n def forward(self, inputs):\n embeds = self.embeddings(inputs)\n # print(\"embeds: \", embeds)\n qsum = torch.sum(embeds, dim=0)\n # print(\"qsum: \", qsum)\n out = self.linear(qsum)\n # print(\"out: \", out)\n log_probs = F.log_softmax(out, dim=0)\n # print(\"log probs: \", log_probs)\n return log_probs\n\n# create your model and train. here are some functions to help you make\n# the data ready for use by your module\n\n\ndef make_context_vector(context, word_to_ix):\n idxs = [word_to_ix[w] for w in context]\n return torch.tensor(idxs, dtype=torch.long)\n\n\ncontext_vector = make_context_vector(data[0][0], word_to_ix) # example\nprint(\"context vector: \", context_vector)\n\nlosses = []\nloss_function = nn.NLLLoss()\nmodel = CBOW(len(vocab), EMBEDDING_DIM)\noptimizer = optim.SGD(model.parameters(), lr=0.001)\n\nfor epoch in range(10):\n total_loss = 0\n for context, target in data:\n\n # Step 1. Prepare the inputs to be passed to the model (i.e, turn the words\n # into integer indices and wrap them in tensors)\n # context_idxs = torch.tensor([word_to_ix[w] for w in context], dtype=torch.long)\n context_idxs = make_context_vector(context, word_to_ix)\n\n # Step 2. Recall that torch *accumulates* gradients. Before passing in a\n # new instance, you need to zero out the gradients from the old\n # instance\n model.zero_grad()\n\n # Step 3. Run the forward pass, getting log probabilities over next\n # words\n log_probs = model(context_idxs)\n\n # Step 4. Compute your loss function. (Again, Torch wants the target\n # word wrapped in a tensor)\n # loss_function requires a minibatch index - here we have only 1\n loss = loss_function(log_probs.unsqueeze(0), torch.tensor([word_to_ix[target]], dtype=torch.long))\n\n # Step 5. Do the backward pass and update the gradient\n loss.backward()\n optimizer.step()\n\n # Get the Python number from a 1-element Tensor by calling tensor.item()\n total_loss += loss.item()\n losses.append(total_loss)\nprint(losses) # The loss decreased every iteration over the training data!", "[(['We', 'are', 'to', 'study'], 'about'), (['are', 'about', 'study', 'the'], 'to'), (['about', 'to', 'the', 'idea'], 'study'), (['to', 'study', 'idea', 'of'], 'the'), (['study', 'the', 'of', 'a'], 'idea')]\ncontext vector: tensor([41, 15, 12, 30])\n[256.88402342796326, 253.96123218536377, 251.09937977790833, 248.29585433006287, 245.548273563385, 242.8544623851776, 240.2124011516571, 237.6202473640442, 235.07628321647644, 232.57891368865967]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb0ddb0166f7dbefebf039754519261d80329753
415,907
ipynb
Jupyter Notebook
notebooks/Evaluations/Continuous_Timeseries/King_County/Hourly_Timeseries/PointWilliams/2018_PointWilliams_Timeseries.ipynb
SalishSeaCast/analysis-keegan
64eb44809a6581c210d02087c11b92a382945529
[ "Apache-2.0" ]
null
null
null
notebooks/Evaluations/Continuous_Timeseries/King_County/Hourly_Timeseries/PointWilliams/2018_PointWilliams_Timeseries.ipynb
SalishSeaCast/analysis-keegan
64eb44809a6581c210d02087c11b92a382945529
[ "Apache-2.0" ]
null
null
null
notebooks/Evaluations/Continuous_Timeseries/King_County/Hourly_Timeseries/PointWilliams/2018_PointWilliams_Timeseries.ipynb
SalishSeaCast/analysis-keegan
64eb44809a6581c210d02087c11b92a382945529
[ "Apache-2.0" ]
null
null
null
613.432153
104,312
0.948811
[ [ [ "This notebook will hopefully contain timeseries that plot continuous data from moorings alongside model output. ", "_____no_output_____" ] ], [ [ "import sys\nsys.path.append('/ocean/kflanaga/MEOPAR/analysis-keegan/notebooks/Tools')", "_____no_output_____" ], [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nimport netCDF4 as nc\nimport xarray as xr\nimport datetime as dt\nfrom salishsea_tools import evaltools as et, viz_tools\nimport gsw \nimport matplotlib.gridspec as gridspec\nimport matplotlib as mpl\nimport matplotlib.dates as mdates\nimport cmocean as cmo\nimport scipy.interpolate as sinterp\nimport pickle\nimport cmocean\nimport json\nimport f90nml\nimport Keegan_eval_tools as ket\nfrom collections import OrderedDict\nfrom matplotlib.colors import LogNorm\n\nfs=16\nmpl.rc('xtick', labelsize=fs)\nmpl.rc('ytick', labelsize=fs)\nmpl.rc('legend', fontsize=fs)\nmpl.rc('axes', titlesize=fs)\nmpl.rc('axes', labelsize=fs)\nmpl.rc('figure', titlesize=fs)\nmpl.rc('font', size=fs)\nmpl.rc('font', family='sans-serif', weight='normal', style='normal')\n\nimport warnings\n#warnings.filterwarnings('ignore')\nfrom IPython.display import Markdown, display\n\n%matplotlib inline", "_____no_output_____" ], [ "saveloc='/ocean/kflanaga/MEOPAR/savedData/King_CountyData/hourly_pickle_files'\nyear=2019\nMooring='PointWilliams'", "_____no_output_____" ], [ "# Parameters\nsaveloc = \"/ocean/kflanaga/MEOPAR/savedData/King_CountyData/hourly_pickle_files\"\nyear = 2018\nMooring = \"PointWilliams\"\n", "_____no_output_____" ], [ "##### Loading in pickle file data\nwith open(os.path.join(saveloc,f'hourly_data_{Mooring}_{year}.pkl'),'rb') as hh:\n data=pickle.load(hh)", "_____no_output_____" ], [ "grid=xr.open_mfdataset(f'/ocean/kflanaga/MEOPAR/savedData/201905_grid_data/ts_HC201905_{year}_{Mooring}.nc')", "_____no_output_____" ], [ "%%time\ntt=grid.time_centered\nvot=grid.votemper.isel(deptht=0,y=0,x=0)\nvos=grid.vosaline.isel(deptht=0,y=0,x=0)", "CPU times: user 1.54 ms, sys: 488 µs, total: 2.03 ms\nWall time: 2.03 ms\n" ], [ "obsvar='CT'\nfig,ax=plt.subplots(1,1,figsize=(14,7))\n\nps=[]\np0,=ax.plot(data['dtUTC'],data[obsvar],'.',color='blue',label=f'Observed ')\nps.append(p0)\np0,=ax.plot(tt,vot,'-',color='red',label='Modeled')\nps.append(p0)\nax.legend(handles=ps)\nax.set_ylabel(f'{obsvar}')\nax.set_xlabel('Date')\nax.set_title('Temperature timeseries')\nplt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')\nM = 15\nxticks = mpl.ticker.MaxNLocator(M)\nax.xaxis.set_major_locator(xticks)\nyearsFmt = mdates.DateFormatter('%d %b %y')\nax.xaxis.set_major_formatter(yearsFmt)", "_____no_output_____" ], [ "obsvar='SA'\nfig,ax=plt.subplots(1,1,figsize=(14,7))\n\nps=[]\np0,=ax.plot(data['dtUTC'],data[obsvar],'.',color='blue',label=f'Observed')\nps.append(p0)\np0,=ax.plot(tt,vos,'-',color='red',label='Modeled')\nps.append(p0)\nax.legend(handles=ps)\nax.set_ylabel(f'{obsvar}')\nax.set_xlabel('Date')\nax.set_title('Salinity timeseries')\nplt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')\nM = 15\nxticks = mpl.ticker.MaxNLocator(M)\nax.xaxis.set_major_locator(xticks)\nyearsFmt = mdates.DateFormatter('%d %b %y')\nax.xaxis.set_major_formatter(yearsFmt)", "_____no_output_____" ], [ "grid.close()", "_____no_output_____" ], [ "bio=xr.open_mfdataset(f'/ocean/kflanaga/MEOPAR/savedData/201905_ptrc_data/ts_HC201905_{year}_{Mooring}.nc')", "_____no_output_____" ], [ "ik=0\nij=0\nii=0", "_____no_output_____" ], [ "%%time\ntt=bio.time_counter\nmod_nitrate=(bio.nitrate.isel(deptht=ik,y=ij,x=ii))\ndiatom=bio.diatoms.isel(deptht=ik,y=ij,x=ii)\nflagellate=bio.flagellates.isel(deptht=ik,y=ij,x=ii)\nciliate=bio.ciliates.isel(deptht=ik,y=ij,x=ii)\nmod_Chl=(diatom+flagellate+ciliate)*1.8", "CPU times: user 6.18 ms, sys: 595 µs, total: 6.78 ms\nWall time: 6.56 ms\n" ], [ "data.columns", "_____no_output_____" ], [ "obsvar='Chl'\nmodvar=mod_Chl\nfig,ax=plt.subplots(1,1,figsize=(14,7))\n\nps=[]\np0,=ax.plot(data['dtUTC'],data[obsvar],'.',color='blue',label=f'Observed ')\nps.append(p0)\np0,=ax.plot(tt,modvar,'-',color='red',label='Modeled')\nps.append(p0)\nax.legend(handles=ps)\nax.set_ylabel(f'{obsvar}')\nax.set_xlabel('Date')\nax.set_title('Chlorophyll Timeseries')\nplt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')\nM = 15\nxticks = mpl.ticker.MaxNLocator(M)\nax.xaxis.set_major_locator(xticks)\nyearsFmt = mdates.DateFormatter('%d %b %y')\nax.xaxis.set_major_formatter(yearsFmt)", "_____no_output_____" ], [ "obsvar='NO23'\nmodvar=mod_nitrate\nfig,ax=plt.subplots(1,1,figsize=(14,7))\n\nps=[]\np0,=ax.plot(data['dtUTC'],data[obsvar],'.',color='blue',label=f'Observed ')\nps.append(p0)\np0,=ax.plot(tt,modvar,'-',color='red',label='Modeled')\nps.append(p0)\nax.legend(handles=ps)\nax.set_ylabel(f'{obsvar}')\nax.set_ylim((0,40))\nax.set_xlabel('Date')\nax.set_title('Chlorophyll Timeseries')\nplt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')\nM = 15\nxticks = mpl.ticker.MaxNLocator(M)\nax.xaxis.set_major_locator(xticks)\nyearsFmt = mdates.DateFormatter('%d %b %y')\nax.xaxis.set_major_formatter(yearsFmt)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0df9ac78a09c7db758986f68e527faa5a99415
64,452
ipynb
Jupyter Notebook
PlotBot/Plot_Bot.ipynb
brgjap11/social_analytics
30db07f07c00f4c99d95ddbb79b1be3c849064ab
[ "ADSL" ]
null
null
null
PlotBot/Plot_Bot.ipynb
brgjap11/social_analytics
30db07f07c00f4c99d95ddbb79b1be3c849064ab
[ "ADSL" ]
null
null
null
PlotBot/Plot_Bot.ipynb
brgjap11/social_analytics
30db07f07c00f4c99d95ddbb79b1be3c849064ab
[ "ADSL" ]
null
null
null
145.162162
48,292
0.851704
[ [ [ "# Dependencies\nimport tweepy\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport time\nfrom pprint import pprint\n# Import and Initialize Sentiment Analyzer\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nanalyzer = SentimentIntensityAnalyzer()\n\n#import Twitter API keys\nfrom bot_config import access_token,access_token_secret,consumer_key,consumer_secret", "_____no_output_____" ], [ "# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())", "_____no_output_____" ], [ "#target_handle\n# Search through bot tweets for new handles to analyze\n#bot =\"@brgrave1_graves\"\n#public_tweets = api.user_timeline(bot)\n\n#pprint(public_tweets)", "_____no_output_____" ], [ "print(tweet[\"in_reply_to_screen_name\"])", "CNN\n" ], [ "#define target search from twitter bots account \n#target_search= (\"@brgrave1_graves:@%s\" % handle_requested)\n\n\n# Search for all tweets\n#public_tweets=api.status_lookup(target_search,show_user=True)\n#pprint(public_tweets)", "_____no_output_____" ], [ "#scan my account for new analysis to run\ndef Scan_Account():\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\n\n# Search for all tweets\npublic_tweets=api.user_timeline()\n# Loop through all tweets\nfor tweet in public_tweets:\n # Get ID and Author of most recent tweet directed to me\n tweet_id = tweet[\"id\"]\n tweet_author = tweet[\"user\"][\"screen_name\"]\n handle_requested = tweet[\"in_reply_to_screen_name\"]\n # Use Try-Except to avoid the duplicate error\n try:\n # Respond to tweet & perform sentiment analysis\n target_handle = (\"@%s\" % handle_requested)\n # Counter\n counter = 1\n # Variables for holding sentiments\n compound_sentiments = []\n tweets_ago = []\n # Loop through 5 pages of tweets (total 100 tweets)\n for x in range(5):\n # Get all tweets from home feed\n public_tweets = api.user_timeline(target_handle)\n # Loop through all tweets \n for tweet in public_tweets: \n # Run Vader Analysis on each tweet\n compound = analyzer.polarity_scores(tweet[\"text\"])[\"compound\"]\n pos = analyzer.polarity_scores(tweet[\"text\"])[\"pos\"]\n neu = analyzer.polarity_scores(tweet[\"text\"])[\"neu\"]\n neg = analyzer.polarity_scores(tweet[\"text\"])[\"neg\"]\n # Add to counter \n counter = counter + 1\n # Add sentiments for each tweet into an array\n compound_sentiments.append(compound)\n tweets_ago.append(counter)\n except Exception:\n print(\"Already responded to this one!\")\n # Print message if duplicate\n \n", "_____no_output_____" ], [ "#creating the chart function\ndef analysis_chart():\n \n sns.set()\n\n #creating chart\n plt.plot(tweets_ago, compound_sentiments, linewidth=0.5, marker=\"o\", color=\"blue\")\n # Add labels to the x and y axes\n plt.title(\"Sentiment Analysis of %s's tweets\" % target_handle)\n plt.ylabel(\"Tweet Polarity\")\n plt.xlabel(\"Tweets Ago\")\n #adding legend\n legend = (\"%s's tweets\" % tweet_author)\n plt.legend(legend, bbox_to_anchor=(1.1, 1), \n fancybox=True, shadow=True, ncol=1, loc='upper center', title=\"Tweets\")\n # Set a grid on the plot\n plt.grid(True)\n # Add a semi-transparent horizontal line at y = 0\n plt.hlines(0, 0, 10, alpha=0.9)\n plt.savefig(\"Sentiment Analysis of tweets.jpg\")\n\n # tweet analysis back to twitter \n api.update_with_media(\"Sentiment Analysis of tweets.jpg\")\n \n ", "_____no_output_____" ], [ "counter = 0\nfor counter in range(3):\n analysis_chart()\n time.sleep(60)\n", "_____no_output_____" ], [ "#scan my account for new analysis to run\ndef Scan_Account():\n # Setup Tweepy API Authentication\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n \n # Search for all tweets\n bot_tweets = api.search(bot, count=100, result_type=\"recent\")\n # Loop through all tweets\n for tweet in bot_tweets[\"statuses\"]:\n # Get ID and Author of most recent tweet directed to me\n tweet_id = tweet[\"id\"]\n tweet_author = tweet[\"user\"][\"screen_name\"]\n #create loop to check if analysis has been run on the target_handle by looping through ayalysis_already_run\n for tweet_author in handles_analyzed:\n if tweet_author == handles_analzyed:\n #tweet submitter of analysis this analysis has already been run\n api.udate_status(\"Sentiment Analysis has already beeen performed on @%s! Please feel free to submit another\"\n % tweet_author, reply_to_id=tweet_id)\n else:\n #add handle to list of analyzed twitter handles to not clutter timeline\n handles_analyzed.append(tweet_author)\n #perform sentiment analysis\n target_handle = (\"@%s!\" % tweet_author)\n # Counter\n counter = 1\n # Variables for holding sentiments\n handle_sentiments = []\n # Loop through 5 pages of tweets (total 100 tweets)\n for x in range(5):\n # Get all tweets from home feed\n public_tweets = api.user_timeline(target_handle)\n # Loop through all tweets \n for tweet in public_tweets: \n # Run Vader Analysis on each tweet\n compound = analyzer.polarity_scores(tweet[\"text\"])[\"compound\"]\n pos = analyzer.polarity_scores(tweet[\"text\"])[\"pos\"]\n neu = analyzer.polarity_scores(tweet[\"text\"])[\"neu\"]\n neg = analyzer.polarity_scores(tweet[\"text\"])[\"neg\"]\n tweets_ago = counter\n # Add sentiments for each tweet into an array\n handle_sentiments.append({\"Twitter Handle\":target_handle,\n \"Compound\": compound,\n \"Positive\": pos,\n \"Negative\": neu,\n \"Neutral\": neg,\n \"Tweets Ago\": counter}) \n # Add to counter \n counter = counter + 1\n \n\n \n ", "_____no_output_____" ], [ " for handle_requested in handles_analyzed:\n if handle_requested == handle_requested:\n #tweet submitter of analysis this analysis has already been run\n api.udate_status(\"Sentiment Analysis has already beeen performed on @%s! Please feel free to submit another\"\n % handle_requested,in_reply_to_status_id=tweet_id )\n else:\n #add handle to list of analyzed twitter handles to not clutter timeline\n handles_analyzed.append(handle_requested)", "_____no_output_____" ], [ "target_handle = (\"@%s\" % tweet_author)\n# Counter\ncounter = 1\n# Variables for holding sentiments\nbbc_sentiments = []\n# Loop through 5 pages of tweets (total 100 tweets)\nfor x in range(5):\n # Get all tweets from home feed\n public_tweets = api.user_timeline(target_handle)\n # Loop through all tweets \n for tweet in public_tweets: \n # Run Vader Analysis on each tweet\n compound = analyzer.polarity_scores(tweet[\"text\"])[\"compound\"]\n pos = analyzer.polarity_scores(tweet[\"text\"])[\"pos\"]\n neu = analyzer.polarity_scores(tweet[\"text\"])[\"neu\"]\n neg = analyzer.polarity_scores(tweet[\"text\"])[\"neg\"]\n tweets_ago = counter\n # Add sentiments for each tweet into an array\n bbc_sentiments.append({\"Media Source\":target_handle,\n \"Compound\": compound,\n \"Positive\": pos,\n \"Negative\": neu,\n \"Neutral\": neg,\n \"Date\": tweet[\"created_at\"],\n \"Tweets Ago\": counter,\n \"Tweet\": tweet[\"text\"]}) \n # Add to counter \n counter = counter + 1", "_____no_output_____" ], [ "\n#perform sentiment analysis\ntarget_handle = (\"@%s\" % handle_requested)\n# Counter\ncounter = 1\n# Variables for holding sentiments\ncompound_sentiments = []\ntweets_ago = []\n# Loop through 5 pages of tweets (total 100 tweets)\nfor x in range(5):\n # Get all tweets from home feed\n public_tweets = api.user_timeline(target_handle)\n # Loop through all tweets \n for tweet in public_tweets: \n # Run Vader Analysis on each tweet\n compound = analyzer.polarity_scores(tweet[\"text\"])[\"compound\"]\n pos = analyzer.polarity_scores(tweet[\"text\"])[\"pos\"]\n neu = analyzer.polarity_scores(tweet[\"text\"])[\"neu\"]\n neg = analyzer.polarity_scores(tweet[\"text\"])[\"neg\"]\n # Add to counter \n counter = counter + 1\n # Add sentiments for each tweet into an array\n compound_sentiments.append(compound)\n tweets_ago.append(counter)", "_____no_output_____" ], [ "# Create converse function\ndef Converse(line_number):\n\n # Find the latest tweet from conversation_partner\n public_tweets = api.search(conversation_partner, count=1, result_type=\"recent\")\n for tweet in public_tweets[\"statuses\"]:\n print(tweet)\n\n # Respond to the tweet with one of the response lines\n tweet_id = tweet[\"id\"]\n print(tweet_id)\n print(tweet[\"text\"])\n api.update_status(\n response_lines[line_number],\n in_reply_to_status_id=tweet_id)", "_____no_output_____" ], [ "# Create Thank You Function\ndef ThankYou():\n\n # Twitter Credentials\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\n # Search for all tweets\n public_tweets = api.search(target_term, count=100, result_type=\"recent\")\n\n # Loop through all tweets\n for tweet in public_tweets[\"statuses\"]:\n\n # Get ID and Author of most recent tweet directed to me\n tweet_id = tweet[\"id\"]\n tweet_author = tweet[\"user\"][\"screen_name\"]\n\n # Print the tweet_id\n print(tweet_id)\n\n # Use Try-Except to avoid the duplicate error\n try:\n # Respond to tweet\n api.update_status(\n \"Thank you @%s! Come again!\" %\n tweet_author,\n in_reply_to_status_id=tweet_id)\n\n # Print success message\n print(\"Successful response!\")\n\n except Exception: # Print message if duplicate\n print(\"Already responded to this one!\")\n\n # Print message to signify complete cycle\n print(\"We're done for now. I'll check again in 60 seconds.\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb0dffb9fad38d729d3810f7f5e2f66c4e859b49
10,375
ipynb
Jupyter Notebook
notebooks/radon-small/[prediction] On-line learning.ipynb
carldata/argo
a6bf8309121346f41796aec9739498fb07236f37
[ "Apache-2.0" ]
1
2018-02-14T19:15:28.000Z
2018-02-14T19:15:28.000Z
notebooks/radon-small/[prediction] On-line learning.ipynb
carldata/argo
a6bf8309121346f41796aec9739498fb07236f37
[ "Apache-2.0" ]
18
2018-01-19T11:26:53.000Z
2018-03-15T11:50:26.000Z
notebooks/radon-small/[prediction] On-line learning.ipynb
carldata/argo
a6bf8309121346f41796aec9739498fb07236f37
[ "Apache-2.0" ]
null
null
null
24.820574
118
0.50612
[ [ [ "# Online prediction for radon-small\n\nIn online mode, the model is learning as soon as a new data arrives.\nIt means that when we want our prediction we don't need to provide feature vector, \nsince all data was already processed by the model.\n\nExplore the following models:\n\n * Constant model - The same value for all future points\n * Previous day model - Next day is the same like previous day\n * Daily Pattern model - Calculate daily pattern from historical data. Use it as next day prediction.", "_____no_output_____" ] ], [ [ "import datetime\nimport calendar\nimport pprint\nimport json\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nrcParams['figure.figsize'] = 12, 4", "_____no_output_____" ] ], [ [ "# Load project", "_____no_output_____" ] ], [ [ "project_folder = '../../datasets/radon-small/'\nwith open(project_folder + 'project.json', 'r') as file:\n project = json.load(file)\npprint.pprint(project)\nprint('Flow1')\nflow = pd.read_csv(project_folder + 'flow1.csv', parse_dates=['time'])\nflow = flow.set_index('time')['flow'].fillna(0)\nflow = flow.resample('5T').pad()\nflow.head()", "{'end-date': '2017-11-09',\n 'flows': ['flow1'],\n 'name': 'radon-small',\n 'rainfalls': [],\n 'split-date': '2016-11-09',\n 'start-date': '2013-10-01'}\nFlow1\n" ] ], [ [ "## Helper functions\n\nHelper functions for building training and test sets and calculating score", "_____no_output_____" ] ], [ [ "class PredictionModel:\n \n def fit(self, data_points):\n pass\n \n def predict(self, prediction_day):\n pass\n\n \ndef mae(y_hat, y):\n \"\"\"\n Calculate Mean Absolute Error \n This metric is better here since serries have quite big outliers\n \"\"\"\n return np.sum(np.absolute(y_hat-y))/y.shape[0]\n\n\ndef split_data(split_day):\n \"\"\"Get all data up to given day\"\"\"\n end_day = split_day - pd.Timedelta('1 min')\n return flow[:end_day]\n\n\ndef evaluate_day(model, split_day):\n \"\"\"Evaluate data for single day\"\"\"\n xs = split_data(split_day)\n next_day = split_day + pd.Timedelta(1, 'D')\n y = flow[next_day: next_day+pd.Timedelta('1439 min')]\n model.fit(xs)\n y_hat = model.predict(next_day)\n return mae(y_hat, y)\n\n\ndef evaluate_model(model, start_day):\n \"\"\"\n Evaluate model on all days starting from split_day.\n Returns 90th percentile error as model score\n \"\"\"\n last_day = pd.Timestamp(project['end-date'])\n split_day = start_day\n costs = []\n while split_day < last_day:\n cost = evaluate_day(model, split_day)\n costs.append(cost)\n split_day += pd.Timedelta(1, 'D')\n return np.percentile(costs, 90), costs\n\n\nsplit_data(pd.Timestamp('2016-11-10')).tail()", "_____no_output_____" ] ], [ [ "# Models\n\n# ConstMeanModel", "_____no_output_____" ] ], [ [ "class ConstantMeanModel(PredictionModel):\n \n def __init__(self):\n self.mu = 0\n \n def fit(self, xs):\n self.mu = np.mean(xs)\n \n def predict(self, day):\n return np.ones(12*24) * self.mu \n\n \nscore, costs = evaluate_model(ConstantMeanModel(), pd.Timestamp('2016-11-11'))\nprint('ConstantMeanModel score: {:.2f}'.format(score))", "ConstantMeanModel score: 18.86\n" ] ], [ [ "## Previous Day Model\n\nUses values from last day", "_____no_output_____" ] ], [ [ "class LastDayModel(PredictionModel):\n \n def fit(self, xs):\n self.y = xs.values[-288:]\n \n def predict(self, day):\n return self.y\n\n \nscore, costs = evaluate_model(LastDayModel(), pd.Timestamp('2016-11-11'))\nprint('LastDayModel score: {:.2f}'.format(score))", "LastDayModel score: 11.99\n" ] ], [ [ "Model for single day. Easy case", "_____no_output_____" ] ], [ [ "evaluate_day(LastDayModel(), pd.Timestamp('2016-11-11'))", "_____no_output_____" ] ], [ [ "And when next day is kind of outlier", "_____no_output_____" ] ], [ [ "evaluate_day(LastDayModel(), pd.Timestamp('2017-05-01'))", "_____no_output_____" ] ], [ [ "## Daily Pattern model\n\nCreate pattern of daily usage based on historical data. Use this pattern to predict next values\n\n(This can take up to 10 minutes to calculate)", "_____no_output_____" ] ], [ [ "class DailyPatternModel(PredictionModel):\n \n def fit(self, xs):\n df = flow.to_frame().reset_index()\n self.daily_pattern = df.groupby(by=[df.time.map(lambda x : (x.hour, x.minute))]).flow.mean().values\n \n def predict(self, day):\n return self.daily_pattern\n\n \nscore, costs = evaluate_model(DailyPatternModel(), pd.Timestamp('2016-11-11'))\nprint('DailyPatternModel score: {:.2f}'.format(score))", "DailyPatternModel score: 9.61\n" ] ], [ [ "### Daily Pattern Median Model\nCalculate median value for each time. Use it as a prediction for the next day.", "_____no_output_____" ] ], [ [ "class DayMedianModel(PredictionModel):\n \n def fit(self, xs):\n df = flow.to_frame().reset_index()\n self.daily_pattern = df.groupby(by=[df.time.map(lambda x : (x.hour, x.minute))]).flow.median().values\n \n def predict(self, day):\n return self.daily_pattern\n\n \nscore, costs = evaluate_model(DayMedianModel(), pd.Timestamp('2016-11-11'))\nprint('DayModel score: {:.2f}'.format(score))", "DayModel score: 9.73\n" ] ], [ [ "## Daily pattern with last value correction\n\nThis model calculates daily pattern, but also corrects it based on previous value\n\n$$ x_{t} = \\alpha (x_{t-1} - dp(t-1)) + dp(t)$$\n\nwhere\n - dp - daily pattern", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]