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_datas... | _____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 t... | 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 ... | _____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=... | _____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,
... | _____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 ... | # 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)
re... | _____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... | _____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 im... | 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 = i... | _____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,m... | 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 = out... | _____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... | _____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 mu... | #### 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... | 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
... | _____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.... | 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 chi... | _____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 pr... | # 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('# m... | 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... | # 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(int... | _____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 vol... | # 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 vol... | _____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... | _____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()-boo... | 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... | _____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.ra... | _____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 = ... | _____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 ... | 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... | 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... | 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 ... | 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 ... | 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 backwa... | 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 fol... | 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 th... | _____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), dty... | 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.T... | 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:
... | _____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... | 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)
... | _____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).T... | 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 Py... | _____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]`. Thi... | 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... | 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) ... | 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. #
####################... | 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 a... | 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 defin... | 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... | 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-padd... | 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 d... | 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 l... | _____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 op... | 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 e... | _____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... | 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
Ch... | 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 u... | learning_rate = 3e-3
channel_1 = 32
channel_2 = 16
model = None
optimizer = None
################################################################################
# TODO: Instantiate your ThreeLayerConvNet model and a corresponding 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
Ch... | 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__`, an... | # 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(),
n... | 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
Ch... | 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 ... | 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. ... | 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
Ch... | 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**... | ################################################################################
# TODO: #
# Experiment with any architectures, optimizers, and hyperparameters. #
# Achieve AT LEAST 70% accuracy on the *validation set* within 10 ep... | 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
Chec... | 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 ... | 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. ... | ### 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 linregr... | _____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,
... | _____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,
... | _____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'):
# ... | _____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.sc... | _____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))
... | _____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] # R... | _____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 ... | 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.