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 |
|---|---|---|---|---|---|
ํ๋ จ ํ ํ
์คํธ์
์ ๋ํ ์ ํ๋๊ฐ 90%๋ฅผ ์กฐ๊ธ ์๋ ์ ๋๋ก ๋ง์ด ํฅ์๋์๋ค. | model = get_model()
callbacks = [
keras.callbacks.ModelCheckpoint("binary_2gram.keras",
save_best_only=True)
]
model.fit(binary_2gram_train_ds.cache(),
validation_data=binary_2gram_val_ds.cache(),
epochs=10,
callbacks=callbacks)
model = keras.mode... | Epoch 1/10
625/625 [==============================] - 12s 18ms/step - loss: 0.3857 - accuracy: 0.8347 - val_loss: 0.2791 - val_accuracy: 0.9000
Epoch 2/10
625/625 [==============================] - 4s 6ms/step - loss: 0.2592 - accuracy: 0.9082 - val_loss: 0.2947 - val_accuracy: 0.8988
Epoch 3/10
625/625 [==============... | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
**๋ฐฉ์ 3: ๋ฐ์ด๊ทธ๋จ TF-IDF ์ธ์ฝ๋ฉ** N-๊ทธ๋จ์ ๋ฒกํฐํํ ๋ ์ฌ์ฉ ๋น๋๋ฅผ ํจ๊ป ์ ์ฅํ๋ ๋ฐฉ์์ ์ฌ์ฉํ ์ ์๋ค.๋จ์ด์ ์ฌ์ฉ ๋น๋๊ฐ ์๋ฌด๋๋ ๋ฌธ์ฅ ํ๊ฐ์ ์ค์ํ ์ญํ ์ ์ํํ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ด๋ค.์๋ ์ฝ๋์์์ฒ๋ผ `output_mode="count"` ์ต์
์ ์ฌ์ฉํ๋ฉด ๋๋ค. | text_vectorization = TextVectorization(
ngrams=2,
max_tokens=20000,
output_mode="count"
) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
๊ทธ๋ฐ๋ฐ ์ด๋ ๊ฒ ํ๋ฉด "the", "a", "is", "are" ๋ฑ์ ์ฌ์ฉ ๋น๋๋ ๋งค์ฐ ๋์ ๋ฐ๋ฉด์"Chollet" ๋ฑ์ ๋จ์ด๋ ๋น๋๊ฐ ๊ฑฐ์ 0์ ๊ฐ๊น๊ฒ ๋์จ๋ค.๋ํ ์์ฑ๋ ๋ฒกํฐ์ ๋๋ถ๋ถ์ 0์ผ๋ก ์ฑ์์ง ๊ฒ์ด๋ค. `max_tokens=20000`์ ์ฌ์ฉํ ๋ฐ๋ฉด์ ํ๋์ ๋ฌธ์ฅ์ ๋ง์์ผ ๋ช ์ญ๊ฐ ์ ๋์ ๋จ์ด๋ง ์ฌ์ฉ๋์๊ธฐ ๋๋ฌธ์ด๋ค. ```pythoninputs[0]: tf.Tensor([1. 1. 1. ... 0. 0. 0.], shape=(20000,), dtype=float32)``` ์ด ์ ์ ๊ณ ๋ คํด์ ์ฌ์ฉ ๋น๋๋ฅผ ์ ๊ทํํ๋ค. ํ๊ท ์ ์์ ์ผ๋ก ๋ง๋ค์ง๋ ์๊ณ TF-IDF ... | text_vectorization = TextVectorization(
ngrams=2,
max_tokens=20000,
output_mode="tf_idf",
) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
ํ๋ จ ํ ํ
์คํธ์
์ ๋ํ ์ ํ๋๊ฐ ๋ค์ 89% ์๋๋ก ๋ด๋ ค๊ฐ๋ค.์ฌ๊ธฐ์๋ ๋ณ ๋์์ด ๋์ง ์์์ง๋ง ๋ง์ ํ
์คํธ ๋ถ๋ฅ ๋ชจ๋ธ์์๋ 1% ์ ๋์ ์ฑ๋ฅ ํฅ์์ ๊ฐ์ ธ์จ๋ค.**์ฃผ์์ฌํญ**: ์๋ ์ฝ๋๋ ํ์ฌ(Tensorflow 2.6๊ณผ 2.7) GPU๋ฅผ ์ฌ์ฉํ์ง ์๋ ๊ฒฝ์ฐ์๋ง ์๋ํ๋ค. ์ด์ ๋ ์์ง ๋ชจ๋ฅธ๋ค([์ฌ๊ธฐ ์ฐธ์กฐ](https://github.com/fchollet/deep-learning-with-python-notebooks/issues/190)). | text_vectorization.adapt(text_only_train_ds)
tfidf_2gram_train_ds = train_ds.map(lambda x, y: (text_vectorization(x), y))
tfidf_2gram_val_ds = val_ds.map(lambda x, y: (text_vectorization(x), y))
tfidf_2gram_test_ds = test_ds.map(lambda x, y: (text_vectorization(x), y))
model = get_model()
model.summary()
callbacks = ... | Model: "model_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_3 (InputLayer) [(None, 20000)] 0
... | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
**๋ถ๋ก: ๋ฌธ์์ด ๋ฒกํฐํ ์ ์ฒ๋ฆฌ๋ฅผ ํจ๊ป ์ฒ๋ฆฌํ๋ ๋ชจ๋ธ ๋ด๋ณด๋ด๊ธฐ** ํ๋ จ๋ ๋ชจ๋ธ์ ์ค์ ์ ๋ฐฐ์นํ๋ ค๋ฉด ํ
์คํธ ๋ฒกํฐํ๋ ๋ชจ๋ธ๊ณผ ํจ๊ป ๋ด๋ณด๋ด์ผ ํ๋ค.์ด๋ฅผ ์ํด `TextVectorization` ์ธต์ ๊ฒฐ๊ณผ๋ฅผ ์ฌํ์ฉ๋ง ํ๋ฉด ๋๋ค. | inputs = keras.Input(shape=(1,), dtype="string")
# ํ
์คํธ ๋ฒกํฐํ ์ถ๊ฐ
processed_inputs = text_vectorization(inputs)
# ํ๋ จ๋ ๋ชจ๋ธ์ ์ ์ฉ
outputs = model(processed_inputs)
# ์ต์ข
๋ชจ๋ธ
inference_model = keras.Model(inputs, outputs) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
`inference_model`์ ์ผ๋ฐ ํ
์คํธ ๋ฌธ์ฅ์ ์ง์ ์ธ์๋ก ๋ฐ์ ์ ์๋ค.์๋ฅผ ๋ค์ด "That was an excellent movie, I loved it."๋ผ๋ ๋ฆฌ๋ทฐ๋๊ธ์ ์ผ ํ๋ฅ ์ด ๋งค์ฐ ๋๋ค๊ณ ์์ธก๋๋ค. | import tensorflow as tf
raw_text_data = tf.convert_to_tensor([
["That was an excellent movie, I loved it."],
])
predictions = inference_model(raw_text_data)
print(f"{float(predictions[0] * 100):.2f} percent positive") | 92.10 percent positive
| MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
Loading neurons from s3 | import numpy as np
from skimage import io
from pathlib import Path
from brainlit.utils.session import NeuroglancerSession
from brainlit.utils.Neuron_trace import NeuronTrace
import napari
from napari.utils import nbscreenshot
%gui qt | _____no_output_____ | Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
Loading entire neuron from AWS `s3_trace = NeuronTrace(s3_path,seg_id,mip)` to create a NeuronTrace object with s3 file path`swc_trace = NeuronTrace(swc_path)` to create a NeuronTrace object with swc file path1. `s3_trace.get_df()` to output the s3 NeuronTrace object as a pd.DataFrame2. `swc_trace.get_df()` to output... | """
s3_path = "s3://open-neurodata/brainlit/brain1_segments"
seg_id = 2
mip = 1
s3_trace = NeuronTrace(s3_path, seg_id, mip)
df = s3_trace.get_df()
df.head()
""" | Downloading: 100%|โโโโโโโโโโ| 1/1 [00:00<00:00, 5.13it/s]
Downloading: 100%|โโโโโโโโโโ| 1/1 [00:00<00:00, 5.82it/s]
| Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
2. `swc_trace.get_df()`This function outputs the swc NeuronTrace object as a pd.DataFrame. Each row is a vertex in the swc file with the following information: `sample number``structure identifier``x coordinate``y coordinate``z coordinate``radius of dendrite``sample number of parent`The coordinates are given in spatia... | """
swc_path = str(Path().resolve().parents[2] / "data" / "data_octree" / "consensus-swcs" / '2018-08-01_G-002_consensus.swc')
swc_trace = NeuronTrace(path=swc_path)
df = swc_trace.get_df()
df.head()
""" | _____no_output_____ | Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
3. `swc_trace.generate_df_subset(list_of_voxels)`This function creates a smaller subset of the original dataframe with coordinates in img space. Each row is a vertex in the swc file with the following information: `sample number``structure identifier``x coordinate``y coordinate``z coordinate``radius of dendrite``sampl... | """# Choose vertices to use for the subneuron
subneuron_df = df[0:3]
vertex_list = subneuron_df['sample'].array
# Define a neuroglancer session
url = "s3://open-neurodata/brainlit/brain1"
mip = 1
ngl = NeuroglancerSession(url, mip=mip)
# Get vertices
seg_id = 2
buffer = 10
img, bounds, vox_in_img_list = ngl.pull_ve... | Downloading: 100%|โโโโโโโโโโ| 1/1 [00:00<00:00, 6.08it/s]
Downloading: 100%|โโโโโโโโโโ| 1/1 [00:00<00:00, 6.95it/s]
Downloading: 100%|โโโโโโโโโโ| 1/1 [00:00<00:00, 5.02it/s]
Downloading: 0%| | 0/4 [00:01<?, ?it/s] sample structure x y z r parent
0 1 0 106 106 112 1.0 ... | Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
4. `swc_trace.get_df_voxel()` If we want to overlay the swc file with a corresponding image, we need to make sure that they are in the same coordinate space. Because an image in an array of voxels, it makes sense to convert the vertices from spatial units into voxel units.Given the `spacing` (spatial units/voxel) and ... | # spacing = np.array([0.29875923,0.3044159,0.98840415])
# origin = np.array([70093.276,15071.596,29306.737])
# df_voxel = swc_trace.get_df_voxel(spacing=spacing, origin=origin)
# df_voxel.head() | _____no_output_____ | Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
5. `swc_trace.get_graph()`A neuron is a graph with no cycles (tree). While napari does not support displaying graph objects, it can display multiple paths. The DataFrame already contains all the possible edges in the neurons. Each row in the DataFrame is an edge. For example, from the above we can see that `sample 2`... | # G = swc_trace.get_graph()
# print('Number of nodes:', len(G.nodes))
# print('Number of edges:', len(G.edges))
# print('\n')
# print('Sample 1 coordinates (x,y,z)')
# print(G.nodes[1]['x'],G.nodes[1]['y'],G.nodes[1]['z']) | Number of nodes: 1650
Number of edges: 1649
Sample 1 coordinates (x,y,z)
-387 1928 -1846
| Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
6. `swc_trace.get_paths()` This function returns the NeuronTrace object as a list of non-overlapping paths. The union of the paths forms the graph.The algorithm works by:1. Find longest path in the graph ([networkx.algorithms.dag.dag_longest_path](https://networkx.github.io/documentation/stable/reference/algorithms/ge... | # paths = swc_trace.get_paths()
# print(f"The graph was decomposed into {len(paths)} paths") | The graph was decomposed into 179 paths
| Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
7. `ViewerModel.add_shapes`napari displays "layers". The most common layer is the image layer. In order to display the neuron, we use `path` from the [shapes](https://napari.org/tutorials/shapes) layer | # viewer = napari.Viewer(ndisplay=3)
# viewer.add_shapes(data=paths, shape_type='path', edge_color='white', name='Skeleton 2')
# nbscreenshot(viewer) | _____no_output_____ | Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
Loading sub-neuronThe image of the entire brain has dimensions of (33792, 25600, 13312) voxels. G-002 spans a sub-image of (7386, 9932, 5383) voxels. Both are too big to load in napari and overlay the neuron.To circumvent this, we can crop out a smaller region of the neuron, load the sub-neuron, and load the correspon... | # # Create an NGL session to get the bounding box
# url = "s3://open-neurodata/brainlit/brain1"
# mip = 1
# ngl = NeuroglancerSession(url, mip=mip)
# img, bbbox, vox = ngl.pull_chunk(2, 300, 1)
# bbox = bbbox.to_list()
# box = (bbox[:3], bbox[3:])
# print(box)
# G_sub = s3_trace.get_sub_neuron(box)
# paths_sub = s3_tr... | 459
| Apache-2.0 | docs/notebooks/visualization/loading.ipynb | neurodata/brainl |
Deep Convolutional GANsIn this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The DCGAN architecture was first explored in 2016 and has seen impressive results in generating new images; you can read the [original ... | # import libraries
import matplotlib.pyplot as plt
import numpy as np
import pickle as pkl
%matplotlib inline | _____no_output_____ | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
Getting the dataHere you can download the SVHN dataset. It's a dataset built-in to the PyTorch datasets library. We can load in training data, transform it into Tensor datatypes, then create dataloaders to batch our data into a desired size. | import torch
from torchvision import datasets
from torchvision import transforms
# Tensor transform
transform = transforms.ToTensor()
# SVHN training datasets
svhn_train = datasets.SVHN(root='data/', split='train', download=True, transform=transform)
batch_size = 128
num_workers = 0
# build DataLoaders for SVHN dat... | Using downloaded and verified file: data/train_32x32.mat
| MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
Visualize the DataHere I'm showing a small sample of the images. Each of these is 32x32 with 3 color channels (RGB). These are the real, training images that we'll pass to the discriminator. Notice that each image has _one_ associated, numerical label. | # obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
plot_size=20
for idx in np.arange(plot_size):
ax = fig.add_subplot(2, plot_size/2, idx+1, xticks=[], yticks=[])
... | <ipython-input-3-a55faf2ffde6>:9: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later.
ax = fig.add_subplot(2, plot_size/2, idx+1, xticks=[], yticks=[])
| MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
Pre-processing: scaling from -1 to 1We need to do a bit of pre-processing; we know that the output of our `tanh` activated generator will contain pixel values in a range from -1 to 1, and so, we need to rescale our training images to a range of -1 to 1. (Right now, they are in a range from 0-1.) | # current range
img = images[0]
print('Min: ', img.min())
print('Max: ', img.max())
# helper scale function
def scale(x, feature_range=(-1, 1)):
''' Scale takes in an image x and returns that image, scaled
with a feature_range of pixel values from -1 to 1.
This function assumes that the input x is a... | Scaled min: tensor(-0.4196)
Scaled max: tensor(0.2627)
| MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
--- Define the ModelA GAN is comprised of two adversarial networks, a discriminator and a generator. DiscriminatorHere you'll build the discriminator. This is a convolutional classifier like you've built before, only without any maxpooling layers. * The inputs to the discriminator are 32x32x3 tensor images* You'll wan... | import torch.nn as nn
import torch.nn.functional as F
# helper conv function
def conv(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
"""Creates a convolutional layer, with optional batch normalization.
"""
layers = []
conv_layer = nn.Conv2d(in_channels, out_channels,
... | _____no_output_____ | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
GeneratorNext, you'll build the generator network. The input will be our noise vector `z`, as before. And, the output will be a $tanh$ output, but this time with size 32x32 which is the size of our SVHN images.What's new here is we'll use transpose convolutional layers to create our new images. * The first layer is a ... | # helper deconv function
def deconv(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
"""Creates a transposed-convolutional layer, with optional batch normalization.
"""
## TODO: Complete this function
## create a sequence of transpose + optional batch norm layers
layers... | _____no_output_____ | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
Build complete networkDefine your models' hyperparameters and instantiate the discriminator and generator from the classes defined above. Make sure you've passed in the correct input arguments. | # define hyperparams
conv_dim = 32
z_size = 100
# define discriminator and generator
D = Discriminator(conv_dim)
G = Generator(z_size=z_size, conv_dim=conv_dim)
print(D)
print()
print(G) | Discriminator(
(conv1): Sequential(
(0): Conv2d(3, 32, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
)
(conv2): Sequential(
(0): Conv2d(32, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats... | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
Training on GPUCheck if you can train on GPU. If you can, set this as a variable and move your models to GPU. > Later, we'll also move any inputs our models and loss functions see (real_images, z, and ground truth labels) to GPU as well. | train_on_gpu = torch.cuda.is_available()
if train_on_gpu:
# move models to GPU
G.cuda()
D.cuda()
print('GPU available for training. Models moved to GPU')
else:
print('Training on CPU.')
| GPU available for training. Models moved to GPU
| MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
--- Discriminator and Generator LossesNow we need to calculate the losses. And this will be exactly the same as before. Discriminator Losses> * For the discriminator, the total loss is the sum of the losses for real and fake images, `d_loss = d_real_loss + d_fake_loss`. * Remember that we want the discriminator to outp... | def real_loss(D_out, smooth=False):
batch_size = D_out.size(0)
# label smoothing
if smooth:
# smooth, real labels = 0.9
labels = torch.ones(batch_size)*0.9
else:
labels = torch.ones(batch_size) # real labels = 1
# move labels to GPU if available
if train_on_gpu:
... | _____no_output_____ | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
OptimizersNot much new here, but notice how I am using a small learning rate and custom parameters for the Adam optimizers, This is based on some research into DCGAN model convergence. HyperparametersGANs are very sensitive to hyperparameters. A lot of experimentation goes into finding the best hyperparameters such th... | import torch.optim as optim
# params
lr = 0.0002
beta1=0.5
beta2=0.999
# Create optimizers for the discriminator and generator
d_optimizer = optim.Adam(D.parameters(), lr, [beta1, beta2])
g_optimizer = optim.Adam(G.parameters(), lr, [beta1, beta2]) | _____no_output_____ | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
--- TrainingTraining will involve alternating between training the discriminator and the generator. We'll use our functions `real_loss` and `fake_loss` to help us calculate the discriminator losses in all of the following cases. Discriminator training1. Compute the discriminator loss on real, training images 2. ... | import pickle as pkl
# training hyperparams
num_epochs = 30
# keep track of loss and generated, "fake" samples
samples = []
losses = []
print_every = 300
# Get some fixed data for sampling. These are images that are held
# constant throughout training, and allow us to inspect the model's performance
sample_size=16
... | Epoch [ 1/ 30] | d_loss: 1.4085 | g_loss: 0.9993
Epoch [ 1/ 30] | d_loss: 0.6737 | g_loss: 1.9478
Epoch [ 2/ 30] | d_loss: 0.7026 | g_loss: 2.6182
Epoch [ 2/ 30] | d_loss: 0.4292 | g_loss: 2.3596
Epoch [ 3/ 30] | d_loss: 0.2889 | g_loss: 2.7350
Epoch [ 3/ 30] | d_loss: 0.1361 | g_loss: 4.5... | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
Training lossHere we'll plot the training losses for the generator and discriminator, recorded after each epoch. | fig, ax = plt.subplots()
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator', alpha=0.5)
plt.plot(losses.T[1], label='Generator', alpha=0.5)
plt.title("Training Losses")
plt.legend() | _____no_output_____ | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
Generator samples from trainingHere we can view samples of images from the generator. We'll look at the images we saved during training. | # helper function for viewing a list of passed in sample images
def view_samples(epoch, samples):
fig, axes = plt.subplots(figsize=(16,4), nrows=2, ncols=8, sharey=True, sharex=True)
for ax, img in zip(axes.flatten(), samples[epoch]):
img = img.detach().cpu().numpy()
img = np.transpose(img, (1, ... | _____no_output_____ | MIT | DCGAN_Exercise.ipynb | ng572/DCGAN_SVHN |
get names of each condition for later | pd.Categorical(luminescence_raw_df.condition)
names = luminescence_raw_df.condition.unique()
for name in names:
print(name)
#get list of promoters
pd.Categorical(luminescence_raw_df.Promoter)
prom_names = luminescence_raw_df.Promoter.unique()
for name in prom_names:
print(name) | UBQ10
NIR1
NOS
STAP4
NRP
| MIT | src/plotting/luminescence/24.11.19/luminescence_plots.ipynb | Switham1/PromoterArchitecture |
test normality | #returns test statistic, p-value
for name1 in prom_names:
for name in names:
print('{}: {}'.format(name, stats.shapiro(luminescence_raw_df['nluc/fluc'][luminescence_raw_df.condition == name])))
| nitrate_free: (0.7033216953277588, 0.0002697518502827734)
100mM nitrate_2hrs_morning: (0.7973607182502747, 0.00463036959990859)
100mM nitrate_overnight: (0.8101227879524231, 0.004972793627530336)
nitrate_free: (0.7033216953277588, 0.0002697518502827734)
100mM nitrate_2hrs_morning: (0.7973607182502747, 0.004630369599908... | MIT | src/plotting/luminescence/24.11.19/luminescence_plots.ipynb | Switham1/PromoterArchitecture |
not normal | #test variance
stats.levene(luminescence_raw_df['nluc/fluc'][luminescence_raw_df.condition == names[0]],
luminescence_raw_df['nluc/fluc'][luminescence_raw_df.condition == names[1]],
luminescence_raw_df['nluc/fluc'][luminescence_raw_df.condition == names[2]])
test = luminescence_raw_df.gr... | _____no_output_____ | MIT | src/plotting/luminescence/24.11.19/luminescence_plots.ipynb | Switham1/PromoterArchitecture |
ะะฐะณััะทะบะฐ ะฑะธะฑะปะธะพัะตะบ ะธ ะดะฐะฝะฝัั
| !pip install simpletransformers==0.61.13
!pip uninstall transformers
!pip install transformers==4.10.0
!git clone https://github.com/GoldenRMT/WikiSearch.git
!pip install googledrivedownloader
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from nltk.corpus import stopwords
nltk.download('wordnet')
stopwo... | Downloading 13Nuwm7BV-4RXI9JqjPTDE9rcdupkKqlF into /Data/AIIJC/aiijc_1578_goodFromTrain_pretrained.model... Done.
| MIT | solution_AIIJC(NLP)/Notebooks/singleAnswering_Aiijc.ipynb | Makual/AIIJC_NLP |
ะคัะฝะบัะธะธ ะดะปั ะฟัะตะดะพะฑัะฐะฑะพัะบะธ ัะตะบััะฐ | def normal_form(word): #ะะพะปััะตะฝะธะต ะฝะพัะผะฐะปัะฝะพะน ัะพัะผั ัะปะพะฒะฐ
word = word.lower()
return word
def clean_html(html): #ะัะธััะบะฐ html
soup = BeautifulSoup(BeautifulSoup(html, "lxml").text)
return str(soup.body)
def get_good_tokens(text): #ะัะดะตะปะตะฝะธะต ะบะปััะตะฒัั
ัะปะพะฒ
good_tokens = []
for tokens in tokenizer(text)[1]:... | _____no_output_____ | MIT | solution_AIIJC(NLP)/Notebooks/singleAnswering_Aiijc.ipynb | Makual/AIIJC_NLP |
ะะฐะณััะทะบะฐ ะผะพะดะตะปะธ ะธ ััะฝะบัะธั ะดะปั ะพัะฒะตัะพะฒ ะฝะฐ ะฒะพะฟัะพั | model = joblib.load('/Data/AIIJC/aiijc_1578_goodFromTrain_pretrained.model')
model.args.max_seq_length = 512
model.args.silent = True
def answering(question):
text = question
good_tokens = get_good_tokens(text)
try:
urls = wikipedia.search(text,results=2)
except:
link_1 = '-'
link_2 = '-'
tr... | _____no_output_____ | MIT | solution_AIIJC(NLP)/Notebooks/singleAnswering_Aiijc.ipynb | Makual/AIIJC_NLP |
ะัะพะฒะตัะบะฐ ัะฐะฑะพัะพัะฟะพัะพะฑะฝะพััะธ ะธ ะฒัะตะผะตะฝะธ ัะฐะฑะพัั ััะฝะบัะธะธ | import time
time_1 = time.time()
print(answering("What is the name of Trump first daughter?"))
print('ะัะตะผั ะพะฑัะฐะฑะพัะบะธ ะทะฐะฟัะพัะฐ: ' + str(time.time()-time_1)) | Ivana Marie "Ivanka" Trump
ะัะตะผั ะพะฑัะฐะฑะพัะบะธ ะทะฐะฟัะพัะฐ: 1.6687853336334229
| MIT | solution_AIIJC(NLP)/Notebooks/singleAnswering_Aiijc.ipynb | Makual/AIIJC_NLP |
CNTK 101: Logistic Regression and ML PrimerThis tutorial is targeted to individuals who are new to CNTK and to machine learning. In this tutorial, you will train a simple yet powerful machine learning model that is widely used in industry for a variety of applications. The model trained below scales to massive data se... | # Figure 1
Image(url="https://www.cntk.ai/jup/cancer_data_plot.jpg", width=400, height=400) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
**Goal**:Our goal is to learn a classifier that can automatically label any patient into either the benign or malignant categories given two features (age and tumor size). In this tutorial, we will create a linear classifier, a fundamental building-block in deep networks. | # Figure 2
Image(url= "https://www.cntk.ai/jup/cancer_classify_plot.jpg", width=400, height=400) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
In the figure above, the green line represents the model learned from the data and separates the blue dots from the red dots. In this tutorial, we will walk you through the steps to learn the green line. Note: this classifier does make mistakes, where a couple of blue dots are on the wrong side of the green line. Howev... | # Figure 3
Image(url= "https://www.cntk.ai/jup/logistic_neuron.jpg", width=300, height=200) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
In the above figure, contributions from different input features are linearly weighted and aggregated. The resulting sum is mapped to a (0, 1) range via a [sigmoid]( https://en.wikipedia.org/wiki/Sigmoid_function) function. For classifiers with more than two output labels, one can use a [softmax](https://en.wikipedia.o... | # Import the relevant components
from __future__ import print_function
import numpy as np
import sys
import os
import cntk as C
import cntk.tests.test_utils
cntk.tests.test_utils.set_device_from_pytest_env() # (only needed for our build system)
C.cntk_py.set_fixed_random_seed(1) # fix the random seed so that LR exampl... | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Data GenerationLet us generate some synthetic data emulating the cancer example using the `numpy` library. We have two input features (represented in two-dimensions) and two output classes (benign/blue or malignant/red). In our example, each observation (a single 2-tuple of features - age and size) in the training dat... | # Define the network
input_dim = 2
num_output_classes = 2 | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Input and LabelsIn this tutorial we are generating synthetic data using the `numpy` library. In real-world problems, one would use a [reader](https://docs.microsoft.com/en-us/cognitive-toolkit/brainscript-and-python---understanding-and-extending-readers), that would read feature values (`features`: *age* and *tumor si... | # Ensure that we always get the same results
np.random.seed(0)
# Helper function to generate a random data sample
def generate_random_data_sample(sample_size, feature_dim, num_classes):
# Create synthetic data using NumPy.
Y = np.random.randint(size=(sample_size, 1), low=0, high=num_classes)
# Make sure ... | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Let us visualize the input data.**Note**: If the import of `matplotlib.pyplot` fails, please run `conda install matplotlib`, which will fix the `pyplot` version dependencies. If you are on a python environment different from Anaconda, then use `pip install matplotlib`. | # Plot the data
import matplotlib.pyplot as plt
%matplotlib inline
# let 0 represent malignant/red and 1 represent benign/blue
colors = ['r' if label == 0 else 'b' for label in labels[:,0]]
plt.scatter(features[:,0], features[:,1], c=colors)
plt.xlabel("Age (scaled)")
plt.ylabel("Tumor size (in cm)")
plt.show() | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Model CreationA logistic regression (a.k.a. LR) network is a simple building block, but has powered many ML applications in the past decade. LR is a simple linear model that takes as input a vector of numbers describing the properties of what we are classifying (also known as a feature vector, $\bf{x}$, the blue nodes... | # Figure 4
Image(url= "https://www.cntk.ai/jup/logistic_neuron2.jpg", width=300, height=200) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
The first step is to compute the evidence for an observation. $$z = \sum_{i=1}^n w_i \times x_i + b = \textbf{w} \cdot \textbf{x} + b$$ where $\bf{w}$ is the weight vector of length $n$ and $b$ is known as the [bias](https://www.quora.com/What-does-the-bias-term-represent-in-logistic-regression) term. Note: we use **bo... | feature = C.input_variable(input_dim, np.float32) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Network setupThe `linear_layer` function is a straightforward implementation of the equation above. We perform two operations:0. multiply the weights ($\bf{w}$) with the features ($\bf{x}$) using the CNTK `times` operator,1. add the bias term ($b$).These CNTK operations are optimized for execution on the available ha... | # Define a dictionary to store the model parameters
mydict = {}
def linear_layer(input_var, output_dim):
input_dim = input_var.shape[0]
weight_param = C.parameter(shape=(input_dim, output_dim))
bias_param = C.parameter(shape=(output_dim))
mydict['w'], mydict['b'] = weight_param, bias_param
... | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
`z` will be used to represent the output of the network. | output_dim = num_output_classes
z = linear_layer(feature, output_dim) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Learning model parametersNow that the network is set up, we would like to learn the parameters $\bf w$ and $b$ for our simple linear layer. To do so we convert, the computed evidence ($z$) into a set of predicted probabilities ($\textbf p$) using a `softmax` function.$$ \textbf{p} = \mathrm{softmax}(z)$$ The `softmax`... | label = C.input_variable(num_output_classes, np.float32)
loss = C.cross_entropy_with_softmax(z, label) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
EvaluationIn order to evaluate the classification, we can compute the [classification_error](https://www.cntk.ai/pythondocs/cntk.metrics.htmlcntk.metrics.classification_error), which is 0 if our model was correct (it assigned the true label the most probability), otherwise 1. | eval_error = C.classification_error(z, label) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Configure trainingThe trainer strives to minimize the `loss` function using an optimization technique. In this tutorial, we will use [Stochastic Gradient Descent](https://en.wikipedia.org/wiki/Stochastic_gradient_descent) (`sgd`), one of the most popular techniques. Typically, one starts with random initialization of ... | # Instantiate the trainer object to drive the model training
learning_rate = 0.5
lr_schedule = C.learning_rate_schedule(learning_rate, C.UnitType.minibatch)
learner = C.sgd(z.parameters, lr_schedule)
trainer = C.Trainer(z, (loss, eval_error), [learner]) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
First, let us create some helper functions that will be needed to visualize different functions associated with training. Note: these convenience functions are for understanding what goes on under the hood. | # Define a utility function to compute the moving average.
# A more efficient implementation is possible with np.cumsum() function
def moving_average(a, w=10):
if len(a) < w:
return a[:]
return [val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)]
# Define a utility that prints... | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Run the trainerWe are now ready to train our Logistic Regression model. We want to decide what data we need to feed into the training engine.In this example, each iteration of the optimizer will work on 25 samples (25 dots w.r.t. the plot above) a.k.a. `minibatch_size`. We would like to train on 20000 observations. If... | # Initialize the parameters for the trainer
minibatch_size = 25
num_samples_to_train = 20000
num_minibatches_to_train = int(num_samples_to_train / minibatch_size)
from collections import defaultdict
# Run the trainer and perform model training
training_progress_output_freq = 50
plotdata = defaultdict(list)
for i in ... | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Run evaluation / Testing Now that we have trained the network, let us evaluate the trained network on data that hasn't been used for training. This is called **testing**. Let us create some new data and evaluate the average error and loss on this set. This is done using `trainer.test_minibatch`. Note the error on this... | # Run the trained model on a newly generated dataset
test_minibatch_size = 25
features, labels = generate_random_data_sample(test_minibatch_size, input_dim, num_output_classes)
trainer.test_minibatch({feature : features, label : labels}) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Checking prediction / evaluation For evaluation, we softmax the output of the network into a probability distribution over the two classes, the probability of each observation being malignant or benign. | out = C.softmax(z)
result = out.eval({feature : features}) | _____no_output_____ | MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
Let us compare the ground-truth label with the predictions. They should be in agreement.**Question:** - How many predictions were mislabeled? Can you change the code below to identify which observations were misclassified? | print("Label :", [np.argmax(label) for label in labels])
print("Predicted:", [np.argmax(x) for x in result]) | Label : [1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1]
Predicted: [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1]
| MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
VisualizationIt is desirable to visualize the results. In this example, the data can be conveniently plotted using two spatial dimensions for the input (patient age on the x-axis and tumor size on the y-axis), and a color dimension for the output (red for malignant and blue for benign). For data with higher dimensions... | # Model parameters
print(mydict['b'].value)
bias_vector = mydict['b'].value
weight_matrix = mydict['w'].value
# Plot the data
import matplotlib.pyplot as plt
# let 0 represent malignant/red, and 1 represent benign/blue
colors = ['r' if label == 0 else 'b' for label in labels[:,0]]
plt.scatter(features[:,0], featu... | [ 8.00007153 -8.00006485]
| MIT | Tutorials/CNTK_101_LogisticRegression.ipynb | shyamalschandra/CNTK |
3์ฅ ์ฒ์ ์์ํ๋ ๋จธ์ ๋ฌ๋ | # ๅฟ
่ฆใฉใคใใฉใชใฎๅฐๅ
ฅ
!pip install japanize_matplotlib | tail -n 1
!pip install torchviz | tail -n 1
# ๅฟ
่ฆใฉใคใใฉใชใฎใคใณใใผใ
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
#import japanize_matplotlib
from IPython.display import display
# PyTorch้ข้ฃใฉใคใใฉใช
import torch
from torchviz import make_dot
# ใใใฉใซใใใฉใณใใตใคใบๅคๆด... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.4 ๊ฒฝ์ฌ ํ๊ฐ๋ฒ์ ๊ตฌํ ๋ฐฉ๋ฒ | def L(u, v):
return 3 * u**2 + 3 * v**2 - u*v + 7*u - 7*v + 10
def Lu(u, v):
return 6* u - v + 7
def Lv(u, v):
return 6* v - u - 7
u = np.linspace(-5, 5, 501)
v = np.linspace(-5, 5, 501)
U, V = np.meshgrid(u, v)
Z = L(U, V)
# ๅพ้
้ไธๆณใฎใทใใฅใฌใผใทใงใณ
W = np.array([4.0, 4.0])
W1 = [W[0]]
W2 = [W[1]]
N = 21
alpha = 0.... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.5 ใใผใฟๅๅฆ็5ไบบใฎไบบใฎ่บซ้ทใจไฝ้ใฎใใผใฟใไฝฟใใ 1ๆฌก้ขๆฐใง่บซ้ทใใไฝ้ใไบๆธฌใใๅ ดๅใๆ้ฉใช็ด็ทใๆฑใใใใจใ็ฎ็ใ | # ใตใณใใซใใผใฟใฎๅฎฃ่จ
sampleData1 = np.array([
[166, 58.7],
[176.0, 75.7],
[171.0, 62.1],
[173.0, 70.4],
[169.0,60.1]
])
print(sampleData1)
# ๆฉๆขฐๅญฆ็ฟใขใใซใงๆฑใใใใ่บซ้ทใ ใใๆใๅบใใๅคๆฐxใจ
# ไฝ้ใ ใใๆใๅบใใๅคๆฐyใใปใใใใ
x = sampleData1[:,0]
y = sampleData1[:,1]
import matplotlib
# '๋ง์ ๊ณ ๋'์ผ๋ก ํฐํธ ์ค์
matplotlib.rcParams['font.family'] = '... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
ๅบงๆจ็ณปใฎๅคๆๆฉๆขฐๅญฆ็ฟใขใใซใงใฏใใใผใฟใฏ0ใซ่ฟใๅคใๆใคใใจใๆใพใใใ ใใใงใx, y ใจใใซๅนณๅๅคใ0ใซใชใใใใซๅนณ่ก็งปๅใใๆฐใใๅบงๆจ็ณปใX, Yใจใใใ | X = x - x.mean()
Y = y - y.mean()
# ๆฃๅธๅณ่กจ็คบใง็ตๆใฎ็ขบ่ช
fig1 = plt.gcf()
plt.scatter(X, Y, c='k', s=50)
plt.xlabel('$X$')
plt.ylabel('$Y$')
plt.title('๋ฐ์ดํฐ ๊ฐ๊ณต ํ ์ ์ฅ๊ณผ ์ฒด์ค์ ๊ด๊ณ')
plt.show()
plt.draw()
fig1.savefig('ex03-04.tif', format='tif', dpi=300) | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.6 ไบๆธฌ่จ็ฎ | # XใจYใใใณใฝใซๅคๆฐๅใใ
X = torch.tensor(X).float()
Y = torch.tensor(Y).float()
# ็ตๆ็ขบ่ช
print(X)
print(Y)
# ้ใฟๅคๆฐใฎๅฎ็พฉ
# WใจBใฏๅพ้
่จ็ฎใใใใฎใงใrequires_grad=Trueใจใใ
W = torch.tensor(1.0, requires_grad=True).float()
B = torch.tensor(1.0, requires_grad=True).float()
# ไบๆธฌ้ขๆฐใฏไธๆฌก้ขๆฐ
def pred(X):
return W * X + B
# ไบๆธฌๅคใฎ่จ็ฎ
Yp = pred(X)
#... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.7 ๆๅคฑ่จ็ฎ | # ๆๅคฑ้ขๆฐใฏ่ชคๅทฎไบไนๅนณๅ
def mse(Yp, Y):
loss = ((Yp - Y) ** 2).mean()
return loss
# ๆๅคฑ่จ็ฎ
loss = mse(Yp, Y)
# ็ตๆๆจ็คบ
print(loss)
# ๆๅคฑใฎ่จ็ฎใฐใฉใๅฏ่ฆๅ
params = {'W': W, 'B': B}
g = make_dot(loss, params=params)
display(g)
g.render('ex03-11', format='tif')
!dot -Ttif -Gdpi=300 ex03-11 -o ex03-11_large.tif | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.8 ๅพ้
่จ็ฎ | # ๅพ้
่จ็ฎ
loss.backward()
# ๅพ้
ๅค็ขบ่ช
print(W.grad)
print(B.grad) | tensor(-19.0400)
tensor(2.0000)
| Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.9 ใใฉใกใผใฟไฟฎๆญฃ | # ๅญฆ็ฟ็ใฎๅฎ็พฉ
lr = 0.001
# ๊ฒฝ์ฌ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ํ๋ผ๋ฏธํฐ ์์
W -= lr * W.grad
B -= lr * B.grad | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
WใจBใฏไธๅบฆ่จ็ฎๆธใฟใชใฎใงใใใฎ็ถๆ
ใงๅคใฎๆดๆฐใใงใใชใ ๆฌกใฎๆธใๆนใซใใๅฟ
่ฆใใใ | # ๅพ้
ใๅ
ใซใใฉใกใผใฟไฟฎๆญฃ
# with torch.no_grad() ใไปใใๅฟ
่ฆใใใ
with torch.no_grad():
W -= lr * W.grad
B -= lr * B.grad
# ่จ็ฎๆธใฟใฎๅพ้
ๅคใใชใปใใใใ
W.grad.zero_()
B.grad.zero_()
# ใใฉใกใผใฟใจๅพ้
ๅคใฎ็ขบ่ช
print(W)
print(B)
print(W.grad)
print(B.grad) | tensor(1.0190, requires_grad=True)
tensor(0.9980, requires_grad=True)
tensor(0.)
tensor(0.)
| Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
ๅ
ใฎๅคใฏใฉใกใใ1.0ใ ใฃใใฎใงใWใฏๅพฎๅฐ้ๅขๅ ใBใฏๅพฎๅฐ้ๆธๅฐใใใใจใใใใใ ใใฎ่จ็ฎใ็นฐใ่ฟใใใจใงใๆ้ฉใชWใจBใๆฑใใใฎใๅพ้
้ไธๆณใจใชใใ 3.10 ็นฐใ่ฟใ่จ็ฎ | # ๅๆๅ
# WใจBใๅคๆฐใจใใฆๆฑใ
W = torch.tensor(1.0, requires_grad=True).float()
B = torch.tensor(1.0, requires_grad=True).float()
# ็นฐใ่ฟใๅๆฐ
num_epochs = 500
# ๅญฆ็ฟ็
lr = 0.001
# ่จ้ฒ็จ้
ๅๅๆๅ
history = np.zeros((0, 2))
# ใซใผใๅฆ็
for epoch in range(num_epochs):
# ไบๆธฌ่จ็ฎ
Yp = pred(X)
# ๆๅคฑ่จ็ฎ
loss = mse(Yp, Y)
... | epoch = 0 loss = 13.3520
epoch = 10 loss = 10.3855
epoch = 20 loss = 8.5173
epoch = 30 loss = 7.3364
epoch = 40 loss = 6.5858
epoch = 50 loss = 6.1047
epoch = 60 loss = 5.7927
epoch = 70 loss = 5.5868
epoch = 80 loss = 5.4476
epoch = 90 loss = 5.3507
epoch = 100 loss = 5.2805
epoch = 110 loss = 5.2275
epoch... | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.11 ็ตๆ็ขบ่ช | # ใใฉใกใผใฟใฎๆ็ตๅค
print('W = ', W.data.numpy())
print('B = ', B.data.numpy())
#ๆๅคฑใฎ็ขบ่ช
print(f'์ด๊ธฐ์ํ: ์์ค:{history[0,1]:.4f}')
print(f'์ต์ข
์ํ: ์์ค:{history[-1,1]:.4f}')
# ๅญฆ็ฟๆฒ็ทใฎ่กจ็คบ (ๆๅคฑ)
fig1 = plt.gcf()
plt.plot(history[:,0], history[:,1], 'b')
plt.xlabel('๋ฐ๋ณต ํ์')
plt.ylabel('์์ค')
plt.title('ํ์ต ๊ณก์ (์์ค)')
plt.show()
plt.draw()
fig1... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
ๆฃๅธๅณใซๅๅธฐ็ด็ทใ้ใญๆธใใใ | # xใฎ็ฏๅฒใๆฑใใ(Xrange)
X_max = X.max()
X_min = X.min()
X_range = np.array((X_min, X_max))
X_range = torch.from_numpy(X_range).float()
print(X_range)
# ๅฏพๅฟใใyใฎไบๆธฌๅคใๆฑใใ
Y_range = pred(X_range)
print(Y_range.data)
# ใฐใฉใๆ็ป
fig1 = plt.gcf()
plt.scatter(X, Y, c='k', s=50)
plt.xlabel('$X$')
plt.ylabel('$Y$')
plt.plot(X_range.d... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
ๅ ๅทฅๅใใผใฟใธใฎๅๅธฐ็ด็ทๆ็ป | # yๅบงๆจๅคใจxๅบงๆจๅคใฎ่จ็ฎ
x_range = X_range + x.mean()
yp_range = Y_range + y.mean()
# ใฐใฉใๆ็ป
fig1 = plt.gcf()
plt.scatter(x, y, c='k', s=50)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.plot(x_range, yp_range.data, lw=2, c='b')
plt.title('์ ์ฅ๊ณผ ์ฒด์ค์ ์๊ด ์ง์ (๊ฐ๊ณต ์ )')
plt.show()
plt.draw()
fig1.savefig('ex03-21.tif', format='tif', dpi=30... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.12 ๆ้ฉๅ้ขๆฐใจstep้ขๆฐใฎๅฉ็จ | # ๅๆๅ
# WใจBใๅคๆฐใจใใฆๆฑใ
W = torch.tensor(1.0, requires_grad=True).float()
B = torch.tensor(1.0, requires_grad=True).float()
# ็นฐใ่ฟใๅๆฐ
num_epochs = 500
# ๅญฆ็ฟ็
lr = 0.001
# optimizerใจใใฆSGD(็ขบ็็ๅพ้
้ไธๆณ)ใๆๅฎใใ
import torch.optim as optim
optimizer = optim.SGD([W, B], lr=lr)
# ่จ้ฒ็จ้
ๅๅๆๅ
history = np.zeros((0, 2))
# ใซใผใๅฆ็
for epo... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
3.7ใฎ็ตๆใจ่ฆๆฏในใใจใพใฃใใๅใใงใใใใจใใใใใ ใคใพใใstep้ขๆฐใงใใฃใฆใใใใจใฏใๆฌกใฎใณใผใใจๅใใ```py3 with torch.no_grad(): ใใฉใกใผใฟไฟฎๆญฃ (ใใฌใผใ ใฏใผใฏใไฝฟใๅ ดๅใฏstep้ขๆฐ) W -= lr * W.grad B -= lr * B.grad``` ๆ้ฉๅ้ขๆฐใฎใใฅใผใใณใฐ | # ๅๆๅ
# WใจBใๅคๆฐใจใใฆๆฑใ
W = torch.tensor(1.0, requires_grad=True).float()
B = torch.tensor(1.0, requires_grad=True).float()
# ็นฐใ่ฟใๅๆฐ
num_epochs = 500
# ๅญฆ็ฟ็
lr = 0.001
# optimizerใจใใฆSGD(็ขบ็็ๅพ้
้ไธๆณ)ใๆๅฎใใ
import torch.optim as optim
optimizer = optim.SGD([W, B], lr=lr, momentum=0.9)
# ่จ้ฒ็จ้
ๅๅๆๅ
history2 = np.zeros((0, 2))
#... | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
ใณใฉใ ใๅฑๆๆ้ฉ่งฃ | def f(x):
return x * (x+1) * (x+2) * (x-2)
x = np.arange(-3, 2.7, 0.05)
y = f(x)
plt.plot(x, y)
plt.axis('off')
plt.show() | _____no_output_____ | Apache-2.0 | notebooks/ch03_first_ml.ipynb | ychoi-kr/pytorch_book_info |
Assignment 2: **Machine learning with tree based models** In this assignment, you will work on the **Titanic** dataset and use machine learning to create a model that predicts which passengers survived the **Titanic** shipwreck. --- About the dataset:---* The column named `Survived` is the label and the remaining c... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
import seaborn as sns
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split,cross_val_score,GridSearchCV
from sklearn.linear_model import LinearRegression,Logis... | _____no_output_____ | MIT | Assignment_06/Assignment_ML_L2_Sankalp_Jain_ipynb_txt.ipynb | Sankalp679/SHALA |
Read the CSV and Perform Basic Data Cleaning | df = pd.read_csv("exoplanet_data.csv")
# Drop the null columns where all values are null
df = df.dropna(axis='columns', how='all')
# Drop the null rows
df = df.dropna()
df.head()
df.describe() | _____no_output_____ | MIT | exoplanet1.ipynb | bshub6/machine-learning-challenge |
Select your features (columns) | # Set features. This will also be used as your x values.
target = df["koi_disposition"]
data = df.drop("koi_disposition", axis=1)
feature_names = data.columns
data.head() | _____no_output_____ | MIT | exoplanet1.ipynb | bshub6/machine-learning-challenge |
Create a Train Test SplitUse `koi_disposition` for the y values | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)
X_train.head() | _____no_output_____ | MIT | exoplanet1.ipynb | bshub6/machine-learning-challenge |
Pre-processingScale the data using the MinMaxScaler and perform some feature selection | # Scale your data
from sklearn.preprocessing import MinMaxScaler
X_minmax = MinMaxScaler().fit(X_train)
X_train_minmax = X_minmax.transform(X_train)
X_test_minmax = X_minmax.transform(X_test)
from sklearn.svm import SVC
model = SVC(kernel='linear')
model.fit(X_train_minmax, y_train) | _____no_output_____ | MIT | exoplanet1.ipynb | bshub6/machine-learning-challenge |
Train the Model | print(f"Training Data Score: {model.score(X_train_minmax, y_train)}")
print(f"Testing Data Score: {model.score(X_test_minmax, y_test)}") | Training Data Score: 0.8455082967766546
Testing Data Score: 0.8415331807780321
| MIT | exoplanet1.ipynb | bshub6/machine-learning-challenge |
Hyperparameter TuningUse `GridSearchCV` to tune the model's parameters | # Create the GridSearchCV model
from sklearn.model_selection import GridSearchCV
param_grid = {'C': [1, 5, 10, 50],
'gamma': [0.0001, 0.0005, 0.001, 0.005]}
grid = GridSearchCV(model, param_grid, verbose=3)
# Train the model with GridSearch
grid.fit(X_train_minmax, y_train)
print(grid.best_params_)
print(... | precision recall f1-score support
CANDIDATE 0.81 0.67 0.73 411
CONFIRMED 0.76 0.85 0.80 484
FALSE POSITIVE 0.98 1.00 0.99 853
accuracy 0.88 1748
macro avg 0.85 0.84 ... | MIT | exoplanet1.ipynb | bshub6/machine-learning-challenge |
Save the Model | # save your model by updating "your_name" with your name
# and "your_model" with your model variable
# be sure to turn this in to BCS
# if joblib fails to import, try running the command to install in terminal/git-bash
import joblib
filename = 'models/bridgette_svm.sav'
joblib.dump(model, filename) | _____no_output_____ | MIT | exoplanet1.ipynb | bshub6/machine-learning-challenge |
Watershed Distance Transform for 3D Data---Implementation of papers:[Deep Watershed Transform for Instance Segmentation](http://openaccess.thecvf.com/content_cvpr_2017/papers/Bai_Deep_Watershed_Transform_CVPR_2017_paper.pdf)[Learn to segment single cells with deep distance estimator and deep cell detector](https://arx... | import os
import errno
import datetime
import numpy as np
import deepcell | Using TensorFlow backend.
| Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Load the Training Data | # Download the data (saves to ~/.keras/datasets)
filename = 'mousebrain.npz'
test_size = 0.1 # % of data saved as test
seed = 0 # seed for random train-test split
(X_train, y_train), (X_test, y_test) = deepcell.datasets.mousebrain.load_data(filename, test_size=test_size, seed=seed)
print('X.shape: {}\ny.shape: {}'.fo... | Downloading data from https://deepcell-data.s3.amazonaws.com/nuclei/mousebrain.npz
1730158592/1730150850 [==============================] - 106s 0us/step
X.shape: (176, 15, 256, 256, 1)
y.shape: (176, 15, 256, 256, 1)
| Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Set up filepath constants | # the path to the data file is currently required for `train_model_()` functions
# change DATA_DIR if you are not using `deepcell.datasets`
DATA_DIR = os.path.expanduser(os.path.join('~', '.keras', 'datasets'))
# DATA_FILE should be a npz file, preferably from `make_training_data`
DATA_FILE = os.path.join(DATA_DIR, f... | _____no_output_____ | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Set up training parameters | from tensorflow.keras.optimizers import SGD
from deepcell.utils.train_utils import rate_scheduler
fgbg_model_name = 'conv_fgbg_3d_model'
conv_model_name = 'conv_watershed_3d_model'
n_epoch = 10 # Number of training epochs
norm_method = 'whole_image' # data normalization - `whole_image` for 3d conv
receptive_field =... | _____no_output_____ | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
First, create a foreground/background separation model Instantiate the fgbg model | from deepcell import model_zoo
fgbg_model = model_zoo.bn_feature_net_skip_3D(
receptive_field=receptive_field,
n_features=2, # segmentation mask (is_cell, is_not_cell)
n_frames=frames_per_batch,
n_skips=n_skips,
n_conv_filters=32,
n_dense_filters=128,
input_shape=tuple([frames_per_batch] +... | _____no_output_____ | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Train the fgbg model | from deepcell.training import train_model_conv
fgbg_model = train_model_conv(
model=fgbg_model,
dataset=DATA_FILE, # full path to npz file
model_name=fgbg_model_name,
test_size=test_size,
seed=seed,
transform='fgbg',
optimizer=optimizer,
batch_size=batch_size,
frames_per_batch=fram... | X_train shape: (198, 15, 256, 256, 1)
y_train shape: (198, 15, 256, 256, 1)
X_test shape: (22, 15, 256, 256, 1)
y_test shape: (22, 15, 256, 256, 1)
Output Shape: (None, 3, 256, 256, 2)
Number of Classes: 2
Training on 1 GPUs
Epoch 1/10
197/198 [============================>.] - ETA: 0s - loss: 0.8965 - model_loss: 0.21... | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Next, Create a model for the watershed energy transform Instantiate the distance transform model | from deepcell import model_zoo
watershed_model = model_zoo.bn_feature_net_skip_3D(
fgbg_model=fgbg_model,
receptive_field=receptive_field,
n_skips=n_skips,
n_features=distance_bins,
n_frames=frames_per_batch,
n_conv_filters=32,
n_dense_filters=128,
multires=False,
last_only=False,
... | _____no_output_____ | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Train the model | from deepcell.training import train_model_conv
watershed_model = train_model_conv(
model=watershed_model,
dataset=DATA_FILE, # full path to npz file
model_name=conv_model_name,
test_size=test_size,
seed=seed,
transform=transform,
distance_bins=distance_bins,
erosion_width=erosion_width... | X_train shape: (198, 15, 256, 256, 1)
y_train shape: (198, 15, 256, 256, 1)
X_test shape: (22, 15, 256, 256, 1)
y_test shape: (22, 15, 256, 256, 1)
Output Shape: (None, 3, 256, 256, 4)
Number of Classes: 4
Training on 1 GPUs
Epoch 1/10
197/198 [============================>.] - ETA: 0s - loss: 3.8927 - model_5_loss: 0.... | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Run the modelThe model was trained on only a `frames_per_batch` frames at a time. In order to run this data on a full set of frames, a new model must be instantiated, which will load the trained weights. Save weights of trained models | fgbg_weights_file = os.path.join(MODEL_DIR, '{}.h5'.format(fgbg_model_name))
fgbg_model.save_weights(fgbg_weights_file)
watershed_weights_file = os.path.join(MODEL_DIR, '{}.h5'.format(conv_model_name))
watershed_model.save_weights(watershed_weights_file) | _____no_output_____ | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Initialize the new models | from deepcell import model_zoo
# All training parameters should match except for the `input_shape`
run_fgbg_model = model_zoo.bn_feature_net_skip_3D(
receptive_field=receptive_field,
n_features=2,
n_frames=frames_per_batch,
n_skips=n_skips,
n_conv_filters=32,
n_dense_filters=128,
input_sha... | (4, 15, 256, 256, 1)
| Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Make predictions on test data | test_images = run_watershed_model.predict(X_test)[-1]
test_images_fgbg = run_fgbg_model.predict(X_test)[-1]
print('watershed transform shape:', test_images.shape)
print('segmentation mask shape:', test_images_fgbg.shape) | watershed transform shape: (4, 15, 256, 256, 4)
segmentation mask shape: (4, 15, 256, 256, 2)
| Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Watershed post-processing | argmax_images = []
for i in range(test_images.shape[0]):
max_image = np.argmax(test_images[i], axis=-1)
argmax_images.append(max_image)
argmax_images = np.array(argmax_images)
argmax_images = np.expand_dims(argmax_images, axis=-1)
print('watershed argmax shape:', argmax_images.shape)
# threshold the foreground... | _____no_output_____ | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Plot the results | import matplotlib.pyplot as plt
import matplotlib.animation as animation
index = np.random.randint(low=0, high=watershed_images.shape[0])
frame = np.random.randint(low=0, high=watershed_images.shape[1])
print('Image:', index)
print('Frame:', frame)
fig, axes = plt.subplots(ncols=3, nrows=2, figsize=(15, 15), sharex=... | _____no_output_____ | Apache-2.0 | scripts/watershed/Watershed Transform 3D Fully Convolutional.ipynb | esgomezm/deepcell-tf |
Tutorial 6 - Handle Missing Data replace function | import pandas as pd
import numpy as np
df = pd.read_csv('sample_data_tutorial_06.csv')
df
newdf = df.replace(-99999,np.NaN)
newdf
newdf = df.replace([-99999, -88888],np.NaN)
newdf
newdf = df.replace({
'temperature': -99999,
'windspeed': [-99999, -88888],
'event': 'No event'
}, np.NaN)
newdf
... | _____no_output_____ | MIT | Python Pandas Tutorials 06.ipynb | HenriqueArgentieri/Tutoriais |
PARSE SINGLE ABSTRACT WITH NON-INDEXED AUTHORS LIST | abstract = text_dict['P123']
#abstract
abstract_info = re.findall(r"\w+[A-Z\w+]\w+.*(?=TNF\stherapy.*)", abstract)
abstract_head = str(abstract_info[0])
abstract_head
authors_info = re.findall(r"\w+[^A-Z\d)\W]\s\w.*(?=TNF\stherapy*)", abstract)
authors = str(authors_info[0])
authors
author_name = re.findall(r"\w.+(?=Sp... | _____no_output_____ | MIT | file_parse.ipynb | ivanlohvyn/beetroot_parse_pdf |
PARSE SINGLE ABSTRACT WITH INDEXED AUTHORS LIST | abstract = text_dict['P120']
#abstract
abstract_info = re.findall(r"\w+[A-Z\w+]\w+.*(?=Introduction.*)", abstract)
abstract_head = str(abstract_info[0])
abstract_head
authors_info = re.findall(r"\w+[^A-Z\d)\W]\s\w.*(?=Introduction.*)", abstract)
authors = str(authors_info[0])
authors
author_name = re.findall(r"(\w+.\s[... | _____no_output_____ | MIT | file_parse.ipynb | ivanlohvyn/beetroot_parse_pdf |
 6.3.2 Self Check **2. _(IPython Session)_** Given the sets `{10, 20, 30}` and `{5, 10, 15, 20}` use the mathematical set operators to produce the following results:**a.** `{30}` **b.** `{5, 15, 30}` **c.** `{5, 10, 15, 20, 30}` **d.** `{10, 20}`**Answer:*... | {10, 20, 30} - {5, 10, 15, 20}
{10, 20, 30} ^ {5, 10, 15, 20}
{10, 20, 30} | {5, 10, 15, 20}
{10, 20, 30} & {5, 10, 15, 20}
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved.... | _____no_output_____ | Apache-2.0 | examples/ch06/snippets_ipynb/06.03.02selfcheck.ipynb | germanngc/PythonFundamentals |
All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)** Python Nested `if` statementWe can have a nested-**[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** or nested-*... | # Example 1:
a=10
if a>=20: # Condition FALSE
print ("Condition is True")
else: # Code will go to ELSE body
if a>=15: # Condition FALSE
print ("Checking second value")
else: # Code will go to ELSE body
print ("All Conditions are false")
# Example 2:
x = 10
y = 12
if x > y:
print( "... | 96 is greater than 66
96 and 96 are equal
| MIT | 004_Python_Nested_if_statement.ipynb | chen181016/03_Python_Flow_Control |
import torch
import torch.nn as nn
import torchvision.transforms.functional as TF | _____no_output_____ | MIT | notebooks/Original_U-Net_PyTorch.ipynb | jimmiemunyi/fastai-experiments | |
The Original U-Net Architecture :
return nn.Sequential(
nn.Conv2d(ni, nf, kernel_size=3, stride=1),
nn.ReLU(inplace=True),
nn.Conv2d(nf, nf, kernel_size=3, stride=1),
nn.ReLU(inplace=True)
) | _____no_output_____ | MIT | notebooks/Original_U-Net_PyTorch.ipynb | jimmiemunyi/fastai-experiments |
Implementing the origal architecture: | class UNET(nn.Module):
def __init__(self, in_channels=1, out_channels=1,
features = [64, 128, 256, 512]):
super(UNET, self).__init__()
self.encoder = nn.ModuleList()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
# create the contracting path (encoder + bottleneck)
for feature... | _____no_output_____ | MIT | notebooks/Original_U-Net_PyTorch.ipynb | jimmiemunyi/fastai-experiments |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.