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 and prepare the datasetYou will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data. | (train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]
BUFFER_SIZE = 60000
BATCH_SIZE = 256
# Batch and shuffle the data
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Create the modelsBoth the generator and discriminator are defined using the [Keras Sequential API](https://www.tensorflow.org/guide/kerassequential_model). The GeneratorThe generator uses `tf.keras.layers.Conv2DTranspose` (upsampling) layers to produce an image from a seed (random noise). Start with a `Dense` layer that takes this seed as input, then upsample several times until you reach the desired image size of 28x28x1. Notice the `tf.keras.layers.LeakyReLU` activation for each layer, except the output layer which uses tanh. | def make_generator_model():
model = tf.keras.Sequential()
model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size
model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 128)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
assert model.output_shape == (None, 14, 14, 64)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 28, 28, 1)
return model | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Use the (as yet untrained) generator to create an image. | generator = make_generator_model()
noise = tf.random.normal([1, 100])
generated_image = generator(noise, training=False)
plt.imshow(generated_image[0, :, :, 0], cmap='gray') | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
The DiscriminatorThe discriminator is a CNN-based image classifier. | def make_discriminator_model():
model = tf.keras.Sequential()
model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[28, 28, 1]))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Flatten())
model.add(layers.Dense(1))
return model | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images. | discriminator = make_discriminator_model()
decision = discriminator(generated_image)
print (decision) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Define the loss and optimizersDefine loss functions and optimizers for both models. | # This method returns a helper function to compute cross entropy loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Discriminator lossThis method quantifies how well the discriminator is able to distinguish real images from fakes. It compares the discriminator's predictions on real images to an array of 1s, and the discriminator's predictions on fake (generated) images to an array of 0s. | def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Generator lossThe generator's loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the discriminators decisions on the generated images to an array of 1s. | def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
The discriminator and the generator optimizers are different since we will train two networks separately. | generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Save checkpointsThis notebook also demonstrates how to save and restore models, which can be helpful in case a long running training task is interrupted. | checkpoint_dir = './training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
discriminator_optimizer=discriminator_optimizer,
generator=generator,
discriminator=discriminator) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Define the training loop | EPOCHS = 50
noise_dim = 100
num_examples_to_generate = 16
# We will reuse this seed overtime (so it's easier)
# to visualize progress in the animated GIF)
seed = tf.random.normal([num_examples_to_generate, noise_dim]) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
The training loop begins with generator receiving a random seed as input. That seed is used to produce an image. The discriminator is then used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss is calculated for each of these models, and the gradients are used to update the generator and discriminator. | # Notice the use of `tf.function`
# This annotation causes the function to be "compiled".
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output)
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
def train(dataset, epochs):
for epoch in range(epochs):
start = time.time()
for image_batch in dataset:
train_step(image_batch)
# Produce images for the GIF as we go
display.clear_output(wait=True)
generate_and_save_images(generator,
epoch + 1,
seed)
# Save the model every 15 epochs
if (epoch + 1) % 15 == 0:
checkpoint.save(file_prefix = checkpoint_prefix)
print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))
# Generate after the final epoch
display.clear_output(wait=True)
generate_and_save_images(generator,
epochs,
seed) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
**Generate and save images** | def generate_and_save_images(model, epoch, test_input):
# Notice `training` is set to False.
# This is so all layers run in inference mode (batchnorm).
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
plt.axis('off')
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show() | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Train the modelCall the `train()` method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).At the beginning of the training, the generated images look like random noise. As training progresses, the generated digits will look increasingly real. After about 50 epochs, they resemble MNIST digits. This may take about one minute / epoch with the default settings on Colab. | train(train_dataset, EPOCHS) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Restore the latest checkpoint. | checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir)) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Create a GIF | # Display a single image using the epoch number
def display_image(epoch_no):
return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))
display_image(EPOCHS) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
Use `imageio` to create an animated gif using the images saved during training. | anim_file = 'dcgan.gif'
with imageio.get_writer(anim_file, mode='I') as writer:
filenames = glob.glob('image*.png')
filenames = sorted(filenames)
last = -1
for i,filename in enumerate(filenames):
frame = 2*(i**0.5)
if round(frame) > round(last):
last = frame
else:
continue
image = imageio.imread(filename)
writer.append_data(image)
image = imageio.imread(filename)
writer.append_data(image)
import IPython
if IPython.version_info > (6,2,0,''):
display.Image(filename=anim_file) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
If you're working in Colab you can download the animation with the code below: | try:
from google.colab import files
except ImportError:
pass
else:
files.download(anim_file) | _____no_output_____ | Apache-2.0 | site/en/tutorials/generative/dcgan.ipynb | PhilipMay/docs |
The first step in any data analysis is acquiring and munging the dataOur starting data set can be found here: http://jakecoltman.com in the pyData postIt is designed to be roughly similar to the output from DCM's path to conversionDownload the file and transform it into something with the columns: id,lifetime,age,male,event,search,brand where lifetime is the total time that we observed someone not convert for and event should be 1 if we see a conversion and 0 if we don't. Note that all values should be converted into intsIt is useful to note that end_date = datetime.datetime(2016, 5, 3, 20, 36, 8, 92165) | running_id = 0
output = [[0]]
with open("E:/output.txt") as file_open:
for row in file_open.read().split("\n"):
cols = row.split(",")
if cols[0] == output[-1][0]:
output[-1].append(cols[1])
output[-1].append(True)
else:
output.append(cols)
output = output[1:]
for row in output:
if len(row) == 6:
row += [datetime(2016, 5, 3, 20, 36, 8, 92165), False]
output = output[1:-1]
def convert_to_days(dt):
day_diff = dt / np.timedelta64(1, 'D')
if day_diff == 0:
return 23.0
else:
return day_diff
df = pd.DataFrame(output, columns=["id", "advert_time", "male","age","search","brand","conversion_time","event"])
df["lifetime"] = pd.to_datetime(df["conversion_time"]) - pd.to_datetime(df["advert_time"])
df["lifetime"] = df["lifetime"].apply(convert_to_days)
df["male"] = df["male"].astype(int)
df["search"] = df["search"].astype(int)
df["brand"] = df["brand"].astype(int)
df["age"] = df["age"].astype(int)
df["event"] = df["event"].astype(int)
df = df.drop('advert_time', 1)
df = df.drop('conversion_time', 1)
df = df.set_index("id")
df = df.dropna(thresh=2)
df.median()
###Parametric Bayes
#Shout out to Cam Davidson-Pilon
## Example fully worked model using toy data
## Adapted from http://blog.yhat.com/posts/estimating-user-lifetimes-with-pymc.html
## Note that we've made some corrections
N = 2500
##Generate some random data
lifetime = pm.rweibull( 2, 5, size = N )
birth = pm.runiform(0, 10, N)
censor = ((birth + lifetime) >= 10)
lifetime_ = lifetime.copy()
lifetime_[censor] = 10 - birth[censor]
alpha = pm.Uniform('alpha', 0, 20)
beta = pm.Uniform('beta', 0, 20)
@pm.observed
def survival(value=lifetime_, alpha = alpha, beta = beta ):
return sum( (1-censor)*(log( alpha/beta) + (alpha-1)*log(value/beta)) - (value/beta)**(alpha))
mcmc = pm.MCMC([alpha, beta, survival ] )
mcmc.sample(50000, 30000)
pm.Matplot.plot(mcmc)
mcmc.trace("alpha")[:] | _____no_output_____ | MIT | PyMC Part 1 Done.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Problems: 1 - Try to fit your data from section 1 2 - Use the results to plot the distribution of the median Note that the media of a Weibull distribution is:$$β(log 2)^{1/α}$$ | censor = np.array(df["event"].apply(lambda x: 0 if x else 1).tolist())
alpha = pm.Uniform("alpha", 0,50)
beta = pm.Uniform("beta", 0,50)
@pm.observed
def survival(value=df["lifetime"], alpha = alpha, beta = beta ):
return sum( (1-censor)*(np.log( alpha/beta) + (alpha-1)*np.log(value/beta)) - (value/beta)**(alpha))
mcmc = pm.MCMC([alpha, beta, survival ] )
mcmc.sample(10000)
def weibull_median(alpha, beta):
return beta * ((log(2)) ** ( 1 / alpha))
plt.hist([weibull_median(x[0], x[1]) for x in zip(mcmc.trace("alpha"), mcmc.trace("beta"))]) | _____no_output_____ | MIT | PyMC Part 1 Done.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Problems: 4 - Try adjusting the number of samples for burning and thinnning 5 - Try adjusting the prior and see how it affects the estimate | #### Adjust burn and thin, both paramters of the mcmc sample function
#### Narrow and broaden prior | _____no_output_____ | MIT | PyMC Part 1 Done.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Problems: 7 - Try testing whether the median is greater than a different values | #### Hypothesis testing | _____no_output_____ | MIT | PyMC Part 1 Done.ipynb | Journeyman08/BayesianSurvivalAnalysis |
If we want to look at covariates, we need a new approach. We'll use Cox proprtional hazards, a very popular regression model.To fit in python we use the module lifelines:http://lifelines.readthedocs.io/en/latest/ | ### Fit a cox proprtional hazards model | _____no_output_____ | MIT | PyMC Part 1 Done.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Once we've fit the data, we need to do something useful with it. Try to do the following things: 1 - Plot the baseline survival function 2 - Predict the functions for a particular set of features 3 - Plot the survival function for two different set of features 4 - For your results in part 3 caculate how much more likely a death event is for one than the other for a given period of time | #### Plot baseline hazard function
#### Predict
#### Plot survival functions for different covariates
#### Plot some odds | _____no_output_____ | MIT | PyMC Part 1 Done.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Model selectionDifficult to do with classic tools (here)Problem: 1 - Calculate the BMA coefficient values 2 - Try running with different priors | #### BMA Coefficient values
#### Different priors | _____no_output_____ | MIT | PyMC Part 1 Done.ipynb | Journeyman08/BayesianSurvivalAnalysis |
* Normalizing helps in getting better convergence in training data | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
raw_data = pd.read_csv('data.txt', sep = ',', header = None)
X = raw_data.iloc[:,0].values
y = raw_data.iloc[:,1].values
X_1 = X.reshape(len(X), 1)
plt.scatter(X,y)
plt.show() | _____no_output_____ | Apache-2.0 | linear_regression_from_scratch.ipynb | arjunjanamatti/tf_nptel |
Using scikit library | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_1, y, test_size=0.2, random_state=42)
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X = X_train,
y = y_train)
print("Accuracy of model: ", round((model.score(X = X_1,
y = y)),2))
print()
print('Intercept: ', model.intercept_)
print()
print('slope: ', model.coef_)
predicted_value = model.predict(X = X_1)
plt.scatter(X, y)
plt.plot(X, predicted_value)
plt.show() | Accuracy of model: 0.59
Intercept: 15.07636055026471
slope: [1.19463787]
| Apache-2.0 | linear_regression_from_scratch.ipynb | arjunjanamatti/tf_nptel |
Using gradient descent algorithm | b = 0
w_1 = 0
count = 0
w_1_list = []
b_list = []
loss_function_list = []
while count < 1000:
predicted_y = b + (w_1 * X)
loss_function = (np.sum(predicted_y - y)**2) * 0.5
gradient_of_w_1 = np.sum(((predicted_y - y) * X))
gradient_of_b = np.sum(((predicted_y - y) * 1))
learning_rate = 0.000001
w_1 = w_1 - (learning_rate * gradient_of_w_1)
b = b - (learning_rate * gradient_of_b)
w_1_list.append(w_1)
b_list.append(b)
loss_function_list.append(loss_function)
count = count + 1
pred = b_list[np.argmin(loss_function_list)] + ((w_1_list[np.argmin(loss_function_list)])* X)
print("Accuracy of model: ", round(r_square(y, pred),2))
print()
print('Intercept: ', model.intercept_)
print()
print('slope: ', model.coef_)
plt.scatter(X, y)
plt.plot(X, pred)
plt.show()
def r_square(y, pred):
mean_value = np.mean(y)
total = np.sum((y - mean_value)**2)
residuals = np.sum((y - pred)**2)
return 1 - (residuals / total) | _____no_output_____ | Apache-2.0 | linear_regression_from_scratch.ipynb | arjunjanamatti/tf_nptel |
Probability Distributions Some typical stuff we'll likely use | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%config InlineBackend.figure_format = 'retina' | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
[SciPy](https://scipy.org) [scipy.stats](https://docs.scipy.org/doc/scipy-0.14.0/reference/stats.html) | import scipy as sp
import scipy.stats as st | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
Binomial Distribution **Example**: A couple, who are both carriers for a recessive disease, wish to have 5 children. They want to know the probability that they will have four healthy kids.In this case the random variable is the number of healthy kids. | # number of trials (kids)
n = 5
# probability of success on each trial
# i.e. probability that each child will be healthy = 1 - 0.5 * 0.5 = 0.75
p = 0.75
# a binomial distribution object
dist = st.binom(n, p)
# probability of four healthy kids
dist.pmf(4)
print(f"The probability of having four healthy kids is {dist.pmf(4):.3f}") | The probability of having four healthy kids is 0.396
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
Probability to have each of 0-5 healthy kids. | # all possible # of successes out of n trials
# i.e. all possible outcomes of the random variable
# i.e. all possible number of healthy kids = 0-5
numHealthyKids = np.arange(n+1)
numHealthyKids
# probability of obtaining each possible number of successes
# i.e. probability of having each possible number of healthy children
pmf = dist.pmf(numHealthyKids)
pmf | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
Visualize the probability to have each of 0-5 healthy kids. | plt.bar(numHealthyKids, pmf)
plt.xlabel('# healthy children', fontsize=18)
plt.ylabel('probability', fontsize=18); | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
Probability to have at least 4 healthy kids. | # sum of probabilities of 4 and 5 healthy kids
pmf[-2:].sum()
# remaining probability after subtracting CDF for 3 kids
1 - dist.cdf(3)
# survival function for 3 kids
dist.sf(3) | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
What is the expected number of healthy kids? | print(f"The expected number of healthy kids is {dist.mean()}") | The expected number of healthy kids is 3.75
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
How sure are we about the above estimate? | print(f"The expected number of healthy kids is {dist.mean()} ± {dist.std():.2f}") | The expected number of healthy kids is 3.75 ± 0.97
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
ExerciseShould the couple consider having six children?1. Plot the *pmf* for the probability of each possible number of healthy children.2. What's the probability that they will all be healthy? Poisson Distribution **Example**: Assume that the rate of deleterious mutations is ~1.2 per diploid genome. What is the probability that an individual has 8 or more spontaneous deleterious mutations?In this case the random variable is the number of deleterious mutations within an individuals genome. | # the rate of deleterious mutations is 1.2 per diploid genome
rate = 1.2
# poisson distribution describing the predicted number of spontaneous mutations
dist = st.poisson(rate)
# let's look at the probability for 0-10 mutations
numMutations = np.arange(11)
plt.bar(numMutations, dist.pmf(numMutations))
plt.xlabel('# mutations', fontsize=18)
plt.ylabel('probability', fontsize=18);
print(f"Probability of less than 8 mutations = {dist.cdf(7)}")
print(f"Probability of 8 or more mutations = {dist.sf(7)}")
dist.cdf(7) + dist.sf(7) | Probability of less than 8 mutations = 0.9999630211320938
Probability of 8 or more mutations = 3.6978867906171055e-05
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
ExerciseFor the above example, what is the probability that an individual has three or fewer mutations? Exponential Distribution **Example**: Assume that a neuron spikes 1.5 times per second on average. Plot the probability density function of interspike intervals from zero to five seconds with a resolution of 0.01 seconds.In this case the random variable is the interspike interval time. | # spike rate per second
rate = 1.5
# exponential distribution describing the neuron's predicted interspike intervals
dist = st.expon(loc=0, scale=1/rate)
# plot interspike intervals from 0-5 seconds at 0.01 sec resolution
intervalsSec = np.linspace(0, 5, 501)
# probability density for each interval
pdf = dist.pdf(intervalsSec)
plt.plot(intervalsSec, pdf)
plt.xlabel('interspike interval (sec)', fontsize=18)
plt.ylabel('pdf', fontsize=18); | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
What is the average interval? | print(f"Average interspike interval = {dist.mean():.2f} seconds.") | Average interspike interval = 0.67 seconds.
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
time constant = 1 / rate = mean | tau = 1 / rate
tau | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
What is the probability that an interval will be between 1 and 2 seconds? | prob1to2 = dist.cdf(2) - dist.cdf(1);
print(f"Probability of an interspike interval being between 1 and 2 seconds is {prob1to2:.2f}") | Probability of an interspike interval being between 1 and 2 seconds is 0.17
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
For what time *T* is the probability that an interval is shorter than *T* equal to 25%? | timeAtFirst25PercentOfDist = dist.ppf(0.25) # percent point function
print(f"There is a 25% chance that an interval is shorter than {timeAtFirst25PercentOfDist:.2f} seconds.") | There is a 25% chance that an interval is shorter than 0.19 seconds.
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
ExerciseFor the above example, what is the probability that 3 seconds will pass without any spikes? Normal Distribution **Example**: Under basal conditions the resting membrane voltage of a neuron fluctuates around -70 mV with a variance of 10 mV.In this case the random variable is the neuron's resting membrane voltage. | # mean resting membrane voltage (mV)
mu = -70
# standard deviation about the mean
sd = np.sqrt(10)
# normal distribution describing the neuron's predicted resting membrane voltage
dist = st.norm(mu, sd)
# membrane voltages from -85 to -55 mV
mV = np.linspace(-85, -55, 301)
# probability density for each membrane voltage in mV
pdf = dist.pdf(mV)
plt.plot(mV, pdf)
plt.xlabel('membrane voltage (mV)', fontsize=18)
plt.ylabel('pdf', fontsize=18); | _____no_output_____ | Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
What range of membrane voltages (centered on the mean) account for 95% of the probability. | low = dist.ppf(0.025) # first 2.5% of distribution
high = dist.ppf(0.975) # first 97.5% of distribution
print(f"95% of membrane voltages are expected to fall within {low :.1f} and {high :.1f} mV.") | 95% of membrane voltages are expected to fall within -76.2 and -63.8 mV.
| Unlicense | lectures/Feb-25-probability_distributions/probability_distributions.ipynb | nishadalal120/NEU-365P-385L-Spring-2021 |
Dr. Ignaz Semmelweis | import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
# Read datasets/yearly_deaths_by_clinic.csv into yearly
yearly = pd.read_csv('datasets/yearly_deaths_by_clinic.csv')
# Print out yearly
display(yearly) | _____no_output_____ | CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
The alarming number of deaths | # Calculate proportion of deaths per no. births
yearly['proportion_deaths'] = yearly.deaths / yearly.births
# Extract Clinic 1 data into clinic_1 and Clinic 2 data into clinic_2
clinic_1 = yearly[yearly.clinic == 'clinic 1']
clinic_2 = yearly[yearly.clinic == 'clinic 2']
# Print out clinic_1
display(clinic_2) | _____no_output_____ | CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
Death at the clinics | # Plot yearly proportion of deaths at the two clinics
ax = clinic_1.plot(x='year', y='proportion_deaths', label='Clinic 1')
clinic_2.plot(x='year', y='proportion_deaths', label='Clinic 2', ax=ax)
plt.ylabel("Proportion deaths")
plt.show() | _____no_output_____ | CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
The handwashing | # Read datasets/monthly_deaths.csv into monthly
monthly = pd.read_csv('datasets/monthly_deaths.csv', parse_dates=['date'])
# Calculate proportion of deaths per no. births
monthly["proportion_deaths"] = monthly.deaths/monthly.births
# Print out the first rows in monthly
display(monthly.head()) | _____no_output_____ | CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
The effect of handwashing | # Date when handwashing was made mandatory
handwashing_start = pd.to_datetime('1847-06-01')
# Split monthly into before and after handwashing_start
before_washing = monthly[monthly.date < handwashing_start]
after_washing = monthly[monthly.date >= handwashing_start]
# Plot monthly proportion of deaths before and after handwashing
ax = before_washing.plot(x='date',
y='proportion_deaths', label='Before Washing')
after_washing.plot(x='date',y='proportion_deaths', label='After Washing', ax=ax)
plt.ylabel("Proportion deaths")
plt.show() | _____no_output_____ | CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
More handwashing, fewer deaths? | # Difference in mean monthly proportion of deaths due to handwashing
before_proportion = before_washing.proportion_deaths
after_proportion = after_washing.proportion_deaths
mean_diff = after_proportion.mean() - before_proportion.mean()
print(mean_diff) | -0.0839566075118334
| CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
Bootstrap analysis | # A bootstrap analysis of the reduction of deaths due to handwashing
boot_mean_diff = []
for i in range(3000):
boot_before = before_proportion.sample(replace=True,n=len(before_proportion))
boot_after = after_proportion.sample(replace=True,n=len(after_proportion))
boot_mean_diff.append(boot_after.mean()-boot_before.mean())
# Calculating a 95% confidence interval from boot_mean_diff
confidence_interval = pd.Series(boot_mean_diff).quantile([0.025, 0.975] )
print(confidence_interval) | 0.025 -0.101638
0.975 -0.067481
dtype: float64
| CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
Conclusion | # The data Semmelweis collected points to that:
doctors_should_wash_their_hands = True
print(doctors_should_wash_their_hands) | True
| CC-BY-4.0 | handwashing_notebook.ipynb | shukkkur/Analyzing-The-Discovery-of-Handwashing |
ColorspacesLet's have a brief introduction into converting to different colorspaces! The video goes into more detail about colorspaces. | import cv2
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
img = cv2.imread('../DATA/00-puppy.jpg') | _____no_output_____ | MIT | Neelesh_Color-Mappings_opencv.ipynb | Shreyansh-Gupta/Open-contributions |
Converting to Different Colorspaces | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img) | _____no_output_____ | MIT | Neelesh_Color-Mappings_opencv.ipynb | Shreyansh-Gupta/Open-contributions |
**Converting to HSV**https://en.wikipedia.org/wiki/HSL_and_HSV | img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
plt.imshow(img)
img = cv2.imread('../DATA/00-puppy.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
plt.imshow(img) | _____no_output_____ | MIT | Neelesh_Color-Mappings_opencv.ipynb | Shreyansh-Gupta/Open-contributions |
Classification | from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, ExtraTreesClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone
from sklearn.model_selection import KFold, cross_val_score, train_test_split, GridSearchCV, StratifiedKFold
from sklearn.metrics import mean_squared_error, accuracy_score
from sklearn.preprocessing import LabelEncoder
y_train = train['outliers']
del train['outliers']
train['target'] = target
test['target'] = predictions_3
models = [RandomForestClassifier(),ExtraTreesClassifier()]
names = ["RF", "Xtree"]
dict_score = {}
for name, model in zip(names, models):
model.fit(train, y_train)
model_train_pred = model.predict(train)
accy = round(accuracy_score(y_train, model_train_pred), 6)
dict_score[name] = accy
import operator
dict_score = sorted(dict_score.items(), key = operator.itemgetter(1), reverse = True)
dict_score
Xtree = ExtraTreesClassifier()
XtreeMd = Xtree.fit(train, y_train)
y_pred = XtreeMd.predict(test)
sample_submission['outliers'] = y_pred
sample_submission.loc[sample_submission['outliers'] == 1, 'target'] = -33.218750
sample_submission = sample_submission.drop(['outliers'], axis = 1)
sample_submission.to_csv('submission.csv', index=False)
sample_submission.loc[sample_submission['target'] == -33.21875][:40] | _____no_output_____ | MIT | Elo merchant/Elo_mixer1.ipynb | nguyenphuhien13/Kaggle |
Histograms, Binnings, and Density | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
data = np.random.randn(1000)
plt.hist(data);
plt.hist(data, bins=30, normed=True, alpha=0.5,
histtype='stepfilled', color='steelblue',
edgecolor='none');
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, normed=True, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs);
counts, bin_edges = np.histogram(data, bins=5)
print(counts)
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
counts, xedges, yedges = np.histogram2d(x, y, bins=30)
plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')
from scipy.stats import gaussian_kde
# fit an array of size [Ndim, Nsamples]
data = np.vstack([x, y])
kde = gaussian_kde(data)
# evaluate on a regular grid
xgrid = np.linspace(-3.5, 3.5, 40)
ygrid = np.linspace(-6, 6, 40)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)
Z = kde.evaluate(np.vstack([Xgrid.ravel(), Ygrid.ravel()]))
# Plot the result as an image
plt.imshow(Z.reshape(Xgrid.shape),
origin='lower', aspect='auto',
extent=[-3.5, 3.5, -6, 6],
cmap='Blues')
cb = plt.colorbar()
cb.set_label("density") | _____no_output_____ | MIT | code_listings/04.05-Histograms-and-Binnings.ipynb | cesar-rocha/PythonDataScienceHandbook |
Putting it All Together | import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
#load the classifying models
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
iris = datasets.load_iris()
X = iris.data[:, :2] #load the first two features of the iris data
y = iris.target #load the target of the iris data
from sklearn.neighbors import KNeighborsClassifier
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state = 0)
from sklearn.model_selection import cross_val_score
knn_3_clf = KNeighborsClassifier(n_neighbors = 3)
knn_5_clf = KNeighborsClassifier(n_neighbors = 5)
knn_3_scores = cross_val_score(knn_3_clf, X_train, y_train, cv=10)
knn_5_scores = cross_val_score(knn_5_clf, X_train, y_train, cv=10)
print "knn_3 mean scores: ", knn_3_scores.mean(), "knn_3 std: ",knn_3_scores.std()
print "knn_5 mean scores: ", knn_5_scores.mean(), " knn_5 std: ",knn_5_scores.std()
all_scores = []
for n_neighbors in range(3,9,1):
knn_clf = KNeighborsClassifier(n_neighbors = n_neighbors)
all_scores.append((n_neighbors, cross_val_score(knn_clf, X_train, y_train, cv=10).mean()))
sorted(all_scores, key = lambda x:x[1], reverse = True) | _____no_output_____ | MIT | Chapter01/Putting it All Together.ipynb | kraussc/scikit-learn-Cookbook-Second-Edition |
What's this PyTorch business?You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are some of the workhorses of deep learning in computer vision. You've also worked hard to make your code efficient and vectorized.For the last part of this assignment, though, we're going to leave behind your beautiful codebase and instead migrate to one of two popular deep learning frameworks: in this instance, PyTorch (or TensorFlow, if you choose to use that notebook). What is PyTorch?PyTorch is a system for executing dynamic computational graphs over Tensor objects that behave similarly as numpy ndarray. It comes with a powerful automatic differentiation engine that removes the need for manual back-propagation. Why?* Our code will now run on GPUs! Much faster training. When using a framework like PyTorch or TensorFlow you can harness the power of the GPU for your own custom neural network architectures without having to write CUDA code directly (which is beyond the scope of this class).* We want you to be ready to use one of these frameworks for your project so you can experiment more efficiently than if you were writing every feature you want to use by hand. * We want you to stand on the shoulders of giants! TensorFlow and PyTorch are both excellent frameworks that will make your lives a lot easier, and now that you understand their guts, you are free to use them :) * We want you to be exposed to the sort of deep learning code you might run into in academia or industry. PyTorch versionsThis notebook assumes that you are using **PyTorch version 1.0**. In some of the previous versions (e.g. before 0.4), Tensors had to be wrapped in Variable objects to be used in autograd; however Variables have now been deprecated. In addition 1.0 also separates a Tensor's datatype from its device, and uses numpy-style factories for constructing Tensors rather than directly invoking Tensor constructors. How will I learn PyTorch?Justin Johnson has made an excellent [tutorial](https://github.com/jcjohnson/pytorch-examples) for PyTorch. You can also find the detailed [API doc](http://pytorch.org/docs/stable/index.html) here. If you have other questions that are not addressed by the API docs, the [PyTorch forum](https://discuss.pytorch.org/) is a much better place to ask than StackOverflow. Table of ContentsThis assignment has 5 parts. You will learn PyTorch on **three different levels of abstraction**, which will help you understand it better and prepare you for the final project. 1. Part I, Preparation: we will use CIFAR-10 dataset.2. Part II, Barebones PyTorch: **Abstraction level 1**, we will work directly with the lowest-level PyTorch Tensors. 3. Part III, PyTorch Module API: **Abstraction level 2**, we will use `nn.Module` to define arbitrary neural network architecture. 4. Part IV, PyTorch Sequential API: **Abstraction level 3**, we will use `nn.Sequential` to define a linear feed-forward network very conveniently. 5. Part V, CIFAR-10 open-ended challenge: please implement your own network to get as high accuracy as possible on CIFAR-10. You can experiment with any layer, optimizer, hyperparameters or other advanced features. Here is a table of comparison:| API | Flexibility | Convenience ||---------------|-------------|-------------|| Barebone | High | Low || `nn.Module` | High | Medium || `nn.Sequential` | Low | High | Part I. PreparationFirst, we load the CIFAR-10 dataset. This might take a couple minutes the first time you do it, but the files should stay cached after that.In previous parts of the assignment we had to write our own code to download the CIFAR-10 dataset, preprocess it, and iterate through it in minibatches; PyTorch provides convenient tools to automate this process for us. | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data import sampler
import torchvision.datasets as dset
import torchvision.transforms as T
import numpy as np
NUM_TRAIN = 49000
# The torchvision.transforms package provides tools for preprocessing data
# and for performing data augmentation; here we set up a transform to
# preprocess the data by subtracting the mean RGB value and dividing by the
# standard deviation of each RGB value; we've hardcoded the mean and std.
transform = T.Compose([
T.ToTensor(),
T.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
])
# We set up a Dataset object for each split (train / val / test); Datasets load
# training examples one at a time, so we wrap each Dataset in a DataLoader which
# iterates through the Dataset and forms minibatches. We divide the CIFAR-10
# training set into train and val sets by passing a Sampler object to the
# DataLoader telling how it should sample from the underlying Dataset.
cifar10_train = dset.CIFAR10('./cs231n/datasets', train=True, download=True,
transform=transform)
loader_train = DataLoader(cifar10_train, batch_size=64,
sampler=sampler.SubsetRandomSampler(range(NUM_TRAIN)))
cifar10_val = dset.CIFAR10('./cs231n/datasets', train=True, download=True,
transform=transform)
loader_val = DataLoader(cifar10_val, batch_size=64,
sampler=sampler.SubsetRandomSampler(range(NUM_TRAIN, 50000)))
cifar10_test = dset.CIFAR10('./cs231n/datasets', train=False, download=True,
transform=transform)
loader_test = DataLoader(cifar10_test, batch_size=64) | Files already downloaded and verified
Files already downloaded and verified
Files already downloaded and verified
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
You have an option to **use GPU by setting the flag to True below**. It is not necessary to use GPU for this assignment. Note that if your computer does not have CUDA enabled, `torch.cuda.is_available()` will return False and this notebook will fallback to CPU mode.The global variables `dtype` and `device` will control the data types throughout this assignment. | USE_GPU = True
dtype = torch.float32 # we will be using float throughout this tutorial
if USE_GPU and torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
# Constant to control how frequently we print train loss
print_every = 100
print('using device:', device) | using device: cuda
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Part II. Barebones PyTorchPyTorch ships with high-level APIs to help us define model architectures conveniently, which we will cover in Part II of this tutorial. In this section, we will start with the barebone PyTorch elements to understand the autograd engine better. After this exercise, you will come to appreciate the high-level model API more.We will start with a simple fully-connected ReLU network with two hidden layers and no biases for CIFAR classification. This implementation computes the forward pass using operations on PyTorch Tensors, and uses PyTorch autograd to compute gradients. It is important that you understand every line, because you will write a harder version after the example.When we create a PyTorch Tensor with `requires_grad=True`, then operations involving that Tensor will not just compute values; they will also build up a computational graph in the background, allowing us to easily backpropagate through the graph to compute gradients of some Tensors with respect to a downstream loss. Concretely if x is a Tensor with `x.requires_grad == True` then after backpropagation `x.grad` will be another Tensor holding the gradient of x with respect to the scalar loss at the end. PyTorch Tensors: Flatten FunctionA PyTorch Tensor is conceptionally similar to a numpy array: it is an n-dimensional grid of numbers, and like numpy PyTorch provides many functions to efficiently operate on Tensors. As a simple example, we provide a `flatten` function below which reshapes image data for use in a fully-connected neural network.Recall that image data is typically stored in a Tensor of shape N x C x H x W, where:* N is the number of datapoints* C is the number of channels* H is the height of the intermediate feature map in pixels* W is the height of the intermediate feature map in pixelsThis is the right way to represent the data when we are doing something like a 2D convolution, that needs spatial understanding of where the intermediate features are relative to each other. When we use fully connected affine layers to process the image, however, we want each datapoint to be represented by a single vector -- it's no longer useful to segregate the different channels, rows, and columns of the data. So, we use a "flatten" operation to collapse the `C x H x W` values per representation into a single long vector. The flatten function below first reads in the N, C, H, and W values from a given batch of data, and then returns a "view" of that data. "View" is analogous to numpy's "reshape" method: it reshapes x's dimensions to be N x ??, where ?? is allowed to be anything (in this case, it will be C x H x W, but we don't need to specify that explicitly). | def flatten(x):
N = x.shape[0] # read in N, C, H, W
return x.view(N, -1) # "flatten" the C * H * W values into a single vector per image
def test_flatten():
x = torch.arange(12).view(2, 1, 3, 2)
print('Before flattening: ', x)
print('After flattening: ', flatten(x))
test_flatten() | Before flattening: tensor([[[[ 0, 1],
[ 2, 3],
[ 4, 5]]],
[[[ 6, 7],
[ 8, 9],
[10, 11]]]])
After flattening: tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Barebones PyTorch: Two-Layer NetworkHere we define a function `two_layer_fc` which performs the forward pass of a two-layer fully-connected ReLU network on a batch of image data. After defining the forward pass we check that it doesn't crash and that it produces outputs of the right shape by running zeros through the network.You don't have to write any code here, but it's important that you read and understand the implementation. | import torch.nn.functional as F # useful stateless functions
def two_layer_fc(x, params):
"""
A fully-connected neural networks; the architecture is:
NN is fully connected -> ReLU -> fully connected layer.
Note that this function only defines the forward pass;
PyTorch will take care of the backward pass for us.
The input to the network will be a minibatch of data, of shape
(N, d1, ..., dM) where d1 * ... * dM = D. The hidden layer will have H units,
and the output layer will produce scores for C classes.
Inputs:
- x: A PyTorch Tensor of shape (N, d1, ..., dM) giving a minibatch of
input data.
- params: A list [w1, w2] of PyTorch Tensors giving weights for the network;
w1 has shape (D, H) and w2 has shape (H, C).
Returns:
- scores: A PyTorch Tensor of shape (N, C) giving classification scores for
the input data x.
"""
# first we flatten the image
x = flatten(x) # shape: [batch_size, C x H x W]
w1, w2 = params
# Forward pass: compute predicted y using operations on Tensors. Since w1 and
# w2 have requires_grad=True, operations involving these Tensors will cause
# PyTorch to build a computational graph, allowing automatic computation of
# gradients. Since we are no longer implementing the backward pass by hand we
# don't need to keep references to intermediate values.
# you can also use `.clamp(min=0)`, equivalent to F.relu()
x = F.relu(x.mm(w1))
x = x.mm(w2)
return x
def two_layer_fc_test():
hidden_layer_size = 42
x = torch.zeros((64, 50), dtype=dtype) # minibatch size 64, feature dimension 50
w1 = torch.zeros((50, hidden_layer_size), dtype=dtype)
w2 = torch.zeros((hidden_layer_size, 10), dtype=dtype)
scores = two_layer_fc(x, [w1, w2])
print(scores.size()) # you should see [64, 10]
two_layer_fc_test() | torch.Size([64, 10])
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Barebones PyTorch: Three-Layer ConvNetHere you will complete the implementation of the function `three_layer_convnet`, which will perform the forward pass of a three-layer convolutional network. Like above, we can immediately test our implementation by passing zeros through the network. The network should have the following architecture:1. A convolutional layer (with bias) with `channel_1` filters, each with shape `KW1 x KH1`, and zero-padding of two2. ReLU nonlinearity3. A convolutional layer (with bias) with `channel_2` filters, each with shape `KW2 x KH2`, and zero-padding of one4. ReLU nonlinearity5. Fully-connected layer with bias, producing scores for C classes.Note that we have **no softmax activation** here after our fully-connected layer: this is because PyTorch's cross entropy loss performs a softmax activation for you, and by bundling that step in makes computation more efficient.**HINT**: For convolutions: http://pytorch.org/docs/stable/nn.htmltorch.nn.functional.conv2d; pay attention to the shapes of convolutional filters! | def three_layer_convnet(x, params):
"""
Performs the forward pass of a three-layer convolutional network with the
architecture defined above.
Inputs:
- x: A PyTorch Tensor of shape (N, 3, H, W) giving a minibatch of images
- params: A list of PyTorch Tensors giving the weights and biases for the
network; should contain the following:
- conv_w1: PyTorch Tensor of shape (channel_1, 3, KH1, KW1) giving weights
for the first convolutional layer
- conv_b1: PyTorch Tensor of shape (channel_1,) giving biases for the first
convolutional layer
- conv_w2: PyTorch Tensor of shape (channel_2, channel_1, KH2, KW2) giving
weights for the second convolutional layer
- conv_b2: PyTorch Tensor of shape (channel_2,) giving biases for the second
convolutional layer
- fc_w: PyTorch Tensor giving weights for the fully-connected layer. Can you
figure out what the shape should be?
- fc_b: PyTorch Tensor giving biases for the fully-connected layer. Can you
figure out what the shape should be?
Returns:
- scores: PyTorch Tensor of shape (N, C) giving classification scores for x
"""
conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b = params
scores = None
################################################################################
# TODO: Implement the forward pass for the three-layer ConvNet. #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
scores=F.relu_(F.conv2d(x,conv_w1,conv_b1,padding=2))
scores=F.relu_(F.conv2d(scores,conv_w2,conv_b2,padding=1))
scores=F.linear(flatten(scores),fc_w.T,fc_b)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
# END OF YOUR CODE #
################################################################################
return scores | _____no_output_____ | MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
After defining the forward pass of the ConvNet above, run the following cell to test your implementation.When you run this function, scores should have shape (64, 10). | def three_layer_convnet_test():
x = torch.zeros((64, 3, 32, 32), dtype=dtype) # minibatch size 64, image size [3, 32, 32]
conv_w1 = torch.zeros((6, 3, 5, 5), dtype=dtype) # [out_channel, in_channel, kernel_H, kernel_W]
conv_b1 = torch.zeros((6,)) # out_channel
conv_w2 = torch.zeros((9, 6, 3, 3), dtype=dtype) # [out_channel, in_channel, kernel_H, kernel_W]
conv_b2 = torch.zeros((9,)) # out_channel
# you must calculate the shape of the tensor after two conv layers, before the fully-connected layer
fc_w = torch.zeros((9 * 32 * 32, 10))
fc_b = torch.zeros(10)
scores = three_layer_convnet(x, [conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b])
print(scores.size()) # you should see [64, 10]
three_layer_convnet_test() | torch.Size([64, 10])
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Barebones PyTorch: InitializationLet's write a couple utility methods to initialize the weight matrices for our models.- `random_weight(shape)` initializes a weight tensor with the Kaiming normalization method.- `zero_weight(shape)` initializes a weight tensor with all zeros. Useful for instantiating bias parameters.The `random_weight` function uses the Kaiming normal initialization method, described in:He et al, *Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification*, ICCV 2015, https://arxiv.org/abs/1502.01852 | def random_weight(shape):
"""
Create random Tensors for weights; setting requires_grad=True means that we
want to compute gradients for these Tensors during the backward pass.
We use Kaiming normalization: sqrt(2 / fan_in)
"""
if len(shape) == 2: # FC weight
fan_in = shape[0]
else:
fan_in = np.prod(shape[1:]) # conv weight [out_channel, in_channel, kH, kW]
# randn is standard normal distribution generator.
w = torch.randn(shape, device=device, dtype=dtype) * np.sqrt(2. / fan_in)
w.requires_grad = True
return w
def zero_weight(shape):
return torch.zeros(shape, device=device, dtype=dtype, requires_grad=True)
# create a weight of shape [3 x 5]
# you should see the type `torch.cuda.FloatTensor` if you use GPU.
# Otherwise it should be `torch.FloatTensor`
random_weight((3, 5)) | _____no_output_____ | MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Barebones PyTorch: Check AccuracyWhen training the model we will use the following function to check the accuracy of our model on the training or validation sets.When checking accuracy we don't need to compute any gradients; as a result we don't need PyTorch to build a computational graph for us when we compute scores. To prevent a graph from being built we scope our computation under a `torch.no_grad()` context manager. | def check_accuracy_part2(loader, model_fn, params):
"""
Check the accuracy of a classification model.
Inputs:
- loader: A DataLoader for the data split we want to check
- model_fn: A function that performs the forward pass of the model,
with the signature scores = model_fn(x, params)
- params: List of PyTorch Tensors giving parameters of the model
Returns: Nothing, but prints the accuracy of the model
"""
split = 'val' if loader.dataset.train else 'test'
print('Checking accuracy on the %s set' % split)
num_correct, num_samples = 0, 0
with torch.no_grad():
for x, y in loader:
x = x.to(device=device, dtype=dtype) # move to device, e.g. GPU
y = y.to(device=device, dtype=torch.int64)
scores = model_fn(x, params)
_, preds = scores.max(1)
num_correct += (preds == y).sum()
num_samples += preds.size(0)
acc = float(num_correct) / num_samples
print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc)) | _____no_output_____ | MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
BareBones PyTorch: Training LoopWe can now set up a basic training loop to train our network. We will train the model using stochastic gradient descent without momentum. We will use `torch.functional.cross_entropy` to compute the loss; you can [read about it here](http://pytorch.org/docs/stable/nn.htmlcross-entropy).The training loop takes as input the neural network function, a list of initialized parameters (`[w1, w2]` in our example), and learning rate. | def train_part2(model_fn, params, learning_rate):
"""
Train a model on CIFAR-10.
Inputs:
- model_fn: A Python function that performs the forward pass of the model.
It should have the signature scores = model_fn(x, params) where x is a
PyTorch Tensor of image data, params is a list of PyTorch Tensors giving
model weights, and scores is a PyTorch Tensor of shape (N, C) giving
scores for the elements in x.
- params: List of PyTorch Tensors giving weights for the model
- learning_rate: Python scalar giving the learning rate to use for SGD
Returns: Nothing
"""
for t, (x, y) in enumerate(loader_train):
# Move the data to the proper device (GPU or CPU)
x = x.to(device=device, dtype=dtype)
y = y.to(device=device, dtype=torch.long)
# Forward pass: compute scores and loss
scores = model_fn(x, params)
loss = F.cross_entropy(scores, y)
# Backward pass: PyTorch figures out which Tensors in the computational
# graph has requires_grad=True and uses backpropagation to compute the
# gradient of the loss with respect to these Tensors, and stores the
# gradients in the .grad attribute of each Tensor.
loss.backward()
# Update parameters. We don't want to backpropagate through the
# parameter updates, so we scope the updates under a torch.no_grad()
# context manager to prevent a computational graph from being built.
with torch.no_grad():
for w in params:
w -= learning_rate * w.grad
# Manually zero the gradients after running the backward pass
w.grad.zero_()
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss.item()))
check_accuracy_part2(loader_val, model_fn, params)
print() | _____no_output_____ | MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
BareBones PyTorch: Train a Two-Layer NetworkNow we are ready to run the training loop. We need to explicitly allocate tensors for the fully connected weights, `w1` and `w2`. Each minibatch of CIFAR has 64 examples, so the tensor shape is `[64, 3, 32, 32]`. After flattening, `x` shape should be `[64, 3 * 32 * 32]`. This will be the size of the first dimension of `w1`. The second dimension of `w1` is the hidden layer size, which will also be the first dimension of `w2`. Finally, the output of the network is a 10-dimensional vector that represents the probability distribution over 10 classes. You don't need to tune any hyperparameters but you should see accuracies above 40% after training for one epoch. | hidden_layer_size = 4000
learning_rate = 1e-2
w1 = random_weight((3 * 32 * 32, hidden_layer_size))
w2 = random_weight((hidden_layer_size, 10))
train_part2(two_layer_fc, [w1, w2], learning_rate) | Iteration 0, loss = 3.4106
Checking accuracy on the val set
Got 125 / 1000 correct (12.50%)
Iteration 100, loss = 2.0570
Checking accuracy on the val set
Got 382 / 1000 correct (38.20%)
Iteration 200, loss = 2.2069
Checking accuracy on the val set
Got 347 / 1000 correct (34.70%)
Iteration 300, loss = 1.6645
Checking accuracy on the val set
Got 405 / 1000 correct (40.50%)
Iteration 400, loss = 1.6819
Checking accuracy on the val set
Got 364 / 1000 correct (36.40%)
Iteration 500, loss = 1.7364
Checking accuracy on the val set
Got 443 / 1000 correct (44.30%)
Iteration 600, loss = 2.1000
Checking accuracy on the val set
Got 413 / 1000 correct (41.30%)
Iteration 700, loss = 1.6887
Checking accuracy on the val set
Got 451 / 1000 correct (45.10%)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
BareBones PyTorch: Training a ConvNetIn the below you should use the functions defined above to train a three-layer convolutional network on CIFAR. The network should have the following architecture:1. Convolutional layer (with bias) with 32 5x5 filters, with zero-padding of 22. ReLU3. Convolutional layer (with bias) with 16 3x3 filters, with zero-padding of 14. ReLU5. Fully-connected layer (with bias) to compute scores for 10 classesYou should initialize your weight matrices using the `random_weight` function defined above, and you should initialize your bias vectors using the `zero_weight` function above.You don't need to tune any hyperparameters, but if everything works correctly you should achieve an accuracy above 42% after one epoch. | learning_rate = 3e-3
channel_1 = 32
channel_2 = 16
conv_w1 = None
conv_b1 = None
conv_w2 = None
conv_b2 = None
fc_w = None
fc_b = None
################################################################################
# TODO: Initialize the parameters of a three-layer ConvNet. #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
conv_w1=random_weight((channel_1,3,5,5))
conv_b1=zero_weight(channel_1)
conv_w2=random_weight((channel_2,channel_1,3,3))
conv_b2=zero_weight(channel_2)
fc_w=random_weight((16*32*32,10))
fc_b=zero_weight(10)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
# END OF YOUR CODE #
################################################################################
params = [conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b]
train_part2(three_layer_convnet, params, learning_rate) | Iteration 0, loss = 2.7253
Checking accuracy on the val set
Got 98 / 1000 correct (9.80%)
Iteration 100, loss = 1.9666
Checking accuracy on the val set
Got 358 / 1000 correct (35.80%)
Iteration 200, loss = 1.8562
Checking accuracy on the val set
Got 408 / 1000 correct (40.80%)
Iteration 300, loss = 1.6312
Checking accuracy on the val set
Got 422 / 1000 correct (42.20%)
Iteration 400, loss = 1.4729
Checking accuracy on the val set
Got 465 / 1000 correct (46.50%)
Iteration 500, loss = 1.3871
Checking accuracy on the val set
Got 470 / 1000 correct (47.00%)
Iteration 600, loss = 1.5025
Checking accuracy on the val set
Got 491 / 1000 correct (49.10%)
Iteration 700, loss = 1.5634
Checking accuracy on the val set
Got 496 / 1000 correct (49.60%)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Part III. PyTorch Module APIBarebone PyTorch requires that we track all the parameter tensors by hand. This is fine for small networks with a few tensors, but it would be extremely inconvenient and error-prone to track tens or hundreds of tensors in larger networks.PyTorch provides the `nn.Module` API for you to define arbitrary network architectures, while tracking every learnable parameters for you. In Part II, we implemented SGD ourselves. PyTorch also provides the `torch.optim` package that implements all the common optimizers, such as RMSProp, Adagrad, and Adam. It even supports approximate second-order methods like L-BFGS! You can refer to the [doc](http://pytorch.org/docs/master/optim.html) for the exact specifications of each optimizer.To use the Module API, follow the steps below:1. Subclass `nn.Module`. Give your network class an intuitive name like `TwoLayerFC`. 2. In the constructor `__init__()`, define all the layers you need as class attributes. Layer objects like `nn.Linear` and `nn.Conv2d` are themselves `nn.Module` subclasses and contain learnable parameters, so that you don't have to instantiate the raw tensors yourself. `nn.Module` will track these internal parameters for you. Refer to the [doc](http://pytorch.org/docs/master/nn.html) to learn more about the dozens of builtin layers. **Warning**: don't forget to call the `super().__init__()` first!3. In the `forward()` method, define the *connectivity* of your network. You should use the attributes defined in `__init__` as function calls that take tensor as input and output the "transformed" tensor. Do *not* create any new layers with learnable parameters in `forward()`! All of them must be declared upfront in `__init__`. After you define your Module subclass, you can instantiate it as an object and call it just like the NN forward function in part II. Module API: Two-Layer NetworkHere is a concrete example of a 2-layer fully connected network: | class TwoLayerFC(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super().__init__()
# assign layer objects to class attributes
self.fc1 = nn.Linear(input_size, hidden_size)
# nn.init package contains convenient initialization methods
# http://pytorch.org/docs/master/nn.html#torch-nn-init
nn.init.kaiming_normal_(self.fc1.weight)
self.fc2 = nn.Linear(hidden_size, num_classes)
nn.init.kaiming_normal_(self.fc2.weight)
def forward(self, x):
# forward always defines connectivity
x = flatten(x)
scores = self.fc2(F.relu(self.fc1(x)))
return scores
def test_TwoLayerFC():
input_size = 50
x = torch.zeros((64, input_size), dtype=dtype) # minibatch size 64, feature dimension 50
model = TwoLayerFC(input_size, 42, 10)
scores = model(x)
print(scores.size()) # you should see [64, 10]
test_TwoLayerFC() | torch.Size([64, 10])
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Module API: Three-Layer ConvNetIt's your turn to implement a 3-layer ConvNet followed by a fully connected layer. The network architecture should be the same as in Part II:1. Convolutional layer with `channel_1` 5x5 filters with zero-padding of 22. ReLU3. Convolutional layer with `channel_2` 3x3 filters with zero-padding of 14. ReLU5. Fully-connected layer to `num_classes` classesYou should initialize the weight matrices of the model using the Kaiming normal initialization method.**HINT**: http://pytorch.org/docs/stable/nn.htmlconv2dAfter you implement the three-layer ConvNet, the `test_ThreeLayerConvNet` function will run your implementation; it should print `(64, 10)` for the shape of the output scores. | class ThreeLayerConvNet(nn.Module):
def __init__(self, in_channel, channel_1, channel_2, num_classes):
super().__init__()
########################################################################
# TODO: Set up the layers you need for a three-layer ConvNet with the #
# architecture defined above. #
########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
self.conv1=nn.Conv2d(in_channel,channel_1,5,padding=2)
nn.init.kaiming_normal_(self.conv1.weight)
self.conv2=nn.Conv2d(channel_1,channel_2,3,padding=1)
nn.init.kaiming_normal_(self.conv2.weight)
self.fc=nn.Linear(channel_2*32*32,num_classes)
nn.init.kaiming_normal_(self.fc.weight)
self.relu=nn.ReLU(inplace=True)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
########################################################################
# END OF YOUR CODE #
########################################################################
def forward(self, x):
scores = None
########################################################################
# TODO: Implement the forward function for a 3-layer ConvNet. you #
# should use the layers you defined in __init__ and specify the #
# connectivity of those layers in forward() #
########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
scores=self.relu(self.conv1(x))
scores=self.relu(self.conv2(scores))
scores=self.fc(flatten(scores))
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
########################################################################
# END OF YOUR CODE #
########################################################################
return scores
def test_ThreeLayerConvNet():
x = torch.zeros((64, 3, 32, 32), dtype=dtype) # minibatch size 64, image size [3, 32, 32]
model = ThreeLayerConvNet(in_channel=3, channel_1=12, channel_2=8, num_classes=10)
scores = model(x)
print(scores.size()) # you should see [64, 10]
test_ThreeLayerConvNet() | torch.Size([64, 10])
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Module API: Check AccuracyGiven the validation or test set, we can check the classification accuracy of a neural network. This version is slightly different from the one in part II. You don't manually pass in the parameters anymore. | def check_accuracy_part34(loader, model):
if loader.dataset.train:
print('Checking accuracy on validation set')
else:
print('Checking accuracy on test set')
num_correct = 0
num_samples = 0
model.eval() # set model to evaluation mode
with torch.no_grad():
for x, y in loader:
x = x.to(device=device, dtype=dtype) # move to device, e.g. GPU
y = y.to(device=device, dtype=torch.long)
scores = model(x)
_, preds = scores.max(1)
num_correct += (preds == y).sum()
num_samples += preds.size(0)
acc = float(num_correct) / num_samples
print('Got %d / %d correct (%.2f)' % (num_correct, num_samples, 100 * acc)) | _____no_output_____ | MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Module API: Training LoopWe also use a slightly different training loop. Rather than updating the values of the weights ourselves, we use an Optimizer object from the `torch.optim` package, which abstract the notion of an optimization algorithm and provides implementations of most of the algorithms commonly used to optimize neural networks. | def train_part34(model, optimizer, epochs=1):
"""
Train a model on CIFAR-10 using the PyTorch Module API.
Inputs:
- model: A PyTorch Module giving the model to train.
- optimizer: An Optimizer object we will use to train the model
- epochs: (Optional) A Python integer giving the number of epochs to train for
Returns: Nothing, but prints model accuracies during training.
"""
model = model.to(device=device) # move the model parameters to CPU/GPU
for e in range(epochs):
for t, (x, y) in enumerate(loader_train):
model.train() # put model to training mode
x = x.to(device=device, dtype=dtype) # move to device, e.g. GPU
y = y.to(device=device, dtype=torch.long)
scores = model(x)
loss = F.cross_entropy(scores, y)
# Zero out all of the gradients for the variables which the optimizer
# will update.
optimizer.zero_grad()
# This is the backwards pass: compute the gradient of the loss with
# respect to each parameter of the model.
loss.backward()
# Actually update the parameters of the model using the gradients
# computed by the backwards pass.
optimizer.step()
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss.item()))
check_accuracy_part34(loader_val, model)
print() | _____no_output_____ | MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Module API: Train a Two-Layer NetworkNow we are ready to run the training loop. In contrast to part II, we don't explicitly allocate parameter tensors anymore.Simply pass the input size, hidden layer size, and number of classes (i.e. output size) to the constructor of `TwoLayerFC`. You also need to define an optimizer that tracks all the learnable parameters inside `TwoLayerFC`.You don't need to tune any hyperparameters, but you should see model accuracies above 40% after training for one epoch. | hidden_layer_size = 4000
learning_rate = 1e-2
model = TwoLayerFC(3 * 32 * 32, hidden_layer_size, 10)
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
train_part34(model, optimizer) | Iteration 0, loss = 3.3422
Checking accuracy on validation set
Got 145 / 1000 correct (14.50)
Iteration 100, loss = 2.5751
Checking accuracy on validation set
Got 361 / 1000 correct (36.10)
Iteration 200, loss = 2.1785
Checking accuracy on validation set
Got 332 / 1000 correct (33.20)
Iteration 300, loss = 2.4100
Checking accuracy on validation set
Got 369 / 1000 correct (36.90)
Iteration 400, loss = 1.8031
Checking accuracy on validation set
Got 408 / 1000 correct (40.80)
Iteration 500, loss = 1.6054
Checking accuracy on validation set
Got 418 / 1000 correct (41.80)
Iteration 600, loss = 1.5121
Checking accuracy on validation set
Got 407 / 1000 correct (40.70)
Iteration 700, loss = 1.5409
Checking accuracy on validation set
Got 448 / 1000 correct (44.80)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Module API: Train a Three-Layer ConvNetYou should now use the Module API to train a three-layer ConvNet on CIFAR. This should look very similar to training the two-layer network! You don't need to tune any hyperparameters, but you should achieve above above 45% after training for one epoch.You should train the model using stochastic gradient descent without momentum. | learning_rate = 3e-3
channel_1 = 32
channel_2 = 16
model = None
optimizer = None
################################################################################
# TODO: Instantiate your ThreeLayerConvNet model and a corresponding optimizer #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
model=ThreeLayerConvNet(3,channel_1,channel_2,10)
optimizer=optim.SGD(model.parameters(),lr=learning_rate)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
# END OF YOUR CODE
################################################################################
train_part34(model, optimizer) | Iteration 0, loss = 4.2933
Checking accuracy on validation set
Got 152 / 1000 correct (15.20)
Iteration 100, loss = 1.8243
Checking accuracy on validation set
Got 359 / 1000 correct (35.90)
Iteration 200, loss = 1.9024
Checking accuracy on validation set
Got 406 / 1000 correct (40.60)
Iteration 300, loss = 1.7868
Checking accuracy on validation set
Got 433 / 1000 correct (43.30)
Iteration 400, loss = 1.5867
Checking accuracy on validation set
Got 454 / 1000 correct (45.40)
Iteration 500, loss = 1.4033
Checking accuracy on validation set
Got 462 / 1000 correct (46.20)
Iteration 600, loss = 1.6708
Checking accuracy on validation set
Got 470 / 1000 correct (47.00)
Iteration 700, loss = 1.3941
Checking accuracy on validation set
Got 483 / 1000 correct (48.30)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Part IV. PyTorch Sequential APIPart III introduced the PyTorch Module API, which allows you to define arbitrary learnable layers and their connectivity. For simple models like a stack of feed forward layers, you still need to go through 3 steps: subclass `nn.Module`, assign layers to class attributes in `__init__`, and call each layer one by one in `forward()`. Is there a more convenient way? Fortunately, PyTorch provides a container Module called `nn.Sequential`, which merges the above steps into one. It is not as flexible as `nn.Module`, because you cannot specify more complex topology than a feed-forward stack, but it's good enough for many use cases. Sequential API: Two-Layer NetworkLet's see how to rewrite our two-layer fully connected network example with `nn.Sequential`, and train it using the training loop defined above.Again, you don't need to tune any hyperparameters here, but you shoud achieve above 40% accuracy after one epoch of training. | # We need to wrap `flatten` function in a module in order to stack it
# in nn.Sequential
class Flatten(nn.Module):
def forward(self, x):
return flatten(x)
hidden_layer_size = 4000
learning_rate = 1e-2
model = nn.Sequential(
Flatten(),
nn.Linear(3 * 32 * 32, hidden_layer_size),
nn.ReLU(),
nn.Linear(hidden_layer_size, 10),
)
# you can use Nesterov momentum in optim.SGD
optimizer = optim.SGD(model.parameters(), lr=learning_rate,
momentum=0.9, nesterov=True)
train_part34(model, optimizer) | Iteration 0, loss = 2.3157
Checking accuracy on validation set
Got 149 / 1000 correct (14.90)
Iteration 100, loss = 1.7171
Checking accuracy on validation set
Got 381 / 1000 correct (38.10)
Iteration 200, loss = 1.8746
Checking accuracy on validation set
Got 407 / 1000 correct (40.70)
Iteration 300, loss = 2.0099
Checking accuracy on validation set
Got 393 / 1000 correct (39.30)
Iteration 400, loss = 1.5636
Checking accuracy on validation set
Got 461 / 1000 correct (46.10)
Iteration 500, loss = 1.8556
Checking accuracy on validation set
Got 436 / 1000 correct (43.60)
Iteration 600, loss = 1.8104
Checking accuracy on validation set
Got 457 / 1000 correct (45.70)
Iteration 700, loss = 1.8647
Checking accuracy on validation set
Got 430 / 1000 correct (43.00)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Sequential API: Three-Layer ConvNetHere you should use `nn.Sequential` to define and train a three-layer ConvNet with the same architecture we used in Part III:1. Convolutional layer (with bias) with 32 5x5 filters, with zero-padding of 22. ReLU3. Convolutional layer (with bias) with 16 3x3 filters, with zero-padding of 14. ReLU5. Fully-connected layer (with bias) to compute scores for 10 classesYou should initialize your weight matrices using the `random_weight` function defined above, and you should initialize your bias vectors using the `zero_weight` function above.You should optimize your model using stochastic gradient descent with Nesterov momentum 0.9.Again, you don't need to tune any hyperparameters but you should see accuracy above 55% after one epoch of training. | channel_1 = 32
channel_2 = 16
learning_rate = 1e-2
model = None
optimizer = None
################################################################################
# TODO: Rewrite the 2-layer ConvNet with bias from Part III with the #
# Sequential API. #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
model=nn.Sequential(
nn.Conv2d(3,channel_1,5,padding=2),
nn.ReLU(inplace=True),
nn.Conv2d(channel_1,channel_2,3,padding=1),
nn.ReLU(inplace=True),
Flatten(),
nn.Linear(channel_2*32*32,10)
)
# for i in (0,2,5):
# w_shape=model[i].weight.data.shape
# b_shape=model[i].bias.data.shape
# model[i].weight.data=random_weight(w_shape)
# model[i].bias.data=zero_weight(b_shape)
optimizer=optim.SGD(model.parameters(),nesterov=True,lr=learning_rate, momentum=0.9)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
# END OF YOUR CODE
################################################################################
train_part34(model, optimizer) | Iteration 0, loss = 2.3090
Checking accuracy on validation set
Got 150 / 1000 correct (15.00)
Iteration 100, loss = 1.4854
Checking accuracy on validation set
Got 416 / 1000 correct (41.60)
Iteration 200, loss = 1.3982
Checking accuracy on validation set
Got 476 / 1000 correct (47.60)
Iteration 300, loss = 1.1755
Checking accuracy on validation set
Got 486 / 1000 correct (48.60)
Iteration 400, loss = 1.5517
Checking accuracy on validation set
Got 531 / 1000 correct (53.10)
Iteration 500, loss = 1.3707
Checking accuracy on validation set
Got 554 / 1000 correct (55.40)
Iteration 600, loss = 1.5679
Checking accuracy on validation set
Got 579 / 1000 correct (57.90)
Iteration 700, loss = 1.4356
Checking accuracy on validation set
Got 555 / 1000 correct (55.50)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Part V. CIFAR-10 open-ended challengeIn this section, you can experiment with whatever ConvNet architecture you'd like on CIFAR-10. Now it's your job to experiment with architectures, hyperparameters, loss functions, and optimizers to train a model that achieves **at least 70%** accuracy on the CIFAR-10 **validation** set within 10 epochs. You can use the check_accuracy and train functions from above. You can use either `nn.Module` or `nn.Sequential` API. Describe what you did at the end of this notebook.Here are the official API documentation for each component. One note: what we call in the class "spatial batch norm" is called "BatchNorm2D" in PyTorch.* Layers in torch.nn package: http://pytorch.org/docs/stable/nn.html* Activations: http://pytorch.org/docs/stable/nn.htmlnon-linear-activations* Loss functions: http://pytorch.org/docs/stable/nn.htmlloss-functions* Optimizers: http://pytorch.org/docs/stable/optim.html Things you might try:- **Filter size**: Above we used 5x5; would smaller filters be more efficient?- **Number of filters**: Above we used 32 filters. Do more or fewer do better?- **Pooling vs Strided Convolution**: Do you use max pooling or just stride convolutions?- **Batch normalization**: Try adding spatial batch normalization after convolution layers and vanilla batch normalization after affine layers. Do your networks train faster?- **Network architecture**: The network above has two layers of trainable parameters. Can you do better with a deep network? Good architectures to try include: - [conv-relu-pool]xN -> [affine]xM -> [softmax or SVM] - [conv-relu-conv-relu-pool]xN -> [affine]xM -> [softmax or SVM] - [batchnorm-relu-conv]xN -> [affine]xM -> [softmax or SVM]- **Global Average Pooling**: Instead of flattening and then having multiple affine layers, perform convolutions until your image gets small (7x7 or so) and then perform an average pooling operation to get to a 1x1 image picture (1, 1 , Filter), which is then reshaped into a (Filter) vector. This is used in [Google's Inception Network](https://arxiv.org/abs/1512.00567) (See Table 1 for their architecture).- **Regularization**: Add l2 weight regularization, or perhaps use Dropout. Tips for trainingFor each network architecture that you try, you should tune the learning rate and other hyperparameters. When doing this there are a couple important things to keep in mind:- If the parameters are working well, you should see improvement within a few hundred iterations- Remember the coarse-to-fine approach for hyperparameter tuning: start by testing a large range of hyperparameters for just a few training iterations to find the combinations of parameters that are working at all.- Once you have found some sets of parameters that seem to work, search more finely around these parameters. You may need to train for more epochs.- You should use the validation set for hyperparameter search, and save your test set for evaluating your architecture on the best parameters as selected by the validation set. Going above and beyondIf you are feeling adventurous there are many other features you can implement to try and improve your performance. You are **not required** to implement any of these, but don't miss the fun if you have time!- Alternative optimizers: you can try Adam, Adagrad, RMSprop, etc.- Alternative activation functions such as leaky ReLU, parametric ReLU, ELU, or MaxOut.- Model ensembles- Data augmentation- New Architectures - [ResNets](https://arxiv.org/abs/1512.03385) where the input from the previous layer is added to the output. - [DenseNets](https://arxiv.org/abs/1608.06993) where inputs into previous layers are concatenated together. - [This blog has an in-depth overview](https://chatbotslife.com/resnets-highwaynets-and-densenets-oh-my-9bb15918ee32) Have fun and happy training! | ################################################################################
# TODO: #
# Experiment with any architectures, optimizers, and hyperparameters. #
# Achieve AT LEAST 70% accuracy on the *validation set* within 10 epochs. #
# #
# Note that you can use the check_accuracy function to evaluate on either #
# the test set or the validation set, by passing either loader_test or #
# loader_val as the second argument to check_accuracy. You should not touch #
# the test set until you have finished your architecture and hyperparameter #
# tuning, and only run the test set once at the end to report a final value. #
################################################################################
model = None
optimizer = None
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
class AlexNet(nn.Module):
def __init__(self, num_classes=10):
super(AlexNet, self).__init__()
self.relu=nn.ReLU(inplace=True)
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1),
self.relu,
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(64, 192, kernel_size=3, padding=1),
self.relu,
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
self.relu,
nn.Conv2d(384, 256, kernel_size=3, padding=1),
self.relu,
# nn.Conv2d(256, 256, kernel_size=3, padding=1),
# nn.ReLU(inplace=True),
# nn.MaxPool2d(kernel_size=2),
)
self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 7 * 7, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes)
)
def forward(self, x):
x = self.features(x)
x: Tensor = self.avgpool(x)
x = x.view(-1, 7 * 7 * 256)
x = self.classifier(x)
return x
model=AlexNet()
optimizer=optim.Adam(model.parameters())
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
# END OF YOUR CODE
################################################################################
# You should get at least 70% accuracy
train_part34(model, optimizer, epochs=10) | Iteration 0, loss = 2.2991
Checking accuracy on validation set
Got 87 / 1000 correct (8.70)
Iteration 100, loss = 1.7552
Checking accuracy on validation set
Got 297 / 1000 correct (29.70)
Iteration 200, loss = 1.5173
Checking accuracy on validation set
Got 422 / 1000 correct (42.20)
Iteration 300, loss = 1.8898
Checking accuracy on validation set
Got 462 / 1000 correct (46.20)
Iteration 400, loss = 1.2726
Checking accuracy on validation set
Got 454 / 1000 correct (45.40)
Iteration 500, loss = 1.3788
Checking accuracy on validation set
Got 517 / 1000 correct (51.70)
Iteration 600, loss = 1.4038
Checking accuracy on validation set
Got 549 / 1000 correct (54.90)
Iteration 700, loss = 1.3585
Checking accuracy on validation set
Got 585 / 1000 correct (58.50)
Iteration 0, loss = 1.2974
Checking accuracy on validation set
Got 521 / 1000 correct (52.10)
Iteration 100, loss = 1.1283
Checking accuracy on validation set
Got 595 / 1000 correct (59.50)
Iteration 200, loss = 1.0768
Checking accuracy on validation set
Got 561 / 1000 correct (56.10)
Iteration 300, loss = 1.3051
Checking accuracy on validation set
Got 578 / 1000 correct (57.80)
Iteration 400, loss = 1.1316
Checking accuracy on validation set
Got 614 / 1000 correct (61.40)
Iteration 500, loss = 1.3126
Checking accuracy on validation set
Got 610 / 1000 correct (61.00)
Iteration 600, loss = 0.9826
Checking accuracy on validation set
Got 615 / 1000 correct (61.50)
Iteration 700, loss = 1.0879
Checking accuracy on validation set
Got 642 / 1000 correct (64.20)
Iteration 0, loss = 0.8668
Checking accuracy on validation set
Got 649 / 1000 correct (64.90)
Iteration 100, loss = 0.6691
Checking accuracy on validation set
Got 640 / 1000 correct (64.00)
Iteration 200, loss = 1.0020
Checking accuracy on validation set
Got 651 / 1000 correct (65.10)
Iteration 300, loss = 1.0449
Checking accuracy on validation set
Got 658 / 1000 correct (65.80)
Iteration 400, loss = 1.0965
Checking accuracy on validation set
Got 689 / 1000 correct (68.90)
Iteration 500, loss = 0.8982
Checking accuracy on validation set
Got 690 / 1000 correct (69.00)
Iteration 600, loss = 1.0119
Checking accuracy on validation set
Got 683 / 1000 correct (68.30)
Iteration 700, loss = 1.0148
Checking accuracy on validation set
Got 714 / 1000 correct (71.40)
Iteration 0, loss = 0.9760
Checking accuracy on validation set
Got 701 / 1000 correct (70.10)
Iteration 100, loss = 1.0729
Checking accuracy on validation set
Got 723 / 1000 correct (72.30)
Iteration 200, loss = 0.9246
Checking accuracy on validation set
Got 723 / 1000 correct (72.30)
Iteration 300, loss = 1.0231
Checking accuracy on validation set
Got 688 / 1000 correct (68.80)
Iteration 400, loss = 0.7594
Checking accuracy on validation set
Got 702 / 1000 correct (70.20)
Iteration 500, loss = 0.9763
Checking accuracy on validation set
Got 720 / 1000 correct (72.00)
Iteration 600, loss = 0.8896
Checking accuracy on validation set
Got 723 / 1000 correct (72.30)
Iteration 700, loss = 0.8060
Checking accuracy on validation set
Got 722 / 1000 correct (72.20)
Iteration 0, loss = 0.7393
Checking accuracy on validation set
Got 701 / 1000 correct (70.10)
Iteration 100, loss = 0.7035
Checking accuracy on validation set
Got 735 / 1000 correct (73.50)
Iteration 200, loss = 0.6795
Checking accuracy on validation set
Got 729 / 1000 correct (72.90)
Iteration 300, loss = 0.6972
Checking accuracy on validation set
Got 727 / 1000 correct (72.70)
Iteration 400, loss = 1.0203
Checking accuracy on validation set
Got 740 / 1000 correct (74.00)
Iteration 500, loss = 0.5909
Checking accuracy on validation set
Got 747 / 1000 correct (74.70)
Iteration 600, loss = 0.7872
Checking accuracy on validation set
Got 708 / 1000 correct (70.80)
Iteration 700, loss = 0.9953
Checking accuracy on validation set
Got 726 / 1000 correct (72.60)
Iteration 0, loss = 0.6975
Checking accuracy on validation set
Got 729 / 1000 correct (72.90)
Iteration 100, loss = 0.9017
Checking accuracy on validation set
Got 758 / 1000 correct (75.80)
Iteration 200, loss = 0.8283
Checking accuracy on validation set
Got 742 / 1000 correct (74.20)
Iteration 300, loss = 0.5002
Checking accuracy on validation set
Got 745 / 1000 correct (74.50)
Iteration 400, loss = 0.6421
Checking accuracy on validation set
Got 756 / 1000 correct (75.60)
Iteration 500, loss = 0.5054
Checking accuracy on validation set
Got 764 / 1000 correct (76.40)
Iteration 600, loss = 0.6842
Checking accuracy on validation set
Got 724 / 1000 correct (72.40)
Iteration 700, loss = 0.6907
Checking accuracy on validation set
Got 762 / 1000 correct (76.20)
Iteration 0, loss = 0.5623
Checking accuracy on validation set
Got 733 / 1000 correct (73.30)
Iteration 100, loss = 0.5849
Checking accuracy on validation set
Got 763 / 1000 correct (76.30)
Iteration 200, loss = 0.9528
Checking accuracy on validation set
Got 759 / 1000 correct (75.90)
Iteration 300, loss = 0.5026
Checking accuracy on validation set
Got 755 / 1000 correct (75.50)
Iteration 400, loss = 0.6748
Checking accuracy on validation set
Got 758 / 1000 correct (75.80)
Iteration 500, loss = 0.8019
Checking accuracy on validation set
Got 775 / 1000 correct (77.50)
Iteration 600, loss = 0.8776
Checking accuracy on validation set
Got 771 / 1000 correct (77.10)
Iteration 700, loss = 0.3650
Checking accuracy on validation set
Got 748 / 1000 correct (74.80)
Iteration 0, loss = 0.7855
Checking accuracy on validation set
Got 771 / 1000 correct (77.10)
Iteration 100, loss = 0.6223
Checking accuracy on validation set
Got 770 / 1000 correct (77.00)
Iteration 200, loss = 0.5580
Checking accuracy on validation set
Got 767 / 1000 correct (76.70)
Iteration 300, loss = 0.4888
Checking accuracy on validation set
Got 750 / 1000 correct (75.00)
Iteration 400, loss = 0.9556
Checking accuracy on validation set
Got 764 / 1000 correct (76.40)
Iteration 500, loss = 0.5919
Checking accuracy on validation set
Got 762 / 1000 correct (76.20)
Iteration 600, loss = 0.6052
Checking accuracy on validation set
Got 766 / 1000 correct (76.60)
Iteration 700, loss = 0.5001
Checking accuracy on validation set
Got 762 / 1000 correct (76.20)
Iteration 0, loss = 0.5619
Checking accuracy on validation set
Got 768 / 1000 correct (76.80)
Iteration 100, loss = 0.5155
Checking accuracy on validation set
Got 758 / 1000 correct (75.80)
Iteration 200, loss = 0.5664
Checking accuracy on validation set
Got 773 / 1000 correct (77.30)
Iteration 300, loss = 0.5228
Checking accuracy on validation set
Got 749 / 1000 correct (74.90)
Iteration 400, loss = 0.5239
Checking accuracy on validation set
Got 759 / 1000 correct (75.90)
Iteration 500, loss = 0.5380
Checking accuracy on validation set
Got 769 / 1000 correct (76.90)
Iteration 600, loss = 0.4890
Checking accuracy on validation set
Got 785 / 1000 correct (78.50)
Iteration 700, loss = 0.5316
Checking accuracy on validation set
Got 766 / 1000 correct (76.60)
Iteration 0, loss = 0.6571
Checking accuracy on validation set
Got 768 / 1000 correct (76.80)
Iteration 100, loss = 0.6541
Checking accuracy on validation set
Got 766 / 1000 correct (76.60)
Iteration 200, loss = 0.4546
Checking accuracy on validation set
Got 766 / 1000 correct (76.60)
Iteration 300, loss = 0.4215
Checking accuracy on validation set
Got 783 / 1000 correct (78.30)
Iteration 400, loss = 0.3967
Checking accuracy on validation set
Got 778 / 1000 correct (77.80)
Iteration 500, loss = 0.6639
Checking accuracy on validation set
Got 778 / 1000 correct (77.80)
Iteration 600, loss = 0.9450
Checking accuracy on validation set
Got 775 / 1000 correct (77.50)
Iteration 700, loss = 0.5720
Checking accuracy on validation set
Got 789 / 1000 correct (78.90)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Describe what you did In the cell below you should write an explanation of what you did, any additional features that you implemented, and/or any graphs that you made in the process of training and evaluating your network. TODO: Describe what you did Test set -- run this only onceNow that we've gotten a result we're happy with, we test our final model on the test set (which you should store in best_model). Think about how this compares to your validation set accuracy. | best_model = model
check_accuracy_part34(loader_test, best_model) | Checking accuracy on test set
Got 7581 / 10000 correct (75.81)
| MIT | assignment2/PyTorch.ipynb | Lion-HuangGz/CS231nAssignment |
Analysis of Engineered Features Table of Contents**Note:** In this notebook, the engineered features are referred to as "covariates".----1. [Preparations](prep)2. [Analysis of Covariates](covar_analysis) 1. [Boxplots](covar_analysis_boxplots) 2. [Forward Mapping (onto Shape Space)](covar_analysis_fwdmap) 3. [Back Mapping (Tissue Consensus Map)](covar_analysis_backmap) 4. [Covariate Correlations](covar_analysis_correlations)3. [Covariate-Shape Relationships](covar_fspace) 1. [Covariate-Shape Correlations](covar_fspace_correlations) 2. [Covariate Relation Graph](covar_fspace_graph) 1. Preparations---- | ### Import modules
# External, general
from __future__ import division
import os, sys
import numpy as np
np.random.seed(42)
import matplotlib.pyplot as plt
%matplotlib inline
# External, specific
import pandas as pd
import ipywidgets as widgets
from IPython.display import display, HTML
from scipy.stats import linregress, pearsonr, gaussian_kde
from scipy.spatial import cKDTree
import seaborn as sns
sns.set_style('white')
import networkx as nx
# Internal
import katachi.utilities.loading as ld
import katachi.utilities.plotting as kp
### Load data
# Prep loader
loader = ld.DataLoaderIDR()
loader.find_imports(r"data/experimentA/extracted_measurements/", recurse=True, verbose=True)
# Import embedded feature space
dataset_suffix = "shape_TFOR_pca_measured.tsv"
#dataset_suffix = "shape_CFOR_pca_measured.tsv"
#dataset_suffix = "tagRFPtUtrCH_TFOR_pca_measured.tsv"
#dataset_suffix = "mKate2GM130_TFOR_pca_measured.tsv"
fspace_pca, prim_IDs, fspace_idx = loader.load_dataset(dataset_suffix)
print "Imported feature space of shape:", fspace_pca.shape
# Import TFOR centroid locations
centroids = loader.load_dataset("_other_measurements.tsv", IDs=prim_IDs)[0][:,3:6][:,::-1]
print "Imported TFOR centroids of shape:", centroids.shape
# Import engineered features
covar_df, _, _ = loader.load_dataset("_other_measurements.tsv", IDs=prim_IDs, force_df=True)
del covar_df['Centroids RAW X']; del covar_df['Centroids RAW Y']; del covar_df['Centroids RAW Z']
covar_names = list(covar_df.columns)
print "Imported covariates of shape:", covar_df.shape
### Report
print "\ncovar_df.head()"
display(covar_df.head())
print "\ncovar_df.describe()"
display(covar_df.describe())
### Z-standardize the covariates
covar_df_z = (covar_df - covar_df.mean()) / covar_df.std() | _____no_output_____ | MIT | ANALYSIS_engineered.ipynb | WhoIsJack/data-driven-analysis-lateralline |
2. Analysis of Covariates---- Boxplots | ### General boxplot of Covariates
# Interactive selection of covariates
wid = widgets.SelectMultiple(
options=covar_names,
value=covar_names,
description='Covars',
)
# Interactive plot
@widgets.interact(selected=wid, standardized=True)
def covariate_boxplot(selected=covar_names,
standardized=True):
# Select data
if standardized:
covar_df_plot = covar_df_z[list(selected)]
else:
covar_df_plot = covar_df[list(selected)]
# Plot
fig = plt.figure(figsize=(12,3))
covar_df_plot.boxplot(grid=False)
plt.tick_params(axis='both', which='major', labelsize=6)
fig.autofmt_xdate()
if standardized: plt.title("Boxplot of Covariates [standardized]")
if not standardized: plt.title("Boxplot of Covariates [raw]")
plt.show() | _____no_output_____ | MIT | ANALYSIS_engineered.ipynb | WhoIsJack/data-driven-analysis-lateralline |
Forward Mapping (onto Shape Space) | ### Interactive mapping of covariates onto PCA-transformed shape space
# Set interactions
@widgets.interact(covariate=covar_names,
prim_ID=prim_IDs,
PCx=(1, fspace_pca.shape[1], 1),
PCy=(1, fspace_pca.shape[1], 1),
standardized=False,
show_all_prims=True)
# Show
def show_PCs(covariate=covar_names[0], prim_ID=prim_IDs[0],
PCx=1, PCy=2, standardized=False, show_all_prims=True):
# Select covariate data
if standardized:
covar_df_plot = covar_df_z[covariate]
else:
covar_df_plot = covar_df[covariate]
# Prep
plt.figure(figsize=(9,7))
# If all should be shown...
if show_all_prims:
# Plot
plt.scatter(fspace_pca[:,PCx-1], fspace_pca[:,PCy-1],
c=covar_df_plot, cmap=plt.cm.plasma,
s=10, edgecolor='', alpha=0.75)
# Cosmetics
cbar = plt.colorbar()
if standardized:
cbar.set_label(covariate+" [standardized]", rotation=270, labelpad=15)
else:
cbar.set_label(covariate+" [raw]", rotation=270, labelpad=15)
plt.xlabel("PC "+str(PCx))
plt.ylabel("PC "+str(PCy))
plt.title("PCA-Transformed Shape Space [All Prims]")
plt.show()
# If individual prims should be shown...
else:
# Plot
plt.scatter(fspace_pca[fspace_idx==prim_IDs.index(prim_ID), PCx-1],
fspace_pca[fspace_idx==prim_IDs.index(prim_ID), PCy-1],
c=covar_df_plot[fspace_idx==prim_IDs.index(prim_ID)],
cmap=plt.cm.plasma, s=10, edgecolor='',
vmin=covar_df_plot.min(), vmax=covar_df_plot.max())
# Cosmetics
cbar = plt.colorbar()
if standardized:
cbar.set_label(covariate+" [standardized]", rotation=270, labelpad=15)
else:
cbar.set_label(covariate+" [raw]", rotation=270, labelpad=15)
plt.xlabel("PC "+str(PCx))
plt.ylabel("PC "+str(PCy))
plt.title("PCA-Transformed Shape Space [prim "+prim_ID+"]")
plt.show() | _____no_output_____ | MIT | ANALYSIS_engineered.ipynb | WhoIsJack/data-driven-analysis-lateralline |
Back Mapping (Tissue Consensus Map) | ### Interactive mapping of covariates onto centroids in TFOR
# Axis range
xlim = (-175, 15)
ylim = (- 25, 25)
# Set interactions
@widgets.interact(covariate=covar_names,
standardized=['no','z'])
# Plot
def centroid_backmap(covariate=covar_names[0],
standardized='no'):
# Select covariate data
if standardized=='no':
covar_df_plot = covar_df[covariate]
elif standardized=='z':
covar_df_plot = covar_df_z[covariate]
# Init
fig,ax = plt.subplots(1, figsize=(12,5))
# Back-mapping plot
#zord = np.argsort(covar_df_plot)
zord = np.arange(len(covar_df_plot)); np.random.shuffle(zord) # Random is better!
scat = ax.scatter(centroids[zord,2], centroids[zord,1],
color=covar_df_plot[zord], cmap=plt.cm.plasma,
edgecolor='', s=15, alpha=0.75)
# Cosmetics
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.invert_yaxis() # To match images
ax.set_xlabel('TFOR x')
ax.set_ylabel('TFOR y')
cbar = plt.colorbar(scat,ax=ax)
if standardized:
ax.set_title('Centroid Back-Mapping of '+covariate+' [standardized]')
cbar.set_label(covariate+' [standardized]', rotation=270, labelpad=10)
else:
ax.set_title('Centroid Back-Mapping of '+covariate+' [raw]')
cbar.set_label(covariate+' [raw]', rotation=270, labelpad=20)
# Done
plt.tight_layout()
plt.show()
### Contour plot backmapping plot for publication
# Set interactions
@widgets.interact(covariate=covar_names,
standardized=['no','z'])
# Plot
def contour_backmap(covariate=covar_names[0],
standardized='no'):
# Settings
xlim = (-130, 8)
ylim = ( -19, 19)
# Select covariate data
if standardized=='no':
covar_df_plot = covar_df[covariate]
elif standardized=='z':
covar_df_plot = covar_df_z[covariate]
# Tools for smoothing on scatter
from katachi.utilities.pcl_helpers import pcl_gaussian_smooth
from scipy.spatial.distance import pdist, squareform
# Cut off at prim contour outline
kernel_prim = gaussian_kde(centroids[:,1:].T)
f_prim = kernel_prim(centroids[:,1:].T)
f_prim_mask = f_prim > f_prim.min() + (f_prim.max()-f_prim.min())*0.1
plot_values = covar_df_plot[f_prim_mask]
plot_centroids = centroids[f_prim_mask]
# Smoothen
pdists = squareform(pdist(plot_centroids[:,1:]))
plot_values = pcl_gaussian_smooth(pdists, plot_values[:,np.newaxis], sg_percentile=0.5)[:,0]
# Initialize figure
fig, ax = plt.subplots(1, figsize=(8, 3.25))
# Contourf plot
cfset = ax.tricontourf(plot_centroids[:,2], plot_centroids[:,1], plot_values, 20,
cmap='plasma')
# Illustrative centroids from a single prim
plt.scatter(centroids[fspace_idx==prim_IDs.index(prim_IDs[0]), 2],
centroids[fspace_idx==prim_IDs.index(prim_IDs[0]), 1],
c='', alpha=0.5)
# Cosmetics
ax.set_xlabel('TFOR x', fontsize=16)
ax.set_ylabel('TFOR y', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=13)
plt.xlim(xlim); plt.ylim(ylim)
ax.invert_yaxis() # To match images
# Colorbar
cbar = plt.colorbar(cfset, ax=ax, pad=0.01)
cbar.set_label(covariate, rotation=270, labelpad=10, fontsize=16)
cbar.ax.tick_params(labelsize=13)
# Done
plt.tight_layout()
plt.show() | _____no_output_____ | MIT | ANALYSIS_engineered.ipynb | WhoIsJack/data-driven-analysis-lateralline |
Covariate Correlations | ### Interactive linear fitting plot
# Set interaction
@widgets.interact(covar_x=covar_names,
covar_y=covar_names)
# Plotting function
def corr_plot_covar(covar_x=covar_names[0],
covar_y=covar_names[1]):
# Prep
plt.figure(figsize=(5,3))
# Scatterplot
plt.scatter(covar_df[covar_x], covar_df[covar_y],
facecolor='darkblue', edgecolor='',
s=5, alpha=0.5)
plt.xlabel(covar_x)
plt.ylabel(covar_y)
# Linear regression and pearson
fitted = linregress(covar_df[covar_x], covar_df[covar_y])
pearson = pearsonr(covar_df[covar_x], covar_df[covar_y])
# Report
print "Linear regression:"
for param,value in zip(["slope","intercept","rvalue","pvalue","stderr"], fitted):
print " {}:\t{:.2e}".format(param,value)
print "Pearson:"
print " r:\t{:.2e}".format(pearson[0])
print " p:\t{:.2e}".format(pearson[1])
# Add fit to plot
xmin,xmax = (covar_df[covar_x].min(), covar_df[covar_x].max())
ymin,ymax = (covar_df[covar_y].min(), covar_df[covar_y].max())
ybot,ytop = (xmin*fitted[0]+fitted[1], xmax*fitted[0]+fitted[1])
plt.plot([xmin,xmax], [ybot,ytop], c='blue', lw=2, alpha=0.5)
# Cosmetics and show
plt.xlim([xmin,xmax])
plt.ylim([ymin,ymax])
plt.show()
### Full pairwise correlation plot
# Create the plot
mclust = sns.clustermap(covar_df_z.corr(method='pearson'),
figsize=(10, 10),
cmap='RdBu')
# Fix the y axis orientation
mclust.ax_heatmap.set_yticklabels(mclust.ax_heatmap.get_yticklabels(),
rotation=0)
# Other cosmetics
mclust.ax_heatmap.set_title("Pairwise Correlations Cluster Plot", y=1.275)
plt.ylabel("Pearson\nCorr. Coef.")
plt.show() | _____no_output_____ | MIT | ANALYSIS_engineered.ipynb | WhoIsJack/data-driven-analysis-lateralline |
3. Covariate-Shape Relationships---- Covariate-Shape Correlations | ### Interactive linear fitting plot
# Set interaction
@widgets.interact(covar_x=covar_names,
PC_y=range(1,fspace_pca.shape[1]+1))
# Plotting function
def corr_plot_covar(covar_x=covar_names[0],
PC_y=1):
# Prep
PC_y = int(PC_y)
plt.figure(figsize=(5,3))
# Scatterplot
plt.scatter(covar_df[covar_x], fspace_pca[:, PC_y-1],
facecolor='darkred', edgecolor='',
s=5, alpha=0.5)
plt.xlabel(covar_x)
plt.ylabel("PC "+str(PC_y))
# Linear regression and pearson
fitted = linregress(covar_df[covar_x], fspace_pca[:, PC_y-1])
pearson = pearsonr(covar_df[covar_x], fspace_pca[:, PC_y-1])
# Report
print "Linear regression:"
for param,value in zip(["slope","intercept","rvalue","pvalue","stderr"], fitted):
print " {}:\t{:.2e}".format(param,value)
print "Pearson:"
print " r:\t{:.2e}".format(pearson[0])
print " p:\t{:.2e}".format(pearson[1])
# Add fit to plot
xmin,xmax = (covar_df[covar_x].min(), covar_df[covar_x].max())
ymin,ymax = (fspace_pca[:, PC_y-1].min(), fspace_pca[:, PC_y-1].max())
ybot,ytop = (xmin*fitted[0]+fitted[1], xmax*fitted[0]+fitted[1])
plt.plot([xmin,xmax], [ybot,ytop], c='red', lw=2, alpha=0.5)
# Cosmetics and show
plt.xlim([xmin,xmax])
plt.ylim([ymin,ymax])
plt.show()
### Selected linear fits
# Settings for TFOR PC 3
if 'TFOR' in dataset_suffix:
covar_x = 'Z Axis Length'
PC_y = 3
x_reduc = 0
lbl_x = 'TFOR PC 3'
lbl_y = 'Z Axis Length\n(Cell Height)'
# Settings for CFOR PC 1
if 'CFOR' in dataset_suffix:
covar_x = 'Sphericity'
PC_y = 1
x_reduc = 2
lbl_x = 'CFOR PC 1'
lbl_y = 'Sphericity'
# Prep
plt.figure(figsize=(6,4))
# Scatterplot
plt.scatter(fspace_pca[:, PC_y-1], covar_df[covar_x],
facecolor='darkblue', edgecolor='',
s=5, alpha=0.25)
plt.xlabel(covar_x)
plt.ylabel("PC "+str(PC_y))
# Linear regression and pearson
fitted = linregress(fspace_pca[:, PC_y-1], covar_df[covar_x])
pearson = pearsonr(fspace_pca[:, PC_y-1], covar_df[covar_x])
# Report
print "Linear regression:"
for param,value in zip(["slope","intercept","rvalue","pvalue","stderr"], fitted):
print " {}:\t{:.2e}".format(param,value)
print "Pearson:"
print " r:\t{:.2e}".format(pearson[0])
print " p:\t{:.2e}".format(pearson[1])
# Add fit to plot
ymin,ymax = (covar_df[covar_x].min(), covar_df[covar_x].max())
xmin,xmax = (fspace_pca[:, PC_y-1].min()-x_reduc, fspace_pca[:, PC_y-1].max())
ybot,ytop = (xmin*fitted[0]+fitted[1], xmax*fitted[0]+fitted[1])
plt.plot([xmin,xmax], [ybot,ytop], c='black', lw=1, alpha=0.5)
# Cosmetics
plt.tick_params(axis='both', which='major', labelsize=16)
plt.xlabel(lbl_x, fontsize=18)
plt.ylabel(lbl_y, fontsize=18)
plt.xlim([xmin,xmax])
plt.ylim([ymin,ymax+0.05])
plt.tight_layout()
# Done
plt.show()
### Full pairwise correlation plot
# Prepare the pairwise correlation
fspace_pca_z = (fspace_pca - fspace_pca.mean(axis=0)) / fspace_pca.std(axis=0)
fspace_pca_z_df = pd.DataFrame(fspace_pca_z[:,:25])
pairwise_corr = covar_df_z.expanding(axis=1).corr(fspace_pca_z_df, pairwise=True).iloc[-1, :, :] # Ouf, pandas...
# Create the plot
mclust = sns.clustermap(pairwise_corr,
figsize=(10, 10),
col_cluster=False,
cmap='RdBu')
# Fix the y axis orientation
mclust.ax_heatmap.set_yticklabels(mclust.ax_heatmap.get_yticklabels(),
rotation=0)
# Other cosmetics
mclust.ax_heatmap.set_title("Pairwise Correlations Cluster Plot", y=1.275)
mclust.ax_heatmap.set_xticklabels(range(1,fspace_pca_z_df.shape[1]+1))
plt.ylabel("Pearson\nCorr. Coef.")
# Done
plt.show() | _____no_output_____ | MIT | ANALYSIS_engineered.ipynb | WhoIsJack/data-driven-analysis-lateralline |
Covariate Relation Graph | # Parameters
num_PCs = 8 # Number of PCs to include
corr_measure = 'pearsonr' # Correlation measure to use
threshold = 0.30 # Threshold to include a correlation as relevant
# Get relevant data
if corr_measure == 'pearsonr':
covar_fspace_dists = pairwise_corr.get_values()[:, :num_PCs] # Retrieved from above!
else:
raise NotImplementedError()
# Generate the plot
kp.covar_pc_bigraph(covar_fspace_dists, threshold, covar_names,
height=0.6, verbose=True, show=False)
# Done
plt.show() | _____no_output_____ | MIT | ANALYSIS_engineered.ipynb | WhoIsJack/data-driven-analysis-lateralline |
pandasでデータの整形データの整形、条件抽出、並べ替えを行います。 内容- データ抽出- データ型変換- 並べ替え- 不要なカラム削除- 組合せデータの挿入 データ抽出 | import pandas as pd
import numpy as np
df = pd.read_excel("data/201704health.xlsx")
df | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
- 歩数が10000歩以上の日のみを抽出 | df.loc[:, "歩数"] >= 10000
df_fill = df[df.loc[:, "歩数"] >= 10000]
df_fill
df_fill.shape
df.query('歩数 >= 10000 and 摂取カロリー <= 1800') | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
データ型変換 | df.loc[:, "日付"]
df.loc[:, "date"] = df.loc[:, "日付"].apply(lambda x: pd.to_datetime(x)) | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
カラム 日付 に対して、applyメソッドを使うことで、データ変換し "date"カラムに挿入apply は、データ一つづつに順次関数を適用するものです。lambda は Pythonの無名関数です。ここでは、引数を x とし、先程実行した日付型を返すpandasの関数 to_datetime を実行しています。 | df.loc[:, "date"]
df
df.loc[:, "摂取カロリー"] = df.loc[:, "摂取カロリー"].astype(np.float32)
df = df.set_index("date")
df.head() | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
インデックをdateで置き換えました。 並べ替え | df.sort_values(by="歩数")
df.sort_values(by="歩数", ascending=False).head() | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
不要なカラム削除 | df = df.drop("日付", axis=1)
df.tail() | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
組合せデータの挿入 歩数 / 摂取カロリー という新たなカラムを追加します。 | df.loc[:, "歩数/カロリー"] = df.loc[:, "歩数"] / df.loc[:, "摂取カロリー"]
df | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
ここで計算した、歩数/カロリーを元に、新たに、運動指数カラムを作ります。3以下をLow, 3を超え6以下をMid、6を超えるのをHighとします。 | def exercise_judge(ex):
if ex <= 3.0:
return "Low"
elif 3 < ex <= 6.0:
return "Mid"
else:
return "High"
df.loc[:, "運動指数"] = df.loc[:, "歩数/カロリー"].apply(exercise_judge)
df | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
別の章で使うのでデータをPickle形式で保存しておきます | df.to_pickle("data/df_201704health.pickle") | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
One-hot Encording(データフレームの結合は次の次の章で) | df_moved = pd.get_dummies(df.loc[:, "運動指数"], prefix="運動")
df_moved | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
このデータもPickle形式で保存しておきます | df_moved.to_pickle("data/df_201704moved.pickle") | _____no_output_____ | MIT | 5-pandas-reshape.ipynb | terapyon/python-datahandling-tutorial |
**Due Date: Monday, October 19th, 11:59pm**- Fill out the missing parts.- Answer the questions (if any) in a separate document or by adding a new `Text` block inside the Colab.- Save the notebook by going to the menu and clicking `File` > `Download .ipynb`.- Make sure the saved version is showing your solutions.- Send the saved notebook by email to your TA. | import numpy as np
np.random.seed(0) | _____no_output_____ | MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Simulate a dataset of 100 coin flips for a coin with $p$ = P(head) = 0.6. | n = 100 # number of coin flips
p = 0.6 # probability of getting a head (not a fair coin)
# A coin toss experiment can be modeled with a binomial distribution
# if we set n=1 (one trial), which is equivalent to a Bernoulli distribution
y = np.random.binomial(n=1, p=p, size=n)
y | _____no_output_____ | MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Point Estimation Estimate the value of $p$ using the data. | def estimator(y):
return np.mean(y)
p_hat = estimator(y)
p_hat | _____no_output_____ | MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.