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 |
|---|---|---|---|---|---|
Visualize Decision Tree | my_data.columns
import matplotlib.pyplot as plt
import graphviz
fig = plt.figure(figsize=(25,20))
data = tree.export_graphviz(model,
feature_names=my_data.columns[0:5],
class_names=my_data.Drug.unique().tolist(),
filled=True)
graph = graphviz.Source(data, for... | Collecting graphviz
Downloading https://files.pythonhosted.org/packages/62/dc/9dd6a6b9b8977248e165e075b109eea6e8eac71faa28ca378c3d98e54fbe/graphviz-0.14.1-py2.py3-none-any.whl
Installing collected packages: graphviz
Successfully installed graphviz-0.14.1
| MIT | Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb | Syed-Sherjeel/Classification-Problems |
Visualization Lets visualize the tree | # Notice: You might need to uncomment and install the pydotplus and graphviz libraries if you have not installed these before
# !conda install -c conda-forge pydotplus -y
# !conda install -c conda-forge python-graphviz -y
from sklearn.externals.six import StringIO
import pydotplus
import matplotlib.image as mpimg
from ... | _____no_output_____ | MIT | Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb | Syed-Sherjeel/Classification-Problems |
**Chapter 11 – Training Deep Neural Networks** _This notebook contains all the sample code and solutions to the exercises in chapter 11._ Setup Đầu tiên hãy nhập một vài mô-đun thông dụng, đảm bảo rằng Matplotlib sẽ vẽ đồ thị ngay trong notebook, và chuẩn bị một hàm để lưu đồ thị. Ta cũng kiểm tra xem... | # Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)
# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
# TensorFlow ≥2.0 is required
import tensorflow as tf... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Vanishing/Exploding Gradients Problem | def logit(z):
return 1 / (1 + np.exp(-z))
z = np.linspace(-5, 5, 200)
plt.plot([-5, 5], [0, 0], 'k-')
plt.plot([-5, 5], [1, 1], 'k--')
plt.plot([0, 0], [-0.2, 1.2], 'k-')
plt.plot([-5, 5], [-3/4, 7/4], 'g--')
plt.plot(z, logit(z), "b-", linewidth=2)
props = dict(facecolor='black', shrink=0.1)
plt.annotate('Saturat... | Saving figure sigmoid_saturation_plot
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Xavier and He Initialization | [name for name in dir(keras.initializers) if not name.startswith("_")]
keras.layers.Dense(10, activation="relu", kernel_initializer="he_normal")
init = keras.initializers.VarianceScaling(scale=2., mode='fan_avg',
distribution='uniform')
keras.layers.Dense(10, activation="relu",... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Nonsaturating Activation Functions Leaky ReLU | def leaky_relu(z, alpha=0.01):
return np.maximum(alpha*z, z)
plt.plot(z, leaky_relu(z, 0.05), "b-", linewidth=2)
plt.plot([-5, 5], [0, 0], 'k-')
plt.plot([0, 0], [-0.5, 4.2], 'k-')
plt.grid(True)
props = dict(facecolor='black', shrink=0.1)
plt.annotate('Leak', xytext=(-3.5, 0.5), xy=(-5, -0.2), arrowprops=props, fo... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Let's train a neural network on Fashion MNIST using the Leaky ReLU: | (X_train_full, y_train_full), (X_test, y_test) = keras.datasets.fashion_mnist.load_data()
X_train_full = X_train_full / 255.0
X_test = X_test / 255.0
X_valid, X_train = X_train_full[:5000], X_train_full[5000:]
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]
tf.random.set_seed(42)
np.random.seed(42)
model =... | Epoch 1/10
1719/1719 [==============================] - 2s 1ms/step - loss: 1.6314 - accuracy: 0.5054 - val_loss: 0.8886 - val_accuracy: 0.7160
Epoch 2/10
1719/1719 [==============================] - 2s 892us/step - loss: 0.8416 - accuracy: 0.7247 - val_loss: 0.7130 - val_accuracy: 0.7656
Epoch 3/10
1719/1719 [========... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Now let's try PReLU: | tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dense(300, kernel_initializer="he_normal"),
keras.layers.PReLU(),
keras.layers.Dense(100, kernel_initializer="he_normal"),
keras.layers.PReLU(),
keras.layers.Dens... | Epoch 1/10
1719/1719 [==============================] - 2s 1ms/step - loss: 1.6969 - accuracy: 0.4974 - val_loss: 0.9255 - val_accuracy: 0.7186
Epoch 2/10
1719/1719 [==============================] - 2s 990us/step - loss: 0.8706 - accuracy: 0.7247 - val_loss: 0.7305 - val_accuracy: 0.7630
Epoch 3/10
1719/1719 [========... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
ELU | def elu(z, alpha=1):
return np.where(z < 0, alpha * (np.exp(z) - 1), z)
plt.plot(z, elu(z), "b-", linewidth=2)
plt.plot([-5, 5], [0, 0], 'k-')
plt.plot([-5, 5], [-1, -1], 'k--')
plt.plot([0, 0], [-2.2, 3.2], 'k-')
plt.grid(True)
plt.title(r"ELU activation function ($\alpha=1$)", fontsize=14)
plt.axis([-5, 5, -2.2, ... | Saving figure elu_plot
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Implementing ELU in TensorFlow is trivial, just specify the activation function when building each layer: | keras.layers.Dense(10, activation="elu") | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
SELU This activation function was proposed in this [great paper](https://arxiv.org/pdf/1706.02515.pdf) by Günter Klambauer, Thomas Unterthiner and Andreas Mayr, published in June 2017. During training, a neural network composed exclusively of a stack of dense layers using the SELU activation function and LeCun initial... | from scipy.special import erfc
# alpha and scale to self normalize with mean 0 and standard deviation 1
# (see equation 14 in the paper):
alpha_0_1 = -np.sqrt(2 / np.pi) / (erfc(1/np.sqrt(2)) * np.exp(1/2) - 1)
scale_0_1 = (1 - erfc(1 / np.sqrt(2)) * np.sqrt(np.e)) * np.sqrt(2 * np.pi) * (2 * erfc(np.sqrt(2))*np.e**2 ... | Saving figure selu_plot
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
By default, the SELU hyperparameters (`scale` and `alpha`) are tuned in such a way that the mean output of each neuron remains close to 0, and the standard deviation remains close to 1 (assuming the inputs are standardized with mean 0 and standard deviation 1 too). Using this activation function, even a 1,000 layer dee... | np.random.seed(42)
Z = np.random.normal(size=(500, 100)) # standardized inputs
for layer in range(1000):
W = np.random.normal(size=(100, 100), scale=np.sqrt(1 / 100)) # LeCun initialization
Z = selu(np.dot(Z, W))
means = np.mean(Z, axis=0).mean()
stds = np.std(Z, axis=0).mean()
if layer % 100 == 0:
... | Layer 0: mean -0.00, std deviation 1.00
Layer 100: mean 0.02, std deviation 0.96
Layer 200: mean 0.01, std deviation 0.90
Layer 300: mean -0.02, std deviation 0.92
Layer 400: mean 0.05, std deviation 0.89
Layer 500: mean 0.01, std deviation 0.93
Layer 600: mean 0.02, std deviation 0.92
Layer 700: mean -0.02, std deviat... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Using SELU is easy: | keras.layers.Dense(10, activation="selu",
kernel_initializer="lecun_normal") | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Let's create a neural net for Fashion MNIST with 100 hidden layers, using the SELU activation function: | np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[28, 28]))
model.add(keras.layers.Dense(300, activation="selu",
kernel_initializer="lecun_normal"))
for layer in range(99):
model.add(keras.layers.Dense(100, activation... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Now let's train it. Do not forget to scale the inputs to mean 0 and standard deviation 1: | pixel_means = X_train.mean(axis=0, keepdims=True)
pixel_stds = X_train.std(axis=0, keepdims=True)
X_train_scaled = (X_train - pixel_means) / pixel_stds
X_valid_scaled = (X_valid - pixel_means) / pixel_stds
X_test_scaled = (X_test - pixel_means) / pixel_stds
history = model.fit(X_train_scaled, y_train, epochs=5,
... | Epoch 1/5
1719/1719 [==============================] - 12s 6ms/step - loss: 1.3556 - accuracy: 0.4808 - val_loss: 0.7711 - val_accuracy: 0.6858
Epoch 2/5
1719/1719 [==============================] - 9s 5ms/step - loss: 0.7537 - accuracy: 0.7235 - val_loss: 0.7534 - val_accuracy: 0.7384
Epoch 3/5
1719/1719 [============... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Now look at what happens if we try to use the ReLU activation function instead: | np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[28, 28]))
model.add(keras.layers.Dense(300, activation="relu", kernel_initializer="he_normal"))
for layer in range(99):
model.add(keras.layers.Dense(100, activation="relu", kernel_initializer="he_... | Epoch 1/5
1719/1719 [==============================] - 11s 5ms/step - loss: 2.0460 - accuracy: 0.1919 - val_loss: 1.5971 - val_accuracy: 0.3048
Epoch 2/5
1719/1719 [==============================] - 8s 5ms/step - loss: 1.2654 - accuracy: 0.4591 - val_loss: 0.9156 - val_accuracy: 0.6372
Epoch 3/5
1719/1719 [============... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Not great at all, we suffered from the vanishing/exploding gradients problem. Batch Normalization | model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.BatchNormalization(),
keras.layers.Dense(300, activation="relu"),
keras.layers.BatchNormalization(),
keras.layers.Dense(100, activation="relu"),
keras.layers.BatchNormalization(),
keras.layers.Dense(10... | Epoch 1/10
1719/1719 [==============================] - 3s 1ms/step - loss: 1.2287 - accuracy: 0.5993 - val_loss: 0.5526 - val_accuracy: 0.8230
Epoch 2/10
1719/1719 [==============================] - 2s 1ms/step - loss: 0.5996 - accuracy: 0.7959 - val_loss: 0.4725 - val_accuracy: 0.8468
Epoch 3/10
1719/1719 [==========... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Sometimes applying BN before the activation function works better (there's a debate on this topic). Moreover, the layer before a `BatchNormalization` layer does not need to have bias terms, since the `BatchNormalization` layer some as well, it would be a waste of parameters, so you can set `use_bias=False` when creatin... | model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.BatchNormalization(),
keras.layers.Dense(300, use_bias=False),
keras.layers.BatchNormalization(),
keras.layers.Activation("relu"),
keras.layers.Dense(100, use_bias=False),
keras.layers.BatchNormalizati... | Epoch 1/10
1719/1719 [==============================] - 3s 1ms/step - loss: 1.3677 - accuracy: 0.5604 - val_loss: 0.6767 - val_accuracy: 0.7812
Epoch 2/10
1719/1719 [==============================] - 2s 1ms/step - loss: 0.7136 - accuracy: 0.7702 - val_loss: 0.5566 - val_accuracy: 0.8184
Epoch 3/10
1719/1719 [==========... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Gradient Clipping All Keras optimizers accept `clipnorm` or `clipvalue` arguments: | optimizer = keras.optimizers.SGD(clipvalue=1.0)
optimizer = keras.optimizers.SGD(clipnorm=1.0) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Reusing Pretrained Layers Reusing a Keras model Let's split the fashion MNIST training set in two:* `X_train_A`: all images of all items except for sandals and shirts (classes 5 and 6).* `X_train_B`: a much smaller training set of just the first 200 images of sandals or shirts.The validation set and the test set are ... | def split_dataset(X, y):
y_5_or_6 = (y == 5) | (y == 6) # sandals or shirts
y_A = y[~y_5_or_6]
y_A[y_A > 6] -= 2 # class indices 7, 8, 9 should be moved to 5, 6, 7
y_B = (y[y_5_or_6] == 6).astype(np.float32) # binary classification task: is it a shirt (class 6)?
return ((X[~y_5_or_6], y_A),
... | Epoch 1/4
7/7 [==============================] - 1s 83ms/step - loss: 0.6155 - accuracy: 0.6184 - val_loss: 0.5843 - val_accuracy: 0.6329
Epoch 2/4
7/7 [==============================] - 0s 9ms/step - loss: 0.5550 - accuracy: 0.6638 - val_loss: 0.5467 - val_accuracy: 0.6805
Epoch 3/4
7/7 [==============================... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
So, what's the final verdict? | model_B.evaluate(X_test_B, y_test_B)
model_B_on_A.evaluate(X_test_B, y_test_B) | 63/63 [==============================] - 0s 705us/step - loss: 0.0682 - accuracy: 0.9935
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Great! We got quite a bit of transfer: the error rate dropped by a factor of 4.5! | (100 - 97.05) / (100 - 99.35) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Faster Optimizers Momentum optimization | optimizer = keras.optimizers.SGD(learning_rate=0.001, momentum=0.9) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Nesterov Accelerated Gradient | optimizer = keras.optimizers.SGD(learning_rate=0.001, momentum=0.9, nesterov=True) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
AdaGrad | optimizer = keras.optimizers.Adagrad(learning_rate=0.001) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
RMSProp | optimizer = keras.optimizers.RMSprop(learning_rate=0.001, rho=0.9) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Adam Optimization | optimizer = keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Adamax Optimization | optimizer = keras.optimizers.Adamax(learning_rate=0.001, beta_1=0.9, beta_2=0.999) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Nadam Optimization | optimizer = keras.optimizers.Nadam(learning_rate=0.001, beta_1=0.9, beta_2=0.999) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Learning Rate Scheduling Power Scheduling ```lr = lr0 / (1 + steps / s)**c```* Keras uses `c=1` and `s = 1 / decay` | optimizer = keras.optimizers.SGD(learning_rate=0.01, decay=1e-4)
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dense(300, activation="selu", kernel_initializer="lecun_normal"),
keras.layers.Dense(100, activation="selu", kernel_initializer="lecun_normal"),
ker... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Exponential Scheduling ```lr = lr0 * 0.1**(epoch / s)``` | def exponential_decay_fn(epoch):
return 0.01 * 0.1**(epoch / 20)
def exponential_decay(lr0, s):
def exponential_decay_fn(epoch):
return lr0 * 0.1**(epoch / s)
return exponential_decay_fn
exponential_decay_fn = exponential_decay(lr0=0.01, s=20)
model = keras.models.Sequential([
keras.layers.Flat... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
The schedule function can take the current learning rate as a second argument: | def exponential_decay_fn(epoch, lr):
return lr * 0.1**(1 / 20) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
If you want to update the learning rate at each iteration rather than at each epoch, you must write your own callback class: | K = keras.backend
class ExponentialDecay(keras.callbacks.Callback):
def __init__(self, s=40000):
super().__init__()
self.s = s
def on_batch_begin(self, batch, logs=None):
# Note: the `batch` argument is reset at each epoch
lr = K.get_value(self.model.optimizer.learning_rate)
... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Piecewise Constant Scheduling | def piecewise_constant_fn(epoch):
if epoch < 5:
return 0.01
elif epoch < 15:
return 0.005
else:
return 0.001
def piecewise_constant(boundaries, values):
boundaries = np.array([0] + boundaries)
values = np.array(values)
def piecewise_constant_fn(epoch):
return valu... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Performance Scheduling | tf.random.set_seed(42)
np.random.seed(42)
lr_scheduler = keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=5)
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dense(300, activation="selu", kernel_initializer="lecun_normal"),
keras.layers.Dense(100, activation=... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
tf.keras schedulers | model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dense(300, activation="selu", kernel_initializer="lecun_normal"),
keras.layers.Dense(100, activation="selu", kernel_initializer="lecun_normal"),
keras.layers.Dense(10, activation="softmax")
])
s = 20 * len(X_train... | Epoch 1/25
1719/1719 [==============================] - 2s 1ms/step - loss: 0.5995 - accuracy: 0.7923 - val_loss: 0.4095 - val_accuracy: 0.8606
Epoch 2/25
1719/1719 [==============================] - 2s 1ms/step - loss: 0.3890 - accuracy: 0.8613 - val_loss: 0.3738 - val_accuracy: 0.8692
Epoch 3/25
1719/1719 [==========... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
For piecewise constant scheduling, try this: | learning_rate = keras.optimizers.schedules.PiecewiseConstantDecay(
boundaries=[5. * n_steps_per_epoch, 15. * n_steps_per_epoch],
values=[0.01, 0.005, 0.001]) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
1Cycle scheduling | K = keras.backend
class ExponentialLearningRate(keras.callbacks.Callback):
def __init__(self, factor):
self.factor = factor
self.rates = []
self.losses = []
def on_batch_end(self, batch, logs):
self.rates.append(K.get_value(self.model.optimizer.learning_rate))
self.losse... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
**Warning**: In the `on_batch_end()` method, `logs["loss"]` used to contain the batch loss, but in TensorFlow 2.2.0 it was replaced with the mean loss (since the start of the epoch). This explains why the graph below is much smoother than in the book (if you are using TF 2.2 or above). It also means that there is a lag... | tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dense(300, activation="selu", kernel_initializer="lecun_normal"),
keras.layers.Dense(100, activation="selu", kernel_initializer="lecun_normal"),
keras.layers.Dense(10, ac... | Epoch 1/25
430/430 [==============================] - 1s 2ms/step - loss: 0.6572 - accuracy: 0.7740 - val_loss: 0.4872 - val_accuracy: 0.8338
Epoch 2/25
430/430 [==============================] - 1s 2ms/step - loss: 0.4580 - accuracy: 0.8397 - val_loss: 0.4274 - val_accuracy: 0.8520
Epoch 3/25
430/430 [================... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Avoiding Overfitting Through Regularization $\ell_1$ and $\ell_2$ regularization | layer = keras.layers.Dense(100, activation="elu",
kernel_initializer="he_normal",
kernel_regularizer=keras.regularizers.l2(0.01))
# or l1(0.1) for ℓ1 regularization with a factor of 0.1
# or l1_l2(0.1, 0.01) for both ℓ1 and ℓ2 regularization, with factors 0.1 and 0.... | Epoch 1/2
1719/1719 [==============================] - 6s 3ms/step - loss: 3.2911 - accuracy: 0.7924 - val_loss: 0.7218 - val_accuracy: 0.8310
Epoch 2/2
1719/1719 [==============================] - 5s 3ms/step - loss: 0.7282 - accuracy: 0.8245 - val_loss: 0.6826 - val_accuracy: 0.8382
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Dropout | model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dropout(rate=0.2),
keras.layers.Dense(300, activation="elu", kernel_initializer="he_normal"),
keras.layers.Dropout(rate=0.2),
keras.layers.Dense(100, activation="elu", kernel_initializer="he_normal"),
kera... | Epoch 1/2
1719/1719 [==============================] - 6s 3ms/step - loss: 0.7611 - accuracy: 0.7576 - val_loss: 0.3730 - val_accuracy: 0.8644
Epoch 2/2
1719/1719 [==============================] - 5s 3ms/step - loss: 0.4306 - accuracy: 0.8401 - val_loss: 0.3395 - val_accuracy: 0.8722
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Alpha Dropout | tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.AlphaDropout(rate=0.2),
keras.layers.Dense(300, activation="selu", kernel_initializer="lecun_normal"),
keras.layers.AlphaDropout(rate=0.2),
keras.layers.Dense(100, act... | 1719/1719 [==============================] - 2s 1ms/step - loss: 0.4225 - accuracy: 0.8432
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
MC Dropout | tf.random.set_seed(42)
np.random.seed(42)
y_probas = np.stack([model(X_test_scaled, training=True)
for sample in range(100)])
y_proba = y_probas.mean(axis=0)
y_std = y_probas.std(axis=0)
np.round(model.predict(X_test_scaled[:1]), 2)
np.round(y_probas[:, :1], 2)
np.round(y_proba[:1], 2)
y_std = y_pr... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Now we can use the model with MC Dropout: | np.round(np.mean([mc_model.predict(X_test_scaled[:1]) for sample in range(100)], axis=0), 2) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Max norm | layer = keras.layers.Dense(100, activation="selu", kernel_initializer="lecun_normal",
kernel_constraint=keras.constraints.max_norm(1.))
MaxNormDense = partial(keras.layers.Dense,
activation="selu", kernel_initializer="lecun_normal",
kernel_constra... | Epoch 1/2
1719/1719 [==============================] - 5s 3ms/step - loss: 0.5763 - accuracy: 0.8020 - val_loss: 0.3674 - val_accuracy: 0.8674
Epoch 2/2
1719/1719 [==============================] - 5s 3ms/step - loss: 0.3545 - accuracy: 0.8709 - val_loss: 0.3714 - val_accuracy: 0.8662
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Exercises 1. to 7. See appendix A. 8. Deep Learning on CIFAR10 a.*Exercise: Build a DNN with 20 hidden layers of 100 neurons each (that's too many, but it's the point of this exercise). Use He initialization and the ELU activation function.* | keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[32, 32, 3]))
for _ in range(20):
model.add(keras.layers.Dense(100,
activation="elu",
kernel_initial... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
b.*Exercise: Using Nadam optimization and early stopping, train the network on the CIFAR10 dataset. You can load it with `keras.datasets.cifar10.load_data()`. The dataset is composed of 60,000 32 × 32–pixel color images (50,000 for training, 10,000 for testing) with 10 classes, so you'll need a softmax output layer wi... | model.add(keras.layers.Dense(10, activation="softmax")) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Let's use a Nadam optimizer with a learning rate of 5e-5. I tried learning rates 1e-5, 3e-5, 1e-4, 3e-4, 1e-3, 3e-3 and 1e-2, and I compared their learning curves for 10 epochs each (using the TensorBoard callback, below). The learning rates 3e-5 and 1e-4 were pretty good, so I tried 5e-5, which turned out to be slight... | optimizer = keras.optimizers.Nadam(learning_rate=5e-5)
model.compile(loss="sparse_categorical_crossentropy",
optimizer=optimizer,
metrics=["accuracy"]) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Let's load the CIFAR10 dataset. We also want to use early stopping, so we need a validation set. Let's use the first 5,000 images of the original training set as the validation set: | (X_train_full, y_train_full), (X_test, y_test) = keras.datasets.cifar10.load_data()
X_train = X_train_full[5000:]
y_train = y_train_full[5000:]
X_valid = X_train_full[:5000]
y_valid = y_train_full[:5000] | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Now we can create the callbacks we need and train the model: | early_stopping_cb = keras.callbacks.EarlyStopping(patience=20)
model_checkpoint_cb = keras.callbacks.ModelCheckpoint("my_cifar10_model.h5", save_best_only=True)
run_index = 1 # increment every time you train the model
run_logdir = os.path.join(os.curdir, "my_cifar10_logs", "run_{:03d}".format(run_index))
tensorboard_cb... | 157/157 [==============================] - 0s 1ms/step - loss: 1.4960 - accuracy: 0.4762
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
The model with the lowest validation loss gets about 47.6% accuracy on the validation set. It took 27 epochs to reach the lowest validation loss, with roughly 8 seconds per epoch on my laptop (without a GPU). Let's see if we can improve performance using Batch Normalization. c.*Exercise: Now try adding Batch Normaliza... | keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[32, 32, 3]))
model.add(keras.layers.BatchNormalization())
for _ in range(20):
model.add(keras.layers.Dense(100, kernel_initializer="he_normal"))
model.add(keras.... | Epoch 1/100
1407/1407 [==============================] - 19s 9ms/step - loss: 1.9765 - accuracy: 0.2968 - val_loss: 1.6602 - val_accuracy: 0.4042
Epoch 2/100
1407/1407 [==============================] - 11s 8ms/step - loss: 1.6787 - accuracy: 0.4056 - val_loss: 1.5887 - val_accuracy: 0.4304
Epoch 3/100
1407/1407 [=====... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
* *Is the model converging faster than before?* Much faster! The previous model took 27 epochs to reach the lowest validation loss, while the new model achieved that same loss in just 5 epochs and continued to make progress until the 16th epoch. The BN layers stabilized training and allowed us to use a much larger lear... | keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[32, 32, 3]))
for _ in range(20):
model.add(keras.layers.Dense(100,
kernel_initializer="lecun_normal",
... | 157/157 [==============================] - 0s 1ms/step - loss: 1.4633 - accuracy: 0.4792
| Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
We get 47.9% accuracy, which is not much better than the original model (47.6%), and not as good as the model using batch normalization (54.0%). However, convergence was almost as fast as with the BN model, plus each epoch took only 7 seconds. So it's by far the fastest model to train so far. e.*Exercise: Try regulari... | keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[32, 32, 3]))
for _ in range(20):
model.add(keras.layers.Dense(100,
kernel_initializer="lecun_normal",
... | Epoch 1/100
1407/1407 [==============================] - 9s 5ms/step - loss: 2.0583 - accuracy: 0.2742 - val_loss: 1.7429 - val_accuracy: 0.3858
Epoch 2/100
1407/1407 [==============================] - 6s 5ms/step - loss: 1.6852 - accuracy: 0.4008 - val_loss: 1.7055 - val_accuracy: 0.3792
Epoch 3/100
1407/1407 [=======... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
The model reaches 48.9% accuracy on the validation set. That's very slightly better than without dropout (47.6%). With an extensive hyperparameter search, it might be possible to do better (I tried dropout rates of 5%, 10%, 20% and 40%, and learning rates 1e-4, 3e-4, 5e-4, and 1e-3), but probably not much better in thi... | class MCAlphaDropout(keras.layers.AlphaDropout):
def call(self, inputs):
return super().call(inputs, training=True) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Now let's create a new model, identical to the one we just trained (with the same weights), but with `MCAlphaDropout` dropout layers instead of `AlphaDropout` layers: | mc_model = keras.models.Sequential([
MCAlphaDropout(layer.rate) if isinstance(layer, keras.layers.AlphaDropout) else layer
for layer in model.layers
]) | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Then let's add a couple utility functions. The first will run the model many times (10 by default) and it will return the mean predicted class probabilities. The second will use these mean probabilities to predict the most likely class for each instance: | def mc_dropout_predict_probas(mc_model, X, n_samples=10):
Y_probas = [mc_model.predict(X) for sample in range(n_samples)]
return np.mean(Y_probas, axis=0)
def mc_dropout_predict_classes(mc_model, X, n_samples=10):
Y_probas = mc_dropout_predict_probas(mc_model, X, n_samples)
return np.argmax(Y_probas, a... | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
Now let's make predictions for all the instances in the validation set, and compute the accuracy: | keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
y_pred = mc_dropout_predict_classes(mc_model, X_valid_scaled)
accuracy = np.mean(y_pred == y_valid[:, 0])
accuracy | _____no_output_____ | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
We get no accuracy improvement in this case (we're still at 48.9% accuracy).So the best model we got in this exercise is the Batch Normalization model. f.*Exercise: Retrain your model using 1cycle scheduling and see if it improves training speed and model accuracy.* | keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[32, 32, 3]))
for _ in range(20):
model.add(keras.layers.Dense(100,
kernel_initializer="lecun_normal",
... | Epoch 1/15
352/352 [==============================] - 3s 6ms/step - loss: 2.2298 - accuracy: 0.2349 - val_loss: 1.7841 - val_accuracy: 0.3834
Epoch 2/15
352/352 [==============================] - 2s 6ms/step - loss: 1.7928 - accuracy: 0.3689 - val_loss: 1.6806 - val_accuracy: 0.4086
Epoch 3/15
352/352 [================... | Apache-2.0 | 11_training_deep_neural_networks.ipynb | mlbvn/d2l-book-vn |
1 | import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', '... | Number of attempts in the examination is greater than 2:
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
count the number of rows and columns | total_rows=len(df.axes[0])
total_cols=len(df.axes[1])
print("Number of Rows: "+str(total_rows))
print("Number of Columns: "+str(total_cols))
print(f"Number of Rows: {df.shape[0]}")
print(f"Number of Columns: {df.shape[1]}") | Number of Rows: 10
Number of Columns: 4
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
select the rows where the score is missing | print("Rows where score is missing:")
df[df['score'].isnull()]
| Rows where score is missing:
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
select the rows the score is between 15 and 20 (inclusive) | df[df['score'].between(15, 20)]
df[(df['score']>=15) & (df['score']<=20)] | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
select the rows where number of attempts in the examination is less than 2 and score greater than 15 | df[(df['attempts'] < 2) & (df['score'] > 15)] | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
change the score in row 'd' to 11.5 | print("\nOriginal data frame:")
print(df)
print("\nChange the score in row 'd' to 11.5:")
df.loc['d', 'score'] = 11.5
df |
Original data frame:
name score attempts qualify
a Anastasia 12.5 1 yes
b Dima 9.0 3 no
c Katherine 16.5 2 yes
d James NaN 3 no
e Emily 9.0 2 no
f Michael 20.0 3 yes
g Matthew 14.5 1 ... | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
sum of the examination attempts by the students | df['attempts'].sum()
sum(df.attempts) | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
mean score for each different student in DataFrame | np.mean(df['score'])
mean = df['score'].mean()
"{:.2f}".format(mean)
"{:.3f}".format(mean)
"{:.2f}%".format(mean) | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
append a new row 'k' to data frame | print("\nAppend a new row:")
df.loc['k'] = [1, 'Suresh', 'yes', 15.5]
df
df = df.drop('k')
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
sort the DataFrame first by 'name' in descending order, then by 'score' in ascending order | df.sort_values(by=['name', 'score'], ascending=[False, True]) | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
replace the 'qualify' column contains the values 'yes' and 'no' with True and False | print("\nReplace the 'qualify' column contains the values 'yes' and 'no' with True and False:")
df['qualify'] = df['qualify'].map({'yes': True, 'no': False})
df |
Replace the 'qualify' column contains the values 'yes' and 'no' with True and False:
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
change the name 'James' to 'Suresh' in name column of the DataFrame | df['name'] = df['name'].replace('James', 'Suresh')
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
delete the 'attempts' column from the DataFrame | df.pop('attempts')
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
insert a new column in existing DataFrame | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', '... | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
iterate over rows in a DataFrame | for index, row in df.iterrows():
print(row['name'], row['score']) | Anastasia 12.5
Dima 9.0
Katherine 16.5
James nan
Emily 9.0
Michael 20.0
Matthew 14.5
Laura nan
Kevin 8.0
Jonas 19.0
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
get list from DataFrame column headers | list(df.columns.values) | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
rename columns of a given DataFrame | d = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
df
df.columns = ['Column1', 'Column2', 'Column3']
df = df.rename(columns={'col1': 'Column1', 'col2': 'Column2', 'col3': 'Column3'})
print("New DataFrame after renaming columns:")
df | New DataFrame after renaming columns:
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
select rows from a given DataFrame based on values in some columns | d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]}
df = pd.DataFrame(data=d)
df
df.loc[df['col1'] == 4] | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
change the order of a DataFrame columns | df[['col3', 'col2', 'col1']] | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
add one row in an existing DataFrame | df2 = {'col1': 10, 'col2': 11, 'col3': 12}
df = df.append(df2, ignore_index=True)
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
count city wise number of people from a given of data set |
df1 = pd.DataFrame({'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'city': ['California', 'Los Angeles', 'California', 'California', 'California', 'Los Angeles', 'Los Angeles', 'Georgia', 'Georgia', 'Los Angeles']})
g1 = df1.groupby(["city"]).size().reset... | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
delete DataFrame row(s) based on given column value | df = df[df.col2 != 5]
print("New DataFrame")
df | New DataFrame
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
widen output display to see more columns | pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 50)
pd.set_option('display.width', 200)
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
select a row of series/dataframe by given integer index | result = df.iloc[[2]]
print("Index-2: Details")
result | Index-2: Details
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
replace all the NaN values with Zero's in a column of a dataframe | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'n... | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
convert index in a column of the given dataframe. | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'n... | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
set a given value for particular cell in DataFrame using index value | df
print("\nSet a given value for particular cell in the DataFrame")
df.at[8,'score']=100
df
|
Set a given value for particular cell in the DataFrame
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
count the NaN values in one or more columns in DataFrame | df.isnull().values.sum() | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
drop a list of rows from a specified DataFrame | df = df.drop(df.index[[2,4]])
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
reset index in a given DataFrame. | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'n... |
Reset the Index:
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
devide a DataFrame in a given ratio | s1 = pd.Series(['100', '200', 'python', '300.12', '400'])
s2 = pd.Series(['10', '20', 'php', '30.12', '40'])
print("Data Series:")
s1
s2
df = pd.concat([s1, s2], axis=1)
print("New DataFrame combining two series:")
df | New DataFrame combining two series:
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
shuffle a given DataFrame rows | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'n... | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
41. Write a Pandas program to convert DataFrame column type from string to datetime. | s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000'])
s
r = pd.to_datetime(pd.Series(s))
df = pd.DataFrame(r)
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
42. Write a Pandas program to rename a specific column name in a given DataFrame. | d = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
df
df=df.rename(columns = {'col2':'Column2'})
list(df.columns) | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
get a list of a specified column of a DataFrame. | lst = df["col1"].tolist()
lst | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
get the specified row value of a given DataFrame | print("Value of Row1")
df.iloc[0]
print("Value of Row4")
df.iloc[2] | Value of Row4
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
get the datatypes of columns of a DataFrame | df.dtypes | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
append data to an empty DataFrame | df = pd.DataFrame()
data = pd.DataFrame({"col1": range(3),"col2": range(3)})
print("After appending some data:")
df = df.append(data)
df | After appending some data:
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
convert the datatype of a given column | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9.1, 16.5, 12.77, 9.21, 20.22, 14.5, 11.34, 8.8, 19.13],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes... | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
group by the first column and get second column as lists in rows. | df = pd.DataFrame( {'col1':['C1','C1','C2','C2','C2','C3','C2'], 'col2':[1,2,3,3,4,6,5]})
print("Original DataFrame")
df
df = df.groupby('col1')['col2'].apply(list)
df | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
Write a Pandas program to select all columns, except one given column in a DataFrame. | d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
df
print("\nAll columns except 'col3':")
df = df.loc[:, df.columns != 'col3']
df |
All columns except 'col3':
| MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
Write a Pandas program to get topmost n records within each group of a DataFrame. | d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
df
print("\ntopmost n records within each group of a DataFrame:")
df1 = df.nlargest(2, 'col1')
df1
df2 = df.nlargest(3, 'col2')
df2
df3 = df.nlargest(3, 'col3')
df3 | _____no_output_____ | MIT | Pandas_Exercise_Dataframe.ipynb | yaozeliang/pandas_share |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.