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 |
|---|---|---|---|---|---|
**Read and Load the pre-trained model weight** | class WeightReader:
def __init__(self, weight_file):
with open(weight_file, 'rb') as w_f:
major, = struct.unpack('i', w_f.read(4))
minor, = struct.unpack('i', w_f.read(4))
revision, = struct.unpack('i', w_f.read(4))
if (major*10 + minor) >= 2 and major < 1000 and minor < 1000:
w_f.read(8)
else:
... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Define the model** | model = make_yolov3_model() | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Call class WeightReader to read the weight & load to the model** | weight_reader = WeightReader("/content/drive/MyDrive/yolo_custom_model_Training/backup/test_cfg_20000.weights")
weight_reader.load_weights(model) | loading weights of convolution #0
loading weights of convolution #1
loading weights of convolution #2
loading weights of convolution #3
no convolution #4
loading weights of convolution #5
loading weights of convolution #6
loading weights of convolution #7
no convolution #8
loading weights of convolution #9
loading weig... | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**We will use a pre-trained model to perform object detection** | import numpy as np
from matplotlib import pyplot
from matplotlib.patches import Rectangle
from numpy import expand_dims
from keras.models import load_model
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
# define the expected input shape for the model
input_w, input_... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Draw bounding box on the images** | class BoundBox:
def __init__(self, xmin, ymin, xmax, ymax, objness = None, classes = None):
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
self.objness = objness
self.classes = classes
self.label = -1
self.score = -1
def get_label(self):
if self.label == -1:
self.label = np.... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Intersection over Union - Actual bounding box vs predicted bounding box** | def _interval_overlap(interval_a, interval_b):
x1, x2 = interval_a
x3, x4 = interval_b
if x3 < x1:
if x4 < x1:
return 0
else:
return min(x2,x4) - x1
else:
if x2 < x3:
return 0
else:
return min(x2,x4) - x3
#intersection over union
def bbox_iou(box1, box2):
intersect_w = _interval_overl... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Non Max Suppression - Only choose the high probability bounding boxes** | #boxes from correct_yolo_boxes and decode_netout
def do_nms(boxes, nms_thresh):
if len(boxes) > 0:
nb_class = len(boxes[0].classes)
else:
return
for c in range(nb_class):
sorted_indices = np.argsort([-box.classes[c] for box in boxes])
for i in range(len(sorted_indices)):
index_i = sorted_indices[i]
... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Load and Prepare images** | def load_image_pixels(filename, shape):
# load the image to get its shape
image = load_img(filename) #load_img() Keras function to load the image .
width, height = image.size
# load the image with the required size
image = load_img(filename, target_size=shape) # target_size argument to resize the image after loadi... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Save all of the boxes above the threshold** | def get_boxes(boxes, labels, thresh):
v_boxes, v_labels, v_scores = list(), list(), list()
# enumerate all boxes
for box in boxes:
# enumerate all possible labels
for i in range(len(labels)):
# check if the threshold for this label is high enough
if box.classes[i] > thresh:
v_boxes.append(box)
v_la... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Draw all the boxes based on the information from the previous step** | def draw_boxes(filename, v_boxes, v_labels, v_scores):
# load the image
data = pyplot.imread(filename)
# plot the image
pyplot.imshow(data)
# get the context for drawing boxes
ax = pyplot.gca()
# plot each box
for i in range(len(v_boxes)):
#by retrieving the coordinates from each bounding box and creati... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
**Detection** | %cd '/content/drive/MyDrive/yolo_custom_model_Training/custom_data/'
input_w, input_h = 416, 416
anchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]]
class_threshold = 0.15
pred_right = 0
labels = ['clear_plastic_bottle','plastic_bottle_cap','drink_can','plastic_straw','paper_straw',
... | _____no_output_____ | MIT | experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb | moeraza/juice-box |
SymcaSymca is used to perform symbolic metabolic control analysis [[3,4]](references.html) on metabolic pathway models in order to dissect the control properties of these pathways in terms of the different chains of local effects (or control patterns) that make up the total control coefficient values. Symbolic/algebra... | mod = pysces.model('lin4_fb')
sc = psctb.Symca(mod) | Assuming extension is .psc
Using model directory: /home/jr/Pysces/psc
/home/jr/Pysces/psc/lin4_fb.psc loading .....
Parsing file: /home/jr/Pysces/psc/lin4_fb.psc
Info: "X4" has been initialised but does not occur in a rate equation
Calculating L matrix . . . . . . . done.
Calculating K matrix . . . . . . . done.
... | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Additionally `Symca` has the following arguments:* `internal_fixed`: This must be set to `True` in the case where an internal metabolite has a fixed concentration *(default: `False`)** `auto_load`: If `True` `Symca` will try to load a previously saved session. Saved data is unaffected by the `internal_fixed` argument a... | sc.do_symca() | Simplifying matrix with 28 elements
****************************
| BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
`do_symca` has the following arguments:* `internal_fixed`: This must be set to `True` in the case where an internal metabolite has a fixed concentration *(default: `False`)** `auto_save_load`: If set to `True` `Symca` will attempt to load a previously saved session and only generate new expressions in case of a failure... | sc.cc_results | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Inspecting an individual control coefficient yields a symbolic expression together with a value: | sc.cc_results.ccJR1_R4 | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
In the above example, the expression of the control coefficient consists of two numerator terms and a common denominator shared by all the control coefficient expression signified by $\Sigma$. Various properties of this control coefficient can be accessed such as the:* Expression (as a `SymPy` expression) | sc.cc_results.ccJR1_R4.expression | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
* Numerator expression (as a `SymPy` expression) | sc.cc_results.ccJR1_R4.numerator | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
* Denominator expression (as a `SymPy` expression) | sc.cc_results.ccJR1_R4.denominator | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
* Value (as a `float64`) | sc.cc_results.ccJR1_R4.value | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Additional, less pertinent, attributes are `abs_value`, `latex_expression`, `latex_expression_full`, `latex_numerator`, `latex_name`, `name` and `denominator_object`. The individual control coefficient numerator terms, otherwise known as control patterns, may also be accessed as follows: | sc.cc_results.ccJR1_R4.CP001
sc.cc_results.ccJR1_R4.CP002 | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Each control pattern is numbered arbitrarily starting from 001 and has similar properties as the control coefficient object (i.e., their expression, numerator, value etc. can also be accessed). Control pattern percentage contributionAdditionally control patterns have a `percentage` field which indicates the degree to w... | sc.cc_results.ccJR1_R4.CP001.percentage
sc.cc_results.ccJR1_R4.CP002.percentage | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Unlike conventional percentages, however, these values are calculated as percentage contribution towards the sum of the absolute values of all the control coefficients (rather than as the percentage of the total control coefficient value). This is done to account for situations where control pattern values have differe... | mod.reLoad()
# mod.Vf_4 has a default value of 50
mod.Vf_4 = 0.1
# calculating new steady state
mod.doMca()
# now ccJR1_R4 and its two control patterns should have new values
sc.cc_results.ccJR1_R4
# original value was 0.000
sc.cc_results.ccJR1_R4.CP001
# original value was 0.964
sc.cc_results.ccJR1_R4.CP002
# resettin... |
Parsing file: /home/jr/Pysces/psc/lin4_fb.psc
Info: "X4" has been initialised but does not occur in a rate equation
Calculating L matrix . . . . . . . done.
Calculating K matrix . . . . . . . done.
(hybrd) The solution converged.
| BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Control pattern graphsAs described under [Basic Usage](basic_usage.ipynbgraphic-representation-of-metabolic-networks), `Symca` has the functionality to display the chains of local effects represented by control patterns on a scheme of a metabolic model. This functionality can be accessed via the `highlight_patterns` m... | # This path leads to the provided layout file
path_to_layout = '~/Pysces/psc/lin4_fb.dict'
# Correct path depending on platform - necessary for platform independent scripts
if platform == 'win32' and pysces.version.current_version_tuple() < (0,9,8):
path_to_layout = psctb.utils.misc.unix_to_windows_path(path_to_l... | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
`highlight_patterns` has the following optional arguments:* `width`: Sets the width of the graph (*default*: 900).* `height`:Sets the height of the graph (*default*: 500).* `show_dummy_sinks`: If `True` reactants with the "dummy" or "sink" will not be displayed (*default*: `False`).* `show_external_modifier_links`: If ... | # clicking on CP002 shows that this control pattern representing
# the chain of effects passing through the feedback loop
# is totally responsible for the observed control coefficient value.
sc.cc_results.ccJR1_R4.highlight_patterns(height = 350, pos_dic=path_to_layout)
# To avoid duplication - do not run ... | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Parameter scansParameter scans can be performed in order to determine the effect of a parameter change on either the control coefficient and control pattern values or of the effect of a parameter change on the contribution of the control patterns towards the control coefficient (as discussed [above](Symca.ipynbcontrol... | percentage_scan_data = sc.cc_results.ccJR1_R4.do_par_scan(parameter='Vf_4',
scan_range=numpy.logspace(-1,3,200),
scan_type='percentage') | MaxMode 1
0 min 0 sec
SCANNER: Tsteps 200
SCANNER: 200 states analysed
(hybrd) The solution converged.
| BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
As previously described, these data can be displayed using `ScanFig` by calling the `plot` method of `percentage_scan_data`. Furthermore, lines can be enabled/disabled using the `toggle_category` method of `ScanFig` or by clicking on the appropriate buttons: | percentage_scan_plot = percentage_scan_data.plot()
# set the x-axis to a log scale
percentage_scan_plot.ax.semilogx()
# enable all the lines
percentage_scan_plot.toggle_category('Control Patterns', True)
percentage_scan_plot.toggle_category('CP001', True)
percentage_scan_plot.toggle_category('CP002', True)
# display... | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
A `value` plot can similarly be generated and displayed. In this case, however, an additional line indicating $C^{J}_{4}$ will also be present: | value_scan_data = sc.cc_results.ccJR1_R4.do_par_scan(parameter='Vf_4',
scan_range=numpy.logspace(-1,3,200),
scan_type='value')
value_scan_plot = value_scan_data.plot()
# set the x-axis to a log scale
value_scan_p... | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Fixed internal metabolitesIn the case where the concentration of an internal intermediate is fixed (such as in the case of a GSDA) the `internal_fixed` argument must be set to `True` in either the `do_symca` method, or when instantiating the `Symca` object. This will typically result in the creation of a `cc_results_N... | # Create a variant of mod with 'C' fixed at its steady-state value
mod_fixed_S3 = psctb.modeltools.fix_metabolite_ss(mod, 'S3')
# Instantiate Symca object the 'internal_fixed' argument set to 'True'
sc_fixed_S3 = psctb.Symca(mod_fixed_S3,internal_fixed=True)
# Run the 'do_symca' method (internal_fixed can also be set... | (hybrd) The solution converged.
I hope we have a filebuffer
Seems like it
Reaction stoichiometry and rate equations
Species initial values
Parameters
Assuming extension is .psc
Using model directory: /home/jr/Pysces/psc
Using file: lin4_fb_S3.psc
/home/jr/Pysces/psc/orca/lin4_fb_S3.psc loading .....
Parsing file: ... | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
The normal `sc_fixed_S3.cc_results` object is still generated, but will be invalid for the fixed model. Each additional `cc_results_N` contains control coefficient expressions that have the same common denominator and corresponds to a specific reaction block. These `cc_results_N` objects are numbered arbitrarily, but c... | sc_fixed_S3.cc_results_1 | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
* `cc_results_0` contains the control coefficients describing the sensitivity of flux and concentrations of either reaction block towards reactions in the other reaction block (i.e., all control coefficients here should be zero). Due to the fact that the `S3` demand block consists of a single reaction, this object also... | sc_fixed_S3.cc_results_0 | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
If the demand block of `S3` in this pathway consisted of multiple reactions, rather than a single reaction, there would have been an additional `cc_results_N` object containing the control coefficients of that reaction block. Saving resultsIn addition to being able to save parameter scan results (as previously descr... | sc.save_results() | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
`save_results` has the following optional arguments:* `file_name`: Specifies a path to save the results to. If `None`, the path defaults as described above.* `separator`: The separator between fields (*default*: `","`) The contents of the saved data file is as follows: | # the following code requires `pandas` to run
import pandas as pd
# load csv file at default path
results_path = '~/Pysces/lin4_fb/symca/cc_summary_0.csv'
# Correct path depending on platform - necessary for platform independent scripts
if platform == 'win32' and pysces.version.current_version_tuple() < (0,9,8):
r... | _____no_output_____ | BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
Saving/loading sessionsSaving and loading `Symca` sessions is very simple and works similar to `RateChar`. Saving a session takes place with the `save_session` method, whereas the `load_session` method loads the saved expressions. As with the `save_results` method and most other saving and loading functionality, if no... | # saving session
sc.save_session()
# create new Symca object and load saved results
new_sc = psctb.Symca(mod)
new_sc.load_session()
# display saved results
new_sc.cc_results | (hybrd) The solution converged.
| BSD-3-Clause | documentation/notebooks/Symca.ipynb | PySCeS/PyscesToolbox |
오토인코더 (TensorFlow 2)텐서플로우 2에서 제공하는 고수준 API인 케라스를 이용해, 오토인코더(autoencoder)를 구현한다.* Google Colab 환경에서 사용하는 경우에 초점을 맞춤.* 텐서플로우 2* 텐서플로우 2 내장 케라스 기준참고문헌* [TensorFlow 소개](https://www.tensorflow.org/learn)* [TensorFlow > 학습 > TensorFlow Core > 가이드 > 케라스: 빠르게 훑어보기](https://www.tensorflow.org/guide/keras/overview)* [Deep Lea... | import tensorflow as tf # 텐서플로우 임포트
from tensorflow.keras import models, layers # 케라스 관련 모듈 임포트
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__) # 텐서플로우 버전을 확인하도록 한다.
print(tf.keras.__version__) # 케라스 버전을 확인한다. | 2.2.0-rc3
2.3.0-tf
| MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
MNIST 데이터셋 띄우기* mnist 데이터셋은 LeCun이 만든 숫자(digit) 손글씨 데이터셋이다.* 60,000개의 트레이닝 데이터와 10,000개의 테스트 데이터로 이루어져 있다. MNIST 이미지 데이터* 트레이닝 이미지와 테스트 이미지에 들어 있는 영상은 3차원 텐서이다. + 트레이닝 이미지의 경우, shape = (60000, 28, 28) + 테스트 이미지의 경우, shape=(10000, 28, 28)* 3차원 텐서는 다음의 의미로 구성되어 있음을 유념하자. + ( of images, image Height, image Width) 혹은 ... | # MNIST 데이터 로딩
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print('train_images의 *원래* 데이터의 shape과 dype:',
train_images.shape, train_images.dtype)
print('test_images의 *원래* 데이터의 shape과 dype:',
test_images.shape, test_images.dtype)
# Conv2d l... | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
train_images의 *원래* 데이터의 shape과 dype: (60000, 28, 28) uint8
test_images의 *원래* 데이터의 shape과 dype: (10000, 28, 28) uint8
train_images의 *바뀐* 데이터의 shape과 dype: (60000, 2... | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
네트워크 모델 설계* 인코더 모델: 케라스 시퀀셜 모델로 설계 + InputLayer로 (28,28) 영상을 받고, 출력으로 n_dim차원 벡터가 나오도록 함.* 디코더 모델: 케라스 시퀀셜 모델로 설계 + InputLayer에서 n_dim차원 벡터를 받고, 출력으로 (28,28) 영상이 나오도록 함.* 오토인코더 모델: 인코더, 디코더를 결합하여 설계 + 주의: InputLayer를 추가해야 곧장 함수로서 활용할 수 있음. 여기서는 n_dim을 우선 2로 설정한다.* 즉, n_dim=2 | n_dim = 2 | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코더 모델 정의* (28, 28, 1) 영상을 입력으로 받는 필터가 8개이고, kernel_size가 (2,2)인 Conv2d Layer를 정의한다(padding은 입력과 출력의 크기가 같도록 하기 위해 same을 넣어주었다)* Conv2D layer를 통과한 영상 크기를 maxpooling2d layer를 통과시켜 반으로 줄여줍니다.* 이것을 두번 반복해줍니다 + conv2d: (28,28,1) -> (28,28,8) + maxpooling2d: (28,28,8) -> (14,14,8) + conv2d: (14,14,8) -> (14,14,8) + maxp... | enc = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(8, (2,2), activation='relu', padding='same', input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D((2,2), padding='same'),
tf.keras.layers.Conv2D(8, (2,2), activation='relu', padding='same'),
tf.keras.layers.MaxPooling2D((2,2), padding='same'),
tf.keras... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
디코더 모델 정의* Fully connected layey로 n_dim > 64 > 128 > 392로 차원 확대* 392-vector를 Reshape을 통해 (7,7,8)의 텐서로 변환* 필터가 8이고 kernel_size가 (2,2)인 conv2d layer를 통과시킨다.* UpSampling2d를 통과시켜 conv2d layer를 통과한 영상의 크기를 2배로 늘려준다(이것을 2번 반복 시행) + conv2d: (7,7,8) -> (7,7,8) + upsampling2d: (7,7,8) -> (14,14,8) + conv2d: (14,14,8) -> (14,... | dec = tf.keras.models.Sequential([
tf.keras.layers.InputLayer(input_shape=(n_dim,)), # 주의: 반드시 1D tensor를 (ndim, )로 표현할 것
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(392, activation='relu'),
tf.keras.layers.Reshape(target_shape=(7,7,8)),... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
AutoEncoder 모델 정의* 인코더 > 디코더로 구성 | ae = tf.keras.models.Sequential([
enc,
dec,
]) | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
훈련 전, 네트워크 모델을 함수로서 활용* AutoEncoder ae를 모델로 구성했기 때문에, 지금부터 함수로서 활용 가능 [(효과적인 TensorFlow: 세션 대신 함수)](https://www.tensorflow.org/guide/effective_tf2?hl=ko%EC%84%B8%EC%85%98_%EB%8C%80%EC%8B%A0_%ED%95%A8%EC%88%98) + 단, ae 함수는 batch 단위로 수행됨을 명심할 것. - 단순히, (28, 28, 1) -> ae -> (28, 28, 1)로 동작하지 않고, - batch 단위로 (?, ... | y_pred = ae(train_images)
print('input shape:', train_images.shape)
print('output shape:', y_pred.shape) | input shape: (60000, 28, 28, 1)
output shape: (60000, 28, 28, 1)
| MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
train_images[idx] 영상에 대한 결과 확인* ae의 입력 / 출력 가시화 | import ipywidgets as widgets
def io_imshow(idx):
print('GT label:', train_labels[idx])
plt.subplot(121)
plt.imshow(train_images[idx,:,:,0])
plt.subplot(122)
plt.imshow(y_pred[idx,:,:,0])
plt.show()
widgets.interact(io_imshow, idx=widgets.IntSlider(min=0, max=train_images.shape[0]-1, continuous_update=Fals... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
네트워크 모델 구조 확인* summary() 함수로 모델의 구조를 텍스트로 프린트할 수 있음.* plot_model() 함수로 모델의 구조를 텍스트로 프린트할 수 있음. | enc.summary()
tf.keras.utils.plot_model(enc, 'enc.png', show_shapes=True)
dec.summary()
tf.keras.utils.plot_model(dec, 'dec.png', show_shapes=True)
ae.summary()
tf.keras.utils.plot_model(ae, 'ae.png', show_shapes=True) | Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
sequential (Sequential) (None, 2) 58994
__________________________________... | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
오토인코더 인스턴스 트레이닝AutoEncoder 인스턴스 ae에 대한 훈련 수행* 인스턴스 ae를 [compile](https://www.tensorflow.org/api_docs/python/tf/keras/Modelcompile) + cf) shader program 컴파일과 유사하게 이해해도 됨 + 이때, 훈련에 활용될 [optimizer](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers), [loss](https://www.tensorflow.org/api_docs/python/tf/kera... | ae.compile(optimizer='Adam', # optimizer의 name 혹은 함수 객체 설정
loss='mse',
metrics=['mae'])
ae.fit(train_images, train_images, epochs=10, batch_size=32) | Epoch 1/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0593 - mae: 0.1298
Epoch 2/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0464 - mae: 0.1062
Epoch 3/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0437 - mae: 0.1012
Epoch 4/10
1875/1875 [=======... | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
트레이닝 이후 ae 함수를 다시 수행 | y_pred = ae(train_images)
import ipywidgets as widgets
def io_imshow(idx):
print('GT label:', train_labels[idx])
plt.subplot(121)
plt.imshow(train_images[idx,:,:,0])
plt.subplot(122)
plt.imshow(y_pred[idx,:,:,0])
plt.show()
widgets.interact(io_imshow, idx=widgets.IntSlider(min=0, max=train_images.shape[0]... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코더 / 디코더 모델을 각각 따로 함수로서 활용하기다음과 같은 방법으로 트레이닝이 끝난 오토인코더의 enc와 dec를 각각 수행할 수 있다. | z = enc(train_images)
y_pred = dec(z) | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코딩 결과 확인 및 디코딩 결과 확인* 특정 이미지에 대한 인코딩 결과를 확인한다.* 인코딩 결과와 유사한 좌표값을 디코딩에 보내도 유사한 결과가 나옴을 확인한다. | import ipywidgets as widgets
def z_show(idx):
print(z[idx])
print('GT label:', train_labels[idx])
widgets.interact(z_show, idx=widgets.IntSlider(min=0, max=train_images.shape[0]-1)); | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코딩 결과와 유사한 좌표값을 디코딩에 보내도 유사한 결과가 나옴을 확인 | import ipywidgets as widgets
u=widgets.FloatSlider(min=-5.0, max=5.0)
v=widgets.FloatSlider(min=-5.0, max=5.0)
ui = widgets.HBox([u,v])
def z_test(u, v):
z_test = np.array([[u,v]])
print(z_test)
img_gen = dec(z_test)
plt.imshow(img_gen[0,:,:,0])
plt.show()
out = widgets.interactive_output(z_test, {'u... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코딩 결과 가시화오토인코더의 encoder가 만들어 내는 representation인 z 값을 가시화 한다. | # 로딩된 MNIST 데이터 가시화
import matplotlib.pyplot as plt
z_list = []
z_list[:] = []
for i in range(0,10):
print("z_{} :".format(i), z[train_labels==i].shape)
z_list.append(z[train_labels == i])
colors = ['red', 'green', 'blue', 'orange', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan']
for z, color in zip(z_list,... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코딩 결과 가시화를 통해 알 수 있는 점오토인코더의 encoder가 만들어 내는 representation인 z 값을 가시화를 해본 결과 label별로 discriminative한 representation을 만들어내지 못하는 것을 알 수 있다. 디코더를 이용한 Generative Model 구성 | z = np.array([[-1, 0.2],
[0.5, 0.5],
[5, -5]
])
result = dec(z)
print(z.shape)
print(result.shape) | (3, 2)
(3, 28, 28, 1)
| MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
결과 가시화 + [-1, 0.2]는 숫자 8의 분포에 속한다. + [0.5, 0.5]는 숫자 6의 분포에 속한다. + [5, -5]는 숫자 0의 분포에 속한다.* 하지만, 8을 보면 5와 8의 애매한 경계선에 있는 것 같다.* 이를 통해, 분포가 겹치는 것을 확인할 수 있다.* 이 때문에 condition을 주어 분포가 겹치지 않게 하는 conditional autoencoder가 나오게 되었다. | # 로딩된 MNIST 데이터 가시화
import matplotlib.pyplot as plt
plt.subplot(131)
plt.imshow(result[0,:,:,0])
plt.subplot(132)
plt.imshow(result[1,:,:,0])
plt.subplot(133)
plt.imshow(result[2,:,:,0]) | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
차원 늘리기n_dim을 2에서 7로 늘려본다. | n_dim = 7 | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코딩 모델 정의 | enc = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(8, (2,2), activation='relu', padding='same', input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D((2,2), padding='same'),
tf.keras.layers.Conv2D(8, (2,2), activation='relu', padding='same'),
tf.keras.layers.MaxPooling2D((2,2), padding='same'),
tf.keras... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
디코딩 모델 정의 | dec = tf.keras.models.Sequential([
tf.keras.layers.InputLayer(input_shape=(n_dim,)), # 주의: 반드시 1D tensor를 (ndim, )로 표현할 것
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(392, activation='relu'),
tf.keras.layers.Reshape(target_shape=(7,7,8)),... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
AutoEncoder 정의 | ae = tf.keras.models.Sequential([
enc,
dec,
]) | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
네트워크 학습 | ae.compile(optimizer='Adam', # optimizer의 name 혹은 함수 객체 설정
loss='mse',
metrics=['mae'])
ae.fit(train_images, train_images, epochs=10, batch_size=32) | Epoch 1/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0443 - mae: 0.1027
Epoch 2/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0264 - mae: 0.0672
Epoch 3/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0238 - mae: 0.0620
Epoch 4/10
1875/1875 [=======... | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
학습된 결과 확인 | y_pred = ae(train_images)
import ipywidgets as widgets
def io_imshow(idx):
print('GT label:', train_labels[idx])
plt.subplot(121)
plt.imshow(train_images[idx,:,:,0])
plt.subplot(122)
plt.imshow(y_pred[idx,:,:,0])
plt.show()
widgets.interact(io_imshow, idx=widgets.IntSlider(min=0, max=train_images.shape[0]... | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
인코더 결과값 확인 | z = enc(train_images)
y_pred = dec(z)
import ipywidgets as widgets
def z_show(idx):
print(z[idx])
print('GT label:', train_labels[idx])
widgets.interact(z_show, idx=widgets.IntSlider(min=0, max=train_images.shape[0]-1)); | _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
TSNE를 통해 인코더 결과값(7,7,8) 분포 가시화n_dim이 2일 때보다 좀 더 discriminative한 분포를 갖게 되었다. | from sklearn.manifold import TSNE
model = TSNE(learning_rate=100)
transformed = model.fit_transform(z)
xs = transformed[:,0]
ys = transformed[:,1]
plt.scatter(xs,ys,c=train_labels)
plt.show()
| _____no_output_____ | MIT | AutoEncoder_Conv(TensorFlow_2).ipynb | bluesky0960/AI_Study |
Content with notebooksYou can also create content with Jupyter Notebooks. This means that you can includecode blocks and their outputs in your book. Markdown + notebooksAs it is markdown, you can embed images, HTML, etc into your posts!You ... | from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
# Fixing random state for reproducibility
np.random.seed(19680801)
N = 10
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap = plt.cm.coolwarm
rcParams['axes.pro... | _____no_output_____ | Apache-2.0 | seminar_skript/notebooks.ipynb | nitram-bot/fhnw_lecture |
Writing data to bigquery | from google.cloud import storage
from google.cloud import bigquery
import sys
import os
bigquery_client = bigquery.Client.from_service_account_json('../../credentials/data-analysis-sql-309220-6ce084250abd.json')
countries = ['UK', 'DE', 'AT']
countries_probs = [0.5, 0.4, 0.1]
agents = ['android', 'ios', 'web']
agents... | _____no_output_____ | MIT | synthetic_datasets/model.ipynb | dzianissokalau/data_generator |
Introduction to Spark and PythonLet's learn how to use Spark with Python by using the pyspark library! Make sure to view the video lecture explaining Spark and RDDs before continuing on with this code.This notebook will serve as reference code for the Big Data section of the course involving Amazon Web Services. The v... | from pyspark import SparkContext | _____no_output_____ | MIT | 21-Big-Data-and-Spark/01-Introduction to Spark and Python.ipynb | atse0612/Python-for-Data-Science-and-Machine-Learning-Bootcamp |
Now create the SparkContext,A SparkContext represents the connection to a Spark cluster, and can be used to create an RDD and broadcast variables on that cluster.*Note! You can only have one SparkContext at a time the way we are running things here.* | sc = SparkContext() | _____no_output_____ | MIT | 21-Big-Data-and-Spark/01-Introduction to Spark and Python.ipynb | atse0612/Python-for-Data-Science-and-Machine-Learning-Bootcamp |
Basic OperationsWe're going to start with a 'hello world' example, which is just reading a text file. First let's create a text file.___ Let's write an example text file to read, we'll use some special jupyter notebook commands for this, but feel free to use any .txt file: | %%writefile example.txt
first line
second line
third line
fourth line | Overwriting example.txt
| MIT | 21-Big-Data-and-Spark/01-Introduction to Spark and Python.ipynb | atse0612/Python-for-Data-Science-and-Machine-Learning-Bootcamp |
Creating the RDD Now we can take in the textfile using the **textFile** method off of the SparkContext we created. This method will read a text file from HDFS, a local file system (available on allnodes), or any Hadoop-supported file system URI, and return it as an RDD of Strings. | textFile = sc.textFile('example.txt') | _____no_output_____ | MIT | 21-Big-Data-and-Spark/01-Introduction to Spark and Python.ipynb | atse0612/Python-for-Data-Science-and-Machine-Learning-Bootcamp |
Spark’s primary abstraction is a distributed collection of items called a Resilient Distributed Dataset (RDD). RDDs can be created from Hadoop InputFormats (such as HDFS files) or by transforming other RDDs. ActionsWe have just created an RDD using the textFile method and can perform operations on this object, such as... | textFile.count()
textFile.first() | _____no_output_____ | MIT | 21-Big-Data-and-Spark/01-Introduction to Spark and Python.ipynb | atse0612/Python-for-Data-Science-and-Machine-Learning-Bootcamp |
TransformationsNow we can use transformations, for example the filter transformation will return a new RDD with a subset of items in the file. Let's create a sample transformation using the filter() method. This method (just like Python's own filter function) will only return elements that satisfy the condition. Let's... | secfind = textFile.filter(lambda line: 'second' in line)
# RDD
secfind
# Perform action on transformation
secfind.collect()
# Perform action on transformation
secfind.count() | _____no_output_____ | MIT | 21-Big-Data-and-Spark/01-Introduction to Spark and Python.ipynb | atse0612/Python-for-Data-Science-and-Machine-Learning-Bootcamp |
Recognize named entities on Twitter with LSTMsIn this assignment, you will use a recurrent neural network to solve Named Entity Recognition (NER) problem. NER is a common task in natural language processing systems. It serves for extraction such entities from the text as persons, organizations, locations, etc. In this... | try:
import google.colab
IN_COLAB = True
except:
IN_COLAB = False
if IN_COLAB:
! wget https://raw.githubusercontent.com/hse-aml/natural-language-processing/master/setup_google_colab.py -O setup_google_colab.py
import setup_google_colab
setup_google_colab.setup_week2()
import sys
sys.path.appen... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Load the Twitter Named Entity Recognition corpusWe will work with a corpus, which contains tweets with NE tags. Every line of a file contains a pair of a token (word/punctuation symbol) and a tag, separated by a whitespace. Different tweets are separated by an empty line.The function *read_data* reads a corpus from th... | def read_data(file_path):
tokens = []
tags = []
tweet_tokens = []
tweet_tags = []
for line in open(file_path, encoding='utf-8'):
line = line.strip()
if not line:
if tweet_tokens:
tokens.append(tweet_tokens)
tags.append(tweet_tags)
... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
And now we can load three separate parts of the dataset: - *train* data for training the model; - *validation* data for evaluation and hyperparameters tuning; - *test* data for final evaluation of the model. | train_tokens, train_tags = read_data('data/train.txt')
validation_tokens, validation_tags = read_data('data/validation.txt')
test_tokens, test_tags = read_data('data/test.txt') | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
You should always understand what kind of data you deal with. For this purpose, you can print the data running the following cell: | for i in range(3):
for token, tag in zip(train_tokens[i], train_tags[i]):
print('%s\t%s' % (token, tag))
print() | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Prepare dictionariesTo train a neural network, we will use two mappings: - {token}$\to${token id}: address the row in embeddings matrix for the current token;- {tag}$\to${tag id}: one-hot ground truth probability distribution vectors for computing the loss at the output of the network.Now you need to implement the fun... | from collections import defaultdict
def build_dict(tokens_or_tags, special_tokens):
"""
tokens_or_tags: a list of lists of tokens or tags
special_tokens: some special tokens
"""
# Create a dictionary with default value 0
tok2idx = defaultdict(lambda: 0)
idx2tok = []
# Create... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
After implementing the function *build_dict* you can make dictionaries for tokens and tags. Special tokens in our case will be: - `` token for out of vocabulary tokens; - `` token for padding sentence to the same length when we create batches of sentences. | special_tokens = ['<UNK>', '<PAD>']
special_tags = ['O']
# Create dictionaries
token2idx, idx2token = build_dict(train_tokens + validation_tokens, special_tokens)
tag2idx, idx2tag = build_dict(train_tags, special_tags) | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
The next additional functions will help you to create the mapping between tokens and ids for a sentence. | def words2idxs(tokens_list):
return [token2idx[word] for word in tokens_list]
def tags2idxs(tags_list):
return [tag2idx[tag] for tag in tags_list]
def idxs2words(idxs):
return [idx2token[idx] for idx in idxs]
def idxs2tags(idxs):
return [idx2tag[idx] for idx in idxs] | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Generate batchesNeural Networks are usually trained with batches. It means that weight updates of the network are based on several sequences at every single time. The tricky part is that all sequences within a batch need to have the same length. So we will pad them with a special `` token. It is also a good practice t... | def batches_generator(batch_size, tokens, tags,
shuffle=True, allow_smaller_last_batch=True):
"""Generates padded batches of tokens and tags."""
n_samples = len(tokens)
if shuffle:
order = np.random.permutation(n_samples)
else:
order = np.arange(n_samples)
... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Build a recurrent neural networkThis is the most important part of the assignment. Here we will specify the network architecture based on TensorFlow building blocks. It's fun and easy as a lego constructor! We will create an LSTM network which will produce probability distribution over tags for each token in a sentenc... | import tensorflow as tf
import numpy as np
class BiLSTMModel():
pass | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
First, we need to create [placeholders](https://www.tensorflow.org/api_docs/python/tf/compat/v1/placeholder) to specify what data we are going to feed into the network during the execution time. For this task we will need the following placeholders: - *input_batch* — sequences of words (the shape equals to [batch_size... | def declare_placeholders(self):
"""Specifies placeholders for the model."""
# Placeholders for input and ground truth output.
self.input_batch = tf.placeholder(dtype=tf.int32, shape=[None, None], name='input_batch')
self.ground_truth_tags = ######### YOUR CODE HERE #############
# Placeholder f... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Now, let us specify the layers of the neural network. First, we need to perform some preparatory steps: - Create embeddings matrix with [tf.Variable](https://www.tensorflow.org/api_docs/python/tf/Variable). Specify its name (*embeddings_matrix*), type (*tf.float32*), and initialize with random values.- Create forward... | def build_layers(self, vocabulary_size, embedding_dim, n_hidden_rnn, n_tags):
"""Specifies bi-LSTM architecture and computes logits for inputs."""
# Create embedding variable (tf.Variable) with dtype tf.float32
initial_embedding_matrix = np.random.randn(vocabulary_size, embedding_dim) / np.sqrt(embeddi... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
To compute the actual predictions of the neural network, you need to apply [softmax](https://www.tensorflow.org/api_docs/python/tf/nn/softmax) to the last layer and find the most probable tags with [argmax](https://www.tensorflow.org/api_docs/python/tf/argmax). | def compute_predictions(self):
"""Transforms logits to probabilities and finds the most probable tags."""
# Create softmax (tf.nn.softmax) function
softmax_output = ######### YOUR CODE HERE #############
# Use argmax (tf.argmax) to get the most probable tags
# Don't forget to set axis=-1
... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
During training we do not need predictions of the network, but we need a loss function. We will use [cross-entropy loss](http://ml-cheatsheet.readthedocs.io/en/latest/loss_functions.htmlcross-entropy), efficiently implemented in TF as [cross entropy with logits](https://www.tensorflow.org/api_docs/python/tf/nn/softmax_... | def compute_loss(self, n_tags, PAD_index):
"""Computes masked cross-entopy loss with logits."""
# Create cross entropy function function (tf.nn.softmax_cross_entropy_with_logits_v2)
ground_truth_tags_one_hot = tf.one_hot(self.ground_truth_tags, n_tags)
loss_tensor = ######### YOUR CODE HERE ######... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
The last thing to specify is how we want to optimize the loss. We suggest that you use [Adam](https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer) optimizer with a learning rate from the corresponding placeholder. You will also need to apply clipping to eliminate exploding gradients. It can be easily done... | def perform_optimization(self):
"""Specifies the optimizer and train_op for the model."""
# Create an optimizer (tf.train.AdamOptimizer)
self.optimizer = ######### YOUR CODE HERE #############
self.grads_and_vars = self.optimizer.compute_gradients(self.loss)
# Gradient clipping (tf.clip_b... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Congratulations! You have specified all the parts of your network. You may have noticed, that we didn't deal with any real data yet, so what you have written is just recipes on how the network should function.Now we will put them to the constructor of our Bi-LSTM class to use it in the next section. | def init_model(self, vocabulary_size, n_tags, embedding_dim, n_hidden_rnn, PAD_index):
self.__declare_placeholders()
self.__build_layers(vocabulary_size, embedding_dim, n_hidden_rnn, n_tags)
self.__compute_predictions()
self.__compute_loss(n_tags, PAD_index)
self.__perform_optimization()
BiLSTMModel... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Train the network and predict tags [Session.run](https://www.tensorflow.org/api_docs/python/tf/Sessionrun) is a point which initiates computations in the graph that we have defined. To train the network, we need to compute *self.train_op*, which was declared in *perform_optimization*. To predict tags, we just need to ... | def train_on_batch(self, session, x_batch, y_batch, lengths, learning_rate, dropout_keep_probability):
feed_dict = {self.input_batch: x_batch,
self.ground_truth_tags: y_batch,
self.learning_rate_ph: learning_rate,
self.dropout_ph: dropout_keep_probability,
... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Implement the function *predict_for_batch* by initializing *feed_dict* with input *x_batch* and *lengths* and running the *session* for *self.predictions*. | def predict_for_batch(self, session, x_batch, lengths):
######################################
######### YOUR CODE HERE #############
######################################
return predictions
BiLSTMModel.predict_for_batch = classmethod(predict_for_batch) | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
We finished with necessary methods of our BiLSTMModel model and almost ready to start experimenting. Evaluation To simplify the evaluation process we provide two functions for you: - *predict_tags*: uses a model to get predictions and transforms indices to tokens and tags; - *eval_conll*: calculates precision, recall a... | from evaluation import precision_recall_f1
def predict_tags(model, session, token_idxs_batch, lengths):
"""Performs predictions and transforms indices to tokens and tags."""
tag_idxs_batch = model.predict_for_batch(session, token_idxs_batch, lengths)
tags_batch, tokens_batch = [], []
for tag_i... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Run your experiment Create *BiLSTMModel* model with the following parameters: - *vocabulary_size* — number of tokens; - *n_tags* — number of tags; - *embedding_dim* — dimension of embeddings, recommended value: 200; - *n_hidden_rnn* — size of hidden layers for RNN, recommended value: 200; - *PAD_index* — an index of t... | tf.reset_default_graph()
model = ######### YOUR CODE HERE #############
batch_size = ######### YOUR CODE HERE #############
n_epochs = ######### YOUR CODE HERE #############
learning_rate = ######### YOUR CODE HERE #############
learning_rate_decay = ######### YOUR CODE HERE #############
dropout_keep_probability = #... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
If you got an error *"Tensor conversion requested dtype float64 for Tensor with dtype float32"* in this point, check if there are variables without dtype initialised. Set the value of dtype equals to *tf.float32* for such variables. Finally, we are ready to run the training! | sess = tf.Session()
sess.run(tf.global_variables_initializer())
print('Start training... \n')
for epoch in range(n_epochs):
# For each epoch evaluate the model on train and validation data
print('-' * 20 + ' Epoch {} '.format(epoch+1) + 'of {} '.format(n_epochs) + '-' * 20)
print('Train data evaluation:')
... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
Now let us see full quality reports for the final model on train, validation, and test sets. To give you a hint whether you have implemented everything correctly, you might expect F-score about 40% on the validation set.**The output of the cell below (as well as the output of all the other cells) should be present in t... | print('-' * 20 + ' Train set quality: ' + '-' * 20)
train_results = eval_conll(model, sess, train_tokens, train_tags, short_report=False)
print('-' * 20 + ' Validation set quality: ' + '-' * 20)
validation_results = ######### YOUR CODE HERE #############
print('-' * 20 + ' Test set quality: ' + '-' * 20)
test_results... | _____no_output_____ | MIT | week2/week2-NER.ipynb | rahul263-stack/PROJECT-Dump |
TV Script GenerationIn this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chroniclesscripts.csv) of scripts from 9 seasons. The Neural Network you'll build will genera... | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
# load in data
import helper
data_dir = './data/Seinfeld_Scripts.txt'
text = helper.load_data(data_dir) | _____no_output_____ | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Explore the DataPlay around with `view_line_range` to view different parts of the data. This will give you a sense of the data you'll be working with. You can see, for example, that it is all lowercase text, and each new line of dialogue is separated by a newline character `\n`. | view_line_range = (0, 10)
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
import numpy as np
print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))
lines = text.split('\n')
print('Number of lines: {}'.format(len(lines)))
word_count... | Dataset Stats
Roughly the number of unique words: 46367
Number of lines: 109233
Average number of words in each line: 5.544240293684143
The lines 0 to 10:
jerry: do you know what this is all about? do you know, why were here? to be out, this is out...and out is one of the single most enjoyable experiences of life. peo... | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
--- Implement Pre-processing FunctionsThe first thing to do to any dataset is pre-processing. Implement the following pre-processing functions below:- Lookup Table- Tokenize Punctuation Lookup TableTo create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:- Di... | import problem_unittests as tests
from collections import Counter
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
# TODO: Implement Function
word_counter =... | Tests Passed
| MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Tokenize PunctuationWe'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks can create multiple ids for the same word. For example, "bye" and "bye!" would generate two different word ids.Implement the function `token_lookup` to return a dict... | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenized dictionary where the key is the punctuation and the value is the token
"""
# TODO: Implement Function
token_dict = {
'.': "||dot||",
',': "||comma||",
'"': "||doublequote||",... | Tests Passed
| MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Pre-process all the data and save itRunning the code cell below will pre-process all the data and save it to file. You're encouraged to lok at the code for `preprocess_and_save_data` in the `helpers.py` file to see what it's doing in detail, but you do not need to change this code. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
# pre-process training data
helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables) | _____no_output_____ | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Check PointThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import problem_unittests as tests
int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() | _____no_output_____ | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Build the Neural NetworkIn this section, you'll build the components necessary to build an RNN by implementing the RNN Module and forward and backpropagation functions. Check Access to GPU | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import torch
# Check for a GPU
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('No GPU found. Please use a GPU to train your neural network.') | _____no_output_____ | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
InputLet's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.htmltorch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.htmltorch.utils.data.DataLoader), it will handle batching, ... | from torch.utils.data import TensorDataset, DataLoader
def batch_data(words, sequence_length, batch_size):
"""
Batch the neural network data using DataLoader
:param words: The word ids of the TV scripts
:param sequence_length: The sequence length of each batch
:param batch_size: The size of each b... | _____no_output_____ | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Test your dataloader You'll have to modify this code to test a batching function, but it should look fairly similar.Below, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our da... | # test dataloader
test_text = range(50)
t_loader = batch_data(test_text, sequence_length=5, batch_size=10)
data_iter = iter(t_loader)
sample_x, sample_y = data_iter.next()
print(sample_x.shape)
print(sample_x)
print()
print(sample_y.shape)
print(sample_y) | range(0, 50) 5 10
torch.Size([10, 5])
tensor([[ 18, 19, 20, 21, 22],
[ 42, 43, 44, 45, 46],
[ 41, 42, 43, 44, 45],
[ 1, 2, 3, 4, 5],
[ 15, 16, 17, 18, 19],
[ 32, 33, 34, 35, 36],
[ 26, 27, 28, 29, 30],
[ 30, 31, 32, 33, 34],
... | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
--- Build the Neural NetworkImplement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.htmltorch.nn.Module). You may choose to use a GRU or an LSTM. To complete the RNN, you'll have to implement the following functions for the class: - `__init__` - The initialize function. - `init_hidden` - The ... | import torch.nn as nn
class RNN(nn.Module):
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""
Initialize the PyTorch RNN Module
:param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)
... | Tests Passed
| MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Define forward and backpropagationUse the RNN class you implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows:```loss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target)```And it should return the average loss over a batch and ... | def forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):
"""
Forward and backward propagation on the neural network
:param decoder: The PyTorch Module that holds the neural network
:param decoder_optimizer: The PyTorch optimizer for the neural network
:param criterion: The PyTorch loss... | Tests Passed
| MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Neural Network TrainingWith the structure of the network complete and data ready to be fed in the neural network, it's time to train it. Train LoopThe training loop is implemented for you in the `train_decoder` function. This function will train the network over all the batches for the number of epochs given. The mode... | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
def train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches=100):
batch_losses = []
rnn.train()
print("Training for %d epoch(s)..." % n_epochs)
for epoch_i in range(1, n_epochs + 1):
# initialize hidden state
... | _____no_output_____ | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
HyperparametersSet and train the neural network with the following parameters:- Set `sequence_length` to the length of a sequence.- Set `batch_size` to the batch size.- Set `num_epochs` to the number of epochs to train for.- Set `learning_rate` to the learning rate for an Adam optimizer.- Set `vocab_size` to the numbe... | # Data params
# Sequence Length
sequence_length = 8 # of words in a sequence
# Batch Size
batch_size = 128
# data loader - do not change
train_loader = batch_data(int_text, sequence_length, batch_size)
# Training parameters
# Number of Epochs
num_epochs = 9
# Learning Rate
learning_rate = 0.001
# Model parameters
# ... | _____no_output_____ | MIT | project-tv-script-generation/dlnd_tv_script_generation.ipynb | typekev/deep-learning-v2-pytorch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.