markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Load diabetes data setFrom [sklearn diabetes data set](https://scikit-learn.org/stable/datasets/toy_dataset.htmldiabetes-dataset):"Ten baseline variables, age, sex, body mass index, average blood pressure, and six blood serum measurements were obtained for each of n = 442 diabetes patients, as well as the response of ...
d = load_diabetes() len(d.data) df = pd.DataFrame(d.data, columns=d.feature_names) df['disease'] = d.target # "quantitative measure of disease progression one year after baseline" df.head(3)
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Split data into train, validation setsAny sufficiently powerful model is able to effectively drive down the training loss (error). What we really care about, though, is how well the model generalizes. That means we have to look at the validation or test error, computed from records the model was not trained on. (We'll...
np.random.seed(1) # set a random seed for consistency across runs n = len(df) X = df.drop('disease',axis=1).values y = df['disease'].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20) # hold out 20% len(X), len(X_train), len(X_test)
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Let's also make sure to normalize the data to make training easier:
m = np.mean(X_train,axis=0) std = np.std(X_train,axis=0) X_train = (X_train-m)/std X_test = (X_test-m)/std # use training data only when prepping test sets
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Baseline with random forestWhen building machine learning models, it's always important to ask how good your model is. One of the best ways is to choose a baseline model, such as a random forest or a linear regression model, and compare your new model to make sure it can beat the old model. Random forests are easy to...
rf = RandomForestRegressor(n_estimators=100, n_jobs=-1, min_samples_leaf=20) rf.fit(X_train, y_train.reshape(-1))
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
To evaluate our models, let's compute the mean squared error (MSE) for both training and validation sets:
y_pred = rf.predict(X_train) mse = np.mean((y_pred - y_train.reshape(-1))**2) y_pred_test = rf.predict(X_test) mse_test = np.mean((y_pred_test - y_test.reshape(-1))**2) print(f"Training MSE {mse:.2f} validation MSE {mse_test:.2f}")
Training MSE 2533.91 validation MSE 3473.22
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Let's check $R^2$ as well.
rf.score(X_train, y_train), rf.score(X_test, y_test)
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
ExerciseWhy is the validation error much larger than the training error?Solution Because the model was trained on the training set, one would expect it to generally perform better on it than any other data set. The more the validation error diverges from the training error, the less general you should assume your ...
def train0(model, X_train, y_train, learning_rate = .5, nepochs=2000): optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) for epoch in range(nepochs+1): y_pred = model(X_train) loss = torch.mean((y_pred - y_train)**2) if epoch % (nepochs//10) == 0: p...
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
To use this method, we have to convert the training and validation data sets to pytorch tensors from numpy (they are already normalized):
X_train = torch.tensor(X_train).float() X_test = torch.tensor(X_test).float() y_train = torch.tensor(y_train).float().reshape(-1,1) # column vector y_test = torch.tensor(y_test).float().reshape(-1,1)
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Let's create a model with one hidden layer and an output layer, glued together with a ReLU nonlinearity. The network looks something like the following except of course we have many more input features and neurons than shown here:There is an implied input layer which is really just the input vector of features. The ou...
ncols = X.shape[1] n_neurons = 150 model = nn.Sequential( nn.Linear(ncols, n_neurons), # hidden layer nn.ReLU(), # nonlinearity nn.Linear(n_neurons, 1) # output layer ) train0(model, X_train, y_train, learning_rate=.08, nepochs=5000)
Epoch 0 MSE train loss 29693.615 Epoch 500 MSE train loss 552.236 Epoch 1000 MSE train loss 85.343 Epoch 1500 MSE train loss 25.167 Epoch 2000 MSE train loss 120.147 Epoch 2500 MSE train loss 9.741 Epoch 3000 MSE train loss 14.483 Epoch 3500 MSE train loss 3.674 Epoch 40...
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Run this a few times and you'll see that we can drive the training error very close to zero with 150 neurons and many iterations (epochs). Compare this to the RF training MSE which is orders of magnitude bigger (partly due to the `min_samples_leaf` hyperparameter). ExerciseWhy does the training loss sometimes pop up ...
ncols = X.shape[1] n_neurons = 150 model = nn.Sequential( nn.Linear(ncols, n_neurons), # hidden layer nn.ReLU(), # nonlinearity nn.Linear(n_neurons, 1) # output layer ) train0(model, X_train, y_train, learning_rate=.017, nepochs=15000)
Epoch 0 MSE train loss 29626.404 Epoch 1500 MSE train loss 1588.800 Epoch 3000 MSE train loss 264.717 Epoch 4500 MSE train loss 64.575 Epoch 6000 MSE train loss 17.353 Epoch 7500 MSE train loss 6.367 Epoch 9000 MSE train loss 2.682 Epoch 10500 MSE train loss 0.691 Epoch 1...
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Notice now that we can reliably drive that training error down to zero without bouncing around, although it takes longer with the smaller learning rate. ExercisePlay around with the learning rate and nepochs to see how fast you can reliably get MSE down to 0. Tracking validation lossA low training error doesn't reall...
def train1(model, X_train, X_test, y_train, y_test, learning_rate = .5, nepochs=2000): optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) history = [] # track training and validation loss for epoch in range(nepochs+1): y_pred = model(X_train) loss = torch.mean((y_p...
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Let's create the exact same model that we had before but plot train/validation errors against the number of epochs:
ncols = X.shape[1] n_neurons = 150 model = nn.Sequential( nn.Linear(ncols, n_neurons), nn.ReLU(), nn.Linear(n_neurons, 1) ) history = train1(model, X_train, X_test, y_train, y_test, learning_rate=.02, nepochs=8000) plot_history(torch.clamp(history, 0, 12000), file="train-test")
Epoch 0 MSE train loss 29654.730 test loss 27063.545 Epoch 800 MSE train loss 1841.183 test loss 3583.445 Epoch 1600 MSE train loss 806.315 test loss 5304.467 Epoch 2400 MSE train loss 286.301 test loss 7847.571 Epoch 3200 MSE train loss 98.467 test loss 9669.961 ...
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Wow. The validation error is much much worse than the training error, which is almost 0. That tells us that the model is severely overfit to the training data and is not general at all. Well, the validation error actually makes a lot of progress initially but then after a few thousand epochs immediately starts to grow ...
def train2(model, X_train, X_test, y_train, y_test, learning_rate = .5, nepochs=2000, weight_decay=0): optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay) history = [] # track training and validation loss best_loss = 1e10 ...
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Let's use the exact same model and learning rate with no weight decay and see what happens.
ncols = X.shape[1] n_neurons = 150 model = nn.Sequential( nn.Linear(ncols, n_neurons), nn.ReLU(), nn.Linear(n_neurons, 1) ) history, best_model = train2(model, X_train, X_test, y_train, y_test, learning_rate=.02, nepochs=1000, weight_decay=0) # ver...
Epoch 0 MSE train loss 29607.461 test loss 27006.693 Epoch 100 MSE train loss 2629.585 test loss 3087.739 Epoch 200 MSE train loss 2384.102 test loss 3186.564 Epoch 300 MSE train loss 2285.357 test loss 3230.039 Epoch 400 MSE train loss 2208.642 test loss 3257.470 ...
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Let's also look at $R^2$:
y_pred = best_model(X_train).detach().numpy() y_pred_test = best_model(X_test).detach().numpy() r2_score(y_train, y_pred), r2_score(y_test, y_pred_test)
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
The best MSE bounces around a loss value of 3000 from run to run, a bit above it or a bit below, depending on the run. And this decent result occurs without having to understand or use weight decay (more on this next). Compare the validation R^2 to that of the RF; the network does much better! Weight decay to reduce...
def train3(model, X_train, X_test, y_train, y_test, learning_rate = .5, nepochs=2000, weight_decay=0, trace=True): optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay) history = [] # track training and validation loss for e...
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
How do we know what the right value of the weight decay is? Typically we try a variety of weight decay values and then see which one gives us the best validation error, so let's do that using a grid of images. The following loop uses the same network and learning rate for each run but varies the weight decay:
ncols = X.shape[1] n_neurons = 150 fig, axes = plt.subplots(1, 4, figsize=(12.5,2.5)) for wd,ax in zip([0,.3,.6,1.5],axes): model = nn.Sequential( nn.Linear(ncols, n_neurons), nn.ReLU(), nn.Linear(n_neurons, 1) ) history = train3(model, X_train, X_test, y_train, y_test, ...
_____no_output_____
MIT
notebooks/deep-learning/3.train-test-diabetes.ipynb
edithlee972/msds621
Simple AttackIn this notebook, we will examine perhaps the simplest possible attack on an individual's private data and what the OpenDP library can do to mitigate it. Loading the dataThe vetting process is currently underway for the code in the OpenDP Library.Any constructors that have not been vetted may still be acc...
import numpy as np from opendp.mod import enable_features enable_features('contrib')
_____no_output_____
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
We begin with loading up the data.
import os data_path = os.path.join('.', 'data', 'PUMS_california_demographics_1000', 'data.csv') with open(data_path) as input_file: data = input_file.read() col_names = ["age", "sex", "educ", "race", "income", "married"] print(col_names) print('\n'.join(data.split('\n')[:6]))
['age', 'sex', 'educ', 'race', 'income', 'married'] 59,1,9,1,0,1 31,0,1,3,17000,0 36,1,11,1,0,1 54,1,11,1,9100,1 39,0,5,3,37000,0 34,0,9,1,0,1
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
The following code parses the data into a vector of incomes.More details on preprocessing can be found [here](https://github.com/opendp/opendp/blob/main/python/example/basic_data_analysis.ipynb).
from opendp.trans import make_split_dataframe, make_select_column, make_cast, make_impute_constant income_preprocessor = ( # Convert data into a dataframe where columns are of type Vec<str> make_split_dataframe(separator=",", col_names=col_names) >> # Selects a column of df, Vec<str> make_select_column...
[0.0, 17000.0, 0.0, 9100.0, 37000.0, 0.0, 6000.0]
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
A simple attackSay there's an attacker who's target is the income of the first person in our data (i.e. the first income in the csv). In our case, its simply `0` (but any number is fine, i.e. 5000).
person_of_interest = incomes[0] print('person of interest:\n\n{0}'.format(person_of_interest))
person of interest: 0.0
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
Now consider the case an attacker that doesn't know the POI income, but do know the following: (1) the average income without the POI income, and (2) the number of persons in the database.As we show next, if he would also get the average income (including the POI's one), by simple manipulation he can easily back out th...
# attacker information: everyone's else mean, and their count. known_mean = np.mean(incomes[1:]) known_obs = len(incomes) - 1 # assume the attackers know legitimately get the overall mean (and hence can infer the total count) overall_mean = np.mean(incomes) n_obs = len(incomes) # back out POI's income poi_income = ov...
poi_income: 0.0
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
The attacker now knows with certainty that the POI has an income of $0. Using OpenDPLet's see what happens if the attacker were made to interact with the data through OpenDP and was given a privacy budget of $\epsilon = 1$.We will assume that the attacker is reasonably familiar with differential privacy and believes th...
from opendp.trans import make_clamp, make_sized_bounded_mean, make_bounded_resize from opendp.meas import make_base_laplace enable_features("floating-point") max_influence = 1 count_release = 100 income_bounds = (0.0, 100_000.0) clamp_and_resize_data = ( make_clamp(bounds=income_bounds) >> make_bounded_resi...
DP mean: 28203.570278867388 Known mean: 28488.08080808081
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
We will be using `n_sims` to simulate the process a number of times to get a sense for various possible outcomes for the attacker.In practice, they would see the result of only one simulation.
# initialize vector to store estimated overall means n_sims = 10_000 n_queries = 1 poi_income_ests = [] estimated_means = [] # get estimates of overall means for i in range(n_sims): query_means = [mean_measurement(incomes) for j in range(n_queries)] # get estimates of POI income estimated_means.append(np....
Known Mean Income (after truncation): 28488.08080808081 Observed Mean Income: 28203.193459994138 Estimated POI Income: -0.6540005867157132 True POI Income: 0.0
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
We see empirically that, in expectation, the attacker can get a reasonably good estimate of POI's income. However, they will rarely (if ever) get it exactly and would have no way of knowing if they did.In our case, indeed the mean estimated POI income approaches the true income, as the number of simulations `n_sims` in...
import warnings import seaborn as sns # hide warning created by outstanding scipy.stats issue warnings.simplefilter(action='ignore', category=FutureWarning) # distribution of POI income ax = sns.distplot(poi_income_ests, kde = False, hist_kws = dict(edgecolor = 'black', linewidth = 1)) ax.set(xlabel = 'Estimated POI ...
_____no_output_____
MIT
python/example/attack_simple.ipynb
souravrhythm/opendp
ConvPool_CNN Model
def ConvPool_CNN_C(): model = Sequential() model.add(Conv2D(96,kernel_size=(3,3),activation='relu',padding='same')) model.add(Conv2D(96,kernel_size=(3,3),activation='relu',padding='same')) model.add(Conv2D(96,kernel_size=(3,3),activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=(3,3),strides=2...
_____no_output_____
MIT
kneeoa/Preprocessing/Model/Model.ipynb
Tommy-Ngx/oa_rerun2
ALL_CNN_MODEL
def all_cnn_c(X,y,learningRate=0.001,lossFunction='categorical_crossentropy'): model = Sequential() model.add(Conv2D(96,kernel_size=(3,3),activation='relu',padding='same')) model.add(Conv2D(96,kernel_size=(3,3),activation='relu',padding='same')) model.add(Conv2D(96,kernel_size=(3,3),activation='relu',padding='s...
_____no_output_____
MIT
kneeoa/Preprocessing/Model/Model.ipynb
Tommy-Ngx/oa_rerun2
NIN_CNN_MODEL
def nin_cnn_c(): model = Sequential() model.add(Conv2D(32,kernel_size=(5,5),activation='relu',padding='valid')) model.add(Conv2D(32,kernel_size=(5,5),activation='relu')) model.add(Conv2D(32,kernel_size=(5,5),activation='relu')) model.add(MaxPooling2D(pool_size=(3,3),strides=2)) model.add(Dropout(0.5)) mod...
_____no_output_____
MIT
kneeoa/Preprocessing/Model/Model.ipynb
Tommy-Ngx/oa_rerun2
© 2018 Suzy Beeler and Vahe Galstyan. This work is licensed under a [Creative Commons Attribution License CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/). All code contained herein is licensed under an [MIT license](https://opensource.org/licenses/MIT) This exercise was generated from a Jupyter notebook. You c...
# Import modules import numpy as np import matplotlib.pyplot as plt # Show figures in the notebook %matplotlib inline # For pretty plots import seaborn as sns rc={'lines.linewidth': 2, 'axes.labelsize': 14, 'axes.titlesize': 14, \ 'xtick.labelsize' : 14, 'ytick.labelsize' : 14} sns.set(rc=rc)
_____no_output_____
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
To simulate the flipping of a coin, we will make use of `numpy`'s `random.uniform()` function that produces a random number between $0$ and $1$. Let's see it in action by printing a few random numbers:
for i in range(10): print(np.random.uniform())
0.8342160184177014 0.9430314233421397 0.007367989009862352 0.09402902047181094 0.4641922790100985 0.9895482225120592 0.1652578614128407 0.6038851928675221 0.675556259583081 0.2558372886656155
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
We can now use these randomly generated numbers to simulate the process of a diffusing particle moving in one dimension, where any value below $0.5$ corresponds to step to the left and any value above $0.5$ corresponds to a step to the right. Below, we keep track of the position of a particle for $1000$ steps, where ea...
# Number of steps n_steps = 1000 # Array to store walker positions positions = np.zeros(n_steps) # simulate the particle moving and store the new position for i in range(1, n_steps): # generate random number rand = np.random.uniform() # step in the positive direction if rand > 0.5: ...
_____no_output_____
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
As we can see, the position of the particle moves about the origin in an undirected fashion as a result of the randomness of the steps taken. However, it's hard to conclude anything from this single trace. Only by simulating many of these trajectories can we begin to conclude some of the scaling properties of diffusing...
# Number of trajectories n_traj = 1000 # 2d array for storing the trajectories positions_2D = np.zeros([n_traj, n_steps]) # first iterate through the trajectories for i in range(n_traj): # then iterate through the steps for j in range(1, n_steps): # generate random number rand =...
_____no_output_____
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
Now let's plot the results, once again by looping.
# iterate through each trajectory and plot for i in range(n_traj): plt.plot(positions_2D[i,:]) # label plt.xlabel('steps') plt.ylabel('position');
_____no_output_____
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
The overall tendency is that the average displacement from the origin increases with the number of time steps. Because each trajectory is assigned a solid color and all trajectories are overlaid on top of each other, it's hard to see the distribution of the walker position at a given number of times steps. To get a bet...
# iterate through each trajectory and plot for i in range(n_traj): # lower alpha corresponds to lighter lines plt.plot(positions_2D[i,:], alpha=0.01, color='k') # label plt.xlabel('steps') plt.ylabel('position');
_____no_output_____
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
As we can see, over the course of diffusion the distribution of the walker's position becomes wider but remains centered around the origin, indicative of the unbiased nature of the random walk. To see how the walkers are distributed at this last time point, let's make a histogram of the walker's final positions.
# Make a histogram of final positions _ = plt.hist(positions_2D[:,-1], bins=20) plt.xlabel('final position') plt.ylabel('frequency');
_____no_output_____
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
As expected, the distribution is centered around the origin and has a Gaussian-like shape. The more trajectories we sample, the "more Gaussian" the distribution will become. However, we may notice that the distribution appears to change depending on the number of bins we choose. This is known as *bin bias* and doesn't ...
# sort the final positions sorted_positons = np.sort(positions_2D[:,-1]) # make the corresponding y_values (i.e. percentiles) y_values = np.linspace(start=0, stop=1, num=len(sorted_positons)) # plot the cumulative histogram plt.plot(sorted_positons, y_values, '.') plt.xlabel("final position") plt.ylabel("cumulative f...
_____no_output_____
MIT
code/diffusion_via_coin_flips.ipynb
RPGroup-PBoC/gist_pboc_2019
1. Python and notebook basicsIn this first chapter, we will cover the very essentials of Python and notebooks such as creating a variable, importing packages, using functions, seeing how variables behave in the notebook etc. We will see more details on some of these topics, but this very short introduction will then a...
a = 3
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
As long as we **don't execute the cell** using Shift+Enter or the play button in the menu, the above cell is **purely text**. We can close our Jupyter session and then re-start it and this line of text will still be there. However other parts of the notebook are not "aware" that this variable has been defined and so we...
a
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
So we actually need to **execute** the cell so that Python reads that line and executes the command. Here it's a very simple command that just says that the value of the variable ```a``` is three. So let's go back to the cell that defined ```a``` and now execute it (click in the cell and hit Shift+Enter). Now this vari...
a
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
We see that now we get an *output* with the value three. Most variables display an output when they are not involved in an operation. For example the line ```a=3``` didn't have an output.Now we can define other variables in a new cell. Note that we can put as **many lines** of commands as we want in a single cell. Each...
b = 5 c = 2
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
As variables are defined for the entire notebook we can combine information that comes from multiple cells. Here we do some basic mathematics:
a + b
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Here we only see the output. We can't re-use that ouput for further calculations as we didn't define a new variable to contain it. Here we do it:
d = a + b d
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
```d``` is now a new variable. It is purely numerical and not a mathematical formula as the above cell could make you believe. For example if we change the value of ```a```:
a = 100
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
and check the value of ```d```:
d
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
it has not change. We would have to rerun the operation and assign it again to ```d``` for it to update:
d = a + b d
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
We will see many other types of variables during the course. Some are just other types of data, for example we can define a **text** variable by using quotes ```' '``` around a given text:
my_text = 'This is my text' my_text
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Others can contain multiple elements like lists:
my_list = [3, 8, 5, 9] my_list
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
but more on these data structures later... FunctionsWe have seen that we could define variables and do some basic operations with them. If we want to go beyond simple arithmetic we need more **complex functions** that can operate on variables. Imagine for example that we need a function $f(x, a, b) = a * x + b$. For t...
def my_fun(x, a, b): out = a * x + b return out
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
We see a series of Python rules to define a function:- we use the word **```def```** to signal that we are creating a function- we pick a **function name**, here ```my_fun```- we open the **parenthesis** and put all our **variables ```x```, ```a```, ```b```** in there, just like when we do mathematics- we do some opera...
my_fun(3, 2, 5)
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Note that **some functions are defined by default** in Python. For example if I define a variable which is a string:
my_text = 'This is my text'
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
I can count the number of characters in this text using the ```len()``` function which comes from base Python:
len(my_text)
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
The ```len``` function has not been manually defined within a ```def``` statement, it simply exist by default in the Python language. Variables as objectsIn the Python world, variables are not "just" variables, they are actually more complex objects. So for example our variable ```my_text``` does indeed contain the te...
my_text my_text.lower()
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
If we define a complex number:
a = 3 + 5j
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
then we can access the property ```real``` that gives us only the real part of the number:
a.real
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Note that when we use a method (function) we need to use the parenthesis, just like for regular functions, while for properties we don't. PackagesIn the examples above, we either defined a function ourselves or used one generally accessible in base Python but there is a third solution: **external packages**. These pac...
pip install scikit-image
Requirement already satisfied: scikit-image in /Users/gw18g940/mambaforge/envs/improc_beginner/lib/python3.9/site-packages (0.19.2) Requirement already satisfied: networkx>=2.2 in /Users/gw18g940/mambaforge/envs/improc_beginner/lib/python3.9/site-packages (from scikit-image) (2.7.1) Requirement already satisfied: tifff...
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Once installed we can **import** the packakge in a notebook in the following way (note that the name of the package is scikit-image, but in code we use an abbreviated name ```skimage```):
import skimage
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
The import is valid for the **entire notebook**, we don't need that line in each cell. Now that we have imported the package we can access all function that we define in it using a *dot notation* ```skimage.myfun```. Most packages are organized into submodules and in that case to access functions of a submodule we use ...
import skimage as sk
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Nowe if we want to use the ```median``` function in the filters sumodule we would write:```pythonim_out = sk.filters.median(im_in)``` We can also import only a certain submodule using:
from skimage import filters
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Now we have to write:```pythonim_out = filters.median(im_in)``` Finally, we can import a **single** function like this:
from skimage.filters import median
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
and now we have to write:```pythonim_out = median(im_in)``` StructuresAs mentioned above we cannot execute those various lines like ```im_out = median(im_in)``` because the image variable ```im_in``` is not yet defined. This variable should be an image, i.e. it cannot be a single number like in ```a=3``` but an entire...
a = 3
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Text:
b = 'my text'
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
or even lists of numbers:
c = [6,2,8,9]
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
This last type of variable is called a ```list``` in Python and is one of the **structures** that is available in Python. If we think of an image that has multiple lines and columns of pixels, we could now imagine that we can represent it as a list of lists, each single list being e.g. one row pf pixels. For example a ...
my_image = [[4,8,7], [6,4,3], [5,3,7]] my_image
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
While in principle we could use a ```list``` for this, computations on such objects would be very slow. For example if we wanted to do background correction and subtract a given value from our image, effectively we would have to go through each element of our list (each pixel) one by one and sequentially remove the bac...
my_address = 'https://github.com/guiwitz/PyImageCourse_beginner/raw/master/images/19838_1252_F8_1.tif'
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Now we can call our function:
skimage.io.imread(my_address)
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
We see here an output which is what is returned by our function. It is as expected a list of numbers, and not all numbers are shown because the list is too long. We see that we also have ```[]``` to specify rows, columns etc. The main difference compared to our list of lists that we defined previously is the ```array``...
import matplotlib.pyplot as plt
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Now we can use the ```plt.imshow()``` function. There are many options for plot, but we can use that function already by just passing an ```array``` as an input. First we need to assign the imported array to a variable:
import skimage.io image = skimage.io.imread(my_address) plt.imshow(image);
_____no_output_____
BSD-3-Clause
01-Python_essentials.ipynb
guiwitz/Python_image_processing_beginner
Multiple Linear Regression Objective How to make the prediction for multiple inputs. How to use linear class to build more complex models. How to build a custom module. Table of ContentsIn this lab, you will review how to make a prediction in several different ways by using PyTorch. Prediction Class Linea...
# Import the libraries and set the random seed from torch import nn import torch torch.manual_seed(1)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Prediction Set weight and bias.
# Set the weight and bias w = torch.tensor([[2.0], [3.0]], requires_grad=True) b = torch.tensor([[1.0]], requires_grad=True)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Define the parameters. torch.mm uses matrix multiplication instead of scaler multiplication.
# Define Prediction Function def forward(x): yhat = torch.mm(x, w) + b return yhat
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
The function forward implements the following equation: If we input a 1x2 tensor, because we have a 2x1 tensor as w, we will get a 1x1 tensor:
# Calculate yhat x = torch.tensor([[1.0, 2.0]]) yhat = forward(x) print("The result: ", yhat)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Each row of the following tensor represents a sample:
# Sample tensor X X = torch.tensor([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0]]) # Make the prediction of X yhat = forward(X) print("The result: ", yhat)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Class Linear We can use the linear class to make a prediction. You'll also use the linear class to build more complex models. Let us create a model.
# Make a linear regression model using build-in function model = nn.Linear(2, 1)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Make a prediction with the first sample:
# Make a prediction of x yhat = model(x) print("The result: ", yhat)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Predict with multiple samples X:
# Make a prediction of X yhat = model(X) print("The result: ", yhat)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
The function performs matrix multiplication as shown in this image: Build Custom Modules Now, you'll build a custom module. You can make more complex models by using this method later.
# Create linear_regression Class class linear_regression(nn.Module): # Constructor def __init__(self, input_size, output_size): super(linear_regression, self).__init__() self.linear = nn.Linear(input_size, output_size) # Prediction function def forward(self, x): yhat =...
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Build a linear regression object. The input feature size is two.
model = linear_regression(2, 1)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
This will input the following equation: You can see the randomly initialized parameters by using the parameters() method:
# Print model parameters print("The parameters: ", list(model.parameters()))
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
You can also see the parameters by using the state_dict() method:
# Print model parameters print("The parameters: ", model.state_dict())
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Now we input a 1x2 tensor, and we will get a 1x1 tensor.
# Make a prediction of x yhat = model(x) print("The result: ", yhat)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
The shape of the output is shown in the following image: Make a prediction for multiple samples:
# Make a prediction of X yhat = model(X) print("The result: ", yhat)
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
The shape is shown in the following image: Practice Build a model or object of type linear_regression. Using the linear_regression object will predict the following tensor:
# Practice: Build a model to predict the follow tensor. X = torch.tensor([[11.0, 12.0, 13, 14], [11, 12, 13, 14]])
_____no_output_____
MIT
4.1.multiple_linear_regression_prediction_v2.ipynb
indervirbanipal/deep-neural-networks-with-pytorch
Classifying Fashion-MNISTNow it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% ...
import torch from torchvision import datasets, transforms import helper # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) # Download and load the training data trainset = datasets.FashionMNIST('~/.pyt...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
philip-le/deep-learning-v2-pytorch
Here we can see one of the images.
image, label = next(iter(trainloader)) print(image.shape, label.shape) helper.imshow(image[0,:]);
torch.Size([64, 1, 28, 28]) torch.Size([64])
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
philip-le/deep-learning-v2-pytorch
Building the networkHere you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up t...
# TODO: Define your network architecture here from torch import nn model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128,32), nn.ReLU(), nn.Linear(32,10)) model.parameters
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
philip-le/deep-learning-v2-pytorch
Train the networkNow you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.htmlloss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).Then write t...
# TODO: Create the network, define the criterion and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(params=model.parameters(), lr=0.01) len(trainloader), 60000/64 # TODO: Train the network here epochs = 10 for e in range(epochs): running_loss = 0 for image,label in iter(trainloader):...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
philip-le/deep-learning-v2-pytorch
**Create Train / Dev / Test files. Each file is a dictionary where each key represent the ID of a certain Author and each value is a dict where the keys are : - author_embedding : the Node embedding that correspond to the author (tensor of shape (128,)) - papers_embedding : the abstract embedding of every papers (te...
import pandas as pd import numpy as np import networkx as nx from tqdm import tqdm_notebook as tqdm from sklearn.utils import shuffle import gzip import pickle import torch def load_dataset_file(filename): with gzip.open(filename, "rb") as f: loaded_object = pickle.load(f) return loaded_object def s...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Roberta Embedding
# Load the paper's embedding embedding_per_paper = load_dataset_file('/content/drive/MyDrive/altegrad_datachallenge/files_generated/embedding_per_paper_clean.txt') # Load the node's embedding embedding_per_nodes = load_dataset_file('/content/drive/MyDrive/altegrad_datachallenge/files_generated/Node2Vec.txt') # read the...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Train
train_data = {} for i, row in tqdm(df_train.iterrows()): author_id, y = str(int(row['authorID'])), row['h_index'] degree, core_number_, avg_neighbor_degree_ = G.degree(int(author_id)), core_number[int(author_id)], avg_neighbor_degree[int(author_id)] author_embedding = torch.from_numpy(embedding_per_nodes[in...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Validation
valid_data = {} for i, row in tqdm(df_valid.iterrows()): author_id, y = str(int(row['authorID'])), row['h_index'] degree, core_number_, avg_neighbor_degree_ = G.degree(int(author_id)), core_number[int(author_id)], avg_neighbor_degree[int(author_id)] author_embedding = torch.from_numpy(embedding_per_nodes[in...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Test
test_data = {} for i, row in tqdm(df_test.iterrows()): author_id = str(int(row['authorID'])) degree, core_number_, avg_neighbor_degree_ = G.degree(int(author_id)), core_number[int(author_id)], avg_neighbor_degree[int(author_id)] author_embedding = torch.from_numpy(embedding_per_nodes[int(author_id)].reshape...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Doc2Vec
# Load the paper's embedding embedding_per_paper = load_dataset_file('/content/drive/MyDrive/altegrad_datachallenge/files_generated/doc2vec_paper_embedding.txt') # Load the node's embedding embedding_per_nodes = load_dataset_file('/content/drive/MyDrive/altegrad_datachallenge/files_generated/Node2Vec.txt') # read the f...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Train
train_data = {} for i, row in tqdm(df_train.iterrows()): author_id, y = str(int(row['authorID'])), row['h_index'] degree, core_number_, avg_neighbor_degree_ = G.degree(int(author_id)), core_number[int(author_id)], avg_neighbor_degree[int(author_id)] author_embedding = torch.from_numpy(embedding_per_nodes[in...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Dev
valid_data = {} for i, row in tqdm(df_valid.iterrows()): author_id, y = str(int(row['authorID'])), row['h_index'] degree, core_number_, avg_neighbor_degree_ = G.degree(int(author_id)), core_number[int(author_id)], avg_neighbor_degree[int(author_id)] author_embedding = torch.from_numpy(embedding_per_nodes[in...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
Test
test_data = {} for i, row in tqdm(df_test.iterrows()): author_id = str(int(row['authorID'])) degree, core_number_, avg_neighbor_degree_ = G.degree(int(author_id)), core_number[int(author_id)], avg_neighbor_degree[int(author_id)] author_embedding = torch.from_numpy(embedding_per_nodes[int(author_id)].reshape...
_____no_output_____
MIT
notebook_utils/generate_data.ipynb
omarsou/altegrad_challenge_hindex
WeatherPy---- Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
!pip3 install citipy # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time from scipy.stats import linregress # Import API key from api_keys import weather_api_key # Incorporated citipy to determine city based on latitude and longitude from citipy...
_____no_output_____
MIT
WeatherPy/WeatherPy.ipynb
ball4410/python-api-challenge
Generate Cities List
# List for holding lat_lngs and cities lat_lngs = [] cities = [] # Create a set of random lat and lng combinations lats = np.random.uniform(lat_range[0], lat_range[1], size=1500) lngs = np.random.uniform(lng_range[0], lng_range[1], size=1500) lat_lngs = zip(lats, lngs) # Identify nearest city for each lat, lng combin...
_____no_output_____
MIT
WeatherPy/WeatherPy.ipynb
ball4410/python-api-challenge
Perform API Calls* Perform a weather check on each city using a series of successive API calls.* Include a print log of each city as it'sbeing processed (with the city number and city name).
# Save config information url = "http://api.openweathermap.org/data/2.5/weather?units=Imperial&" base_url = f"{url}APPID={weather_api_key}&q=" city_data = [] print("Beginning Data Retrieval") print("--------------------------") # use iterrows to iterate through pandas dataframe for index, city in enumerate(cities)...
Beginning Data Retrieval -------------------------- Processing record 0: souillac Processing record 1: shubarkuduk http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=9ffa18eb275e20275c32d718a9a31ad7&q=shubarkuduk Processing record 2: bukavu Processing record 3: tuktoyaktuk Processing record 4: westport...
MIT
WeatherPy/WeatherPy.ipynb
ball4410/python-api-challenge
Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame
# Make city data into DF and export the cities DataFrame to a CSV file city_df = pd.DataFrame(city_data) city_df.describe() city_df.to_csv(output_data_file, index_label="City ID") city_df.head() city_df.count() city_df.describe()
_____no_output_____
MIT
WeatherPy/WeatherPy.ipynb
ball4410/python-api-challenge
Inspect the data and remove the cities where the humidity > 100%.----Skip this step if there are no cities that have humidity > 100%.
city_df.loc[city_df["Humidity"] > 100] # No rows returned # Get the indices of cities that have humidity over 100%. # Make a new DataFrame equal to the city data to drop all humidity outliers by index. # Passing "inplace=False" will make a copy of the city_data DataFrame, which we call "clean_city_data".
_____no_output_____
MIT
WeatherPy/WeatherPy.ipynb
ball4410/python-api-challenge